A production-grade, event-driven arbitrage monitoring and automated trading system that operates across Hyperliquid (tradeXYZ) and Binance USD-M perpetual futures for TradFi stock contracts (TSLA, NVDA, SKHYNIX, SAMSUNG, etc.).
Status: Live production system | Language: Node.js | Tests: 47 test files
- Real-time bilateral spread monitoring — Tracks executable BBO spreads between XYZ and Binance for all co-listed TradFi equity perpetuals, with funding rate differentials and historical trend analysis.
- Automated cross-exchange hedging — Upon fill on one venue, immediately hedges the other leg using the optimal route (maker or protected taker IOC), managed by a unified order lifecycle state machine.
- Risk-managed execution — Position balance verification, margin checks, per-ticker allowlists, global trading gate (
/pause//resume), and multi-channel alerts (Telegram + Pushover). - Full audit trail — Every cycle, slice, order, fill, and hedge is assigned a stable ID and recorded in a JSONL execution journal backed by SQLite history, making every trade traceable and replayable.
The system follows a strict four-layer separation:
Market Data Layer Strategy Layer Execution Layer Risk Layer
───────────────── ──────────────── ───────────────── ───────────
Binance REST + WS Spread Threshold ParentOrderExecutor Risk Gate
bookTicker Strategy (~41K loc) Position Balance
Hyperliquid WS allMids Spike Canary ┌─ xyz_maker Margin Check
+ REST l2Book Spread Reversion ├─ protected_taker Leverage Setting
Funding Rate Polling (emits trade intent) ├─ binance_maker Trading Gate
│ Order placement Allowlist
│ Cancellation
│ Requoting
│ Fill attribution
│ Hedge execution
└─ Residual processing
Key principle: Strategies only emit signals (trade intent with direction, size, price, reason). All order execution, fill capture, hedging, and recovery goes through the single ParentOrderExecutor. No strategy calls exchanges directly.
Typical trade flow:
Spread condition triggers
→ Strategy emits trade intent
→ ParentOrderExecutor reads risk snapshot
→ Place XYZ order (maker or protected taker IOC)
→ XyzFillWatcher captures fill (WS real-time + REST catch-up, deduplicated)
→ Binance immediate market hedge
→ ExecutionJournal logs → Telegram notification → Web dashboard update
| Layer | Technology |
|---|---|
| Runtime | Node.js 20+ (vanilla JS, no TypeScript) |
| Exchange API | ccxt (multi-exchange abstraction), native WebSocket (ws) |
| Web Server | Built-in node:http, serves REST API + WebSocket dashboard |
| Frontend | Vanilla JS SPA (~140K), real-time WebSocket updates |
| Storage | SQLite (history), JSONL (execution journal), JSON (config/state) |
| Deployment | systemd on Linux server, autossh tunnel for local dashboard access |
| Testing | Node built-in test runner (node --test), 47 test files |
| Alerts | Telegram Bot API, Pushover push notifications |
-
All orders go through a single executor — One
ParentOrderExecutor(~41K lines) handles all routes (maker, taker, hedge). No duplicated order/cancel/fill-capture logic across strategies. Full state machine with crash recovery. -
Dual-path fill capture with deduplication — WebSocket real-time stream + REST polling catch-up, sharing the same fill key (
{txHash}-{logIndex}). If WS misses a fill, REST catches it within seconds without double-hedging. -
Executable price, not mid-price — All triggers, backtests, and recaps use actual executable prices (BBO with slippage buffer). Mid-price is display-only. This ensures backtests match live execution.
-
Fail-closed by default —
TRADING_MODE=dry-rununtil explicitly set tolive. Manual/pauseis a hard pause: no new positions, no auto-repair, no background close. Survives process restart via on-disk state file. -
Hot path optimization — Market snapshot → strategy → risk → sign → order → fill/hedge uses only in-memory reads and local computation. No REST pre-checks, no waiting on Telegram/dashboard/history writes.
-
Exchange truth is final — After crash restart, the system verifies real orders/positions/cycles from the exchange before resuming. The local journal is a process record, not the position source of truth.
# Install
npm install
cp .env.example .env # Edit with your API keys
# Run (dry-run by default, no real orders)
npm start
# Run tests
npm test
# Open dashboard
open http://127.0.0.1:4321/Set TRADING_MODE=live in .env to enable real order submission. See .env.example for all 80+ configuration options.
src/
├── parent-order-executor.js (~41K) Core execution orchestrator
├── xyz-fill-watcher.js (~34K) Fill capture: WS + REST + dedup
├── xyz-trader.js (~21K) Hyperliquid/XYZ order execution
├── binance-trader.js (~32K) Binance order execution & hedging
├── spike-canary.js (~32K) Spike canary strategy
├── spread-threshold-strategy.js (~31K) Spread threshold strategy
├── radar.js (~23K) Opportunity radar engine
├── history.js (~22K) SQLite historical storage
├── telegram-bot.js (~20K) Telegram bot commands & alerts
├── execution-journal.js (~13K) JSONL trade journal
├── calculations.js Price/spread calculations
├── fill-identity.js Fill deduplication keys
├── live-hedge-attribution.js Hedge attribution logic
├── proxy-detect.js Proxy auto-detection
├── risk-gate.js Risk gate & position balance
└── variational-lighter-quote-poller.js Variational quote polling
server.js (~105K) Main entry: HTTP server, WS, API routes, config
public/
├── app.js (~140K) Frontend dashboard SPA
├── index.html (~27K) Dashboard HTML
└── styles.css (~39K) Dashboard CSS
test/ 47 test files mirroring src/ 1:1
systemd/ systemd service, timer, and health check units
scripts/ Deployment, tunnel, and data management scripts
tools/ Backtesting, history backup, and utility tools
docs/ Architecture docs, engineering principles, reviews
For day-to-day operations (SSH tunnel setup, systemd management, deployment, troubleshooting), see docs/OPS.md.
Read the full engineering principles before contributing. Core rules:
- Test before code — Bug fixes must first write a failing test, then fix.
- Strategies only emit signals — Never call exchanges directly.
- All orders through ParentOrderExecutor — No per-strategy order/cancel logic.
- Hot path minimal — Market snapshot → order must be fast. Defer logging, alerts, history writes.
- Exchange truth is final — Real positions and orders override local state after restart.
这是一个实盘级别的跨交易所套利监控与自动交易系统,在 Hyperliquid(tradeXYZ)与 Binance USD-M 永续合约之间运行,覆盖 TSLA、NVDA、SKHYNIX、SAMSUNG 等 TradFi 股票合约。
- 实时双边价差监控 — 基于 BBO 可成交价的价差、资金费率差、历史趋势
- 自动跨交易所对冲 — XYZ 成交后立即触发 Binance 对冲,或反之
- 风控管理 — 仓位平衡校验、保证金检查、白名单、全局交易闸门
- 完整审计链路 — 每笔订单从触发到成交到对冲全程记录,可回溯可复现
- 市场数据层 — Binance (REST + WebSocket bookTicker) 和 XYZ/Hyperliquid (WebSocket allMids + REST l2Book) 的实时行情快照
- 策略层 — 读取行情快照,产出行 trade intent(方向、数量、价格、原因)。策略不直接调用交易所
- 执行层 (
src/parent-order-executor.js) — 统一的订单执行器,处理所有下单、撤单、重挂、成交归因、对冲和残差处理 - 风控层 — 风险闸门、仓位平衡、保证金检查、杠杆设置、交易闸门
npm install
cp .env.example .env # 编辑填入 API 密钥
npm start # 默认 dry-run,不发真实订单
npm test # 运行 47 个测试文件浏览器打开 http://127.0.0.1:4321/。
详见 docs/OPS.md,包含 SSH 隧道、systemd 管理、部署同步、故障排查和紧急控制。
所有配置通过环境变量设置。参考 .env.example(80+ 配置项):
- Binance API 密钥与交易模式
- XYZ/Hyperliquid 钱包地址与 API Wallet 私钥
- 自动交易白名单
AUTO_TRADE_TICKER_ALLOWLIST - 价差策略阈值、切片大小、最大仓位
- Telegram 风险监控 bot 和价格提醒 bot
- Pushover 强提醒通道
- 资金费率与手续费配置
关键配置:
TRADING_MODE=live # 开启真实下单
AUTO_TRADE_TICKER_ALLOWLIST=DRAM,SKHYNIX # 自动交易白名单
XYZ_ORDER_TRANSPORT=ws # XYZ 下单走 WebSocket
BINANCE_ORDER_TRANSPORT=ws # Binance 下单走 WebSocket
XYZ_TARGET_LEVERAGE=2 # 统一 2 倍杠杆本机 Python runtime(tools/variational-v1/)捕获 Variational 浏览器成交事件,在 Lighter 反向补腿。默认 request_sent 模式(见 Variational 下单请求即对冲),可选 fill_confirmed 模式(等待成交确认)。
启动 runtime 后可通过 http://127.0.0.1:8769/var-lighter 查看终端同源价格、最近成交记录,以及 Variational + Lighter 双边资金变动图。资金快照每小时自动写入 SQLite:
- Variational 权益:portfolio
balance + upnl - Lighter 权益:账户
total_asset_value,含 collateral 和浮盈亏 - 历史 API:
/api/variational-lighter/funds?hours=720 - 合计为双边权益之和;任一边缺失不写零不插值
注意:这是账户权益变动,不是纯交易盈亏归因;浮盈亏、充值、提现或两个平台之间的转账都可能影响显示值,转账同样会显示为资金变动。
- 价差统一使用
B-X = Binance - XYZ - 策略、报警、回测使用可成交价(BBO + 滑点缓冲),不用中间价
- Binance 只匹配
TRADIFI_PERPETUAL/EQUITY类型合约 - 资金费统一年化 APR 显示
- XYZ 成交监听:
WebSocket 实时 + REST 补漏 + 成交唯一键去重
- 百分比模式显示
B-X %,绝对值模式显示B-X 美元/股 - 图表 EMA / rolling median 仅为视觉辅助
- 策略触发使用真实可成交价,不使用平滑数据
每轮策略完整开平仓后发送复盘;每天北京时间 00:00 汇总每日复盘。
- 价差收益:实际 XYZ 成交价与 Binance 成交价的 B-X 变化
- 手续费:优先使用交易所返回的真实手续费
- 资金费:跨结算点时按当时持仓方向、数量和资金费率估算
- 净收益:价差收益 + 资金费 - 手续费