orderbook-rs 0.10.1

A high-performance, lock-free price level implementation for limit order books in Rust. This library provides the building blocks for creating efficient trading systems with support for multiple order types and concurrent access patterns.
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
//! Tests for fee schedule functionality

use orderbook_rs::{FeeSchedule, OrderBook, TradeResult};
use pricelevel::{Id, Side, TimeInForce};
use std::sync::Arc;

#[test]
fn test_fee_schedule_creation() {
    let schedule = FeeSchedule::new(-2, 5);
    assert_eq!(schedule.maker_fee_bps, -2);
    assert_eq!(schedule.taker_fee_bps, 5);
    assert!(schedule.has_maker_rebate());
    assert!(!schedule.is_zero_fee());
}

#[test]
fn test_zero_fee_schedule() {
    let schedule = FeeSchedule::zero_fee();
    assert_eq!(schedule.maker_fee_bps, 0);
    assert_eq!(schedule.taker_fee_bps, 0);
    assert!(!schedule.has_maker_rebate());
    assert!(schedule.is_zero_fee());
}

#[test]
fn test_taker_only_schedule() {
    let schedule = FeeSchedule::taker_only(10);
    assert_eq!(schedule.maker_fee_bps, 0);
    assert_eq!(schedule.taker_fee_bps, 10);
    assert!(!schedule.has_maker_rebate());
    assert!(!schedule.is_zero_fee());
}

#[test]
fn test_maker_rebate_schedule() {
    let schedule = FeeSchedule::with_maker_rebate(3, 7);
    assert_eq!(schedule.maker_fee_bps, -3);
    assert_eq!(schedule.taker_fee_bps, 7);
    assert!(schedule.has_maker_rebate());
    assert!(!schedule.is_zero_fee());
}

#[test]
fn test_fee_calculation_taker() {
    let schedule = FeeSchedule::new(-2, 5);
    let notional = 100_000_000; // $1,000 in cents

    // 5 bps of $1,000 = $0.50 = 50 cents
    let fee = schedule.calculate_fee(notional, false);
    assert_eq!(fee, 50_000);
}

#[test]
fn test_fee_calculation_maker_rebate() {
    let schedule = FeeSchedule::new(-2, 5);
    let notional = 100_000_000; // $1,000 in cents

    // -2 bps of $1,000 = -$0.20 = -20 cents
    let rebate = schedule.calculate_fee(notional, true);
    assert_eq!(rebate, -20_000);
}

#[test]
fn test_fee_calculation_zero_fee() {
    let schedule = FeeSchedule::zero_fee();
    let notional = 100_000_000;

    assert_eq!(schedule.calculate_fee(notional, true), 0);
    assert_eq!(schedule.calculate_fee(notional, false), 0);
}

#[test]
fn test_fee_calculation_edge_cases() {
    let schedule = FeeSchedule::new(1, 1);
    let notional = 0;

    assert_eq!(schedule.calculate_fee(notional, true), 0);
    assert_eq!(schedule.calculate_fee(notional, false), 0);
}

#[test]
fn test_fee_calculation_large_values() {
    let schedule = FeeSchedule::new(1, 1);
    let notional = u128::MAX / 10_000 - 1; // Safe large value

    let fee = schedule.calculate_fee(notional, false);
    assert!(fee > 0);
    assert!(fee < i128::MAX);
}

#[test]
fn test_orderbook_fee_schedule_default() {
    let book = OrderBook::<()>::new("BTC/USD");
    assert_eq!(book.fee_schedule(), None);
}

#[test]
fn test_orderbook_set_fee_schedule() {
    let mut book = OrderBook::<()>::new("BTC/USD");
    let schedule = FeeSchedule::new(-2, 5);

    book.set_fee_schedule(Some(schedule));
    assert_eq!(book.fee_schedule(), Some(schedule));
}

