Search code examples
pythonjsonbinance

Is there a faster way to get price value from Binance


Currently I am trying to write an exchange bot to be used with Binance. Whenever I decide in code to make a sell or buy, the price value is almost always different, from the value, that I decide upon to make the exchange. Is there a faster way to get the price value than the code below?

I tried with the code below:

def get_price_value():

    # Set the API endpoint for the coin1/coin2 pair
    api_endpoint = 'https://api.binance.com/api/v3/ticker/price?symbol=' + currency
    response = requests.get(api_endpoint)

    # Parse the JSON data from the response and extract the current price
    data = response.json()
    current_price = float(data['price'])
    return current_price

Thanks.


Solution

  • keep in mind that the price of a cryptocurrency is constantly changing due to market fluctuations, and it can be affected by various factors such as trading volume, market depth, and news events. it's expected that the price you see in your code may differ from the actual execution price when you place a buy or sell order.

    To minimize the difference between the price you see in your code and the actual execution price, you can try using the Binance WebSocket API. The WebSocket API provides real-time streaming data, which can give you more accurate and up-to-date price information and increase the speed of your trading bot.

    install the websocket-client package

    pip install websocket-client

    import websocket
    import json
    
    def on_message(ws, message):
        data = json.loads(message)
        current_price = float(data['c'])
        print(current_price)
    
    def on_error(ws, error):
        print(error)
    
    def on_close(ws):
        print("WebSocket closed")
    
    def on_open(ws):
        # Subscribe to the real-time price updates for the given symbol
        symbol = 'btcusdt'
        ws.send(json.dumps({"method": "SUBSCRIBE", "params": [f"{symbol}@ticker"], "id": 1}))
    
    if __name__ == "__main__":
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("wss://stream.binance.com:9443/ws", on_message = on_message, on_error = on_error, on_close = on_close)
        ws.on_open = on_open
        ws.run_forever()