What's New: Full trade execution system with risk management, CLOB API integration, and three execution modes (DRY_RUN, DEMO, LIVE).
-
Trade Executor — Places orders on Polymarket CLOB API
- Market order execution
- Limit order support
- Order tracking and status monitoring
- Demo mode with paper trading
-
Risk Manager — Enforces trading constraints
- Max position size limits
- Daily loss limits
- Daily volume caps
- Max concurrent positions
- Risk event logging
-
Trade Orchestrator — Converts signals → orders
- Signal validation
- Risk pre-flight checks
- Position sizing (scales whale signals)
- Execution monitoring
-
Order Management — Tracks orders and positions
- Order status (PENDING, PLACED, FILLED, CLOSED, etc.)
- Position tracking (open, closed, P&L)
- Execution statistics
- Risk event history
| Mode | Purpose | Usage |
|---|---|---|
| DRY_RUN | Logging only, no orders placed | Testing, debugging |
| DEMO | Paper trading at live prices | Testing signals, validating strategy |
| LIVE | Real money on Polymarket | Production trading (after validation) |
Add to .env or .env.local:
# Execution settings
EXECUTION_MODE=demo # DRY_RUN, DEMO, or LIVE
DEFAULT_POSITION_SIZE_USD=100 # Demo position sizing
MAX_POSITION_SIZE_USD=5000 # Hard limit per trade
MAX_DAILY_LOSS_USD=1000 # Stop loss for the day
MAX_DAILY_VOLUME_USD=10000 # Max daily trading volume
MAX_CONCURRENT_POSITIONS=10 # Max open positionsRequirements already added in Phase 1. Just verify:
pip install sqlalchemy asyncpgPostgreSQL will auto-create on first run:
# When you start the bot with Phase 2 enabled, tables are created automatically
# OR manually initialize:
python -c "
import asyncio
from polytracker.db_pg import AsyncDatabase
from polytracker.models_execution import Base
async def init():
db = AsyncDatabase()
await db.connect()
# Tables created automatically via SQLAlchemy
await db.disconnect()
asyncio.run(init())
"Edit polytracker/main.py to wire in Phase 2 (shown in PHASE_2_INTEGRATION.md).
export EXECUTION_MODE=demo
export DEFAULT_POSITION_SIZE_USD=100
export TELEGRAM_BOT_TOKEN="your_token"
export TELEGRAM_CHANNEL_ID="your_channel"
python -m polytracker.mainBot will now:
- Detect whale signals
- Execute paper trades at live Polymarket prices
- Track P&L in demo
- Send Telegram alerts
- Log execution statistics
Tracks all trade orders:
id— Order ID (primary key)order_id— Polymarket order ID (after placement)wallet_address— Whale wallet addressmarket_id,market_slug,market_title— Market detailsdirection— YES or NOsize_usd— Position sizeentry_price,avg_fill_price— Execution pricesstatus— PENDING, PLACED, FILLED, CANCELLED, FAILEDexecution_mode— DRY_RUN, DEMO, or LIVEcreated_at,filled_at,closed_at— Timestampspnl,roi_pct— Profit/loss when resolvederror_message— Failure reason (if applicable)
Open trading positions:
id— Position IDorder_id— Links to order (FK)wallet_address— Tradermarket_id— Marketdirection— Original entry directionsize_usd,entry_price,entry_timestampcurrent_price,unrealized_pnl— Live P&Lis_closed— Position statusrealized_pnl,realized_roi_pct— Final P&L when closed
Risk management event log:
- Tracks every risk check (passed or blocked)
- Why orders were rejected
- What limits were breached
- Actions taken (cancelled, blocked, etc.)
Daily execution summary:
- Orders placed, filled, cancelled, failed
- Daily P&L, win rate
- Max concurrent positions
- Risk events triggered
# Position size
max_position_size_usd = 50000.0 # Max per order
default_position_size_usd = 1000.0 # Default scale for demo
# Daily limits
max_daily_loss_usd = 10000.0 # Stop loss
max_daily_volume_usd = 100000.0 # Max daily trading
# Position limits
max_concurrent_positions = 10 # Max open trades
position_max_age_hours = 72 # Auto-close after 72h
# Signal filtering (existing)
min_whale_win_rate = 0.60 # Only follow 60%+ win rate whales
min_market_liquidity_usd = 10000.0 # Liquid markets onlyPhase 2 execution logs show:
🐋 Processing signal: Should Bitcoin hit $100k? | YES | high_conviction | Strength: 0.95
✅ Risk check passed
📊 Execution size: $250.00 (whale: $2,500.00, scaling: 10.00%)
📋 Demo execution: fetching current price...
Current price: $0.6234
✅ Demo filled: $250.00 @ $0.6234
Track stats with:
# In main bot (if integrated)
await orchestrator.get_execution_stats(hours=24)
# Output:
{
'period_hours': 24,
'orders_placed': 15,
'orders_filled': 14,
'total_pnl': 234.50,
'winning_trades': 10,
'losing_trades': 4,
'win_rate': 0.714
}When orders execute (will be wired up in Phase 2 integration):
Order Placed ✅
Market: Should Bitcoin hit $100k?
Direction: YES
Size: $250
Entry: $0.624
Mode: DEMO
export EXECUTION_MODE=dry_run
python -m polytracker.mainLogs all signals but places zero actual orders. Perfect for testing signal detection.
export EXECUTION_MODE=demo
python -m polytracker.mainPlaces paper orders at live Polymarket prices. Watch P&L without real money risk.
Demo validation steps:
- Run 2-4 hours, capture 5-10 demo signals
- Check that orders fill at reasonable prices
- Review demo P&L (should trend positive if signals are good)
- Verify risk checks are working (blocks exceed limits)
- Check Telegram alerts format
Only after demo validation and Phase 1 signal quality confirmed:
export EXECUTION_MODE=live
export MAX_POSITION_SIZE_USD=1000 # Start small
export DEFAULT_POSITION_SIZE_USD=500
python -m polytracker.mainBefore going live:
- Phase 1 signals validated (win rate >60%)
- Demo mode tested (2-7 days minimum)
- Risk limits configured appropriately
- Telegram alerts working
- Team aware of live trading
- Start with small position sizes
- Monitor first 24 hours closely
Demo/Live position sizes scale whale positions:
| Alert Type | Execution Mode | Scale Factor |
|---|---|---|
| Standard | DRY_RUN | 0% (no orders) |
| Standard | DEMO | 10% of whale |
| Standard | LIVE | 25% of whale |
| High Conviction | DRY_RUN | 0% (no orders) |
| High Conviction | DEMO | 25% of whale |
| High Conviction | LIVE | 50% of whale |
Examples:
- Whale buys $5,000 YES (standard alert) → We buy $500 (DEMO) or $1,250 (LIVE)
- Whale buys $2,000 YES (high conviction) → We buy $500 (DEMO) or $1,000 (LIVE)
Example: Daily loss limit = $1,000
Trade sequence:
- Order 1: Lose $400 → OK, total: -$400
- Order 2: Lose $300 → OK, total: -$700
- Order 3: Requested $500 → BLOCKED (would exceed $1,000 daily limit)
- Result: "Daily loss $700 exceeds limit $1,000" (shown as $1,200 if we placed it)
Risk event recorded:
Risk Event [warning] daily_loss_exceeded:
Daily loss $700 exceeds limit $1,000
Action: blocked new order
- Validate Phase 1 signals (in progress by you)
- Configure execution settings (.env or config)
- Run Demo Mode (2-7 days, watch P&L)
- Review P&L, risk events, alerts
- Adjust thresholds based on demo results
- Graduate to Live (if validated and confident)
polytracker/execution/__init__.py ✅ Module init
polytracker/execution/executor.py ✅ Trade executor
polytracker/execution/risk_manager.py ✅ Risk management
polytracker/execution/orchestrator.py ✅ Signal → order orchestration
polytracker/models_execution.py ✅ SQLAlchemy models (orders, positions, risks)
polytracker/polymarket/client.py ✅ Added CLOB trade execution methods
- place_market_order()
- place_limit_order()
- cancel_order()
- get_order_status()
- get_open_orders()
PHASE_2_OVERVIEW.md ✅ This document
PHASE_2_INTEGRATION.md ✅ Wiring Phase 2 into main bot
PHASE_2_SETUP.md ✅ Detailed setup guide
# In a test script
import asyncio
from polytracker.db_pg import AsyncDatabase
from polytracker.execution.orchestrator import TradeOrchestrator
from polytracker.execution.executor import ExecutionMode
from polytracker.config import get_config
async def test():
config = get_config()
db = AsyncDatabase()
await db.connect()
orchestrator = TradeOrchestrator(config, db, ExecutionMode.DEMO)
stats = await orchestrator.get_execution_stats(hours=24)
print(f"Stats: {stats}")
await db.disconnect()
asyncio.run(test())-- Connect to PostgreSQL
psql -h localhost -U polytracker -d polytracker
-- List all orders
SELECT id, market_title, direction, size_usd, status, execution_mode, created_at
FROM orders
ORDER BY created_at DESC
LIMIT 20;
-- Check risk events
SELECT * FROM risk_events ORDER BY timestamp DESC LIMIT 10;- No order updates (orders placed but status not monitored)
- Position tracking is basic (not synced with blockchain)
- P&L calculation simplified (binary outcomes)
- No stop-loss orders (manual close only)
- No partial fills handling
- Alert system not fully integrated
These will be refined in Phase 3 (hardening).
Phase 2 Status: ✅ Complete & Ready for Demo Testing
Next Phase: Phase 3 — Hardening (integration tests, alert tuning, logging refinement)
Telegram Bot: @mcinerney_bot
Ready to execute. Start with demo mode!