Event-Driven
In addition to polling at fixed intervals, strategies can wait for events before processing data, reducing unnecessary requests and responding more quickly to market changes.
EventLoop
EventLoop waits for events such as the completion of concurrent tasks started by exchange.Go() or HttpQuery_Go(), readable data on a WebSocket connection, or incoming thread messages; when an event occurs, it returns event information, and the strategy then reads the corresponding data. Event recording starts only on the first call to EventLoop(), so call EventLoop(-1) once before starting concurrent tasks:
javascript
function main() {
EventLoop(-1) // Start recording events so that none occurring afterwards are missed
var r1 = exchange.Go("GetTicker")
var r2 = exchange.Go("GetDepth")
var ev = EventLoop(1000) // Wait for any concurrent task to complete, up to 1 second
Log("event:", ev)
Log("ticker:", r1.wait(), "depth:", r2.wait())
}
ctx.subscribe / ctx.poll
Strategies can also use exchange WebSocket feeds directly: ctx.subscribe subscribes to market data, market-wide tickers, or private account streams for the specified account and returns a Subscription object; ctx.poll retrieves the next feed event (with a configurable wait timeout), which the strategy processes according to its kind (event type name, such as depth or order) and channel. JavaScript and Python strategies use the global ctx object, while Rust strategies use functions with the same names in the ctx module.
javascript
function main() {
// The first argument is the exchange object; if no symbol is given, its current trading pair is used
var tk = ctx.subscribe(exchange, {channel: "ticker"})
var book = ctx.subscribe(exchange, {channel: "depth", depth: 20}) // 20-level order book
// Account private stream: order updates, positions and balances are all pushed through this one feed
var acct = ctx.subscribe(exchange, {channel: "private"})
while (true) {
const ev = ctx.poll([], 1000) // [] means all subscriptions of this thread; wait up to 1 second
if (!ev) {
continue
}
if (ev.type === "status") { // Handle gateway status and subscription status events separately first
if (ev.kind === "status" && ev.prefillStatus === 2) {
Log("subscription failed:", ev.channel, ev.message)
}
continue
}
if (ev.channel === "ticker") {
Log("ticker:", ev.symbol, ev.bid, ev.ask, ev.last)
} else if (ev.channel === "depth") {
// Depth events carry no level data; read it from this subscription's own order book
const b = ev.book(1)
if (b.bids.length > 0 && b.asks.length > 0) {
Log("bid1:", b.bids[0][0], "ask1:", b.asks[0][0])
}
} else if (ev.channel === "orders") {
Log("order:", ev.id, ev.state, ev.filledQty)
} else if (ev.channel === "positions" || ev.channel === "balance") {
Log("positions:", acct.positions(), "balances:", acct.balances())
}
}
}
Usage in Python is the same: options are passed as dictionaries, and events are returned as dictionaries (attribute access such as ev.kind is also supported):
python
def main():
tk = ctx.subscribe(exchange, {"channel": "ticker"})
book = ctx.subscribe(exchange, {"channel": "depth", "depth": 20})
acct = ctx.subscribe(exchange, {"channel": "private"})
while True:
ev = ctx.poll([], 1000) # Returns None on timeout
if ev is None:
continue
if ev.type == "status":
if ev.kind == "status" and ev.prefillStatus == 2:
Log("subscription failed:", ev.channel, ev.message)
continue
if ev.channel == "ticker":
Log("ticker:", ev.symbol, ev.bid, ev.ask, ev.last)
elif ev.channel == "depth":
b = ev.book(1)
if b["bids"] and b["asks"]:
Log("bid1:", b["bids"][0][0], "ask1:", b["asks"][0][0])
elif ev.channel == "orders":
Log("order:", ev.id, ev.state, ev.filledQty)
elif ev.channel in ("positions", "balance"):
Log("positions:", acct.positions(), "balances:", acct.balances())
- The first argument is an exchange object (
exchange,exchanges[1]) or the account's index inexchanges; the second argument is an options object{channel, symbol, depth, interval, mode, buffer}, with the instrument specified bysymbol. channelcan beticker,bbo,depth(depthspecifies the number of price levels),trade,kline(intervalspecifies the period in seconds),tickers, orprivate.privatedoes not require an instrument; order updates, positions, and balances are all delivered through this subscription, with eventchannelvalues oforders,positions, andbalance, respectively; an initial account snapshot is delivered after subscribing, and once the subscription is ready, the subscription object'spositions()andbalances()return the latest positions and balances.tickersdoes not require an instrument; a single subscription receives tickers for all instruments on the exchange, with each event'ssymbolidentifying the corresponding instrument. This subscription is supported only by exchanges that provide market-wide feeds; see the "Push" column in theCapability Matrix; if unsupported, this subscription receives a status event indicating subscription failure.- Passing an array as
symbolsubscribes to multiple instruments at once and returns an array of subscription objects in the same order as the instrument array: all parameters in the batch are validated before subscribing, and if any parameter is invalid, none of the subscriptions in the batch are created; the array can be passed directly toctx.poll(), and calling the array'sunsubscribe()unsubscribes all subscriptions at once. - Every event contains fields such as
kind(an event type name string, such asticker,depth,order, orstatus; do not use numbers),stream(theidof the associated subscription),type, andchannel; seectx.pollfor field descriptions and the respective purposes ofkind,channel, andstream. Depth events only indicate that the order book has been updated; price level data is read throughev.book(n)or the subscription object'sbook(n). - Identical subscriptions share a single feed. Unsubscribe using the subscription object's
unsubscribe(); the exchange-side subscription is canceled only when the last subscription object unsubscribes. Subscriptions unsupported by the exchange do not throw exceptions; instead, the subscription returns a status event withprefillStatusset to2. - When market data subscriptions are not consumed promptly, only the latest data is retained or the oldest data is discarded. Order updates, positions, and balances are never discarded, so strategies must keep calling
ctx.poll(). Inspect thefeedcounters for each exchange inctx.connectors()to assess whether events are being processed promptly. - Feeds and REST APIs operate independently: functions such as
exchange.GetTicker()andexchange.GetDepth()still request the exchange's REST API on every call and do not read feed data. See the corresponding exchange page for supported feed channels. - In
JavaScriptandRust,EventLoop()andctx.poll()within the same thread consume events from the same event queue, so each thread should use only one of them;Python'sEventLoop()uses a separate queue and does not compete withctx.poll()for events.
Subscriptions belong to the thread that calls ctx.subscribe(): events are delivered only to that thread, ctx.poll() retrieves only events for subscriptions in the current thread, and only that thread can unsubscribe. To dedicate a thread to processing a set of market data feeds, create the subscriptions within that thread; when different threads subscribe to the same content, only one exchange-side subscription is established, but each thread receives its own copy of the events:
javascript
function main() {
var t = threading.Thread(function(symbols) {
var subs = ctx.subscribe(0, {channel: "depth", symbol: symbols, depth: 5})
while (true) {
var ev = ctx.poll([], 1000) // Only the two feeds subscribed by this thread
if (ev && ev.kind === "depth") {
var b = ev.book(1)
if (b.bids.length > 0 && b.asks.length > 0) {
Log(ev.symbol, "bid1:", b.bids[0][0], "ask1:", b.asks[0][0])
}
}
}
}, ["ETH_USDT", "SOL_USDT"])
var acct = ctx.subscribe(0, {channel: "private"}) // The main thread handles only the account private stream
while (true) {
var ev = ctx.poll([acct], 1000)
if (ev && ev.kind === "order") {
Log("order:", ev.id, ev.state)
}
}
}
Python uses threading.Thread from the standard library to create threads, with the same subscription and event processing approach; when a thread exits, its subscriptions are automatically canceled.
Rust strategies use ctx::subscribe() and ctx::poll(), with subscription options constructed through ctx::SubOpts and batch subscriptions created using ctx::subscribe_many(); subscriptions can be created from any thread. Events are provided as raw structures. After importing sdk::ctx::EventExt, they can be read by event type through methods such as ev.channel(), ev.book(n), ev.ticker(), ev.order(), and ev.feed_status() (prices and quantities have already been converted to real numbers, no unsafe code is required, and None is returned when the event type does not match); to handle multiple event types separately, use match ev.event_kind() to match the ctx::Kind enum (such as Kind::Fill and Kind::Order, with a required _ arm). ev.kind_str() returns the same type name as kind and can be used for logging:
rust
use sdk::ctx::EventExt;
fn main() {
let book = ctx::subscribe(exchange, ctx::SubOpts::depth(20)).unwrap();
loop {
match ctx::poll(&[book.id()], Some(1000)) {
ctx::Polled::Event(ev) => {
if let Ok(b) = ev.book(1) {
if !b.bids.is_empty() && !b.asks.is_empty() {
Log!("bid1:", b.bids[0].0, "ask1:", b.asks[0].0);
}
}
}
ctx::Polled::Stopped => break,
_ => {}
}
}
}