Content
# Tool List
**Bollinger Grid with auto-entries, ATR-adaptive SL/TP, trailing, DCA, self-learning and post-trade cluster analysis. MCP server for AI-agents. Telegram/ntfy alerts.**
[](./CHANGELOG.md) [](https://python.org) [](./LICENSE) [](./test_smoke.py) [](./AGENTS.md)
---
## Module Architecture (v7.3)
```
┌─────────────────── MAIN LOOP (async, 30s) ───────────────────┐
│ main_async.py — main cycle (asyncio) │
│ │
│ Each cycle: │
| • state_db.py — SQLite SSOT (WAL, 11 tables) |
│ • auto_sl.py — ATR-adaptive SL v2 (±k×ATR, 2% floor)│
│ • trailing_sl.py — trailing SL (LONG + SHORT) │
│ • auto_tp.py — ATR-based TP (1.0×/2.0×/3.0× ATR) │
│ • time_exit.py — Time exit (6ч/48ч) │
│ • risk management — Circuit breaker, BlackSwan 3-tier │
│ │
│ Every 10 cycles (HEAVY, ~5 min): │
│ • auto_entry.py — auto-LONG (MTF+OB+Volume+Judge) │
│ • auto_short.py — auto-SHORT + Dry Spell Throttle │
│ • pump_detect.py — pump detection (24ч/нед) │
│ • correlation.py — correlation matrix │
│ • dca.py — DCA purchases │
│ │
│ Daily (2880 cycles): │
│ • post_trade.py — cluster analysis (WR<40% → block) │
│ • journal/self_learn.py — self-learning + canary v3 │
│ │
│ Import history (each cycle): │
│ • Bybit closed-pnl → trades.jsonl │
│ • → post_trade_features.jsonl (since 30.06) │
│ │
└───────────────────────────────────────────────────────────────┘
│
▼ RPC (port 8766) + WS push (port 8768)
• rpc.py — JSON-RPC, /metrics Prometheus
• push_notifier.py — ntfy + Telegram alerts
```
### Full List of Engine Files
| File | Purpose |
|------|-----------|
| `state_db.py` | SQLite (WAL, 8 tables) — trade_history, cooldowns, alert_dedup |
| `main.py` | Main cycle, RPC server, module orchestration |
| `api.py` | Bybit REST API: positions, orders, SL/TP, BB-data |
| `config.py` | Config: 8 strategies, risk management, tiers |
| `position_sizing.py` | Dynamic sizing (% deposit × score × multiplier) |
| `auto_short.py` | Auto-SHORT: Tier A/B (regular) + JUNK C/D (pump-shorts without SL) |
| `auto_entry.py` | Auto-LONG: BB < threshold, score ≥ min |
| `auto_tp.py` | Auto-TP: 20% on Middle BB + 80% on Upper BB (LONG + SHORT) |
| `auto_sl.py` | Auto-SL: check and fix stop-losses (LONG + SHORT, tier-based) |
| `trailing_sl.py` | Trailing SL: LONG (BB>75%) + SHORT (BB<25%), PnL>15% |
| **`junk_trail.py`** | Trailing TP for JUNK shorts: fix 70% at +15%, 85% at +30% |
| `pump_detect.py` | Pump detection: 24ч ≥80%, weekly ≥230% |
| `dca.py` | DCA purchases LONG at −5/−10/−15% from entry |
| `correlation.py` | Correlation matrix: block if >80% correlation |
| `health.py` | Monitoring: liquidations, BB-squeezes, funding, daily drawdown |
| `overbought.py` | Rotation of overbought coins watchlist |
| `rsi.py` | RSI divergences |
| `squeeze.py` | BB-squeeze detector |
| `reporting.py` | Summaries, compliance audit (LONG + SHORT), coverage summary |
| `cleanup.py` | Cleanup of expired/old orders |
| `cost_tracker.py` | Trading commission tracking |
| `recycle.py` | Recycling TP → re-entry |
| `metrics.py` | Metrics logging (alerts, auto-entries) |
| `alerts.py` | Telegram alerts, deduplication |
| `snapshot.py` | Position/order snapshots, change detection |
| `rpc.py` | HTTP-RPC server (:8766) — direct api.bybit() calls |
---
## Operation Modes
### LONG (BB Grid)
- **Trigger**: BB Daily < threshold (Tier A: <15%, B: <25%, C: <40%, D: <65%)
- **Leverage**: 3x
- **Margin**: dynamic (deposit × 20% / max_positions × score_multiplier)
- **SL**: −7% from Lower BB (trading-stop)
- **TP**: 20% on Middle BB + 80% on Upper BB (limit reduceOnly)
- **Trailing SL**: trailing at BB Weekly >75% and profit >15%
- **DCA**: purchases at −5/−10/−15% from entry, max 2 additions
- **Max positions**: 12
### SHORT (hedge)
- **Trigger**: BB Daily > 85%, Tier A/B/C/D coins
- **Leverage**: 3x
- **SL**: +5% (Tier A/B), +7% (Tier C/D)
- **Trailing SL**: BB Weekly < 25% + PnL > 15% → SL trails down
- **TP**: Middle BB
- **Max positions**: 3 (shared limit with JUNK)
### SHORT JUNK Tier C/D (pump-shorts) 🆕
- **Trigger**: 24ч growth ≥ 80% + BB Daily > 70%
- **Leverage**: 3x
- **SL**: **NONE** (JUNK too volatile — SL only eats margin)
- **Protection**: max_loss −15% margin (hard market-close), max_hold 48ч (auto-close)
- **Entry**: limit Sell at +2% above market (waiting for bounce)
- **TP #1**: Middle BB (limit reduceOnly Buy, set at entry)
- **TP #2 (trailing)**: at profit >15% → trailing TP, fixing 70% profit
- **TP #3 (trailing)**: at profit >30% → trailing to 85% profit
- **DCA ladder**: limit Sells at +100% and +120% from entry
- **Max positions**: 3 (shared limit with Tier A/B)
### JUNK short: full lifecycle
```
1. pump_detect.py → pump +80% in 24ч
2. auto_short.py → limit Sell +2%, TP Middle BB, DCA +100%/+120%
3. check_junk_dca() → check max_loss/max_hold/DCA levels
4. junk_trail.py → profit >15%: TP trailed (fixing 70%)
5. junk_trail.py → profit >30%: TP trailed (fixing 85%)
6. TP triggers → position closed with profit
```
### SL Re-entry
- After SL trigger — re-entry ladder (price / 1.05, price / 1.10, price / 1.15)
- Up to 3 attempts per coin
### x10 Strategies (high risk)
| Strategy | TF | Trigger | SL | TP | Max pos |
|-----------|-----|---------|-----|-----|---------|
| Scalp M5 | M5 | BB touch + RSI | −3% | Middle | 3 |
| Mean Revert | D | BB <5% or >95% | −5% | Middle | 5 |
| Funding Momentum | D | Funding ±0.1% + BB + trend | −4% | Middle | 3 |
⚠️ **x10 leverage — liquidation at ~10% move against position.**
---
## Notification Format
```
🔴 SHORT JUNK HMSTR: entry $0.000373 limit $0.000380 ×664190 (3x) | pump +120% | TP $0.000112 | DCA: +100% @ $0.000746, +120% @ $0.000821
🔴 SHORT MOVE: entry $0.0143 limit $0.0146 ×700 (3x) | BB=92% | SL $0.0150 (+5%) | TP $0.0120
🔴 DCA JUNK HMSTR: +100% @ $0.000746 ×664190 | entry $0.000373 → now $0.000750
🔒 JUNK Trail TP HMSTR: fix 70% at +22.5% | entry $0.000373 → TP $0.000210 (was $0.000112)
🛑 STOP JUNK HMSTR: loss -16.2% > limit 15% | entry $0.000373 → exit $0.000433 | PnL $-12.40
⏰ TIMEOUT JUNK HMSTR: 49ч > 48ч limit | exit $0.000380 | PnL $-1.20
```
---
## Risk Management
| Mechanism | Details |
|----------|--------|
| Dynamic sizing | deposit × risk% / max_positions × score_multiplier |
| Drawdown alert | Alert + optional emergency close at −3% daily / −15% overall (configurable) |
| Daily loss limit | Trading halt at −$50/day |
| Correlation block | No entry if ≥2 positions with correlation >0.8 |
| x10 protection | Max 3 losing x10 trades → cooldown 24ч |
| Cascade protection | Market-close if price is 2× closer to liquidation than SL |
| Ban list | config-driven, permanent |
| JUNK protection | max_loss −15% margin, max_hold 48ч, no SL |
| **BlackSwan multi-tier** 🆕 | Tier 1: BTC -3%/15min → 50% | Tier 2: BTC -5%/30min → 80% | Tier 3: BTC -8%/1h → 100% |
| **Canary mode** 🆕 | 10% entries with new self-learned parameters, auto-rollback on WR drop |
---
## Interfaces
### REST API (port 8766)
```bash
curl http://localhost:8766/health # status
curl http://localhost:8766/positions # positions (read)
curl http://localhost:8766/scan?mode=short # market scan
curl -H "Authorization: Bearer $TOKEN" \
-X POST http://localhost:8766/enter # entry (write, requires auth)
```
### MCP Server
```python
# AI-agents (Claude Code, Codex, Cursor, Hermes) connect directly
mcp_bybit_ws_get_positions() # positions + PnL + SL
mcp_bybit_ws_scan_market() # BB signals LONG/SHORT
mcp_bybit_ws_get_metrics() # daily statistics
mcp_bybit_ws_vpn_status() # VPN + traffic
```
### Python SDK
```python
from bybit_ws_sdk import Monitor
m = Monitor("http://localhost:8766", token="your-token")
```
# Market Scanning
signals = m.scan(mode="short", limit=5)
for s in signals["signals"]:
preview = m.enter(s["symbol"], "Sell", s["qty"], confirm=False)
print(f"Preview {s['symbol']}: sell {preview['qty']} @ market")
m.enter(s["symbol"], "Sell", s["qty"], confirm=True)
# Positions and Metrics
positions = m.positions() # all positions + PnL + SL
metrics = m.metrics() # daily statistics (SL/TP/entries)
pnl = sum(p["upnl"] for p in positions["positions"]) # total PnL
# Management
m.set_sl("DOGEUSDT", 0.075) # set stop-loss
m.close("APTUSDT") # close position at market
m.cancel_all() # cancel all orders
## Quick Start
### Installation
```bash
git clone https://github.com/poliakarmai/bybit-ws.git
cd bybit-ws
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cp config.example.yaml ~/.config/bybit-ws/config.yaml
cp .env.example ~/.config/bybit-ws/.env
nano ~/.config/bybit-ws/.env # BYBIT_API_KEY, BYBIT_API_SECRET
python3 -m bybit_ws # launch
```
### systemd (recommended)
```bash
mkdir -p ~/.config/systemd/user
cp bybit-ws.service ~/.config/systemd/user/
# Ensure the path in ExecStart leads to bybit-ws:
which bybit-ws # should be ~/.local/bin/bybit-ws
systemctl --user daemon-reload
systemctl --user enable --now bybit-ws
systemctl --user status bybit-ws # check
journalctl --user -u bybit-ws -f # logs
```
### Docker
```bash
docker compose up -d
```
## Troubleshooting
| Symptom | Cause | Solution |
|---------|--------|----------|
| `ModuleNotFoundError: bybit_ws` | Package not installed | `pip install -e .` from project root |
| `bybit-ws: command not found` | No entry point | `pip install -e .` or `python3 -m bybit_ws` |
| RPC returns 401 | Invalid token | Check `RPC_TOKEN` in `.env` |
| Server does not start | Empty RPC_TOKEN + bind not localhost | Set `RPC_TOKEN` in `.env` |
| Bybit: «invalid API key» | Incorrect keys or testnet/mainnet | Check `api.base_url` and keys |
| Positions not opening | Deposit < $30 or banned | Check `get_deposit()` logs |
| Telegram alerts not coming | Bot or chat not set | Check `TG_BOT_TOKEN`, `TG_CHAT_ID` |
| `Connection refused` to RPC | Server not running or port occupied | `systemctl --user status bybit-ws`, `ss -tlnp :8766` |
| High PnL minus at launch | No stop-losses | Wait for first cycle (30s), auto_sl sets SL |
## Configuration
Key parameters `~/.config/bybit-ws/config.yaml`:
```yaml
api:
key: "${BYBIT_API_KEY}"
secret: "${BYBIT_API_SECRET}"
base_url: "https://api-testnet.bybit.com"
strategy:
long:
leverage: 3
max_positions: 12 # max simultaneous LONG positions (hard limit)
sl_offset: 0.07
short:
leverage: 3
max_positions: 3 # max simultaneous SHORT (including JUNK)
bb_threshold: 85
junk: # JUNK shorts
daily_pump_threshold: 0.80 # 80% growth in 24h
weekly_pump_threshold: 2.30 # 230% in a week
dca_levels: [1.0, 1.2] # DCA at +100% and +120%
max_loss_pct: 15 # hard stop at −15% margin
max_hold_hours: 48 # auto-close after 48h
risk:
max_drawdown_pct: 15
max_daily_loss: 50
emergency_close_all: true
position_sizing:
long_risk_pct: 0.20 # 20% deposit at risk
max_positions: 5 # base for margin calculation: deposit × risk% / N positions
max_position_share: 0.40 # no more than 40% budget per position
rpc:
port: 8766
auth_token: "${RPC_TOKEN}"
```
## Requirements
- Python 3.11+
- `requests`, `pyyaml`, `websocket-client`, `numpy`
- Bybit Unified Trading Account + API keys (read/write + trading)
- Linux (VPS $5/month) or Docker
## Security
**API Keys:**
- Keys via `~/.config/bybit-ws/.env` → read as `${BYBIT_API_KEY}`
- Never commit `.env` (added to `.gitignore`)
- `chmod 600 ~/.config/bybit-ws/.env ~/.config/bybit-ws/config.yaml`
**RPC Server:**
- Write endpoints (`/enter`, `/close`, `/set-sl`) require `Authorization: Bearer <token>`
- ⚠️ If `RPC_TOKEN` is not set and `bind ≠ 127.0.0.1` — server refuses to start
- Bind: `127.0.0.1` by default. For external access — `0.0.0.0`
**Bybit:**
- IP-whitelist for API keys (Bybit → Account → API Management)
- Regular key rotation (every 90 days)
- Separate keys for reading and trading (principle of least privilege)
## Statistics
Actual numbers depend on market conditions. Past results do not guarantee future.
## 🤖 GridSignal Bot (@Gridbolbot)
Telegram bot for Bollinger Grid signals.
```
Commands:
/scan Top 5 LONG signals
/scan short Top 5 SHORT
/scan scalp BB Scalping x10
/scan mean Mean Reversion x10
/pro GridSignal Pro (unlimited)
```
**Subscription:**
| Tariff | Scans | Price |
|-------|-------|------|
| 🆓 Free | 3 /scan per day | 0₽ |
| ⭐ Pro | Unlimited + alerts | 300 Stars (~400₽) or ~2 TON |
**Payment:** Telegram Stars + TON (CryptoBot).
Bot: [@Gridbolbot](https://t.me/Gridbolbot)
Code: `~/.local/bin/gridsignal-bot.py`
## Documentation Files
| File | Content |
|------|---------|
| [`docs/README.md`](docs/README.md) | **Full documentation:** installation, operation, capabilities, errors, logging, checks |
| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Architecture: components, data streams, data model, Mermaid diagrams |
| [`docs/API.md`](docs/API.md) | API Reference: 20 RPC endpoints, 6 MCP tools, curl examples |
| [`docs/SECURITY.md`](docs/SECURITY.md) | Security: secrets, threat model, incidents, audit |
| [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) | Troubleshooting: 13 categories, 60+ causes |
| [`DESIGN-STRATEGIES.md`](DESIGN-STRATEGIES.md) | Strategy design: Bollinger Grid, scoring, risk management |
| [`AGENTS.md`](AGENTS.md) | Navigation for AI agents, auto-discovery of paths |
| [`CHANGELOG.md`](CHANGELOG.md) | Changelog (Keep a Changelog) |
| [`config.example.yaml`](config.example.yaml) | Full config with comments |
## Disclaimer
**This software trades real money on futures with up to 10x leverage. You can lose your entire deposit.** Authors are not responsible for financial losses. Start with testnet.
## License
MIT
*Built for AI agents. Ready for yours. Questions? Write to [@Poliakarm](https://t.me/Poliakarm).*
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available