MFT/HFT & Market Making suite for Hyperliquid. Features SAC/PPO agent that optimizes Avellaneda-Stoikov inventory control, VPIN & Kyle's Lambda toxicity classification, FIFO queue warfare estimation, spoofing counter, predatory liquidity hunting, and tactical funding arbitrage. Simulation & Live WS runner.
game-theory-trading-strats
Game-theoretic microstructure strategies for crypto perpetuals. Tested on Hyperliquid; adaptable to Binance Perps, dYdX, and similar venues.
Modules
Strategies (strategies/)
| Module | Game | Edge | |--------|------|------| | spoofing_counter.py | Crawford-Sobel Signaling | Detect fake depth, fade the illusion | | predatory_liquidity.py | Stackelberg Coordination | Join or fade stop cascades | | info_asymmetry.py | Glosten-Milgrom Adverse Selection | VPIN + Rolling ADV, Kyle's ฮป, flow toxicity | | queue_warfare.py | FIFO Queue Leadership | Iceberg detection, stochastic cancel factor ฮฑ, OFI-triggered cancel | | funding_arbitrage.py | Convergence Timing Game | Pre-print funding capture, spot-perp divergence | | liquidation_frontrun.py | Dominated Strategy Exploitation | Front-run deterministic liq engines | | adaptive_guerrilla.py | Avellaneda-Stoikov + toxic flow cancel | Decaying risk horizon T-t, inventory skew, adverse selection deflection | | adverse_selection.py | โ | Markout PnL, effective/realized spread decomposition, Roll estimator, Amihud ratio |
Engine (engine/)
| Module | Role | |--------|------| | init.py | Shared data structures, enums, simulation utilities | | runner.py | Central orchestrator - simulation and live Hyperliquid modes | | hyperliquidfeed.py | Live WebSocket feed with asyncio.Queue + callsoon_threadsafe, REST funding polling, reconnect watchdog | | centralriskmanager.py | Pre-trade risk gate: circuit breaker, sizing shaver, fat-finger, toxicity cooldown | | hot_paths.py | Auto-selecting wrapper - Cython extension or pure Python fallback | | hotpaths.pyx | Cython hot paths: OFI, VPIN bucket fill, Kyle's ฮป OLS, Poisson fill prob, lot floor | | hotpaths_pure.py | Pure Python fallback - identical API to the compiled extension | | setuphotpaths.py | Build script for the Cython extension |
Backtesting (backtesting/)
| Module | Role | |--------|------| | tickbytick_backtester.py | Tick-by-tick L2 replay with FIFO queue simulation, latency modeling, and PnL attribution | | RL_tuner.py | SAC/PPO agent that optimizes Avellaneda-Stoikov parameters + toxic flow thresholds in real time |
Setup
pip install -r requirements.txt
Optional: compile Cython hot paths (~10-100x speedup on inner loops)
pip install Cython>=3.0.0 # or: pip install -e ".[speed]"
cd engine && python setuphotpaths.py build_ext --inplace && cd ..
Optional: RL parameter tuner
pip install gymnasium stable-baselines3 # or: pip install -e ".[rl]"
Run
# Simulation
python -m engine.runner
Live
python -m engine.runner --live --coin BTC
Testnet
python -m engine.runner --live --coin BTC --testnet
Backtest - simple mode
python -m backtesting.tickbytick_backtester
Backtest - pro mode (FIFO queue + latency)
python -c "
from backtesting.tickbytick_backtester import ProBacktestEngine, TickLoader, LatencyConfig, ProbQueueCancelModel
ticks = TickLoader.fromcsv('data/btcticks.csv')
engine = ProBacktestEngine(
strategies={...},
latencyconfig=LatencyConfig(feedlatencyus=150, orderlatency_us=600),
cancel_model=ProbQueueCancelModel(),
)
engine.run(ticks).print_summary()
"
RL parameter tuner - pipeline demo (no gym required)
python -m backtesting.RL_tuner
RL parameter tuner - train SAC agent
python -c "
from backtesting.RLtuner import trainagent, TrainConfig
agent = trainagent(TrainConfig(algorithm='SAC', totaltimesteps=500_000))
agent.save('models/asrlagent')
"
Each strategy module is independently runnable:
python -m strategies.spoofing_counter
python -m strategies.funding_arbitrage
python -m strategies.adverse_selection
All -m commands run from the repo root.
Testing
pip install -e ".[dev]"
pytest -v
84 tests covering init.py (InventoryState fill accounting + unrealized_pnl), centralriskmanager.py (circuit breaker, pre-flight fat-finger/price-deviation/ cooldown/shave logic, regime haircuts), hotpaths.py, hyperliquidfeed.py (WS payload parsing against the official schema, reconnect watchdog), fundingarbitrage.py and liquidationfrontrun.py (PnL math), and a runner.py integration/smoke suite. Runs automatically on push/PR via .github/workflows/tests.yml across Python 3.10-3.12.
Architecture
[Market Data]
โ
โโโ HyperliquidFeed (live) or TickLoader (backtest)
โ
โผ
[CentralRunner / BacktestEngine / ProBacktestEngine]
โ
โโโ FlowToxicityClassifier (VPIN + Kyle's ฮป + Rolling ADV)
โ
โโโ Strategy modules (per-tick signals + execution orders)
โ โโโ hot_paths (OFI, vol, fill prob - Cython if available)
โ โโโ RLAugmentedGuerrillaStrategy โ ASParamAgent (SAC/PPO)
โ โโโ optimizes ฮณ, spread, toxicity threshold, size
โ
โโโ CentralRiskManager (pre-flight: halt / shave / fat-finger / cooldown)
โ
โโโ FIFOQueueSimulator + LatencySimulator [ProBacktestEngine only]
โ โโโ ReduceRatioCancelModel / ProbQueueCancelModel
โ โโโ Iceberg detection via level replenishment
โ โโโ Log-normal order flight time (feed + order latency)
โ
โโโ AdverseSelectionMonitor (markout PnL, Roll spread, Amihud)
Backtester modes
| Feature | BacktestEngine | ProBacktestEngine | |---------|-----------------|---------------------| | Tick-by-tick L2 replay | โ | โ | | Passive fill simulation | conservative queue share | FIFO queue position | | Cancellation model | - | ReduceRatio / ProbQueue | | Iceberg detection | - | replenishment pattern | | Feed latency (stale book) | - | log-normal, configurable | | Order flight time | - | log-normal, configurable | | Latency displacement tracking | - | โ | | Queue advancement metrics | - | โ |
Note on L2 vs L3. Hyperliquid's public feed is L2. ProBacktestEngine extracts maximum fidelity from L2: FIFO position is estimated probabilistically from depth and inferred cancellations. True event-by-event L3 replay would require exchange-side data not publicly available.
RL parameter tuner
RL_tuner.py trains a SAC agent to continuously optimize the Avellaneda-Stoikov parameters and toxic flow thresholds of AdaptiveGuerrillaStrategy. The agent does not replace the strategy - it tunes it.
State (14 features): AS model state (ฮณ, ฯ, T-t), toxicity metrics (VPIN, Kyle's ฮป, composite score), inventory skew, cancel rate, spread bps, book imbalance, realized PnL, adverse selection cost, time to funding.
Actions (4 continuous): gammamultiplier โ [0.3, 3.0], spreadmultiplier โ [0.5, 2.0], toxicitythreshold โ [0.25, 0.85], sizemultiplier โ [0.3, 1.5].
Reward: ฮPnL โ inventory risk penalty โ adverse selection cost โ drawdown penalty โ toxic hold penalty.
from backtesting.RLtuner import trainagent, compare_baseline, TrainConfig
agent = trainagent(TrainConfig(algorithm="SAC", totaltimesteps=500_000)) compare_baseline(agent) # prints RL-tuned vs fixed-param PnL side by side
The pipeline (observation โ action โ params) works without gymnasium. Only training requires pip install gymnasium stable-baselines3.
Risk manager
from engine.centralriskmanager import CentralRiskManager, RiskConfig
rm = CentralRiskManager(RiskConfig( maxnetposition = 5.0, # BTC maxdrawdownlimit = 500.0, # USD dailylosslimit = 1000.0, # USD size_decimals = 4, # Hyperliquid BTC lot step = 0.0001 toxicitycooldowns = 60.0, ))
Per-tick call order:
rm.updatemarketstate(book.mid)
alive = rm.updateglobalpnl(realized, unrealized) # False = circuit breaker
orders = rm.preflightcheck(strategyname, proposedorders, inventory, vol, regime)
rm.reporttoxicfill(strategy_name) # after detecting adverse fill
PnL decomposition
All strategies track: spread capture, inventory PnL, adverse selection cost, and funding/basis PnL. AdverseSelectionMonitor adds post-fill markout analysis at 5s / 15s / 30s / 60s / 300s horizons.
Notes
- Liquidation front-running uses only publicly observable order book data and exchange OI metrics.
- Spoofing detection is a counter-strategy tool, not a spoofing implementation.
- Calibrate all rolling windows, thresholds, and
size_decimalsto your venue before going live. - The Cython extension is optional. All hot paths fall back to pure Python automatically.
cancel_ratioinReduceRatioCancelModelshould be calibrated per venue and distance-to-BBO. Typical range for crypto perps: 0.10-0.35.- SAC is recommended over PPO for this problem - off-policy learning handles the non-stationarity of market regimes better.