YuppiHunt
YuppiHunt

Reputation: 21

get live price in milliseconds (Binance Websocket)

how can i change my code so i get the informations every 100 milliseconds ?

import asyncio
from binance import AsyncClient, BinanceSocketManager


async def main():
    client = await AsyncClient.create()
    bm = BinanceSocketManager(client)
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket('BTCBUSD')
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)

    await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

i apperciate every answer i can get , thanks a lot !

Upvotes: 1

Views: 8888

Answers (3)

Gaurav kushwaha
Gaurav kushwaha

Reputation: 21

Try this out:

import asyncio
import websockets
import json

async def hello():
    async with websockets.connect("wss://stream.binance.com:9443/ws/btcusdt@bookTicker") as ws:
        while True:
            response = await asyncio.wait_for(ws.recv(), timeout=2)
            response=json.loads(response)
            print(response)
            await asyncio.sleep(0.5)

asyncio.get_event_loop().run_until_complete(hello())

Upvotes: 2

Oliver
Oliver

Reputation: 115

You asked about "how to get live price in milliseconds (Binance Websocket)"

Here is a list of available streams on binance with the available options for "update speed": https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md#detailed-stream-information

For my understand most stream types are updating once a second (update speed: 1000ms).

Only depth streams are possible to update 10 times per second (1000ms and 100ms interval)

Trade streams (agg and normal) and Bookticker (individual and all) are in real time. That means, as soon this info is available, you will receive it...

If there is no trade, you will not receive anything, because there is no change in price... but as soon a trade happens, it will get reported to you.

If you want to know, the current buy and sell price for that an asset is available you can use the bookticker which is much less data compared to depth and diff. depth streams... if you need more than the first positions of the current orderbook i recommend using a local depth cache: https://www.lucit.tech/unicorn-binance-local-depth-cache.html

To get a stable websocket connection i recommend using UNICORN Binance WebSocket API, it catches most exceptions and reconnects automatically after a disconnect, it uses asyncio inside (callback function is inside an event loop) and the syntax to use it is easy:

from unicorn_binance_websocket_api.manager import BinanceWebSocketApiManager


def process_new_receives(stream_data, stream_buffer_name=False):
    print(str(stream_data))


ubwa = BinanceWebSocketApiManager(exchange="binance.com")
ubwa.create_stream('trade',
                   ['ethbtc', 'btcusdt', 'bnbbtc', 'ethbtc'],
                   process_stream_data=process_new_receives)

Upvotes: 1

Alex B
Alex B

Reputation: 1182

Since you seem in a rush, below is what I use although I'm using the websockets library to make the calls. I'll take a look at the binance api when I have some more time to see if I can get the calls to be faster but this should hopefully achieve what you want.

You can change the delay between the requests by changing the time of sleep in await asyncio.sleep(0.5) but if you put it any lower than 0.5 seconds it will trigger an error: received 1008 (policy violation) Too many requests; then sent 1008 (policy violation) Too many requests

import asyncio
import websockets
import json

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

async def call_api():
    async with websockets.connect('wss://stream.binance.com:9443/ws/btcusdt@depth') as ws:
        while True:
            await ws.send(json.dumps(msg))
            response = await asyncio.wait_for(ws.recv(), timeout=2)
            response = json.loads(response)
            print(response)
            await asyncio.sleep(0.5)

asyncio.get_event_loop().run_until_complete(call_api())

Upvotes: 0

Related Questions