Skip to main content

ccxt_common/pro/
order_book.rs

1// CCXT-pro OrderBook types — Value-shaped facades.
2//
3// Mirrors `ts/src/base/ws/OrderBook.ts` and `OrderBookSide.ts` as
4// Value::Dict markers. Tags:
5//   * `__bookKind` ∈ {OrderBook, IndexedOrderBook, CountedOrderBook}
6//   * `__sideKind` (on the per-side markers carried under `bids`/`asks`)
7//     ∈ {OrderBookSide, IndexedOrderBookSide, CountedOrderBookSide}
8//
9// All mutation logic — `store`/`storeArray`/`limit`/`reset`/`update` —
10// lives in `Value::*` methods (see `value.rs`). The transpiled tests
11// in `rust/tests/base_ws/test.orderBook.rs` operate on Value-typed
12// locals throughout, so the factories must return Value to satisfy
13// the call sites the AST transpiler emits.
14
15use crate::Value;
16use indexmap::IndexMap;
17
18pub const BOOK_PLAIN:   &str = "OrderBook";
19pub const BOOK_INDEXED: &str = "IndexedOrderBook";
20pub const BOOK_COUNTED: &str = "CountedOrderBook";
21
22pub const SIDE_PLAIN:   &str = "OrderBookSide";
23pub const SIDE_INDEXED: &str = "IndexedOrderBookSide";
24pub const SIDE_COUNTED: &str = "CountedOrderBookSide";
25
26const MAX_DEPTH_SENTINEL: i64 = i64::MAX / 2;
27
28fn iso8601_millis(ts: i64) -> Option<String> {
29    if ts < 0 { return None; }
30    chrono::DateTime::<chrono::Utc>::from_timestamp_millis(ts)
31        .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
32}
33
34/// Build a side marker (`OrderBookSide` / `IndexedOrderBookSide` /
35/// `CountedOrderBookSide`) seeded from a `[[price, size, …], …]` list.
36/// `is_bid: true` flips the price comparison (TS uses `index_price =
37/// side ? -price : price`); we keep the same semantics inside
38/// `Value::store_array`.
39fn new_side(kind: &str, is_bid: bool, depth: i64, deltas: &Value) -> Value {
40    let mut side = crate::value::make_side_marker(kind, is_bid, depth);
41    if let Value::Arr(rows) = deltas {
42        for row in rows.iter() {
43            if let Value::Arr(_) = row {
44                side.store_array(row.clone());
45            }
46        }
47    }
48    side
49}
50
51fn build_book(kind: &str, snapshot: Value, depth: Value) -> Value {
52    let max_depth = match &depth {
53        Value::Int(n) if *n > 0 => *n,
54        _ => MAX_DEPTH_SENTINEL,
55    };
56    let (side_kind, _) = match kind {
57        BOOK_INDEXED => (SIDE_INDEXED, true),
58        BOOK_COUNTED => (SIDE_COUNTED, true),
59        _            => (SIDE_PLAIN,   true),
60    };
61    let bids_deltas = crate::get_value(&snapshot, &Value::Str("bids".into()));
62    let asks_deltas = crate::get_value(&snapshot, &Value::Str("asks".into()));
63    let bids = new_side(side_kind, /*is_bid=*/ true,  max_depth, &bids_deltas);
64    let asks = new_side(side_kind, /*is_bid=*/ false, max_depth, &asks_deltas);
65
66    let timestamp = match crate::get_value(&snapshot, &Value::Str("timestamp".into())) {
67        Value::Int(n)   => Some(n),
68        Value::Float(f) => Some(f as i64),
69        _ => None,
70    };
71    let datetime = timestamp.and_then(iso8601_millis);
72    let nonce = match crate::get_value(&snapshot, &Value::Str("nonce".into())) {
73        Value::Int(n)   => Value::Int(n),
74        Value::Float(f) => Value::Int(f as i64),
75        _ => Value::Null,
76    };
77    let symbol = crate::get_value(&snapshot, &Value::Str("symbol".into()));
78
79    // Scalar meta lives in the shared book store (keyed by `__book_id`) so WS
80    // handlers that mutate a cloned book — okx's seqId nonce — propagate.
81    let book_id = crate::value::alloc_book_id();
82    crate::value::book_meta_set(book_id, "timestamp", timestamp.map(Value::Int).unwrap_or(Value::Null));
83    crate::value::book_meta_set(book_id, "datetime",  datetime.map(|s| Value::Str(s.into())).unwrap_or(Value::Null));
84    crate::value::book_meta_set(book_id, "nonce",     nonce);
85    crate::value::book_meta_set(book_id, "symbol",    symbol);
86
87    let mut m = IndexMap::new();
88    m.insert("__bookKind".to_string(), Value::Str(kind.to_string().into()));
89    m.insert("__book_id".to_string(),  Value::Int(book_id));
90    m.insert("_depth".to_string(),     Value::Int(max_depth));
91    m.insert("bids".to_string(),       bids);
92    m.insert("asks".to_string(),       asks);
93    Value::Map(m)
94}
95
96// ─── factories ────────────────────────────────────────────────────────────
97
98/// `new Bids(deltas, depth)` — TS side-class shorthand for an
99/// `OrderBookSide` constructed with `is_bid: true`. The transpiled
100/// per-exchange WS code (`bitmart`, `bitvavo`, …) uses this when
101/// patching an inner side of an order book snapshot. Returns the same
102/// `__sideKind` marker as `OrderBook::new`'s seeded sides.
103pub struct Bids;
104impl Bids {
105    pub fn new(deltas: Value, depth: Value) -> Value {
106        let max_depth = match &depth {
107            Value::Int(n) if *n > 0 => *n,
108            _ => MAX_DEPTH_SENTINEL,
109        };
110        new_side(SIDE_PLAIN, /*is_bid=*/ true, max_depth, &deltas)
111    }
112}
113
114/// `new Asks(deltas, depth)` — the ask-side companion.
115pub struct Asks;
116impl Asks {
117    pub fn new(deltas: Value, depth: Value) -> Value {
118        let max_depth = match &depth {
119            Value::Int(n) if *n > 0 => *n,
120            _ => MAX_DEPTH_SENTINEL,
121        };
122        new_side(SIDE_PLAIN, /*is_bid=*/ false, max_depth, &deltas)
123    }
124}
125
126pub struct OrderBook;
127impl OrderBook {
128    /// `new OrderBook(snapshot)` or `new OrderBook(snapshot, depth)`.
129    /// Both arities are emitted by the transpiler — `padCallsForVariadicFn`
130    /// pads the 1-arg call with `Value::Null`, so we can declare the
131    /// 2-arg signature unconditionally.
132    pub fn new(snapshot: Value, depth: Value) -> Value {
133        build_book(BOOK_PLAIN, snapshot, depth)
134    }
135}
136
137pub struct IndexedOrderBook;
138impl IndexedOrderBook {
139    pub fn new(snapshot: Value, depth: Value) -> Value {
140        build_book(BOOK_INDEXED, snapshot, depth)
141    }
142}
143
144pub struct CountedOrderBook;
145impl CountedOrderBook {
146    pub fn new(snapshot: Value, depth: Value) -> Value {
147        build_book(BOOK_COUNTED, snapshot, depth)
148    }
149}