-1

hello i am trying to i set up a webhook to binance for live update(ever sec) of future market prices
i keep getting error :++Rcv decoded: fin=1 opcode=1 data=b'{"id":1,"result":null}'
should be really easy but cant get it to work
or find a working example on google
any help will be welcome thx

code:

import websocket
import json
import threading
import time

def on_message(ws, message):
    data = json.loads(message)
    if 'data' in data:
        # Extract the market price from the data
        market_price = data['data']['markPrice']
        print("Market Price:", market_price)

def on_error(ws, error):
    print("Error:", error)

def on_close(ws, close_status_code, close_msg):
    print("WebSocket closed")

def on_open(ws):
    print("WebSocket connected")

    # Subscribe to the BTCUSDT perpetual market price updates
    subscription_message = {
        "method": "SUBSCRIBE",
        "params": ["btcusdt_perpetual@markPrice"],
        "id": 1
    }
    ws.send(json.dumps(subscription_message))

def run_websocket():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(
        "wss://fstream.binance.com/ws/btcusdt_perpetual@markPrice",
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.on_open = on_open
    ws.run_forever()

if __name__ == "__main__":
    # Run the WebSocket connection in a separate thread
    websocket_thread = threading.Thread(target=run_websocket)
    websocket_thread.start()

    # Keep the main thread running to fetch prices every second
    while True:
        # Wait for 1 second
        time.sleep(1)
Nadir Belhaj
  • 11,953
  • 2
  • 22
  • 21
user1246950
  • 1,022
  • 2
  • 10
  • 19

2 Answers2

0
import websocket
import json
import threading
import time

def on_message(ws, message):
    if isinstance(message, bytes):
        # Convert the message data from bytes to a string
        message = message.decode('utf-8')

    data = json.loads(message)
    if 'data' in data and data['data'] is not None:
        # Extract the market price from the data
        market_price = data['data']['markPrice']
        print("Market Price:", market_price)

def on_error(ws, error):
    print("Error:", error)

def on_close(ws, close_status_code, close_msg):
    print("WebSocket closed")

def on_open(ws):
    print("WebSocket connected")

    # Subscribe to the BTCUSDT perpetual market price updates
    subscription_message = {
        "method": "SUBSCRIBE",
        "params": ["btcusdt_perpetual@markPrice"],
        "id": 1
    }
    ws.send(json.dumps(subscription_message))

def run_websocket():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(
        "wss://fstream.binance.com/ws/btcusdt_perpetual@markPrice",
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.on_open = on_open
    ws.run_forever()

if __name__ == "__main__":
    # Run the WebSocket connection in a separate thread
    websocket_thread = threading.Thread(target=run_websocket)
    websocket_thread.start()

    # Keep the main thread running to fetch prices every second
    while True:
        # Wait for 1 second
        time.sleep(1)
Nadir Belhaj
  • 11,953
  • 2
  • 22
  • 21
0

{"id":1,"result":null} is a legit response to a successfully subscription.

In this case, please change the URL to:

"wss://fstream.binance.com/ws/btcusdt@markPrice"

which should be working.

The reason is the real working symbol in stream should be identical as the value at this endpoint https://binance-docs.github.io/apidocs/futures/en/#exchange-information

For the USD-M futures, btcusdt_perpetual is not a valid symbol. If you check BTCUSDT symbol from the endpoint, you will see:

{
            "symbol": "BTCUSDT",
            "pair": "BTCUSDT",
            "contractType": "PERPETUAL",
            "deliveryDate": 4133404800000,
            "onboardDate": 1569398400000,
            "status": "TRADING",
            "maintMarginPercent": "2.5000",
            "requiredMarginPercent": "5.0000",
            "baseAsset": "BTC",
            "quoteAsset": "USDT",
            "marginAsset": "USDT",
            "pricePrecision": 2,
            "quantityPrecision": 3,
            "baseAssetPrecision": 8,
            "quotePrecision": 8,
            "underlyingType": "COIN",
            "underlyingSubType": [
                "PoW"
            ],
            "settlePlan": 0,
            "triggerProtect": "0.0500",
            "liquidationFee": "0.012500",
            "marketTakeBound": "0.05",
            "maxMoveOrderLimit": 10000,
            "filters": [
                {
                    "minPrice": "556.80",
                    "tickSize": "0.10",
                    "filterType": "PRICE_FILTER",
                    "maxPrice": "4529764.00"
                },
                {
                    "minQty": "0.001",
                    "maxQty": "1000.000",
                    "filterType": "LOT_SIZE",
                    "stepSize": "0.001"
                },
                {
                    "stepSize": "0.001",
                    "filterType": "MARKET_LOT_SIZE",
                    "maxQty": "120.000",
                    "minQty": "0.001"
                },
                {
                    "filterType": "MAX_NUM_ORDERS",
                    "limit": 200
                },
                {
                    "limit": 10,
                    "filterType": "MAX_NUM_ALGO_ORDERS"
                },
                {
                    "filterType": "MIN_NOTIONAL",
                    "notional": "5"
                },
                {
                    "multiplierDown": "0.9500",
                    "filterType": "PERCENT_PRICE",
                    "multiplierDecimal": "4",
                    "multiplierUp": "1.0500"
                }
            ],
            "orderTypes": [
                "LIMIT",
                "MARKET",
                "STOP",
                "STOP_MARKET",
                "TAKE_PROFIT",
                "TAKE_PROFIT_MARKET",
                "TRAILING_STOP_MARKET"
            ],
            "timeInForce": [
                "GTC",
                "IOC",
                "FOK",
                "GTX"
            ]
        },

Binance
  • 69
  • 6