📊 Polymarket Bot

Панель исследований и торговли
Бумажный режим Обновлено:
Банкролл
$0.00
Доступно: $0.00
Общий P&L
$0.00
Нереализовано: $0.00
Открытые позиции
0
Инвестировано: $0.00
Всего сделок
0
Реал: 0 | Бумага: 0
Средний Edge
0.00%
Ср. EQ: 0.000
Активность сегодня
0 сделок
Объём: $0.00

📈 Прогнозы и сделки

🎯 Edge и качество данных

🏷️ Типы рынков

💰 Кривая капитала (Кумулятивный P&L)

🤖 AI Trading
$0.00
0 сделок | Win rate: 0%
⚡ Short-Term AI
$0.00
0 сделок | Win rate: 0%
Статус движка
OFF
Циклы: 0
Просадка
0.0%
Пик: $0 | Текущий: $0
Нагрев
🟢 Спокойно
Множитель Kelly: 1.0x
Аварийный стоп
OFF

🌡️ Режим рынка

Текущий режим
NORMAL
Уверенность: —
Множитель Kelly
1.00x
Размер: 1.00x
Описание режима

📋 Активные позиции

РынокТипНаправлениеВходТекущая РазмерСтавкаP&LP&L %Δ ЦенаДержится
Нет активных позиций

🔬 Кандидаты

ЦиклРынокТипImplied PModel P EdgeEQИсточникиУверенность РешениеСтавкаПричинаВремя
Кандидаты ещё не обработаны

🔮 Последние прогнозы

РынокТипImplied PModel PEdge EQИсточникиУверенностьРешениеВремя
Прогнозов пока нет

📜 История сделок

РынокНаправлениеВходВыход / Текущая СтавкаP&LP&L %Статус Причина закрытияДлительностьРежимОткрыто
Сделок пока нет

📊 Аналитика результатов

Процент побед
7d: — | 30d: —
Коэффициент Шарпа
Sortino: —
Фактор прибыли
Ср. выигрыш/проигрыш: —
Макс. просадка
Calmar: —
ROI
Всего поставлено: —
Серия
Лучшая: — | Худшая: —

📊 P&L по категориям

🎯 Точность калибровки

🤖 Точность моделей

🏆 Рейтинг стратегий

РангКатегорияROI %Процент побед Общий P&LСделкиСредний EdgeОценка
Нет данных аналитики — заполняется по мере закрытия сделок

🐋 Терминал умных денег

● ПРЯМОЙ ЭФИР
Последнее сканирование: — | 0 кошельков | ⟳ 30s

🔍 Сканер китов ликвидных рынков

Мульти-источники: Лидерборд · Глобальная лента сделок · Сканирование по рынкам · Умная дедупликация
● ОЖИДАНИЕ
Leaderboard
🏦
Рынки
📡
Глобальные сделки
📊
Сделки рынков
Ранжирование
🔬
Анализ
💾
Оценка и сохранение
🏦
0
Ликвидные рынки
🔄
0
Просканировано / Цикл
📡
0
Сделок проанализировано
🔎
0
Адресов найдено
👛
0
Кошельков проанализировано
🐋
0
Кандидаты
0
Продвинуто
🏆
0
Лидерборд
📊
0
Сделки рынков
⏱️
Время сканирования

Распределение оценок

🏆 Лучшие кандидаты-киты

0 кандидатов
Запустите сканирование для поиска китов
🔭
Отслеживаемые кошельки
0
0 позиций
🎯
Сигналы убеждённости
0
Сильные: 0 · Mod: 0
🧠
Индекс умных денег
50
Нейтрально
💰
Чистый поток китов
$0
In: $0 · Out: $0
📊
Ср. % побед
0%
Total P&L: $0
🏆
Топ убеждённость
0

🧠 Индекс умных денег

🐻 Медвежьи Нейтрально Бычьи 🐂

Индекс умных денег агрегирует убеждённость китов по всем активным сигналам, взвешенных по размеру позиции.

📡 Разбивка потоков

🟢 Входы
0
📈 Размер ↑
0
📉 Размер ↓
0
🔴 Выходы
0

📈 Моментум китов (Чистый поток по окнам)

⚡ Скорость позиций (Действия/Час)

1h 0
6h 0
24h 0
🐑 Индекс стадного поведения
0%

📊 Направление сигналов

🏔️ Топ рынков по капиталу китов

🏷️ Разбивка по категориям

⏱️ Хронология активности (Последние 24 часа)

Нет Низко Средне Высоко Всплеск

🔄 Накопление / Распределение

Чистое давление покупок и продаж по рынку
Данных накопления пока нет

🔗 Матрица пересечений китов

Общие позиции между китами по рынкам
Данных пересечений китов пока нет

🔥 Алерты высокого консенсуса 0

Рынки, где 3+ кита согласны по одному исходу — сильнейшие сигналы умных денег.

Сигналов высокого консенсуса пока нет

🎯 Сигналы убеждённости

РынокКатегорияИсход🐋Капитал ВходТекущаяEdgeУбеждённость ТрендСилаСвежийВозрастНап.
Сигналов убеждённости нет — запустите сканирование кошельков

📡 Лента активности

Активности китов пока не обнаружено

🏆 Рейтинг китов

Кошельки не отслеживаются

🔔 История алертов 0

Постоянный лог всех алертов рисков, обнаруженных сканером китов
Алертов пока не зафиксировано

🧠 Центр аналитики решений

● ПРЯМОЙ ЭФИР
Последний цикл: — | 0 решений
📊
0
Всего решений
0%
Доля сделок
🎯
Ср. DI Score
📈
Средний Edge
📚
Ср. качество данных
Завершённость пайплайна
🏷️
Топ категория
🏆
Ср. оценка

📊 Распределение решений

🏆 Распределение оценок

📈 Распределение Edge

🏷️ Разбивка по категориям

🕐 Хронология активности

⚡ Воронка пайплайна

💡 Автосгенерированные инсайты

0
Инсайтов пока нет — запустите больше циклов для генерации паттернов.

📈 Тренд DI Score и доли сделок

🎯 Калибровка уверенности

Данных калибровки пока нет.

🏆 Рейтинг производительности по категориям

Данных по категориям пока нет.