#[test]
fn test_orderbook_update_fee_schedule() {
    let mut book = OrderBook::<()>::new("BTC/USD");

    // Set initial schedule
    let initial_schedule = FeeSchedule::new(-1, 3);
    book.set_fee_schedule(Some(initial_schedule));
    assert_eq!(book.fee_schedule(), Some(initial_schedule));

    // Update to different schedule
    let new_schedule = FeeSchedule::new(-2, 5);
    book.set_fee_schedule(Some(new_schedule));
    assert_eq!(book.fee_schedule(), Some(new_schedule));

    // Disable fees
    book.set_fee_schedule(None);
    assert_eq!(book.fee_schedule(), None);
}

#[test]
fn test_orderbook_fee_schedule_persistence() {
    let mut book = OrderBook::<()>::new("BTC/USD");
    let schedule = FeeSchedule::with_maker_rebate(2, 6);

    book.set_fee_schedule(Some(schedule));

    // Add an order (maker)
    let order_id = Id::new_uuid();
    let result = book.add_limit_order(order_id, 100_000, 10, Side::Buy, TimeInForce::Gtc, None);
    assert!(result.is_ok());

    // Fee schedule should still be set
    assert_eq!(book.fee_schedule(), Some(schedule));
}

#[test]
fn test_orderbook_constructors_with_fee_schedule() {
    let schedule = FeeSchedule::new(-2, 5);

    // Test basic constructor
    let mut book1 = OrderBook::<()>::new("BTC/USD");
    book1.set_fee_schedule(Some(schedule));
    assert_eq!(book1.fee_schedule(), Some(schedule));

    // Test constructor with trade listener
    let listener: Arc<dyn Fn(&TradeResult) + Send + Sync> =
        Arc::new(|_trade_result: &TradeResult| {
            // Empty listener for testing
        });
    let mut book2 = OrderBook::<()>::with_trade_listener("BTC/USD", listener);
    book2.set_fee_schedule(Some(schedule));
    assert_eq!(book2.fee_schedule(), Some(schedule));
}

#[test]
fn test_fee_schedule_serialization() {
    let schedule = FeeSchedule::new(-2, 5);

    // Test JSON serialization
    let json = serde_json::to_string(&schedule).unwrap();
    let deserialized: FeeSchedule = serde_json::from_str(&json).unwrap();

    assert_eq!(schedule, deserialized);

    // Test with zero fees
    let zero_schedule = FeeSchedule::zero_fee();
    let json = serde_json::to_string(&zero_schedule).unwrap();
    let deserialized: FeeSchedule = serde_json::from_str(&json).unwrap();

    assert_eq!(zero_schedule, deserialized);
}

#[test]
fn test_orderbook_serialization_with_fee_schedule() {
    let mut book = OrderBook::<()>::new("BTC/USD");
    let schedule = FeeSchedule::with_maker_rebate(3, 7);
    book.set_fee_schedule(Some(schedule));

    // Test serialization
    let json = serde_json::to_string(&book).unwrap();
    assert!(json.contains("fee_schedule"));
}

#[test]
fn test_orderbook_serialization_without_fee_schedule() {
    let book = OrderBook::<()>::new("BTC/USD");

    // Test serialization with no fee schedule
    let json = serde_json::to_string(&book).unwrap();
    assert!(json.contains("fee_schedule"));
}

#[test]
fn test_fee_schedule_mathematical_properties() {
    let schedule = FeeSchedule::new(10, 20);
    let notional = 100_000; // $1,000

    // Test linearity: double the notional should double the fee
    let fee1 = schedule.calculate_fee(notional, false);
    let fee2 = schedule.calculate_fee(notional * 2, false);
    assert_eq!(fee2, fee1 * 2);

    // Test sign consistency
    assert!(schedule.calculate_fee(notional, false) > 0); // Taker fee positive
    assert!(schedule.calculate_fee(notional, true) > 0); // Maker fee positive

    // Test with rebates
    let rebate_schedule = FeeSchedule::new(-5, 10);
    assert!(rebate_schedule.calculate_fee(notional, true) < 0); // Maker rebate negative
    assert!(rebate_schedule.calculate_fee(notional, false) > 0); // Taker fee positive
}

#[test]
fn test_fee_schedule_precision() {
    let schedule = FeeSchedule::new(1, 1);

    // Test with small notional values
    let small_notional = 1;
    let fee = schedule.calculate_fee(small_notional, false);
    assert_eq!(fee, 0); // Should be 0 due to integer division (1 * 1 / 10000)

    // Test with exact division
    let exact_notional = 10_000;
    let fee = schedule.calculate_fee(exact_notional, false);
    assert_eq!(fee, 1); // Should be exactly 1 (10000 * 1 / 10000)
}

#[test]
fn test_fee_schedule_default_trait() {
    let default_schedule = FeeSchedule::default();
    assert!(default_schedule.is_zero_fee());
    assert_eq!(default_schedule.maker_fee_bps, 0);
    assert_eq!(default_schedule.taker_fee_bps, 0);
}

#[cfg(test)]
mod integration_tests {
    use super::*;
    use std::sync::Mutex;

    #[test]
    fn test_fee_schedule_with_matching() {
        let mut book = OrderBook::<()>::new("BTC/USD");
        let schedule = FeeSchedule::new(-2, 5);
        book.set_fee_schedule(Some(schedule));

        // Add a bid order (maker)
        let bid_order_id = Id::new_uuid();
        let bid_result =
            book.add_limit_order(bid_order_id, 100_000, 10, Side::Buy, TimeInForce::Gtc, None);
        assert!(bid_result.is_ok());

        // Add an ask order that will match (taker)
        let ask_order_id = Id::new_uuid();
        let ask_result =
            book.add_limit_order(ask_order_id, 100_000, 5, Side::Sell, TimeInForce::Ioc, None);
        assert!(ask_result.is_ok());

        // The fee schedule should still be intact after matching
        assert_eq!(book.fee_schedule(), Some(schedule));

        // Verify the book state
        let snapshot = book.create_snapshot(10);
        assert_eq!(snapshot.bids.len(), 1); // Remaining bid quantity
        assert_eq!(snapshot.asks.len(), 0); // Ask fully consumed
    }

    #[test]
    fn test_fee_schedule_with_multiple_operations() {
        let mut book = OrderBook::<()>::new("BTC/USD");

        // Start with no fees
        assert_eq!(book.fee_schedule(), None);

        // Add orders with no fees
        let order1_id = Id::new_uuid();
        book.add_limit_order(order1_id, 100_000, 10, Side::Buy, TimeInForce::Gtc, None)
            .unwrap();
        assert_eq!(book.fee_schedule(), None);

        // Set fee schedule
        let schedule = FeeSchedule::taker_only(10);
        book.set_fee_schedule(Some(schedule));
        assert_eq!(book.fee_schedule(), Some(schedule));

        // Add more orders with fees active
        let order2_id = Id::new_uuid();
        book.add_limit_order(order2_id, 100_000, 5, Side::Sell, TimeInForce::Gtc, None)
            .unwrap();
        assert_eq!(book.fee_schedule(), Some(schedule));

        // Fee schedule should persist through operations
        let snapshot = book.create_snapshot(10);
        assert!(!snapshot.bids.is_empty() || !snapshot.asks.is_empty());
        assert_eq!(book.fee_schedule(), Some(schedule));
    }

