A Rust-based account monitor for tracking trading status on Polymarket. This tool allows you to monitor a target account's positions, trades, and overall trading activity in real-time.
- 📊 Real-time Position Monitoring: Track open positions and their current values
- 📈 Trade History: Monitor recent trades and trading activity
- 🔄 Automatic Updates: Poll-based monitoring with configurable intervals
- 🦀 Rust Performance: Fast, safe, and efficient monitoring
- 🎯 Easy Integration: Simple API for custom monitoring solutions
- 🛡️ Type-Safe: Full Rust type safety with comprehensive type definitions
- Rust 1.70+ (install from rustup.rs)
- Cargo (comes with Rust)
# Clone the repository
git clone <repository-url>
cd polymarket-account-monitor-rust
# Build the project
cargo build --releaseThe monitor uses Polymarket's public APIs. You may need an API key for certain endpoints (check Polymarket's documentation).
Set environment variables:
# Windows PowerShell
$env:TARGET_ADDRESS="0x..." # The Ethereum address to monitor
$env:POLYMARKET_API_KEY="..." # Optional: API key if required
# Linux/Mac
export TARGET_ADDRESS=0x... # The Ethereum address to monitor
export POLYMARKET_API_KEY=... # Optional: API key if requiredOr create a .env file:
TARGET_ADDRESS=0x...
POLYMARKET_API_KEY=...
# Run with default settings (2 second polling interval)
cargo run -- --target-address 0x1234567890123456789012345678901234567890
# Or use environment variable
TARGET_ADDRESS=0x... cargo run
# Custom polling interval (in milliseconds)
cargo run -- --target-address 0x... --poll-interval 30000
# With API key
cargo run -- --target-address 0x... --api-key your-api-key
# Run release build (faster)
cargo build --release
./target/release/polymarket-monitor --target-address 0x...use polymarket_account_monitor::{AccountMonitor, PolymarketClient, PolymarketConfig, TradingStatus};
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let config = PolymarketConfig {
api_key: Some("your-api-key".to_string()),
..Default::default()
};
let client = PolymarketClient::new(config);
let on_update: Arc<dyn Fn(&TradingStatus) + Send + Sync> = Arc::new(|status: &TradingStatus| {
println!("User: {}", status.user);
println!("Total Positions: {}", status.total_positions);
println!("Total Value: ${}", status.total_value);
println!("Recent Trades: {}", status.recent_trades.len());
});
let monitor = AccountMonitor::new(
client,
polymarket_account_monitor::MonitorOptions {
target_address: "0x...".to_string(),
poll_interval: 30000, // 30 seconds
enable_websocket: false,
on_update: Some(on_update),
on_error: Some(Arc::new(|error: &anyhow::Error| {
eprintln!("Error: {}", error);
})),
},
);
monitor.start().await?;
// Monitor runs until stopped
// monitor.stop();
Ok(())
}Main client for interacting with Polymarket APIs.
PolymarketClient::new(config: PolymarketConfig)-
get_user_positions(user_address: &str) -> Result<UserPositions>- Fetches all open positions for a user
-
get_user_trades(user_address: &str, limit: usize) -> Result<UserTrades>- Fetches trade history for a user
-
get_market(market_id: &str) -> Result<Market>- Fetches market information
Monitors a target account's trading activity.
AccountMonitor::new(client: PolymarketClient, options: MonitorOptions)start() -> Result<()>- Start monitoring (async)stop()- Stop monitoringget_status() -> Result<TradingStatus>- Get current status (async)get_formatted_status(status: &TradingStatus) -> String- Get formatted status stringis_running() -> bool- Check if monitor is running (async)
pub struct TradingStatus {
pub user: String,
pub total_positions: usize,
pub total_value: String,
pub recent_trades: Vec<Trade>,
pub open_positions: Vec<Position>,
pub last_updated: String,
}pub struct Position {
pub id: String,
pub market: Market,
pub outcome: String,
pub quantity: String,
pub price: String,
pub value: String,
pub initial_value: Option<String>,
pub timestamp: String,
}pub struct Trade {
pub id: String,
pub market: Market,
pub outcome: String,
pub side: TradeSide, // Buy or Sell
pub quantity: String,
pub price: String,
pub timestamp: String,
pub transaction_hash: Option<String>,
pub user: String,
}# Build TypeScript
cargo build
# Run in development mode
cargo run -- --target-address 0x...
# Run with debug output
RUST_LOG=debug cargo run -- --target-address 0x...
# Run tests
cargo test
# Check for issues
cargo clippy
# Format code
cargo fmtpolymarket-account-monitor-rust/
├── src/
│ ├── api/
│ │ ├── mod.rs
│ │ └── polymarket_client.rs # API client for Polymarket
│ ├── monitor/
│ │ ├── mod.rs
│ │ └── account_monitor.rs # Main monitor class
│ ├── types.rs # Rust type definitions
│ ├── lib.rs # Library entry point
│ └── main.rs # CLI entry point
├── Cargo.toml # Rust dependencies
├── .gitignore
└── README.md
This monitor uses Polymarket's public APIs:
- Data API: For fetching user positions and trade history
- Gamma API: For market discovery and metadata
- CLOB API: For real-time prices and order books
For more information, visit Polymarket Developer Documentation.
- The monitor uses polling by default. WebSocket support can be added for real-time updates.
- API endpoints may require authentication depending on Polymarket's current API policies.
- Rate limiting: Be mindful of API rate limits when setting poll intervals. Default is 2 seconds (very aggressive).
- The monitor automatically handles pagination for accounts with many positions.
Rust provides excellent performance characteristics:
- Low memory footprint
- Fast HTTP requests with
reqwest - Efficient async/await with
tokio - Zero-cost abstractions
If you're migrating from the TypeScript version:
- Callbacks use
Arc<dyn Fn(...)>instead of closures - All async operations return
Result<T>for error handling - Use
tokio::mainfor async runtime - Types use Rust naming conventions (snake_case)
MIT
Contributions are welcome! Please feel free to submit a Pull Request.