🎯 Результаты сделок

0
Данных о результатах пока нет.

📚 ROI качества исследований

Данных о ROI исследований пока нет.

🔍 Упущенные возможности

0
Упущенных возможностей не обнаружено.
Данных решений пока нет — запустите цикл движка, чтобы увидеть решения бота.

🎯 Стратегии и кошельки

● ПРЯМОЙ ЭФИР
💰
$0
Общий баланс
📈
$0
Общий P&L
📄
0
Бумажные кошельки
🔑
0
Живые кошельки
🤖
0
Активные стратегии
📊
0
Всего сделок

💰 Кошельки

Загрузка кошельков…

🤖 Стратегии

Загрузка стратегий…

📉 Value-at-Risk портфеля

VaR 95%
$0.00
VaR 99%
$0.00
Ожидаемые потери
$0.00
Позиции
0

📈 История капитала (снимки каждые 5 мин)

👁️ Список наблюдения

РынокКатегорияДобавленоЗаметки
Список наблюдения пуст

📓 Журнал сделок

Записей в журнале пока нет. Записи создаются автоматически при закрытии сделок.

Здоровье системы
Время работы
С: —
Циклов движка
0
Интервал: —
Размер БД
0 MB
Строк: 0
Оцен. стоимость API
$0.00
LLM: $0.00 | Поиск: $0.00
API ключи
0 / 0
Настроено
Файл логов
0 MB
Строк: 0
Память (RSS)
0 MB
Потоков: 0
Победы / Поражения
0 / 0
Нейтральных: 0

📉 Производительность циклов

🏥 Состояние движка

Статус
Поток активен
Режим
Количество циклов 0
Интервал цикла
Последняя ошибка Нет

⚠️ Монитор рисков

Дневная экспозиция
$0 / $0
Открытые позиции
0 / 0
Качество данных (средняя)
0.00 / min 0.00

🔑 API ключи и учётные данные

0 / 0 настроено

Введите ваши API ключи ниже. Значения хранятся в .env и загружаются при запуске. Некоторые изменения требуют перезапуска движка.

Загрузка API ключей…

🚩 Флаги функций

Нажмите переключатель — сохраняется немедленно

Загрузка флагов…

📋 Вся конфигурация

Отредактируйте любое значение и нажмите Сохранить для записи в config.yaml. Изменения применяются сразу.

Загрузка конфигурации…

💰 API: использование и стоимость

Вызовы LLM
0
Модель: —
Всего токенов
0
Вход: 0 | Выход: 0
Поисковые запросы
0
Стоимость: $0.00
Ошибки API
0
Всего ошибок

⏱️ Ограничитель запросов

ЭндпоинтВсего запросовВсего ожиданийДоля ожидания
Данных о лимитах нет

📊 Сводка торговой активности

Всего прогнозов 0
Прогнозов сегодня 0
Всего сделок 0
Сделок сегодня 0
Ср. кандидатов/цикл 0

🔒 Журнал аудита

IDРынокРешениеЭтап ДеталиЦелостностьВремя
Записей аудита нет

🔔 Таблица алертов

УровеньКаналСообщениеВремя
Алертов нет

🗄️ Таблицы базы данных

ТаблицаСтрокШкалаСтатусЭкспорт
Загрузка…

💿 Использование хранилища

📈 Внутренние метрики

Счётчики

Измерители

Гистограммы

🔔 Последние алерты

Алертов пока нет

💻 Информация о системе

Имя хоста
Платформа
Python
Архитектура
PID
Ядер CPU
Открытых FD
Путь к БД
Путь к конфигу
Конфиг изменён

💾 Файлы резервных копий

Имя файлаРазмерДата изменения
Резервных копий не найдено

📜 Последние записи лога

Загрузка лога…

⛔ Опасная зона

Эти действия необратимы. Действуйте с крайней осторожностью.

Очистить старые данные Удалить кандидатов, алерты и логи моделей старше 30 дней
Ротация файлов логов Архивировать текущий лог и начать заново
Сбросить все метрики Очистить все счётчики, измерители и гистограммы в памяти

Polymarket — Бот исследований и торговли

Version 0.2.0 · MIT License · Python 3.9+

Что это?

A production-grade, AI-powered autonomous trading agent for Polymarket prediction markets. It discovers markets, gathers authoritative evidence from whitelisted sources, generates calibrated probability forecasts using an LLM ensemble, enforces strict risk controls, and executes trades with fractional Kelly sizing.

Ключевые возможности

🔍

Обнаружение рынков

Auto-scans Polymarket's Gamma API for markets matching volume, liquidity, spread, and category filters.

📚

Исследование на основе данных

Fetches sources from whitelisted authoritative domains (bls.gov, sec.gov, etc.) with LLM-powered evidence extraction.

🧠

Ансамбль нескольких моделей

Queries GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro in parallel with adaptive weighting and Platt calibration.

🛡️

Движок рисков (15 проверок)

Kill switch, drawdown management, portfolio limits, min edge, evidence quality gates, and more. ALL must pass.

📐

Размер позиции по Kelly

Fractional Kelly criterion with confidence scaling, drawdown heat multiplier, and liquidity-aware caps.

🐋

Отслеживание китов

Monitors top Polymarket leaderboard wallets for smart-money conviction signals to boost or penalize edge.

Архитектура

The bot follows a modular pipeline architecture with clear separation of concerns:

