Clojure Connecting to websocket

Hi there,

I want to connect to the market data websocket using aleph, in Clojure:

(def sock
(ws-conn “wss://”
:on-connect (fn [sock]
(println “Connected.”)
(ws-send sock “”)
) ;; send msg to wss to heartbeat
:on-msg (fn [sock msg] (println “>>>>” msg))
:on-close (fn [sock msg] (println “Closed:” msg))
:aleph {:headers mkt-header :body {:symbol “ESU1”} :heartbeats {:send-after-idle 2500 :payload “”}}

I get “Connected”
and and “o” which shows that its connected, but no messages after that. Any idea what I am doing wrong?


Hi Puru,

I’m not familiar with Clojure, but I do have a couple recommendations.

Be sure to connect to wss://, without the subscription endpoint typed at the end. When you send a message to the server, you’ll include the endpoint in the message body.

The server is responding with “o” because it wants to inform you the connection is made. But it’s not ready to accept just any old request yet. The first request you must send after receiving “o” is an authorization request. Otherwise, the server can’t trust your connection. If you need to generate a token, you have to use a separate REST request for that. I’d recommend doing so before you even open the WebSocket.

Once you’ve authorized, the request I think you want to send is:

{“symbol”: “ESU1”}

…with each line delimited by newline characters (\n). You can replace “0” with whatever number you want. My only advice there is to use a unique number with every request in a given session.

I’ll follow up if I learn anything else from a quick dip into the language syntax and the Aleph library.

1 Like

Disclaimer: I have never used Clojure before.

I’m guessing you’re using something like this as a starting point, which would explain some of the definitions (ws-conn, ws-send, etc). Because on-msg runs every time you receive a message, you can do a quick special case for “o” just for debugging.

With pseudocode for the first case, here’s an alternative definition I might try if I were you:

:on-msg (fn [sock msg] (if (= msg “o”) (…send auth request…wait 5 seconds…send data subscription request…) (println “>>>>” msg) ) )

Asynchronous programming is a treat once it all works! Welcome and best of luck to you.

1 Like

Sounds great. I will take a look at your suggestions.