Search code examples
c++websocketbinancelibwebsockets

Binance Futures with libwebsockets is not working


I'm making a C++ application that would get the price information from Binance Futures via WebSockets. To achieve my goal I use Yair Gadelov's websockets wrapper project, which is based on libwebsockets. This article tells how to use this wrapper: https://yairgadelov.me/websockets-with-c-/ This is the Github project: https://github.com/yairgd/websockets

If I use the main.cpp as it is, it works properly, it connects to the Binance spot websocket and floods me with the information I need. But if I change it into the futures stream, it doesn't connect:

#include "WebSockets.h"
#include <iostream>
#include <string>

int main(int argc, const char** argv)
{
    WebSockets ws;

    auto func = [](std::string json, std::string protol_name) ->bool {
        std::cout << protol_name << ": " << json << std::endl;
        return true;
    };

    auto runAfterConnection = [&ws](void) ->void {
        ws["futures"].Write("{\"method\": \"SUBSCRIBE\",\"params\":[\"btcusdt@ticker\"],\"id\": 1}");
    };

    ws.AddProtocol("futures", "fstream.binance.com", "/ws", 9443, func);

    ws.Connect(runAfterConnection);
    ws.Run();
}

I'm not sure how can I test the subscriptions, but this URL works properly and yields the info I need with the WebSocket Test Client extension for Google Chrome: wss://fstream.binance.com/ws/btcusdt@ticker.

What should I modify to achieve the corresponding results?


Solution

  • I figured it out. The source of the problem is the port. For Features, it is not 9443, but 443. So the working code looks like this:

    #include "WebSockets.h"
    #include <iostream>
    #include <string>
    
    int main(int argc, const char** argv)
    {
        WebSockets ws;
    
        auto func = [](std::string json, std::string protol_name) ->bool {
            std::cout << protol_name << ": " << json << std::endl;
            return true;
        };
    
        auto runAfterConnection = [&ws](void) ->void {
            ws["futures"].Write("{\"method\": \"SUBSCRIBE\",\"params\":[\"btcusdt@ticker\"],\"id\": 1}");
        };
    
        ws.AddProtocol("futures", "fstream.binance.com", "/ws", 443, func);
    
        ws.Connect(runAfterConnection);
        ws.Run();
    }