sequence-algo-sdk 0.4.0

Sequence Markets Algo SDK — write HFT trading algos in Rust, compile to WASM, deploy to Sequence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Order actions buffer — place, cancel, amend orders.

use crate::AlgoState;

// =============================================================================
// ORDER TYPES
// =============================================================================

/// Order type for execution semantics.
pub mod OrderType {
    /// Limit order - sits on book until filled or canceled (default).
    pub const LIMIT: u8 = 0;
    /// Market order - fills immediately at best available price.
    pub const MARKET: u8 = 1;
    /// Immediate-Or-Cancel - fill what you can, cancel the rest.
    pub const IOC: u8 = 2;
    /// Fill-Or-Kill - fill entire qty or reject completely.
    pub const FOK: u8 = 3;
    /// Post-only - sits on book, rejected if it would cross (maker only).
    /// Maps to venue-native post-only (Kraken `post_only:true`, Binance `LIMIT_MAKER`).
    /// Venues without native post-only reject with `RejectCode::INVALID_PARAMS`.
    pub const POST_ONLY: u8 = 4;
}

// =============================================================================
// ACTIONS BUFFER
// =============================================================================

// ── Action type constants ────────────────────────────────────────────────
/// New order action (place on book).
pub const ACTION_NEW: u8 = 0;
/// Cancel an existing order.
pub const ACTION_CANCEL: u8 = 1;
/// Amend an existing order (atomic modify price/qty).
pub const ACTION_AMEND: u8 = 2;
/// Intent for remote-venue execution (mesh algo messaging).
pub const ACTION_INTENT: u8 = 3;

/// Intent execution policy (carried in `order_type` field when `is_cancel == ACTION_INTENT`).
pub mod IntentPolicy {
    /// Single IOC at limit price. No retry.
    pub const IOC_SWEEP: u8 = 0;
    /// IOC, retry with escalating price on partial fill until filled or TTL.
    pub const AGGRESSIVE_CHASE: u8 = 1;
}

/// Order action (place, cancel, or amend).
///
/// 32 bytes, `#[repr(C)]`. Byte 27 is `venue_id`:
/// - `0` = default venue (backward compatible — old algos never set this byte)
/// - `1..N` = specific VenueId (from `NbboSnapshot.venue_ids[]`)
///
/// `is_cancel` field doubles as action type:
/// - `0` = new order (ACTION_NEW)
/// - `1` = cancel (ACTION_CANCEL)
/// - `2` = amend (ACTION_AMEND) — modifies price/qty of existing order
#[derive(Debug, Clone, Copy, Default)]
#[repr(C)]
pub struct Action {
    pub order_id: u64,
    pub px_1e9: u64,
    pub qty_1e8: i64,
    pub side: i8, // 1=buy, -1=sell, 0=cancel
    pub is_cancel: u8,
    pub order_type: u8, // OrderType::LIMIT, MARKET, IOC, FOK
    pub venue_id: u8,   // 0=default, 1..N=specific venue (was _pad[0])
    pub pool_idx: u8,   // 0=no pool targeting, 1..=MAX_POOLS=target pool_books.metas[pool_idx-1]
    pub symbol_idx: u8,   // 0=primary/only symbol, 1..N=subscribed symbol index
    pub _pad: [u8; 2],
}

/// Max actions per callback.
pub const MAX_ACTIONS: usize = 16;

/// Actions buffer - orders to send.
#[repr(C)]
pub struct Actions {
    actions: [Action; MAX_ACTIONS],
    len: usize,
}