┌─────────────────────────────────────────────────────────────────────┐
│                         CLI (Click) / Dashboard (Flask)             │
│  scan │ research │ forecast │ paper-trade │ trade │ engine │ dash   │
├───────┴──────────┴──────────┴─────────────┴───────┴────────┴───────┤
│                                                                     │
│  Connectors          Research             Forecast                  │
│  ┌──────────────┐    ┌───────────────┐    ┌───────────────────┐    │
│  │ Gamma API    │    │ Query Builder │    │ Feature Builder    │    │
│  │ CLOB API     │───▶│ Source Fetcher│───▶│ LLM Forecaster    │    │
│  │ Web Search   │    │ Evidence Ext. │    │ Ensemble (3 LLMs) │    │
│  │ WebSocket    │    └───────────────┘    │ Calibrator         │    │
│  │ Rate Limiter │                         └───────────────────┘    │
│  └──────────────┘                                │                  │
│                                                  ▼                  │
│  Policy                        Analytics                            │
│  ┌─────────────────────┐       ┌──────────────────────────┐        │
│  │ Edge Calculator     │       │ Regime Detector          │        │
│  │ Risk Limits (15)    │◀─────▶│ Calibration Feedback     │        │
│  │ Position Sizer      │       │ Adaptive Model Weights   │        │
│  │ Drawdown Manager    │       │ Smart Entry Calculator   │        │
│  │ Portfolio Risk      │       │ Wallet Scanner           │        │
│  │ Timeline Intel      │       └──────────────────────────┘        │
│  └─────────────────────┘                                            │
│            │                                                        │
│            ▼                                                        │
│  Execution                     Storage / Observability              │
│  ┌─────────────────────┐       ┌──────────────────────────┐        │
│  │ Order Builder        │       │ SQLite + WAL + Migrations│        │
│  │ Order Router (dry)   │       │ structlog JSON Logging   │        │
│  │ Fill Tracker         │       │ In-Process Metrics       │        │
│  │ Cancel Manager       │       │ Alerts (Telegram/Slack)  │        │
│  │ TWAP / Iceberg       │       │ JSON Run Reports         │        │
│  └─────────────────────┘       └──────────────────────────┘        │
└─────────────────────────────────────────────────────────────────────┘

Module Map

PackagePurposeKey Files
src/connectors/External API integrationspolymarket_gamma.py, polymarket_clob.py, web_search.py, ws_feed.py
src/research/Evidence gathering pipelinequery_builder.py, source_fetcher.py, evidence_extractor.py
src/forecast/Probability forecastingensemble.py, llm_forecaster.py, calibrator.py, feature_builder.py
src/policy/Risk & sizing decisionsrisk_limits.py, position_sizer.py, edge_calc.py, drawdown.py, portfolio_risk.py
src/execution/Order managementorder_builder.py, order_router.py, fill_tracker.py, cancels.py
src/engine/Continuous trading looploop.py, market_filter.py, market_classifier.py, event_monitor.py
src/analytics/Self-improving analyticsregime_detector.py, adaptive_weights.py, calibration_feedback.py, smart_entry.py, wallet_scanner.py
src/storage/Persistence layerdatabase.py, models.py, migrations.py, cache.py, audit.py
src/observability/Logging & monitoringlogger.py, metrics.py, alerts.py, reports.py, sentry_integration.py
src/dashboard/Web UIapp.py, templates/index.html, static/dashboard.js, static/style.css

Торговый пайплайн

Every trading cycle follows this deterministic pipeline. Each step must succeed for the next to proceed:

1

Обнаружение рынков

Gamma API scan → filter by volume, liquidity, spread, category → classify market type

2

Research & Evidence Gathering

Build site-restricted queries → fetch from whitelisted sources → LLM extracts structured evidence with citations

3

Feature Engineering

30+ features from market data, orderbook, trade history, and evidence quality scores

4

LLM Ensemble Forecast

GPT-4o + Claude 3.5 Sonnet + Gemini 1.5 Pro queried in parallel → trimmed mean aggregation

5

Калибровка

Platt scaling shrinks extremes toward 0.5 → low-evidence penalty → contradiction penalty → historical calibration learning

6

Расчёт Edge

Edge = model_prob − implied_prob → deduct transaction costs → determine BUY_YES or BUY_NO direction

7

Risk Check (15 rules)

Kill switch, drawdown, max stake, daily loss, open positions, min edge, liquidity, spread, evidence quality, confidence, implied prob floor, edge direction, market type, portfolio exposure, timeline

8

Размер позиции

Fractional Kelly × confidence × drawdown heat × timeline × volatility × regime × category multipliers

9

Исполнение ордеров

Build limit/market/TWAP/iceberg order → route through triple dry-run gate → submit to CLOB or simulate

Market Discovery & Classification

The bot discovers markets through Polymarket's Gamma REST API and automatically classifies them by keyword matching.

Scanning Filters

FilterDefaultConfig KeyDescription
Minimum Volume$1,000scanning.min_volume_usdMarkets below this total volume are skipped
Minimum Liquidity$500scanning.min_liquidity_usdCurrent available liquidity threshold
Maximum Spread8%scanning.max_spreadMarkets with wide bid-ask spreads are illiquid
Max Days to Expiry120scanning.max_days_to_expirySkip markets too far from resolution
Batch Size100scanning.batch_sizeMarkets fetched per API call
Research Cooldown60 minscanning.research_cooldown_minutesDon't re-research the same market within this window

Market Type Classification

Markets are classified by matching keywords in the question text:

ТипExample KeywordsPrimary Sources
MACROCPI, inflation, GDP, unemployment, Fed, FOMCbls.gov, federalreserve.gov, fred.stlouisfed.org
ELECTIONelection, vote, president, senate, pollfec.gov, ballotpedia.org
CORPORATEIPO, earnings, stock, SEC, mergersec.gov, investor relations
WEATHERhurricane, temperature, NOAA, wildfireweather.gov, noaa.gov
SPORTSNFL, NBA, Super Bowl, championshipespn.com, sports-reference.com

Pre-Research Filter

Before spending API credits on research, markets are scored (0-100) on volume, liquidity, recency, and category. Markets scoring below filter_min_score (default 25) are skipped. Markets of type UNKNOWN are blocked entirely.

Движок исследований

The research module implements a source-first, whitelisted search pipeline to ensure evidence comes from authoritative sources.

Query Strategy (4 phases)

1
Site-Restricted Queries — Searches primary authoritative domains per market type (e.g., site:bls.gov CPI January 2026)
2
Metric-Specific Queries — Date-scoped searches for specific data releases and official numbers
3
Confirmation Queries — Secondary outlets (Reuters, Bloomberg) for corroboration
4
Contrarian Queries — Deliberately searches for opposing evidence to reduce overconfidence bias

Evidence Extraction

An LLM processes fetched sources to extract structured evidence. Every bullet must include:

