### Install and Build Project (Bash) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md This snippet demonstrates the commands to clone the repository, navigate into the project directory, install dependencies using npm, and build the project. ```bash git clone https://github.com/dylanpersonguy/Polymarket-Trading-Bot.git cd Polymarket-Trading-Bot npm install npm run build ``` -------------------------------- ### Initialize and Start WhaleService (TypeScript) Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Demonstrates how to initialize the WhaleService with configuration and API endpoints, and then start its tracking operations. It also shows how to check the service's running status. ```typescript import { WhaleService } from './src/whales/whale_service'; import { WhaleTrackingConfig } from './src/whales/whale_types'; const config: WhaleTrackingConfig = { dbPath: '.runtime/whales.db', pollIntervalMs: 30000, provisionalMinTrades: 30, scanner: { enabled: true } // ... additional config options }; const whaleService = new WhaleService( config, 'https://clob.polymarket.com', 'https://gamma-api.polymarket.com' ); // Start the whale tracking service whaleService.start(); console.log(`Service running: ${whaleService.isRunning()}`); // Output: Service running: true ``` -------------------------------- ### Start Bot with Live Trading Enabled (Bash) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md To enable live trading with real funds, set the ENABLE_LIVE_TRADING environment variable to 'true' before starting the bot. It is strongly recommended to test strategies in paper trading mode first. ```bash ENABLE_LIVE_TRADING=true npm start ``` -------------------------------- ### Launch Bot and Access Dashboard (Bash) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Provides commands to start the trading bot in paper trading mode and access the real-time dashboard via a web browser. It also shows how to use the CLI for direct control. ```bash # Start the bot with default config (all wallets in PAPER mode) npm start # Or use the CLI directly node dist/cli.js start --config config.yaml # Access the dashboard open http://localhost:3000/dashboard ``` -------------------------------- ### Wallet Configuration Example (YAML) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Illustrates the configuration structure for defining individual wallets within the trading bot. This YAML snippet specifies wallet mode (PAPER/LIVE), strategy, initial capital, and various risk limits to manage trading exposure. ```yaml wallets: - id: paper_convergence mode: PAPER # PAPER or LIVE strategy: filtered_high_prob_convergence capital: 10000 # $10,000 starting capital risk_limits: max_position_size: 500 # Max $500 per position max_exposure_per_market: 1000 max_daily_loss: 500 # Stop at $500 daily loss max_open_trades: 50 max_drawdown: 0.10 # 10% max drawdown ``` -------------------------------- ### GET /api/wallets Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Lists all wallets managed by the bot. ```APIDOC ## GET /api/wallets ### Description Lists all wallets currently managed by the trading bot, including their basic configuration and status. ### Method GET ### Endpoint /api/wallets ### Parameters None ### Response #### Success Response (200) - **wallets** (array) - An array of wallet objects. - **id** (string) - Unique identifier for the wallet. - **mode** (string) - Trading mode (`PAPER` or `LIVE`). - **strategy** (string) - The strategy assigned to the wallet. - **capital** (number) - Initial capital allocated to the wallet. - **status** (string) - Current status of the wallet (e.g., `active`, `paused`). #### Response Example ```json { "wallets": [ { "id": "paper_convergence", "mode": "PAPER", "strategy": "filtered_high_prob_convergence", "capital": 10000, "status": "active" }, { "id": "live_arbitrage_1", "mode": "LIVE", "strategy": "arbitrage", "capital": 50000, "status": "paused" } ] } ``` ``` -------------------------------- ### GET /api/strategies Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Lists all available trading strategies. ```APIDOC ## GET /api/strategies ### Description Lists all trading strategies that are available for use with the bot. ### Method GET ### Endpoint /api/strategies ### Parameters None ### Response #### Success Response (200) - **strategies** (array) - An array of available strategy names. #### Response Example ```json { "strategies": [ "filtered_high_prob_convergence", "arbitrage", "momentum_strategy", "mean_reversion" ] } ``` ``` -------------------------------- ### Example Trade Flow Log (Log) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md This log snippet demonstrates a typical trade flow, from market scanning and filtering to order placement, execution, and profit-taking. It includes details on market conditions and position sizing. ```log [12:03:45] 🔍 Scanning 50 markets (16 parallel)... [12:03:47] ✅ Market "Will BTC hit $100K by Dec?" passed all 7 filters Prob: 72% | Spread: 85 bps | Liquidity: $125K | Resolves: 8 days [12:03:47] 📊 Setup Score: 0.87 (spread=0.92, depth=0.85, flow=0.88, time=0.80) [12:03:47] 💰 Position: $10,000 × 0.5% × 0.87 = $43.50 [12:03:47] 📝 BUY 60 shares @ $0.725 (limit, post-only) [12:03:48] ✅ FILLED: 60 shares @ $0.725 = $43.50 [12:05:12] 📈 Price moved to $0.745 (+200 bps) → TAKE PROFIT triggered [12:05:12] 📝 SELL 60 shares @ $0.745 [12:05:12] ✅ FILLED: Profit = $1.20 (+2.76% on position) ``` -------------------------------- ### GET /api/whales/* Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Endpoints for retrieving whale tracking data. ```APIDOC ## GET /api/whales/* ### Description Provides access to various endpoints related to whale tracking, including individual whale data, clusters, and network graphs. ### Method GET ### Endpoint /api/whales/* ### Parameters #### Path Parameters - *** ** (string) - Required - The specific whale tracking sub-endpoint (e.g., `/api/whales/tracker`, `/api/whales/clusters`). ### Response #### Success Response (200) - **whale_data** (object) - Data specific to the requested whale tracking endpoint. #### Response Example (Response structure depends on the specific sub-endpoint requested, e.g., list of whales, cluster details, network graph data.) ```json { "whales": [ { "id": "whale_123", "score": 85, "profitability": 0.90, "timing_skill": 0.75 } ] } ``` ``` -------------------------------- ### Initialize and Manage Trading Engine (TypeScript) Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Demonstrates how to initialize the TradingEngine by loading configuration, start its execution, check its running status, and gracefully stop it. This class is the central orchestrator for strategy execution and order routing. ```typescript import { TradingEngine } from './src/core/engine'; import { loadConfig } from './src/config'; // Initialize the trading engine const config = loadConfig('./config.yaml'); const engine = new TradingEngine(config); // Start the engine (begins strategy execution) await engine.start(); // Check engine status const isRunning = engine.isRunning(); console.log(`Engine running: ${isRunning}`); // Output: Engine running: true // Stop the engine gracefully await engine.stop(); ``` -------------------------------- ### CLI Commands (Bash) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Provides essential command-line interface commands for managing the trading bot. These commands cover starting, stopping, checking status, managing wallets, listing strategies, and generating performance reports. ```bash # Start the trading engine bot start --config config.yaml # Check status bot status # Stop all strategies bot stop # Add a new wallet bot add-wallet --config config.yaml # Remove a wallet bot remove-wallet --id wallet_1 --config config.yaml # List available strategies bot list-strategies # View performance report bot performance # Paper trading report bot paper-report ``` -------------------------------- ### GET /api/trades/all Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves all trades executed across all wallets. ```APIDOC ## GET /api/trades/all ### Description Retrieves a comprehensive list of all trades executed by any wallet managed by the bot. ### Method GET ### Endpoint /api/trades/all ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of trades to return. - **offset** (integer) - Optional - Number of trades to skip (for pagination). ### Response #### Success Response (200) - **trades** (array) - An array of trade objects. - **wallet_id** (string) - ID of the wallet that executed the trade. - **market** (string) - The market traded (e.g., BTC/USD). - **type** (string) - Trade type (`BUY` or `SELL`). - **size** (number) - Size of the trade. - **price** (number) - Execution price. - **timestamp** (string) - ISO 8601 timestamp of the trade. #### Response Example ```json { "trades": [ { "wallet_id": "paper_convergence", "market": "BTC/USD", "type": "BUY", "size": 0.1, "price": 41000, "timestamp": "2023-10-27T11:00:00Z" }, { "wallet_id": "live_arbitrage_1", "market": "ETH/USD", "type": "SELL", "size": 1.5, "price": 3050, "timestamp": "2023-10-27T11:05:00Z" } ] } ``` ``` -------------------------------- ### Risk Guardrails Log Example (Log) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md This log illustrates the risk management system in action. It shows the bot pausing trading when daily loss limits are approached or breached, while also tracking overall weekly profitability against drawdown limits. ```log [14:22:01] ⚠️ Daily loss at 2.8% ($280) — approaching 3% limit [14:35:15] 🛑 Daily loss hit 3.0% — ALL strategies PAUSED for today [14:35:15] 📊 Weekly P&L: +$420 (+4.2%) — well within 8% drawdown limit ``` -------------------------------- ### GET /dashboard Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves the full HTML for the real-time dashboard. ```APIDOC ## GET /dashboard ### Description Retrieves the full HTML for the real-time dashboard, which is served as a single-page application. ### Method GET ### Endpoint /dashboard ### Parameters None ### Response #### Success Response (200) - **HTML** (string) - The HTML content of the dashboard. #### Response Example (HTML content of the dashboard) ``` -------------------------------- ### Bot Configuration (YAML) Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Example configuration file (`config.yaml`) for the trading bot. It covers environment settings, wallet configurations, strategy-specific parameters, whale tracking engine settings, and API endpoints. ```yaml # Environment settings environment: enable_live_trading: false # Safety: must be true for LIVE mode # Wallet configurations wallets: - id: paper_momentum mode: PAPER strategy: momentum capital: 10000 risk_limits: max_position_size: 500 max_exposure_per_market: 1000 max_daily_loss: 500 max_open_trades: 50 max_drawdown: 0.10 # Strategy-specific configurations strategy_config: momentum: lookback_minutes: 15 market_making: spread_bps: 40 copy_trade: whale_addresses: [] copy_mode: mirror # mirror | inverse poll_interval_seconds: 30 min_trade_size_usd: 50 max_open_positions: 15 # Whale tracking engine whale_tracking: enabled: true dbPath: .runtime/whales.db pollIntervalMs: 30000 scanner: enabled: true scanIntervalMs: 600000 autoPromoteEnabled: true autoPromoteMinScore: 60 # API endpoints polymarket: gamma_api: https://gamma-api.polymarket.com clob_api: https://clob.polymarket.com ``` -------------------------------- ### GET /api/strategies Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Lists the status of all configured trading strategies. ```APIDOC ## GET /api/strategies ### Description Retrieves the status and configuration details for all trading strategies managed by the bot. ### Method GET ### Endpoint /api/strategies ### Parameters None ### Request Example None ### Response #### Success Response (200) - **strategies** (array) - An array of strategy objects. - **id** (string) - The unique identifier of the strategy. - **enabled** (boolean) - Indicates if the strategy is currently enabled. - **assignedWallets** (array) - A list of wallet IDs assigned to this strategy. - **signalsGenerated** (integer) - The total number of trading signals generated by this strategy. - **ordersPlaced** (integer) - The total number of orders placed by this strategy. #### Response Example ```json { "strategies": [ { "id": "momentum", "enabled": true, "assignedWallets": ["paper_momentum"], "signalsGenerated": 42, "ordersPlaced": 28 } ] } ``` ``` -------------------------------- ### GET /api/console/logs Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves historical log entries from the engine. ```APIDOC ## GET /api/console/logs ### Description Fetches a list of historical log entries generated by the trading engine. ### Method GET ### Endpoint /api/console/logs ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of log entries to return. - **level** (string) - Optional - Filter logs by level (e.g., `INFO`, `DEBUG`, `ERROR`). ### Response #### Success Response (200) - **logs** (array) - An array of log entry objects. - **timestamp** (string) - ISO 8601 timestamp of the log entry. - **level** (string) - Log level (e.g., `INFO`, `DEBUG`, `ERROR`). - **message** (string) - The log message content. #### Response Example ```json { "logs": [ { "timestamp": "2023-10-27T10:00:00Z", "level": "INFO", "message": "Engine started successfully." }, { "timestamp": "2023-10-27T10:05:00Z", "level": "DEBUG", "message": "Processing trade for wallet paper_convergence." } ] } ``` ``` -------------------------------- ### Validate Orders with RiskEngine (TypeScript) Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Demonstrates how to initialize and use the RiskEngine to validate order requests against a given wallet state. It shows examples of both successful order approval and rejection due to exceeding risk limits. Dependencies include `RiskEngine`, `KillSwitch`, and `OrderRequest`, `WalletState` types. ```typescript import { RiskEngine } from './src/risk/risk_engine'; import { KillSwitch } from './src/risk/kill_switch'; import { OrderRequest, WalletState } from './src/types'; const killSwitch = new KillSwitch(); const riskEngine = new RiskEngine(killSwitch); // Define wallet state const walletState: WalletState = { walletId: 'paper_momentum', mode: 'PAPER', capitalAllocated: 10000, availableBalance: 8500, openPositions: [ { marketId: '0xabc...', tokenId: '111', side: 'BUY', size: 50, avgPrice: 0.55 } ], realizedPnl: 150, riskLimits: { maxPositionSize: 500, maxExposurePerMarket: 1000, maxDailyLoss: 500, maxOpenTrades: 50, maxDrawdown: 0.10 } }; // Check if an order passes risk validation const orderRequest: OrderRequest = { walletId: 'paper_momentum', marketId: '0xdef...', tokenId: '222', side: 'BUY', price: 0.70, size: 200, strategyId: 'momentum' }; const result = riskEngine.check(orderRequest, walletState); if (result.ok) { console.log('Order approved by risk engine'); } else { console.log(`Order rejected: ${result.reason}`); } // Output: Order approved by risk engine // Example: Order rejection due to position size limit const largeOrder: OrderRequest = { walletId: 'paper_momentum', marketId: '0xdef...', tokenId: '222', side: 'BUY', price: 0.70, size: 1000, // Exceeds maxPositionSize of 500 strategyId: 'momentum' }; const rejectResult = riskEngine.check(largeOrder, walletState); console.log(`Large order result: ${rejectResult.reason}`); // Output: Large order result: Max position size exceeded // Get cancel rate for a wallet (monitors excessive cancellations) const cancelRate = riskEngine.getCancelRate('paper_momentum'); console.log(`Cancel rate: ${(cancelRate * 100).toFixed(1)}%`); // Activate global kill switch (blocks all orders) killSwitch.activate('Manual emergency shutdown'); const blockedResult = riskEngine.check(orderRequest, walletState); console.log(`After kill switch: ${blockedResult.reason}`); // Output: After kill switch: Global kill switch active ``` -------------------------------- ### GET /api/wallets/display-names Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves a list of display names for all wallets. ```APIDOC ## GET /api/wallets/display-names ### Description Fetches a list of display names assigned to each wallet. This is useful for quick identification in UIs. ### Method GET ### Endpoint /api/wallets/display-names ### Parameters None ### Response #### Success Response (200) - **display_names** (object) - An object mapping wallet IDs to their display names. #### Response Example ```json { "display_names": { "paper_convergence": "Paper Convergence Wallet", "live_arbitrage_1": "Live Arbitrage Bot 1" } } ``` ``` -------------------------------- ### GET /api/console/stream Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Provides a Server-Sent Events (SSE) stream for live log output from the engine. ```APIDOC ## GET /api/console/stream ### Description Establishes a Server-Sent Events (SSE) connection to stream live log messages from the trading engine in real-time. ### Method GET ### Endpoint /api/console/stream ### Parameters None ### Response #### Success Response (200) - **event stream** - A stream of log messages in SSE format. #### Response Example ``` id: 1678886400000 event: log data: {"level": "INFO", "message": "Engine started successfully."} id: 1678886401000 event: log data: {"level": "DEBUG", "message": "Scanning market BTC/USD..."} ``` ``` -------------------------------- ### GET /api/wallets/:id/detail Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves detailed information for a specific wallet. ```APIDOC ## GET /api/wallets/:id/detail ### Description Fetches comprehensive details for a specific wallet, including its current positions, trade history, and performance metrics. ### Method GET ### Endpoint /api/wallets/:id/detail ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the wallet. ### Response #### Success Response (200) - **wallet_detail** (object) - Detailed information about the wallet. - **id** (string) - Wallet ID. - **strategy** (string) - Assigned strategy. - **capital** (number) - Current capital. - **pnl** (number) - Profit and Loss. - **positions** (array) - Current open positions. - **trades** (array) - Recent trade history. #### Response Example ```json { "wallet_detail": { "id": "paper_convergence", "strategy": "filtered_high_prob_convergence", "capital": 10500.50, "pnl": 500.50, "positions": [ { "market": "BTC/USD", "size": 0.5, "entry_price": 40000 } ], "trades": [ { "market": "ETH/USD", "type": "BUY", "price": 3000, "timestamp": "2023-10-27T10:00:00Z" } ] } } ``` ``` -------------------------------- ### GET /api/data Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Fetches engine status and summary data. ```APIDOC ## GET /api/data ### Description Fetches the current engine status and summary data, providing an overview of the bot's operations. ### Method GET ### Endpoint /api/data ### Parameters None ### Response #### Success Response (200) - **engine_status** (string) - The current status of the trading engine. - **total_pnl** (number) - Total Profit and Loss across all wallets. - **active_wallets** (integer) - Number of currently active wallets. - **market_count** (integer) - Number of markets being monitored. #### Response Example ```json { "engine_status": "running", "total_pnl": 1500.75, "active_wallets": 5, "market_count": 120 } ``` ``` -------------------------------- ### GET /api/wallets Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Lists all managed wallets along with their current state, capital allocation, and performance metrics. ```APIDOC ## GET /api/wallets ### Description Lists all wallets managed by the bot, including their operational mode, allocated capital, available balance, and performance indicators like open positions and PnL. ### Method GET ### Endpoint /api/wallets ### Parameters None ### Request Example None ### Response #### Success Response (200) - **wallets** (array) - An array of wallet objects. - **walletId** (string) - Unique identifier for the wallet. - **mode** (string) - The operational mode of the wallet (e.g., "PAPER", "LIVE"). - **capitalAllocated** (number) - The total capital allocated to this wallet. - **availableBalance** (number) - The current available balance in the wallet. - **openPositions** (integer) - The number of currently open positions. - **realizedPnl** (number) - The total realized profit and loss for the wallet. - **unrealizedPnl** (number) - The current unrealized profit and loss for the wallet. #### Response Example ```json { "wallets": [ { "walletId": "paper_momentum", "mode": "PAPER", "capitalAllocated": 10000, "availableBalance": 8500, "openPositions": 5, "realizedPnl": 150.50, "unrealizedPnl": 45.25 } ] } ``` ``` -------------------------------- ### GET /api/status Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Retrieves the overall system health and status, including uptime and active components. ```APIDOC ## GET /api/status ### Description Retrieves the overall system health and status, including uptime, number of active strategies, total wallets managed, and the kill switch status. ### Method GET ### Endpoint /api/status ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The current status of the system (e.g., "running"). - **uptime** (integer) - The duration the system has been running in seconds. - **activeStrategies** (integer) - The number of currently active trading strategies. - **totalWallets** (integer) - The total number of wallets being managed by the bot. - **killSwitchActive** (boolean) - Indicates if the emergency kill switch is currently active. #### Response Example ```json { "status": "running", "uptime": 3600, "activeStrategies": 8, "totalWallets": 12, "killSwitchActive": false } ``` ``` -------------------------------- ### GET /api/whales/summary Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Provides a summary of whale tracking activity, including total counts and scanner status. ```APIDOC ## GET /api/whales/summary ### Description Retrieves a summary of the whale tracking engine's activity, including the total number of identified whales, those currently being tracked, unread alerts, and the status of the scanner. ### Method GET ### Endpoint /api/whales/summary ### Parameters None ### Request Example None ### Response #### Success Response (200) - **totalWhales** (integer) - The total number of unique whale addresses identified. - **trackedWhales** (integer) - The number of whales currently being actively tracked. - **unreadAlerts** (integer) - The count of unread alerts generated for whale activity. - **scannerStatus** (string) - The current status of the whale scanner (e.g., "scanning", "idle"). - **topPerformers** (array) - A list of top-performing whales, including their ID, display name, and performance score. - **id** (integer) - Unique identifier for the whale. - **displayName** (string) - Display name of the whale. - **score** (integer) - Performance score of the whale. #### Response Example ```json { "totalWhales": 45, "trackedWhales": 32, "unreadAlerts": 7, "scannerStatus": "scanning", "topPerformers": [ { "id": 1, "displayName": "Top Trader Alpha", "score": 78 } ] } ``` ``` -------------------------------- ### GET /api/wallets/:id/positions Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Retrieves details of all open positions for a specific wallet. ```APIDOC ## GET /api/wallets/:id/positions ### Description Retrieves a list of all currently open positions for a specified wallet. ### Method GET ### Endpoint /api/wallets/:id/positions ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the wallet. ### Request Example None ### Response #### Success Response (200) - **positions** (array) - An array of position objects. - **marketId** (string) - The identifier of the market the position is in. - **tokenId** (string) - The token identifier for the position. - **side** (string) - The direction of the trade (e.g., "BUY", "SELL"). - **size** (number) - The size of the position. - **avgPrice** (number) - The average entry price for the position. - **currentPrice** (number) - The current market price. - **unrealizedPnl** (number) - The unrealized profit or loss for this position. #### Response Example ```json { "positions": [ { "marketId": "0x1234...", "tokenId": "12345", "side": "BUY", "size": 100, "avgPrice": 0.65, "currentPrice": 0.68, "unrealizedPnl": 3.00 } ] } ``` ``` -------------------------------- ### Get Whale Service Summary (JavaScript) Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Retrieves and logs a summary of the whale service, including total whales, actively tracked whales, unread alerts, candidate pool size, and scanner status. This is useful for dashboard display. ```javascript const summary = whaleService.getSummary(); console.log(` Whale Service Summary:`); console.log(` Total whales: ${summary.totalWhales}`); console.log(` Actively tracked: ${summary.trackedWhales}`); console.log(` Unread alerts: ${summary.unreadAlerts}`); console.log(` Candidate pool: ${summary.candidateCount}`); console.log(` Scanner: ${summary.scannerStatus}`); ``` -------------------------------- ### Build and Run Docker Image (Bash) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Build the Docker image for the Polymarket bot using 'docker build'. Run the container in paper trading mode by default, or enable live trading by setting the ENABLE_LIVE_TRADING environment variable. ```bash docker build -t polymarket-bot . docker run -p 3000:3000 polymarket-bot docker run -p 3000:3000 -e ENABLE_LIVE_TRADING=true polymarket-bot ``` -------------------------------- ### GET /api/trades/:walletId Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves trades for a specific wallet. ```APIDOC ## GET /api/trades/:walletId ### Description Retrieves a list of trades executed by a specific wallet. ### Method GET ### Endpoint /api/trades/:walletId ### Parameters #### Path Parameters - **walletId** (string) - Required - The unique identifier of the wallet. #### Query Parameters - **limit** (integer) - Optional - Maximum number of trades to return. - **offset** (integer) - Optional - Number of trades to skip (for pagination). ### Response #### Success Response (200) - **trades** (array) - An array of trade objects for the specified wallet. - **market** (string) - The market traded (e.g., BTC/USD). - **type** (string) - Trade type (`BUY` or `SELL`). - **size** (number) - Size of the trade. - **price** (number) - Execution price. - **timestamp** (string) - ISO 8601 timestamp of the trade. #### Response Example ```json { "trades": [ { "market": "BTC/USD", "type": "BUY", "size": 0.1, "price": 41000, "timestamp": "2023-10-27T11:00:00Z" } ] } ``` ``` -------------------------------- ### Verify Bot Status via API (Bash) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Demonstrates how to use curl and jq to query the bot's API for data, wallet lists, and live trades, helping to verify its operational status. ```bash # View engine status via API curl http://localhost:3000/api/data | jq # List all wallets curl http://localhost:3000/api/wallets | jq # View live trades curl http://localhost:3000/api/trades/all | jq ``` -------------------------------- ### GET /api/markets Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves data for currently scanned markets. ```APIDOC ## GET /api/markets ### Description Fetches data for all markets currently being scanned by the bot's market scanner. ### Method GET ### Endpoint /api/markets ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of markets to return. - **offset** (integer) - Optional - Number of markets to skip (for pagination). ### Response #### Success Response (200) - **markets** (array) - An array of market objects. - **symbol** (string) - Market symbol (e.g., BTC/USD). - **price** (number) - Current price. - **volume_24h** (number) - 24-hour trading volume. - **liquidity** (number) - Market liquidity score. #### Response Example ```json { "markets": [ { "symbol": "BTC/USD", "price": 41500.50, "volume_24h": 500000000, "liquidity": 0.95 }, { "symbol": "ETH/USD", "price": 3050.75, "volume_24h": 200000000, "liquidity": 0.90 } ] } ``` ``` -------------------------------- ### POST /api/wallets Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Creates a new wallet with specified configuration. ```APIDOC ## POST /api/wallets ### Description Creates a new wallet with the provided configuration. This allows for programmatic addition of new trading entities. ### Method POST ### Endpoint /api/wallets ### Parameters #### Request Body - **id** (string) - Required - Unique identifier for the new wallet. - **mode** (string) - Required - Trading mode (`PAPER` or `LIVE`). - **strategy** (string) - Required - The strategy to assign to the wallet. - **capital** (number) - Required - Initial capital for the wallet. - **risk_limits** (object) - Optional - Risk management parameters. - **max_position_size** (number) - Maximum size of a single position. - **max_exposure_per_market** (number) - Maximum exposure allowed per market. - **max_daily_loss** (number) - Maximum daily loss threshold. - **max_open_trades** (integer) - Maximum number of open trades. - **max_drawdown** (number) - Maximum drawdown percentage. ### Request Example ```json { "id": "new_wallet_1", "mode": "PAPER", "strategy": "momentum_strategy", "capital": 20000, "risk_limits": { "max_position_size": 1000, "max_daily_loss": 1000, "max_open_trades": 20 } } ``` ### Response #### Success Response (201) - **message** (string) - Confirmation message of wallet creation. - **wallet_id** (string) - The ID of the newly created wallet. #### Response Example ```json { "message": "Wallet created successfully", "wallet_id": "new_wallet_1" } ``` ``` -------------------------------- ### Run All Tests (Bash) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Execute all tests within the project using the 'npm test' command. For more detailed output, use 'npx vitest run --reporter=verbose'. Specific test files can also be targeted. ```bash npm test npx vitest run --reporter=verbose npx vitest run tests/whale_scanner.test.ts npm run typecheck ``` -------------------------------- ### GET /api/strategies/:id Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Retrieves detailed information about a specific trading strategy. ```APIDOC ## GET /api/strategies/:id ### Description Fetches detailed information about a specific trading strategy, including its parameters and description. ### Method GET ### Endpoint /api/strategies/:id ### Parameters #### Path Parameters - **id** (string) - Required - The name of the strategy. ### Response #### Success Response (200) - **strategy_details** (object) - Details of the strategy. - **name** (string) - Strategy name. - **description** (string) - Description of the strategy. - **parameters** (object) - Available parameters for the strategy. #### Response Example ```json { "strategy_details": { "name": "filtered_high_prob_convergence", "description": "A strategy that identifies high probability convergence points with filters.", "parameters": { "lookback_period": { "type": "integer", "default": 50 }, "convergence_threshold": { "type": "float", "default": 0.85 } } } } ``` ``` -------------------------------- ### Manage Trading Wallets and Place Orders (TypeScript) Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Illustrates the usage of the WalletManager for registering trading wallets in PAPER or LIVE modes, retrieving wallet states (balance, positions, PnL), and placing orders. It includes detailed configuration for risk limits and order parameters. ```typescript import { WalletManager } from './src/wallets/wallet_manager'; import { WalletConfig, TradingMode } from './src/types'; const walletManager = new WalletManager(); // Register a paper trading wallet const paperConfig: WalletConfig = { walletId: 'paper_momentum', mode: 'PAPER' as TradingMode, capitalAllocated: 10000, riskLimits: { maxPositionSize: 500, maxExposurePerMarket: 1000, maxDailyLoss: 500, maxOpenTrades: 50, maxDrawdown: 0.10 } }; walletManager.registerWallet(paperConfig); // Get wallet instance const wallet = walletManager.getWallet('paper_momentum'); // Get wallet state (balance, positions, PnL) const state = await wallet.getState(); console.log(`Available balance: $${state.availableBalance.toFixed(2)}`); console.log(`Open positions: ${state.openPositions.length}`); console.log(`Realized PnL: $${state.realizedPnl.toFixed(2)}`); // Output: // Available balance: $10000.00 // Open positions: 0 // Realized PnL: $0.00 // Place an order through the wallet const orderRequest = { walletId: 'paper_momentum', marketId: '0x1234...abcd', tokenId: '12345', side: 'BUY' as const, price: 0.65, size: 100, strategyId: 'momentum', ttlSeconds: 120 }; const orderResult = await wallet.placeOrder(orderRequest); if (orderResult.success) { console.log(`Order placed: ${orderResult.orderId}`); } else { console.error(`Order failed: ${orderResult.error}`); } // List all registered wallets const wallets = walletManager.listWallets(); console.log(`Registered wallets: ${wallets.map(w => w.walletId).join(', ')}`); ``` -------------------------------- ### Scanner Configuration (YAML) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Configures the market scanner for whale tracking, including scan intervals, market selection criteria, and advanced features like cluster detection and copy trading simulation. This YAML snippet defines parameters for enabling and tuning the bot's market analysis capabilities. ```yaml whale_tracking: scanner: enabled: true scanIntervalMs: 600000 # Scan every 10 minutes marketsPerScan: 50 # Top 50 liquid markets parallelFetchBatch: 16 # 16 concurrent fetches minMarketVolume24hUsd: 10000 # Skip low-volume markets autoPromoteEnabled: true # Auto-track high-scoring whales autoPromoteMinScore: 60 # Minimum score to auto-track clusterDetectionEnabled: true # Detect whale herds networkGraphEnabled: true # Map whale relationships copySimEnabled: true # Simulate copy trading regimeAdaptiveEnabled: true # Adjust scores by regime ``` -------------------------------- ### GET /api/whales/:id Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Retrieves detailed information about a specific whale. ```APIDOC ## GET /api/whales/:id ### Description Fetches a comprehensive profile for a specific whale, including detailed performance metrics, trade history, and current positions. ### Method GET ### Endpoint /api/whales/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the whale. ### Request Example None ### Response #### Success Response (200) - Returns the full whale profile, which may include score breakdown, trade history, and position data. (Specific fields depend on implementation details). #### Response Example (Example structure, actual response may vary) ```json { "id": "whale_123", "displayName": "Whale Alpha", "score": 85, "scoreBreakdown": { "pnl": 70, "activity": 90, "consistency": 80 }, "trades": [ // ... trade objects ... ], "positions": [ // ... position objects ... ] } ``` ``` -------------------------------- ### Analyze Whale Performance and Timing with WhaleService (TypeScript) Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Shows how to retrieve timing analysis for a whale, which breaks down performance by time windows, and how to compare the performance metrics of multiple whales. ```typescript // Get timing analysis (performance by time window) const timing = whaleService.getTimingAnalysis(1); timing.forEach(window => { console.log(`${window.windowMinutes}min: ${window.winRate.toFixed(1)}% win rate, ${window.avgReturnPct.toFixed(2)}% avg return`); }); // Output: // 5min: 58.2% win rate, 1.25% avg return // 30min: 61.5% win rate, 2.10% avg return // 240min: 65.0% win rate, 3.50% avg return // Compare multiple whales const comparison = whaleService.compareWhales([1, 2, 3]); comparison.forEach(c => { console.log(`${c.whale.displayName}: Vol $${c.stats.totalVolume.toFixed(0)}, PnL $${c.stats.settledPnl.toFixed(2)}`); }); ``` -------------------------------- ### Momentum Strategy Configuration (YAML) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Sets up the momentum trading strategy by defining the lookback window in minutes. This strategy capitalizes on short-term price trends. ```yaml strategy_config: momentum: lookback_minutes: 15 ``` -------------------------------- ### Environment Configuration (YAML) Source: https://github.com/dylanpersonguy/polymarket-trading-bot/blob/main/README.md Defines the environment settings for the trading bot, primarily controlling whether live trading is enabled. This configuration ensures the bot operates in PAPER trading mode by default for safety. ```yaml environment: enable_live_trading: false # PAPER mode by default — safety first ``` -------------------------------- ### GET /api/markets/:id/whale-activity Source: https://context7.com/dylanpersonguy/polymarket-trading-bot/llms.txt Analyzes and returns whale activity data for a specific market. ```APIDOC ## GET /api/markets/:id/whale-activity ### Description Provides insights into whale trading activity within a specific market, including net flow, significant trades (prints), and concentration metrics. ### Method GET ### Endpoint /api/markets/:id/whale-activity ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the market. ### Request Example None ### Response #### Success Response (200) - **netFlow** (number) - The net flow of capital into or out of the market attributed to whales. - **biggestPrints** (array) - A list of the largest individual trades (prints) made by whales in this market. - **concentration** (array) - Data representing the concentration of whale activity or capital within the market. #### Response Example ```json { "netFlow": 1500.75, "biggestPrints": [ { "size": 500, "price": 0.70, "side": "BUY" }, { "size": 450, "price": 0.69, "side": "SELL" } ], "concentration": [ { "whaleId": "whale_123", "percentage": 0.25 }, { "whaleId": "whale_456", "percentage": 0.15 } ] } ``` ```