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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! # Sequence Algo SDK — Ultra Low Latency Trading
//!
//! Write HFT algorithms in Rust, compile to WASM, deploy to Sequence.
//!
//! ## Execution Models
//!
//! - **Single-venue** (`Algo`) — one exchange, one book, tick-by-tick with OnlineFeatures
//! - **V5 Strategy/Executor** (`Strategy` / `Executor`) — sharded multi-venue
//!   with execution plan intents. The recommended path for cross-venue strategies.
//!
//! ## Modules
//!
//! | Module | Contents |
//! |--------|----------|
//! | [`book`] | `Level`, `L2Book` — order book depth |
//! | [`state`] | `AlgoState`, `OpenOrder`, `SymbolMeta`, `RiskSnapshot` |
//! | [`events`] | `Fill`, `Reject`, `FillExt` |
//! | [`actions`] | `Actions` buffer, `Action`, order types |
//! | [`venue`] | Venue IDs, `NbboSnapshot`, `VenueBooks` |
//! | [`pool`] | `PoolBooks`, `PoolMeta`, `PoolAmm`, `PoolStateTable` |
//! | [`features`] | `OnlineFeatures`, `ChainFeeTable` |
//! | [`builders`] | Fluent builders for V5 execution plans |
//! | [`units`] | Type-safe `Px`/`Qty` newtypes |
//! | [`config`] | `ConfigRegion` for runtime parameter tuning |
//! | [`testing`] | Test harness for native strategy development |
//! | [`amm_math`] | Pure AMM/CLMM pricing math |

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(non_snake_case)]

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std as alloc;

// ═══════════════════════════════════════════════════════════════════════════
// MODULES
// ═══════════════════════════════════════════════════════════════════════════

// ── Core data types ─────────────────────────────────────────────────────
pub mod book;
pub mod state;
pub mod events;
pub mod actions;

// ── Market structure ────────────────────────────────────────────────────
pub mod venue;
pub mod pool;
pub mod features;

// ── Algo traits & macros ────────────────────────────────────────────────
pub mod traits;
#[doc(hidden)]
pub mod wasm_macros;

// ── Mesh messaging ─────────────────────────────────────────────────────
pub mod messaging;


// ── AMM pricing math ────────────────────────────────────────────────────
pub mod amm_math;

// ── Logging ─────────────────────────────────────────────────────────────
pub mod log;

// ── New features ────────────────────────────────────────────────────────
/// Type-safe fixed-point price and quantity newtypes.
pub mod units;


/// Runtime parameter configuration via shared WASM memory.
pub mod config;

/// Test harness for native strategy development (non-WASM only).
pub mod testing;

// ═══════════════════════════════════════════════════════════════════════════
// RE-EXPORTS — `use algo_sdk::*` brings everything into scope
// ═══════════════════════════════════════════════════════════════════════════

// ── book.rs ─────────────────────────────────────────────────────────────
pub use book::{Level, L2Book};

// ── state.rs ────────────────────────────────────────────────────────────
pub use state::{
    AlgoState, OpenOrder, PnlSnapshot, RiskSnapshot, SymbolMeta, Status, MAX_ORDERS,
};

// ── events.rs ───────────────────────────────────────────────────────────
pub use events::{Fill, FillExt, Reject, RejectCode};

// ── actions.rs ──────────────────────────────────────────────────────────
pub use actions::{
    Action, Actions, WasmActions, OrderType,
    MAX_ACTIONS, ACTION_NEW, ACTION_CANCEL, ACTION_AMEND,
};

// ── venue.rs ────────────────────────────────────────────────────────────
pub use venue::{
    NbboSnapshot, VenueBooks,
    MAX_VENUES, VENUE_BOOKS_WASM_OFFSET,
    VENUE_KRAKEN, VENUE_COINBASE, VENUE_BINANCE, VENUE_BITGET,
    VENUE_CRYPTOCOM, VENUE_BITMART, VENUE_DEX, VENUE_OKX, VENUE_BYBIT,
    VENUE_UNKNOWN, VENUE_DEX_ETH, VENUE_DEX_ARB, VENUE_DEX_BASE,
    VENUE_DEX_OP, VENUE_DEX_POLY, VENUE_DEX_SOL, VENUE_HYPERLIQUID,
    is_dex, is_cex, venue_name,
};

// ── pool.rs ─────────────────────────────────────────────────────────────
pub use pool::{
    PoolMeta, PoolBooks, PoolAmm, PoolStateTable, pool_type,
    MAX_POOLS, MAX_POOL_STATES,
    POOL_BOOKS_WASM_OFFSET, POOL_STATE_TABLE_WASM_OFFSET,
};

// ── features.rs ─────────────────────────────────────────────────────────
pub use features::{
    OnlineFeatures, ChainFee, ChainFeeTable, chain_id, venue_chain_id,
    ONLINE_FEATURES_WASM_OFFSET, CHAIN_FEE_TABLE_WASM_OFFSET, MAX_CHAINS,
};

// ── traits.rs ───────────────────────────────────────────────────────────
pub use traits::Algo;

// ── messaging.rs ────────────────────────────────────────────────────────
pub use messaging::{send, MAX_MESSAGE_SIZE};
pub use actions::{ACTION_INTENT, IntentPolicy};


// ── log.rs ──────────────────────────────────────────────────────────────
pub use log::LogLevel;

// ── config.rs ───────────────────────────────────────────────────────────
pub use config::{ConfigRegion, CONFIG_REGION_WASM_OFFSET, MAX_CONFIG_PARAMS};

// ── time helpers ────────────────────────────────────────────────────────
/// Simple timing helpers for client-controlled latency measurement.
pub mod time {
    /// Start a timer from an event timestamp.
    #[inline(always)]
    pub fn start(now_ns: u64) -> u64 { now_ns }

    /// Elapsed nanoseconds.
    #[inline(always)]
    pub fn stop_ns(start_ns: u64, now_ns: u64) -> u64 {
        now_ns.saturating_sub(start_ns)
    }

    #[inline(always)]
    pub fn stop_us(start_ns: u64, now_ns: u64) -> u64 {
        stop_ns(start_ns, now_ns) / 1_000
    }

    #[inline(always)]
    pub fn stop_ms(start_ns: u64, now_ns: u64) -> u64 {
        stop_ns(start_ns, now_ns) / 1_000_000
    }

    /// Stateful timer.
    #[derive(Debug, Clone, Copy, Default)]
    pub struct Timer { start_ns: u64 }

    impl Timer {
        #[inline(always)]
        pub const fn new() -> Self { Self { start_ns: 0 } }

        #[inline(always)]
        pub fn start(&mut self, now_ns: u64) { self.start_ns = now_ns; }

        #[inline(always)]
        pub fn stop_ns(&self, now_ns: u64) -> u64 {
            now_ns.saturating_sub(self.start_ns)
        }

        #[inline(always)]
        pub fn stop_us(&self, now_ns: u64) -> u64 { self.stop_ns(now_ns) / 1_000 }

        #[inline(always)]
        pub fn stop_ms(&self, now_ns: u64) -> u64 { self.stop_ns(now_ns) / 1_000_000 }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// LOGGING MACROS (must be in crate root for #[macro_export])
// ═══════════════════════════════════════════════════════════════════════════

/// Log info message with formatting.
#[macro_export]
macro_rules! log_info {
    ($($arg:tt)*) => {
        $crate::log::info_fmt(format_args!($($arg)*))
    };
}

/// Log warning with formatting.
#[macro_export]
macro_rules! log_warn {
    ($($arg:tt)*) => {
        $crate::log::warn_fmt(format_args!($($arg)*))
    };
}

/// Log error with formatting.
#[macro_export]
macro_rules! log_error {
    ($($arg:tt)*) => {
        $crate::log::error_fmt(format_args!($($arg)*))
    };
}

/// Log debug with formatting.
#[macro_export]
macro_rules! log_debug {
    ($($arg:tt)*) => {
        $crate::log::debug_fmt(format_args!($($arg)*))
    };
}

// ═══════════════════════════════════════════════════════════════════════════
// ENTRY MACRO — eliminates WASM boilerplate
// ═══════════════════════════════════════════════════════════════════════════

/// Set up WASM entry boilerplate: panic handler + bump allocator.
///
/// Place this at the top of your strategy's `lib.rs` to eliminate the
/// standard `no_std` / panic handler / allocator boilerplate.
///
/// # Example
/// ```rust,ignore
/// #![no_std]
/// extern crate alloc;
/// use algo_sdk::*;
///
/// sequence_algo_entry!();
///
/// struct MyAlgo;
/// // ... impl Algo for MyAlgo ...
/// export_algo!(MyAlgo);
/// ```
#[macro_export]
macro_rules! sequence_algo_entry {
    () => {
        #[cfg(target_arch = "wasm32")]
        mod _seq_entry {
            #[panic_handler]
            fn panic(_: &core::panic::PanicInfo) -> ! {
                core::arch::wasm32::unreachable()
            }

            /// Simple bump allocator for WASM — strategies rarely free memory.
            struct BumpAlloc;
            static mut HEAP_POS: usize = 0;
            // 64KB heap — sufficient for most strategies.
            static mut HEAP: [u8; 65536] = [0u8; 65536];

            unsafe impl core::alloc::GlobalAlloc for BumpAlloc {
                unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 {
                    let align = layout.align();
                    let pos = (HEAP_POS + align - 1) & !(align - 1);
                    let end = pos + layout.size();
                    if end > HEAP.len() {
                        return core::ptr::null_mut();
                    }
                    HEAP_POS = end;
                    HEAP.as_mut_ptr().add(pos)
                }
                unsafe fn dealloc(&self, _: *mut u8, _: core::alloc::Layout) {}
            }

            #[global_allocator]
            static ALLOC: BumpAlloc = BumpAlloc;
        }
    };
}

// ═══════════════════════════════════════════════════════════════════════════
// TESTS — exercising types through the re-export layer
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    // ── helper ───────────────────────────────────────────────────────────
    fn make_book(bid_px: u64, bid_sz: u64, ask_px: u64, ask_sz: u64) -> L2Book {
        let mut book = L2Book::default();
        if bid_px > 0 {
            book.bids[0] = Level { px_1e9: bid_px, sz_1e8: bid_sz };
            book.bid_ct = 1;
        }
        if ask_px > 0 {
            book.asks[0] = Level { px_1e9: ask_px, sz_1e8: ask_sz };
            book.ask_ct = 1;
        }
        book
    }

