tiagosiebler / binance

Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & browser support, integration tests, beautification & more.
MIT License
728 stars 264 forks source link

Live Subscribing/Unsubscribing to streams #334

Open KDVMan opened 1 year ago

KDVMan commented 1 year ago

https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams

Binance has this option:


**Live Subscribing/Unsubscribing to streams

The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below. The id used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth. In the response, if the result received is null this means the request sent was a success.**

Subscribe to a stream Request

{ "method": "SUBSCRIBE", "params": [ "btcusdt@aggTrade", "btcusdt@depth" ], "id": 1 }


Unsubscribe to a stream Request { "method": "UNSUBSCRIBE", "params": [ "btcusdt@depth" ], "id": 312 }


Does your library have such an implementation? (I did not find it), if not, can you add it? Because as I understand it, if, for example, I call subscribeAggregateTrades 20 times for different coins, then I will open 20 connections, and the limit for binance seems to be 5 but I would like to be able to add and remove coins in an already open connection (for example, listen to 100 coins, then add 2 more, or remove 5)

thank you in advance

tiagosiebler commented 1 year ago

Not supported right now in the current implementation. Originally this wasn't possible with binance until they added this later on.

I do want to add support for it though, exactly for the same reasons/concerns you've mentioned as well. In fact, the other exchanges I have SDKs for work this way too - open one connection and subscribe to events after connecting. Should be viable to adapt the way I have this working for my other SDKs, but need to evaluate the cleanest way to do this - I'm somewhat tempted to add a second websocket client (v2) dedicated to working a newer way, instead of expanding the ever growing ws client. Not sure yet though...

KDVMan commented 1 year ago

I have solved it like this

private wsTrades: WebsocketClient; private subscribeTrades: Set = new Set(); private keyTrades: string = getWsKeyWithContext('spot', 'aggTrade');

in connection method

this.wsTrades = this.client.connectToWsUrl('wss://stream.binance.com:9443/ws/aggTrade', this.keyTrades);

and then the method I need

public async subscribeTrade(symbol: string): Promise { if (this.subscribeTrades.has(symbol)) return;

const topic = ${symbol.toLowerCase()}@aggTrade;

const message = JSON.stringify({ method: 'SUBSCRIBE', params: [topic], id: new Date().getTime(), });

this.client.tryWsSend(this.keyTrades, message); this.subscribeTrades.add(symbol); }

aalwayslucky commented 7 months ago

what i have to change ? little bit confused