Skip to Main Content
WSstart_websocket(...)

Code Examples

How the official example scripts wire up order-update and quote callbacks against the WebSocket feed — the real callback pattern, not the raw frame format.

Overview

The raw t/tk/tf frame format on Subscribe to Market Feed and Order Update Feed is what travels over the wire. The Python SDK hides that behind three callbacks passed to a single start_websocket call, as used in both example_orders.py and example_market.py.

The three callbacks

python
socket_opened = False

def event_handler_order_update(message):
    print("order event: " + str(message))

def event_handler_quote_update(message):
    # e   Exchange
    # tk  Token
    # lp  LTP
    # pc  Percentage change
    # v   Volume
    # o   Open price
    # h   High price
    # l   Low price
    # c   Close price
    # ap  Average trade price
    print("quote event: {0}".format(time.strftime('%d-%m-%Y %H:%M:%S')) + str(message))

def open_callback():
    global socket_opened
    socket_opened = True
    print('app is connected')
    api.subscribe('NSE|11630')
    # api.subscribe(['NSE|22', 'BSE|522032'])  # subscribe to several tokens in one call

ret = api.start_websocket(
    order_update_callback=event_handler_order_update,
    subscribe_callback=event_handler_quote_update,
    socket_open_callback=open_callback,
)
CallbackFires onCorresponds to (raw frame)
socket_open_callbackSuccessful connection handshake{"t":"ck","s":"OK"} on WebSocket Overview
subscribe_callbackEvery tick — both the initial full snapshot and subsequent diffst:'tk' and t:'tf' on Subscribe to Market Feed
order_update_callbackEvery order lifecycle event for the logged-in accountt:'om' on Order Update Feed
The wrapper doesn't merge tick diffs for youPer Subscribe to Market Feed, the raw feed sends a full snapshot once, then only-changed-fields after that. subscribe_callback hands you each message exactly as received — if you need a complete, always-current quote object, merge message into your own dict keyed by token; the example script's print(message) is not doing that for you.

Why subscribe happens inside open_callback

Both example scripts call api.subscribe(...) from inside open_callback — never immediately after calling start_websocket. start_websocket returns before the connection handshake necessarily completes; subscribing before open_callback fires risks sending a subscribe frame down a socket that isn't confirmed open yet. The socket_opened global flag exists purely so the rest of the program (e.g. a menu option to start the socket) can check connection state without re-entering start_websocket:

python
elif prompt1 == 's':
    if socket_opened:
        print('websocket already opened')
        continue
    ret = api.start_websocket(
        order_update_callback=event_handler_order_update,
        subscribe_callback=event_handler_quote_update,
        socket_open_callback=open_callback,
    )
    print(ret)

Subscribing to more than one token

Both scripts show the single-token call live and the multi-token call commented out directly beneath it:

python
api.subscribe('NSE|11630')
# api.subscribe(['NSE|22', 'BSE|522032'])

Passing a list subscribes to every token in one call — this is the wrapper-level equivalent of the #-delimited k field documented on Subscribe to Market Feed ("NSE|22#BSE|522032"). Prefer batching into one subscribe call over looping single-token calls, for the same reasons documented there.

Best practices

  • Keep event_handler_quote_update and event_handler_order_update fast — per WebSocket Overview, slow handlers block the read loop for every other message on the same socket. The example's print() calls are fine for a demo; route to a queue in production.
  • Re-issue every api.subscribe(...) call from inside a fresh open_callback after a reconnect — subscriptions are not remembered across a dropped socket by the server, and the wrapper doesn't replay them for you either.
  • Don't call api.subscribe(...) before socket_opened is True — mirror the example's pattern of putting the subscribe calls inside open_callback, not right after invoking start_websocket.

Notes

Field comments in event_handler_quote_update (e, tk, lp, pc, v, o, h, l, c, ap) match the raw tick fields on Subscribe to Market Feed — cross-reference that page for the full field table, since the example script only comments the handful it expects to see most often.