weirdnet-exchange 0.2.0

Weirdnet exchange types and traits: instruments, exact decimal prices and sizes, orders with a state machine, fills, balances, positions, market data, an async adapter trait, cost and rate-limit helpers, and an in-memory paper exchange.
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
//! Market data: trades, tickers, order books and candles.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::ExchangeError;
use crate::instrument::{Market, ProductStatus};
use crate::num::{Decimal, Price, Qty};
use crate::order::Side;

/// A public trade.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Trade {
    pub market: Market,
    pub trade_id: String,
    pub price: Price,
    pub size: Qty,
    /// The taker's side, when the venue says.
    pub taker_side: Option<Side>,
    pub at_ms: i64,
}

/// Best bid and ask and the last trade.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ticker {
    pub market: Market,
    pub bid: Option<Level>,
    pub ask: Option<Level>,
    pub last: Option<Price>,
    pub volume_24h: Option<Qty>,
    pub at_ms: i64,
}

/// A price level: the size resting at a price.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Level {
    pub price: Price,
    pub size: Qty,
}

impl Level {
    pub fn new(price: Price, size: Qty) -> Self {
        Self { price, size }
    }
}

/// A whole book at one sequence number. Bids best (highest) first, asks best (lowest) first.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BookSnapshot {
    pub market: Market,
    pub bids: Vec<Level>,
    pub asks: Vec<Level>,
    pub sequence: u64,
    pub at_ms: i64,
}

/// One level's new size; a zero size removes the level. `side` is the book side
/// ([`Side::Buy`] for bids).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BookChange {
    pub side: Side,
    pub price: Price,
    pub size: Qty,
}

/// Changes to a book. `sequence` follows the snapshot's or the previous delta's by one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BookDelta {
    pub market: Market,
    pub sequence: u64,
    pub changes: Vec<BookChange>,
    pub at_ms: i64,
}

/// A level-2 order book kept from a snapshot and deltas.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrderBook {
    pub market: Market,
    bids: BTreeMap<Price, Qty>,
    asks: BTreeMap<Price, Qty>,
    pub sequence: u64,
    pub updated_ms: i64,
}

impl OrderBook {
    /// An empty book at sequence 0.
    pub fn new(market: Market) -> Self {
        Self { market, bids: BTreeMap::new(), asks: BTreeMap::new(), sequence: 0, updated_ms: 0 }
    }

    pub fn from_snapshot(s: &BookSnapshot) -> Self {
        let mut b = Self::new(s.market.clone());
        b.reset(s);
        b
    }

    /// Replaces the book with a snapshot.
    pub fn reset(&mut self, s: &BookSnapshot) {
        let keep = |l: &&Level| l.size.is_positive();
        self.bids = s.bids.iter().filter(keep).map(|l| (l.price, l.size)).collect();
        self.asks = s.asks.iter().filter(keep).map(|l| (l.price, l.size)).collect();
        self.sequence = s.sequence;
        self.updated_ms = s.at_ms;
    }

    /// Applies a delta. A delta at or before the current sequence is ignored (`Ok(false)`); one
    /// that skips a sequence is a [`ExchangeError::BookGap`] and changes nothing: fetch a new
    /// snapshot.
    pub fn apply(&mut self, d: &BookDelta) -> Result<bool, ExchangeError> {
        if d.market != self.market {
            return Err(ExchangeError::invalid(format!("delta for {} applied to {}", d.market, self.market)));
        }
        if d.sequence <= self.sequence {
            return Ok(false);
        }
        if d.sequence != self.sequence + 1 {
            return Err(ExchangeError::BookGap { expected: self.sequence + 1, got: d.sequence });
        }
        for c in &d.changes {
            self.set(c.side, c.price, c.size);
        }
        self.sequence = d.sequence;
        self.updated_ms = d.at_ms;
        Ok(true)
    }

    /// Sets one level without sequence checks; a zero size removes it.
    pub fn set(&mut self, side: Side, price: Price, size: Qty) {
        let m = self.side_mut(side);
        if size.is_positive() {
            m.insert(price, size);
        } else {
            m.remove(&price);
        }
    }