    // ── Level ────────────────────────────────────────────────────────────

    #[test]
    fn level_empty_is_zero() {
        let l = Level::EMPTY;
        assert_eq!(l.px_1e9, 0);
        assert_eq!(l.sz_1e8, 0);
    }

    #[test]
    fn level_is_valid() {
        assert!(!Level::EMPTY.is_valid());
        assert!(Level { px_1e9: 1, sz_1e8: 0 }.is_valid());
    }

    // ── L2Book ───────────────────────────────────────────────────────────

    #[test]
    fn book_best_bid_ask_empty() {
        let book = L2Book::default();
        assert!(book.best_bid().is_none());
        assert!(book.best_ask().is_none());
    }

    #[test]
    fn book_best_bid_ask_populated() {
        let book = make_book(99_000_000_000, 1_000_000, 101_000_000_000, 2_000_000);
        assert_eq!(book.best_bid().unwrap().px_1e9, 99_000_000_000);
        assert_eq!(book.best_ask().unwrap().px_1e9, 101_000_000_000);
    }

    #[test]
    fn book_mid_and_spread() {
        let book = make_book(99_000_000_000, 1, 101_000_000_000, 1);
        assert_eq!(book.mid_px_1e9(), 100_000_000_000);
        assert_eq!(book.spread_1e9(), 2_000_000_000);
        assert_eq!(book.spread_bps(), 200);
        assert_eq!(book.spread_bps_x1000(), 200_000);
        assert!(!book.is_crossed());
    }

    #[test]
    fn book_crossed() {
        let book = make_book(101_000_000_000, 1, 99_000_000_000, 1);
        assert!(book.is_crossed());
        assert!(book.spread_bps_x1000() < 0);
    }

    #[test]
    fn book_depth_and_imbalance() {
        let mut book = make_book(100_000_000_000, 500, 101_000_000_000, 300);
        book.bids[1] = Level { px_1e9: 99_000_000_000, sz_1e8: 200 };
        book.bid_ct = 2;
        assert_eq!(book.bid_depth_1e8(5), 700);
        assert_eq!(book.imbalance_bps(5), 4000);
    }

    // ── OpenOrder ────────────────────────────────────────────────────────

    #[test]
    fn open_order_lifecycle() {
        let mut o = OpenOrder::EMPTY;
        o.status = Status::ACKED;
        assert!(o.is_live());
        o.status = Status::DEAD;
        assert!(!o.is_live());
    }

    // ── SymbolMeta ───────────────────────────────────────────────────────

    #[test]
    fn symbol_rounding() {
        let meta = SymbolMeta {
            tick_size_1e9: 10_000_000,
            lot_size_1e8: 1_000_000,
            ..SymbolMeta::EMPTY
        };
        assert_eq!(meta.round_px(95_000_000), 90_000_000);
        assert_eq!(meta.round_qty(1_500_000), 1_000_000);
    }

    // ── AlgoState ────────────────────────────────────────────────────────

    #[test]
    fn algo_state_pnl() {
        let mut s = AlgoState::default();
        s.realized_pnl_1e9 = 5_000_000_000;
        s.unrealized_pnl_1e9 = -2_000_000_000;
        assert_eq!(s.total_pnl_1e9(), 3_000_000_000);
        assert!((s.total_pnl_usd() - 3.0).abs() < 1e-9);
    }