{
  "text": "CPI-U increased 3.1% YoY in January 2026",
  "metric_name": "CPI-U YoY",
  "metric_value": "3.1",
  "metric_unit": "percent",
  "metric_date": "2026-01-31",
  "confidence": 0.97,
  "citation": {
    "url": "https://www.bls.gov/...",
    "publisher": "Bureau of Labor Statistics",
    "authority_score": 1.0
  }
}

Evidence Quality Scoring

Quality is computed independently of LLM self-assessment using:

  • Source recency — Penalty for stale data (>7 days old, severe >30 days)
  • Domain authority — Government sources score 1.0, news outlets 0.6-0.8
  • Cross-source agreement — Multiple sources confirming the same metric
  • Numeric density — Bonus for evidence with concrete numbers, dates, and units
  • Contradiction detection — Conflicting sources reduce confidence

Search Providers

ProviderEnv VariableNotes
TavilyTAVILY_API_KEYPreferred; purpose-built for research agents
SerpAPISERPAPI_KEYGoogle search results
BingBING_API_KEYMicrosoft Bing search
FallbackAny availableTries each provider in order (default mode)

Blocked Domains

The following domains are always excluded: wikipedia.org, reddit.com, medium.com, twitter.com/x.com, quora.com, and other user-generated content sites.

Прогнозирование и ансамбль

The forecasting system queries multiple Large Language Models in parallel to produce probability estimates.

Ensemble Architecture

ModelProviderDefault WeightEnv Variable
GPT-4oOpenAI40%OPENAI_API_KEY
Claude 3.5 SonnetAnthropic35%ANTHROPIC_API_KEY
Gemini 1.5 ProGoogle25%GOOGLE_API_KEY

Aggregation Methods

  • Trimmed Mean (default) — Removes the highest and lowest forecasts, averages the rest. Robust to outlier models.
  • Median — Takes the middle forecast. Completely resistant to outliers.
  • Weighted — Uses per-model weights (static or adaptive). Best when model quality is known.

Graceful Degradation

If some models fail (API errors, timeouts), the ensemble degrades gracefully. It requires min_models_required (default 1) to succeed. If all models fail, it falls back to a single-model query to fallback_model (default: GPT-4o).

Prompt Structure

Each model receives: the market question, market type, evidence summary, top evidence bullets, contradictions, and market features (volume, spread, implied probability, days to resolution). The model must return a probability (0-1), confidence level (LOW/MEDIUM/HIGH), reasoning, and invalidation triggers.

Adaptive Model Weights

The AdaptiveModelWeighter module tracks per-model, per-category Brier scores from resolved markets. It computes inverse-Brier weights so that models with better track records in a specific category receive more influence. Uses Bayesian smoothing to blend learned weights with priors, requiring 50+ samples for full confidence.

Калибровка

Raw LLM probabilities are systematically adjusted for better real-world calibration.

Platt Scaling (Default)

Applies logistic compression with shrinkage toward 0.5. This counteracts the tendency of LLMs to produce overconfident extreme probabilities.

Formula:

calibrated = sigmoid(a × logit(raw) + b)

Where a < 1 provides shrinkage (pulling extremes inward) and b provides a base-rate shift.

Adjustments Applied

  • Shrinkage — Extreme probabilities (>0.95 or <0.05) are pulled toward 0.5
  • Low-Evidence Penalty — Up to 15% penalty when evidence quality is below threshold
  • Contradiction Penalty — Each contradiction reduces confidence proportionally
  • Ensemble Disagreement — Wide spread among models triggers additional shrinkage

Historical Calibration Learning

The CalibrationFeedbackLoop records every (forecast, outcome) pair when markets resolve. After 30+ samples, the bot trains a logistic regression to learn optimal calibration parameters from its own track record, becoming more accurate over time.

Расчёт Edge

Edge measures the difference between the bot's model probability and the market-implied probability.

Core Formula:

raw_edge = model_probability − implied_probability

net_edge = |raw_edge| − transaction_cost_pct

Direction Logic

  • If model_prob > implied_probBUY YES (the market underestimates probability)
  • If model_prob < implied_probBUY NO (the market overestimates probability)

Transaction Costs

Costs include entry fees (transaction_fee_pct, default 2%) and gas costs. The bot uses a hold-to-resolution model (single-leg entry, no exit trade), so only entry costs are deducted.

Expected Value

EV per dollar = (model_prob × $1 − cost) / cost. Only positive net-EV trades pass risk checks.

Управление рисками

The risk engine enforces 15 independent checks. A trade is only allowed if ALL pass. Any single violation blocks the trade.

1
Аварийный стоп
Manual global halt; immediately stops all trading
2
Drawdown Kill
Auto-kill when drawdown exceeds max (default 20%)
3
Drawdown Heat
Reduces sizing at heat level 2+; blocks at level 3
4
Max Stake
No single trade exceeds max_stake_per_market ($50)
5
Daily Loss Limit
Cumulative daily losses capped at max_daily_loss ($500)
6
Открытые позиции
Maximum concurrent positions (default 25)
7
Minimum Edge
Net edge after costs must exceed min_edge (default 4%)
8
Min Liquidity
Market must have sufficient liquidity ($2,000 default)
9
Max Spread
Bid-ask spread must be under max_spread (default 6%)
10
Evidence Quality
Must meet min_evidence_quality threshold (default 0.55)
11
Confidence Level
Rejects LOW confidence forecasts (requires MEDIUM+)
12
Implied Prob Floor
Blocks micro-probability markets (<5% implied)
13
Edge Direction
Edge must be positive after costs in the chosen direction
14
Market Type
Market category must be in allowed list (not restricted)
15
Portfolio Exposure
Category and event exposure within portfolio limits

Position Sizing (Kelly Criterion)

Position sizes are computed using the fractional Kelly criterion with multiple adjustment layers.

Kelly Formula (Binary Outcome):

f* = (p × b − q) / b

Where: p = model probability, q = 1−p, b = odds = (1/cost) − 1

Adjustment Multipliers

MultiplierSourceRangePurpose
Kelly FractionConfig0.25 (quarter-Kelly)Reduces full Kelly for real-world variance
ConfidenceLLM ForecastLOW=0.5, MED=0.75, HIGH=1.0Scale by forecast confidence
Drawdown HeatDrawdownManager0.0 – 1.0Reduce sizing during drawdowns
TimelineTimelineAssessment0.5 – 1.3Adjust for resolution timing
VolatilityMarket microstructure0.0 – 1.0Reduce in volatile markets
RegimeRegimeDetector0.5 – 1.0Reduce in HIGH_VOLATILITY regime
CategoryConfig per-categoryMACRO=1.0, CORP=0.75, ELEC=0.5Category-specific risk appetite

Caps

  • max_stake_per_market — Hard cap per trade (default $50)
  • max_bankroll_fraction — No trade exceeds 5% of bankroll
  • Liquidity cap — Stake capped at 5% of available market liquidity

Drawdown Management

The drawdown system tracks the equity curve and progressively reduces risk during losing periods.

Heat Levels

LevelDrawdown %Kelly MultiplierAction
0 (Cool)<10%1.00Normal trading
1 (Warning)10%0.50Position sizes halved
2 (Critical)15%0.25Position sizes quartered
3 (Kill)20%0.00All trading halted (kill switch)
Auto-Kill Switch:

When auto_kill_at_max: true (default), the bot automatically engages the kill switch at max drawdown. This prevents catastrophic losses but requires manual reset to resume trading.

Portfolio Risk Management

Portfolio-level constraints prevent over-concentration and correlated losses.

ConstraintDefaultDescription
Max Category Exposure35%No single market category can exceed this % of bankroll
Max Event Exposure25%No single event (grouped markets) can exceed this %
Max Correlated Positions4Limit on positions with >70% correlation similarity
Category LimitsMACRO: 40%, ELEC: 35%, CORP: 30%Per-category exposure caps

Исполнение ордеров

The execution layer builds orders and routes them through safety checks before submission.

Order Types

  • Limit Orders — Default; placed at calculated price with TTL (default 300s)
  • Market Orders — Immediate fill at current price; used for urgent entries
  • TWAP — Time-Weighted Average Price; splits large orders into 5 slices over 30s intervals
  • Iceberg — Hides order size; shows only 20% of total, refills as filled. Triggered at $500+ orders

Triple Dry-Run Gate

Three independent gates prevent accidental live trading:
  1. order.dry_run flag on the order object itself
  2. config.execution.dry_run in config.yaml (default: true)
  3. ENABLE_LIVE_TRADING environment variable (must be "true")

ALL THREE must allow live trading for any order to be submitted to the CLOB.

Smart Entry Timing

The SmartEntryCalculator calculates optimal entry levels using orderbook depth analysis, VWAP divergence, microstructure signals, and momentum. This can improve entry prices by 1-3% (10-30 basis points).

Position Exits

Exit TriggerDefaultDescription
Stop Loss20%Exit when position loses 20% of entry value
Take Profit30%Exit when position gains 30%
Max Holding Time240 hoursAuto-exit positions held longer than 10 days
Resolution / 100%N/AExit when market resolves or price reaches 100%

Continuous Trading Engine

The engine runs the full pipeline in a loop, coordinating all components autonomously.

Cycle (Default: every 3 minutes)

1
Discover & filter markets from Gamma API
2
Classify and score candidate markets
3
Research top candidates (evidence gathering)
4
Forecast probabilities via LLM ensemble
5
Calculate edges and check risk limits
6
Size positions and build orders
7
Route orders (paper or live)
8
Monitor existing positions for exits
9
Update drawdown state and persist to DB

Between Cycles

  • Check drawdown state and heat level
  • Monitor position exits (stop-loss, take-profit, time-based, resolution)
  • Scan whale wallet activity
  • Detect market regime changes
  • Persist engine state to DB for dashboard visibility

Analytics & Regime Detection

Market Regime Detector

Adapts strategy based on detected market conditions:

RegimeDetection SignalStrategy Adjustment
NORMALStable spreads, moderate volumeStandard parameters
TRENDINGDirectional price momentumFavor momentum entries
MEAN_REVERTINGOscillating pricesContrarian entries, more patience
HIGH_VOLATILITYWide spreads, rapid price swingsReduce sizes, raise edge threshold
LOW_ACTIVITYLow volume, few marketsConservative, fewer trades

Calibration Feedback Loop

When markets resolve, the bot records (forecast_prob, actual_outcome) pairs and periodically retrains calibration. Per-model accuracy is tracked for adaptive weighting. This creates a self-improving system that gets more accurate over time.

Performance Tracking

The analytics module tracks: win rate, Brier score, Sharpe ratio, max drawdown, average edge, P&L by category, accuracy by confidence level, and more.

Whale / Smart-Money Scanner

The Whale Tracker is a comprehensive smart-money intelligence system that monitors the top 15 Polymarket leaderboard wallets and generates actionable signals. It provides real-time visibility into what the most profitable traders are doing.

Архитектура

The scanner runs on a 15-minute cycle within the bot's main engine loop:

  • Phase 1 – Fetch: Queries positions for all 15 tracked wallets via the Data API (up to 200 positions each)
  • Phase 2 – Score: Computes a composite quality score (0-100) per wallet based on P&L, win rate, and activity
  • Phase 3 – Delta Detection: Compares current positions against the previous snapshot to identify new entries, exits, and size changes (>10% threshold)
  • Phase 4 – Conviction Signals: Groups positions by market+outcome and generates conviction signals where 2+ whales agree

Smart Money Index (SMI)

A proprietary aggregate indicator (0-100) computed from all active whale signals, weighted by position size:

SMI RangeInterpretationDescription
70-100Very БычьиСильные net positive whale conviction across markets
60-70БычьиУмеренные positive bias from smart money
40-60NeutralMixed signals — no clear directional consensus
30-40МедвежьиУмеренные negative bias from smart money
0-30Very МедвежьиСильные net negative whale conviction
How SMI is Calculated:

SMI = (Σ bullish_conviction × position_usd) / (Σ all_conviction × position_usd) × 100. A value of 50 means equal bullish and bearish conviction-weighted capital.

Conviction Scoring

Each market where 2+ whales hold the same outcome receives a conviction score (0-100):

ComponentWeightDescription
Whale Count25 pts/whaleMore whales on same market = higher conviction
Capital Sizelog₁₀(USD) × 8Logarithmic scaling of total whale capital committed
Фактор прибылиUp to 15 ptsBonus when whales are in profit (entry < current price)

