polyfill-rs
A high-performance, drop-in replacement for polymarket-rs-client optimized for high-frequency trading.
Quick Start
Add to your Cargo.toml:
[]
= "0.1.0"
Replace your imports:
// Before: use polymarket_rs_client::{ClobClient, Side, OrderType};
use ;
async
That's it! Your existing code works unchanged, but now runs significantly faster.
Why polyfill-rs?
🔄 100% API Compatible: Drop-in replacement for polymarket-rs-client with identical method signatures
🚀 Performance Optimized: Fixed-point arithmetic and zero-allocation hot paths for HFT environments
📈 Production Ready: Used in live trading environments processing thousands of updates per second
🛠️ Enhanced Features: WebSocket streaming, advanced fill processing, and comprehensive metrics
Distribution & Usage
Crates.io Publication
Once published to crates.io, users can add polyfill-rs to their projects with a simple dependency declaration. Documentation is automatically hosted on docs.rs.
Migration from polymarket-rs-client
See our Migration Guide for detailed instructions. The process is typically:
- Update dependency in
Cargo.toml - Change import statements
- Enjoy improved performance with zero code changes
Usage Patterns
Basic Trading Bot:
use ;
use dec;
let client = with_l2_headers;
// Create and submit order
let order_args = new;
let result = client.create_and_post_order.await?;
High-Frequency Market Making:
use ;
// Real-time order book with fixed-point optimizations
let mut book = new;
let mut stream = new.await?;
// Process thousands of updates per second
while let Some = stream.next.await
How It Works
The library has four main pieces that work together:
Order Book Engine
This is where the magic happens. Instead of using slow decimal math like everyone else, we use fixed-point integers internally:
- Before:
BTreeMap<Decimal, Decimal>(slow decimal operations + allocations) - After:
BTreeMap<u32, i64>(fast integer operations, zero allocations)
The order book can process updates much faster because integer comparisons are fundamentally faster than decimal ones. We only convert back to decimals when you actually need the data.
Want to see how this works? Check out src/book.rs - every optimization has commented-out "before" code so you can see exactly what changed and why.
Trade Execution Simulator
Want to know what would happen if you bought 1000 tokens right now? This simulates walking through the order book levels:
let impact = book.calculate_market_impact;
// Tells you: average price, total cost, market impact percentage
It's smart about slippage protection and won't let you accidentally market-buy at ridiculous prices.
Real-Time Data Streaming
WebSocket connections that don't give up. When the connection drops (and it will), the library automatically reconnects with exponential backoff. No more babysitting your data feeds.
HTTP Client
All the boring stuff like authentication, rate limiting, and retry logic. It just works so you don't have to think about it.
Performance (Benchmarks Coming Soon)
The library is designed around several key optimizations:
Order Book Operations
- Fixed-point math: Integer operations instead of decimal arithmetic
- Zero allocations: Reuse data structures in hot paths
- Efficient lookups: Optimized data structures for common operations
- Batch processing: Handle multiple updates efficiently
Memory Efficiency
- Compact representations: Smaller memory footprint per price level
- Controlled depth: Only track relevant price levels
- Smart cleanup: Remove stale data automatically
Design Philosophy
The core insight is that most trading operations don't need full decimal precision during intermediate calculations. By using fixed-point integers internally and only converting to decimals at the API boundaries, we can:
- Eliminate allocation overhead in hot paths
- Use faster integer arithmetic
- Reduce memory usage significantly
- Maintain full precision where it matters
Learning from the code: The performance optimizations are documented with detailed comments explaining the math, memory layout, and algorithmic choices. It's like a mini-course in high-frequency trading optimization.
Getting Started
[]
= "0.1.0"
Basic Usage
If You're Coming From polymarket-rs-client
Good news: your existing code should work without changes. I kept the same API.
use ;
use Decimal;
// Same initialization as before
let mut client = with_l1_headers;
// Same API calls
let api_creds = client.create_or_derive_api_key.await?;
client.set_api_creds;
// Same order creation
let order_args = new;
let result = client.create_and_post_order.await?;
The difference is that this now runs way faster under the hood.
Real-Time Order Book Tracking
Here's where it gets interesting. You can track live order books for multiple tokens:
use ;
let mut book_manager = new; // Keep top 50 price levels
// This is what happens when you get a WebSocket update
let delta = OrderDelta ;
book_manager.apply_delta?; // This is now super fast
// Get current market state
let book = book_manager.get_book?;
let spread = book.spread; // How tight is the market?
let mid_price = book.mid_price; // Fair value estimate
let best_bid = book.best_bid; // Highest buy price
let best_ask = book.best_ask; // Lowest sell price
The apply_delta call used to be the bottleneck. Now it's basically free.
Market Impact Analysis
Before you place a big order, you probably want to know what it'll cost you:
use FillEngine;
let mut fill_engine = new;
// Simulate buying $1000 worth
let order = MarketOrderRequest ;
let result = fill_engine.execute_market_order?;
println!;
println!;
println!;
println!;
println!;
This tells you exactly what would happen without actually placing the order. Super useful for position sizing.
WebSocket Streaming (The Fun Part)
Here's how you connect to live market data. The library handles all the annoying reconnection stuff:
use ;
let mut stream = new;
// Set up authentication (you'll need API credentials)
let auth = WssAuth ;
stream = stream.with_auth;
// Subscribe to specific markets
stream.subscribe_market_channel.await?;
// Process live updates
while let Some = stream.next.await
The stream automatically reconnects when it drops. You just keep processing messages.
Example: Simple Spread Trading Bot
Here's a basic bot that looks for wide spreads and tries to capture them:
use ;
The key insight: with fast order book updates, you can check hundreds of tokens for opportunities without the library being the bottleneck.
Pro tip: The trading strategy examples in the code include detailed comments about market microstructure, order flow, and risk management techniques.
Configuration Tips
Order Book Depth Settings
The most important performance knob is how many price levels to track:
// For most trading bots: 10-50 levels is plenty
let book_manager = new;
// For market making: maybe 100+ levels
let book_manager = new;
// For analysis/research: could go higher, but memory usage grows
let book_manager = new;
Why this matters: Each price level takes memory, but 90% of trading happens in the top 10 levels anyway. More levels = more memory usage for diminishing returns.
The code comments in src/book.rs explain the memory layout and why we chose these specific data structures for different use cases.
WebSocket Reconnection
The defaults are pretty good, but you can tune them:
let reconnect_config = ReconnectConfig ;
let stream = new
.with_reconnect_config;
Memory Usage
If you're tracking lots of tokens, you might want to clean up stale books:
// Remove books that haven't updated in 5 minutes
let removed = book_manager.cleanup_stale_books?;
println!;
Error Handling (Because Things Break)
The library tries to be helpful about what went wrong:
use PolyfillError;
match book_manager.apply_delta
Most errors tell you whether they're worth retrying or if you should give up.
What's Different From Other Libraries?
Performance
Most trading libraries are built for "demo day" - they work fine for small examples but fall apart under real load. This one is designed for people who actually need to process thousands of updates per second.
Tick Alignment
The library enforces price tick alignment automatically. If someone sends you a price that doesn't align to the market's tick size (like $0.6543 when the tick size is $0.01), it gets rejected. This prevents weird pricing bugs.
The tick alignment code includes detailed comments about why this matters for market integrity and how the integer math makes validation nearly free.
Memory Management
Order books can grow huge if you're not careful. The library automatically trims them to keep only the relevant price levels, and you can clean up stale books that haven't updated recently.