Skip to content

Releases: joaquinbejar/PriceLevel

v0.4.2

30 Sep 16:10
575f511

Choose a tag to compare

Bump version to 0.4.2 and update workflows to include `clippy` and `r…

v0.4.0

24 Sep 16:43
d6cfa97

Choose a tag to compare

Release Notes: Version 0.4.0 - Snapshot Serialization and Checksum Validation for PriceLevel

Summary

This release introduces robust snapshot serialization, checksum validation, and reconstruction capabilities for the PriceLevel data structure. With SHA-256 checksum protection and expanded error handling, the system ensures stronger data integrity during persistence and transmission. These features set the groundwork for more advanced persistence and distributed synchronization in future versions.


What's New

  • Snapshot & Package Support

    • Added PriceLevelSnapshotPackage to bundle snapshots with checksum validation.
    • Introduced JSON-based serialization and deserialization for snapshots and packages.
    • Exposed PriceLevelSnapshotPackage in public module exports.
  • Reconstruction Methods

    • Added support for reconstructing PriceLevel from:
      • PriceLevelSnapshot
      • PriceLevelSnapshotPackage
      • JSON representations
    • Ensured order position preservation during reconstruction.

Enhancements

  • Integrated checksum computation and validation using SHA-256 via the sha2 crate.
  • Expanded PriceLevelError with:
    • SerializationError
    • DeserializationError
    • ChecksumMismatch
  • Improved error messages with updated fmt::Display implementations.
  • Strengthened roundtrip consistency for snapshot serialization and deserialization.

Bug Fixes

  • Corrected error handling for corrupted and mismatched checksums.
  • Resolved edge case handling in snapshot reconstruction with multiple orders.

Documentation Updates

  • Updated API documentation to cover:
    • PriceLevelSnapshotPackage
    • New serialization/deserialization methods
    • Error variants for integrity validation
  • Added examples for reconstructing PriceLevel from snapshots and JSON formats.

Migration Notes

  • Breaking Changes: None in this release.
  • Dependency Update: Added sha2 as a new dependency for checksum validation.
  • Version Bump: Crate version incremented to 0.4.0.

Release Links

v0.3.1

18 Sep 16:40
e3af428

Choose a tag to compare

Release Notes: Version 1.3.0 - Flexible Order Identification

Summary

This release introduces a major improvement to the OrderId system, enabling support for both UUID and ULID formats. This enhancement increases flexibility in order tracking and system interoperability.


What's New

  • Dual Format Support for OrderId
    The OrderId now supports both UUID and ULID formats, allowing developers to choose the identifier type best suited to their use case.

Enhancements

  • Refactored the OrderId implementation to handle multiple identifier formats seamlessly.
  • Improved internal validation logic for better reliability when parsing and generating order identifiers.

Bug Fixes

  • None in this release.

Breaking Changes

  • No breaking changes were introduced.
    Existing UUID-based identifiers will continue to work without modifications.

Documentation Updates

  • Updated internal documentation to reflect the new dual-format OrderId.
  • Added usage examples showcasing both UUID and ULID options.

Migration Notes

  • No action required for existing users.
  • To leverage ULID, update your order creation logic to specify ULID as the preferred format.

Release Links

v0.3.0

18 Sep 11:32
9dbc191

Choose a tag to compare

Release Notes: Version 0.3.0 – Generic OrderType with Custom Fields

Summary

This release introduces a foundational refactor of the matching engine data model. OrderType is now generic, enabling custom, user-defined fields while preserving ergonomic helpers. Dependent components (OrderQueue, PriceLevel, and PriceLevelSnapshot) were updated to align with the new type signature. Tests, benchmarks, and documentation were refreshed to reflect the changes.


What's New

  • Generic OrderType<T>
    • OrderType now accepts a generic parameter T to carry custom extra fields alongside core order data.
    • New helper methods:
      • extra_fields() – read-only access to extra fields.
      • extra_fields_mut() – mutable access to extra fields.
      • map_extra_fields() – transform extra fields while keeping the order intact.
    • Type aliases provided for common cases (e.g., OrderType<()> for no extra fields).
    • FromStr and fmt::Display implementations updated to fully support generics.

Enhancements

  • OrderQueue updated to explicitly use OrderType<()> when no custom fields are needed.
  • PriceLevel struct and methods refactored to accept generic OrderType<T>.
  • PriceLevelSnapshot adjusted to work with the generic OrderType.
  • Test & Benchmark Simplification
    • Tests migrated to use extra_fields, reducing boilerplate and improving clarity.
    • Expected outputs in simulations updated to match the new model.
  • Documentation
    • README and inline docs refreshed to include examples of OrderType<T> usage and migration tips.

Bug Fixes

  • No functional bugs were reported; however, test expectations and simulation outputs were corrected to ensure consistency with the generic model, reducing false negatives and confusion in CI.

Breaking Changes

  • OrderType now requires a generic parameter.
    • Code using OrderType without generics must be updated:
      • Use OrderType<()> when you do not need custom fields.
      • Or define a custom struct and use OrderType<MyFields> for extended data.
  • APIs that accept/return OrderType now operate on OrderType<T>. Function signatures and type annotations may require adjustments across OrderQueue, PriceLevel, and PriceLevelSnapshot.

Migration Notes

Quick Path (no extra fields)

  • Before
  fn submit(order: OrderType) { /* ... */ }
  let order = OrderType::new(/* ... */);
  • After
fn submit(order: OrderType<()>) { /* ... */ }
let order: OrderType<()> = OrderType::new(/* ... */);

With custom fields

  1. Define your extra fields:
#[derive(Clone, Debug)]
struct MyFields {
    source: String,
    tag: u64,
}
  1. Use the generic type:
let order: OrderType<MyFields> = OrderType::new(/* core fields */, MyFields { source: "api".into(), tag: 42 });
  1. Access/modify extras with helpers:
let src = order.extra_fields().source.as_str();
order.extra_fields_mut().tag += 1;

let mapped = order.map_extra_fields(|f| MyFields { source: f.source, tag: f.tag + 100 });

Touchpoints to review
• Function signatures involving orders (e.g., in OrderQueue, PriceLevel, PriceLevelSnapshot).
• Test fixtures and builders: ensure they instantiate OrderType<()> (or your custom type).
• Parsing/printing: verify any FromStr/Display usage in logs, snapshots, or CLI tools.

Documentation Updates
• README examples updated for OrderType patterns (no-extras and custom fields).
• Added notes on extra_fields* helpers and recommended aliasing for ergonomics.
• Simulation and benchmark sections adjusted to reflect new expected outputs.

Related Commits
• Add generic support for OrderType + helpers: aa9ade0
• Refactor OrderType and tests to use <()>: 9dbc191
• Update OrderQueue to generic <()>: a133887
• Refactor PriceLevel for generic OrderType: 1e36afc
• Refine PriceLevelSnapshot usage: ea0e4db

Release Links
• Repository: https://github.com/joaquinbejar/PriceLevel
• Release Tag: v0.3.0
• Compare View: Changes since last version

v0.2.0

15 Jul 10:32
7be4f48

Choose a tag to compare

Release Notes · Version 0.2.0 – Deterministic Order Handling & OrderQueue Acceleration

Summary

This release focuses on eliminating timestamp non-determinism, dramatically speeding up order look-ups, and publishing refreshed high-frequency-trading (HFT) benchmarks. The core order-matching logic is now rock-solid under concurrency, while OrderQueue achieves constant-time performance thanks to a new internal data structure.


What’s New

  • Deterministic Timestamps
    A module-level TIMESTAMP_COUNTER (AtomicU64) guarantees strictly increasing timestamps for every order, removing flaky test runs and closing subtle race conditions.
  • Instant Order Retrieval
    OrderQueue now stores orders in a DashMap instead of SegQueue, reducing look-up complexity from O(n) to O(1) and boosting mixed-workload throughput beyond 280 k ops/s.
  • Up-to-date Benchmarks
    README and crate-level docs (lib.rs) now report fresh HFT numbers, including hot-spot write scenarios peaking at 7.75 M ops/s.

Enhancements

  • All ten order-helper constructors (create_standard_order, create_iceberg_order, …) now automatically consume the atomic counter, keeping application code clean.
  • Logging calls switched to inline format! parameters for improved readability.
  • Version bumped to 0.2.0 in Cargo.toml.

Bug Fixes

Area Issue Resolution
Tests test_iter_orders failed intermittently due to unordered timestamps Uses deterministic atomic timestamps
Tests test_price_level_from_str overwrote orders with duplicate IDs Switched to unique IDs (1-5)
Stability Rare race conditions in concurrent order creation Atomic counter removes timing holes

Breaking Changes

This release does not introduce API-level breaking changes.
However, timestamp semantics have tightened:

Before After
External caller could supply any timestamp Timestamp is always assigned internally via atomic counter

If you previously relied on caller-supplied timestamps, remove that code and let the library handle ordering.


Documentation Updates

  • README & lib.rs now include:
    • Mixed-workload benchmark: ≈ 264 k ops/s sustained
    • Contention profiles (Hot Spot, Write-Heavy, Read/Write Mix) with exact ops/s
    • Explicit note that price, then arrival time (not order ID) defines book depth

Migration Notes

  1. Re-compile: cargo clean && cargo build --release to link against the new DashMap dependency.
  2. Remove custom timestamps: Constructors auto-assign timestamps; passing your own will be ignored.
  3. Benchmark delta: Expect higher throughput but verify on your hardware—hot-spot write metrics can vary.

Useful Links

v0.1.4

25 Jun 07:56
9f56383

Choose a tag to compare

Release Notes: Version 0.1.4 - Improved CI, Documentation, and Dependency Updates

Summary

Version 0.1.4 focuses on modernizing our development workflows, aligning example dependencies with the latest stable releases, and improving project documentation. Key changes include adding a semantic versioning workflow, refactoring benchmarks, centralizing setup instructions, and updating core dependencies to ensure compatibility with Rust 2024 edition.

What’s New
• Semantic Versioning Workflow: Introduced a new GitHub Actions workflow (.github/workflows/semver.yml) that automatically checks for semantic versioning compliance via cargo-semver-checks-action.
• Centralized README Template: Removed inline setup and contribution instructions from lib.rs and moved them into a structured README.tpl, enhancing consistency and maintainability.

Enhancements
• Dependency Updates in Examples:
• Upgraded tracing to version 0.1 for improved tracing API compatibility.
• Updated uuid to 1.17 with the v4 feature enabled to streamline unique identifier generation.
• Benchmark Refactoring:
• Switched from criterion::black_box to std::hint::black_box in benchmark code to reduce external dependencies.
• Build Matrix Optimization:
• Cleaned up build.yml by removing the outdated Ubuntu 20.04 runner, focusing on supported platforms.

Bug Fixes

No user-facing bug fixes in this release.

Breaking Changes
• Example Projects: The dependency version bumps in examples/Cargo.toml (tracing 0.1, uuid 1.17) may require example code adjustments if you pin older versions.
• CI Configuration: Removal of the Ubuntu 20.04 runner in the main build matrix may affect users relying on that environment.

Documentation Updates
• Added README.tpl at the project root, consolidating setup, usage, and contribution guidelines.
• Updated project Cargo.toml and CI workflow documentation to reflect the new version and workflow additions.

Migration Notes
• Upgrade Examples: Pull the latest examples/Cargo.toml to get updated tracing and uuid versions. Run cargo update -p tracing --precise 0.1 and cargo update -p uuid --precise 1.17 if needed.
• CI Workflows: Copy or merge the new .github/workflows/semver.yml into your forks to enable semantic versioning checks.
• Benchmarks: If you maintain custom benchmarks, replace any criterion::black_box calls with std::hint::black_box.

Release Links
Full Changelog
Documentation

v0.1.3

30 Mar 19:37
9626a14

Choose a tag to compare

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 a recent simulation conducted on an M4 Max processor, demonstrating the library's capability to handle intensive concurrent trading operations.

Simulation Parameters

  • Price Level: 10000
  • Duration: 5000 ms (5 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 329,558 65,151.94
Matches Executed 147,398 29,139.84
Cancellations 27,119 5,361.29
Total Operations 504,075 99,653.07

Final State After Simulation

  • Price: 10000
  • Visible Quantity: 2,172,773
  • Hidden Quantity: 1,880,104
  • Total Quantity: 4,052,877
  • Order Count: 326,040

Price Level Statistics

  • Orders Added: 330,558
  • Orders Removed: 159
  • Orders Executed: 156,597
  • Quantity Executed: 441,708
  • Value Executed: 4,417,080,000
  • Average Execution Price: 10,000.00
  • Average Waiting Time: 1,236.15 ms
  • Time Since Last Execution: 58 ms

Analysis

The simulation demonstrates the library's capability to handle nearly 100,000 operations per second with multiple concurrent threads operating on the same price level. This includes a mix of order additions, executions, and cancellations - providing a realistic simulation of a high-frequency trading environment.

The lock-free architecture enables high throughput while maintaining data consistency. The minimal difference between orders added (329,558) and the final order count (326,040) indicates efficient order processing with minimal overhead.

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

Setup Instructions

  1. Clone the repository:
git clone https://github.com/joaquinbejar/PriceLevel.git
cd PriceLevel
  1. Build the project:
make build
  1. Run tests:
make test
  1. Format the code:
make fmt
  1. Run linting:
make lint
  1. Clean the project:
make clean
  1. Run the project:
make run
  1. Fix issues:
make fix
  1. Run pre-push checks:
make pre-push
  1. Generate documentation:
make doc
  1. Publish the package:
make publish
  1. Generate coverage report:
make coverage

Library Usage

To use the library in your project, add the following to your Cargo.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:

make test

To run tests with coverage:

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

We appreciate your interest and look forward to your contributions!

License: MIT

v0.1.2

30 Mar 10:11
4da69f2

Choose a tag to compare

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 a recent simulation conducted on an M4 Max processor, demonstrating the library's capability to handle intensive concurrent trading operations.

Simulation Parameters

  • Price Level: 10000
  • Duration: 5000 ms (5 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 329,558 65,151.94
Matches Executed 147,398 29,139.84
Cancellations 27,119 5,361.29
Total Operations 504,075 99,653.07

Final State After Simulation

  • Price: 10000
  • Visible Quantity: 2,172,773
  • Hidden Quantity: 1,880,104
  • Total Quantity: 4,052,877
  • Order Count: 326,040

Price Level Statistics

  • Orders Added: 330,558
  • Orders Removed: 159
  • Orders Executed: 156,597
  • Quantity Executed: 441,708
  • Value Executed: 4,417,080,000
  • Average Execution Price: 10,000.00
  • Average Waiting Time: 1,236.15 ms
  • Time Since Last Execution: 58 ms

Analysis

The simulation demonstrates the library's capability to handle nearly 100,000 operations per second with multiple concurrent threads operating on the same price level. This includes a mix of order additions, executions, and cancellations - providing a realistic simulation of a high-frequency trading environment.

The lock-free architecture enables high throughput while maintaining data consistency. The minimal difference between orders added (329,558) and the final order count (326,040) indicates efficient order processing with minimal overhead.

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

Setup Instructions

  1. Clone the repository:
git clone https://github.com/joaquinbejar/PriceLevel.git
cd PriceLevel
  1. Build the project:
make build
  1. Run tests:
make test
  1. Format the code:
make fmt
  1. Run linting:
make lint
  1. Clean the project:
make clean
  1. Run the project:
make run
  1. Fix issues:
make fix
  1. Run pre-push checks:
make pre-push
  1. Generate documentation:
make doc
  1. Publish the package:
make publish
  1. Generate coverage report:
make coverage

Library Usage

To use the library in your project, add the following to your Cargo.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:

make test

To run tests with coverage:

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

We appreciate your interest and look forward to your contributions!

License: MIT

v0.1.1

29 Mar 20:20

Choose a tag to compare

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 a recent simulation conducted on an M4 Max processor, demonstrating the library's capability to handle intensive concurrent trading operations.

Simulation Parameters

  • Price Level: 10000
  • Duration: 5000 ms (5 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 329,558 65,151.94
Matches Executed 147,398 29,139.84
Cancellations 27,119 5,361.29
Total Operations 504,075 99,653.07

Final State After Simulation

  • Price: 10000
  • Visible Quantity: 2,172,773
  • Hidden Quantity: 1,880,104
  • Total Quantity: 4,052,877
  • Order Count: 326,040

Price Level Statistics

  • Orders Added: 330,558
  • Orders Removed: 159
  • Orders Executed: 156,597
  • Quantity Executed: 441,708
  • Value Executed: 4,417,080,000
  • Average Execution Price: 10,000.00
  • Average Waiting Time: 1,236.15 ms
  • Time Since Last Execution: 58 ms

Analysis

The simulation demonstrates the library's capability to handle nearly 100,000 operations per second with multiple concurrent threads operating on the same price level. This includes a mix of order additions, executions, and cancellations - providing a realistic simulation of a high-frequency trading environment.

The lock-free architecture enables high throughput while maintaining data consistency. The minimal difference between orders added (329,558) and the final order count (326,040) indicates efficient order processing with minimal overhead.

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

Setup Instructions

  1. Clone the repository:
git clone https://github.com/joaquinbejar/PriceLevel.git
cd PriceLevel
  1. Build the project:
make build
  1. Run tests:
make test
  1. Format the code:
make fmt
  1. Run linting:
make lint
  1. Clean the project:
make clean
  1. Run the project:
make run
  1. Fix issues:
make fix
  1. Run pre-push checks:
make pre-push
  1. Generate documentation:
make doc
  1. Publish the package:
make publish
  1. Generate coverage report:
make coverage

Library Usage

To use the library in your project, add the following to your Cargo.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:

make test

To run tests with coverage:

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

We appreciate your interest and look forward to your contributions!

License: MIT