Signal strength classification:

StrengthScore RangeDashboard Badge
🟢 STRONG≥70Green pill — highest confidence signals
🟡 MODERATE45-69Orange pill — worth monitoring
WEAK30-44Gray pill — low confidence

High Consensus Alerts

When 3+ whales agree on the same market outcome, a "High Consensus Alert" is triggered. These are the strongest smart money signals and appear as highlighted cards in the dashboard. The bot uses these for whale-edge convergence detection.

Чистый поток китов

Tracks aggregate capital entering vs. exiting whale positions:

  • Flow In: Sum of $ from NEW_ENTRY and SIZE_INCREASE deltas
  • Flow Out: Sum of $ from EXIT and SIZE_DECREASE deltas
  • Net Flow: Flow In - Flow Out (positive = net accumulation, negative = net distribution)

Whale Tier System

Each tracked wallet is classified into a performance tier based on total P&L:

TierP&L ThresholdIcon
👑 LEGENDARY≥$2MGold crown
💎 ELITE≥$1MPurple diamond
PRO≥$500KBlue star
🌱 RISING<$500KGreen seedling

Delta Detection

Position changes tracked between scan cycles:

ActionTriggerFeed Icon
NEW_ENTRYPosition appears for first time🟢
EXITPosition disappears from snapshot🔴
SIZE_INCREASEPosition size grows >10%📈
SIZE_DECREASEPosition size shrinks >10%📉

Dashboard Components

The Whale Tracker tab includes:

  • 6 KPI Cards: Tracked Wallets, Conviction Signals, Smart Money Index, Net Whale Flow, Avg Win Rate, Top Conviction
  • SMI Gauge: Visual gauge showing bullish/bearish sentiment with animated fill
  • Flow Breakdown: Bar chart of entry/exit/increase/decrease activity
  • Direction Distribution: Doughnut chart (bullish vs bearish signals)
  • Top Markets by Whale Capital: Horizontal bar chart of most concentrated markets
  • High Consensus Alerts: Highlighted cards for 3+ whale agreement
  • Conviction Signals Table: Filterable table with conviction progress bars
  • Live Activity Feed: Styled event feed of whale moves with icons
  • Whale Leaderboard: Card-based leaderboard with tiers, scores, and activity counts

Edge Integration

ScenarioAdjustmentDefault
Whales agree with modelEdge boost+8%
Whales disagree with modelEdge penalty−2%
Whale + model convergenceLower min_edgeDown to 2%
Tracked Wallets:

The scanner monitors 15 wallets scraped from Polymarket's leaderboard, with combined P&L exceeding $18M. Wallet list is defined in wallet_scanner.py and can be customized.

Database Tables

TablePurpose
tracked_walletsWallet metadata: address, name, P&L, win rate, score
wallet_signalsConviction signals per market+outcome (unique constraint)
wallet_deltasPosition change events (entries, exits, size changes)

API Endpoint

GET /api/whale-activity

Returns: tracked_wallets, conviction_signals, recent_deltas, high_consensus_signals, top_markets, and summary (including SMI, net flow, direction distribution, action breakdown, tier enrichment).

Decision Intelligence Log

A comprehensive audit trail of every decision the engine makes, from market scanning through trade execution. Provides full transparency into the AI's reasoning process.

What Gets Logged

  • SCAN: Market discovery and initial filtering decisions
  • RESEARCH: Evidence gathering, source quality, query construction
  • FORECAST: Probability estimates from individual models and the ensemble
  • EDGE: Edge calculations — market price vs. forecast probability
  • RISK: Risk check passes/failures (drawdown, exposure, position limits)
  • SIZE: Position sizing decisions (Kelly fraction, scaling)
  • EXECUTE: Order submission, fill tracking, simulated execution
  • MONITOR: Position monitoring, TP/SL proximity, exit triggers

Dashboard Tab Features

  • Real-time feed of all decisions with timestamps
  • Color-coded decision types (TRADE, NO_TRADE, SKIP, ERROR)
  • Filter by stage (SCAN, RESEARCH, FORECAST, etc.)
  • Search across all decision fields
  • Integrity verification via SHA-256 hashes
  • Summary cards: total decisions, trade rate, top categories

API Endpoint

GET /api/decision-log

Returns: entries (decision records with id, market_id, decision, stage, details, integrity_hash, timestamp), summary (total, by_stage breakdown, by_decision breakdown, recent_rate).

Data Integrity

Each decision entry includes a SHA-256 integrity_hash computed from the decision data, ensuring the audit trail cannot be tampered with. The dashboard shows a ✅ indicator for verified entries.

Стратегии и кошельки

A portfolio management system for organizing trading activity across multiple wallets and strategies, enabling multi-strategy allocation and performance tracking.

Core Concepts

ConceptDescription
КошелёкA funding source with a name, address (optional), initial balance, and P&L tracking
СтратегияA named trading approach (e.g., "AI Trading", "Momentum", "Arbitrage") with its own risk parameters and description
BindingA many-to-many link between strategies and wallets, controlling how capital is allocated across approaches

Database Tables

TablePurpose
walletsWallet metadata: name, address, balance, P&L, status, created/updated timestamps
strategiesStrategy definitions: name, description, type, risk level, status
strategy_walletsMany-to-many binding with allocation percentage per pair
wallet_tradesTrade records linked to specific wallets
wallet_equity_snapshotsPoint-in-time equity snapshots for equity curve charting

API Endpoints

MethodEndpointDescription
GET/api/strategies-overviewFull overview: wallets, strategies, bindings, summary stats
POST/api/walletsCreate a new wallet
PUT/api/wallets/<id>Update wallet (name, balance, status)
DELETE/api/wallets/<id>Delete a wallet
POST/api/strategiesCreate a new strategy
PUT/api/strategies/<id>Update strategy details
DELETE/api/strategies/<id>Delete a strategy
POST/api/strategy-wallets/bindBind a strategy to a wallet with allocation %
DELETE/api/strategy-wallets/unbindUnbind a strategy from a wallet

Dashboard Tab

