Skip to content

Repository files navigation

DepthWatch

Python React SQLite License

A self-hosted Binance order book monitor that detects directed density repositioning — large order walls that appear, move, and pull near the price to manipulate market direction — and emits scored signals to a database and Telegram.


Features

  • Real-time order book monitoring via Binance WebSocket depth streams
  • Pattern detection: wall detection, laddering, and pull-before-touch scoring
  • 0–100 signal scoring with configurable thresholds per symbol
  • Database + Telegram alerts — pluggable messaging provider architecture
  • Per-symbol configuration — independent detector parameters per trading pair
  • Web dashboard — full React UI for bot control, config, secrets, and live events
  • REST API — complete programmatic control (bot lifecycle, config, symbols, secrets, SSE stream)
  • Accuracy monitoring — built-in session runner with market-validated reports
  • i18n — English and Russian interface

Prerequisites

Requirement Version Notes
Python 3.11+ Managed via uv
uv latest Python package manager
Node.js 18+ For the React dashboard
npm 9+ Bundled with Node.js

Windows prerequisites

The Makefile commands require a Unix shell. On Windows, use one of:

  • MSYS2 / Git Bash — provides make, bash, and Unix utilities; Makefiles work unchanged.
  • WSL 2 — full Linux environment; recommended for production-like setups.
  • PowerShell scripts (no extra tools needed) — see scripts/windows/ for setup.ps1, start-api.ps1, start-ui.ps1, and more.

The Python source code is fully cross-platform and runs natively on Windows.


Project Structure

depthwatch/
├── packages/
│   ├── common/          # Shared DB layer: models, stores, Alembic migrations
│   ├── bot/             # Detection bot (WebSocket, detectors, sinks)
│   ├── api/             # Flask REST API + SSE stream
│   └── ui/              # React 19 dashboard (Vite + Tailwind)
├── .env.example         # Environment variable template
└── Makefile             # Top-level orchestration commands

Quick Start

macOS / Linux

git clone https://github.com/your-org/depthwatch.git
cd depthwatch
make setup

make setup automatically:

  1. Creates .env with a generated encryption key
  2. Installs all Python and Node.js dependencies
  3. Applies all database migrations
# Recommended: two separate terminals
make api-start          # Terminal 1 — API at http://localhost:5000
make ui-dev             # Terminal 2 — Dashboard at http://localhost:3010

Windows (PowerShell)

git clone https://github.com/your-org/depthwatch.git
cd depthwatch
.\scripts\windows\setup.ps1

Then in two terminals:

# Terminal 1
.\scripts\windows\start-api.ps1

# Terminal 2
.\scripts\windows\start-ui.ps1

All scripts\windows\ scripts must be run from the workspace root (depthwatch\).

If PowerShell blocks unsigned scripts, run: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

(Optional) Add credentials

Telegram alerts and Binance authentication are optional — the bot streams public market data without any credentials. To enable them, use the Secrets page in the dashboard after starting the services.

Open the dashboard

Navigate to http://localhost:3010, click Start to launch the bot, and watch live detections appear on the Events page.


Common Commands

macOS / Linux (make)

make help           # Show all available commands
make setup          # One-time setup (env + deps + migrations)
make api-start      # Start API server (http://localhost:5000)
make ui-dev         # Start UI in dev mode (http://localhost:3010)
make bot-start      # Start bot directly
make start-all      # API (background) + UI (foreground)
make stop-all       # Stop all services
make test           # Run all Python tests
make lint           # Lint Python + TypeScript
make format         # Format Python code (black)

Windows (PowerShell — from workspace root)

.\scripts\windows\setup.ps1      # One-time setup
.\scripts\windows\start-api.ps1  # Start API server
.\scripts\windows\start-ui.ps1   # Start UI dev server
.\scripts\windows\stop-all.ps1   # Stop all services
.\scripts\windows\migrate.ps1    # Apply database migrations
.\scripts\windows\test.ps1       # Run all Python tests

Dashboard

Access http://localhost:3010 after starting the services.

Page Description
Bot Start / stop / restart — live PID, uptime, CPU, memory
Configuration Manage global settings (detector params, thresholds)
Symbols Add / enable trading pairs with per-symbol JSON overrides
Secrets Securely store API keys (Fernet-encrypted at rest)
Events Query historical detections with symbol/type/score filters
Live Stream Real-time SSE event feed

Language selector (EN / RU) is in the top-right corner.


Configuration

All runtime configuration lives in the database — no code changes needed.

Table Purpose
config_key_value Global settings and feature flags
symbol_config Per-symbol overrides (JSON)
token_secret Encrypted credentials (Fernet)

Resolution order: Hardcoded defaults → Active profile → ConfigKeyValueSymbolConfig.overrides_json

Key configuration values (set via dashboard or make seed-interactive):

Key Default Description
detector.wall_k_multiplier 3.0 Multiplier over median qty to identify a wall
detector.near_bps 50.0 Max basis points from best price to flag a wall
detector.min_score 70 Minimum score to emit a detection event
telegram.min_score 80 Minimum score to send a Telegram alert
messaging.providers logger,telegram Active messaging providers

Detection Logic

Detects manipulative order book patterns with a 0–100 composite score:

Pattern Description Score
Wall near price Large order within N bps of best price Base 50
+ High qty ratio Quantity > 1.5× detection threshold +10
+ Laddering Wall repositioned ≥2 times toward price +15
+ Pull-before-touch Wall disappears just before price reaches it +25
+ Tight spread Bid/ask spread below threshold +10

Events are emitted when score ≥ detector.min_score (default 70). Telegram alerts fire when score ≥ telegram.min_score (default 80).


Accuracy Monitoring

Run a session to measure how often detections precede actual price moves:

# 4-hour session with live terminal dashboard
uv run --package depthwatch-bot python -m depthwatch_bot.app.main monitor

# Quick 10-minute test
uv run --package depthwatch-bot python -m depthwatch_bot.app.main monitor --duration 600

# Specific symbols, headless
uv run --package depthwatch-bot python -m depthwatch_bot.app.main monitor \
  --symbols BTCUSDT,ETHUSDT --no-dashboard

Produces a Markdown report with precision/recall/F1, win rates by symbol and pattern type, ROI simulation, and score threshold analysis. Saved to the system temp directory (/tmp/ on macOS/Linux, %TEMP% on Windows) as depthwatch_accuracy_report_<TIMESTAMP>.md.


Architecture

Layer Separation

Models (ORM)        — SQLAlchemy entities only; no business logic
  └─ Stores         — CRUD operations; no network, no orchestration
       └─ Managers  — Orchestration and business flows
            └─ Clients  — External API integrations (Binance, Telegram)

Data Flow

Binance WebSocket
      │
      ▼
  BookManager ──► DetectionManager ──► EventBus
                                           │
                              ┌────────────┴────────────┐
                              ▼                         ▼
                           DbSink               MessagingSink
                        (SignalEvent)      ┌──────────┴──────────┐
                                           ▼                     ▼
                                     LoggerProvider      TelegramProvider
                                                               │
REST API ◄────────────────────────────────────────────────────┘
   │
   ▼
UI Dashboard (SSE stream for live events)

Database Migrations

Migrations are managed with Alembic and run automatically during make setup.

make migrate                              # Apply all pending migrations
make makemigrations MSG="describe change" # Generate migration from model diff
make migrate-rollback                     # Undo last migration
make migrate-history                      # Show full history
make migrate-current                      # Show current revision

Development

Running Tests

make test                                        # All packages
cd packages/bot && uv run pytest tests/          # Bot only
cd packages/api && uv run pytest tests/          # API only
cd packages/bot && uv run pytest --cov=src --cov-report=term-missing

Code Quality

make lint                                   # ruff + eslint
make format                                 # black
cd packages/bot && uv run mypy src/         # Type checking

Adding Translations

Edit the locale files in packages/ui/src/locales/:

  • en.json — English
  • ru.json — Russian

Both files must have matching keys.


Production Deployment

Systemd — Bot

# /etc/systemd/system/depthwatch-bot.service
[Unit]
Description=DepthWatch Bot
After=network.target

[Service]
Type=simple
User=depthwatch
WorkingDirectory=/opt/depthwatch
ExecStart=/opt/depthwatch/.venv/bin/python -m depthwatch_bot.app.main run
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Systemd — API

# /etc/systemd/system/depthwatch-api.service
[Unit]
Description=DepthWatch API
After=network.target

[Service]
Type=simple
User=depthwatch
WorkingDirectory=/opt/depthwatch
EnvironmentFile=/opt/depthwatch/.env
ExecStart=/opt/depthwatch/.venv/bin/flask --app depthwatch_api.app:create_app run --host=0.0.0.0 --port=5000
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Nginx — UI + API Proxy

server {
    listen 80;
    server_name dashboard.yourdomain.com;

    root /opt/depthwatch/packages/ui/dist;
    index index.html;

    location /api {
        proxy_pass http://localhost:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Build the UI before deploying:

cd packages/ui && npm run build

Troubleshooting

API won't start

  • Check .env exists at the workspace root and contains SECRETS_ENCRYPTION_KEY.

Bot won't start

  • macOS/Linux: ps aux | grep depthwatch
  • Windows: Get-Process python | Where-Object { $_.CommandLine -like '*depthwatch*' }
  • Re-apply migrations: make migrate (macOS/Linux) or .\scripts\windows\migrate.ps1 (Windows)

UI connection errors

  • Verify the API is running: curl http://localhost:5000/api/bot/status
  • Check the browser console for CORS errors.

Port already in use

macOS/Linux:

lsof -ti:5000 | xargs kill   # free API port
lsof -ti:3010 | xargs kill   # free UI port

Windows (PowerShell):

Stop-Process -Id (Get-NetTCPConnection -LocalPort 5000).OwningProcess -Force   # free API port
Stop-Process -Id (Get-NetTCPConnection -LocalPort 3010).OwningProcess -Force   # free UI port

UI styles not loading

cd packages/ui && rm -rf node_modules/.vite dist && npm run dev

Security

  • Credentials (Telegram token, Binance keys) are encrypted at rest using Fernet symmetric encryption.
  • The encryption key (SECRETS_ENCRYPTION_KEY) lives only in .env — never committed.
  • The API supports optional key authentication: set API_KEY in .env and pass X-API-Key: <value> on every request.
  • No plaintext credentials appear in logs or API responses.

Architecture Reference

See CLAUDE.md for a full technical reference covering layer responsibilities, exchange abstraction, messaging provider architecture, detection scoring details, and the analytics monitoring system.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages