Coinbase websockets relay
In this project I create a relay between the client and the coinbase websocket API. The coinbase websocket API streams crypto data through a websocket connection. I relay the websocket data into the client that connects to my intermediary clojure server websocket exposed on the port 8982.
(defn server-handler [req]
(prn "req is!! " req)
(let [client-id (get
(:headers req)
"client-id")
old-conn (filter #(= (:client-id %) client-id) @sockets)]
(d/chain
(http/websocket-connection req)
(fn [socket]
(prn "socket is " socket)
(if (seq old-conn)
(swap! sockets disj (nth old-conn 0))
)
(swap! sockets conj {:socket socket
:client-id client-id
:coinbase-socket
(ws-conn "wss://ws-feed.pro.coinbase.com"
:on-connect on-connect
:on-msg on-msg
:on-close on-close)
:pairs #{}})
(s/consume (fn [msg] (uppercase-handler socket msg)) socket))))
)
(def server
(http/start-server server-handler {:port 8992}))
And there’s an http server exposed on the port 3000.
A client sends the request to our intermediary server at the route "/api/v1/subscribe/:pair", where “:pair” is a currency pair, such as ETH-USD or ETH-EUR.
Sending a request to the intermediary Clojure server toggles whether the client will receive data for that currency pair or not.
The app is built on top of the luminus framework, and most of the websocket relay code and the http-toggle code is in the directory: