how would I build a dedicated execution module for polymarket in Rust which I would be…
- User
how would I build a dedicated execution module for polymarket in Rust which I would be able to use in all of my strategies
Assistant
how would I build a dedicated execution module for polymarket in Rust which I would be able to use in all of my strategies
To build a dedicated execution module for Polymarket in Rust, you'll want to create a modular library that handles order placement, position management, and interaction with Polymarket's infrastructure. Here's how to structure it:
Your execution module should have these main components:
1. Client Layer
pub struct PolymarketExecutor {
http_client: reqwest::Client,
ws_client: Option<WebSocketClient>,
signer: EthereumSigner,
config: ExecutorConfig,
}
pub struct ExecutorConfig {
api_key: String,
private_key: String,
network: Network,
max_retries: u32,
timeout: Duration,
}
2. Order Types and Models
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Order {
pub market_id: String,
pub outcome: Outcome,
pub side: OrderSide,
pub size: Decimal,
pub price: Decimal,
pub order_type: OrderType,
}
pub enum OrderType {
Limit,
Market,
PostOnly,
}
pub enum OrderSide {
Buy,
Sell,
}
3. Core Execution Interface
#[async_trait]
pub trait ExecutionEngine {
async fn place_order(&self, order: Order) -> Result<OrderResponse, ExecutionError>;
async fn cancel_order(&self, order_id: &str) -> Result<(), ExecutionError>;
async fn get_position(&self, market_id: &str) -> Result<Position, ExecutionError>;
async fn get_open_orders(&self) -> Result<Vec<OpenOrder>, ExecutionError>;
}
Order Signing and Submission
impl PolymarketExecutor {
pub async fn place_order(&self, order: Order) -> Result<OrderResponse, ExecutionError> {
// Build order payload
let order_payload = self.build_order_payload(&order)?;
// Sign the order
let signature = self.signer.sign_order(&order_payload)?;
// Submit with retry logic
let response = self.submit_with_retry(order_payload, signature).await?;
// Parse and validate response
self.parse_order_response(response)
}
async fn submit_with_retry(&self, payload: OrderPayload, signature: Signature)
-> Result<Response, ExecutionError> {
let mut attempts = 0;
loop {
match self.http_client
.post(&self.build_url("/orders"))
.json(&payload)
.header("Authorization", &self.config.api_key)
.header("X-Signature", signature.to_string())
.send()
.await
{
Ok(resp) if resp.status().is_success() => return Ok(resp),
Ok(resp) if resp.status() == 429 => {
// Rate limited - implement exponential backoff
let delay = Duration::from_millis(100 * 2_u64.pow(attempts));
tokio::time::sleep(delay).await;
}
Err(e) if attempts < self.config.max_retries => {
attempts += 1;
continue;
}
Err(e) => return Err(ExecutionError::NetworkError(e)),
Ok(resp) => return Err(ExecutionError::ApiError(resp.status())),
}
}
}
}
Position and Risk Management
pub struct PositionManager {
executor: Arc<PolymarketExecutor>,
positions: DashMap<String, Position>,
}
impl PositionManager {
pub async fn update_position(&self, market_id: &str, delta: Decimal)
-> Result<(), ExecutionError> {
let current = self.get_position(market_id).await?;
let target = current.size + delta;
if target > self.max_position_size(market_id) {
return Err(ExecutionError::PositionLimitExceeded);
}
let order = self.build_order(market_id, delta)?;
self.executor.place_order(order).await?;
Ok(())
}
}
WebSocket Integration for Real-time Updates
pub struct WebSocketManager {
url: String,
subscriptions: Arc<RwLock<HashMap<String, mpsc::Sender<MarketUpdate>>>>,
}
impl WebSocketManager {
pub async fn subscribe_to_orders(&self, tx: mpsc::Sender<OrderUpdate>)
-> Result<(), ExecutionError> {
let (ws_stream, _) = connect_async(&self.url).await?;
let (write, read) = ws_stream.split();
// Send subscription message
let sub_msg = json!({
"type": "subscribe",
"channel": "orders",
"auth": self.generate_auth_token()?
});
write.send(Message::Text(sub_msg.to_string())).await?;
// Handle incoming messages
tokio::spawn(async move {
read.for_each(|msg| async {
if let Ok(Message::Text(text)) = msg {
if let Ok(update) = serde_json::from_str::<OrderUpdate>(&text) {
let _ = tx.send(update).await;
}
}
}).await;
});
Ok(())
}
}
Create a trait that your strategies can implement:
#[async_trait]
pub trait TradingStrategy {
async fn generate_signals(&mut self, market_data: &MarketData) -> Vec<Signal>;
async fn execute_signals(&self, signals: Vec<Signal>, executor: &PolymarketExecutor)
-> Result<Vec<OrderResponse>, ExecutionError>;
}
// Example usage in a strategy
pub struct MyArbitrageStrategy {
executor: Arc<PolymarketExecutor>,
position_manager: PositionManager,
}
impl MyArbitrageStrategy {
pub async fn run(&mut self) -> Result<(), Box<dyn Error>> {
let signals = self.generate_signals(&market_data).await;
for signal in signals {
let order = Order {
market_id: signal.market_id,
outcome: signal.outcome,
side: signal.side,
size: self.calculate_size(&signal),
price: signal.price,
order_type: OrderType::Limit,
};
match self.executor.place_order(order).await {
Ok(response) => log::info!("Order placed: {:?}", response),
Err(e) => log::error!("Order failed: {:?}", e),
}
}
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
pub enum ExecutionError {
#[error("Network error: {0}")]
NetworkError(#[from] reqwest::Error),
#[error("Invalid order: {0}")]
InvalidOrder(String),
#[error("Insufficient balance")]
InsufficientBalance,
#[error("Rate limited")]
RateLimited,
#[error("Position limit exceeded")]
PositionLimitExceeded,
}
pub struct ExecutionMetrics {
orders_placed: Counter,
orders_failed: Counter,
latency_histogram: Histogram,
}
[dependencies]
tokio = { version = "1.35", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
ethers = "2.0"
rust_decimal = "1.33"
async-trait = "0.1"
thiserror = "1.0"
dashmap = "5.5"
tokio-tungstenite = "0.21"
log = "0.4"
prometheus = "0.13"
This modular design allows you to:
The key is keeping the execution logic separate from strategy logic, making it reusable across all your trading strategies.