    // ── Fill / Reject ────────────────────────────────────────────────────

    #[test]
    fn fill_timing() {
        let fill = Fill { order_id: 1, px_1e9: 0, qty_1e8: 0, recv_ns: 10_000_000, side: 1, _pad: [0; 7] };
        assert_eq!(fill.since_ms(5_000_000), 5);
    }

    #[test]
    fn reject_reason() {
        let r = Reject { order_id: 1, code: RejectCode::AUTH, _pad: [0; 7] };
        assert_eq!(r.reason(), "AUTH");
    }

    // ── Actions ──────────────────────────────────────────────────────────

    #[test]
    fn actions_buy_sell_cancel() {
        let mut a = Actions::new();
        assert!(a.buy(1, 100, 50_000));
        assert!(a.sell(2, 200, 60_000));
        assert!(a.cancel(3));
        assert_eq!(a.len(), 3);
        assert_eq!(a.get(0).unwrap().side, 1);
        assert_eq!(a.get(1).unwrap().side, -1);
        assert_eq!(a.get(2).unwrap().is_cancel, 1);
    }

    #[test]
    fn actions_order_types() {
        let mut a = Actions::new();
        a.ioc_buy(1, 10, 100);
        a.fok_buy(2, 20, 200);
        a.post_only_buy(3, 30, 300);
        a.market_buy(4, 40);
        assert_eq!(a.get(0).unwrap().order_type, OrderType::IOC);
        assert_eq!(a.get(1).unwrap().order_type, OrderType::FOK);
        assert_eq!(a.get(2).unwrap().order_type, OrderType::POST_ONLY);
        assert_eq!(a.get(3).unwrap().order_type, OrderType::MARKET);
    }


    // ── Venue constants ──────────────────────────────────────────────────

    #[test]
    fn venue_classification() {
        assert!(is_cex(VENUE_KRAKEN));
        assert!(is_cex(VENUE_COINBASE));
        assert!(is_cex(VENUE_HYPERLIQUID));
        assert!(is_dex(VENUE_DEX));
        assert!(is_dex(VENUE_DEX_SOL));
        assert!(!is_cex(VENUE_DEX));
        assert!(!is_dex(VENUE_KRAKEN));
    }

    #[test]
    fn venue_names() {
        assert_eq!(venue_name(VENUE_KRAKEN), "kraken");
        assert_eq!(venue_name(VENUE_DEX_SOL), "dex-sol");
        assert_eq!(venue_name(0), "default");
    }

    // ── NBBO ─────────────────────────────────────────────────────────────

    #[test]
    fn nbbo_spread_and_crossed() {
        let mut snap = NbboSnapshot::default();
        snap.nbbo_bid_px_1e9 = 99_000_000_000;
        snap.nbbo_ask_px_1e9 = 101_000_000_000;
        snap.nbbo_bid_venue = 0;
        snap.nbbo_ask_venue = 1;
        snap.venue_ct = 2;
        assert!(!snap.is_crossed());

        snap.nbbo_bid_px_1e9 = 101_500_000_000;
        assert!(snap.is_crossed());
    }

    // ── ABI ──────────────────────────────────────────────────────────────

    #[test]
    fn abi_sizes_unchanged() {
        assert_eq!(core::mem::size_of::<L2Book>(), 656);
        assert_eq!(core::mem::size_of::<Fill>(), 40);
        assert_eq!(core::mem::size_of::<Reject>(), 16);
        assert_eq!(core::mem::size_of::<Action>(), 32);
        assert_eq!(core::mem::size_of::<OnlineFeatures>(), 256);
    }

    // ── VenueBooks ───────────────────────────────────────────────────────

    #[test]
    fn venue_books_lookup() {
        let mut vb = VenueBooks::default();
        vb.book_ct = 2;
        vb.venue_ids[0] = VENUE_KRAKEN;
        vb.venue_ids[1] = VENUE_COINBASE;
        vb.books[0].bid_ct = 1;
        vb.books[0].bids[0].px_1e9 = 100_000_000_000;
        assert_eq!(vb.book_for_venue(VENUE_KRAKEN).unwrap().bids[0].px_1e9, 100_000_000_000);
        assert!(vb.book_for_venue(VENUE_BINANCE).is_none());
    }

    // ── Time helpers ─────────────────────────────────────────────────────

    #[test]
    fn time_helpers() {
        assert_eq!(time::stop_ns(1000, 2500), 1500);
        assert_eq!(time::stop_us(1000, 2_001_000), 2_000);
        let mut t = time::Timer::new();
        t.start(1_000_000);
        assert_eq!(t.stop_ns(3_000_000), 2_000_000);
    }
}