### Run project examples Source: https://github.com/augustin-v/polysqueeze/blob/main/CONTRIBUTING.md Executes specific project examples. ```bash cargo run --example order cargo run --example wss_market ``` -------------------------------- ### Run order placement example Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Executes the order placement example script using cargo. ```bash cargo run --example order ``` -------------------------------- ### Run market data subscription example Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Executes the market data streaming example script. ```bash cargo run --example wss_market ``` -------------------------------- ### GET /markets Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Retrieves a list of markets based on optional filtering parameters. ```APIDOC ## GET /markets ### Description Retrieves a list of markets with optional filtering for liquidity, volume, and other metadata. ### Method GET ### Endpoint /markets ### Parameters #### Query Parameters - **limit** (Option) - Optional - Maximum number of markets to return - **closed** (Option) - Optional - Include or exclude closed markets - **liquidity_num_min** (Option) - Optional - Minimum liquidity threshold - **liquidity_num_max** (Option) - Optional - Maximum liquidity threshold - **volume_num_min** (Option) - Optional - Minimum trading volume threshold - **volume_num_max** (Option) - Optional - Maximum trading volume threshold - **cyom** (Option) - Optional - Include create-your-own markets (CYOM) - **include_tag** (Option) - Optional - Include tag metadata in response - **tag** (Option) - Optional - Filter by specific tag - **related** (Option) - Optional - Include related markets - **archived** (Option) - Optional - Include archived markets - **order_by** (Option) - Optional - Sort field (e.g., "volume", "liquidity", "created_date") - **order_dir** (Option) - Optional - Sort direction ("asc" or "desc") - **currency** (Option) - Optional - Currency for pricing (default: "USD") - **maker_fee** (Option) - Optional - Maker fee filter - **taker_fee** (Option) - Optional - Taker fee filter - **pfm** (Option) - Optional - Profit/fee mode - **search** (Option) - Optional - Free text search across markets ``` -------------------------------- ### Initialize ClobClient and Post Order Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Initializes ClobClient with L1 and L2 headers, derives API keys, filters markets using GammaListParams, and posts a sample order. Requires POLY_PRIVATE_KEY environment variable and a valid token ID. ```rust use polysqueeze::{types::GammaListParams, ClobClient, OrderArgs, OrderType, Side}; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let base_url = "https://clob.polymarket.com"; let private_key = std::env::var("POLY_PRIVATE_KEY")?; let l1_client = ClobClient::with_l1_headers(base_url, &private_key, 137); let creds = l1_client.create_or_derive_api_key(None).await?; let mut client = ClobClient::with_l2_headers(base_url, &private_key, 137, creds.clone()); // Filter markets with various criteria let gamma_params = GammaListParams { limit: Some(10), closed: Some(false), // Exclude closed markets liquidity_num_min: Some(Decimal::from(1000)), // Min liquidity liquidity_num_max: Some(Decimal::from(1000000)), // Max liquidity volume_num_min: Some(Decimal::from(10000)), // Min volume cyom: Some(false), // Exclude create-your-own markets include_tag: Some(true), // Include tag data ..Default::default() }; let market_data = client.get_markets(None, Some(&gamma_params)).await?; println!("{} markets fetched", market_data.data.len()); // Replace with a real CLOB token id (see `market_data` or use `.env.example` + examples). let token_id = "token-id-here"; let order_args = OrderArgs::new( token_id, Decimal::new(5000, 4), Decimal::new(1, 0), Side::BUY, ); let signed_order = client.create_order(&order_args, None, None, None).await?; client.post_order(signed_order, OrderType::GTC).await?; Ok(()) } ``` -------------------------------- ### Query Gamma API endpoints Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Demonstrates initializing GammaClient and fetching markets, events, and tags. ```rust use polysqueeze::api::GammaClient; #[tokio::main] async fn main() -> Result<(), Box> { let gamma_client = GammaClient::new(); // Fetch markets let markets = gamma_client.get_markets(None, None).await?; println!("Markets: {:?}", markets); // Fetch events let events = gamma_client.get_events(None).await?; println!("Events: {:?}", events); // Fetch tags let tags = gamma_client.get_tags().await?; println!("Tags: {:?}", tags); Ok(()) } ``` -------------------------------- ### Initialize environment variables Source: https://github.com/augustin-v/polysqueeze/blob/main/CONTRIBUTING.md Copies the template environment file to a local .env file. ```bash cp .env.example .env ``` -------------------------------- ### Run live order placement test Source: https://github.com/augustin-v/polysqueeze/blob/main/CONTRIBUTING.md Executes the order placement test; requires appropriate environment variables to be set. ```bash RUN_PLACE_ORDER_TEST=1 cargo test place_order -- --nocapture ``` -------------------------------- ### Create Authenticated ClobClient Source: https://context7.com/augustin-v/polysqueeze/llms.txt Demonstrates creating a ClobClient with L1 and L2 authentication. Requires POLY_PRIVATE_KEY environment variable. Handles API key creation and derivation. ```rust use polysqueeze::{ClobClient, OrderArgs, OrderType, Side}; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let base_url = "https://clob.polymarket.com"; let private_key = std::env::var("POLY_PRIVATE_KEY")?; let chain_id = 137; // Polygon mainnet // Step 1: Create L1 client for authentication let l1_client = ClobClient::with_l1_headers(base_url, &private_key, chain_id); // Step 2: Derive or create API credentials let creds = l1_client.create_or_derive_api_key(None).await?; println!("API Key: {}", creds.api_key); // Step 3: Create L2 client for authenticated trading let client = ClobClient::with_l2_headers(base_url, &private_key, chain_id, creds); // Verify connectivity let server_time = client.get_server_time().await?; println!("Server time: {}", server_time); Ok(()) } ``` -------------------------------- ### Create and Post a Single Order Source: https://context7.com/augustin-v/polysqueeze/llms.txt Use `create_order` to generate a signed order and `post_order` to submit it. The SDK automatically handles EIP-712 signature generation, tick size validation, and neg-risk detection. ```rust use polysqueeze::{ClobClient, OrderArgs, OrderType, Side, types::GammaListParams}; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let private_key = std::env::var("POLY_PRIVATE_KEY")?; // Create authenticated client let l1_client = ClobClient::with_l1_headers( "https://clob.polymarket.com", &private_key, 137 ); let creds = l1_client.create_or_derive_api_key(None).await?; let client = ClobClient::with_l2_headers( "https://clob.polymarket.com", &private_key, 137, creds ); // Find a liquid market let params = GammaListParams { limit: Some(5), liquidity_num_min: Some(Decimal::from(100_000)), ..Default::default() }; let markets = client.get_markets(None, Some(¶ms)).await?; let market = markets.data.first().expect("No markets found"); let token_id = market.clob_token_ids.first().expect("No token ID"); // Get current order book to determine price let book = client.get_order_book(token_id).await?; let best_bid = book.bids.first().map(|l| l.price).unwrap_or(Decimal::ZERO); let best_ask = book.asks.first().map(|l| l.price).unwrap_or(Decimal::ONE); let mid_price = (best_bid + best_ask) / Decimal::from(2); // Create order arguments let order_args = OrderArgs::new( token_id, mid_price, // price Decimal::from(5), // size (number of contracts) Side::BUY ); // Sign the order (SDK fetches tick_size and neg_risk automatically) let signed_order = client.create_order(&order_args, None, None, None).await?; // Submit the order (GTC = Good Till Cancelled) let response = client.post_order(signed_order, OrderType::GTC).await?; let order_id = response["orderID"].as_str().unwrap_or("unknown"); println!("Order placed: {}", order_id); Ok(()) } ``` -------------------------------- ### Format project code Source: https://github.com/augustin-v/polysqueeze/blob/main/CONTRIBUTING.md Applies standard Rust formatting to all files. ```bash cargo fmt --all ``` -------------------------------- ### Run project tests Source: https://github.com/augustin-v/polysqueeze/blob/main/CONTRIBUTING.md Executes all tests in the project. ```bash cargo test --all ``` -------------------------------- ### Simplified ClobClient Creation with new_with_auth Source: https://context7.com/augustin-v/polysqueeze/llms.txt Provides a simplified method for creating an authenticated ClobClient in a single call. Automatically derives API credentials. Optionally accepts a funder address. ```rust use polysqueeze::ClobClient; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let private_key = std::env::var("POLY_PRIVATE_KEY")?; let funder_address = std::env::var("POLY_FUNDER").ok(); // Single call to create authenticated client let client = ClobClient::new_with_auth( &private_key, funder_address.as_deref() ).await?; // Client is ready for trading let is_connected = client.get_ok().await; println!("Connected: {}", is_connected); Ok(()) } ``` -------------------------------- ### Market Discovery with GammaClient Source: https://context7.com/augustin-v/polysqueeze/llms.txt Perform unauthenticated queries for markets, events, and tags using GammaClient. ```rust use polysqueeze::api::GammaClient; use polysqueeze::types::GammaListParams; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let gamma = GammaClient::new(); // Fetch markets with filters let params = GammaListParams { limit: Some(20), closed: Some(false), liquidity_num_min: Some(Decimal::from(50_000)), ..Default::default() }; let markets = gamma.get_markets(None, Some(¶ms)).await?; println!("Found {} markets", markets.data.len()); // Fetch all events let events = gamma.get_events(None).await?; for event in &events { println!("Event: {} ({})", event.slug, event.id); } // Fetch event by slug let event = gamma.get_event_by_slug("presidential-election-2024").await?; println!("Event: {:?}", event.name); // Fetch event by ID let event = gamma.get_event_by_id("12345").await?; println!("Event markets: {:?}", event.markets.len()); // Fetch available tags for filtering let tags = gamma.get_tags().await?; for tag in &tags { println!("Tag: {} ({})", tag.name, tag.id); } // Fetch sports metadata let sports = gamma.get_sports().await?; println!("Available sports: {:?}", sports); Ok(()) } ``` -------------------------------- ### Enable Other Live Tests Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Opt-in to other live tests by setting specific environment variables. These tests cover authentication, Gamma live endpoints, and data API functionalities. ```bash RUN_AUTH_TEST=1 ``` ```bash RUN_GAMMA_TESTS=1 ``` ```bash RUN_DATA_API_TESTS=1 ``` -------------------------------- ### Perform Batch Market Data Queries Source: https://context7.com/augustin-v/polysqueeze/llms.txt Executes bulk requests for multiple tokens to improve performance when monitoring several markets simultaneously. ```rust use polysqueeze::{ClobClient, Side, types::BookParams}; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let client = ClobClient::new("https://clob.polymarket.com"); let token_ids = vec![ "token-id-1".to_string(), "token-id-2".to_string(), "token-id-3".to_string(), ]; // Batch order books let books = client.get_order_books(&token_ids).await?; for book in &books { println!("{}: {} bids, {} asks", book.asset_id, book.bids.len(), book.asks.len()); } // Batch midpoints let midpoints = client.get_midpoints(&token_ids).await?; for (token_id, mid) in &midpoints { println!("{}: midpoint = {}", token_id, mid); } // Batch spreads let spreads = client.get_spreads(&token_ids).await?; for (token_id, spread) in &spreads { println!("{}: spread = {}", token_id, spread); } // Batch prices (specify side for each token) let book_params: Vec = token_ids.iter().map(|id| BookParams { token_id: id.clone(), side: Side::BUY, }).collect(); let prices = client.get_prices(&book_params).await?; println!("Prices: {:?}", prices); // Batch last trade prices let last_trades = client.get_last_trade_prices(&token_ids).await?; println!("Last trades: {:?}", last_trades); Ok(()) } ``` -------------------------------- ### Query Wallet Positions with DataApiClient Source: https://context7.com/augustin-v/polysqueeze/llms.txt Use DataApiClient to fetch a wallet's total position value and detailed holdings. Requires no authentication. ```rust use polysqueeze::DataApiClient; use polysqueeze::types::{DataApiPositionsParams, DataApiSortBy, DataApiSortDirection}; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let data_client = DataApiClient::new(); let wallet_address = "0x1234..."; // Get total positions value let value = data_client.get_total_positions_value(wallet_address).await?; for entry in &value { println!("User {} total value: {}", entry.user, entry.value); } // Get detailed positions let params = DataApiPositionsParams { size_threshold: Some(1), limit: Some(100), sort_by: Some(DataApiSortBy::Current), sort_direction: Some(DataApiSortDirection::Desc), }; let positions = data_client.get_positions(wallet_address, Some(params)).await?; for pos in &positions { println!("Position: {} @ {}", pos.title.as_deref().unwrap_or("Unknown"), pos.cur_price); println!(" Size: {}, Avg Price: {}", pos.size, pos.avg_price); println!(" Current Value: {}, P&L: {} ({}%)", pos.current_value, pos.cash_pnl, pos.percent_pnl); } Ok(()) } ``` -------------------------------- ### Managing Balances and Allowances Source: https://context7.com/augustin-v/polysqueeze/llms.txt Check account balances and token allowances. Use update_balance_allowance to refresh cached values. ```rust use polysqueeze::{ClobClient, types::{BalanceAllowanceParams, AssetType}}; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let private_key = std::env::var("POLY_PRIVATE_KEY")?; let client = ClobClient::new_with_auth(&private_key, None).await?; // Get all balances and allowances let balance_info = client.get_balance_allowance(None).await?; println!("Balance info: {:?}", balance_info); // Get balance for specific asset type let params = BalanceAllowanceParams { asset_type: Some(AssetType::COLLATERAL), token_id: None, signature_type: None, }; let collateral = client.get_balance_allowance(Some(params)).await?; println!("Collateral balance: {:?}", collateral); // Get balance for specific token let params = BalanceAllowanceParams { asset_type: Some(AssetType::CONDITIONAL), token_id: Some("token-id".to_string()), signature_type: None, }; let token_balance = client.get_balance_allowance(Some(params)).await?; println!("Token balance: {:?}", token_balance); // Update balance allowance (refresh cached values) let updated = client.update_balance_allowance(None).await?; println!("Updated balance: {:?}", updated); Ok(()) } ``` -------------------------------- ### Stream authenticated user events with WssUserClient Source: https://context7.com/augustin-v/polysqueeze/llms.txt Uses WssUserClient to subscribe to order and trade updates for specific markets. Requires valid API credentials and an active event loop to process incoming messages. ```rust use polysqueeze::{ClobClient, OrderArgs, OrderType, Side}; use polysqueeze::wss::{WssUserClient, WssUserEvent}; use polysqueeze::types::GammaListParams; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let private_key = std::env::var("POLY_PRIVATE_KEY")?; // Authenticate and get credentials let l1_client = ClobClient::with_l1_headers( "https://clob.polymarket.com", &private_key, 137 ); let creds = l1_client.create_or_derive_api_key(None).await?; let l2_client = ClobClient::with_l2_headers( "https://clob.polymarket.com", &private_key, 137, creds.clone() ); // Find liquid markets let params = GammaListParams { limit: Some(5), liquidity_num_min: Some(Decimal::from(1_000_000)), ..Default::default() }; let markets = l2_client.get_markets(None, Some(¶ms)).await?; // Get market IDs (condition IDs) for subscription let market_ids: Vec = markets.data .iter() .map(|m| m.condition_id.clone()) .filter(|id| !id.is_empty()) .take(3) .collect(); // Create authenticated user channel client let mut user_client = WssUserClient::new(creds.clone()); user_client.subscribe(market_ids.clone()).await?; println!("Subscribed to user events for markets: {:?}", market_ids); // Place an order to generate events let market = &markets.data[0]; let token_id = market.clob_token_ids.first().unwrap(); let book = l2_client.get_order_book(token_id).await?; let far_price = book.bids.first().map(|l| l.price - Decimal::new(5, 2)) .unwrap_or(Decimal::new(10, 2)); let order_args = OrderArgs::new(token_id, far_price, Decimal::from(5), Side::BUY); let signed = l2_client.create_order(&order_args, None, None, None).await?; let response = l2_client.post_order(signed, OrderType::GTC).await?; let order_id = response["orderID"].as_str().unwrap_or("unknown"); println!("Placed order: {}", order_id); // Listen for order/trade events loop { match user_client.next_event().await { Ok(WssUserEvent::Order(order)) => { println!("Order event: {} {} {} @ {} (matched: {})", order.id, order.message_type, order.side.as_str(), order.price, order.size_matched ); if order.message_type.eq_ignore_ascii_case("CANCELLATION") { println!("Order cancelled, exiting"); break; } } Ok(WssUserEvent::Trade(trade)) => { println!("Trade event: {} {} {}@{} status={}", trade.id, trade.side.as_str(), trade.size, trade.price, trade.status ); } Err(e) => { eprintln!("User stream error: {}", e); break; } } } Ok(()) } ``` -------------------------------- ### Run project lints Source: https://github.com/augustin-v/polysqueeze/blob/main/CONTRIBUTING.md Runs clippy lints with warnings treated as errors. ```bash cargo clippy --all-targets --all-features -- -D warnings ``` -------------------------------- ### Stream Market Events with WssMarketClient Source: https://context7.com/augustin-v/polysqueeze/llms.txt Connect to the WebSocket market channel to receive real-time order book updates, price changes, and trades. Requires initial market discovery. ```rust use polysqueeze::wss::{WssMarketClient, WssMarketEvent}; use polysqueeze::ClobClient; use polysqueeze::types::GammaListParams; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { // First, find markets to subscribe to let clob = ClobClient::new("https://clob.polymarket.com"); let params = GammaListParams { limit: Some(5), liquidity_num_min: Some(Decimal::from(1_000_000)), ..Default::default() }; let markets = clob.get_markets(None, Some(¶ms)).await?; // Get asset IDs (token IDs) for subscription let asset_ids: Vec = markets.data .iter() .flat_map(|m| m.clob_token_ids.clone()) .take(5) .collect(); // Create and subscribe to market channel let mut wss_client = WssMarketClient::new(); wss_client.subscribe(asset_ids.clone()).await?; println!("Subscribed to assets: {:?}", asset_ids); // Process incoming events loop { match wss_client.next_event().await { Ok(WssMarketEvent::Book(book)) => { println!("Book update for {}: {} bids, {} asks", book.asset_id, book.bids.len(), book.asks.len()); } Ok(WssMarketEvent::PriceChange(change)) => { for entry in &change.price_changes { println!("Price change: {} {} @ {} (bid: {}, ask: {})", entry.asset_id, entry.side.as_str(), entry.price, entry.best_bid, entry.best_ask ); } } Ok(WssMarketEvent::TickSizeChange(change)) => { println!("Tick size changed for {}: {} -> {}", change.asset_id, change.old_tick_size, change.new_tick_size); } Ok(WssMarketEvent::LastTrade(trade)) => { println!("Trade: {} {} {}@{}", trade.asset_id, trade.side.as_str(), trade.size, trade.price ); } Err(e) => { eprintln!("Stream error: {}", e); break; } } } Ok(()) } ``` -------------------------------- ### Querying Orders and Trades with ClobClient Source: https://context7.com/augustin-v/polysqueeze/llms.txt Retrieve open orders and trade history using the authenticated ClobClient. Supports filtering by market and time range. ```rust use polysqueeze::{ClobClient, types::{OpenOrderParams, TradeParams}}; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let private_key = std::env::var("POLY_PRIVATE_KEY")?; let client = ClobClient::new_with_auth(&private_key, None).await?; // Get all open orders let orders = client.get_orders(None, None).await?; for order in &orders { println!("Order {}: {} {} @ {} (matched: {})", order.id, order.side.as_str(), order.original_size, order.price, order.size_matched ); } // Get orders filtered by market let params = OpenOrderParams { market: Some("condition-id".to_string()), asset_id: None, id: None, }; let market_orders = client.get_orders(Some(¶ms), None).await?; println!("Orders in market: {}", market_orders.len()); // Get a specific order by ID let order_id = "specific-order-id"; let order = client.get_order(order_id).await?; println!("Order status: {}", order.status); // Get trade history let trades = client.get_trades(None, None).await?; println!("Trade history: {:?}", trades); // Get trades filtered by time range let trade_params = TradeParams { after: Some(1700000000), // Unix timestamp before: None, market: None, asset_id: None, maker_address: None, id: None, }; let recent_trades = client.get_trades(Some(&trade_params), None).await?; println!("Recent trades: {:?}", recent_trades); Ok(()) } ``` -------------------------------- ### Create a new git branch Source: https://github.com/augustin-v/polysqueeze/blob/main/CONTRIBUTING.md Use this command to create and switch to a new feature branch. ```bash git checkout -b feat/short-description ``` -------------------------------- ### Submit Multiple Orders in Batch Source: https://context7.com/augustin-v/polysqueeze/llms.txt Use `post_orders` to submit multiple signed orders in a single request for improved efficiency. This method is suitable for placing several orders simultaneously. ```rust use polysqueeze::{ClobClient, OrderArgs, OrderType, Side}; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let private_key = std::env::var("POLY_PRIVATE_KEY")?; let client = ClobClient::new_with_auth(&private_key, None).await?; let token_id = "your-token-id-here"; // Create multiple orders at different price levels let orders = vec![ OrderArgs::new(token_id, Decimal::new(50, 2), Decimal::from(10), Side::BUY), // 0.50 OrderArgs::new(token_id, Decimal::new(48, 2), Decimal::from(15), Side::BUY), // 0.48 OrderArgs::new(token_id, Decimal::new(46, 2), Decimal::from(20), Side::BUY), // 0.46 ]; // Sign all orders let mut signed_orders = Vec::new(); for args in &orders { let signed = client.create_order(args, None, None, None).await?; signed_orders.push(signed); } // Submit batch let results = client.post_orders(signed_orders, OrderType::GTC).await?; for (i, result) in results.iter().enumerate() { if result.success { println!("Order {}: placed successfully (ID: {:?})", i, result.order_id); } else { println!("Order {}: failed - {:?}", i, result.error_msg); } } Ok(()) } ``` -------------------------------- ### Format Code with Cargo Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Format your Rust code using the cargo fmt command. This ensures consistent code style across the project. ```bash cargo fmt ``` -------------------------------- ### Retrieve Market Data Source: https://context7.com/augustin-v/polysqueeze/llms.txt Fetches individual market metrics such as order books, midpoints, spreads, and last trade prices for a specific token. ```rust use polysqueeze::{ClobClient, Side}; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let client = ClobClient::new("https://clob.polymarket.com"); let token_id = "your-token-id-here"; // Get full order book let book = client.get_order_book(token_id).await?; println!("Order book for {}", book.asset_id); println!("Bids:"); for level in &book.bids { println!(" {} @ {}", level.size, level.price); } println!("Asks:"); for level in &book.asks { println!(" {} @ {}", level.size, level.price); } // Get midpoint price let midpoint = client.get_midpoint(token_id).await?; println!("Midpoint: {}", midpoint.mid); // Get bid-ask spread let spread = client.get_spread(token_id).await?; println!("Spread: {}", spread.spread); // Get best price for a specific side let buy_price = client.get_price(token_id, Side::BUY).await?; let sell_price = client.get_price(token_id, Side::SELL).await?; println!("Best buy: {}, Best sell: {}", buy_price.price, sell_price.price); // Get last trade price let last_trade = client.get_last_trade_price(token_id).await?; println!("Last trade: {:?}", last_trade); // Get tick size for a token let tick_size = client.get_tick_size(token_id).await?; println!("Tick size: {}", tick_size); Ok(()) } ``` -------------------------------- ### Handle SDK errors with PolyError Source: https://context7.com/augustin-v/polysqueeze/llms.txt Demonstrates matching against the PolyError enum to handle specific failure modes like API, network, or authentication errors. ```rust use polysqueeze::{ClobClient, PolyError}; #[tokio::main] async fn main() { let client = ClobClient::new("https://clob.polymarket.com"); match client.get_order_book("invalid-token-id").await { Ok(book) => println!("Got book: {:?}", book), Err(PolyError::Api { status, message }) => { eprintln!("API error ({}): {}", status, message); } Err(PolyError::Network { message, .. }) => { eprintln!("Network error: {}", message); } Err(PolyError::Parse { message, .. }) => { eprintln!("Parse error: {}", message); } Err(PolyError::Auth { message }) => { eprintln!("Authentication error: {}", message); } Err(PolyError::Validation { message }) => { eprintln!("Validation error: {}", message); } Err(PolyError::Order { message, kind }) => { eprintln!("Order error ({:?}): {}", kind, message); } Err(e) => eprintln!("Other error: {}", e), } } ``` -------------------------------- ### Add Polysqueeze to Dependencies Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Add the polysqueeze crate to your project's dependencies using cargo. ```bash cargo add polysqueeze ``` -------------------------------- ### Fetch Markets with GammaListParams Filtering Source: https://context7.com/augustin-v/polysqueeze/llms.txt Queries the Gamma API to retrieve prediction markets with advanced filtering options. Use GammaListParams to specify criteria like liquidity, volume, tags, and date ranges. Supports pagination. ```rust use polysqueeze::{ClobClient, types::GammaListParams}; use rust_decimal::Decimal; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let client = ClobClient::new("https://clob.polymarket.com"); // Configure market filters let params = GammaListParams { limit: Some(10), closed: Some(false), liquidity_num_min: Some(Decimal::from(10_000)), liquidity_num_max: Some(Decimal::from(1_000_000)), volume_num_min: Some(Decimal::from(5_000)), cyom: Some(false), // Exclude create-your-own markets include_tag: Some(true), ..Default::default() }; let response = client.get_markets(None, Some(¶ms)).await?; for market in &response.data { println!("Market: {} ({})", market.question, market.condition_id); println!(" Liquidity: {:?}", market.liquidity_num); println!(" Volume: {:?}", market.volume_num); println!(" Token IDs: {:?}", market.clob_token_ids); println!(" Tick Size: {}", market.minimum_tick_size); } // Pagination: fetch next page if available if let Some(cursor) = &response.next_cursor { let next_page = client.get_markets(Some(cursor), Some(¶ms)).await?; println!("Next page has {} markets", next_page.data.len()); } Ok(()) } ``` -------------------------------- ### Cancel Orders Source: https://context7.com/augustin-v/polysqueeze/llms.txt Provides methods to cancel single, multiple, or all open orders. Requires authentication via private key. ```rust use polysqueeze::ClobClient; #[tokio::main] async fn main() -> polysqueeze::Result<()> { let private_key = std::env::var("POLY_PRIVATE_KEY")?; let client = ClobClient::new_with_auth(&private_key, None).await?; // Cancel a single order by ID let order_id = "order-id-to-cancel"; let result = client.cancel(order_id).await?; println!("Cancel result: {:?}", result); // Cancel multiple orders let order_ids = vec![ "order-id-1".to_string(), "order-id-2".to_string(), ]; let results = client.cancel_orders(&order_ids).await?; println!("Batch cancel result: {:?}", results); // Cancel all orders for a specific market/asset let market_id = Some("condition-id"); let asset_id = Some("token-id"); let result = client.cancel_market_orders(market_id, asset_id).await?; println!("Market orders cancelled: {:?}", result); // Cancel ALL open orders let result = client.cancel_all().await?; println!("All orders cancelled: {:?}", result); Ok(()) } ``` -------------------------------- ### Check Code with Cargo Clippy Source: https://github.com/augustin-v/polysqueeze/blob/main/README.md Perform linting and static analysis on your Rust code using the cargo clippy command. This helps catch common errors and improve code quality. ```bash cargo clippy ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.