impl Actions {
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            actions: [Action {
                order_id: 0,
                px_1e9: 0,
                qty_1e8: 0,
                side: 0,
                is_cancel: 0,
                order_type: 0,
                venue_id: 0,
                pool_idx: 0,
                symbol_idx: 0,
                _pad: [0; 2],
            }; MAX_ACTIONS],
            len: 0,
        }
    }

    #[inline(always)]
    pub fn clear(&mut self) {
        self.len = 0;
    }

    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }

    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[inline(always)]
    pub fn is_full(&self) -> bool {
        self.len >= MAX_ACTIONS
    }

    // =========================================================================
    // LIMIT ORDERS (default) - sit on book until filled or canceled
    // =========================================================================

    /// Place a limit buy order (GTC - Good Till Canceled).
    #[inline(always)]
    pub fn buy(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, 1, qty_1e8, px_1e9, OrderType::LIMIT)
    }

    /// Place a limit sell order (GTC - Good Till Canceled).
    #[inline(always)]
    pub fn sell(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, -1, qty_1e8, px_1e9, OrderType::LIMIT)
    }

    /// Place limit order with explicit side (1=buy, -1=sell).
    #[inline(always)]
    pub fn order(&mut self, order_id: u64, side: i8, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, side, qty_1e8, px_1e9, OrderType::LIMIT)
    }

    // =========================================================================
    // MARKET ORDERS - fill immediately at best available price
    // =========================================================================

    /// Place a market buy order (fills immediately).
    #[inline(always)]
    pub fn market_buy(&mut self, order_id: u64, qty_1e8: i64) -> bool {
        self.order_typed(order_id, 1, qty_1e8, 0, OrderType::MARKET)
    }

    /// Place a market sell order (fills immediately).
    #[inline(always)]
    pub fn market_sell(&mut self, order_id: u64, qty_1e8: i64) -> bool {
        self.order_typed(order_id, -1, qty_1e8, 0, OrderType::MARKET)
    }

    // =========================================================================
    // IOC ORDERS - Immediate-Or-Cancel (fill what you can, cancel rest)
    // =========================================================================

    /// Place IOC buy - fills available liquidity, cancels unfilled portion.
    #[inline(always)]
    pub fn ioc_buy(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, 1, qty_1e8, px_1e9, OrderType::IOC)
    }

    /// Place IOC sell - fills available liquidity, cancels unfilled portion.
    #[inline(always)]
    pub fn ioc_sell(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, -1, qty_1e8, px_1e9, OrderType::IOC)
    }

    // =========================================================================
    // FOK ORDERS - Fill-Or-Kill (fill entire qty or reject)
    // =========================================================================

    /// Place FOK buy - must fill entire quantity or rejected.
    #[inline(always)]
    pub fn fok_buy(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, 1, qty_1e8, px_1e9, OrderType::FOK)
    }

    /// Place FOK sell - must fill entire quantity or rejected.
    #[inline(always)]
    pub fn fok_sell(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, -1, qty_1e8, px_1e9, OrderType::FOK)
    }

    // =========================================================================
    // POST-ONLY ORDERS - maker only, rejected if would cross book
    // =========================================================================

    /// Place a post-only buy order (maker only, rejected if would cross).
    #[inline(always)]
    pub fn post_only_buy(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, 1, qty_1e8, px_1e9, OrderType::POST_ONLY)
    }

    /// Place a post-only sell order (maker only, rejected if would cross).
    #[inline(always)]
    pub fn post_only_sell(&mut self, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        self.order_typed(order_id, -1, qty_1e8, px_1e9, OrderType::POST_ONLY)
    }

    // =========================================================================
    // CORE ORDER PLACEMENT
    // =========================================================================

    /// Place order with explicit type.
    #[inline(always)]
    pub fn order_typed(
        &mut self,
        order_id: u64,
        side: i8,
        qty_1e8: i64,
        px_1e9: u64,
        order_type: u8,
    ) -> bool {
        if self.len >= MAX_ACTIONS {
            return false;
        }
        self.actions[self.len] = Action {
            order_id,
            px_1e9,
            qty_1e8,
            side,
            is_cancel: 0,
            order_type,
            venue_id: 0,
            pool_idx: 0,
            symbol_idx: 0,
            _pad: [0; 2],
        };
        self.len += 1;
        true
    }

    /// Cancel an order.
    #[inline(always)]
    pub fn cancel(&mut self, order_id: u64) -> bool {
        if self.len >= MAX_ACTIONS {
            return false;
        }
        self.actions[self.len] = Action {
            order_id,
            px_1e9: 0,
            qty_1e8: 0,
            side: 0,
            is_cancel: 1,
            order_type: 0,
            venue_id: 0,
            pool_idx: 0,
            symbol_idx: 0,
            _pad: [0; 2],
        };
        self.len += 1;
        true
    }

    /// Cancel all open orders.
    #[inline(always)]
    pub fn cancel_all(&mut self, state: &AlgoState) {
        for i in 0..state.order_ct as usize {
            let o = &state.orders[i];
            if o.is_live() && self.len < MAX_ACTIONS {
                self.cancel(o.order_id);
            }
        }
    }

    // =========================================================================
    // AMEND ORDERS - atomic modify price/qty of existing order
    // =========================================================================

    /// Amend an existing order's price and/or quantity.
    ///
    /// Uses `is_cancel = ACTION_AMEND (2)`. The venue performs an atomic
    /// edit — the order keeps its ID and (when only qty decreases) its
    /// queue position.
    ///
    /// Returns `false` if the actions buffer is full.
    #[inline(always)]
    pub fn amend(&mut self, order_id: u64, new_qty_1e8: i64, new_px_1e9: u64) -> bool {
        if self.len >= MAX_ACTIONS {
            return false;
        }
        self.actions[self.len] = Action {
            order_id,
            px_1e9: new_px_1e9,
            qty_1e8: new_qty_1e8,
            side: 0, // not relevant for amend
            is_cancel: ACTION_AMEND,
            order_type: 0,
            venue_id: 0,
            pool_idx: 0,
            symbol_idx: 0,
            _pad: [0; 2],
        };
        self.len += 1;
        true
    }

    // =========================================================================
    // INTENTS (mesh algo remote-venue execution)
    // =========================================================================

    /// Emit an intent for remote-venue execution.
    ///
    /// The hosting edge sends this to CC, which routes to the target venue's edge.
    /// A built-in executor on the target edge handles order placement.
    ///
    /// - `intent_id`: unique ID for fill correlation (algo-assigned)
    /// - `venue_id`: target venue (from `NbboSnapshot.venue_ids[]`)
    /// - `side`: 1=buy, -1=sell
    /// - `qty_1e8`: target fill quantity
    /// - `limit_px_1e9`: worst acceptable price
    /// - `policy`: `IntentPolicy::IOC_SWEEP` or `IntentPolicy::AGGRESSIVE_CHASE`
    /// - `ttl_ms`: executor timeout (0 = no timeout)
    #[inline(always)]
    pub fn intent(
        &mut self,
        intent_id: u64,
        venue_id: u8,
        side: i8,
        qty_1e8: i64,
        limit_px_1e9: u64,
        policy: u8,
        ttl_ms: u16,
    ) -> bool {
        if self.len >= MAX_ACTIONS {
            return false;
        }
        let ttl_bytes = ttl_ms.to_le_bytes();
        self.actions[self.len] = Action {
            order_id: intent_id,
            px_1e9: limit_px_1e9,
            qty_1e8,
            side,
            is_cancel: ACTION_INTENT,
            order_type: policy,
            venue_id,
            pool_idx: 0,
            symbol_idx: 0,
            _pad: ttl_bytes,
        };
        self.len += 1;
        true
    }

    // =========================================================================
    // SYMBOL-TARGETED ORDERS (multi-symbol algos)
    // =========================================================================

    /// Place a buy order targeting a specific symbol in a multi-symbol deployment.
    pub fn buy_symbol(&mut self, symbol_idx: u8, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        if self.len >= MAX_ACTIONS { return false; }
        self.actions[self.len] = Action {
            order_id, px_1e9, qty_1e8, side: 1,
            is_cancel: 0, order_type: 0, venue_id: 0, pool_idx: 0,
            symbol_idx, _pad: [0; 2],
        };
        self.len += 1;
        true
    }

    /// Place a sell order targeting a specific symbol in a multi-symbol deployment.
    pub fn sell_symbol(&mut self, symbol_idx: u8, order_id: u64, qty_1e8: i64, px_1e9: u64) -> bool {
        if self.len >= MAX_ACTIONS { return false; }
        self.actions[self.len] = Action {
            order_id, px_1e9, qty_1e8, side: -1,
            is_cancel: 0, order_type: 0, venue_id: 0, pool_idx: 0,
            symbol_idx, _pad: [0; 2],
        };
        self.len += 1;
        true
    }


    /// Zero out an action at index (marks as no-op).
    /// Used by risk engine to neutralize rejected actions in-place.
    #[inline(always)]
    pub fn clear_at(&mut self, idx: usize) {
        if idx < self.len {
            self.actions[idx] = Action {
                order_id: 0,
                px_1e9: 0,
                qty_1e8: 0,
                side: 0,
                is_cancel: 0,
                order_type: 0,
                venue_id: 0,
                pool_idx: 0,
                symbol_idx: 0,
                _pad: [0; 2],
            };
        }
    }

    #[inline(always)]
    pub fn get(&self, idx: usize) -> Option<&Action> {
        if idx < self.len {
            Some(&self.actions[idx])
        } else {
            None
        }
    }

    #[inline(always)]
    pub fn iter(&self) -> impl Iterator<Item = &Action> {
        self.actions[..self.len].iter()
    }
}

impl Default for Actions {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// WASM EXPORTS
// =============================================================================

/// Wire format for actions buffer.
#[repr(C)]
pub struct WasmActions {
    pub count: u32,
    pub _pad: u32,
    pub actions: [Action; MAX_ACTIONS],
}

impl WasmActions {
    pub const fn new() -> Self {
        Self {
            count: 0,
            _pad: 0,
            actions: [Action {
                order_id: 0,
                px_1e9: 0,
                qty_1e8: 0,
                side: 0,
                is_cancel: 0,
                order_type: 0,
                venue_id: 0,
                pool_idx: 0,
                symbol_idx: 0,
                _pad: [0; 2],
            }; MAX_ACTIONS],
        }
    }

    pub fn from_actions(&mut self, actions: &Actions) {
        self.count = actions.len() as u32;
        for i in 0..actions.len() {
            self.actions[i] = actions.actions[i];
        }
    }
}