bybit-ws
Allows Hermes AI agents to scan Bybit markets, receive trading signals, and execute trades via the MCP protocol.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@bybit-ws scan the market for long signals"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
bybit-ws — AI-Native Trading Engine
Русский · English
24/7 автотрейдинг на фьючерсах Bybit. Bollinger Grid + AI-фильтры. Подключил — зарабатывает.
English readers — start here. The design is written up in English: bybit-ws: a trading tool, an analyst, and an assistant. Code comments and the rest of the docs are in Russian; the file-by-file map is in AGENTS.md. If you think a part of this design is wrong, say so in issues — the pinned issue lists five things I'm not sure about, and a one-line "you'll regret this, because X" is more useful than a star.
Что это
Автономный трейдинг-движок, который:
Находит точки входа по Bollinger Bands + 9-метричному AI-скорингу
Входит LONG/SHORT автоматически
Управляет рисками: стоп-лоссы, тейк-профиты, трейлинг, DCA
Защищает депозит: Circuit Breaker, BlackSwan, Anti-ludomania, корреляционный блок
Самообучается: LSTM-классификатор рынка, Thompson Sampling, Dynamic Bandit, Drift Detector, Ensemble (20+ механик)
Работает 24/7 на VPS за $5/мес. pytest-набор + 52 smoke-проверки, атомарный деплой.
Related MCP server: bybit-mcp
Результаты
Статистику здесь не держим: она меняется несколько раз в день, а статичный снимок в README через сутки врёт. Живые числа — из самого бота:
curl -s localhost:8766/metrics # сделки, входы, SL/TP за день
curl -s localhost:8766/positions # открытые позиции + PnL (Bearer)
python3 -m bybit_ws.reconcile --days 30 # сходимость state.db с биржей
python3 -m bybit_ws.paper_trade SOLUSDT --days 90 # бэктест на своих параметрахНе гарантия доходности. Цифры конкретной инсталляции (
strategy='auto',manual=0) — не обещание.trade_history.side— сторона закрытия (Buy=закрыл SHORT), в/positionsнаоборот: сырой Bybit.
Быстрый старт (3 шага)
1. Клонируй и настрой
git clone https://github.com/poliakarmai/bybit-ws.git
cd bybit-ws
pip install -r requirements.txt2. Добавь ключи Bybit
mkdir -p ~/.config/bybit-ws
cp config.example.yaml ~/.config/bybit-ws/config.yaml
# Создай env с API-ключами (chmod 600!)
cat > ~/.config/bybit-ws/env << 'EOF'
BYBIT_API_KEY=your_key
BYBIT_API_SECRET=your_secret
RPC_TOKEN=your_random_token_32_chars
TG_BOT_TOKEN=optional_telegram_bot_token
TG_CHAT_ID=optional_chat_id
EOF
chmod 600 ~/.config/bybit-ws/env3. Запусти
# Тестовый прогон (без реальных сделок — убедись что всё ок)
python3 -m bybit_ws.paper_trade SOLUSDT --days 30
# Боевой запуск
python3 test_smoke.py # 52 проверки → PASS
python3 -m pytest -q # весь набор (должно быть зелёным)
python3 -m pytest tests/ -q # только tests/
bash deploy.sh # атомарный деплой с canary-проверкойГотово. Движок работает. Позиции открываются автоматически при сигналах.
Установка для AI-агентов (MCP)
bybit-ws — не библиотека, а движок; MCP-сервер — тонкая обёртка над его RPC.
Ставится на машину, где работает движок (или на машину, которой доступен его RPC).
⚠️ Имя
bybit-wsв PyPI занято официальным WS-клиентом Bybit —pip install bybit-wsпоставит чужой пакет. Ставить из git:
pip install "git+https://github.com/poliakarmai/bybit-ws.git"Подключение (Claude Desktop / Cursor / Codex / Hermes) — запись в mcpServers:
{
"mcpServers": {
"bybit-ws": {
"command": "bybit-ws-mcp",
"env": {
"BYBIT_RPC_URL": "http://127.0.0.1:8766",
"RPC_TOKEN": "<токен из ~/.config/bybit-ws/env>"
}
}
}
}Инструменты: get_positions, get_risk_status, scan_market, place_entry, get_metrics,
get_journal, backtest_run, validation_report, experiment_list, vpn_status.
place_entry — реальный ордер. Держи RPC_TOKEN в env, не в конфиге MCP-клиента в открытом виде.
Проверка: агент вызывает get_positions → позиции с uPnL. Пусто/ошибка подключения —
сначала подними движок: systemctl --user start bybit-ws-async, затем curl -s 127.0.0.1:8766/health.
Возможности
🤖 Авто-трейдинг
Bollinger Grid LONG/SHORT на дневном таймфрейме
9-метричный скоринг: BB%, объём, падающие дни, фондинг, волатильность, качество + ML Gate
LSTM-классификатор рынка (5 классов) — не в строю:
val_accuracy 0.653, режим залипает (два значения за 22 дня), требует переобученияАвто-входы с MTF-подтверждением, orderbook-анализом и Entry Judge (DeepSeek, fail-closed, fail-open только при длительном отказе LLM)
Auto-TP: ATR-adaptive, 3 ноги
[0.40, 0.35, 0.25](% размера), множители ATR по режиму. BB 20% Middle / 80% Upper — fallback, когда ATR недоступенUnified SL: 5 механизмов → один приоритетный (tight > simple > hard > BE > default)
🛡️ Защита депозита
Circuit Breaker при 80% дневного лимита
BlackSwan v2: 5+ красных позиций + uPnL < -$150 → алерт (без авто-закрытия)
Anti-ludomania: 3 убытка за час → блок авто-входов на 30 минут
Корреляционный блок: запрет входа при >80% корреляции с открытой позицией
Pump Detection: детект пампов +24ч/+230% нед → блок входа
Kill Switch: мгновенное закрытие всех позиций через RPC
📊 Бэктестинг
Paper Trading на исторических данных (
paper_trade.py)6-метричный скоринг, LONG/SHORT, SL/TP с RR
Метрики: Sharpe, макс. просадка, profit factor, винрейт
🔌 Интерфейсы
RPC API (порт 8766):
/health,/scan,/enter,/close,/positions,/metrics,/risk,/balance— полный список путей вdo_GET/do_POST(rpc.py)HTTP RPC для ботов и интеграций (
http.server, не JSON-RPC)MCP Server для AI-агентов (Claude Code, Hermes, Codex)
Telegram-алерты: входы, SL, TP, DCA, пампы, ошибки
One-click trading через Hermes-чат: «просканируй SOL» → «бери 5%»
🧠 AI & Self-Learning (v10 — 20+ механик)
Thompson Sampling: Dynamic Bandit — авто-прунинг + генерация рук, Uncertainty-aware selection
Ensemble Learning: отдельный bandit на режим — 6 (5 классов LSTM +
CHOPPY)Drift Detector: per-regime окна с EMA baseline, Causal inference (market vs parameters)
Stress Testing: 4 исторических backtest-сценария + 1000 Pareto Monte Carlo симуляций
Composite Score: WR+PF+Sharpe+MaxDD+AvgHold с adaptive per-regime весами и exponential decay
Micro-updates: обучение после каждой сделки с outlier-защитой (>3σ)
Canary mode: Bayesian A/B тест, адаптивный 5-20%, авто-rollback. ⚠️ В проде выключен (
CANARY_ENABLED=False) — код жив, но к live-входам не применяется.Entry Judge: одна модель (DeepSeek, fail-closed); Qwen убран 17.10, Nemotron в коде вызова нет
LSTM Market Regime: 5 классов, авто-адаптация LONG/SHORT (82.3% — заявлено, не перезамерялось)
LSTM World Model: multi-task OHLCV prediction для скоринга входов
Для кого
Ты | Как использовать |
🧑💻 Трейдер | Поставил на VPS, подключил алерты в Telegram — двигатель крутит 24/7 |
🤖 Квант/разработчик | Форкни, подключи свою модель, используй RPC API |
💼 Провайдер сигналов | Подключи @Gridbolbot к RPC — клиенты получают сигналы |
🏢 Фонд/команда | Multi-instance, общий RPC, shared мониторинг |
Архитектура
┌───────────── MAIN LOOP (async, 30s) ─────────────┐
│ Каждый цикл: │
│ • unified_sl.py — Unified SL (5 механизмов) │
│ • time_exit.py — Time exit (каждый цикл, макс 24ч)│
│ • auto_tp.py — ATR-based TP │
│ • risk_manager.py — Circuit Breaker + BlackSwan │
│ │
│ Каждые 10 циклов (HEAVY, ~5 мин): │
│ • auto_entry.py — LONG с AI-скорингом │
│ • auto_short.py — SHORT + JUNK tier │
│ • pump_detect.py — детект пампов │
│ • correlation.py — корреляционная матрица │
│ • dca.py — DCA-докупки │
│ │
│ Self-learn (event-driven: ≥10 сделок И ≥6ч, иначе 24ч):│
│ • self_learn.py — Dynamic Bandit, Drift, Ensemble│
│ • canary mode — Bayesian A/B (выключен в проде)│
└─────────────────────────────────────────────────────┘Проекты экосистемы
Проект | Назначение |
bybit-ws | Трейдинг-движок (этот репо) |
Telegram-бот сигналов (Pro-подписка: безлимит + алерты) | |
Встроенный трейдинг в Hermes Agent | |
Бэктестинг на истории | |
Карта документации: что актуально, что архив |
Документация
Файл | Содержание |
Пошаговая инструкция: от нуля до первой сделки | |
Архитектура, потоки данных, Mermaid-диаграммы | |
RPC API: реальный список эндпоинтов из | |
Карта документации + статус каждого файла | |
Безопасность: секреты, модель угроз, аудит | |
Решение проблем: 60+ причин | |
One-click trading через чат | |
Навигация для AI-агентов | |
История версий |
Требования
Python 3.11+
Bybit Unified Trading Account + API ключи (read/write + trading)
Linux-сервер (VPS $5/мес) или Docker
Минимальный депозит: $50 на testnet, $200 на mainnet
Безопасность
API-ключи через
env(chmod 600) — никогда в кодеRPC write-эндпоинты требуют Bearer-токен
IP-whitelist на уровне Bybit
Атомарный деплой: 3 pre-deploy шага (чистота репо → logic → smoke) + 8 canary-проверок
Kill Switch: мгновенное закрытие всех позиций
Дисклеймер
Этот софт торгует реальными деньгами на фьючерсах с плечом до 10x. Можно потерять весь депозит. Авторы не несут ответственности за финансовые потери. Начинайте с testnet. Бэктестите через paper_trade.py. Прошлые результаты не гарантируют будущих.
Лицензия
AGPL-3.0
Built for traders. Hardened by AI. Вопросы: @Poliakarm.
Available Tools
10 toolsbacktest_runA
Run reproducible backtest via bybit_ws.experiments.backtest_runner. Пишет только в experiments.db (боевой state.db не трогает), 180s timeout, single-flight. Returns metrics: trades, win_rate, pnl, total_fees, equity_hash, git_commit
Inputs: symbol (required), days, params, interval.
experiment_listA
List recent experiments from experiments.db (read-only). Returns experiment id, name, last run metrics
Inputs: limit.
get_journalB
Get trading journal analysis: FIFO-matched roundtrips, win rate, profit/loss ratio, disposition effect, overtrading, chasing, anchoring biases, and alerts
Inputs: no named parameters.
get_metricsA
Get daily trading metrics: SL/TP counts, entries, auto-entry stats
Inputs: no named parameters.
get_positionsA
Get current trading positions with unrealized PnL, stop-losses, and leverage
Inputs: no named parameters.
get_risk_statusA
Get risk limits and current usage: daily PnL vs max_daily_loss, margin vs max_total_margin, entry blocked status
Inputs: no named parameters.
place_entryB
Place a market or limit order to enter a LONG or SHORT position with SL/TP
Inputs: qty (required), side (required), symbol (required), sl, +4 more.
scan_marketB
Scan market for Bollinger Grid signals (LONG/SHORT candidates with scores)
Inputs: mode, limit, interval.
validation_reportB
Get DSR/PBO/permutation validation from a saved run artifact or DB. Returns honest 'no data' if missing
Inputs: run_id (required).
vpn_statusA
Get VPN health: service status, traffic rates, connected clients
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 10 tools
Most tools target clearly distinct objects: orders (place_entry), positions (get_positions), risk limits (get_risk_status), market signals (scan_market), VPN (vpn_status), and backtests (backtest_run, experiment_list). The only real overlap is among the analytics reads — get_metrics (SL/TP counts, entries), get_journal (roundtrips, win rate, biases), and validation_report (DSR/PBO) all report performance numbers, though the descriptions differentiate their sources well enough.
Several conventions coexist: verb_noun for actions (place_entry, scan_market), get_* for reads (get_positions, get_metrics, get_journal), noun_noun for status reads (vpn_status, validation_report), and reversed noun_verb for research tools (backtest_run, experiment_list). Every name is readable and the pattern roughly correlates with tool family, but there is no single predictable convention.
Ten tools is a well-scoped set for a trading server covering signal scanning, execution, monitoring, risk, performance analytics, and research. Nothing is obviously redundant, though vpn_status sits a bit outside the core trading surface.
The live-trading lifecycle is only half covered: you can place_entry and inspect positions/risk, but there is no close_position, cancel_order, or modify_sl_tp tool, forcing agents to dead-end on position management. The research side (backtest_run, experiment_list, validation_report) is more complete, and read coverage for metrics/journal is solid.
Maintenance
Related MCP Connectors
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
MCP server for Gainium — manage trading bots, deals, and balances via AI assistants
MCP server for OpenMM — exposes market data, account, trading, and strategy tools to AI agents
MCP server exposing the Backtest360 engine API as tools for AI agents.
Related MCP Servers
- FlicenseBqualityDmaintenanceA comprehensive MCP server providing full access to Bybit's v5 API for real-time market data, trading operations, and account management. It enables AI assistants to execute trades, manage positions, and monitor wallet balances with built-in safety controls for both testnet and production environments.226-
- AlicenseCqualityDmaintenanceMCP server for Bybit exchange enabling 246 tools for trading, market data, account management, and more via natural language.1002MIT
- AlicenseNot gradedqualityDmaintenanceMCP server that provides AI agents with financial tools including real-time quotes, backtesting, technical analysis, and multi-exchange data via a simple CLI interface.2MIT

Bybit MCP Serverofficial
AlicenseCqualityBmaintenanceA production-ready MCP server for Bybit — 206 tools covering market data, trading, positions, account management, assets, and real-time WebSocket streams. Enables AI assistants to interact directly with the Bybit cryptocurrency exchange through natural language.4031,095 npm45MIT