### Run an Example Project Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/README.md Execute an example from the Polymarket Rust Client SDK v2 project, such as the 'unauthenticated' example. ```bash cargo run --example unauthenticated ``` -------------------------------- ### Example Market Order Construction Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md Shows a complete example of building a market order with token ID, side, and amount. ```rust let order = client .market_order() .token_id(token_id) .side(Side::Buy) .amount(Amount::usdc(Decimal::ONE_HUNDRED)?) .build() .await?; ``` -------------------------------- ### Full Authentication Workflow Example Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/auth-and-credentials.md Demonstrates the complete process of authenticating with the CLOB client, from loading private keys to using authenticated endpoints and deauthentication. This example covers creating a signer, initializing a client, authenticating, and performing authenticated operations. ```rust use std::str::FromStr; use alloy::signers::local::LocalSigner; use alloy::signers::Signer as _; use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk_v2::clob::{Client, Config}; use polymarket_client_sdk_v2::auth::ExposeSecret; #[tokio::main] async fn main() -> Result<()> { // 1. Load and create signer let private_key = std::env::var(PRIVATE_KEY_VAR)?; let signer = LocalSigner::from_str(&private_key)? .with_chain_id(Some(POLYGON)); println!("Signer address: {}", signer.address()); // 2. Create unauthenticated client let client = Client::new("https://clob-v2.polymarket.com", Config::default())?; println!("Health check: {}", client.ok().await?); // 3. Authenticate (creates new API key) let authenticated = client .authentication_builder(&signer) .authenticate() .await?; println!("Authenticated as: {}", authenticated.address()); // 4. Use authenticated endpoints let creds = authenticated.credentials(); println!("API Key: {}", creds.key()); let api_keys = authenticated.api_keys().await?; println!("Total API keys: {}", api_keys.keys.len()); // 5. Use credentials with L2 signing let balance = authenticated .balance_allowance(&Default::default()) .await?; println!("Balance: {} USDC", balance.balance); // 6. Deauthenticate let public_client = authenticated.deauthenticate().await?; println!("Downgraded to public client"); Ok(()) } ``` -------------------------------- ### Batch Order Placement Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md This example demonstrates how to sign and submit multiple orders simultaneously using the `post_orders` method. ```rust let orders: Vec = vec![ client.sign(&signer, order1).await?, client.sign(&signer, order2).await?, client.sign(&signer, order3).await?, ]; let responses = client.post_orders(orders).await?; ``` -------------------------------- ### Example: Configuring Client with Builder Code Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/types.md Illustrates how to create a `Config` instance using the builder pattern, specifically setting the `builder_code`. ```rust use polymarket_client_sdk_v2::clob::Config; use polymarket_client_sdk_v2::types::B256; use std::str::FromStr; let builder_code = B256::from_str("0x...")?; let config = Config::builder() .builder_code(builder_code) .build(); ``` -------------------------------- ### Setup LocalSigner with Private Key Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Initializes a `LocalSigner` using a private key loaded from the `POLYMARKET_PRIVATE_KEY` environment variable, configured for the Polygon chain. ```rust use std::str::FromStr; use alloy::signers::local::LocalSigner; use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; let private_key = std::env::var(PRIVATE_KEY_VAR) .expect("Set POLYMARKET_PRIVATE_KEY environment variable"); let signer = LocalSigner::from_str(&private_key)? .with_chain_id(Some(POLYGON)); ``` -------------------------------- ### GET /api-keys Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Lists all API keys created for the account. ```APIDOC ## GET /api-keys ### Description List API keys created for this account. ### Method GET ### Endpoint /api-keys ### Response #### Success Response (200) - **ApiKeysResponse** - Response containing a list of API keys. ### Response Example ```json { "keys": [ { "apiKey": "uuid-string", "secret": "base64_secret", "passphrase": "string" } ] } ``` ``` -------------------------------- ### Example: Handling API Errors with StatusCode Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/types.md Demonstrates how to check for specific HTTP status codes, like NOT_FOUND (404), when handling errors from the client. ```rust use polymarket_client_sdk_v2::error::{Kind, StatusCode}; if let Err(e) = client.ok().await { if e.kind() == Kind::Status { if let Some(Status { status_code: StatusCode::NOT_FOUND, .. }) = e.downcast_ref() { // Handle 404 } } } ``` -------------------------------- ### GET /markets Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Lists all markets with pagination support. ```APIDOC ## GET /markets?nextCursor={cursor} ### Description List all markets with pagination. ### Method GET ### Endpoint /markets ### Parameters #### Query Parameters - **nextCursor** (string) - Optional - Pagination cursor from previous response - **limit** (u32) - Optional - Results per page (default varies) ### Response #### Success Response (200) - **Page** - A page of market data with a cursor for the next page. ### Response Example { "data": [ { /* MarketResponse */ } ], "nextCursor": "base64_cursor_or_null" } ``` -------------------------------- ### Configure Order Parameters using Builder Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md This example shows how to construct a limit order using the client's builder pattern. Various options like token ID, side, price, size, and order type can be configured before building the final order object. ```rust let order = client .limit_order() .token_id(token_id) .side(Side::Buy) .price(dec!(0.5)) .size(Decimal::TEN) .order_type(OrderType::GTC) // Good 'til Cancelled (default: FOK) .metadata(B256::ZERO) // Custom order metadata (V2 only) .builder_code(custom_builder) // Override default builder code .nonce(0) // Taker nonce (V1 only) .taker(Address::ZERO) // Specific taker (V1 only, default: public) .fee_rate_bps(50) // Fee rate (V1 only) .defer_exec(false) // Defer execution (V2 only) .build() .await?; ``` -------------------------------- ### Setup AWS KMS Signer Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Initializes an `AwsSigner` for remote signing using AWS KMS. Requires AWS credentials and a KMS key supporting ECDSA. ```rust use alloy::signers::aws::AwsSigner; use polymarket_client_sdk_v2::POLYGON; let aws_signer = AwsSigner::new(client, key_id, POLYGON).await?; ``` -------------------------------- ### GET /prices?tokenIds={id}&sides={side}... Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Performs a batch query to get the best bid or ask prices for multiple tokens and sides. ```APIDOC ## GET /prices?tokenIds={id}&sides={side}... ### Description Batch query best prices. ### Method GET ### Endpoint /prices ### Response #### Success Response (200) - **response** (PricesResponse) - Object containing batch price information. ### Response Example (Response structure depends on PricesResponse definition) ``` -------------------------------- ### Error Display Implementation Example Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/errors.md Illustrates the `Display` implementation for errors, showing how Kind and inner error details are formatted for user-friendly output. ```rust let e = Error::validation("Invalid price"); println!("{}", e); // Output: "Validation: invalid: Invalid price" let e = Error::status(StatusCode::NOT_FOUND, Method::GET, "/order", "Not found"); println!("{}", e); // Output: "Status: error(404) making GET call to /order with Not found" ``` -------------------------------- ### Client::total_earnings_for_user_for_day() Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Gets total earnings across all markets for a day. ```APIDOC ## Client::total_earnings_for_user_for_day() ### Description Gets total earnings across all markets for a day. ### Method `async fn total_earnings_for_user_for_day(&self, request: &UserRewardsEarningRequest) -> Result` ### Parameters #### Request Body - **request** (`&UserRewardsEarningRequest`) - Required - An object containing the user and day for which to retrieve total earnings. ``` -------------------------------- ### L1 Authentication Header Generation Example (Internal) Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/auth-and-credentials.md Illustrates how L1 authentication headers are generated internally by the SDK. This involves creating a ClobAuth struct, signing a message, and adding the computed headers to the request. ```rust // This happens internally when calling authenticate() let headers = auth::l1::create_headers(&signer, POLYGON, 1234567890, Some(0)).await?; // Returns HeaderMap with POLY_ADDRESS, POLY_NONCE, POLY_SIGNATURE, POLY_TIMESTAMP ``` -------------------------------- ### Paginate Market Data with Streams Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/README.md Use cursor-based pagination with streams to efficiently retrieve large result sets from endpoints like markets. This example demonstrates fetching markets and processing them as they become available. ```rust use futures::StreamExt; let mut stream = Box::pin(client.stream_data(|cursor| { client.markets(cursor) })); while let Some(market) = stream.next().await.transpose()? { println!("Market: {:?}", market); } ``` -------------------------------- ### L2 Request Signing Example (Internal) Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/auth-and-credentials.md Shows the internal process for generating L2 request signatures. This involves concatenating request details, computing an HMAC-SHA256 hash, and Base64-encoding the result. ```rust // This happens internally for every authenticated request let message = format!("{}{}{}{}", timestamp, method, path, body); let signature = hmac(&credentials.secret, &message)?; // Signature is Base64-encoded HMAC-SHA256 ``` -------------------------------- ### Get API Credentials Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Returns a reference to the API credentials used for authentication. ```rust pub fn credentials(&self) -> &Credentials ``` -------------------------------- ### Get User Earnings and Market Configuration Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Retrieves combined earnings and market configuration data for a user. Requires a `UserRewardsEarningRequest`. ```rust pub async fn user_earnings_and_markets_config( &self, request: &UserRewardsEarningRequest, ) -> Result ``` -------------------------------- ### Get API Host URL Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Returns the configured API host URL as a `Url` reference. ```rust pub fn host(&self) -> &Url ``` -------------------------------- ### LocalSigner Re-export with Usage Example Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/types.md Re-exports the LocalSigner from 'alloy::signers::local', a wallet signer using a private key. Demonstrates initialization with a private key string and chain ID. ```rust pub use alloy::signers::local::LocalSigner; use std::str::FromStr; let signer = LocalSigner::from_str("0x...")? .with_chain_id(Some(POLYGON)); ``` -------------------------------- ### Client::version() Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Gets the API version (1 for legacy, 2 for current). This value is cached after the first call. ```APIDOC ## Client::version() ### Description Gets the API version (1 for legacy, 2 for current). Cached after first call. ### Method `version` ### Parameters None ### Returns `Result` – API version number ### Example ```rust let version = client.version().await?; ``` ``` -------------------------------- ### GET /book?tokenId={tokenId} Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves the full order book, including bids and asks with their respective prices and sizes, for a given token. ```APIDOC ## GET /book?tokenId={tokenId} ### Description Get full orderbook (bids and asks). ### Method GET ### Endpoint /book ### Parameters #### Query Parameters - **tokenId** (U256) - Required - Token ID ### Response #### Success Response (200) - **bids** (array of arrays) - An array of bid orders, where each inner array contains price and size. - **asks** (array of arrays) - An array of ask orders, where each inner array contains price and size. - **timestamp** (i64) - Unix timestamp of the order book data. ### Response Example ```json { "bids": [ ["0.5400", "100.00"], ["0.5300", "200.00"] ], "asks": [ ["0.5600", "150.00"], ["0.5700", "250.00"] ], "timestamp": 1234567890 } ``` ``` -------------------------------- ### Enable SDK Features in Cargo.toml Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/README.md Configure which features of the Polymarket CLOB client SDK are enabled by adding them to your Cargo.toml file. This example enables the 'ws' and 'data' features. ```toml [dependencies] polymarket_client_sdk_v2 = { version = "=0.6.0-canary.1", features = ["ws", "data"] } ``` -------------------------------- ### GET /earnings Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves user earnings for a specified date range. Supports filtering by start and end dates. ```APIDOC ## GET /earnings?startDate={YYYY-MM-DD}&endDate={YYYY-MM-DD} ### Description User earnings for a date range. ### Method GET ### Endpoint /earnings ### Parameters #### Query Parameters - **startDate** (string) - Required - Start date (YYYY-MM-DD) - **endDate** (string) - Optional - End date (defaults to startDate) ### Response #### Success Response (200) - **Response Type:** `UserEarningResponse` or `TotalUserEarningResponse` ``` -------------------------------- ### Compute Authentication Signature Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md This example shows the computation of the signature for authentication headers. It involves concatenating the timestamp, method, path, and body, then computing an HMAC-SHA256 hash, which is then Base64 encoded. ```text message = TIMESTAMP + METHOD + PATH + BODY signature = Base64(HMAC-SHA256(secret_key, message)) ``` -------------------------------- ### Get Account Balance and Allowance Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Query your USDC balance and token allowances. You can specify a tokenId to get information for a specific token, or omit it to get only USDC details. ```json { "balance": "10000.000000", "allowance": "50000.000000", "tokenAllowances": { "0x...": "1000.00000000" } } ``` -------------------------------- ### Get Bid-Ask Spread for a Token Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Gets the bid-ask spread for a specific token. This indicates the difference between the highest bid and lowest ask. ```rust pub async fn spread(&self, request: &SpreadRequest) -> Result { // ... implementation details ... } ``` -------------------------------- ### Deauthenticate Client Example Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/auth-and-credentials.md Demonstrates how to downgrade an authenticated client back to an unauthenticated state using the `deauthenticate()` method. This is useful for switching users or reusing the client for public endpoints. ```rust let authenticated = client.authenticate().await?; // Use authenticated client... // Downgrade back to public access let public_client = authenticated.deauthenticate().await?; ``` -------------------------------- ### Client::market_order() Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md Creates a builder for market orders where the amount is specified and the order is executed at the best available price. This method starts the market order construction. ```APIDOC ## Client::market_order() ### Description Creates a builder for market orders (amount specified, executed at best price). ### Method ``` pub fn market_order(&self) -> OrderBuilder ``` ### Returns `OrderBuilder` – Market order builder ### Example ```rust let builder = client.market_order(); ``` ``` -------------------------------- ### Pattern Matching on Error Kind Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/errors.md Example of how to use the `kind()` method to perform different actions based on the error category. ```rust use polymarket_client_sdk_v2::error::Kind; match client.ok().await { Err(e) => match e.kind() { Kind::Status => println!("HTTP error"), Kind::Validation => println!("Invalid input"), Kind::Geoblock => println!("Geographic block"), _ => println!("Other error"), }, Ok(status) => println!("OK: {status}"), } ``` -------------------------------- ### GET /spreads?tokenIds={id1}&tokenIds={id2}... Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Performs a batch query to get the bid-ask spreads for multiple tokens. ```APIDOC ## GET /spreads?tokenIds={id1}&tokenIds={id2}... ### Description Batch query spreads. ### Method GET ### Endpoint /spreads ### Response #### Success Response (200) - **response** (SpreadsResponse) - Object containing batch spread information. ### Response Example (Response structure depends on SpreadsResponse definition) ``` -------------------------------- ### Config Struct and Builder Initialization Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/types.md Shows the definition of the `Config` struct and how to initiate the configuration builder. ```rust pub struct Config { // Fields private; // use builder } impl Config { pub fn builder() -> ConfigBuilder { ... } pub fn default() -> Config { ... } } ``` -------------------------------- ### GET /last-trades-prices?tokenIds={id1}&tokenIds={id2}... Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Performs a batch query to get the last trade prices for multiple tokens. ```APIDOC ## GET /last-trades-prices?tokenIds={id1}&tokenIds={id2}... ### Description Batch query last trade prices. ### Method GET ### Endpoint /last-trades-prices ### Response #### Success Response (200) - **response** (LastTradesPricesResponse) - Object containing batch last trade price information. ### Response Example (Response structure depends on LastTradesPricesResponse definition) ``` -------------------------------- ### Create Default and Custom Config Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Shows how to create a default configuration or a custom one using the builder pattern. ```rust use polymarket_client_sdk_v2::clob::Config; // Default configuration let config = Config::default(); // Custom configuration let config = Config::builder() .builder_code(builder_code) .build(); ``` -------------------------------- ### GET /midpoints?tokenIds={id1}&tokenIds={id2}... Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Performs a batch query to get midpoint prices for multiple tokens efficiently. ```APIDOC ## GET /midpoints?tokenIds={id1}&tokenIds={id2}... ### Description Batch query midpoint prices. ### Method GET ### Endpoint /midpoints ### Parameters #### Query Parameters - **tokenIds** (array of U256) - Required - Array of token IDs ### Response #### Success Response (200) - **midpoints** (object) - An object where keys are token IDs and values are their corresponding midpoint prices. ### Response Example ```json { "midpoints": { "123...": "0.5500", "456...": "0.7200" } } ``` ``` -------------------------------- ### Get Best Bid or Ask Price for a Token Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Gets the best available bid or ask price for a token. Specify the side (buy or sell) to query. ```rust use polymarket_client_sdk_v2::clob::types::{request::PriceRequest, Side}; let request = PriceRequest::builder() .token_id(token_id) .side(Side::Buy) .build(); let price = client.price(&request).await?; ``` -------------------------------- ### Initialize Client with V2 API Base URL Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Creates a new client instance pointing to the V2 API base URL. The SDK automatically detects the server's protocol version on the first order build. ```rust let client = Client::new("https://clob-v2.polymarket.com", Config::default())?; // First order build calls GET /version and caches the result let order = client .limit_order() .token_id(token_id) .side(Side::Buy) .price(dec!(0.5)) .size(Decimal::TEN) .build() .await?; // Subsequent builds use cached version let order2 = client .limit_order() .token_id(token_id2) .side(Side::Sell) .price(dec!(0.6)) .size(Decimal::FIVE) .build() .await?; ``` -------------------------------- ### Initialize Client for Localhost Testing Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Connects the client to a local development node, such as Anvil or Hardhat, running on `http://localhost:8545`. ```rust let client = Client::new("http://localhost:8545", Config::default())?; ``` -------------------------------- ### Import and Create CLOB Client Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/README.md Initializes a new CLOB client with a given endpoint and default configuration. Use this to establish a connection to the CLOB service. ```rust use polymarket_client_sdk_v2::clob::{Client, Config}; let client = Client::new("https://clob-v2.polymarket.com", Config::default())?; let status = client.ok().await?; println!("Status: {status}"); ``` -------------------------------- ### Client::earnings_for_user_for_day() Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Gets earnings for a specific day. ```APIDOC ## Client::earnings_for_user_for_day() ### Description Gets earnings for a specific day. ### Method `async fn earnings_for_user_for_day(&self, request: &UserRewardsEarningRequest) -> Result` ### Parameters #### Request Body - **request** (`&UserRewardsEarningRequest`) - Required - An object containing the user and day for which to retrieve earnings. ``` -------------------------------- ### Order with Builder Code Override Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md This example shows how to override the default client builder code with a custom one using the `builder_code` method. The builder code is expected as a B256 type. ```rust use polymarket_client_sdk_v2::types::B256; use std::str::FromStr; let builder_code = B256::from_str("0x...")?; let order = client .limit_order() .token_id(token_id) .side(Side::Buy) .price(dec!(0.55)) .size(Decimal::TEN) .builder_code(builder_code) // Override client default .build() .await?; ``` -------------------------------- ### Complete Limit Order Workflow Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md This snippet demonstrates the full lifecycle of placing a limit order, from client authentication to order submission. Ensure you have your private key set in the PRIVATE_KEY_VAR environment variable. ```rust use std::str::FromStr; use alloy::signers::local::LocalSigner; use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk_v2::clob::{Client, Config}; use polymarket_client_sdk_v2::clob::types::{Amount, OrderType, Side}; use polymarket_client_sdk_v2::types::{Decimal, U256}; use rust_decimal_macros::dec; #[tokio::main] async fn main() -> Result<()> { // 1. Create signer let private_key = std::env::var(PRIVATE_KEY_VAR)?; let signer = LocalSigner::from_str(&private_key)? .with_chain_id(Some(POLYGON)); // 2. Create and authenticate client let client = Client::new("https://clob-v2.polymarket.com", Config::default())? .authentication_builder(&signer) .authenticate() .await?; // 3. Build a limit order let token_id = U256::from_str("123...")?; let order = client .limit_order() .token_id(token_id) .side(Side::Buy) .price(dec!(0.55)) .size(Decimal::TEN) .order_type(OrderType::GTC) .build() .await?; // 4. Sign the order let signed_order = client.sign(&signer, order).await?; // 5. Submit the order let response = client.post_order(signed_order).await?; println!("Order placed: {}", response.order_id); println!("Status: {}", response.status); Ok(()) } ``` -------------------------------- ### GET /price?tokenId={tokenId}&side={side} Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves the best bid or ask price, along with the available size and timestamp, for a given token and side. ```APIDOC ## GET /price?tokenId={tokenId}&side={side} ### Description Get best bid or ask price for a token. ### Method GET ### Endpoint /price ### Parameters #### Query Parameters - **tokenId** (U256) - Required - Token ID - **side** (string) - Required - "BUY" or "SELL" ### Response #### Success Response (200) - **price** (string) - The best price available for the specified side. - **size** (string) - The quantity available at the best price. - **timestamp** (i64) - Unix timestamp of the price data. ### Response Example ```json { "price": "0.5500", "size": "100.00", "timestamp": 1234567890 } ``` ``` -------------------------------- ### GET /simplified-markets Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves markets with reduced metadata for efficiency. ```APIDOC ## GET /simplified-markets?nextCursor={cursor} ### Description Markets with reduced metadata. ### Method GET ### Endpoint /simplified-markets ### Parameters #### Query Parameters - **nextCursor** (string) - Optional - Pagination cursor from previous response ### Response #### Success Response (200) - **Page** - A page of simplified market data with a cursor for the next page. ``` -------------------------------- ### Initialize Authenticated Client Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Sets up an authenticated CLOB client using a private key from environment variables and a specified chain ID. ```rust use std::str::FromStr; use alloy::signers::local::LocalSigner; use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk_v2::clob::{Client, Config}; let private_key = std::env::var(PRIVATE_KEY_VAR)?; let signer = LocalSigner::from_str(&private_key)?.with_chain_id(Some(POLYGON)); // Create and authenticate in one step let config = Config::default(); let client = Client::new("https://clob-v2.polymarket.com", config)? .authentication_builder(&signer) .authenticate() .await?; let api_keys = client.api_keys().await?; ``` -------------------------------- ### GET /market-by-token-id Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves market metadata indexed by its token ID. ```APIDOC ## GET /market-by-token-id?tokenId={tokenId} ### Description Get market metadata indexed by token ID. ### Method GET ### Endpoint /market-by-token-id ### Parameters #### Query Parameters - **tokenId** (string) - Required - The token ID of the market. ### Response #### Success Response (200) - **MarketByTokenResponse** - Market metadata indexed by token ID. ``` -------------------------------- ### GET /sampling-markets Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves markets participating in the sampling rewards program. ```APIDOC ## GET /sampling-markets?nextCursor={cursor} ### Description Markets in the sampling rewards program. ### Method GET ### Endpoint /sampling-markets ### Parameters #### Query Parameters - **nextCursor** (string) - Optional - Pagination cursor from previous response ### Response #### Success Response (200) - **Page** - A page of market data with a cursor for the next page. ``` -------------------------------- ### Market Order Amount Creation Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md Demonstrates how to create Amount objects for market orders, specifying either USDC or token shares. ```rust use polymarket_client_sdk_v2::clob::types::Amount; use polymarket_client_sdk_v2::types::Decimal; // USDC amount (max 6 decimals) let usdc_amount = Amount::usdc(Decimal::ONE_HUNDRED)?; // Token shares amount (max 8 decimals) let shares_amount = Amount::shares(Decimal::FIFTY)?; ``` -------------------------------- ### GET /market Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves market details using a condition ID. ```APIDOC ## GET /market?conditionId={conditionId} ### Description Get market details by condition ID. ### Method GET ### Endpoint /market ### Parameters #### Query Parameters - **conditionId** (string) - Required - Market condition ID ### Response #### Success Response (200) - **MarketResponse** - Market details including condition ID, question, outcomes, resolution source, liquidity, and volume. ### Response Example { "conditionId": "0x...", "question": "Will X happen?", "outcomes": ["Yes", "No"], "resolutionSource": "https://...", "liquidity": "50000.00", "volume24H": "10000.00" } ``` -------------------------------- ### Create Market Order Builder Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md Use this method on an authenticated client to initiate the creation of a market order. This builder focuses on the amount to be traded, executing at the best available price. ```rust let builder = client.market_order(); ``` -------------------------------- ### GET /books Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves batch orderbooks for specified token IDs. ```APIDOC ## GET /books?tokenIds={id1}&tokenIds={id2}... ### Description Batch orderbooks. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **tokenIds** (string) - Required - Token ID(s) to retrieve orderbooks for. Can be specified multiple times. ### Response #### Success Response (200) - **Vec** - A vector of order book summaries. ``` -------------------------------- ### Handling 404 Not Found Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/errors.md Illustrates how to handle `404 Not Found` errors when querying an order. It explains that the order might have been matched or cancelled. ```rust match client.order("invalid-order-id").await { Err(e) if e.kind() == Kind::Status => { // Order doesn't exist; it may have been matched or cancelled } Ok(order) => println!("Order: {order:?}"), Err(e) => eprintln!("Error: {e}"), } ``` -------------------------------- ### Get User Wallet Address Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Returns the wallet address of the authenticated user. ```rust pub fn address(&self) -> Address ``` -------------------------------- ### Create Authentication Builder Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Initializes an authentication builder to transition the client from an unauthenticated to an authenticated state. Requires a signer that implements alloy::signers::Signer. ```Rust use std::str::FromStr; use alloy::signers::local::LocalSigner; use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; let private_key = std::env::var(PRIVATE_KEY_VAR)?; let signer = LocalSigner::from_str(&private_key)?.with_chain_id(Some(POLYGON)); let auth_builder = client.authentication_builder(&signer); ``` -------------------------------- ### GET /notifications Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves user notifications, including order fills and cancellations. ```APIDOC ## GET /notifications ### Description Retrieve user notifications (order fills, cancellations). ### Method GET ### Endpoint /notifications ### Response #### Success Response (200) - **Vec** - An array of notification objects. ``` -------------------------------- ### Initialize Client with Builder Code and Authentication Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Configures and authenticates a CLOB client, including a builder code for market makers. All subsequent orders will include this builder code. ```rust use polymarket_client_sdk_v2::clob::Config; use polymarket_client_sdk_v2::types::B256; use std::str::FromStr; let builder_code = B256::from_str(&std::env::var("POLYMARKET_BUILDER_CODE")?)?; let config = Config::builder() .builder_code(builder_code) .build(); let client = Client::new("https://clob-v2.polymarket.com", config)? .authentication_builder(&signer) .authenticate() .await?; // All orders now include the builder code ``` -------------------------------- ### GET /order Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves details of a specific open order by its order ID. ```APIDOC ## GET /order?orderId={orderId} ### Description Retrieve details of an open order. ### Method GET ### Endpoint /order ### Authentication Requires L2 headers (`POLY_ADDRESS`, `POLY_API_KEY`, `POLY_PASSPHRASE`, `POLY_SIGNATURE`, `POLY_TIMESTAMP`). ### Parameters #### Query Parameters - **orderId** (string) - Required - The ID of the order to retrieve. ### Response #### Success Response (200) - **OpenOrderResponse** - Details of the specified open order. ``` -------------------------------- ### GET /clob-market-info Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Fetches CLOB-specific information for a market, such as tick size and fees. ```APIDOC ## GET /clob-market-info?conditionId={conditionId} ### Description CLOB-specific market info (tick size, fees, asset data). ### Method GET ### Endpoint /clob-market-info ### Parameters #### Query Parameters - **conditionId** (string) - Required - The condition ID of the market. ### Response #### Success Response (200) - **ClobMarketInfoResponse** - CLOB-specific market information. ``` -------------------------------- ### Configure Client with Builder Code Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Sets up a client with a specific builder code for fee attribution on orders. This code is inherited by all orders created by the client unless overridden. ```rust use polymarket_client_sdk_v2::clob::Config; use polymarket_client_sdk_v2::types::B256; use std::str::FromStr; let builder_code = B256::from_str("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef")?; let config = Config::builder() .builder_code(builder_code) .build(); let client = Client::new("https://clob-v2.polymarket.com", config)?; // Now all orders created by this client inherit the builder_code let order = client .limit_order() .token_id(token_id) .side(Side::Buy) .price(dec!(0.5)) .size(Decimal::TEN) .build() .await?; // order.builder == builder_code (unless overridden) ``` -------------------------------- ### GET / Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Provides a health check for the API. Returns 'OK' if the service is operational. ```APIDOC ## GET / ### Description Health check endpoint. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **response** (string) - "OK" ### Response Example ``` "OK" ``` ``` -------------------------------- ### Create Credentials Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/auth-and-credentials.md Creates a `Credentials` instance from a UUID, a Base64-encoded secret, and a passphrase. ```rust use uuid::Uuid; use polymarket_client_sdk_v2::auth::Credentials; let creds = Credentials::new( Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".to_string(), "my_passphrase".to_string(), ); ``` -------------------------------- ### Get Reward Percentages Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Fetches the current reward percentage rates. Returns a `RewardsPercentagesResponse`. ```rust pub async fn reward_percentages(&self) -> Result ``` -------------------------------- ### Load and Use Private Key from Environment Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Loads the private key from the `POLYMARKET_PRIVATE_KEY` environment variable and creates a `LocalSigner` with a specified chain ID. ```rust use std::str::FromStr; use alloy::signers::local::LocalSigner; let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; let signer = LocalSigner::from_str(&private_key)?.with_chain_id(Some(POLYGON)); ``` -------------------------------- ### GET /geoblock Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Checks if the client's IP address is subject to geographic blocking. ```APIDOC ## GET /geoblock ### Description Check if the client's IP is geographically blocked. ### Method GET ### Endpoint /geoblock ### Response #### Success Response (200) - **GeoblockResponse** - Information about the IP address and whether it is blocked. ### Response Example (if blocked) { "ip": "192.168.1.1", "country": "US", "region": "NY", "blocked": true } #### Status Codes - 200 OK – Not blocked - 451 Unavailable for Legal Reasons – Blocked (triggers `Kind::Geoblock` error) ``` -------------------------------- ### Place a Limit Order Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/README.md Use this snippet to place a limit order. Ensure you have set the PRIVATE_KEY_VAR environment variable. Specify the desired size and price for the order. ```rust use std::str::FromStr as _; use alloy::signers::Signer as _; use alloy::signers::local::LocalSigner; use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk_v2::clob::{Client, Config}; use polymarket_client_sdk_v2::clob::types::Side; use polymarket_client_sdk_v2::types::Decimal; use rust_decimal_macros::dec; #[tokio::main] async fn main() -> anyhow::Result<()> { let private_key = std::env::var(PRIVATE_KEY_VAR).expect("Need a private key"); let signer = LocalSigner::from_str(&private_key)?.with_chain_id(Some(POLYGON)); let client = Client::new("https://clob-v2.polymarket.com", Config::default())? .authentication_builder(&signer) .authenticate() .await?; let order = client .limit_order() .token_id("") .size(Decimal::ONE_HUNDRED) .price(dec!(0.1)) .side(Side::Buy) .build() .await?; let signed_order = client.sign(&signer, order).await?; let response = client.post_order(signed_order).await?; println!("Order response: {:?}", response); Ok(()) } ``` -------------------------------- ### GET /time Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves the current server timestamp. Useful for time synchronization and logging. ```APIDOC ## GET /time ### Description Returns current server timestamp. ### Method GET ### Endpoint /time ### Response #### Success Response (200) - **timestamp** (i64) - Current server timestamp in Unix seconds. ### Response Example ```json { "timestamp": 1234567890 } ``` ``` -------------------------------- ### Place a Market Order Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/README.md Use this snippet to place a market order. Ensure you have set the PRIVATE_KEY_VAR environment variable. The order type can be set to FOK (Fill-or-Kill). ```rust use std::str::FromStr as _; use alloy::signers::Signer as _; use alloy::signers::local::LocalSigner; use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk_v2::clob::{Client, Config}; use polymarket_client_sdk_v2::clob::types::{Amount, OrderType, Side}; use polymarket_client_sdk_v2::types::Decimal; #[tokio::main] async fn main() -> anyhow::Result<()> { let private_key = std::env::var(PRIVATE_KEY_VAR).expect("Need a private key"); let signer = LocalSigner::from_str(&private_key)?.with_chain_id(Some(POLYGON)); let client = Client::new("https://clob-v2.polymarket.com", Config::default())? .authentication_builder(&signer) .authenticate() .await?; let order = client .market_order() .token_id("") .amount(Amount::usdc(Decimal::ONE_HUNDRED)?) .side(Side::Buy) .order_type(OrderType::FOK) .build() .await?; let signed_order = client.sign(&signer, order).await?; let response = client.post_order(signed_order).await?; println!("Order response: {:?}", response); Ok(()) } ``` -------------------------------- ### Get API Key UUID Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/auth-and-credentials.md Retrieves the API key UUID from the `Credentials` struct. ```rust let key: Uuid = credentials.key(); ``` -------------------------------- ### Create Market Order Builder Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Initializes a builder for constructing a market order. The order must be finalized by calling `.build()`. ```rust use polymarket_client_sdk_v2::clob::types::{Amount, OrderType, Side}; let order = client .market_order() .token_id(token_id) .amount(Amount::usdc(Decimal::ONE_HUNDRED)?) .side(Side::Buy) .order_type(OrderType::FOK) .build() .await?; ``` -------------------------------- ### Get Authenticated State Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Returns a reference to the authenticated state, which includes credentials and user address. ```rust pub fn state(&self) -> &Authenticated ``` -------------------------------- ### Add Polymarket Rust Client using Cargo Add Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/README.md Alternatively, add the Polymarket Rust Client SDK v2 to your project using the `cargo add` command. ```bash cargo add polymarket_client_sdk_v2 ``` -------------------------------- ### Get Current Rewards Information Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Retrieves information about currently active rewards. Returns a `CurrentRewardResponse`. ```rust pub async fn current_rewards(&self) -> Result ``` -------------------------------- ### Get Market by Token ID Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/clob-client.md Retrieves market metadata using its associated token ID. ```rust pub async fn market_by_token(&self, token_id: U256) -> Result ``` -------------------------------- ### Enable Tracing and Detailed Logging Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md This command adds the tracing feature to the client library. The subsequent Rust code initializes the tracing subscriber, allowing SDK logs to be viewed by setting the RUST_LOG environment variable. ```bash cargo add --features tracing polymarket_client_sdk_v2 ``` ```rust use tracing_subscriber::EnvFilter; // Initialize subscriber tracing_subscriber::fmt() .with_env_filter(EnvFilter::from_default_env()) .init(); // Set env var to see SDK logs // RUST_LOG=polymarket_client_sdk_v2=debug cargo run ``` -------------------------------- ### Catching Validation Errors Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/errors.md Demonstrates how to catch and handle validation errors when creating a client. Ensure the client host parameter is a valid URL. ```rust use polymarket_client_sdk_v2::error::Kind; match client.new("invalid-url", Config::default()) { Err(e) if e.kind() == Kind::Validation => { eprintln!("Validation error: {e}"); } Ok(client) => { /* use client */ } Err(e) => eprintln!("Unexpected error: {e}"), } ``` -------------------------------- ### GET /ban Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Checks the account status to determine if it is in closed-only mode (banned from certain actions). ```APIDOC ## GET /ban ### Description Check if the account is in closed-only mode (banned from certain actions). ### Method GET ### Endpoint /ban ### Response #### Success Response (200) - **Response Body:** ```json { "banned": false, "closedOnly": true } ``` - **Response Type:** `BanStatusResponse` ``` -------------------------------- ### GET /fee-rate-bps Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves the trading fee in basis points for a market, using cached data. ```APIDOC ## GET /fee-rate-bps?tokenId={tokenId} ### Description Trading fee in basis points (cached). ### Method GET ### Endpoint /fee-rate-bps ### Parameters #### Query Parameters - **tokenId** (string) - Required - Token ID ### Response #### Success Response (200) - **FeeRateResponse** - Contains the trading fee in basis points and its exponent. ### Response Example { "feeRateBps": 50, "exponent": 1 } ``` -------------------------------- ### Create USDC and Token Amounts Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/types.md Creates `Amount` instances for USDC (max 6 decimal places) and conditional tokens (max 8 decimal places) using `Amount::usdc()` and `Amount::shares()`. Requires a `Result` context. ```rust let usdc_amount = Amount::usdc(Decimal::ONE_HUNDRED)?; let token_amount = Amount::shares(dec!(50.5))?; ``` -------------------------------- ### GET /neg-risk Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Checks if a market uses the Neg Risk adapter, using cached data. ```APIDOC ## GET /neg-risk?tokenId={tokenId} ### Description Whether market uses Neg Risk adapter (cached). ### Method GET ### Endpoint /neg-risk ### Parameters #### Query Parameters - **tokenId** (string) - Required - Token ID ### Response #### Success Response (200) - **NegRiskResponse** - Indicates if the market uses the Neg Risk adapter. ``` -------------------------------- ### Create Ethereum Address Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/types.md Creates an Ethereum account address using the `address!()` macro. This type represents a 20-byte address. ```rust use polymarket_client_sdk_v2::types::address; let addr = address!("0x0000000000000000000000000000000000000000"); ``` -------------------------------- ### Load and Use Builder Code from Environment Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/configuration.md Loads the builder code from the `POLYMARKET_BUILDER_CODE` environment variable and configures the client with it. ```rust use polymarket_client_sdk_v2::types::B256; use std::str::FromStr; let builder_code = B256::from_str(&std::env::var("POLYMARKET_BUILDER_CODE")?)?; let config = Config::builder().builder_code(builder_code).build(); ``` -------------------------------- ### GET /last-trade-price?tokenId={tokenId} Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/endpoints.md Retrieves the price of the most recent trade executed for a given token. ```APIDOC ## GET /last-trade-price?tokenId={tokenId} ### Description Get the most recent trade price. ### Method GET ### Endpoint /last-trade-price ### Parameters #### Query Parameters - **tokenId** (U256) - Required - Token ID ### Response #### Success Response (200) - **response** (LastTradePriceResponse) - Object containing the last trade price information. ### Response Example (Response structure depends on LastTradePriceResponse definition) ``` -------------------------------- ### Create Limit Order Builder Source: https://github.com/polymarket/rs-clob-client-v2/blob/main/_autodocs/api-reference/order-builder.md Use this method on an authenticated client to initiate the creation of a limit order. This builder requires price and size to be specified. ```rust let builder = client.limit_order(); ```