    fn side_mut(&mut self, side: Side) -> &mut BTreeMap<Price, Qty> {
        match side {
            Side::Buy => &mut self.bids,
            Side::Sell => &mut self.asks,
        }
    }

    /// Levels on one side, best first.
    pub fn levels(&self, side: Side) -> Box<dyn Iterator<Item = Level> + '_> {
        match side {
            Side::Buy => Box::new(self.bids.iter().rev().map(|(p, q)| Level::new(*p, *q))),
            Side::Sell => Box::new(self.asks.iter().map(|(p, q)| Level::new(*p, *q))),
        }
    }

    pub fn best_bid(&self) -> Option<Level> {
        self.levels(Side::Buy).next()
    }

    pub fn best_ask(&self) -> Option<Level> {
        self.levels(Side::Sell).next()
    }

    pub fn mid(&self) -> Option<Price> {
        Some(Price((self.best_bid()?.price.0 + self.best_ask()?.price.0) / Decimal::TWO))
    }

    pub fn spread(&self) -> Option<Decimal> {
        Some(self.best_ask()?.price.0 - self.best_bid()?.price.0)
    }

    /// The best bid is at or above the best ask (a stale or broken book).
    pub fn is_crossed(&self) -> bool {
        matches!((self.best_bid(), self.best_ask()), (Some(b), Some(a)) if b.price >= a.price)
    }

    pub fn is_empty(&self) -> bool {
        self.bids.is_empty() && self.asks.is_empty()
    }

    /// What a taker on `side` would get for `size` walking the opposite side, up to `limit`
    /// when given: the size filled and its notional.
    pub fn walk(&self, side: Side, size: Qty, limit: Option<Price>) -> (Qty, Decimal) {
        let mut left = size;
        let mut notional = Decimal::ZERO;
        for l in self.levels(side.opposite()) {
            if !left.is_positive() || limit.is_some_and(|lim| crosses(side, lim, l.price)) {
                break;
            }
            let take = left.min(l.size);
            notional += l.price * take;
            left = left - take;
        }
        (size - left, notional)
    }

    /// A snapshot of the top `depth` levels on each side (all levels for `None`).
    pub fn snapshot(&self, depth: Option<usize>) -> BookSnapshot {
        let n = depth.unwrap_or(usize::MAX);
        BookSnapshot {
            market: self.market.clone(),
            bids: self.levels(Side::Buy).take(n).collect(),
            asks: self.levels(Side::Sell).take(n).collect(),
            sequence: self.sequence,
            at_ms: self.updated_ms,
        }
    }
}

/// A level at `level` is beyond a taker's `limit` on `side`.
fn crosses(side: Side, limit: Price, level: Price) -> bool {
    match side {
        Side::Buy => level > limit,
        Side::Sell => level < limit,
    }
}

/// Candle widths, ordered narrowest first.
///
/// Serialized in snake case (`"one_minute"`, `"four_hours"`, ...). The enum is
/// `#[non_exhaustive]`: new widths may be added in minor releases, so a `match`
/// outside this crate needs a `_ =>` arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Granularity {
    OneMinute,
    FiveMinutes,
    FifteenMinutes,
    OneHour,
    FourHours,
    SixHours,
    OneDay,
}

impl Granularity {
    /// Every width, narrowest first. A slice, so its type stays the same when widths are added.
    pub const ALL: &'static [Granularity] =
        &[Self::OneMinute, Self::FiveMinutes, Self::FifteenMinutes, Self::OneHour, Self::FourHours, Self::SixHours, Self::OneDay];

    pub fn ms(self) -> i64 {
        const M: i64 = 60_000;
        match self {
            Self::OneMinute => M,
            Self::FiveMinutes => 5 * M,
            Self::FifteenMinutes => 15 * M,
            Self::OneHour => 60 * M,
            Self::FourHours => 240 * M,
            Self::SixHours => 360 * M,
            Self::OneDay => 1440 * M,
        }
    }

    /// The start of the candle holding `at_ms`.
    pub fn start_of(self, at_ms: i64) -> i64 {
        at_ms.div_euclid(self.ms()) * self.ms()
    }
}

/// Open, high, low, close and volume over one interval starting at `start_ms`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Candle {
    pub market: Market,
    pub granularity: Granularity,
    pub start_ms: i64,
    pub open: Price,
    pub high: Price,
    pub low: Price,
    pub close: Price,
    pub volume: Qty,
}

impl Candle {
    fn from_trade(t: &Trade, g: Granularity) -> Self {
        Self {
            market: t.market.clone(),
            granularity: g,
            start_ms: g.start_of(t.at_ms),
            open: t.price,
            high: t.price,
            low: t.price,
            close: t.price,
            volume: t.size,
        }
    }

    fn add(&mut self, t: &Trade) {
        self.high = self.high.max(t.price);
        self.low = self.low.min(t.price);
        self.close = t.price;
        self.volume = self.volume + t.size;
    }
}

/// Builds candles from trades in time order.
#[derive(Debug, Clone)]
pub struct CandleBuilder {
    granularity: Granularity,
    current: Option<Candle>,
}

impl CandleBuilder {
    pub fn new(granularity: Granularity) -> Self {
        Self { granularity, current: None }
    }

    /// Adds a trade. Returns the previous candle when this trade starts a new one. Trades older
    /// than the current candle are dropped.
    pub fn push(&mut self, t: &Trade) -> Option<Candle> {
        let start = self.granularity.start_of(t.at_ms);
        match &mut self.current {
            Some(c) if c.start_ms == start => {
                c.add(t);
                None
            }
            Some(c) if c.start_ms > start => None,
            _ => self.current.replace(Candle::from_trade(t, self.granularity)),
        }
    }

    /// The candle being built.
    pub fn current(&self) -> Option<&Candle> {
        self.current.as_ref()
    }
}

/// Something a market-data stream delivered.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum MarketEvent {
    Trade(Trade),
    Ticker(Ticker),
    /// A full book; replaces what came before.
    Book(BookSnapshot),
    BookDelta(BookDelta),
    Candle(Candle),
    Status {
        market: Market,
        status: ProductStatus,
        at_ms: i64,
    },
    Heartbeat {
        at_ms: i64,
    },
}

impl MarketEvent {
    pub fn market(&self) -> Option<&Market> {
        match self {
            MarketEvent::Trade(t) => Some(&t.market),
            MarketEvent::Ticker(t) => Some(&t.market),
            MarketEvent::Book(b) => Some(&b.market),
            MarketEvent::BookDelta(d) => Some(&d.market),
            MarketEvent::Candle(c) => Some(&c.market),
            MarketEvent::Status { market, .. } => Some(market),
            MarketEvent::Heartbeat { .. } => None,
        }
    }
}

