### Run an example using cargo run Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/index.html Execute one of the provided examples, such as the 'unauthenticated' example, using `cargo run`. ```bash cargo run --example unauthenticated ``` -------------------------------- ### Authenticated Client Example (Rust) Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/index.html Example demonstrating how to create and use an authenticated client for trading operations using a private key. ```Rust use std::str::FromStr as _; use alloy::signers::Signer; use alloy::signers::local::LocalSigner; use polymarket_client_sdk::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk::clob::{Client, Config}; use polymarket_client_sdk::clob::types::{Side, SignedOrder}; use polymarket_client_sdk::types::{dec, Decimal, U256}; // Create signer from private key let private_key = std::env::var(PRIVATE_KEY_VAR)?; let signer = LocalSigner::from_str(&private_key)?.with_chain_id(Some(POLYGON)); let client = Client::new("https://clob.polymarket.com", Config::default())? .authentication_builder(&signer) .authenticate() .await?; let order = client .limit_order() .token_id(U256::from_str("15871154585880608648532107628464183779895785213830018178010423617714102767076")?) .side(Side::Buy) .price(dec!(0.5)) .size(Decimal::TEN) .build() .await?; let signed_order = client.sign(&signer, order).await?; let response = client.post_order(signed_order).await?; println!("Order ID: {}", response.order_id); ``` -------------------------------- ### Rust SDK Example Usage Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/index.html Example demonstrating how to use the Polymarket Gamma API client in Rust to fetch events. ```rust use polymarket_client_sdk::gamma::{Client, types::request::EventsRequest}; // Create a client with the default endpoint let client = Client::default(); // Build a request for active events let request = EventsRequest::builder() .active(true) .limit(10) .build(); // Fetch events let events = client.events(&request).await?; for event in events { println!("{}: {{}}", event.id, event.title); } ``` -------------------------------- ### Client Initialization and Subscription Examples Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/rtds/client/struct.Client.html Demonstrates how to initialize the RTDS client and subscribe to cryptocurrency price updates. ```APIDOC ## Client Initialization and Crypto Price Subscription ### Description This example shows how to create a new RTDS client, subscribe to real-time cryptocurrency price updates from Binance for specific symbols, and process the incoming price data. ### Method `Client::new` and `Client::subscribe_crypto_prices` ### Endpoint `wss://rtds.polymarket.com` (for client initialization) ### Parameters #### Request Body None for initialization and subscription methods shown. ### Request Example ```rust use polymarket_client_sdk::rtds::Client; use polymarket_client_sdk::ws::config::Config; use futures::StreamExt; use tokio::pin; let client = Client::new("wss://rtds.polymarket.com", Config::default())?; let stream = client.subscribe_crypto_prices(Some(vec!["BTCUSDT".to_string()]))?; pin!(stream); while let Some(price_result) = stream.next().await { let price = price_result?; println!("BTC Price: ${}", price.value); } ``` ### Response #### Success Response (Stream Item) - **CryptoPrice** (struct) - Contains real-time cryptocurrency price data. #### Response Example (for each price update) ```json { "symbol": "btcusdt", "value": 65000.50, "timestamp": 1678886400 } ``` ``` -------------------------------- ### URL Parsing Example Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/auth/builder/struct.Url.html Demonstrates basic URL parsing and string conversion. ```APIDOC ## URL Parsing Example ### Description This example shows how to parse a URL string and convert it back to a string. ### Method `Url::parse` and `into_string` (or `String::from`) ### Endpoint N/A (Local operation) ### Request Body N/A ### Request Example ```rust use url::Url; let url_str = "https://example.net/"; let url = Url::parse(url_str)?; assert_eq!(url.as_str(), url_str); ``` ### Response N/A (Assertion-based example) ### Response Example N/A ``` -------------------------------- ### Example TradesRequest Construction Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/request/struct.TradesRequest.html Demonstrates how to construct a TradesRequest using the builder pattern. This example filters trades for a specific user, sets the side to BUY, and specifies a minimum cash trade amount. ```rust use polymarket_client_sdk::types::address; use polymarket_client_sdk::data::{types::request::TradesRequest, types::{Side, TradeFilter}}; use rust_decimal_macros::dec; let request = TradesRequest::builder() .user(address!("56687bf447db6ffa42ffe2204a05edaa20f55839")) .side(Side::Buy) .trade_filter(TradeFilter::cash(dec!(100)).unwrap()) .build(); ``` -------------------------------- ### Decimal Rounding Examples Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.Decimal.html Examples demonstrating the `round_sf_with_strategy` method for rounding Decimal numbers with different significant figures and rounding strategies. ```APIDOC ## Decimal Rounding Examples ### Description Demonstrates rounding of `Decimal` numbers using the `round_sf_with_strategy` method with `RoundingStrategy::ToZero`. ### Method `round_sf_with_strategy` ### Parameters - **significant_figures** (usize) - The number of significant figures to round to. - **strategy** (RoundingStrategy) - The rounding strategy to apply. ### Request Example ```rust let value = dec!(305.459); assert_eq!(value.round_sf_with_strategy(0, RoundingStrategy::ToZero), Some(dec!(0))); assert_eq!(value.round_sf_with_strategy(1, RoundingStrategy::ToZero), Some(dec!(300))); assert_eq!(value.round_sf_with_strategy(2, RoundingStrategy::ToZero), Some(dec!(300))); assert_eq!(value.round_sf_with_strategy(3, RoundingStrategy::ToZero), Some(dec!(305))); assert_eq!(value.round_sf_with_strategy(4, RoundingStrategy::ToZero), Some(dec!(305.4))); assert_eq!(value.round_sf_with_strategy(5, RoundingStrategy::ToZero), Some(dec!(305.45))); assert_eq!(value.round_sf_with_strategy(6, RoundingStrategy::ToZero), Some(dec!(305.459))); assert_eq!(value.round_sf_with_strategy(7, RoundingStrategy::ToZero), Some(dec!(305.4590))); assert_eq!(Decimal::MAX.round_sf_with_strategy(1, RoundingStrategy::ToZero), Some(dec!(70000000000000000000000000000))); let value = dec!(0.012301); assert_eq!(value.round_sf_with_strategy(3, RoundingStrategy::AwayFromZero), Some(dec!(0.0124))); ``` ### Response - **Option** - The rounded Decimal number, or None if rounding fails. ``` -------------------------------- ### Address Examples Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.Address.html Demonstrates how to parse, format, and use the Address type with EIP-55 checksums and other utilities. ```APIDOC ## §Examples ### Parsing and formatting: ```rust use alloy_primitives::{address, Address}; let checksummed = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; let expected = address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045"); let address = Address::parse_checksummed(checksummed, None).expect("valid checksum"); assert_eq!(address, expected); // Format the address with the checksum assert_eq!(address.to_string(), checksummed); assert_eq!(address.to_checksum(None), checksummed); // Format the compressed checksummed address assert_eq!(format!("{address:#}"), "0xd8dA…6045"); // Format the address without the checksum assert_eq!(format!("{address:?}"), "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"); ``` ### From EVM Word: ```rust use alloy_primitives::{address, Address, b256}; let word = b256!("0x000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045"); assert_eq!(Address::from_word(word), address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045")); ``` ### Into EVM Word: ```rust use alloy_primitives::{address, Address, b256}; assert_eq!( address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045").into_word(), b256!("0x000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045"), ); ``` ``` -------------------------------- ### Approximate Base 2 Logarithm Examples Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/type.U256.html Provides examples demonstrating the usage of the `approx_log2` function for various Uint values, including zero, one, two, and the maximum value. ```rust assert_eq!(0_U64.approx_log2(), f64::NEG_INFINITY); assert_eq!(1_U64.approx_log2(), 0.0); assert_eq!(2_U64.approx_log2(), 1.0); assert_eq!(U64::MAX.approx_log2(), 64.0); ``` -------------------------------- ### Uuid Creation and Parsing Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/auth/struct.Uuid.html Examples of how to create and parse Uuid values. ```APIDOC ## §Examples ### Parse a UUID Parse a UUID given in the simple format and print it as a urn: ```rust let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?; println!("{}", my_uuid.urn()); ``` ### Create a new random (V4) UUID Create a new random (V4) UUID and print it out in hexadecimal form: ```rust // Note that this requires the `v4` feature enabled in the uuid crate. let my_uuid = Uuid::new_v4(); println!("{}", my_uuid); ``` ``` -------------------------------- ### Client Initialization and Basic Usage Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/bridge/client/struct.Client.html Demonstrates how to initialize the Client and perform basic operations like getting deposit addresses and supported assets. ```APIDOC ## Client Initialization and Usage ### Description This section provides examples of how to initialize the `Client` and use its core functionalities. ### Methods - `Client::default()`: Creates a new Bridge API client with default settings. - `Client::new(host: &str)`: Creates a new Bridge API client with a custom host. - `client.deposit(&request)`: Generates deposit addresses. - `client.supported_assets()`: Retrieves a list of supported assets and chains. ### Request Body Examples #### DepositRequest ```json { "address": "56687bf447db6ffa42ffe2204a05edaa20f55839" } ``` ### Response Examples #### DepositResponse ```json { "address": { "evm": "0x...", "svm": "...", "btc": "..." } } ``` #### SupportedAssetsResponse ```json { "supported_assets": [ { "chain_name": "Ethereum", "chain_id": 1, "min_checkout_usd": 10.0, "token": { "name": "USD Coin", "symbol": "USDC", "decimals": 6 } } ] } ``` ``` -------------------------------- ### Get Day0 from NaiveDate Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.NaiveDate.html Retrieves the day of the month from a NaiveDate, starting from 0 (0-30). ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().day0(), 7); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().day0(), 13); ``` -------------------------------- ### Client Initialization and Authentication Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/client/struct.Client.html Demonstrates how to create an unauthenticated client and how to elevate it to an authenticated client using a private key. ```APIDOC ## Client Initialization and Authentication ### Unauthenticated Client Creation This example shows how to create a new `Client` instance without authentication. ```rust use polymarket_client_sdk::Result; use polymarket_client_sdk::clob::{Client, Config}; #[tokio::main] async fn main() -> Result<()> { let client = Client::new("https://clob.polymarket.com", Config::default())?; let ok = client.ok().await?; println!("Ok: {ok}"); Ok(()) } ``` ### Authenticated Client Creation This example demonstrates how to authenticate the client using a private key and elevate it to an authenticated state. ```rust use std::str::FromStr as _; use alloy::signers::Signer as _; use alloy::signers::local::LocalSigner; use polymarket_client_sdk::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk::clob::{Client, Config}; #[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.polymarket.com", Config::default())? .authentication_builder(&signer) .authenticate() .await?; let ok = client.ok().await?; println!("Ok: {ok}"); let api_keys = client.api_keys().await?; println!("API keys: {api_keys:?}"); Ok(()) } ``` ``` -------------------------------- ### Get Month0 from NaiveDate Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.NaiveDate.html Retrieves the month component of a NaiveDate, starting from 0 (0-11). ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().month0(), 8); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().month0(), 2); ``` -------------------------------- ### Get Ordinal0 Day of Year from NaiveDate Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.NaiveDate.html Retrieves the day of the year from a NaiveDate, starting from 0. The value ranges from 0 to 365. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().ordinal0(), 250); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().ordinal0(), 73); ``` -------------------------------- ### Get Ordinal Day of Year from NaiveDate Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.NaiveDate.html Retrieves the day of the year from a NaiveDate, starting from 1. The value ranges from 1 to 366. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().ordinal(), 251); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().ordinal(), 74); ``` -------------------------------- ### Get URL Path Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/auth/builder/struct.Url.html Retrieves the path component of a URL. The path is returned as a percent-encoded ASCII string. For URLs that cannot be a base, this is an arbitrary string. For others, it starts with '/' and includes path segments. ```rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2")?; assert_eq!(url.path(), "/api/versions"); ``` ```rust let url = Url::parse("https://example.com")?; assert_eq!(url.path(), "/"); ``` ```rust let url = Url::parse("https://example.com/countries/việt nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam"); ``` -------------------------------- ### GET /fee_rate_bps Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/client/struct.Client.html Retrieves the trading fee rate for a market outcome token. Returns the fee rate in basis points (bps) charged on trades for this token. For example, 10 bps = 0.10% fee. Results are cached internally to reduce API calls. ```APIDOC ## GET /fee_rate_bps ### Description Retrieves the trading fee rate for a market outcome token. Returns the fee rate in basis points (bps) charged on trades for this token. For example, 10 bps = 0.10% fee. Results are cached internally to reduce API calls. ### Method GET ### Endpoint /fee_rate_bps ### Parameters #### Query Parameters - **token_id** (string) - Required - The unique identifier of the market outcome token. ### Request Example ```json { "token_id": "0xabc..." } ``` ### Response #### Success Response (200) - **fee_rate_bps** (integer) - The trading fee rate in basis points (bps). #### Response Example ```json { "fee_rate_bps": 10 } ``` ### Errors - Returns an error if the request fails or the token ID is invalid. ``` -------------------------------- ### Client Initialization Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/client/struct.Client.html Demonstrates how to create a new Client instance for the Polymarket Data API, either with the default endpoint or a custom one. ```APIDOC ## Client Initialization ### Description Initializes the Polymarket Data API client. You can use the default API endpoint or specify a custom one. ### Usage ```rust use polymarket_client_sdk::data::Client; // Create client with default endpoint let client = Client::default(); // Or with a custom endpoint let client = Client::new("https://custom-api.example.com").unwrap(); ``` ### Methods #### `Client::default()` Creates a new Data API client with the default host URL. #### `Client::new(host: &str) -> Result` Creates a new Data API client with a custom host URL. * **host** (string) - The base URL for the Data API (e.g., `https://data-api.polymarket.com`). ### Errors Returns an error if the URL is invalid or the HTTP client cannot be created. ``` -------------------------------- ### GET /tick_size Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/client/struct.Client.html Retrieves the minimum tick size for a market outcome token. The tick size defines the minimum price increment for orders on this token. Results are cached internally to reduce API calls. For example, a tick size of 0.01 means prices must be in increments of $0.01. ```APIDOC ## GET /tick_size ### Description Retrieves the minimum tick size for a market outcome token. The tick size defines the minimum price increment for orders on this token. Results are cached internally to reduce API calls. For example, a tick size of 0.01 means prices must be in increments of $0.01. ### Method GET ### Endpoint /tick_size ### Parameters #### Query Parameters - **token_id** (string) - Required - The unique identifier of the market outcome token. ### Request Example ```json { "token_id": "0xabc..." } ``` ### Response #### Success Response (200) - **tick_size** (string) - The minimum tick size for the specified token. #### Response Example ```json { "tick_size": "0.0001" } ``` ### Errors - Returns an error if the request fails or the token ID is invalid. ``` -------------------------------- ### Client Initialization Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/client/struct.Client.html Demonstrates how to create an instance of the Polymarket Gamma API client, either with the default endpoint or a custom one. ```APIDOC ## Client Initialization ### Description Instantiates the Polymarket Gamma API client. You can use the default API endpoint or provide a custom one. ### Request Example ```rust use polymarket_client_sdk::gamma::Client; // Create client with default endpoint let client = Client::default(); // Or with a custom endpoint let client = Client::new("https://custom-api.example.com").unwrap(); ``` ``` -------------------------------- ### Set Start Timestamp Filter Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/request/struct.ActivityRequestBuilder.html Sets the start timestamp filter (Unix timestamp, minimum: 0). The state S must have an unset Start field. ```rust pub fn start(self, value: u64) -> ActivityRequestBuilder> where S::Start: IsUnset, ``` -------------------------------- ### Create LiveVolume Instance with Builder Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/response/struct.LiveVolume.html Demonstrates how to create an instance of `LiveVolume` using the builder pattern. This is the recommended way to construct `LiveVolume` objects. ```rust pub fn builder() -> LiveVolumeBuilder ``` -------------------------------- ### ClobRewardBuilder Start Date Setter Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.ClobRewardBuilder.html Sets the optional start date for the ClobReward. Use this method when the start date is present. Requires the StartDate state to be unset. ```rust pub fn start_date(self, value: NaiveDate) -> ClobRewardBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### Instantiate ConnectionManager and Subscribe Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/ws/connection/struct.ConnectionManager.html Demonstrates how to create a new ConnectionManager instance with a given endpoint, configuration, and parser. It also shows how to subscribe to incoming messages and process them. ```rust let parser = SimpleParser; let connection = ConnectionManager::new( "wss://example.com".to_owned(), config, parser, )?; // Subscribe to messages let mut rx = connection.subscribe(); while let Ok(msg) = rx.recv().await { println!("Received: {:?}", msg); } ``` -------------------------------- ### Example Usage of StatusRequest Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/bridge/types/struct.StatusRequest.html Demonstrates how to create a StatusRequest instance using the builder pattern. Ensure the polymarket_client_sdk is imported. ```rust use polymarket_client_sdk::bridge::types::StatusRequest; let request = StatusRequest::builder().address("0x9cb12Ec30568ab763ae5891ce4b8c5C96CeD72C9").build(); ``` -------------------------------- ### ClobRewardBuilder Maybe Start Date Setter Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.ClobRewardBuilder.html Sets the optional start date for the ClobReward. Use this method when the start date might be absent (None). Requires the StartDate state to be unset. ```rust pub fn maybe_start_date( self, value: Option, ) -> ClobRewardBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### Set Optional Start Timestamp Filter with Option Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/request/struct.ActivityRequestBuilder.html Sets the start timestamp filter (Unix timestamp, minimum: 0) using an Option. The state S must have an unset Start field. ```rust pub fn maybe_start( self, value: Option, ) -> ActivityRequestBuilder> where S::Start: IsUnset, ``` -------------------------------- ### Client Initialization Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/ctf/client/struct.Client.html Constructors for creating a new CTF client. ```APIDOC ## Client Initialization ### `Client::new` Creates a new CTF client for the specified chain. #### Arguments * `provider` - An alloy provider instance * `chain_id` - The chain ID (e.g., 137 for Polygon mainnet, 80002 for Amoy testnet) #### Errors Returns an error if the contract configuration is not found for the given chain. ### `Client::with_neg_risk` Creates a new CTF client with `NegRisk` adapter support. Use this constructor when you need to work with negative risk markets. #### Arguments * `provider` - An alloy provider instance * `chain_id` - The chain ID (e.g., 137 for Polygon mainnet, 80002 for Amoy testnet) #### Errors Returns an error if the contract configuration is not found for the given chain, or if the `NegRisk` adapter is not configured for the chain. ``` -------------------------------- ### Example Usage of DepositRequest Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/bridge/types/struct.DepositRequest.html Demonstrates how to create an instance of DepositRequest using the builder pattern. Ensure the necessary types and macros are imported. ```rust use polymarket_client_sdk::types::address; use polymarket_client_sdk::bridge::types::DepositRequest; let request = DepositRequest::builder() .address(address!("56687bf447db6ffa42ffe2204a05edaa20f55839")) .build(); ``` -------------------------------- ### SimpleParser Implementation Example Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/ws/traits/trait.MessageParser.html An example implementation of the MessageParser trait for a custom message type `MyMessage`. ```APIDOC ## §Example ```rust pub struct SimpleParser; impl MessageParser for SimpleParser { fn parse(&self, bytes: &[u8]) -> crate::Result> { let msg: MyMessage = serde_json::from_slice(bytes)?; Ok(vec![msg]) } } ``` ``` -------------------------------- ### Set Event Start Date Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.EventBuilder.html Sets the start date for the event. The state `S::StartDate` must be `IsUnset`. ```rust pub fn start_date(self, value: DateTime) -> EventBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### Create MarketVolume Instance with Builder Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/response/struct.MarketVolume.html Demonstrates how to create an instance of MarketVolume using the builder pattern. This is the recommended way to construct MarketVolume objects. ```rust pub fn builder() -> MarketVolumeBuilder ``` -------------------------------- ### Set MarketRewardsConfig Start Date Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/types/response/struct.MarketRewardsConfigBuilder.html Sets the required start date for the MarketRewardsConfig. Requires S::StartDate to be IsUnset. ```rust pub fn start_date( self, value: NaiveDate, ) -> MarketRewardsConfigBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### Initialize Polymarket Data API Client Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/client/struct.Client.html Create a client instance using the default API endpoint or a custom URL. Ensure the provided URL is valid. ```rust use polymarket_client_sdk::data::Client; // Create client with default endpoint let client = Client::default(); // Or with a custom endpoint let client = Client::new("https://custom-api.example.com").unwrap(); ``` -------------------------------- ### Example of NaiveDateTime creation with microseconds Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.NaiveDate.html Demonstrates creating a NaiveDateTime with microsecond precision and asserting its properties. Note the conversion of microseconds to nanoseconds for the `nanosecond()` method. ```rust use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike, Weekday}; let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap(); let dt: NaiveDateTime = d.and_hms_micro_opt(12, 34, 56, 789_012).unwrap(); assert_eq!(dt.year(), 2015); assert_eq!(dt.weekday(), Weekday::Wed); assert_eq!(dt.second(), 56); assert_eq!(dt.nanosecond(), 789_012_000); ``` -------------------------------- ### Get Subscription Count Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/rtds/client/struct.Client.html Get the number of active subscriptions managed by this client using the `subscription_count` method. ```rust use polymarket_client_sdk::rtds::Client; let client = Client::default(); let count = client.subscription_count(); println!("Subscription Count: {}", count); ``` -------------------------------- ### Optional Event Start Time Setter Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.MarketBuilder.html Sets the start time for the event associated with the market. This is an optional field. ```APIDOC ## POST /api/markets (Hypothetical Endpoint) ### Description Sets the start time for the event associated with the market. This is an optional field. ### Method POST (Hypothetical) ### Endpoint /api/markets ### Parameters #### Request Body - **event_start_time** (string) - Optional - ISO 8601 format timestamp of the event start time. ### Request Example ```json { "event_start_time": "2023-10-28T14:30:00Z" } ``` ### Response #### Success Response (200) - **market_id** (string) - The ID of the created or updated market. #### Response Example ```json { "market_id": "market_abc123" } ``` ``` -------------------------------- ### TryFrom Implementations for Decimal Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.Decimal.html Demonstrates how to attempt conversion from various types into a Decimal, including error handling. ```APIDOC ## TryFrom Implementations for Decimal ### `impl TryFrom<&str> for Decimal` Try to convert a `&str` into a `Decimal`. Can fail if the value is out of range for `Decimal`. #### `type Error = Error` The type returned in the event of a conversion error. #### `fn try_from(t: &str) -> Result` Performs the conversion. ### `impl TryFrom for TickSize` #### `type Error = Error` The type returned in the event of a conversion error. #### `fn try_from(value: Decimal) -> Result` Performs the conversion. ### `impl TryFrom for u16` Try to convert a `Decimal` to `u16` by truncating and returning the integer component. Can fail if the `Decimal` is out of range for `u16`. #### `type Error = Error` The type returned in the event of a conversion error. #### `fn try_from(t: Decimal) -> Result` Performs the conversion. ### `impl TryFrom for Decimal` Try to convert a `f32` into a `Decimal`. Can fail if the value is out of range for `Decimal`. #### `type Error = Error` The type returned in the event of a conversion error. #### `fn try_from(t: f32) -> Result` Performs the conversion. ### `impl TryFrom for Decimal` Try to convert a `f64` into a `Decimal`. Can fail if the value is out of range for `Decimal`. #### `type Error = Error` The type returned in the event of a conversion error. #### `fn try_from(t: f64) -> Result` Performs the conversion. ``` -------------------------------- ### Fetch User Positions using Data API Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/index.html This example shows how to retrieve a user's open positions using the Data API. Ensure the `data` feature is enabled for the SDK. Replace the placeholder address with the target user's address. ```rust use polymarket_client_sdk::data::Client; use polymarket_client_sdk::data::types::request::PositionsRequest; use polymarket_client_sdk::types::address; #[tokio::main] async fn main() -> anyhow::Result<()> { let client = Client::default(); let user = address!("0x0000000000000000000000000000000000000000"); let request = PositionsRequest::builder().user(user).limit(10)?.build(); let positions = client.positions(&request).await?; println!("Open positions: {:?}", positions); Ok(()) } ``` -------------------------------- ### Set Start Date for RewardsConfigBuilder Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/types/response/struct.RewardsConfigBuilder.html Sets the start date for the RewardsConfig. This is a required field. The state S::StartDate must be IsUnset. ```rust pub fn start_date( self, value: NaiveDate, ) -> RewardsConfigBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### Create BestBidAsk Instance with Builder Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/ws/types/response/struct.BestBidAsk.html Demonstrates how to create an instance of the BestBidAsk struct using the builder pattern. This is the recommended way to construct the struct due to its non-exhaustive nature. ```rust pub fn builder() -> BestBidAskBuilder ``` -------------------------------- ### LocalSigner - Signing and Verifying a Message Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/auth/struct.LocalSigner.html Demonstrates how to use LocalSigner to sign a message and verify the signature using the signer's address. It also shows how to set a chain ID for EIP-155 replay protection and that the signer is cloneable. ```APIDOC ## Signing and Verifying a message The signer can be used to produce ECDSA `Signature` objects, which can be then verified. Note that this uses `eip191_hash_message` under the hood which will prefix the message being hashed with the `Ethereum Signed Message` domain separator. ```rust use alloy_signer::{Signer, SignerSync}; use alloy_signer_local::PrivateKeySigner; let signer = PrivateKeySigner::random(); // Optionally, the signer's chain id can be set, in order to use EIP-155 // replay protection with different chains let signer = signer.with_chain_id(Some(1337)); // The signer can be used to sign messages let message = b"hello"; let signature = signer.sign_message_sync(message)?; assert_eq!(signature.recover_address_from_msg(&message[..]).unwrap(), signer.address()); // LocalSigner is cloneable: let signer_clone = signer.clone(); let signature2 = signer_clone.sign_message_sync(message)?; assert_eq!(signature, signature2); ``` ``` -------------------------------- ### ChatBuilder maybe_start_time() Method Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.ChatBuilder.html Sets an optional start time for the chat using an `Option>`. This provides flexibility for defining the start time. ```rust pub fn maybe_start_time( self, value: Option>, ) -> ChatBuilder> where S::StartTime: IsUnset, ``` -------------------------------- ### Initialize CTF Client and Calculate Condition ID Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/ctf/index.html Demonstrates how to set up the CTF client with a Polygon provider and calculate a condition ID using provided details. Requires a wallet for state-changing operations. ```rust use polymarket_client_sdk::ctf::{Client, types::*}; use polymarket_client_sdk::types::address; use polymarket_client_sdk::POLYGON; use alloy::providers::ProviderBuilder; use alloy::primitives::{B256, U256}; // Create a provider (requires a wallet for state-changing operations) let provider = ProviderBuilder::new() .connect("https://polygon-rpc.com") .await?; let client = Client::new(provider, POLYGON)?; let condition_id_req = ConditionIdRequest::builder() .oracle(address!("")) .question_id(B256::default()) .outcome_slot_count(U256::from(2)) .build(); let condition_id = client.condition_id(&condition_id_req).await?; println!("Condition ID: {}", condition_id.condition_id); ``` -------------------------------- ### Start SubscriptionManager Reconnection Handler Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/ws/subscription/struct.SubscriptionManager.html Starts a background task for the SubscriptionManager to handle reconnections. This ensures subscriptions are re-established automatically upon connection recovery. ```rust pub fn start_reconnection_handler(self: &Arc) ``` -------------------------------- ### Set Event Start Date with Option Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.EventBuilder.html Sets an optional start date for the event using `Option>`. The state `S::StartDate` must be `IsUnset`. ```rust pub fn maybe_start_date( self, value: Option>, ) -> EventBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### HTTP Method Usage Example Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/error/struct.Method.html Demonstrates basic usage of the `Method` enum, including conversion from bytes, checking idempotency, and retrieving the string representation. Ensure the `http` crate is available. ```rust use http::Method; assert_eq!(Method::GET, Method::from_bytes(b"GET").unwrap()); assert!(Method::GET.is_idempotent()); assert_eq!(Method::POST.as_str(), "POST"); ``` -------------------------------- ### MarketBuilder Set Start Date (DateTime) Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.MarketBuilder.html Sets the optional start date for the Market using a DateTime type. The state S::StartDate must be IsUnset. ```rust pub fn start_date(self, value: DateTime) -> MarketBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### Builder-Authenticated Client for Remote Signing Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/index.html This example demonstrates setting up a client for institutional or third-party app integrations using remote signing. Configure the `BuilderConfig` with your signing server's URL. ```rust use std::str::FromStr as _; use alloy::signers::Signer as _; use alloy::signers::local::LocalSigner; use polymarket_client_sdk::auth::builder::Config as BuilderConfig; use polymarket_client_sdk::{POLYGON, PRIVATE_KEY_VAR}; use polymarket_client_sdk::clob::{Client, Config}; use polymarket_client_sdk::clob::types::SignatureType; use polymarket_client_sdk::clob::types::request::TradesRequest; #[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 builder_config = BuilderConfig::remote("http://localhost:3000/sign", None)?; let client = Client::new("https://clob.polymarket.com", Config::default())? .authentication_builder(&signer) .signature_type(SignatureType::Proxy) .authenticate() .await?; let client = client.promote_to_builder(builder_config).await?; let ok = client.ok().await?; println!("Ok: {ok}"); let api_keys = client.api_keys().await?; println!("API keys: {api_keys:?}"); let builder_trades = client.builder_trades(&TradesRequest::default(), None).await?; println!("Builder trades: {builder_trades:?}"); Ok(()) } ``` -------------------------------- ### Add polymarket-client-sdk using cargo add Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/index.html Alternatively, use the `cargo add` command to include the SDK in your Cargo.toml. ```bash cargo add polymarket-client-sdk ``` -------------------------------- ### Get Deposit/Withdrawal Quote Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/bridge/client/struct.Client.html Get an estimated quote for a deposit or withdrawal. This includes output amounts, checkout time, and a detailed fee breakdown. Requires a `QuoteRequest` object. ```rust use polymarket_client_sdk::bridge::{Client, types::QuoteRequest}; let client = Client::default(); // let request = QuoteRequest::builder()...build(); // let response = client.quote(&request).await?; ``` -------------------------------- ### Create Value Instance with Builder Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/response/struct.Value.html Demonstrates how to create an instance of the Value struct using a builder pattern. This is the recommended way to construct Value objects. ```rust pub fn builder() -> ValueBuilder ``` -------------------------------- ### MarketBuilder Set Start Date (Option>) Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/response/struct.MarketBuilder.html Sets the optional start date for the Market using an Option> type. The state S::StartDate must be IsUnset. ```rust pub fn maybe_start_date( self, value: Option>, ) -> MarketBuilder> where S::StartDate: IsUnset, ``` -------------------------------- ### Client Initialization and Authentication Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/client/struct.Client.html Provides details on creating an unauthenticated client and upgrading it to an authenticated client using a signer. ```APIDOC ## POST /api/users ### Description Creates a new unauthenticated CLOB client. This client can access public API endpoints like market data, prices, and orderbooks. To place orders or access user-specific endpoints, use `Self::authentication_builder` to upgrade to an authenticated client. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **host** (string) - Required - The CLOB API URL (e.g., https://clob.polymarket.com) - **config** (object) - Required - Client configuration options ### Request Example ```json { "host": "https://clob.polymarket.com", "config": {} } ``` ### Response #### Success Response (200) - **client** (object) - The newly created unauthenticated client instance. #### Response Example ```json { "client": "" } ``` ## Client Authentication Builder ### Description Creates an authentication builder to upgrade an unauthenticated client to authenticated mode. The builder can be configured with credentials or used to create/derive API keys. Call `AuthenticationBuilder::authenticate` to complete the upgrade. ### Method POST ### Endpoint /api/authenticate ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **signer** (object) - Required - A wallet signer used to generate authentication signatures ### Request Example ```json { "signer": "" } ``` ### Response #### Success Response (200) - **authentication_builder** (object) - An instance of `AuthenticationBuilder`. #### Response Example ```json { "authentication_builder": "" } ``` ## Authenticate Client ### Description Completes the client authentication process by calling `authenticate` on the `AuthenticationBuilder`. ### Method POST ### Endpoint /api/authenticate/complete ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **authentication_builder** (object) - Required - The `AuthenticationBuilder` instance obtained from `authentication_builder`. ### Request Example ```json { "authentication_builder": "" } ``` ### Response #### Success Response (200) - **authenticated_client** (object) - The authenticated client instance. #### Response Example ```json { "authenticated_client": "" } ``` ``` -------------------------------- ### Initialize RewardsBuilder Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/types/response/struct.RewardsBuilder.html Use builder syntax to set the inputs and finish with build(). ```rust pub struct RewardsBuilder { /* private fields */ } ``` -------------------------------- ### Initialize Polymarket Bridge Client Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/bridge/client/struct.Client.html Create a new Bridge API client. Use `Client::default()` for the default host or `Client::new()` with a custom host URL. Ensure the host URL is valid. ```rust use polymarket_client_sdk::bridge::Client; let client = Client::default(); ``` -------------------------------- ### GET /all_prices Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/clob/client/struct.Client.html Retrieves prices for all available market outcome tokens. Returns the current best bid and ask prices for every active token in the system. This is useful for getting a complete market overview. ```APIDOC ## GET /all_prices ### Description Retrieves prices for all available market outcome tokens. Returns the current best bid and ask prices for every active token in the system. This is useful for getting a complete market overview. ### Method GET ### Endpoint /all_prices ### Response #### Success Response (200) - **prices** (array of AllPrices) - A list of all available market outcome tokens with their best bid and ask prices. #### Response Example ```json { "prices": [ { "token_id": "0xabc...", "bid_price": "1.4900", "ask_price": "1.5100" }, { "token_id": "0xdef...", "bid_price": "0.9400", "ask_price": "0.9600" } ] } ``` ### Errors - Returns an error if the request fails. ``` -------------------------------- ### Type Conversions (TryFrom and TryInto) Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/gamma/types/request/struct.PublicProfileRequest.html Demonstrates how to perform type conversions using the TryFrom and TryInto traits, including error handling. ```APIDOC ## Type Conversions (TryFrom and TryInto) ### Description Provides mechanisms for attempting conversions between types, returning a `Result` to handle potential errors. ### TryFrom Trait #### `impl TryFrom for T where U: Into` - **Type `Error`**: `Infallible` - The type returned in the event of a conversion error. This indicates that conversions using this specific `impl` are infallible. - **Function `try_from(value: U) -> Result>::Error>`**: Performs the conversion from type `U` to type `T`. ### TryInto Trait #### `impl TryInto for T where U: TryFrom` - **Type `Error`**: `>::Error` - The type returned in the event of a conversion error. This error type is determined by the `TryFrom` implementation for the target type `U`. - **Function `try_into(self) -> Result>::Error>`**: Performs the conversion from type `T` to type `U`. ``` -------------------------------- ### Type ID Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.Utc.html Gets the `TypeId` of an object. ```APIDOC ## GET /api/type_id ### Description Gets the `TypeId` of `self`. ### Method GET ### Endpoint /api/type_id ### Response #### Success Response (200) - **type_id** (TypeId) - The TypeId of the object. #### Response Example ```json { "type_id": "some_type_id" } ``` ``` -------------------------------- ### Create Trade Filters with TradeFilter Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/struct.TradeFilter.html Examples demonstrating how to create TradeFilter instances for filtering trades by a minimum USDC value or token quantity. Ensure that the amount provided is non-negative to avoid errors. ```rust use polymarket_client_sdk::data::types::TradeFilter; use rust_decimal_macros::dec; // Filter trades with at least $100 USDC value let filter = TradeFilter::cash(dec!(100)).unwrap(); // Filter trades with at least 50 tokens let filter = TradeFilter::tokens(dec!(50)).unwrap(); ``` -------------------------------- ### type_id Function Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/ctf/client/IConditionalTokens/struct.getPositionIdCall.html Gets the TypeId of the getPositionIdCall. ```rust fn type_id(&self) -> TypeId; ``` -------------------------------- ### Create MetaHolder Instance with Builder Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/data/types/response/struct.MetaHolder.html Demonstrates how to create an instance of MetaHolder using the builder pattern. This is the recommended way to construct MetaHolder objects. ```rust pub fn builder() -> MetaHolderBuilder ``` -------------------------------- ### Get Mantissa Source: https://docs.rs/polymarket-client-sdk/latest/polymarket_client_sdk/types/struct.Decimal.html Returns the mantissa of the decimal number. ```APIDOC ## POST /api/products ### Description Adds a new product to the catalog. ### Method POST ### Endpoint /api/products ### Parameters #### Request Body - **name** (string) - Required - The name of the product. - **price** (number) - Required - The price of the product. - **category** (string) - Required - The category the product belongs to. ### Request Example ```json { "name": "USB-C Hub", "price": 39.99, "category": "Accessories" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created product. - **name** (string) - The name of the product. - **price** (number) - The price of the product. - **category** (string) - The category the product belongs to. #### Response Example ```json { "id": "prod_ghi789", "name": "USB-C Hub", "price": 39.99, "category": "Accessories" } ``` ```