Skip to content
All library documents

Maintaining a Live Order Book from WebSocket Updates

Code Quant course library

Summary

This example describes a WebSocket client that connects to a derivatives exchange, authenticates, subscribes to public order-book feeds, and requests private account-related streams after authentication. Its worker loop receives messages, calls event handlers, and reconnects after socket failures; a separate thread sends periodic ping frames. The example keeps bid and ask levels in dictionaries keyed by order identifiers and updates them in response to partial snapshots, inserts, changes, and deletions.

After each order-book message, it sorts bids from highest to lowest and asks from lowest to highest, then copies up to five levels of prices and sizes into a tick-like structure. This illustrates a basic approach to maintaining and presenting a live book. It contains no latency measurements, trading signals, or execution results, and the excerpt does not describe sequencing or recovery safeguards for gaps in updates. Its hard-coded authentication values also make the sample unsuitable for direct deployment.

Key ideas

  • The client authenticates over WebSocket before subscribing to private streams.
  • A worker thread receives messages and reconnects after socket errors, while another thread sends periodic pings.
  • Order-book snapshots and incremental messages update bid and ask maps keyed by order identifiers.
  • The best five levels are selected by sorting bids descending and asks ascending by price.
  • The example provides no performance evidence and omits discussion of update-gap recovery and safe credential handling.

Tags

From a private course collection; the original is not published.