Search code examples
pythonbinance-api-client

The price from get_ticker() is different from the market


I'm trying to improuve my python script on the Binance API. Now I have seen that if I get the price of a symbol with the API "get_ticker" and then try to buy or sell at market price, the prices are very different. The difference is about 1/2%.

Is there another API to get the market price?


Solution

  • It's because get_ticker method gives you the 24 hour price change statistics.

    Slow solution: You can use get_kline and take the last close price.

    Fast solution: Use websocket-client package and subscribe to the aggregate trade stream which is real time

    import websocket
    import threading
    import json
    
    symbol = 'ETHUSDT'
    
    def process_msg_stream(*args):
        msg = json.loads(args[1])
        print("Last price = ", str(msg['p']))
    
    ws = websocket.WebSocketApp("".join(['wss://stream.binance.com:9443/ws/', symbol.lower(), '@aggTrade']), on_message=process_msg_stream)
    
    threading.Thread(target=ws.run_forever, daemon=True).start()