8000 GitHub - dongziair/polymarket · GitHub
[go: up one dir, main page]

Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

₿ Polymarket BTC 5-Minute Sniper — Trading System

Automated prediction market trading system for Polymarket's "BTC 5-min Up/Down" market.
Real-time Binance data → Signal engine → Smart execution + React dashboard.


📋 Table of Contents


Architecture

┌─────────────┐     ┌─────────────────────┐     ┌──────────────┐
│ 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)    │
└─────────────┘                                 └──────────────┘

Tech Stack

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

Quick Start

Prerequisites

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

1. Clone & Setup

cd polymarket

# Copy environment template
cp .env.template .env

# Install Python dependencies
pip install -r requirements.txt

2. Build Frontend

cd frontend
npm install
npm run build
cd ..

3. Configure (Optional)

Edit .env with your Polymarket credentials. Without credentials, the system runs in simulation mode — all trading logic executes but orders are simulated.

4. Run

python main.py

Open http://localhost:8899 in your browser to see the dashboard.


Configuration

All settings are in .env (see .env.template for defaults):

Polymarket Credentials

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

Market IDs

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

Trading Parameters

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)

Server

Variable Default Description
HOST 0.0.0.0 Bind address
PORT 8899 HTTP/WS port

Signal Engine

The signal engine combines 5 indicators to produce a directional confidence score:

1. Window Delta (max +55% confidence)

Compares current price vs. cycle start price.
Only activates when Δ > 0.1%, with weight scaling up to Δ = 0.4%.

2. CVD Confirmation (max +25% confidence)

Cumulative Volume Delta over the last 60 seconds.
Confirms or conflicts with the Window Delta direction.

3. OFI — Order Flow Imbalance (max +20% confidence)

Tracks best bid/ask changes from the Binance depth5 stream.
Uses configurable exponential smoothing (OFI_ALPHA).

4. CVD Divergence (−30% penalty)

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 ↑).

5. Liquidity Sweep / Pin Bar (−20% penalty)

Detects price briefly breaking above/below cycle extremes then reversing.
Also checks wick-to-range ratio for pin bar patterns.

6. Flash Candle Guard (hard block)

If price moves > 0.5% within 1 second, or volume spikes 5x above 3s average,
the trade is completely blocked to avoid liquidity traps.

Confidence Calculation

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.


Trading Logic

Fee-Aware Execution

Uses the formula: fee = C · feeRate · p · (1 − p)

Trades are skipped when:

  • Market price p is 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

Sniper Window

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

Settlement direction is determined by:

  1. Chainlink Oracle prices (if available via Polymarket WS) — this matches Polymarket's actual settlement oracle
  2. 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)

Safety Features

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

Dashboard

The React dashboard provides real-time monitoring at 5 Hz update rate.

Panels

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.

Controls

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

API Reference

REST

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

WebSocket

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

Development

Frontend Dev Mode

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 dev

Then open http://localhost:5173 — Vite proxies WebSocket and API calls to the backend.

Project Structure

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

Troubleshooting

"Frontend not built" message

Run cd frontend && npm install && npm run build, then restart the backend.

No trades executing

  1. Check MIN_CONFIDENCE — the signal must exceed this threshold
  2. Check if circuit breaker is ON (dashboard Controls panel)
  3. Trades only execute during the sniper window (15s–5s before cycle end)
  4. Check the Signal panel for block reasons (flash candle, divergence, etc.)

Binance WS disconnects

Normal behavior — the system auto-reconnects with exponential backoff (1s → 2s → 4s → … → 30s max). Check the connection indicator in the dashboard header.

Simulation vs Live mode

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

Port already in use

Change the PORT in .env or stop the existing process:

lsof -ti:8899 | xargs kill

⚠️ Disclaimer

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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0