Skip to content

Instantly share code, notes, and snippets.

@jjttjj
Created August 2, 2019 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjttjj/29997ff463df1cbe5b5036becbc171dc to your computer and use it in GitHub Desktop.
Save jjttjj/29997ff463df1cbe5b5036becbc171dc to your computer and use it in GitHub Desktop.
(defn client
"Takes one or more message handler functions and returns a map which
represents an IB api client."
[& handlers]
(let [handlers (atom (set handlers))
handle-message (fn [msg]
(doseq [f @handlers]
(try (f (unqualify-msg msg))
(catch Throwable t
(log/error t "Error handling message")))))
wrap (wrapper handle-message)
sig (EJavaSignal.)
ecs (EClientSocket. wrap sig)
next-id (atom 0)
next-id-fn #(swap! next-id inc)] ;;todo: seperate order ids?
{:connect-fn (fn [host port & [client-id]]
(.eConnect ecs host port (or client-id (rand-int (Integer/MAX_VALUE))))
(let [reader (EReader. ecs sig)]
(.start reader)
(future (process-messages ecs reader sig))))
:ecs ecs
:handlers handlers
:next-id next-id-fn}))
(defn connect
"Takes a connection map, a host string, a port number and optionally a
client-id and connects to the IB api server. If no client id is
provided, a random integer will be used."
[conn host port & [client-id]]
((:connect-fn conn) host port client-id))
(defn disconnect [conn] (-> conn :ecs .eDisconnect))
(defn connected? [conn] (-> conn :ecs .isConnected))
(defn add-handler [conn f] (swap! (:handlers conn) conj f))
(defn remove-handler [conn f] (swap! (:handlers conn) disj f))
(defn next-id [conn] ((:next-id conn)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment