Spaces:
Running
Running
|
Download README.md from chigginrice/hyperliquid-bot: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/chigginrice/hyperliquid-bot/resolve/main/README.md
- Command line
-
hf download hf://spaces/chigginrice/hyperliquid-bot/README.md
-
curl -L -o README.md https://huggingface.co/spaces/chigginrice/hyperliquid-bot/resolve/main/README.md
13.2 kB
| title: Hyperliquid Adaptive Bot | |
| emoji: "🤖" | |
| colorFrom: blue | |
| colorTo: purple | |
| sdk: docker | |
| pinned: false | |
| # Hyperliquid Adaptive Bot | |
| This project now includes an adaptive ML bot that uses your existing Hyperliquid framework. | |
| ## What it does | |
| - Trades **only** `HYPE` (single-asset mode) | |
| - Runs in **paper mode by default** | |
| - Learns from closed paper trades with an online ML model (`SGDClassifier`) | |
| - Persists everything learned to disk (`learning_state.joblib`) so restart resumes learning | |
| - Persists paper runtime state (equity, open positions, entry features) so restart does not break learning continuity | |
| - Uses a profitability gate before any live execution is allowed | |
| - Sends Telegram alerts on trade open/close and a midnight UTC summary | |
| - Sends a readiness alert when paper performance is strong enough for live trading | |
| - Optional startup live transaction test (tiny BUY then SELL) to verify live order execution path | |
| - Can mirror to live orders only when: | |
| - `--enable-live` is set | |
| - paper performance is consistently profitable | |
| - manual approval is granted (`ALLOW_LIVE_TRADING=1` or approval flag file exists) | |
| - `HL_PRIVATE_KEY` is configured | |
| ## Files | |
| - `hbot.py`: existing Hyperliquid API framework and order placement helpers | |
| - `adaptive_bot.py`: new adaptive ML paper/live-gated trading bot | |
| - `hf_advisor.py`: optional external advisor client (e.g., Hugging Face endpoint) | |
| - `smoke_test.py`: offline persistence and learning smoke test | |
| - `ml_diagnostics.py`: offline + live learning diagnostics report | |
| - `diagnostics_smoke_test.py`: quick smoke test for diagnostics logic | |
| - `advisor_smoke_test.py`: quick smoke test for advisor parsing behavior | |
| - `paper_report.json`: runtime status and metrics output (created at runtime) | |
| ## Health endpoints (for HF + UptimeRobot) | |
| - `GET /` -> lightweight status response (`200`) for uptime checks | |
| - `GET /healthz` -> same as root (`200`) | |
| - `GET /status` -> concise overview (equity, open position count, performance, live gate) | |
| - `GET /status/full` -> full runtime JSON (equity, open positions, metrics, thresholds) | |
| - `GET /trades` -> open positions list and count | |
| If your Space is `https://chigginrice-hyperliquid-bot.hf.space/`, your existing root monitor will work as-is. | |
| ## Quick start | |
| 1. Install dependencies: | |
| ```bash | |
| python3 -m venv .venv | |
| source .venv/bin/activate | |
| pip install -r requirements.txt | |
| ``` | |
| 2. Run the offline smoke test: | |
| ```bash | |
| python smoke_test.py | |
| ``` | |
| Optional: run diagnostics smoke test: | |
| ```bash | |
| python diagnostics_smoke_test.py | |
| ``` | |
| Optional: run advisor smoke test: | |
| ```bash | |
| python advisor_smoke_test.py | |
| ``` | |
| 3. Start the adaptive paper bot: | |
| ```bash | |
| python adaptive_bot.py --interval 15m --poll-seconds 45 | |
| ``` | |
| 4. Check ML learning quality from saved state: | |
| ```bash | |
| python ml_diagnostics.py --state-file learning_state.joblib | |
| ``` | |
| If the bot is running locally, include live status snapshot: | |
| ```bash | |
| python ml_diagnostics.py --state-file learning_state.joblib --status-url http://127.0.0.1:7860/status/full | |
| ``` | |
| JSON output (useful for storing artifacts in CI/HF workflows): | |
| ```bash | |
| python ml_diagnostics.py --state-file learning_state.joblib --json | |
| ``` | |
| Send a compact diagnostics snapshot to Telegram: | |
| ```bash | |
| python ml_diagnostics.py --state-file learning_state.joblib --send-telegram | |
| ``` | |
| Optional knobs for early growth from scratch: | |
| ```bash | |
| python adaptive_bot.py --interval 15m --exploration-rate 0.08 | |
| ``` | |
| Safer learning defaults (already enabled by default): | |
| ```bash | |
| python adaptive_bot.py --interval 15m --min-model-samples-for-signal 50 --pause-on-negative-expectancy | |
| ``` | |
| Auto-expire the safety pause after 3 hours (default) so the bot can retry entries: | |
| ```bash | |
| python adaptive_bot.py --interval 15m --pause-cooldown-minutes 180 | |
| ``` | |
| Enable periodic ML progress updates to Telegram (good for phone monitoring): | |
| ```bash | |
| python adaptive_bot.py --interval 15m --telegram-ml-report-hours 6 --telegram-ml-report-min-trades 15 | |
| ``` | |
| Enable volatility/regime-aware risk sizing (defaults shown): | |
| ```bash | |
| python adaptive_bot.py \ | |
| --interval 15m \ | |
| --risk-volatility-floor-mult 0.45 \ | |
| --risk-volatility-cap-mult 1.20 \ | |
| --risk-regime-adapt-strength 0.35 \ | |
| --risk-regime-min-samples 12 | |
| ``` | |
| Advisor is built into the bot and always enabled (local in-process engine). You can optionally attach a remote endpoint (for example, Hugging Face) to augment it: | |
| ```bash | |
| python adaptive_bot.py \ | |
| --interval 15m \ | |
| --hf-advisor-url "https://your-endpoint.example/predict" \ | |
| --hf-advisor-mode blend \ | |
| --hf-advisor-blend-weight 0.35 \ | |
| --hf-advisor-min-confidence 0.60 | |
| ``` | |
| Advisor modes: | |
| - `confirm`: only trade when advisor agrees with the model side at/above min confidence | |
| - `veto`: advisor can block opposite-side model trades at/above min confidence | |
| - `blend`: blend local `p_long` with advisor `p_long` and decide from the blended score | |
| If `--hf-advisor-url` is not set, the local advisor still runs and decisions continue with no external dependency. | |
| ## Optional: allow live mirror only after paper consistency gate | |
| ```bash | |
| export HL_PRIVATE_KEY="your_private_key" | |
| # optional if using delegated account | |
| export HL_ACCOUNT_ADDRESS="0x..." | |
| python adaptive_bot.py --interval 15m --enable-live | |
| ``` | |
| By default, live arm still requires manual approval even after the paper gate is passed: | |
| ```bash | |
| export ALLOW_LIVE_TRADING=1 | |
| # or: touch allow_live_trading.flag | |
| python adaptive_bot.py --interval 15m --enable-live | |
| ``` | |
| Strict two-step approval mode (recommended for safety): | |
| ```bash | |
| export ALLOW_LIVE_TRADING=1 | |
| touch allow_live_trading.flag | |
| python adaptive_bot.py --interval 15m --enable-live --live-approval-mode both | |
| ``` | |
| Optional startup live execution test (real tiny transaction): | |
| ```bash | |
| python adaptive_bot.py --interval 15m --enable-live --live-startup-test --live-startup-test-coin HYPE --live-startup-test-notional 12 | |
| ``` | |
| ## Docker (Hugging Face) | |
| `Dockerfile` is included for Docker-based hosting. | |
| Build locally: | |
| ```bash | |
| docker build -t hyperliquid-adaptive-bot . | |
| ``` | |
| Run locally in paper mode: | |
| ```bash | |
| docker run --rm \ | |
| -e BOT_INTERVAL=15m \ | |
| -e BOT_POLL_SECONDS=45 \ | |
| -v "$(pwd)/data:/data" \ | |
| hyperliquid-adaptive-bot | |
| ``` | |
| Run with live mode allowed after paper gate passes: | |
| ```bash | |
| docker run --rm \ | |
| -e BOT_ENABLE_LIVE=1 \ | |
| -e HL_PRIVATE_KEY="your_private_key" \ | |
| -e HL_ACCOUNT_ADDRESS="0x..." \ | |
| -v "$(pwd)/data:/data" \ | |
| hyperliquid-adaptive-bot | |
| ``` | |
| Environment variables used by the container: | |
| - `BOT_INTERVAL` (default `15m`) | |
| - `BOT_POLL_SECONDS` (default `45`) | |
| - `BOT_STATE_FILE` (default `/data/learning_state.joblib`) | |
| - `BOT_REPORT_FILE` (default `/data/paper_report.json`) | |
| - `BOT_ENABLE_LIVE` (set any non-empty value to append `--enable-live`) | |
| - `BOT_HEALTH_HOST` (default `0.0.0.0`) | |
| - `BOT_HEALTH_PORT` (default `7860`) | |
| - `PORT` (default `7860`, used by Hugging Face Spaces) | |
| - `BOT_HF_ADVISOR_URL` (optional external advisor endpoint) | |
| - `BOT_HF_ADVISOR_TOKEN` (optional bearer token) | |
| - `BOT_HF_ADVISOR_MODE` (`confirm|veto|blend`, default `blend`) | |
| - `BOT_HF_ADVISOR_MIN_CONFIDENCE` (default `0.60`) | |
| - `BOT_HF_ADVISOR_BLEND_WEIGHT` (default `0.35`) | |
| - `BOT_HF_ADVISOR_TIMEOUT_SECONDS` (default `4.0`) | |
| - `BOT_MIN_MODEL_SAMPLES_FOR_SIGNAL` (default `50`) | |
| - `BOT_PAUSE_ON_NEGATIVE_EXPECTANCY` (`1/true/yes` by default) | |
| - `BOT_PAUSE_EXPECTANCY_LOOKBACK` (default `30`) | |
| - `BOT_PAUSE_EXPECTANCY_THRESHOLD_USD` (default `-1.0`) | |
| - `BOT_PAUSE_MAX_DRAWDOWN_PCT` (default `12.0`) | |
| - `BOT_PAUSE_COOLDOWN_MINUTES` (default `180`, set `0` to disable auto-expiry) | |
| - `ALLOW_LIVE_TRADING` (set to `1/true/yes` to manually approve live trading) | |
| - `BOT_LIVE_STARTUP_TEST` (set non-empty to add `--live-startup-test`) | |
| - `BOT_LIVE_STARTUP_TEST_COIN` (default `HYPE`) | |
| - `BOT_LIVE_STARTUP_TEST_NOTIONAL` (default `12`) | |
| - `BOT_TELEGRAM_ML_REPORT_HOURS` (default `6`, set `0` to disable periodic ML Telegram report) | |
| - `BOT_TELEGRAM_ML_REPORT_MIN_TRADES` (default `15`) | |
| - `BOT_RISK_VOLATILITY_FLOOR_MULT` (default `0.45`) | |
| - `BOT_RISK_VOLATILITY_CAP_MULT` (default `1.20`) | |
| - `BOT_RISK_REGIME_ADAPT_STRENGTH` (default `0.35`) | |
| - `BOT_RISK_REGIME_MIN_SAMPLES` (default `12`) | |
| - `TELEGRAM_BOT_TOKEN` (required for Telegram notifications) | |
| - `TELEGRAM_CHAT_ID` (required for Telegram notifications) | |
| - `PROXY_URL` (required by `telegram_notifier.py` to forward messages) | |
| - `HL_PRIVATE_KEY` (required for live mirror) | |
| - `HL_ACCOUNT_ADDRESS` (optional) | |
| ## Telegram notifications | |
| - Entry alert: sent when a paper position opens | |
| - Exit alert: sent when TP/SL closes a position | |
| - Midnight summary: sent once per day at `00:00 UTC` | |
| - Readiness alert: sent when profitability gate is reached and bot is ready to request live approval | |
| Summary includes last-24h trades, win rate, PnL, and overall cumulative stats. | |
| ML progress update (periodic, configurable) includes rolling Brier, rolling expectancy, drawdown, and per-coin Brier. | |
| ## Hugging Face diagnostics + phone workflow | |
| 1. Keep state and report under `/data` (already default in `Dockerfile`). | |
| 2. Set Telegram secrets in your Space variables: | |
| - `TELEGRAM_BOT_TOKEN` | |
| - `TELEGRAM_CHAT_ID` | |
| - `PROXY_URL` | |
| 3. Optionally tune ML push cadence: | |
| - `BOT_TELEGRAM_ML_REPORT_HOURS=6` | |
| - `BOT_TELEGRAM_ML_REPORT_MIN_TRADES=15` | |
| 4. View live JSON diagnostics in a phone browser: | |
| - `https://<your-space>.hf.space/status` | |
| - `https://<your-space>.hf.space/status/full` | |
| 5. Trigger one-off diagnostics message from Space shell: | |
| ```bash | |
| python ml_diagnostics.py --state-file /data/learning_state.joblib --status-url http://127.0.0.1:7860/status/full --send-telegram | |
| ``` | |
| ## How the ML learns | |
| At a high level, this bot uses online learning so it improves continuously while paper trading: | |
| 1. For `HYPE`, it builds a feature vector from latest candles: | |
| - short-horizon returns (`ret_1`, `ret_3`, `ret_8`) | |
| - trend/momentum (`macd`, scaled `rsi`) | |
| - volatility and activity (`atr14`, `vol_z`) | |
| 2. `SGDClassifier(loss="log_loss")` predicts probability of a profitable long setup. | |
| 3. Entry logic maps probability to actions: | |
| - `p_long >= threshold` -> long | |
| - `p_long <= 1 - threshold` -> short | |
| - otherwise hold | |
| - when model is cold, bootstrap mode uses weak momentum direction to generate first labels | |
| - optional exploration (`--exploration-rate`) continues collecting data even during neutral model states | |
| 4. When a trade closes (TP/SL), supervision is direction-aware for a long-probability model: | |
| - long trade win -> label `1` | |
| - long trade loss -> label `0` | |
| - short trade win -> label `0` | |
| - short trade loss -> label `1` | |
| 5. The model is updated immediately using `partial_fit(...)` on that single labeled example. | |
| 6. The confidence threshold adapts from recent realized win rate (last 30 outcomes), becoming stricter or looser. | |
| 7. Learned state is persisted to `learning_state.joblib` and reloaded on restart. | |
| 8. Open paper positions and captured entry features are also persisted, so trades crossing restarts still train the model on close. | |
| Additional adaptive controls for safer compounding: | |
| - volatility/regime-aware sizing scales effective `risk_per_trade` down in high/extreme volatility and up modestly in calm conditions | |
| - regime-performance adaptation nudges risk up/down only after enough same-regime samples exist | |
| - drift monitoring tracks feature-distribution shifts and reports a `feature_drift_score` in `/status` and `/status/full` | |
| - calibration/error monitoring now includes rolling calibration error and directional edge metrics | |
| Additional safety controls now reduce repeated losing phases: | |
| - model-driven entries only activate after a minimum sample count per coin | |
| - optional safety pause halts new entries when recent expectancy is poor and drawdown is elevated | |
| So each closed paper trade directly trains the next decision, and training survives restarts. | |
| ## ML diagnostics | |
| `ml_diagnostics.py` helps answer whether the model signal is actually improving. | |
| It reports: | |
| - overall/per-coin/per-side win rate and expectancy | |
| - directional sanity checks: | |
| - long winners should have higher `p_long` than long losers | |
| - short winners should have lower `p_long` than short losers | |
| - direction-aware Brier score (lower is better) | |
| - optional runtime snapshot from `/status/full` including rolling Brier/expectancy/drawdown | |
| - rolling calibration error, directional edge, and feature drift score | |
| If advisor mode is enabled, `/status/full` includes `advisor` status and counters (requests/errors/blocked signals). | |
| This is useful to catch label/specification issues where the model keeps repeating failing trade patterns. | |
| ## Notes | |
| - The consistency gate currently requires: | |
| - at least 30 paper trades | |
| - win rate >= 58% | |
| - profit factor >= 1.25 | |
| - State persistence file is configurable with `--state-file` | |
| - Runtime report file is configurable with `--report-file` | |
| - Live approval can be controlled with: | |
| - `--require-live-approval / --no-require-live-approval` | |
| - `--live-approval-mode either|both` (default `either`) | |
| - `--live-approval-file` (default `allow_live_trading.flag`) | |
| - Startup live order test can be controlled with: | |
| - `--live-startup-test / --no-live-startup-test` | |
| - `--live-startup-test-coin` (default `HYPE`) | |
| - `--live-startup-test-notional` (default `12`) | |