pricelevel 0.7.0

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
419
420
421
422
423
424
425
426
427
428
429
 [![Dual License](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
 [![Crates.io](https://img.shields.io/crates/v/pricelevel.svg)](https://crates.io/crates/pricelevel)
 [![Downloads](https://img.shields.io/crates/d/pricelevel.svg)](https://crates.io/crates/pricelevel)
 [![Stars](https://img.shields.io/github/stars/joaquinbejar/PriceLevel.svg)](https://github.com/joaquinbejar/PriceLevel/stargazers)
 [![Issues](https://img.shields.io/github/issues/joaquinbejar/PriceLevel.svg)](https://github.com/joaquinbejar/PriceLevel/issues)
 [![PRs](https://img.shields.io/github/issues-pr/joaquinbejar/PriceLevel.svg)](https://github.com/joaquinbejar/PriceLevel/pulls)

 [![Build Status](https://img.shields.io/github/workflow/status/joaquinbejar/PriceLevel/CI)](https://github.com/joaquinbejar/PriceLevel/actions)
 [![Coverage](https://img.shields.io/codecov/c/github/joaquinbejar/PriceLevel)](https://codecov.io/gh/joaquinbejar/PriceLevel)
 [![Dependencies](https://img.shields.io/librariesio/github/joaquinbejar/PriceLevel)](https://libraries.io/github/joaquinbejar/PriceLevel)
 [![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://docs.rs/pricelevel)

 # PriceLevel

 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.

 ## Features

 - Lock-free architecture for high-throughput trading applications
 - Support for diverse order types including standard limit orders, iceberg orders, post-only, fill-or-kill, and more
 - Thread-safe operations with atomic counters and lock-free data structures
 - Efficient order matching and execution logic
 - Designed with domain-driven principles for financial markets
 - Comprehensive test suite demonstrating concurrent usage scenarios
 - Built with crossbeam's lock-free data structures
 - Optimized statistics tracking for each price level
 - Memory-efficient implementations suitable for high-frequency trading systems

 Perfect for building matching engines, market data systems, algorithmic trading platforms, and financial exchanges where performance and correctness are critical.

 ## Supported Order Types

 The library provides comprehensive support for various order types used in modern trading systems:

 - **Standard Limit Order**: Basic price-quantity orders with specified execution price
 - **Iceberg Order**: Orders with visible and hidden quantities that replenish automatically
 - **Post-Only Order**: Orders that will not execute immediately against existing orders
 - **Trailing Stop Order**: Orders that adjust based on market price movements
 - **Pegged Order**: Orders that adjust their price based on a reference price
 - **Market-to-Limit Order**: Orders that convert to limit orders after initial execution
 - **Reserve Order**: Orders with custom replenishment logic for visible quantities

 ## Time-in-Force Options

 The library supports the following time-in-force policies:

 - **Good Till Canceled (GTC)**: Order remains active until explicitly canceled
 - **Immediate Or Cancel (IOC)**: Order must be filled immediately (partially or completely) or canceled
 - **Fill Or Kill (FOK)**: Order must be filled completely immediately or canceled entirely
 - **Good Till Date (GTD)**: Order remains active until a specified date/time
 - **Day Order**: Order valid only for the current trading day

 ## Implementation Details

 - **Thread Safety**: Uses atomic operations and lock-free data structures to ensure thread safety without mutex locks
 - **Order Queue Management**: Specialized order queue implementation based on crossbeam's SegQueue
 - **Statistics Tracking**: Each price level tracks execution statistics in real-time
 - **Snapshot Capabilities**: Create point-in-time snapshots of price levels for market data distribution
 - **Efficient Matching**: Optimized algorithms for matching incoming orders against existing orders
 - **Support for Special Order Types**: Custom handling for iceberg orders, reserve orders, and other special types

 ## Price Level Features

 - **Atomic Counters**: Uses atomic types for thread-safe quantity tracking
 - **Efficient Order Storage**: Optimized data structures for order storage and retrieval
 - **Visibility Controls**: Separate tracking of visible and hidden quantities
 - **Performance Monitoring**: Built-in statistics for monitoring execution performance
 - **Order Matching Logic**: Sophisticated algorithms for matching orders at each price level

### Performance Benchmark Results

The `pricelevel` library has been thoroughly tested for performance in high-frequency trading scenarios. Below are the results from recent simulations conducted on an M4 Max processor, demonstrating the library's capability to handle intensive concurrent trading operations.

#### High-Frequency Trading Simulation

##### Simulation Parameters
- **Price Level**: 10000
- **Duration**: 5002 ms (5.002 seconds)
- **Threads**: 30 total
  - 10 maker threads (adding orders)
  - 10 taker threads (executing matches)
  - 10 canceller threads (cancelling orders)
- **Initial Orders**: 1000 orders seeded before simulation

##### Performance Metrics

| Metric | Total Operations | Rate (per second) |
|--------|-----------------|-------------------|
| Orders Added | 715,814 | 143,095.10 |
| Matches Executed | 374,910 | 74,946.54 |
| Cancellations | 96,575 | 19,305.87 |
| **Total Operations** | **1,187,299** | **237,347.51** |

##### Final State After Simulation
- **Price**: 10000
- **Visible Quantity**: 4,590,308
- **Hidden Quantity**: 4,032,155
- **Total Quantity**: 8,622,463
- **Order Count**: 704,156

##### Price Level Statistics
- **Orders Added**: 716,814
- **Orders Removed**: 215
- **Orders Executed**: 401,864
- **Quantity Executed**: 1,124,714
- **Value Executed**: 11,247,140,000
- **Average Execution Price**: 10,000.00
- **Average Waiting Time**: 1,788.31 ms
- **Time Since Last Execution**: 1 ms

#### Contention Pattern Analysis

##### Hot Spot Contention Test
Performance under different levels of contention targeting specific price levels:

| Hot Spot % | Operations/second |
|------------|-------------------|
| 0% | 7,548,438.05 |
| 25% | 7,752,860.57 |
| 50% | 7,584,981.59 |
| 75% | 7,267,749.39 |
| 100% | 6,970,720.77 |

##### Read/Write Ratio Test
Performance under different read/write operation ratios:

| Read % | Operations/second |
|--------|-------------------|
| 0% | 6,353,202.47 |
| 25% | 34,727.89 |
| 50% | 28,783.28 |
| 75% | 31,936.73 |
| 95% | 54,316.57 |

#### Analysis

The simulation demonstrates the library's exceptional performance capabilities:

- **High-Frequency Trading**: Over **264,000 operations per second** in realistic mixed workloads
- **Hot Spot Performance**: Up to **7.75 million operations per second** under optimal conditions
- **Write-Heavy Workloads**: Over **6.3 million operations per second** for pure write operations
- **Lock-Free Architecture**: Maintains high throughput with minimal contention overhead

The performance characteristics demonstrate that the `pricelevel` library is suitable for production use in high-performance trading systems, matching engines, and other financial applications where microsecond-level performance is critical.

### Migration Guide (v0.6 → v0.7)

Version 0.7.0 introduces several intentional breaking changes to improve type safety,
correctness, and API ergonomics. This section provides a complete mapping from the old
API surface to the new one.

#### Execution Domain Rename

The execution domain was renamed from `Transaction` to `Trade` to align with standard
financial terminology.

| v0.6 | v0.7 |
|------|------|
| `Transaction` | [`Trade`] |
| `TransactionList` | [`TradeList`] |
| `transaction_id` field | [`Trade::trade_id()`] accessor |
| `Transaction:` parsing prefix | `Trade:` parsing prefix |

#### Identifier Types

Raw `Uuid` identifiers were replaced with the [`Id`] enum, which supports UUID, ULID, and
sequential (`u64`) formats. Trade IDs are generated via [`UuidGenerator`].

| v0.6 | v0.7 |
|------|------|
| `Uuid` (raw) | [`Id`] enum (`Uuid`, `Ulid`, `Sequential`) |
| `Uuid::new_v4()` | [`Id::new()`] or [`Id::new_uuid()`] |
| `u64` order/trade IDs | [`Id::from_u64()`] or [`Id::sequential()`] |
| `AtomicU64` trade counter | [`UuidGenerator::next()`] |

#### Domain Newtypes

Raw numeric primitives used in the public API were replaced with validated domain
newtypes. Each provides `new()`, `try_new()`, `Display`, `FromStr`, and serde support.

| v0.6 | v0.7 | Inner |
|------|------|-------|
| `u128` (price) | [`Price`] | `u128` |
| `u64` (quantity) | [`Quantity`] | `u64` |
| `u64` (timestamp) | [`TimestampMs`] | `u64` |

```rust
use pricelevel::{Price, Quantity, TimestampMs};

let price = Price::new(10_000);
let qty   = Quantity::new(100);
let ts    = TimestampMs::new(1_716_000_000_000);

// Convert back to primitives
assert_eq!(price.as_u128(), 10_000);
assert_eq!(qty.as_u64(), 100);
assert_eq!(ts.as_u64(), 1_716_000_000_000);
```

#### Checked Arithmetic

All arithmetic in financial-critical paths now uses checked operations and returns
`Result<T, PriceLevelError>` instead of raw values. No silent saturation or wrapping
is performed.

| Method | v0.6 Return | v0.7 Return |
|--------|-------------|-------------|
| [`PriceLevel::total_quantity()`] | `u64` | `Result<u64, PriceLevelError>` |
| [`MatchResult::executed_quantity()`] | `u64` | `Result<u64, PriceLevelError>` |
| [`MatchResult::executed_value()`] | `u128` | `Result<u128, PriceLevelError>` |
| [`MatchResult::average_price()`] | `Option<f64>` | `Result<Option<f64>, PriceLevelError>` |
| [`MatchResult::add_trade()`] | `()` | `Result<(), PriceLevelError>` |

```rust
use pricelevel::{PriceLevel, PriceLevelError};

let level = PriceLevel::new(10_000);
// total_quantity() now returns Result
let total: Result<u64, PriceLevelError> = level.total_quantity();
assert_eq!(total.unwrap(), 0);
```

#### Private Fields and Accessor Methods

All struct fields in the execution and snapshot modules are now private. Use the
provided accessor methods instead of direct field access.

**Trade:**

| v0.6 (field) | v0.7 (accessor) |
|--------------|-----------------|
| `trade.trade_id` | [`trade.trade_id()`]Trade::trade_id |
| `trade.taker_order_id` | [`trade.taker_order_id()`]Trade::taker_order_id |
| `trade.maker_order_id` | [`trade.maker_order_id()`]Trade::maker_order_id |
| `trade.price` | [`trade.price()`]Trade::price |
| `trade.quantity` | [`trade.quantity()`]Trade::quantity |
| `trade.taker_side` | [`trade.taker_side()`]Trade::taker_side |
| `trade.timestamp` | [`trade.timestamp()`]Trade::timestamp |

**MatchResult:**

| v0.6 (field) | v0.7 (accessor) |
|--------------|-----------------|
| `result.order_id` | [`result.order_id()`]MatchResult::order_id |
| `result.trades` | [`result.trades()`]MatchResult::trades |
| `result.remaining_quantity` | [`result.remaining_quantity()`]MatchResult::remaining_quantity |
| `result.is_complete` | [`result.is_complete()`]MatchResult::is_complete |
| `result.filled_order_ids` | [`result.filled_order_ids()`]MatchResult::filled_order_ids |

**TradeList:**

| v0.6 (field) | v0.7 (accessor) |
|--------------|-----------------|
| `list.trades` (direct `Vec`) | [`list.as_vec()`]TradeList::as_vec / [`list.into_vec()`]TradeList::into_vec |
| `list.trades.push(t)` | [`list.add(t)`]TradeList::add |
| `list.trades.len()` | [`list.len()`]TradeList::len |
| `list.trades.is_empty()` | [`list.is_empty()`]TradeList::is_empty |

#### Iterator API Changes

The `iter_orders()` method now returns an iterator instead of a `Vec`, reducing
allocations on the hot path. Use `snapshot_orders()` when a materialized `Vec` is needed.

| v0.6 | v0.7 |
|------|------|
| `level.iter_orders() -> Vec<Arc<OrderType<()>>>` | [`level.iter_orders()`]PriceLevel::iter_orders `-> impl Iterator` |
| (no equivalent) | [`level.snapshot_orders()`]PriceLevel::snapshot_orders `-> Vec<Arc<OrderType<()>>>` |

#### Snapshot Persistence and Recovery

Snapshots are now protected with SHA-256 checksums via [`PriceLevelSnapshotPackage`].
The full persistence/recovery flow is:

```rust
use pricelevel::PriceLevel;

let level = PriceLevel::new(10_000);

// Serialize to JSON (includes checksum)
let json = level.snapshot_to_json().unwrap();

// Restore from JSON (validates checksum)
let restored = PriceLevel::from_snapshot_json(&json).unwrap();
```

#### Compiler Attributes

- **`#[must_use]`** is now applied to all pure/computed methods (`price()`, `quantity()`,
  `trade_id()`, `order_count()`, `visible_quantity()`, `is_complete()`, etc.).
  Ignoring a return value from these methods will produce a compiler warning.
- **`#[repr(u8)]`** is applied to small enums exposed in the public API ([`Side`],
  [`TimeInForce`]).

#### Error Handling

[`PriceLevelError`] gained new variants for the expanded error surface:

| Variant | Purpose |
|---------|---------|
| `InvalidOperation { message }` | Checked arithmetic overflow, invalid state transitions |
| `SerializationError { message }` | JSON/serde serialization failures |
| `DeserializationError { message }` | JSON/serde deserialization failures |
| `ChecksumMismatch { expected, actual }` | Snapshot integrity validation failure |

#### Quick Migration Checklist

1. Replace `Transaction` / `TransactionList` with [`Trade`] / [`TradeList`].
2. Replace raw `Uuid` with [`Id`]; use [`UuidGenerator`] for trade IDs.
3. Wrap raw price/quantity/timestamp literals with [`Price::new()`]Price::new,
   [`Quantity::new()`]Quantity::new, [`TimestampMs::new()`]TimestampMs::new.
4. Replace direct field access on `Trade`, `MatchResult`, `TradeList` with accessors.
5. Handle `Result` returns from `total_quantity()`, `executed_quantity()`,
   `executed_value()`, `average_price()`, and `add_trade()`.
6. Replace `iter_orders()` collecting into `Vec` with `snapshot_orders()` if needed.
7. Update snapshot code to use [`PriceLevelSnapshotPackage`] for checksum validation.
8. Address new `#[must_use]` warnings on query methods.


 ## Setup Instructions

 1. Clone the repository:
 ```shell
 git clone https://github.com/joaquinbejar/PriceLevel.git
 cd PriceLevel
 ```

 2. Build the project:
 ```shell
 make build
 ```

 3. Run tests:
 ```shell
 make test
 ```

 4. Format the code:
 ```shell
 make fmt
 ```

 5. Run linting:
 ```shell
 make lint
 ```

 6. Clean the project:
 ```shell
 make clean
 ```

 7. Run the project:
 ```shell
 make run
 ```

 8. Fix issues:
 ```shell
 make fix
 ```

 9. Run pre-push checks:
 ```shell
 make pre-push
 ```

 10. Generate documentation:
 ```shell
 make doc
 ```

 11. Publish the package:
 ```shell
 make publish
 ```

 12. Generate coverage report:
 ```shell
 make coverage
 ```

 ## Library Usage

 To use the library in your project, add the following to your `Cargo.toml`:

 ```toml
 [dependencies]
 pricelevel = { git = "https://github.com/joaquinbejar/PriceLevel.git" }
 ```

 ## Usage Examples

 Here are some examples of how to use the library:


 ## Testing

 To run unit tests:
 ```shell
 make test
 ```

 To run tests with coverage:
 ```shell
 make coverage
 ```

 ## Contribution and Contact

 We welcome contributions to this project! If you would like to contribute, please follow these steps:

 1. Fork the repository.
 2. Create a new branch for your feature or bug fix.
 3. Make your changes and ensure that the project still builds and all tests pass.
 4. Commit your changes and push your branch to your forked repository.
 5. Submit a pull request to the main repository.

 If you have any questions, issues, or would like to provide feedback, please feel free to contact the project maintainer:

 **Joaquín Béjar García**
 - Email: jb@taunais.com
 - **Telegram**: [@joaquin_bejar]https://t.me/joaquin_bejar
 - GitHub: [joaquinbejar]https://github.com/joaquinbejar

 We appreciate your interest and look forward to your contributions!



License: MIT