Created
August 2, 2019 16:04
-
-
Save jjttjj/29997ff463df1cbe5b5036becbc171dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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