### Rust: Quick Start Example - Fetching Markets Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-opinion/README.md This Rust code demonstrates a quick start example for using the Opinion exchange integration. It shows how to initialize the Opinion exchange client with default configuration and fetch the first five available markets, printing their questions and prices. It relies on the 'drm-core' and 'drm-exchange-opinion' crates. ```rust use drm_core::Exchange; use drm_exchange_opinion::{Opinion, OpinionConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Public API (no auth required) let exchange = Opinion::with_default_config()?; // Fetch markets let markets = exchange.fetch_markets(None).await?; for market in markets.iter().take(5) { println!("{}: {{:?}}", market.question, market.prices); } Ok(()) } ``` -------------------------------- ### Run Example Binaries (Bash) Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md Instructions for executing the example binaries provided within the Rust project. This includes listing markets from Polymarket and watching orderbook updates. Assumes Cargo is installed and the project is cloned. ```bash # List markets from Polymarket cargo run --bin list-markets # Watch orderbook updates cargo run --bin watch-orderbook ``` -------------------------------- ### Rust: Quick Start - Fetch Markets from Limitless Exchange Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-limitless/README.md Demonstrates how to initialize the Limitless exchange client with default configuration and fetch market data. This example uses the `drm_core::Exchange` trait and requires the `tokio` runtime. ```rust use drm_core::Exchange; use drm_exchange_limitless::{Limitless, LimitlessConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Public API (no auth required) let exchange = Limitless::with_default_config()?; // Fetch markets let markets = exchange.fetch_markets(None).await?; for market in markets.iter().take(5) { println!("{}: {{:?}}", market.question, market.prices); } Ok(()) } ``` -------------------------------- ### Rust: Quick Start with Polymarket Public API Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-polymarket/README.md Demonstrates a quick start for using the Polymarket exchange with its public API in Rust. It initializes the Polymarket client without authentication and fetches the first five markets, printing their questions and prices. ```rust use drm_core::Exchange; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Public API (no auth required) let exchange = Polymarket::with_default_config()?; // Fetch markets let markets = exchange.fetch_markets(None).await?; for market in markets.iter().take(5) { println!("{}: {{:?}}", market.question, market.prices); } Ok(()) } ``` -------------------------------- ### Fetch and Display Markets using Polymarket API (Rust) Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md Demonstrates how to initialize the Polymarket exchange client and fetch the first five markets, printing their question and prices. This example uses the `drm_core::Exchange` trait and `drm_exchange_polymarket` crate. ```rust use drm_core::Exchange; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let exchange = Polymarket::with_default_config()?; let markets = exchange.fetch_markets(None).await?; for market in markets.iter().take(5) { println!("{}: {{:?}}", market.question, market.prices); } Ok(()) } ``` -------------------------------- ### Configure Kalshi Exchange Client (Rust) Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md Provides examples for configuring the Kalshi exchange client, including connections to the production API, demo environment, and using a PEM string directly for the private key. Depends on the `drm_exchange_kalshi` crate. ```rust use drm_exchange_kalshi::{Kalshi, KalshiConfig}; // Production API let config = KalshiConfig::new("your-api-key-id", "/path/to/private-key.pem"); let exchange = Kalshi::new(config)?; // Demo environment let config = KalshiConfig::demo("your-api-key-id", "/path/to/private-key.pem"); let exchange = Kalshi::new(config)?; // With PEM string directly let config = KalshiConfig::new("your-api-key-id", "") .with_private_key_pem("-----BEGIN PRIVATE KEY-----\n..."); let exchange = Kalshi::new(config)?; ``` -------------------------------- ### Fetch Single Market - Kalshi (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Retrieves detailed information for a specific prediction market on Kalshi using its unique identifier. This example shows how to initialize the Kalshi exchange with API credentials and access market details such as question, outcomes, description, and close time. Requires the `drm-core` and `drm-exchange-kalshi` crates. ```rust use drm_core::Exchange; use drm_exchange_kalshi::{Kalshi, KalshiConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Initialize Kalshi with credentials let config = KalshiConfig::new("your-api-key-id", "/path/to/private-key.pem"); let exchange = Kalshi::new(config)?; // Fetch specific market by ID let market_id = "KXBTCY-23DEC31-T49000"; let market = exchange.fetch_market(market_id).await?; println!("Question: {}", market.question); println!("Outcomes: {:?}", market.outcomes); println!("Description: {}", market.description); // Access market metadata if let Some(close_time) = market.close_time { println!("Closes at: {}", close_time); } Ok(()) } ``` -------------------------------- ### Rust: Configure Kalshi Exchange with API Key and Private Key Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-kalshi/README.md Shows two methods for configuring the Kalshi exchange client for authenticated access: loading the private key from a file path or directly from a PEM-formatted string. Both methods require an API key ID and utilize the `KalshiConfig` struct. This setup is necessary for actions like creating orders or fetching positions. ```rust use drm_exchange_kalshi::{Kalshi, KalshiConfig}; // From file path let config = KalshiConfig::new() .with_api_key_id("your-api-key-id") .with_private_key_path("/path/to/kalshi_private_key.pem"); // Or from PEM string let config = KalshiConfig::new() .with_api_key_id("your-api-key-id") .with_private_key_pem(include_str!("../kalshi_private_key.pem")); let exchange = Kalshi::new(config)?; // Now you can create orders, fetch positions, etc. ``` -------------------------------- ### Rust: Create a Limit Buy Order on Kalshi Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-kalshi/README.md Demonstrates how to create a limit order to buy a specific number of contracts for a market at a specified price. This example shows creating an order to buy 'Yes' outcome for a market identified by its ticker, at a price of $0.55 for 10 contracts. It requires an authenticated exchange client and uses `drm_core` for `OrderSide` and `Exchange` traits. ```rust use drm_core::{Exchange, OrderSide}; use std::collections::HashMap; // Create a limit order to buy Yes at $0.55 let order = exchange.create_order( "INXD-24DEC31-B5000", // ticker "Yes", // outcome (Yes or No) OrderSide::Buy, // action 0.55, // price in decimal (55 cents) 10.0, // size (number of contracts) HashMap::new(), ).await?; ``` -------------------------------- ### Rust: Polymarket Authentication with Private Key Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-polymarket/README.md Illustrates how to configure and authenticate with the Polymarket exchange using an Ethereum private key and funder address in Rust. This setup is necessary for performing trading operations. ```rust use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; let config = PolymarketConfig::new() .with_private_key("0x...") .with_funder("0x..."); let exchange = Polymarket::new(config)?; exchange.init_trading().await?; // Now you can create orders, cancel orders, etc. ``` -------------------------------- ### Rust: Install drm-exchange-polymarket Dependency Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-polymarket/README.md This snippet shows how to add the drm-exchange-polymarket crate as a dependency to your Rust project using Cargo.toml. It specifies the version of the crate to be used in the project. ```toml [dependencies] drm-exchange-polymarket = "0.1" ``` -------------------------------- ### Rust: Initialize Kalshi Exchange and Fetch Markets Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-kalshi/README.md Demonstrates how to initialize the Kalshi exchange using default public API configuration and fetch a list of available markets. It iterates through the first five markets and prints their question and prices. This snippet requires the `drm-core` and `drm-exchange-kalshi` crates. ```rust use drm_core::Exchange; use drm_exchange_kalshi::{Kalshi, KalshiConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Public API (limited endpoints) let exchange = Kalshi::with_default_config()?; // Fetch markets let markets = exchange.fetch_markets(None).await?; for market in markets.iter().take(5) { println!("{}: {{:?}}", market.question, market.prices); } Ok(()) } ``` -------------------------------- ### Build, Test, and Format Rust Project (Bash) Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md A set of common development commands for Rust projects using Cargo. These include building all crates, running unit tests, linting with clippy, and formatting the code. ```bash # Build all crates carpenter build # Run tests cargo test # Run clippy cargo clippy # Format code cargo fmt ``` -------------------------------- ### Rust: Configure Kalshi Exchange for Demo Environment Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-kalshi/README.md Illustrates how to configure the `Kalshi` exchange client specifically for the demo environment. This involves using the `KalshiConfig::demo()` constructor and providing the necessary API key ID and private key path for the demo account. This is useful for testing authenticated actions without using real funds. ```rust use drm_exchange_kalshi::{Kalshi, KalshiConfig}; let config = KalshiConfig::demo() .with_api_key_id("demo-api-key-id") .with_private_key_path("/path/to/demo_private_key.pem"); let exchange = Kalshi::new(config)?; ``` -------------------------------- ### Implement Trading Strategy in Rust Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Demonstrates how to create and run an automated trading strategy using the `Strategy` trait and `BaseStrategy` helper. It configures the strategy with tick interval, max position size, spread, and verbosity. The strategy loop fetches account state, calculates order prices and sizes based on a mid-price, and places buy/sell orders if within risk limits, after canceling existing orders. Dependencies include `drm_core` and `drm_exchange_polymarket`. Inputs are strategy configurations and market data, output is executed trades and logs. ```rust use drm_core::{Exchange, OrderSide, Strategy, BaseStrategy, StrategyConfig}; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; use std::sync::Arc; #[tokio::main] async fn main() -> anyhow::Result<()> { // Setup exchange let config = PolymarketConfig::new() .with_private_key("0xYOUR_PRIVATE_KEY"); let exchange = Arc::new(Polymarket::new(config)?); // Configure strategy let strategy_config = StrategyConfig { tick_interval_ms: 2000, max_position_size: 100.0, spread_bps: 50, // 0.5% spread verbose: true, }; // Create strategy let market_id = "market-condition-id".to_string(); let mut strategy = BaseStrategy::new( exchange.clone(), market_id, strategy_config ); // Run strategy loop strategy.run_loop(|strat| async move { // Get current state let account = strat.get_account_state().await?; let net_position = strat.get_net_position(); strat.log(&format!("Net position: {:.2}", net_position)); // Calculate order prices let mid_price = 0.50; // Get from orderbook let (bid, ask) = strat.calculate_spread_prices(mid_price, 50); let size = strat.calculate_order_size(mid_price, 1000.0); // Place orders if within risk limits if net_position.abs() < 100.0 { // Cancel old orders strat.cancel_all_orders().await?; // Place new orders if let Some(market) = &strat.market { let outcome = &market.outcomes[0]; strat.place_order(outcome, OrderSide::Buy, bid, size, None).await?; strat.place_order(outcome, OrderSide::Sell, ask, size, None).await?; } } Ok(()) }).await?; Ok(()) } ``` -------------------------------- ### Configure Polymarket Exchange Client (Rust) Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md Shows how to configure the Polymarket exchange client, including options for public access (no authentication) and authenticated access using a private key and funder address. Requires `drm_exchange_polymarket`. ```rust use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; // Public API (no auth required) let exchange = Polymarket::with_default_config()?; // Authenticated (for trading) let config = PolymarketConfig::new() .with_private_key("0x...") .with_funder("0x..."); let exchange = Polymarket::new(config)?; exchange.init_trading().await?; ``` -------------------------------- ### Rust: Add drm-core Dependency Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-core/README.md This snippet shows how to add the `drm-core` crate as a dependency in a Rust project's `Cargo.toml` file. It specifies the version to be used, ensuring compatibility and allowing access to the core functionalities. ```toml [dependencies] drm-core = "0.1" ``` -------------------------------- ### Bash: Generate RSA Private and Public Keys for Kalshi Authentication Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-kalshi/README.md Provides bash commands to generate an RSA private key in PEM format and then extract the corresponding public key. The private key is used for signing requests, and the public key needs to be uploaded to Kalshi. This is a prerequisite for authenticated access to the Kalshi API. ```bash # Generate RSA private key openssl genpkey -algorithm RSA -out kalshi_private_key.pem -pkeyopt rsa_keygen_bits:4096 # Extract public key (upload this to Kalshi) openssl rsa -pubout -in kalshi_private_key.pem -out kalshi_public_key.pem ``` -------------------------------- ### Configure Limitless Exchange Client (Rust) Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md Illustrates configuring the Limitless exchange client for both public API access and authenticated trading using a private key. This utilizes the `drm_exchange_limitless` crate. ```rust use drm_exchange_limitless::{Limitless, LimitlessConfig}; // Public API let exchange = Limitless::with_default_config()?; // Authenticated let config = LimitlessConfig::new() .with_private_key("0x..."); let exchange = Limitless::new(config)?; exchange.authenticate().await?; ``` -------------------------------- ### Configure Polymarket Exchange in Rust Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Sets up a Polymarket exchange client with custom configuration, including private key, funder address, verbosity, request timeout, and rate limits. It then retrieves and prints exchange information such as name, ID, and WebSocket/order creation capabilities. Dependencies include `drm_exchange_polymarket` and `std::time::Duration`. Inputs are configuration parameters, and output is printed exchange details. ```rust use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; use std::time::Duration; #[tokio::main] async fn main() -> anyhow::Result<()> { // Custom configuration let config = PolymarketConfig::new() .with_private_key("0xYOUR_PRIVATE_KEY") .with_funder("0xFUNDER_ADDRESS") .with_verbose(true) .with_timeout(Duration::from_secs(60)) .with_rate_limit(5); // 5 requests per second let exchange = Polymarket::new(config)?; // Get exchange info let info = exchange.describe(); println!("Exchange: {} ({})", info.name, info.id); println!("Has WebSocket: {}", info.has_websocket); println!("Can Create Orders: {}", info.has_create_order); Ok(()) } ``` -------------------------------- ### Configure Opinion Exchange Client (Rust) Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md Demonstrates setting up the Opinion exchange client with options for public access or authenticated access using an API key, private key, and multi-sig address. This requires the `drm_exchange_opinion` crate. ```rust use drm_exchange_opinion::{Opinion, OpinionConfig}; // Public API let exchange = Opinion::with_default_config()?; // Authenticated let config = OpinionConfig::new() .with_api_key("your-api-key") .with_private_key("0x...") .with_multi_sig_addr("0x..."); let exchange = Opinion::new(config)?; ``` -------------------------------- ### Rust: Authenticate with Limitless Exchange using Private Key Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-limitless/README.md Shows how to configure the Limitless exchange client with an Ethereum private key for authenticated trading operations. It involves creating a `LimitlessConfig` and calling the `authenticate` method. ```rust use drm_exchange_limitless::{Limitless, LimitlessConfig}; let config = LimitlessConfig::new() .with_private_key("0x..."); let exchange = Limitless::new(config)?; exchange.authenticate().await?; // Now you can create orders, cancel orders, etc. ``` -------------------------------- ### Rust: Opinion Exchange Authentication Configuration Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-opinion/README.md This Rust code illustrates how to configure the Opinion exchange client for trading operations, requiring authentication. It shows setting up an 'OpinionConfig' with an API key, private key, and multi-sig address. The 'Opinion::new' function then creates an authenticated exchange instance. ```rust use drm_exchange_opinion::{Opinion, OpinionConfig}; let config = OpinionConfig::new() .with_api_key("your-api-key") .with_private_key("0x...") .with_multi_sig_addr("0x..."); let exchange = Opinion::new(config)?; // Now you can create orders, cancel orders, etc. ``` -------------------------------- ### Create Order on Polymarket (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Places buy or sell orders on Polymarket with specified market ID, outcome, side, price, and size. Supports optional parameters like token ID and order type (GTC, FOK, IOC). Requires Polymarket API credentials. ```rust use drm_core::{Exchange, OrderSide}; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; use std::collections::HashMap; #[tokio::main] async fn main() -> anyhow::Result<()> { // Initialize with authentication let config = PolymarketConfig::new() .with_private_key("0xYOUR_PRIVATE_KEY") .with_funder("0xFUNDER_ADDRESS"); let exchange = Polymarket::new(config)?; // Initialize trading (derive API credentials) exchange.init_trading().await?; // Prepare order parameters let market_id = "condition-id-here"; let outcome = "Yes"; let side = OrderSide::Buy; let price = 0.55; // 55 cents let size = 10.0; // 10 shares // Optional parameters for order type, token ID, etc. let mut params = HashMap::new(); params.insert("token_id".to_string(), "token-id-here".to_string()); params.insert("order_type".to_string(), "GTC".to_string()); // GTC, FOK, or IOC // Place the order let order = exchange.create_order( market_id, outcome, side, price, size, params ).await?; println!("Order placed: {}", order.id); println!("Status: {:?}", order.status); println!("Filled: {:.2}/{:.2}", order.filled, order.size); println!("Remaining: {:.2}", order.remaining()); Ok(()) } ``` -------------------------------- ### Fetch Markets - Polymarket (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Fetches a list of prediction markets from Polymarket, with optional parameters for filtering by active status and limiting results. It demonstrates iterating through markets, accessing properties like question, volume, and liquidity, and checking market status. Requires the `drm-core` and `drm-exchange-polymarket` crates. ```rust use drm_core::Exchange; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Initialize exchange with default config let exchange = Polymarket::with_default_config()?; // Fetch markets with parameters let markets = exchange.fetch_markets(Some(drm_core::FetchMarketsParams { limit: Some(10), active_only: true, })).await?; // Iterate through results for market in markets { println!("Market: {}", market.question); println!("Volume: ${:.0}, Liquidity: ${:.0}", market.volume, market.liquidity); // Check market properties if market.is_binary() && market.is_open() { println!("Binary market currently open for trading"); if let Some(spread) = market.spread() { println!("Spread: {:.4}", spread); } } // Access outcome prices for (outcome, price) in &market.prices { println!("{}: {:.2}ยข", outcome, price * 100.0); } } Ok(()) } ``` -------------------------------- ### Rust: Subscribe to Limitless Exchange Orderbook via WebSocket Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-limitless/README.md Illustrates how to establish a WebSocket connection to the Limitless exchange to stream real-time orderbook updates for a specific market. It utilizes `LimitlessWebSocket` and requires the `WebSocketClient` trait. ```rust use drm_exchange_limitless::LimitlessWebSocket; use drm_core::WebSocketClient; let ws = LimitlessWebSocket::new(); let mut stream = ws.subscribe_orderbook("market_id").await?; while let Some(orderbook) = stream.next().await { println!("Bids: {{:?}}, Asks: {{:?}}", orderbook.bids, orderbook.asks); } ``` -------------------------------- ### Fetch Balance on Opinion (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Retrieves account balance information from the Opinion exchange, typically denominated in USDC for prediction markets. It iterates through the balances and prints the currency and amount. Requires Opinion API and private keys. ```rust use drm_core::Exchange; use drm_exchange_opinion::{Opinion, OpinionConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let config = OpinionConfig::new() .with_api_key("your-api-key") .with_private_key("0xYOUR_PRIVATE_KEY") .with_multi_sig_addr("0xMULTISIG_ADDRESS"); let exchange = Opinion::new(config)?; let balances = exchange.fetch_balance().await?; for (currency, amount) in balances { println!("{}: ${:.2}", currency, amount); } Ok(()) } ``` -------------------------------- ### Search Markets with Filters in Rust Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Searches for prediction markets using a query string, minimum liquidity, market type, and a limit on results. This function is useful for finding specific markets or filtering by criteria like liquidity and market type. It returns a list of matching markets. ```rust use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let exchange = Polymarket::with_default_config()?; // Search markets with filters let markets = exchange.search_markets( Some("bitcoin"), // Query string Some(10000.0), // Min liquidity: $10k Some(true), // Binary markets only Some(20) // Limit results ).await?; for market in markets { println!("Q: {}", market.question); println!("Liquidity: ${:.0}", market.liquidity); if market.is_binary() { if let Some(spread) = market.spread() { println!("Spread: {:.2}%", spread * 100.0); } } } Ok(()) } ``` -------------------------------- ### Fetch Open Orders on Limitless (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Retrieves all currently open orders for the authenticated account on the Limitless exchange. It iterates through the orders and prints details such as ID, market, outcome, side, price, size, and fill percentage. Requires Limitless API credentials. ```rust use drm_core::Exchange; use drm_exchange_limitless::{Limitless, LimitlessConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let config = LimitlessConfig::new() .with_private_key("0xYOUR_PRIVATE_KEY"); let exchange = Limitless::new(config)?; exchange.authenticate().await?; let orders = exchange.fetch_open_orders(None).await?; for order in orders { println!("Order ID: {}", order.id); println!("Market: {}", order.market_id); println!("Outcome: {} | Side: {:?}", order.outcome, order.side); println!("Price: ${:.4} | Size: {:.2}", order.price, order.size); println!("Filled: {:.1}%", order.fill_percentage() * 100.0); println!("Is Active: {}", order.is_active()); println!("--- "); } Ok(()) } ``` -------------------------------- ### Exchange Trait Methods Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md This section details the methods available within the `Exchange` trait for interacting with prediction exchanges. ```APIDOC ## Exchange Trait All exchanges implement the `Exchange` trait, providing a unified interface for interacting with prediction markets. ### Methods - **`id()`**: Returns the unique identifier of the exchange. - **`name()`**: Returns the human-readable name of the exchange. - **`fetch_markets(params: Option)`**: Fetches a list of all available markets on the exchange. - **`fetch_market(market_id: &str)`**: Fetches a specific market by its ID. - **`fetch_markets_by_slug(slug: &str)`**: Fetches markets associated with a given slug. - **`create_order(...)`**: Creates a new order on the exchange. - **`cancel_order(order_id: &str, market_id: Option<&str>)`**: Cancels an existing order. - **`fetch_order(order_id: &str, market_id: Option<&str>)`**: Fetches details of a specific order. - **`fetch_open_orders(params: Option)`**: Fetches a list of all open orders. - **`fetch_positions(market_id: Option<&str>)`**: Fetches current positions held by the user. - **`fetch_balance()`**: Fetches the user's account balance. ### Models - **`Market`**: Represents a prediction market, including question, outcomes, prices, and volume. - **`Order`**: Represents an order, containing details like price, size, status, and timestamps. - **`Position`**: Represents a user's position in a market, including size, average entry price, and current price. - **`Orderbook`**: Represents the order book for a market, detailing bids and asks. ``` -------------------------------- ### Fetch Price History in Rust Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Fetches historical price data for a specific market outcome over a defined time interval. This is useful for analyzing market trends and past performance. It requires a market ID, an optional outcome index, an interval (e.g., hourly), and a lookback period. ```rust use drm_core::PriceHistoryInterval; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let exchange = Polymarket::with_default_config()?; let market_id = "market-condition-id"; let outcome_index = 0; // First outcome // Fetch price history let history = exchange.fetch_price_history( market_id, Some(outcome_index), PriceHistoryInterval::OneHour, Some(24) // Last 24 hours ).await?; println!("Price history ({} points):", history.len()); for point in history { println!("{}: ${:.4}", point.timestamp.format("%Y-%m-%d %H:%M"), point.price); } Ok(()) } ``` -------------------------------- ### Rust: WebSocket Orderbook Streaming from Polymarket Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-polymarket/README.md Shows how to subscribe to real-time order book updates from the Polymarket exchange using WebSockets in Rust. It connects to the WebSocket, subscribes to a specific token ID's order book, and prints incoming bid and ask data. ```rust use drm_exchange_polymarket::PolymarketWebSocket; use drm_core::WebSocketClient; let ws = PolymarketWebSocket::new(); let mut stream = ws.subscribe_orderbook("token_id").await?; while let Some(orderbook) = stream.next().await { println!("Bids: {{:?}}, Asks: {{:?}}", orderbook.bids, orderbook.asks); } ``` -------------------------------- ### Subscribe to WebSocket Orderbook Stream in Rust Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Connects to a WebSocket, subscribes to a specific token, and processes real-time orderbook updates. It prints market ID, best bid/ask, mid-price, spread, and the number of bid/ask levels. Dependencies include `drm_core`, `drm_exchange_polymarket`, and `futures`. Inputs are a token ID, and outputs are printed to the console. Limitations may include network connectivity and token validity. ```rust use drm_core::OrderBookWebSocket; use drm_exchange_polymarket::PolymarketWebSocket; use futures::StreamExt; #[tokio::main] async fn main() -> anyhow::Result<()> { let mut ws = PolymarketWebSocket::new(); // Connect to WebSocket ws.connect().await?; println!("Connected to WebSocket"); // Subscribe to a specific token let token_id = "21742633143463906290569050155826241533067272736897614950488156847949938836455"; ws.subscribe(token_id).await?; println!("Subscribed to token: {}", token_id); // Get orderbook stream let mut stream = ws.orderbook_stream(token_id).await?; // Process orderbook updates while let Some(result) = stream.next().await { let orderbook = result?; println!("Market: {}", orderbook.market_id); // Get best bid and ask if let (Some(bid), Some(ask)) = (orderbook.best_bid(), orderbook.best_ask()) { let mid = orderbook.mid_price().unwrap_or(0.0); let spread = orderbook.spread().unwrap_or(0.0); println!("Best Bid: {:.4} | Best Ask: {:.4}", bid, ask); println!("Mid Price: {:.4} | Spread: {:.4}", mid, spread); } // Access price levels println!("Bids: {} levels | Asks: {} levels", orderbook.bids.len(), orderbook.asks.len()); for level in orderbook.bids.iter().take(5) { println!(" Bid: {:.4} @ {:.0}", level.price, level.size); } } ws.disconnect().await?; Ok(()) } ``` -------------------------------- ### Rust: Add drm-exchange-opinion Dependency Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-exchange-opinion/README.md This snippet shows how to add the 'drm-exchange-opinion' crate as a dependency to your Rust project using Cargo.toml. This is the standard way to include external libraries in Rust projects. ```toml [dependencies] drm-exchange-opinion = "0.1" ``` -------------------------------- ### Fetch Markets by Slug - Polymarket (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Searches for prediction markets on Polymarket associated with a specific event slug or URL. This function demonstrates retrieving markets by slug and accessing their questions and token IDs, including mapping outcomes to token IDs. Requires the `drm-core` and `drm-exchange-polymarket` crates. ```rust use drm_core::Exchange; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let exchange = Polymarket::with_default_config()?; // Can use either slug or full URL let slug = "presidential-election-2024"; // Or: let slug = "https://polymarket.com/event/presidential-election-2024"; let markets = exchange.fetch_markets_by_slug(slug).await?; for market in markets { println!("Market: {}", market.question); println!("Token IDs: {:?}", market.get_token_ids()); // Get outcome-token pairs for outcome_token in market.get_outcome_tokens() { println!("{}: {}", outcome_token.outcome, outcome_token.token_id); } } Ok(()) } ``` -------------------------------- ### Rust: Define Exchange Trait for Prediction Market Operations Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/drm-core/README.md This Rust code defines the `Exchange` trait, which serves as a unified asynchronous interface for all prediction market operations. It includes methods for fetching markets, fetching a specific market, and creating orders. This trait is designed to be implemented by concrete exchange integrations. ```rust use drm_core::{Exchange, Market, Order, OrderSide, DrmError}; // The Exchange trait defines the unified API #[async_trait] pub trait Exchange: Send + Sync { fn id(&self) -> &'static str; fn name(&self) -> &'static str; async fn fetch_markets(&self, params: Option) -> Result, DrmError>; async fn fetch_market(&self, market_id: &str) -> Result; async fn create_order(&self, ...) -> Result; // ... more methods } ``` -------------------------------- ### Rust Exchange Trait Definition Source: https://github.com/gtg7784/dr-manhattan-rust/blob/main/README.md Defines the `Exchange` trait in Rust, which all exchange implementations must adhere to. This trait specifies asynchronous methods for fetching market and order data, creating and canceling orders, and managing positions and balances. It requires implementations to be thread-safe (`Send + Sync`). ```rust pub trait Exchange: Send + Sync { fn id(&self) -> &'static str; fn name(&self) -> &'static str; async fn fetch_markets(&self, params: Option) -> Result, DrmError>; async fn fetch_market(&self, market_id: &str) -> Result; async fn fetch_markets_by_slug(&self, slug: &str) -> Result, DrmError>; async fn create_order(&self, market_id: &str, outcome: &str, side: OrderSide, price: f64, size: f64, params: HashMap) -> Result; async fn cancel_order(&self, order_id: &str, market_id: Option<&str>) -> Result; async fn fetch_order(&self, order_id: &str, market_id: Option<&str>) -> Result; async fn fetch_open_orders(&self, params: Option) -> Result, DrmError>; async fn fetch_positions(&self, market_id: Option<&str>) -> Result, DrmError>; async fn fetch_balance(&self) -> Result, DrmError>; } ``` -------------------------------- ### Fetch Positions on Polymarket (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Queries current positions held in a specific market or across all markets on Polymarket. It displays details for each position including outcome, size, average price, current price, cost basis, current value, and P&L. Requires Polymarket API credentials. ```rust use drm_core::Exchange; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let config = PolymarketConfig::new() .with_private_key("0xYOUR_PRIVATE_KEY"); let exchange = Polymarket::new(config)?; exchange.init_trading().await?; // Fetch positions for specific market let market_id = "market-condition-id"; let positions = exchange.fetch_positions(Some(market_id)).await?; for position in positions { println!("Outcome: {}", position.outcome); println!("Size: {:.2} shares", position.size); println!("Avg Price: ${:.4}", position.average_price); println!("Current Price: ${:.4}", position.current_price); println!("Cost Basis: ${:.2}", position.cost_basis()); println!("Current Value: ${:.2}", position.current_value()); println!("Unrealized P&L: ${:.2} ({:.1}%)", position.unrealized_pnl(), position.unrealized_pnl_percent()); println!("--- "); } Ok(()) } ``` -------------------------------- ### Cancel Order on Polymarket (Rust) Source: https://context7.com/gtg7784/dr-manhattan-rust/llms.txt Cancels an existing open order on Polymarket using its unique order ID. The market ID can optionally be provided. Requires Polymarket API credentials. ```rust use drm_core::Exchange; use drm_exchange_polymarket::{Polymarket, PolymarketConfig}; #[tokio::main] async fn main() -> anyhow::Result<()> { let config = PolymarketConfig::new() .with_private_key("0xYOUR_PRIVATE_KEY"); let exchange = Polymarket::new(config)?; exchange.init_trading().await?; let order_id = "order-id-to-cancel"; let market_id = Some("market-id"); // Optional for some exchanges let cancelled_order = exchange.cancel_order(order_id, market_id).await?; println!("Cancelled order: {}", cancelled_order.id); println!("Status: {:?}", cancelled_order.status); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.