Spaces:
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
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-liveis set- paper performance is consistently profitable
- manual approval is granted (
ALLOW_LIVE_TRADING=1or approval flag file exists) HL_PRIVATE_KEYis configured
Files
hbot.py: existing Hyperliquid API framework and order placement helpersadaptive_bot.py: new adaptive ML paper/live-gated trading bothf_advisor.py: optional external advisor client (e.g., Hugging Face endpoint)smoke_test.py: offline persistence and learning smoke testml_diagnostics.py: offline + live learning diagnostics reportdiagnostics_smoke_test.py: quick smoke test for diagnostics logicadvisor_smoke_test.py: quick smoke test for advisor parsing behaviorpaper_report.json: runtime status and metrics output (created at runtime)
Health endpoints (for HF + UptimeRobot)
GET /-> lightweight status response (200) for uptime checksGET /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
- Install dependencies:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
- Run the offline smoke test:
python smoke_test.py
Optional: run diagnostics smoke test:
python diagnostics_smoke_test.py
Optional: run advisor smoke test:
python advisor_smoke_test.py
- Start the adaptive paper bot:
python adaptive_bot.py --interval 15m --poll-seconds 45
- Check ML learning quality from saved state:
python ml_diagnostics.py --state-file learning_state.joblib
If the bot is running locally, include live status snapshot:
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):
python ml_diagnostics.py --state-file learning_state.joblib --json
Send a compact diagnostics snapshot to Telegram:
python ml_diagnostics.py --state-file learning_state.joblib --send-telegram
Optional knobs for early growth from scratch:
python adaptive_bot.py --interval 15m --exploration-rate 0.08
Safer learning defaults (already enabled by default):
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:
python adaptive_bot.py --interval 15m --pause-cooldown-minutes 180
Enable periodic ML progress updates to Telegram (good for phone monitoring):
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):
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:
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 confidenceveto: advisor can block opposite-side model trades at/above min confidenceblend: blend localp_longwith advisorp_longand 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
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:
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):
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):
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:
docker build -t hyperliquid-adaptive-bot .
Run locally in paper mode:
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:
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(default15m)BOT_POLL_SECONDS(default45)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(default0.0.0.0)BOT_HEALTH_PORT(default7860)PORT(default7860, 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, defaultblend)BOT_HF_ADVISOR_MIN_CONFIDENCE(default0.60)BOT_HF_ADVISOR_BLEND_WEIGHT(default0.35)BOT_HF_ADVISOR_TIMEOUT_SECONDS(default4.0)BOT_MIN_MODEL_SAMPLES_FOR_SIGNAL(default50)BOT_PAUSE_ON_NEGATIVE_EXPECTANCY(1/true/yesby default)BOT_PAUSE_EXPECTANCY_LOOKBACK(default30)BOT_PAUSE_EXPECTANCY_THRESHOLD_USD(default-1.0)BOT_PAUSE_MAX_DRAWDOWN_PCT(default12.0)BOT_PAUSE_COOLDOWN_MINUTES(default180, set0to disable auto-expiry)ALLOW_LIVE_TRADING(set to1/true/yesto manually approve live trading)BOT_LIVE_STARTUP_TEST(set non-empty to add--live-startup-test)BOT_LIVE_STARTUP_TEST_COIN(defaultHYPE)BOT_LIVE_STARTUP_TEST_NOTIONAL(default12)BOT_TELEGRAM_ML_REPORT_HOURS(default6, set0to disable periodic ML Telegram report)BOT_TELEGRAM_ML_REPORT_MIN_TRADES(default15)BOT_RISK_VOLATILITY_FLOOR_MULT(default0.45)BOT_RISK_VOLATILITY_CAP_MULT(default1.20)BOT_RISK_REGIME_ADAPT_STRENGTH(default0.35)BOT_RISK_REGIME_MIN_SAMPLES(default12)TELEGRAM_BOT_TOKEN(required for Telegram notifications)TELEGRAM_CHAT_ID(required for Telegram notifications)PROXY_URL(required bytelegram_notifier.pyto 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
- Keep state and report under
/data(already default inDockerfile). - Set Telegram secrets in your Space variables:
TELEGRAM_BOT_TOKENTELEGRAM_CHAT_IDPROXY_URL
- Optionally tune ML push cadence:
BOT_TELEGRAM_ML_REPORT_HOURS=6BOT_TELEGRAM_ML_REPORT_MIN_TRADES=15
- View live JSON diagnostics in a phone browser:
https://<your-space>.hf.space/statushttps://<your-space>.hf.space/status/full
- Trigger one-off diagnostics message from Space shell:
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:
- For
HYPE, it builds a feature vector from latest candles:- short-horizon returns (
ret_1,ret_3,ret_8) - trend/momentum (
macd, scaledrsi) - volatility and activity (
atr14,vol_z)
- short-horizon returns (
SGDClassifier(loss="log_loss")predicts probability of a profitable long setup.- Entry logic maps probability to actions:
p_long >= threshold-> longp_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
- 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
- long trade win -> label
- The model is updated immediately using
partial_fit(...)on that single labeled example. - The confidence threshold adapts from recent realized win rate (last 30 outcomes), becoming stricter or looser.
- Learned state is persisted to
learning_state.jobliband reloaded on restart. - 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_tradedown 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_scorein/statusand/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_longthan long losers - short winners should have lower
p_longthan short losers
- long winners should have higher
- direction-aware Brier score (lower is better)
- optional runtime snapshot from
/status/fullincluding 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(defaulteither)--live-approval-file(defaultallow_live_trading.flag)
- Startup live order test can be controlled with:
--live-startup-test / --no-live-startup-test--live-startup-test-coin(defaultHYPE)--live-startup-test-notional(default12)