The Strategies tab provides a visual interface to:

  • View all wallets with balance, P&L, status, and linked strategies
  • View all strategies with risk levels, descriptions, and linked wallets
  • Create, edit, and delete wallets and strategies via modal dialogs
  • Bind/unbind strategies to wallets with allocation percentages
  • Summary cards showing total capital, active wallets, total P&L, and average allocation

API коннекторы

Gamma API (Market Discovery)

The GammaClient connects to Polymarket's public market-listing API at https://gamma-api.polymarket.com. Used for: listing markets, fetching metadata (question, category, end date, resolution source), and getting pricing snapshots.

CLOB API (Orderbook & Trading)

The CLOBClient connects to https://clob.polymarket.com for real-time orderbook data (bids/asks), trade history, spread calculations, and order placement via the py-clob-client signing library.

WebSocket Feed

The WebSocketFeed subscribes to real-time price ticks for monitored markets, providing live data for the dashboard and microstructure analysis.

Rate Limiter

A global rate limiter prevents API abuse with configurable per-endpoint limits and automatic backoff on 429 responses.

Хранилище и БД

All data is persisted in a SQLite database with WAL (Write-Ahead Logging) mode for concurrent reads.

Tables

TablePurpose
marketsDiscovered market metadata (question, type, volume, liquidity)
forecastsAll forecast results (probabilities, confidence, evidence quality)
tradesExecuted and simulated trade records
positionsOpen positions with entry price and current value
closed_positionsRealized P&L with close reason (TP hit, SL hit, resolved, time exit)
performance_logPer-trade performance data for analytics
calibration_historyForecast vs. outcome pairs for calibration learning
model_forecast_logPer-model forecasts for adaptive weighting
audit_logAdmin actions and configuration changes
whale_scansWallet scanner results and conviction signals
tracked_walletsWhale tracker wallet metadata and scores
wallet_signalsPer-market conviction signals from whale wallets
wallet_deltasPosition change events (entries, exits, size changes)
decision_logDecision intelligence audit trail with integrity hashes
walletsStrategy wallet definitions (name, address, balance, P&L)
strategiesNamed trading strategies with risk parameters
strategy_walletsMany-to-many strategy↔wallet bindings with allocation %
wallet_tradesTrade records linked to specific strategy wallets
wallet_equity_snapshotsPoint-in-time equity snapshots for performance tracking

Migrations

Schema is managed through numbered migrations (currently 10). Migrations run automatically on startup, ensuring the database schema stays in sync with the code. Each migration is idempotent and includes proper error handling.

Backup

Database backups can be triggered from the Admin Panel. Backups are stored as timestamped copies in the data/ directory.

Наблюдаемость

Structured Logging (structlog)

All logs use JSON-structured format via structlog. Sensitive data (API keys, private keys) is automatically redacted by a custom log processor. Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.

In-Process Metrics

The metrics module tracks counters, gauges, and histograms in-memory:

  • orders.simulated, orders.submitted, orders.filled
  • forecasts.total, forecasts.trade, forecasts.no_trade
  • risk.violations, risk.kills
  • api.calls, api.errors, api.latency_ms

Cost Tracking

LLM and search API costs are tracked per-provider with running totals visible in the Admin Panel. Includes token counts and estimated USD costs for OpenAI, Anthropic, Google, and search providers.

JSON Run Reports

Each engine cycle produces a JSON report saved to reports/ with full pipeline details.

Sentry Integration

Optional error tracking via Sentry SDK. Configure with SENTRY_DSN environment variable.

Алерты и уведомления

Multi-channel alerting for critical events:

ChannelConfig Keys
ConsoleAlways enabled
Telegramalerts.telegram_bot_token, alerts.telegram_chat_id
Discordalerts.discord_webhook_url
Slackalerts.slack_webhook_url
Emailalerts.email_smtp_host/port/user/password

Alert Triggers

  • Trade executions (paper and live)
  • Large P&L moves
  • Drawdown warnings and kill switch activations
  • Risk limit breaches
  • System errors
  • Daily summary (configurable hour, default 6pm)

Руководство по дашборду

The web dashboard provides a real-time view of all bot operations, accessible at http://localhost:2345.

Tabs Overview

TabContents
ОбзорPortfolio summary cards, equity curve, engine status, drawdown gauge, regime indicator
TradingOpen positions with live P&L, pipeline candidates, recent forecasts, enhanced trade history with TP/SL hit tracking, close reasons, duration, PnL%, and summary stats
AnalyticsPerformance metrics (Sharpe, Sortino, Calmar), accuracy charts, P&L by category, strategy leaderboard
Whale TrackerTracked wallets with tiering, conviction signals, whale activity feed, Smart Money Index, consensus analysis
Decision IntelFull decision audit trail — every stage (SCAN→RESEARCH→FORECAST→EDGE→RISK→SIZE→EXECUTE→MONITOR) with filtering, search, and integrity hashes
StrategiesMulti-wallet/strategy portfolio management — create wallets & strategies, bind them together, track allocation percentages and per-strategy performance
JournalVaR calculations, watchlist, trade journal entries, equity snapshots
Admin PanelEngine health, risk monitor, API keys, feature flags, config editor, audit trail, alerts, database stats, system info, danger zone actions
DocumentationThis page — complete bot reference with 28 sections

Authentication

Set DASHBOARD_API_KEY in your .env file. Access the dashboard with the API key as a header (X-API-Key) or query parameter (?api_key=...). If no key is set, the dashboard runs in open-access mode.

Auto-Refresh

Обновление каждые 15 сек — только для активной вкладки, чтобы минимизировать нагрузку на API.

Справочник конфигурации

All configuration is managed via config.yaml with environment variable overrides. The dashboard Admin Panel provides a visual config editor.

