### Install and Run Tests with cargo-nextest Source: https://github.com/floor-licker/polyfill-rs/blob/main/docs/TESTING.md Instructions for installing cargo-nextest and running tests locally. cargo-nextest offers faster test execution and does not run ignored tests by default. ```bash # Install cargo-nextest for faster test execution cargo install cargo-nextest # Run with nextest (ignored tests are not run by default) cargo nextest run --all-features ``` -------------------------------- ### Compile-Check All Examples Source: https://github.com/floor-licker/polyfill-rs/blob/main/docs/TESTING.md Perform a compile-time check on all example code provided within the project. This ensures that all examples are syntactically correct and can be compiled. ```bash cargo build --examples ``` -------------------------------- ### Example: Initialize ClientConfig Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/types.md Shows how to create an instance of `ClientConfig` with essential parameters and default values for other fields. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), api_credentials: Some(ApiCredentials { ... }), ..ClientConfig::default() }; ``` -------------------------------- ### Example: Create OrderArgs Instance Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/types.md Demonstrates creating a new `OrderArgs` instance using the `new` constructor for a buy order. ```rust let order = OrderArgs::new( "123456", Decimal::from_str("0.75").unwrap(), Decimal::from_str("100.0").unwrap(), Side::BUY, ); ``` -------------------------------- ### Example: Convert Qty to Decimal Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/types.md Demonstrates converting a quantity from fixed-point units to a Decimal representation. Assumes `qty_to_decimal` function is available. ```rust let qty_units = 1_000_000; // Represents 100.0 tokens let decimal = qty_to_decimal(qty_units); // Returns Decimal::from_str("100.0") ``` -------------------------------- ### Real-Time Order Book Tracking Example Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-streaming.md Shows how to subscribe to market data, process order book updates, and calculate the mid-price in real-time. ```rust use polyfill_rs::{WebSocketStream, OrderBookManager}; use futures::StreamExt; let mut stream = WebSocketStream::new("wss://ws.polymarket.com/clob"); stream.subscribe_market_channel(vec!["123456".to_string()]).await?; let book_manager = OrderBookManager::new(100); while let Some(result) = stream.next().await { match result { Ok(StreamMessage::Book(book_update)) => { // Apply to order book if let Ok(updated_book) = book_manager.apply_delta(book_update) { if let Some(mid) = updated_book.mid_price() { println!("New mid: ${}", mid); } } } Err(e) => eprintln!("Stream error: {}", e), _ => {} } } ``` -------------------------------- ### Get Order Books for Multiple Tokens Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Fetch order book summaries for multiple tokens identified by their IDs. Use this to get an overview of buy and sell orders for several assets. ```rust pub async fn get_order_books(&self, token_ids: &[String]) -> Result> ``` -------------------------------- ### Live Trading Bot Integration Example Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-utilities.md Demonstrates how to set up a live trading bot using ClobClient, WebSocketStream, and OrderBookManager. Includes pre-warming connections and subscribing to market data. ```rust use polyfill_rs::{ClobClient, WebSocketStream, OrderBookManager}; use futures::StreamExt; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { // Setup let client = ClobClient::new_colocated("https://clob.polymarket.com"); let mut ws_stream = WebSocketStream::new("wss://ws.polymarket.com/clob"); let book_manager = OrderBookManager::new(100); // Pre-warm for low latency client.prewarm_connections().await?; client.start_keepalive(Duration::from_secs(30)).await; // Subscribe to market ws_stream.subscribe_market_channel(vec!["123456".to_string()]).await?; // Trading loop while let Some(result) = ws_stream.next().await { match result { Ok(msg) => { // Process with high-performance methods // Use book_manager and fill_engine for execution } Err(e) => eprintln!("Stream error: {}", e), } } client.stop_keepalive().await; Ok(()) } ``` -------------------------------- ### Subscribe to Market Data via WebSocket Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/INDEX.md Provides an example of establishing a WebSocket connection, subscribing to a market channel, and processing incoming messages. ```rust let mut stream = WebSocketStream::new("wss://ws.polymarket.com/clob") .with_auth(api_credentials); stream.subscribe_market_channel(vec!["123456".to_string()]).await?; while let Some(result) = stream.next().await { match result { Ok(msg) => { /* process message */ } Err(e) if e.is_retryable() => { /* stream reconnects automatically */ } Err(e) => return Err(e), } } ``` -------------------------------- ### Get Contract Configuration for Polygon Mumbai Testnet Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Example of retrieving contract configurations for Polygon Mumbai Testnet (Chain 80002) for both standard and negative risk markets using the `get_contract_config` function. ```rust use polyfill_rs::config::{get_contract_config, ContractConfig}; let config = get_contract_config(80002, false)?; // Mumbai, standard let config_nr = get_contract_config(80002, true)?; // Mumbai, neg risk ``` -------------------------------- ### Get All Markets in Simplified Format Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves all markets in a simplified format. Accepts optional filter parameters. ```rust pub async fn get_simplified_markets(&self, params: Option) -> Result ``` -------------------------------- ### Default Client Configuration Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/INDEX.md Shows how to get the default configuration for the client, including base URL, chain ID, timeout, and connection limits. ```rust ClientConfig::default() // - base_url: "https://clob.polymarket.com" // - chain: 137 (Polygon mainnet) // - timeout: 30 seconds // - max_connections: 100 ``` -------------------------------- ### Configure ClientConfig with Proxy Signature Type Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Example of configuring `ClientConfig` for a Proxy signature type. This requires a funder address. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), signature_type: Some(1), // Proxy funder: Some("0x...funder_address".to_string()), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### Get Network Configuration Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Retrieve specific network configurations like Polygon Mainnet and access its details. It also shows how to get a contract for a specific risk type and retrieve global network information by chain ID. ```rust use polyfill_rs::config::{NetworkConfig, GlobalConfig}; // Get specific network let polygon = NetworkConfig::polygon_mainnet(); println!("Chain ID: {}", polygon.chain_id); println!("RPC URL: {}", polygon.rpc_url); println!("Explorer: {}", polygon.block_explorer); // Get contract for specific risk type if let Some(contract) = polygon.get_contract("standard") { println!("Exchange: {}", contract.exchange); } // Global configuration let config = GlobalConfig::new(); if let Some(network) = config.get_network(137) { println!("Network: {}", network.name); } ``` -------------------------------- ### Configure ClientConfig with Gnosis Safe Signature Type Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Example of configuring `ClientConfig` for a Gnosis Safe signature type. This requires a funder address. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), signature_type: Some(2), // Safe funder: Some("0x...safe_address".to_string()), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### get_sampling_simplified_markets Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Get simplified market data (lighter format) for a sample of markets. ```APIDOC ## get_sampling_simplified_markets ### Description Get simplified market data (lighter format) for a sample of markets. ### Method Not specified (likely GET) ### Endpoint Not specified ### Parameters #### Query Parameters - **params** (Option) - Optional - Filter parameters ### Response #### Success Response - **Result** - Simplified market list ``` -------------------------------- ### create_or_derive_api_key Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Creates a new API key if one does not exist, or returns an existing derived key. This is a convenience method for initial setup. ```APIDOC ## create_or_derive_api_key ### Description Create new API key if not exists, or return existing derived key. Convenience method for bootstrapping. ### Method (Implied async Rust method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **nonce** (Option) - No - Nonce ### Response #### Success Response - **ApiCredentials** - API credentials ### Throws (Not explicitly documented for this method, but implied by Result type) ``` -------------------------------- ### High-Frequency Trading Client Configuration with API Keys Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Set up a client for high-frequency trading, including API credentials, custom timeouts, and a large connection pool size. It also pre-warms connections and starts keep-alive. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some(std::env::var("PRIVATE_KEY")?), api_credentials: Some(ApiCredentials { api_key: std::env::var("API_KEY")?, secret: std::env::var("API_SECRET")?, passphrase: std::env::var("API_PASSPHRASE")?, }), timeout: Some(Duration::from_secs(10)), max_connections: Some(200), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; client.prewarm_connections().await?; client.start_keepalive(Duration::from_secs(15)).await; ``` -------------------------------- ### Get API Keys Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves a list of all API key IDs for the authenticated user. Requires authentication. ```rust pub async fn get_api_keys(&self) -> Result> ``` -------------------------------- ### Configure ClientConfig with EOA Signature Type Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Example of configuring `ClientConfig` for an Externally Owned Account (EOA) signature type. This does not require a funder address. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), signature_type: Some(0), // EOA funder: None, // Not needed for EOA ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### Price Type Conversion Example Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/types.md Demonstrates converting between a `Price` type (u32 representing ticks) and a `Decimal` type. The `Price` type is used for high-performance order book operations. ```rust let price_ticks = 6543; // Represents $0.6543 let decimal = price_to_decimal(price_ticks); // Returns Decimal::from_str("0.6543") ``` -------------------------------- ### Get Sampling Simplified Markets Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Fetch simplified market data in a lighter format for a sample of markets. Filtering can be applied using BookParams. ```rust pub async fn get_sampling_simplified_markets(&self, params: Option) -> Result ``` -------------------------------- ### Start and Stop Keep-Alive Connections Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Initiate background keep-alive for connections to maintain warm connections, reducing first-request latency. Ensure to stop keep-alive when it's no longer needed. ```rust // Start background keep-alive every 30 seconds client.start_keepalive(std::time::Duration::from_secs(30)).await; // Do trading... // Stop keep-alive when done client.stop_keepalive().await; ``` -------------------------------- ### Start ClobClient Keep-Alive Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Initiate a background task to maintain warm connections by sending periodic lightweight requests. This prevents connection drops on idle connections. ```rust use std::time::Duration; client.start_keepalive(Duration::from_secs(30)).await; ``` -------------------------------- ### Get Balance and Allowance Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve balance and allowance information for a specific token. Requires `BalanceAllowanceParams` for account and token details. Returns balance and allowance details. ```rust pub async fn get_balance_allowance( &self, params: BalanceAllowanceParams, ) -> Result ``` -------------------------------- ### Get Historical Prices by Timestamp Range Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Fetch historical price data for an asset within a specified start and end timestamp. This method allows for granular historical data retrieval. Ensure start_ts is less than end_ts. ```rust pub async fn get_prices_history_range( &self, asset_id: &str, start_ts: u64, end_ts: u64, fidelity: Option, ) -> Result ``` -------------------------------- ### Initialize and Use ClobClient Source: https://github.com/floor-licker/polyfill-rs/blob/main/README.md Demonstrates how to initialize the ClobClient and fetch sampling markets. Ensure you replace older polymarket_rs_client imports with polyfill_rs. ```rust use polyfill_rs::{ClobClient, Side, OrderType}; #[tokio::main] async fn main() -> Result<(), Box> { let client = ClobClient::new("https://clob.polymarket.com"); let markets = client.get_sampling_markets(None).await?; println!("Found {} markets", markets.data.len()); Ok(()) } ``` -------------------------------- ### ClobClient::start_keepalive Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Starts a background keep-alive task to maintain warm connections by sending periodic lightweight requests to prevent connection drops. ```APIDOC ## ClobClient::start_keepalive ### Description Start background keep-alive to maintain warm connections. Sends periodic lightweight requests to prevent connection drops. ### Method Rust async function ### Parameters #### Path Parameters - **interval** (Duration) - Required - Interval between keep-alive pings ### Returns - `Future<()>` ### Request Example ```rust use std::time::Duration; client.start_keepalive(Duration::from_secs(30)).await; ``` ``` -------------------------------- ### Get Top N Bids in Fast Format Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-orderbook.md Retrieves the top N bids in a fast fixed-point format. This method avoids Decimal allocations for performance. ```rust pub fn bids_fast(&self, depth: Option) -> Vec let fast_bids = book.bids_fast(Some(10)); for level in fast_bids { let notional = level.notional(); } ``` -------------------------------- ### Get Current A Record for Polymarket API Source: https://github.com/floor-licker/polyfill-rs/blob/main/docs/TESTING.md Query Cloudflare's DNS service to get the current A record for `clob.polymarket.com`. This can be used if local DNS resolution is failing. ```bash curl -sS -H 'accept:application/dns-json' \ 'https://cloudflare-dns.com/dns-query?name=clob.polymarket.com&type=A' ``` -------------------------------- ### Get All Open Orders with Filtering Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve all open orders for the authenticated user, with support for filtering via `OpenOrderParams`. Returns an array of matching open orders. ```rust pub async fn get_orders( &self, params: OpenOrderParams, ) -> Result> ``` -------------------------------- ### Get Best Ask (Fast Fixed-Point) Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-orderbook.md Retrieves the best ask using the internal fixed-point format (Price and Qty) for maximum performance. This method avoids Decimal conversions. ```rust if let Some(level) = book.best_ask_fast() { // level.price is in ticks, level.size in units let notional = level.notional(); // Price * Qty without conversion } ``` -------------------------------- ### Get Best Ask (Decimal) Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-orderbook.md Retrieves the lowest ask price and its quantity in the external Decimal format. Performance is logarithmic due to BTreeMap lookup. ```rust if let Some(level) = book.best_ask() { println!("Best ask: {} @ ${}", level.size, level.price); } ``` -------------------------------- ### Subscribe to User Channel for Orders and Trades Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-streaming.md Subscribes to the authenticated user channel to receive real-time updates on user orders and trades. Requires prior authentication setup using `with_auth()`. ```rust let mut stream = WebSocketStream::new("wss://ws.polymarket.com/clob") .with_auth(api_credentials); stream.subscribe_user_channel(vec![ "0x...condition_id".to_string(), ]).await?; // Receive order and trade updates ``` -------------------------------- ### Get Order Book Summary Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Fetches the current order book (bids and asks) for a specific token. This operation may result in a PolyfillError::Api on 4xx/5xx responses. ```rust pub async fn get_order_book(&self, token_id: &str) -> Result ``` ```rust let book = client.get_order_book("123456").await?; println!("Best bid: {}", book.bids.first().unwrap().price); ``` -------------------------------- ### Side Enum Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/types.md Represents the trading side (BUY or SELL). BUY consumes asks, SELL consumes bids. Use `as_str` to get the string representation and `opposite` to get the inverse side. ```rust pub enum Side { BUY = 0, SELL = 1, } ``` -------------------------------- ### Execute Market Order with FillEngine Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/INDEX.md Initializes a FillEngine and executes a market order. Prints the status, total size filled, and average price of the execution. ```rust let mut engine = FillEngine::new( Decimal::from_str("10.0")?, Decimal::from_str("2.0")?, 25, ); let result = engine.execute_market_order(&order, &book)?; println!("Status: {{:?}}, Filled: {{}}, Avg: {{}}", result.status, result.total_size, result.average_price ); ``` -------------------------------- ### get_rfq_best_quote Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Get the best quote for an RFQ request. ```APIDOC ## get_rfq_best_quote ### Description Get the best quote for an RFQ request. ### Method Not specified (likely GET) ### Endpoint Not specified ### Parameters #### Path Parameters - **request_id** (string) - Required - Request ID ### Response #### Success Response - **Result** - Best quote details ``` -------------------------------- ### Configure Client with Builder Code Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Set up a client configuration including a builder code, which is used for referral programs or market maker fees. This code can be set globally in the configuration. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), builder_code: Some("0x...".to_string()), // Default for all orders ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### get_rfq_requester_quotes Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Get quotes received on your RFQ requests. ```APIDOC ## get_rfq_requester_quotes ### Description Get quotes received on your RFQ requests. ### Method Not specified (likely GET) ### Endpoint Not specified ### Parameters #### Query Parameters - **params** (RfqQuotesParams) - Required - Filter parameters ### Response #### Success Response - **Result** - List of quotes ``` -------------------------------- ### Initialize ClobClient with L1 Headers (Deprecated) Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md This is the old, deprecated method for initializing the ClobClient using L1 headers. It is recommended to use `from_config` with `private_key` instead. ```rust // Old (deprecated): let client = ClobClient::with_l1_headers( "https://clob.polymarket.com", "0x...", 137 ); ``` -------------------------------- ### get_rfq_requests Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Get RFQ requests matching criteria. ```APIDOC ## get_rfq_requests ### Description Get RFQ requests matching criteria. ### Method Not specified (likely GET) ### Endpoint Not specified ### Parameters #### Query Parameters - **params** (RfqRequestsParams) - Required - Filter parameters ### Response #### Success Response - **Result** - List of RFQ requests ``` -------------------------------- ### Minimal Client Configuration (Read-Only) Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Initialize a client with the minimal configuration required for read-only operations, specifying only the base URL. ```rust let client = ClobClient::new("https://clob.polymarket.com"); ``` -------------------------------- ### get_sampling_markets Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Get sampling of active markets (limited result set). ```APIDOC ## get_sampling_markets ### Description Get sampling of active markets (limited result set). ### Method Not specified (likely GET) ### Endpoint Not specified ### Parameters #### Query Parameters - **params** (Option) - Optional - Filter parameters ### Response #### Success Response - **Result** - Sample of markets ### Request Example ```rust let markets = client.get_sampling_markets(None).await?; println!("Found {} markets", markets.data.len()); ``` ``` -------------------------------- ### Get Best Bid (Fast Fixed-Point) Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-orderbook.md Retrieves the best bid using the internal fixed-point format (Price and Qty) to avoid Decimal conversion overhead. Offers optimal performance for price-sensitive operations. ```rust if let Some(level) = book.best_bid_fast() { // level.price is in ticks, level.size in units let notional = level.notional(); // Price * Qty without conversion } ``` -------------------------------- ### get_rfq_quoter_quotes Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Get quotes you've provided to others' RFQ requests. ```APIDOC ## get_rfq_quoter_quotes ### Description Get quotes you've provided to others' RFQ requests. ### Method Not specified (likely GET) ### Endpoint Not specified ### Parameters #### Query Parameters - **params** (RfqQuotesParams) - Required - Filter parameters ### Response #### Success Response - **Result** - List of quotes ``` -------------------------------- ### Create New FillEngine Instance Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-utilities.md Instantiates a new FillEngine. Specify the minimum size for partial fills, the maximum acceptable slippage percentage, and the trading fee in basis points. ```rust use polyfill_rs::FillEngine; use rust_decimal::Decimal; use std::str::FromStr; let engine = FillEngine::new( Decimal::from_str("10.0").unwrap(), // min size Decimal::from_str("2.0").unwrap(), // 2% max slippage 25, // 25 bps = 0.25% fee ); ``` -------------------------------- ### Initialize ClobClient using ClientConfig (Recommended) Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md The recommended way to initialize the ClobClient using a `ClientConfig` struct. This method supports various configuration options like base URL, chain ID, private key, and API credentials. ```rust // New (recommended): let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` ```rust // New (recommended): let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), api_credentials: Some(api_creds), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### Get Builder Fee Rate Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Fetch V2 builder fee rates using a bytes32 builder code. This operation requires authentication and returns maker and taker fee rates in basis points. ```rust pub async fn get_builder_fee_rate(&self, builder_code: &str) -> Result ``` -------------------------------- ### Initialize ClobClient with L2 Headers (Deprecated) Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md This is the old, deprecated method for initializing the ClobClient using L2 headers and API credentials. It is recommended to use `from_config` with `api_credentials` instead. ```rust // Old (deprecated): let client = ClobClient::with_l2_headers( "https://clob.polymarket.com", "0x...", 137, api_creds ); ``` -------------------------------- ### Get Current Unix Timestamp Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-utilities.md Retrieves the current Unix timestamp in milliseconds. ```rust pub fn current_timestamp() -> u64 ``` -------------------------------- ### Get All Active Markets Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves all active markets. Accepts optional filter parameters. ```rust pub async fn get_markets(&self, params: Option) -> Result ``` -------------------------------- ### Create and Post Market Order Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Creates and immediately posts a market order. Use `create_options` for market settings and `post_options` for post-only and defer execution settings. ```rust pub async fn create_and_post_market_order( &self, market_order_args: &MarketOrderArgs, create_options: Option, post_options: Option, ) -> Result ``` -------------------------------- ### Get Token Price by Side Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves the best bid or ask price for a token, specified by the 'side' parameter. Use Side::BUY for the best ask and Side::SELL for the best bid. ```rust pub async fn get_price(&self, token_id: &str, side: Side) -> Result ``` -------------------------------- ### Create ClobClient from Configuration Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Create a ClobClient using a ClientConfig object, supporting authenticated trading with private key signing and API credentials. Ensure private key and funder address are valid to avoid errors. ```rust use polyfill_rs::{ClobClient, ClientConfig}; let client = ClobClient::from_config(ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), api_credentials: Some(api_creds), ..ClientConfig::default() })?; ``` -------------------------------- ### Get Last Trade Price Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves the price data for the most recently executed trade of a specific token. ```rust pub async fn get_last_trade_price(&self, token_id: &str) -> Result ``` -------------------------------- ### Get Token Spread Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Fetches the current spread, defined as the difference between the best ask and best bid for a token. ```rust pub async fn get_spread(&self, token_id: &str) -> Result ``` -------------------------------- ### Set Up Environment Variables for Integration Tests Source: https://github.com/floor-licker/polyfill-rs/blob/main/docs/TESTING.md Configure necessary environment variables for running integration tests that interact with the Polymarket API. This includes private keys, API credentials, and network host configurations. ```bash # Required for ignored real-API tests export POLYMARKET_PRIVATE_KEY="your_private_key_here" # Optional: API credentials (some tests/tools may use these) export POLYMARKET_API_KEY="your_api_key" export POLYMARKET_API_SECRET="your_api_secret" export POLYMARKET_API_PASSPHRASE="your_passphrase" # Backward-compatible aliases also accepted by test helpers export POLYMARKET_SECRET="your_api_secret" export POLYMARKET_PASSPHRASE="your_passphrase" # Optional (defaults provided in test helpers) export POLYMARKET_HOST="https://clob.polymarket.com" export POLYMARKET_CHAIN_ID="137" # Optional, but required when funds live in a Polymarket proxy/Safe wallet. # 0 = EOA, 1 = Proxy, 2 = Gnosis Safe/browser wallet, 3 = Poly1271. export POLYMARKET_SIGNATURE_TYPE="2" # Optional: override the derived funder/proxy wallet address. export POLYMARKET_FUNDER_ADDRESS="0x..." # Optional: pin clob.polymarket.com to a known A record if local DNS is blocked. # Keep the hostname in POLYMARKET_HOST so HTTPS/SNI still validates. export POLYMARKET_RESOLVE_IP="104.18.34.205" ``` -------------------------------- ### Standard Trading Client Configuration Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Configure a client for standard trading operations, including the base URL, chain ID, and private key loaded from an environment variable. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some(std::env::var("PRIVATE_KEY")?), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### Get Token Midpoint Price Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves the midpoint price, which is the average of the best bid and ask for a given token. ```rust pub async fn get_midpoint(&self, token_id: &str) -> Result ``` -------------------------------- ### Create Authenticated Client from Config Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Initializes a ClobClient using a custom ClientConfig, including private key and API credentials for trading operations. ```rust use polyfill_rs::{ClobClient, ClientConfig, ApiCredentials}; let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), api_credentials: Some(ApiCredentials { api_key: "...".to_string(), secret: "...".to_string(), passphrase: "...".to_string(), }), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; // Can now call trading methods let order = OrderArgs::new("123456", Decimal::from_str("0.75").unwrap(), ...); let response = client.create_and_post_order(&order, None, None).await?; ``` -------------------------------- ### Get Stream Statistics Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-streaming.md Retrieves the current connection statistics from a stream. Useful for monitoring stream health and activity. ```rust let stats = stream.get_stats(); println!("Messages received: {}", stats.messages_received); println!("Dropped messages: {}", stats.dropped_messages); println!("Connection uptime: {:?}", stats.connection_uptime); ``` -------------------------------- ### Execute Custom Market Order Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-utilities.md Demonstrates the execution of a custom market order using the ClobClient, OrderBookManager, and FillEngine. Includes setting up the client, order book, and fill engine, then executing a market order and printing the results. ```rust use polyfill_rs::{ ClobClient, OrderBookManager, FillEngine, MarketOrderRequest, Side, }; use rust_decimal::Decimal; use std::str::FromStr; #[tokio::main] async fn main() -> Result<(), Box> { let client = ClobClient::new("https://clob.polymarket.com"); let book_manager = OrderBookManager::new(100); let mut fill_engine = FillEngine::new( Decimal::from_str("5.0")?, Decimal::from_str("1.0")?, 25, ); // Get current order book let book = client.get_order_book("123456").await?; // Create market order let market_order = MarketOrderRequest { token_id: "123456".to_string(), side: Side::BUY, amount: Decimal::from_str("500.0")?, slippage_tolerance: Some(Decimal::from_str("1.0")?), client_id: Some("custom_order_1".to_string()), }; // Execute with fill engine let result = fill_engine.execute_market_order(&market_order, &book)?; println!("Status: {:?}", result.status); println!("Filled: {} @ ${}", result.total_size, result.average_price); println!("Cost: ${} (including ${} fees)", result.total_cost, result.fees); Ok(()) } ``` -------------------------------- ### Create Basic ClobClient Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Instantiate a ClobClient for unauthenticated access with default HTTP/2 settings. Optimized for standard internet connections. ```rust use polyfill_rs::ClobClient; let client = ClobClient::new("https://clob.polymarket.com"); ``` -------------------------------- ### Get Recent Trade Events for a Market Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves recent trade events for a specific market using its condition ID. ```rust pub async fn get_market_trades_events(&self, condition_id: &str) -> Result ``` -------------------------------- ### ClobClient::from_config Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Creates a ClobClient from a configuration object, supporting authenticated trading with private key signing and API credentials. This is a V2-native implementation. ```APIDOC ## ClobClient::from_config ### Description Create a client from a configuration object. Supports authenticated trading with private key signing and API credentials. V2-native implementation. ### Method Rust function ### Parameters #### Path Parameters - **config** (ClientConfig) - Required - Configuration object containing base URL, chain ID, credentials, etc. ### Returns - `Result` - Client instance or error ### Throws - `PolyfillError::Config` if private key is invalid - `PolyfillError::Auth` if funder address is invalid ### Request Example ```rust use polyfill_rs::{ClobClient, ClientConfig}; let client = ClobClient::from_config(ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), api_credentials: Some(api_creds), ..ClientConfig::default() })?; ``` ``` -------------------------------- ### Create or Derive API Key Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Convenience method for bootstrapping. Creates a new API key if one doesn't exist, or returns an existing derived key. ```rust pub async fn create_or_derive_api_key(&self, nonce: Option) -> Result ``` -------------------------------- ### Get RFQ Quoter Quotes Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve a list of quotes that you have provided to other traders' RFQ requests. Use RfqQuotesParams for filtering. ```rust pub async fn get_rfq_quoter_quotes(&self, params: RfqQuotesParams) -> Result ``` -------------------------------- ### Run Unit and Doc Tests Source: https://github.com/floor-licker/polyfill-rs/blob/main/docs/TESTING.md Execute unit tests and documentation tests. Integration tests that require network access are ignored by default. ```bash cargo test --all-features ``` -------------------------------- ### Get RFQ Requester Quotes Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Fetch a list of quotes that have been received on your own RFQ requests. Filtering can be applied using RfqQuotesParams. ```rust pub async fn get_rfq_requester_quotes(&self, params: RfqQuotesParams) -> Result ``` -------------------------------- ### Get Pending Notifications Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve pending notifications for the authenticated user. This method does not require parameters and returns notification data. ```rust pub async fn get_notifications(&self) -> Result ``` -------------------------------- ### Create Internet-Optimized ClobClient Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Instantiate a ClobClient optimized for standard internet connections. This configuration uses larger buffer windows and adaptive HTTP/2 settings. ```rust pub fn new_internet(host: &str) -> Self ``` -------------------------------- ### Create Client with Custom Connection Pooling Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Sets up a ClobClient with a specified maximum number of concurrent HTTP connections, adjusting the connection pool size. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, max_connections: Some(50), // Max 50 concurrent connections ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### Get ClobClient Exchange Address Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve the contract address for the exchange on the configured chain. Returns None if the chain is not supported. ```rust pub fn get_exchange_address(&self) -> Option ``` -------------------------------- ### Pre-warm WebSocket Connections Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/INDEX.md Demonstrates how to pre-warm WebSocket connections to reduce latency for subsequent operations. ```rust client.prewarm_connections().await? ``` -------------------------------- ### get_ok Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Tests basic connectivity to the API server. Returns true if the server responds with a success status. ```APIDOC ## get_ok ### Description Tests basic connectivity to the API server. ### Method GET (assumed) ### Endpoint /ok (assumed) ### Parameters None ### Response #### Success Response (200) - **true** (bool) - Indicates server is healthy ### Response Example ```json true ``` ``` -------------------------------- ### Get ClobClient Conditional Address Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve the contract address for the conditional tokens on the configured chain. Returns None if the chain is not supported. ```rust pub fn get_conditional_address(&self) -> Option ``` -------------------------------- ### Get ClobClient Collateral Address Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve the contract address for the collateral token on the configured chain. Returns None if the chain is not supported. ```rust pub fn get_collateral_address(&self) -> Option ``` -------------------------------- ### Get Spread in Ticks Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-orderbook.md Retrieves the spread in fast fixed-point format (ticks). Useful for performance-sensitive applications where tick-based comparisons are sufficient. ```rust pub fn spread_fast(&self) -> Option if let Some(spread_ticks) = book.spread_fast() { if spread_ticks > 50 { println!("Wide spread: {} ticks", spread_ticks); } } ``` -------------------------------- ### config constructor Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/errors.md Creates a configuration error. ```APIDOC ## config Creates a Config error. ### Arguments - `message` (impl Into): A message describing the error. ### Returns - `Self`: A new `PolyfillError` instance of type Config. ### Example ```rust Err(PolyfillError::config("Invalid base_url")) ``` ``` -------------------------------- ### Create Authenticated ClobClient for Trading Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/INDEX.md Sets up an authenticated ClobClient using a ClientConfig that includes private keys and API credentials. This client is required for trading operations like creating and posting orders. ```rust use polyfill_rs::{ClobClient, ClientConfig, OrderArgs, Side}; use rust_decimal::Decimal; use std::str::FromStr; let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some("0x...".to_string()), api_credentials: Some(api_creds), ..Default::default() }; let client = ClobClient::from_config(config)?; let order = OrderArgs::new( "123456", Decimal::from_str("0.75")?, Decimal::from_str("100.0")?, Side::BUY, ); let response = client.create_and_post_order(&order, None, None).await?; ``` -------------------------------- ### Get Spread Percentage Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-orderbook.md Retrieves the spread as a percentage relative to the bid price. Use this to check if the spread is wider than a certain threshold. ```rust pub fn spread_pct(&self) -> Option if let Some(spread) = book.spread_pct() { if spread > Decimal::from_str("0.01")? { println!("Wide spread: {}%", spread); } } ``` -------------------------------- ### Testnet Trading Client Configuration Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Configure a client for trading on a testnet, specifying the Mumbai testnet chain ID and loading the private key from an environment variable. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 80002, // Mumbai testnet private_key: Some(std::env::var("TEST_PRIVATE_KEY")?), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### ClobClient::new Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Creates a basic unauthenticated ClobClient with default HTTP/2 settings, optimized for standard internet connections. ```APIDOC ## ClobClient::new ### Description Creates a basic unauthenticated client with default HTTP/2 settings. Optimized for standard internet connections with 11.4% performance improvement over standard HTTP clients. ### Method Rust function ### Parameters #### Path Parameters - **host** (string) - Required - Base URL (e.g., "https://clob.polymarket.com") ### Returns - `ClobClient` instance ### Request Example ```rust use polyfill_rs::ClobClient; let client = ClobClient::new("https://clob.polymarket.com"); ``` ``` -------------------------------- ### network constructor Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/errors.md Creates a network error with optional source context. ```APIDOC ## network Creates a Network error with source context. ### Arguments - `message` (impl Into): A message describing the error. - `source` (E: Error + Send + Sync + 'static): The underlying error source. ### Returns - `Self`: A new `PolyfillError` instance of type Network. ### Example ```rust PolyfillError::network("Failed to connect", e) ``` ``` -------------------------------- ### Get Sampling Markets Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve a sample of active markets. This function returns a limited result set and can optionally be filtered using BookParams. ```rust pub async fn get_sampling_markets(&self, params: Option) -> Result ``` ```rust let markets = client.get_sampling_markets(None).await?; println!("Found {} markets", markets.data.len()); ``` -------------------------------- ### Configure ClobClient with Safe Wallet Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Sets up the ClientConfig for a Safe wallet, requiring the SAFE_OWNER_KEY and SAFE_ADDRESS environment variables. The signature_type is set to 2 for Safe wallets. ```rust let config = ClientConfig { base_url: "https://clob.polymarket.com".to_string(), chain: 137, private_key: Some(std::env::var("SAFE_OWNER_KEY")?), signature_type: Some(2), // Safe funder: Some(std::env::var("SAFE_ADDRESS")?), ..ClientConfig::default() }; let client = ClobClient::from_config(config)?; ``` -------------------------------- ### Get RFQ Requests Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve a list of RFQ requests that match the specified filter parameters. The parameters are encapsulated within the RfqRequestsParams struct. ```rust pub async fn get_rfq_requests(&self, params: RfqRequestsParams) -> Result ``` -------------------------------- ### Get Server Timestamp Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves the current server timestamp in milliseconds. This function may throw a PolyfillError::Parse if the response format is invalid. ```rust pub async fn get_server_time(&self) -> Result ``` -------------------------------- ### Create and Post Limit Order Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Creates and immediately posts a limit order in a single call. Use `create_options` for tick size and neg_risk, and `post_options` for post-only and defer execution settings. ```rust pub async fn create_and_post_order( &self, order_args: &OrderArgs, create_options: Option, post_options: Option, ) -> Result ``` -------------------------------- ### Create Market Order Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Creates a market order with slippage protection and signs it. Use `create_options` for tick size and neg_risk, and `post_options` for order type and defer execution settings. ```rust pub async fn create_market_order( &self, market_order_args: &MarketOrderArgs, create_options: Option, post_options: Option, ) -> Result ``` -------------------------------- ### Create Custom HTTP Client Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/configuration.md Build a custom HTTP client with specific configurations for timeouts and connection pooling. Note that the public API does not expose the internal client builder directly. ```rust use reqwest::Client; // Create custom HTTP client let http_client = reqwest::ClientBuilder::new() .timeout(std::time::Duration::from_secs(60)) .pool_max_idle_per_host(50) .build()?; // Note: The public API doesn't expose internal client builder, // so use ClientConfig::from_config() with appropriate settings ``` -------------------------------- ### Get Detailed Market Information Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves detailed information for a specific market using its condition ID. The condition ID must be a hex string. ```rust pub async fn get_market(&self, condition_id: &str) -> Result ``` -------------------------------- ### Run Simple Authentication Smoke Test Source: https://github.com/floor-licker/polyfill-rs/blob/main/docs/TESTING.md Execute a basic integration test designed to verify authentication with the Polymarket API. This test requires valid API credentials and is ignored by default. ```bash cargo test --all-features --test simple_auth_test -- --ignored --nocapture --test-threads=1 ``` -------------------------------- ### FillEngine::new Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-utilities.md Creates a new instance of the FillEngine, which is responsible for executing market orders with slippage protection. It requires parameters for minimum fill size, maximum slippage percentage, and trading fee rate in basis points. ```APIDOC ## FillEngine::new ### Description Create a new fill engine. ### Method `FillEngine::new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **min_fill_size** (Decimal) - Required - Min size for partial fills (e.g., "10.0") - **max_slippage_pct** (Decimal) - Required - Max slippage % (e.g., "2.0" for 2%) - **fee_rate_bps** (u32) - Required - Fee rate in bps (e.g., 25 for 0.25%) ### Returns FillEngine instance ### Example ```rust use polyfill_rs::FillEngine; use rust_decimal::Decimal; use std::str::FromStr; let engine = FillEngine::new( Decimal::from_str("10.0").unwrap(), // min size Decimal::from_str("2.0").unwrap(), // 2% max slippage 25, // 25 bps = 0.25% fee ); ``` ``` -------------------------------- ### Get RFQ Best Quote Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve the details of the best quote submitted for a specific RFQ request. The request ID is required to identify the RFQ. ```rust pub async fn get_rfq_best_quote(&self, request_id: &str) -> Result ``` -------------------------------- ### Get Single Order Details Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieve detailed information for a specific order using its ID. Returns order details including status and fills. ```rust pub async fn get_order(&self, order_id: &str) -> Result ``` -------------------------------- ### Get Token Tick Size Source: https://github.com/floor-licker/polyfill-rs/blob/main/_autodocs/api-reference-client.md Retrieves the minimum price increment (tick size) for a given token. This indicates the smallest valid price change. ```rust pub async fn get_tick_size(&self, token_id: &str) -> Result ``` -------------------------------- ### Enable Trace Logging for Tests Source: https://github.com/floor-licker/polyfill-rs/blob/main/docs/TESTING.md Run all tests with trace logging enabled for maximum detail. This provides the most verbose output for debugging. ```bash RUST_LOG=trace cargo test --all-features --test integration_tests -- --ignored --nocapture --test-threads=1 ```