Automated prediction market trading system for Polymarket's "BTC 5-min Up/Down" market.
Real-time Binance data → Signal engine → Smart execution + React dashboard.
- Architecture
- Quick Start
- Configuration
- Signal Engine
- Trading Logic
- Dashboard
- API Reference
- Development
- Troubleshooting
┌─────────────┐ ┌─────────────────────┐ ┌──────────────┐
│ Binance WS │────▶│ Signal Engine │────▶│ Polymarket │
│ aggTrade │ │ │ │ CLOB
8000
API │
│ depth5 │ │ • Window Delta │ │ (Limit Order)│
└─────────────┘ │ • CVD Divergence │ └──────────────┘
│ • OFI │
┌─────────────┐ │ • Liquidity Sweep │ ┌──────────────┐
│ Polymarket │────▶│ • Flash Candle │────▶│ React │
│ Oracle WS │ │ Filter │ │ Dashboard │
│ (Chainlink) │ └─────────────────────┘ │ (5Hz WS) │
└─────────────┘ └──────────────┘
| Layer | Technology |
|---|---|
| Backend | Python 3.12 · FastAPI · asyncio/uvloop · websockets |
| Frontend | React 18 · TypeScript · ECharts 5 · Tailwind CSS 3 |
| Trading | py-clob-client (Polymarket CLOB) |
| Data | Binance WS (aggTrade + depth5) · Chainlink Oracle |
- Python 3.10+ (3.12 recommended)
- Node.js 18+ (for building the frontend)
- A Polymarket account with API credentials (optional; system runs in simulation mode without them)
cd polymarket
# Copy environment template
cp .env.template .env
# Install Python dependencies
pip install -r requirements.txtcd frontend
npm install
npm run build
cd ..Edit .env with your Polymarket credentials. Without credentials, the system runs in simulation mode — all trading logic executes but orders are simulated.
python main.pyOpen http://localhost:8899 in your browser to see the dashboard.
All settings are in .env (see .env.template for defaults):
| Variable | Description |
|---|---|
PRIVATE_KEY |
Ethereum private key (0x…) |
POLYMARKET_API_KEY |
API key from Polymarket |
POLYMARKET_API_SECRET |
API secret |
POLYMARKET_API_PASSPHRASE |
API passphrase |
| Variable | Description |
|---|---|
MARKET_CONDITION_ID |
Polymarket market condition ID |
TOKEN_ID_UP |
Token ID for the "UP" outcome |
TOKEN_ID_DOWN |
Token ID for the "DOWN" outcome |
| Variable | Default | Description |
|---|---|---|
ORDER_SIZE_USDC |
10 |
Size per trade in USDC |
MAX_DAILY_LOSS |
50 |
Daily loss limit (triggers circuit breaker) |
FEE_RATE |
0.02 |
Polymarket fee rate (2%) |
MIN_CONFIDENCE |
0.80 |
Minimum signal confidence to execute (0…1) |
SNIPER_WINDOW_START |
15 |
Start sniping X seconds before cycle end |
SNIPER_WINDOW_END |
5 |
Stop sniping X seconds before cycle end |
OFI_ALPHA |
0.4 |
OFI smoothing factor (higher = more responsive) |
| Variable | Default | Description |
|---|---|---|
HOST |
0.0.0.0 |
Bind address |
PORT |
8899 |
HTTP/WS port |
The signal engine combines 5 indicators to produce a directional confidence score:
Compares current price vs. cycle start price.
Only activates when Δ > 0.1%, with weight scaling up to Δ = 0.4%.
Cumulative Volume Delta over the last 60 seconds.
Confirms or conflicts with the Window Delta direction.
Tracks best bid/ask changes from the Binance depth5 stream.
Uses configurable exponential smoothing (OFI_ALPHA).
Detects when price and volume delta are moving in opposite directions.
Uses quartile-based comparison (1st vs 4th quartile) for robustness.
Flags bull traps (price ↑ CVD ↓) and bear traps (price ↓ CVD ↑).
Detects price briefly breaking above/below cycle extremes then reversing.
Also checks wick-to-range ratio for pin bar patterns.
If price moves > 0.5% within 1 second, or volume spikes 5x above 3s average,
the trade is completely blocked to avoid liquidity traps.
Max achievable: 0.55 + 0.25 + 0.20 = 1.00
Trade threshold: 0.80 (configurable via MIN_CONFIDENCE)
A signal must clear 0.30 to show as UP/DOWN (otherwise NEUTRAL),
and must clear MIN_CONFIDENCE to trigger execution.
Uses the formula: fee = C · feeRate · p · (1 − p)
Trades are skipped when:
- Market price
pis in [0.45, 0.55] AND confidence < MIN_CONFIDENCE
(too uncertain near 50/50 to justify the fee) - Fee impact exceeds 0.5% of order size
Orders are only placed during the last 15–5 seconds of each 5-minute cycle.
This minimizes exposure time and maximizes signal quality near settlement.
Settlement direction is determined by:
- Chainlink Oracle prices (if available via Polymarket WS) — this matches Polymarket's actual settlement oracle
- Binance price as fallback (if oracle data is unavailable)
PnL calculation:
- Win:
profit = size × (1 − price) − fee - Loss:
loss = −(size × price + fee)(fee always deducted)
- Circuit Breaker: Auto-triggers when daily loss exceeds
MAX_DAILY_LOSS. Can also be toggled manually from the dashboard. - Daily Loss Limit: Automatically halts all trading.
- One Trade Per Cycle: Prevents duplicate orders in the same 5-minute window.
- Simulation Mode: Runs full logic without real orders when credentials are missing.
The React dashboard provides real-time monitoring at 5 Hz update rate.
| Panel | Description |
|---|---|
| Price Convergence | Dual-line chart showing Binance (fast, solid blue) vs Chainlink Oracle (slow, dashed amber). Highlights latency arbitrage windows. |
| CVD & OFI | Red/green CVD bars with purple OFI overlay line. Shows buying/selling aggression. |
| Countdown Ring | SVG ring with time remaining. Changes color: blue → amber (≤30s) → red (sniper window). |
| Signal | Direction arrow, confidence bar, indicator pills (CVD DIV, SWEEP, FLASH), and reason list. |
| Account | Balance, daily PnL, trade count, win rate with W/L bar. |
| Controls | Circuit breaker toggle, fee threshold slider, daily stats reset. |
| Trade Log | Table with time, cycle, direction, confidence, price, size, fee, PnL, and status. |
- 🔌 Circuit Breaker — Toggle to halt/resume trading
- 💰 Fee Threshold — Slider to adjust the fee rate used for skip logic (0.5%–5%)
- 🔄 Reset Daily Stats — Clear PnL, trade count, and re-enable circuit breaker
| Method | Path | Description |
|---|---|---|
| GET | / |
Serves React dashboard |
| GET | /api/state |
Full system state snapshot |
| GET | /api/health |
Health check (connections) |
| POST | /api/cb |
Toggle circuit breaker |
| POST | /api/fee?val=0.02 |
Set fee threshold |
Connect to ws://localhost:8899/ws for real-time updates.
Server → Client (5 Hz):
{
"ts": 1712345678.123,
"price": { "current": 69420.5, "cycleStart": 69400, "high": 69450, "low": 69380 },
"cycle": { "remaining": 42.3, "inSniper": false, "id": "c_1712345400" },
"cvd": 15234.5,
"ofi": 1.23,
"signal": { "direction": "UP", "confidence": 0.85, "wDelta": 0.0029, "reasons": [...] },
"trading": { "balance": 1000, "pnl": 12.5, "trades": 5, "wins": 3, "wr": 0.6 },
"ctrl": { "cb": false, "feeThr": 0.02 },
"conn": { "binance": true, "poly": true },
"charts": { "bpx": [...], "ppx": [...], "cvd": [...], "ofi": [...] },
"log": [...]
}Client → Server (commands):
{ "cmd": "toggle_cb" }
{ "cmd": "set_fee", "val": 0.03 }
{ "cmd": "reset_pnl" }For hot-reload during frontend development:
# Terminal 1: Start backend
python main.py
# Terminal 2: Start Vite dev server (proxies /ws and /api to backend)
cd frontend
npm run devThen open http://localhost:5173 — Vite proxies WebSocket and API calls to the backend.
polymarket/
├── main.py # Backend: FastAPI + WS + Signal Engine + Execution
├── requirements.txt # Python dependencies
├── .env.template # Environment variable template
├── .env # Your local config (git-ignored)
├── README.md # This file
└── frontend/
├── package.json
├── vite.config.ts # Vite config with dev proxy
├── tsconfig.json
├── tailwind.config.js
├── postcss.config.js
├── index.html
├── dist/ # Production build (served by FastAPI)
└── src/
├── main.tsx
├── App.tsx
├── index.css
├── types.ts # TypeScript interfaces for WS payload
├── hooks/
│ └── useSocket.ts # WebSocket hook with auto-reconnect
└── components/
├── Header.tsx
├── PriceChart.tsx
├── CVDChart.tsx
├── Countdown.tsx
├── SignalPanel.tsx
├── AccountPanel.tsx
├── Controls.tsx
└── TradeLog.tsx
Run cd frontend && npm install && npm run build, then restart the backend.
- Check
MIN_CONFIDENCE— the signal must exceed this threshold - Check if circuit breaker is ON (dashboard Controls panel)
- Trades only execute during the sniper window (15s–5s before cycle end)
- Check the Signal panel for block reasons (flash candle, divergence, etc.)
Normal behavior — the system auto-reconnects with exponential backoff (1s → 2s → 4s → … → 30s max). Check the connection indicator in the dashboard header.
Without valid PRIVATE_KEY in .env, the system runs in simulation mode:
- All signal logic runs identically
- Orders are logged as "SIMULATED"
- Balance shows $1000 (simulated)
- No real funds are at risk
To go live, provide your Polymarket credentials and install py-clob-client:
pip install py-clob-clientChange the PORT in .env or stop the existing process:
lsof -ti:8899 | xargs killThis software is provided for educational and research purposes only. Automated trading involves significant financial risk. The authors are not responsible for any losses incurred. Always test with small amounts and understand the risks before deploying with real funds.