/// What to subscribe to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Channel {
    Trades,
    Ticker,
    /// A snapshot, then deltas.
    Book,
    Candles(Granularity),
    Status,
}

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

    fn p(s: &str) -> Price {
        Price::parse(s).unwrap()
    }
    fn q(s: &str) -> Qty {
        Qty::parse(s).unwrap()
    }
    fn m() -> Market {
        Market::new("v", "BTC-USD")
    }

    fn book() -> OrderBook {
        OrderBook::from_snapshot(&BookSnapshot {
            market: m(),
            bids: vec![Level::new(p("99"), q("1")), Level::new(p("98"), q("2"))],
            asks: vec![Level::new(p("101"), q("1")), Level::new(p("102"), q("2")), Level::new(p("103"), q("0"))],
            sequence: 10,
            at_ms: 0,
        })
    }

    #[test]
    fn book_snapshot_delta_gap_and_walk() {
        let mut b = book();
        assert_eq!(
            (b.best_bid().unwrap().price, b.best_ask().unwrap().price, b.mid(), b.spread()),
            (p("99"), p("101"), Some(p("100")), Some(Decimal::TWO))
        );
        assert_eq!(b.levels(Side::Sell).count(), 2, "zero levels dropped");
        let d = |seq, changes| BookDelta { market: m(), sequence: seq, changes, at_ms: seq as i64 };
        assert!(!b.apply(&d(10, vec![])).unwrap(), "stale ignored");
        assert!(
            b.apply(&d(
                11,
                vec![
                    BookChange { side: Side::Sell, price: p("101"), size: Qty::ZERO },
                    BookChange { side: Side::Buy, price: p("100"), size: q("3") }
                ]
            ))
            .unwrap()
        );
        assert_eq!((b.best_bid().unwrap(), b.best_ask().unwrap().price), (Level::new(p("100"), q("3")), p("102")));
        assert_eq!(b.apply(&d(13, vec![])), Err(ExchangeError::BookGap { expected: 12, got: 13 }));
        assert_eq!(b.sequence, 11);

        let b = book();
        assert_eq!(b.walk(Side::Buy, q("2"), None), (q("2"), Decimal::from(203)));
        assert_eq!(b.walk(Side::Buy, q("5"), None), (q("3"), Decimal::from(305)));
        assert_eq!(b.walk(Side::Buy, q("5"), Some(p("101"))), (q("1"), Decimal::from(101)));
        assert_eq!(b.walk(Side::Sell, q("2"), None), (q("2"), Decimal::from(197)));
        assert!(!b.is_crossed());
        let s = b.snapshot(Some(1));
        assert_eq!((s.bids.len(), s.asks.len(), s.sequence), (1, 1, 10));
        assert_eq!(OrderBook::from_snapshot(&b.snapshot(None)), b);
    }

    #[test]
    fn candles_from_trades() {
        let t = |id: &str, price: &str, at| Trade { market: m(), trade_id: id.into(), price: p(price), size: q("1"), taker_side: None, at_ms: at };
        let g = Granularity::OneMinute;
        let mut cb = CandleBuilder::new(g);
        assert_eq!(cb.push(&t("1", "10", 60_000)), None);
        assert_eq!(cb.push(&t("2", "12", 61_000)), None);
        assert_eq!(cb.push(&t("3", "9", 62_000)), None);
        assert_eq!(cb.push(&t("x", "1", 1_000)), None, "late trade dropped");
        let done = cb.push(&t("4", "11", 125_000)).unwrap();
        assert_eq!((done.start_ms, done.open, done.high, done.low, done.close, done.volume), (60_000, p("10"), p("12"), p("9"), p("9"), q("3")));
        assert_eq!(cb.current().unwrap().start_ms, 120_000);
        assert_eq!(Granularity::OneDay.start_of(-1), -86_400_000);
    }

    #[test]
    fn four_hour_granularity() {
        let g = Granularity::FourHours;
        assert_eq!(g.ms(), 14_400_000);
        assert_eq!(g.start_of(0), 0);
        assert_eq!(g.start_of(14_399_999), 0);
        assert_eq!(g.start_of(14_400_000), 14_400_000);
        assert_eq!(g.start_of(5 * 3_600_000 + 1), 14_400_000);
        assert_eq!(g.start_of(-1), -14_400_000);
        assert_eq!(serde_json::to_string(&g).unwrap(), "\"four_hours\"");
        assert_eq!(serde_json::from_str::<Granularity>("\"four_hours\"").unwrap(), g);
        assert!(Granularity::OneHour < g && g < Granularity::SixHours);
    }

    #[test]
    fn granularity_all_is_ordered_and_round_trips() {
        assert_eq!(Granularity::ALL.len(), 7);
        assert!(Granularity::ALL.windows(2).all(|w| w[0] < w[1] && w[0].ms() < w[1].ms()));
        for &g in Granularity::ALL {
            let json = serde_json::to_string(&g).unwrap();
            assert_eq!(serde_json::from_str::<Granularity>(&json).unwrap(), g);
            assert_eq!(g.start_of(g.ms() * 3 + 7), g.ms() * 3);
        }
        let names: Vec<String> = Granularity::ALL.iter().map(|g| serde_json::to_string(g).unwrap()).collect();
        assert_eq!(
            names,
            ["\"one_minute\"", "\"five_minutes\"", "\"fifteen_minutes\"", "\"one_hour\"", "\"four_hours\"", "\"six_hours\"", "\"one_day\""]
        );
    }
}