SectionKey SettingsDescription
scanningmin_volume_usd, min_liquidity_usd, max_spread, preferred_types, restricted_typesMarket discovery filters
researchmax_sources, search_provider, min_corroborating_sources, stale_days_penaltyEvidence gathering settings
forecastingllm_model, llm_temperature, min_evidence_quality, min_confidence_levelLLM forecasting parameters
ensemblemodels, aggregation, weights, min_models_required, timeout_per_model_secsMulti-model ensemble config
riskmax_stake_per_market, max_daily_loss, min_edge, kelly_fraction, bankroll, stop_loss_pctRisk management thresholds
drawdownmax_drawdown_pct, warning/critical thresholds, auto_kill_at_maxDrawdown heat system
portfoliomax_category_exposure_pct, max_single_event_exposure_pct, max_correlated_positionsPortfolio-level risk limits
timelinenear_resolution_hours, confidence_boost, exit_before_resolution_hoursResolution timing adjustments
microstructurewhale_size_threshold_usd, flow_imbalance_windows, depth_change_alert_pctMarket microstructure analysis
executiondry_run, slippage_tolerance, twap_enabled, iceberg_threshold, adaptive_pricingOrder execution settings
enginecycle_interval_secs, max_markets_per_cycle, paper_mode, auto_startTrading engine loop settings
alertstelegram/discord/slack/email credentials, alert triggers, daily_summary_hourNotification channels
wallet_scannerscan_interval, min_conviction_score, conviction_edge_boost/penaltyWhale tracking config
cachesearch_ttl_secs, orderbook_ttl_secs, max_cache_size_mbResponse caching
storagedb_type, sqlite_pathDatabase settings
observabilitylog_level, log_format, log_file, enable_metricsLogging and monitoring

CLI команды

The bot is controlled via the bot CLI (Click-based). Entry point: src.cli:cli.

CommandDescriptionKey Flags
bot scanDiscover active markets from Gamma API--limit N
bot research --market IDGather sources & extract evidence
bot forecast --market IDFull pipeline: research → forecast → risk → size
bot paper-tradeRun paper trading simulation--days N, --markets N
bot trade --liveLive trading (requires ENABLE_LIVE_TRADING)--live (required)
bot engine startStart the continuous trading engine
bot engine statusShow engine status summary
bot portfolioShow portfolio risk report
bot drawdownShow drawdown state
bot arbitrageScan for arbitrage opportunities--limit N
bot alertsShow recent alerts--limit N
bot dashboardLaunch web dashboard--host, --port, --debug

Quick Start

# Install
git clone <repo-url> polymarket-bot
cd polymarket-bot
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Configure
cp .env.example .env
# Edit .env with API keys: OPENAI_API_KEY, TAVILY_API_KEY, etc.

# Run
bot scan --limit 20                    # Discover markets
bot forecast --market <CONDITION_ID>   # Full forecast pipeline
bot dashboard                          # Launch web UI on :2345

Безопасность

This bot trades real money.

Always start with dry_run: true (default) and thoroughly test with paper-trade before enabling live trading.

Safety Mechanisms

  • Triple dry-run gate — Three independent flags must all allow live trading
  • Kill switch — Instant halt, accessible from CLI, config, and dashboard
  • Auto-kill on max drawdown — Prevents catastrophic losses
  • 15 independent risk checks — All must pass for any trade
  • Position limits — Per-trade, per-category, and portfolio-wide caps

Security Practices

  • API keys loaded from environment only, never committed to code
  • Private keys automatically redacted in structlog output
  • Dashboard auth via API key header or query parameter
  • Docker — Runs as non-root user in container
  • Audit trail — All admin actions and config changes logged to database

Развёртывание

Local Development

python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
bot dashboard

Docker

docker compose build
docker compose up -d          # Runs dashboard + engine
docker compose logs -f        # Follow logs

Environment Variables

VariableRequiredDescription
OPENAI_API_KEYYesGPT-4o forecasting
ANTHROPIC_API_KEYRecommendedClaude 3.5 Sonnet (ensemble)
GOOGLE_API_KEYRecommendedGemini 1.5 Pro (ensemble)
TAVILY_API_KEYYes*Web search provider (*or SERPAPI_KEY or BING_API_KEY)
POLYMARKET_API_KEYFor live tradingPolymarket CLOB API credentials
POLYMARKET_API_SECRETFor live tradingCLOB API secret
POLYMARKET_PASSPHRASEFor live tradingCLOB API passphrase
ENABLE_LIVE_TRADINGNoMust be "true" to allow live orders
DASHBOARD_API_KEYNoProtects dashboard access
SENTRY_DSNNoSentry error tracking

Testing

pytest                                   # Run all tests
pytest --cov=src --cov-report=term       # With coverage
pytest tests/test_policy.py -v           # Specific test file
mypy src/                                # Type checking
ruff check src/ tests/                   # Linting

Глоссарий

TermDefinition
EdgeThe difference between model probability and market-implied probability; the bot's informational advantage.
Implied ProbabilityThe probability implied by the current market price (best bid or mid-point).
Kelly CriterionA mathematical formula for optimal bet sizing that maximizes long-term bankroll growth.
Fractional KellyUsing a fraction (e.g., 25%) of full Kelly to reduce variance at the cost of slightly lower expected growth.
ПросадкаThe percentage decline from peak equity; measures how much has been lost from the highest point.
Уровень нагреваA 0-3 scale representing drawdown severity; higher levels reduce position sizes and may halt trading.
Brier ScoreA calibration metric: mean squared error between predicted probabilities and outcomes. Lower is better (0 = perfect).
Platt ScalingA calibration technique using logistic regression to adjust raw probabilities for better real-world accuracy.
CLOBCentral Limit Order Book; Polymarket's orderbook for matching trades.
Gamma APIPolymarket's public REST API for market metadata and discovery.
TWAPTime-Weighted Average Price; splits a large order into smaller slices executed over time.
Iceberg OrderAn order that hides its full size, showing only a fraction to the market at a time.
Аварийный стопAn emergency mechanism that immediately halts all trading activity.
Conviction ScoreA whale tracking metric measuring how strongly top traders agree on a market direction.
WALWrite-Ahead Logging; a SQLite journal mode that allows concurrent reads during writes.
Paper ModeSimulation mode where all trades are recorded but no real orders are placed.

Профиль кита

🎯 Разбивка по направлениям

🏷️ Распределение по категориям

🏔️ Топ рынков

РынокИсходНаправлениеКапиталУбеждённостьЦена
🤖

Я ваш Ментор стратегий. Я анализирую паттерны торговли этого кита и предоставляю actionable инсайты.

Попробуйте спросить:

Детали рынка

🐋 Сигналы китов

ИсходКитыКапиталУбеждённостьНаправлениеЦена

📡 Последняя активность

📡 Детали активности