    #[test]
    fn test_trade_listener_receives_fees() {
        // Capture trades via listener
        let captured_trades = Arc::new(Mutex::new(Vec::<TradeResult>::new()));
        let captured_clone = captured_trades.clone();

        let listener: Arc<dyn Fn(&TradeResult) + Send + Sync> =
            Arc::new(move |trade_result: &TradeResult| {
                let mut trades = captured_clone.lock().unwrap();
                trades.push(trade_result.clone());
            });

        let mut book = OrderBook::<()>::with_trade_listener("BTC/USD", listener);

        // Set fee schedule: -2 bps maker rebate, 5 bps taker fee
        let schedule = FeeSchedule::new(-2, 5);
        book.set_fee_schedule(Some(schedule));

        // Add a resting sell order (will become maker)
        let sell_id = Id::new_uuid();
        book.add_limit_order(sell_id, 10_000, 100, Side::Sell, TimeInForce::Gtc, None)
            .unwrap();

        // Submit market buy (taker) — will match and trigger listener
        let buy_id = Id::new_uuid();
        book.submit_market_order(buy_id, 50, Side::Buy).unwrap();

        // Verify the captured trade has correct fees
        let trades = captured_trades.lock().unwrap();
        assert_eq!(trades.len(), 1);

        let tr = &trades[0];
        assert_eq!(tr.symbol, "BTC/USD");

        // notional = 10_000 * 50 = 500_000
        // maker fee: 500_000 * -2 / 10_000 = -100
        assert_eq!(tr.total_maker_fees, -100);
        // taker fee: 500_000 * 5 / 10_000 = 250
        assert_eq!(tr.total_taker_fees, 250);
        // total: -100 + 250 = 150
        assert_eq!(tr.total_fees(), 150);
    }

    #[test]
    fn test_trade_listener_receives_zero_fees_when_no_schedule() {
        let captured_trades = Arc::new(Mutex::new(Vec::<TradeResult>::new()));
        let captured_clone = captured_trades.clone();

        let listener: Arc<dyn Fn(&TradeResult) + Send + Sync> =
            Arc::new(move |trade_result: &TradeResult| {
                let mut trades = captured_clone.lock().unwrap();
                trades.push(trade_result.clone());
            });

        let book = OrderBook::<()>::with_trade_listener("BTC/USD", listener);
        // No fee schedule configured (None by default)

        let sell_id = Id::new_uuid();
        book.add_limit_order(sell_id, 10_000, 100, Side::Sell, TimeInForce::Gtc, None)
            .unwrap();

        let buy_id = Id::new_uuid();
        book.submit_market_order(buy_id, 50, Side::Buy).unwrap();

        let trades = captured_trades.lock().unwrap();
        assert_eq!(trades.len(), 1);
        assert_eq!(trades[0].total_maker_fees, 0);
        assert_eq!(trades[0].total_taker_fees, 0);
        assert_eq!(trades[0].total_fees(), 0);
    }

    #[test]
    fn test_trade_listener_fees_across_multiple_price_levels() {
        let captured_trades = Arc::new(Mutex::new(Vec::<TradeResult>::new()));
        let captured_clone = captured_trades.clone();

        let listener: Arc<dyn Fn(&TradeResult) + Send + Sync> =
            Arc::new(move |trade_result: &TradeResult| {
                let mut trades = captured_clone.lock().unwrap();
                trades.push(trade_result.clone());
            });

        let mut book = OrderBook::<()>::with_trade_listener("BTC/USD", listener);

        // 10 bps taker, -3 bps maker rebate
        let schedule = FeeSchedule::new(-3, 10);
        book.set_fee_schedule(Some(schedule));

        // Add two sell orders at different prices
        let sell_id1 = Id::new_uuid();
        book.add_limit_order(sell_id1, 1000, 10, Side::Sell, TimeInForce::Gtc, None)
            .unwrap();

        let sell_id2 = Id::new_uuid();
        book.add_limit_order(sell_id2, 2000, 10, Side::Sell, TimeInForce::Gtc, None)
            .unwrap();

        // Market buy that sweeps both levels
        let buy_id = Id::new_uuid();
        book.submit_market_order(buy_id, 20, Side::Buy).unwrap();

        let trades = captured_trades.lock().unwrap();
        assert_eq!(trades.len(), 1);

        let tr = &trades[0];
        // tx1: notional = 1000 * 10 = 10_000
        //   maker: -3 * 10_000 / 10_000 = -3
        //   taker: 10 * 10_000 / 10_000 = 10
        // tx2: notional = 2000 * 10 = 20_000
        //   maker: -3 * 20_000 / 10_000 = -6
        //   taker: 10 * 20_000 / 10_000 = 20
        assert_eq!(tr.total_maker_fees, -9);
        assert_eq!(tr.total_taker_fees, 30);
        assert_eq!(tr.total_fees(), 21);
    }
}