Skip to content

Polymarket Tracking Bot || monitoring target's activity and follow instantly when detected order placing

Notifications You must be signed in to change notification settings

crellOS/polymarket-tracking-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Polymarket Account Monitor (Rust)

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.

Features

  • 📊 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

Prerequisites

  • Rust 1.70+ (install from rustup.rs)
  • Cargo (comes with Rust)

Installation

# Clone the repository
git clone <repository-url>
cd polymarket-account-monitor-rust

# Build the project
cargo build --release

Configuration

The 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 required

Or create a .env file:

TARGET_ADDRESS=0x...
POLYMARKET_API_KEY=...

Usage

Command Line Usage

# 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...

Programmatic Usage

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(())
}

API Reference

PolymarketClient

Main client for interacting with Polymarket APIs.

Constructor

PolymarketClient::new(config: PolymarketConfig)

Methods

  • 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

AccountMonitor

Monitors a target account's trading activity.

Constructor

AccountMonitor::new(client: PolymarketClient, options: MonitorOptions)

Methods

  • start() -> Result<()> - Start monitoring (async)
  • stop() - Stop monitoring
  • get_status() -> Result<TradingStatus> - Get current status (async)
  • get_formatted_status(status: &TradingStatus) -> String - Get formatted status string
  • is_running() -> bool - Check if monitor is running (async)

Types

TradingStatus

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,
}

Position

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,
}

Trade

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,
}

Development

# 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 fmt

Project Structure

polymarket-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

Polymarket APIs

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.

Notes

  • 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.

Performance

Rust provides excellent performance characteristics:

  • Low memory footprint
  • Fast HTTP requests with reqwest
  • Efficient async/await with tokio
  • Zero-cost abstractions

Migration from TypeScript

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::main for async runtime
  • Types use Rust naming conventions (snake_case)

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

Polymarket Tracking Bot || monitoring target's activity and follow instantly when detected order placing

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages