Skip to content

Program Trading

Program Trading lets you define trading logic with code. When signals trigger, your strategy executes automatically without AI involvement.

Program Trading vs AI Trader

FeatureAI TraderProgram Trading
DecisionAI model analyzes and decidesCode logic executes directly
FlexibilityHigh, handles complex scenariosMedium, follows preset rules
PredictabilityLow, AI may judge differentlyHigh, same conditions = same results
SpeedSlower (waits for AI response)Fast (direct code execution)
Best forComplex market analysisClear rule-based strategies

When to use which?

  • AI Trader: When you need AI to analyze market conditions and handle ambiguous situations
  • Program Trading: When you have clear trading rules and want fast, predictable execution

Workflow Overview

Market Data Collection → Signal Detection → Program Execution → Order Execution → Attribution

Core Concepts

1. Signals and Signal Pools

Signals define "what conditions are worth watching":

  • Example: CVD exceeds 1M, OI growth > 5%, Funding Rate > 0.01%

Signal Pools combine multiple signals for more reliable triggers:

  • AND mode: All signals must be satisfied (stricter)
  • OR mode: Any signal triggers (more sensitive)

The system uses edge triggering: triggers only once when conditions are first met.

2. Market Regime Detection

The system automatically identifies current market state:

RegimeMeaningTrading Suggestion
BreakoutTrend startingEnter with trend
ContinuationTrend continuingHold or add
ExhaustionTrend weakeningConsider taking profit
AbsorptionLarge orders absorbedWait and watch
Stop HuntStop loss huntingWait for reversal
TrapBull/bear trapTrade cautiously
NoiseNo clear directionStay out

Available Data in Strategies

Account Info

FieldDescription
available_balanceAvailable balance
total_equityTotal equity
positionsCurrent positions (dict by symbol)
open_ordersPending orders
recent_tradesRecent closed trades

Trigger Info

FieldDescription
trigger_symbolTriggered symbol (e.g., BTC)
trigger_typeTrigger type (signal / scheduled)
signal_pool_nameName of triggered signal pool
triggered_signalsList of triggered signal details
trigger_market_regimeMarket regime at trigger time

Environment Config

FieldDescription
environmentEnvironment (testnet / mainnet)
max_leverageMaximum leverage limit
default_leverageDefault leverage

Available Functions

Get K-line Data

python
get_klines(symbol, period, count)
  • Purpose: Get historical candlesticks
  • Parameters: Symbol, period (5m/15m/1h/4h/1d), count
  • Returns: List of candles (time, OHLCV)

Get Technical Indicators

python
get_indicator(symbol, indicator, period)
  • Purpose: Get calculated technical indicators
  • Parameters: Symbol, indicator name, period

Get Market Flow Data

python
get_flow(symbol, metric, period)
  • Purpose: Get market flow metrics
  • Parameters: Symbol, metric type, time window

Get Market Regime

python
get_regime(symbol, period)
  • Purpose: Get current market state classification
  • Returns: Regime type, confidence, direction, reason

Get Price

python
get_price(symbol)              # Get latest price
get_price_change(symbol, period)  # Get price change percentage

Built-in Technical Indicators

Moving Averages

IndicatorDescription
MA5 / MA10 / MA20Simple Moving Average
EMA20 / EMA50 / EMA100Exponential Moving Average

Momentum Indicators

IndicatorDescription
RSI7 / RSI14Relative Strength Index
MACDMoving Average Convergence Divergence (returns macd, signal, histogram)
STOCHStochastic Oscillator (returns K, D values)

Volatility Indicators

IndicatorDescription
BOLLBollinger Bands (returns upper, middle, lower)
ATR14Average True Range

Volume Indicators

IndicatorDescription
OBVOn-Balance Volume
VWAPVolume Weighted Average Price

Market Flow Metrics

MetricDescriptionUse Case
CVDCumulative Volume DeltaBuy/sell pressure comparison
OI_DELTAOpen Interest change rateCapital flow direction
TAKERTaker buy/sell ratioMarket sentiment
DEPTHOrder book depth ratioSupport/resistance strength
IMBALANCEOrder book imbalanceShort-term direction
FUNDINGFunding rateLong/short sentiment

Decision Output

Your strategy must return a Decision object:

FieldRequiredDescription
operationYesOperation type: buy / sell / close / hold
symbolYesTrading pair
reasonYesDecision reasoning
target_portion_of_balanceFor buy/sellBalance portion to use (0.1-1.0)
leverageFor buy/sellLeverage multiplier
take_profit_priceNoTake profit price
stop_loss_priceNoStop loss price

Step-by-Step Guide

Step 1: Configure Signals (Optional)

If you want signal-triggered programs, first create signals and signal pools in Signal Pools.

Common monitoring metrics:

  • CVD: Cumulative Volume Delta - buy/sell pressure
  • OI Change: Open Interest change - capital flow
  • Funding Rate: Long/short sentiment indicator
  • Order Book Depth: Buy/sell pressure comparison

Step 2: Create AI Trader Account

  1. Go to Account Management page
  2. Create new account, select "AI" type
  3. Configure AI model and API Key
  4. Enter Hyperliquid private key (use testnet first)
  5. Enable "Auto Trading" switch

Step 3: Create Trading Program

Create Program

  1. Go to Program Management page
  2. Click AI Code Assistant, describe your strategy in natural language
  3. AI generates and tests code, outputs to editor when passed
  4. Click Save

AI Code Assistant

Step 4: Bind Program to Account

Bind Program

  1. Select the AI Trader account to bind
  2. Check the signal pools to trigger on
  3. Set scheduled trigger interval (optional)
  4. Click Save Binding

Binding Config

Backtesting

After binding, you can backtest your program to validate it.

Backtest Types

TypePurposeDescription
Program BacktestValidate strategy codeSimulate strategy with historical K-lines
Signal BacktestValidate signal effectivenessCheck historical trigger patterns

How Backtesting Works

Load historical K-line data

Iterate from candle #50 onwards

Build MarketData for each candle (only sees current and past data)

Execute strategy code, get Decision

Simulate trade execution (calculate fees, update virtual positions)

Output backtest results

Data Requirements

Backtesting requires historical data. If the system wasn't running during a period, there's no market flow data for that time, making backtest results inaccurate. Keep the system running 24/7 or deploy to a server.

Backtest Result Metrics

MetricDescription
Total TradesNumber of open/close trades
Win RatePercentage of profitable trades
Total PnLCumulative profit/loss
Max DrawdownMaximum equity decline from peak
Sharpe RatioRisk-adjusted return
Equity CurveAccount value over time

Backtest Results

Monitoring

View Execution Logs

Check detailed trigger records in the Signal System page:

Execution Logs

View Positions and Assets

Monitor real-time positions, PnL, and asset curves in the Dashboard:

Dashboard

Best Practices

  1. Test before live trading: Validate all strategies on testnet first
  2. Control position size: Don't use too large a portion per trade
  3. Use reasonable leverage: Choose leverage based on strategy characteristics
  4. Regular review: Analyze strategy performance through execution logs
  5. Diversify risk: Run multiple accounts with different strategies

Next Steps