# Algorithm Builder Reference

Complete reference for building AI trading strategies.

---

## Signal Categories

The platform provides 417 signal primitives across 14 categories.

> **Tip**: Use the **DSL Primitive Browser** at Trading > Algorithms > Primitives to explore all available signals with descriptions, examples, and copy-to-clipboard functionality.

### Price Signals
| Signal | Description | Example |
|--------|-------------|---------|
| `price` | Current price | price > 100 |
| `price_change` | Price change over period | price_change(24h) > 5% |
| `price_above` | Price above level | price_above(sma_50) |
| `price_below` | Price below level | price_below(resistance) |
| `new_high` | New period high | new_high(52w) |
| `new_low` | New period low | new_low(20d) |
| `gap_up` | Gap up from prior close | gap_up > 2% |
| `gap_down` | Gap down from prior close | gap_down > 2% |

### Technical Signals
| Signal | Description | Parameters |
|--------|-------------|------------|
| `rsi` | Relative Strength Index | period (default 14) |
| `rsi_oversold` | RSI below threshold | threshold (default 30) |
| `rsi_overbought` | RSI above threshold | threshold (default 70) |
| `macd_cross_up` | MACD crosses above signal | - |
| `macd_cross_down` | MACD crosses below signal | - |
| `macd_histogram` | MACD histogram value | - |
| `sma` | Simple Moving Average | period (20, 50, 200) |
| `ema` | Exponential Moving Average | period |
| `sma_cross_up` | Shorter MA crosses above longer | fast, slow periods |
| `sma_cross_down` | Shorter MA crosses below longer | fast, slow periods |
| `golden_cross` | 50 SMA crosses above 200 SMA | - |
| `death_cross` | 50 SMA crosses below 200 SMA | - |
| `bollinger_upper` | Price at upper Bollinger | period, stddev |
| `bollinger_lower` | Price at lower Bollinger | period, stddev |
| `atr` | Average True Range | period (default 14) |
| `atr_percent` | ATR as % of price | period |
| `volume_spike` | Volume above average | multiplier (default 2x) |
| `volume_above_avg` | Volume exceeds N-day avg | period |
| `obv_rising` | On-Balance Volume rising | - |
| `stochastic_oversold` | Stochastic < 20 | - |
| `stochastic_overbought` | Stochastic > 80 | - |

### Sentiment Signals
| Signal | Description | Source |
|--------|-------------|--------|
| `news_sentiment` | News sentiment score | -1 to +1 |
| `news_positive` | Positive news sentiment | threshold |
| `news_negative` | Negative news sentiment | threshold |
| `social_sentiment` | Combined social score | -1 to +1 |
| `reddit_sentiment` | Reddit sentiment | -1 to +1 |
| `twitter_sentiment` | Twitter sentiment | -1 to +1 |
| `analyst_buy` | Analyst buy ratings % | threshold |
| `analyst_sell` | Analyst sell ratings % | threshold |
| `human_vs_bot` | Human-driven vs bot score | - |

### Macro Signals
| Signal | Description | Range |
|--------|-------------|-------|
| `vix` | VIX level | absolute |
| `vix_above` | VIX above threshold | threshold |
| `vix_below` | VIX below threshold | threshold |
| `vix_percentile` | VIX historical percentile | 0-100 |
| `yield_curve` | Yield curve slope | spread |
| `yield_inverted` | Yield curve inverted | boolean |
| `fed_funds` | Fed funds rate | rate |
| `fear_greed` | Fear & Greed Index | 0-100 |

### Pattern Signals
| Signal | Description | Output |
|--------|-------------|--------|
| `fvg_bullish` | Bullish FVG detected | boolean |
| `fvg_bearish` | Bearish FVG detected | boolean |
| `fvg_unfilled` | Unfilled FVG exists | boolean |
| `candle_hammer` | Hammer pattern | boolean |
| `candle_engulfing` | Engulfing pattern | bullish/bearish |
| `candle_doji` | Doji pattern | boolean |
| `candle_star` | Morning/Evening star | bullish/bearish |
| `support_near` | Price near support | distance |
| `resistance_near` | Price near resistance | distance |
| `breakout` | Breakout detected | up/down |
| `double_bottom` | Double bottom pattern | boolean |
| `double_top` | Double top pattern | boolean |

### Position Signals
| Signal | Description | Use |
|--------|-------------|-----|
| `has_position` | Currently holding | boolean |
| `position_size` | Current position value | dollars |
| `position_pnl` | Current P&L | percent/dollars |
| `position_time` | Time in position | minutes/hours/days |
| `unrealized_gain` | Unrealized profit | percent |
| `unrealized_loss` | Unrealized loss | percent |
| `max_favorable` | Max favorable excursion | percent |
| `max_adverse` | Max adverse excursion | percent |

### Sizing Signals
| Signal | Description | Output |
|--------|-------------|--------|
| `kelly_fraction` | Kelly criterion sizing | 0-1 |
| `half_kelly` | Half Kelly sizing | 0-0.5 |
| `volatility_size` | Volatility-adjusted size | dollars |
| `atr_size` | ATR-based position size | dollars |
| `fixed_fraction` | Fixed portfolio fraction | percent |
| `max_risk` | Risk-limited sizing | dollars |

### Prediction Market Signals
| Signal | Description | Source |
|--------|-------------|--------|
| `polymarket_prob` | Polymarket probability | 0-100 |
| `polymarket_change` | Prob change over period | percent |
| `kalshi_prob` | Kalshi probability | 0-100 |
| `pred_market_high` | High probability event | threshold |
| `pred_market_momentum` | Prob momentum | direction |

### Fundamental Signals
| Signal | Description | Use |
|--------|-------------|-----|
| `pe_ratio` | P/E Ratio | value |
| `pe_below` | P/E below threshold | value |
| `pb_ratio` | P/B Ratio | value |
| `roe` | Return on Equity | percent |
| `debt_equity` | Debt to Equity ratio | value |
| `dividend_yield` | Dividend yield | percent |
| `eps_growth` | EPS growth rate | percent |
| `revenue_growth` | Revenue growth | percent |
| `market_cap_above` | Market cap > threshold | dollars |

### Paradox Signals
| Signal | Description | Output |
|--------|-------------|--------|
| `vix_complacency` | VIX low despite risk | boolean |
| `bad_news_rally` | Rally on bad news | boolean |
| `good_news_selloff` | Selloff on good news | boolean |
| `sentiment_divergence` | Sentiment vs price diverge | boolean |
| `volume_mismatch` | Volume doesn't match move | boolean |

### Composer Signals
| Signal | Description | Example |
|--------|-------------|---------|
| `and` | Both conditions true | A and B |
| `or` | Either condition true | A or B |
| `not` | Condition is false | not A |
| `if_then_else` | Conditional logic | if A then B else C |
| `threshold` | Value crosses level | threshold(rsi, 30, cross_up) |

---

## Entry Conditions

### Basic Entry
```
entry:
  when: rsi < 30 and sma_cross_up(20, 50)
```

### Multi-Condition Entry
```
entry:
  when:
    - rsi < 30
    - macd_cross_up
    - volume_spike(1.5)
  require: all  # or "any"
```

### Time-Filtered Entry
```
entry:
  when: rsi < 30
  time_filter:
    market_hours: true
    exclude_first_minutes: 30
    exclude_last_minutes: 15
```

---

## Exit Conditions

### Basic Exit
```
exit:
  when: rsi > 70
```

### Multiple Exit Types
```
exit:
  take_profit: 10%      # Exit at 10% gain
  stop_loss: 5%         # Exit at 5% loss
  trailing_stop: 3%     # Trail by 3%
  time_limit: 5d        # Exit after 5 days
  condition: rsi > 80   # Exit when condition met
```

### Priority Order
Exits are checked in order:
1. Stop loss (safety first)
2. Take profit
3. Trailing stop
4. Condition-based
5. Time limit

---

## Position Sizing

### Fixed Sizing
```
sizing:
  type: fixed
  amount: 1000          # $1000 per trade
```

### Percent of Portfolio
```
sizing:
  type: percent
  amount: 5%            # 5% of portfolio per trade
```

### Kelly Criterion
```
sizing:
  type: kelly
  fraction: 0.5         # Half Kelly (safer)
  max_size: 10%         # Never exceed 10%
```

### Volatility-Adjusted
```
sizing:
  type: volatility
  target_risk: 2%       # Target 2% portfolio risk
  atr_multiplier: 2     # Use 2x ATR for stop
```

---

## Risk Parameters

### Position Limits
```
risk:
  max_position_size: 10%      # Max 10% in one position
  max_positions: 5            # Max 5 open positions
  max_sector_exposure: 30%    # Max 30% in one sector
```

### Daily Limits
```
risk:
  max_daily_loss: 3%          # Stop if down 3% today
  max_daily_trades: 10        # Max 10 trades per day
  max_drawdown: 15%           # Stop at 15% drawdown
```

### Stop Losses
```
risk:
  stop_loss: 5%               # Fixed stop
  trailing_stop: 3%           # Trailing stop
  atr_stop: 2                 # 2x ATR stop
```

---

## Strategy Templates

### Mean Reversion
```yaml
name: RSI Mean Reversion
entry:
  when: rsi(14) < 30 and price > sma(200)
exit:
  take_profit: 5%
  stop_loss: 3%
  condition: rsi > 50
sizing:
  type: percent
  amount: 5%
```

### Trend Following
```yaml
name: SMA Crossover
entry:
  when: sma_cross_up(50, 200) and volume_above_avg(20)
exit:
  trailing_stop: 10%
  condition: sma_cross_down(50, 200)
sizing:
  type: volatility
  target_risk: 1%
```

### Breakout
```yaml
name: Breakout System
entry:
  when: breakout(up) and volume_spike(2)
exit:
  take_profit: 15%
  stop_loss: 5%
  time_limit: 10d
sizing:
  type: fixed
  amount: 2000
```

### Sentiment-Based
```yaml
name: Sentiment Contrarian
entry:
  when: social_sentiment < -0.5 and rsi < 40
exit:
  take_profit: 8%
  stop_loss: 4%
  condition: social_sentiment > 0
sizing:
  type: kelly
  fraction: 0.25
```

---

## Multi-Asset Strategies

### Universe Definition
```yaml
universe:
  type: preset
  name: sp500
  # OR
  type: custom
  symbols: [AAPL, MSFT, GOOGL, AMZN]
  # OR
  type: screener
  filters:
    market_cap_above: 10B
    sector: technology
```

### Ranking
```yaml
ranking:
  by: momentum(20d)
  direction: desc
  select: top_10
```

### Allocation
```yaml
allocation:
  method: equal_weight
  # OR
  method: market_cap_weight
  # OR
  method: momentum_weight
  rebalance: monthly
```

---

## Backtesting Parameters

### Date Range
```yaml
backtest:
  start: 2020-01-01
  end: 2024-01-01
```

### Starting Capital
```yaml
backtest:
  capital: 100000
```

### Costs
```yaml
backtest:
  commission: 0           # Commission per trade
  slippage: 0.1%         # Estimated slippage
```

---

## Walk-Forward Settings

```yaml
walk_forward:
  train_window: 180       # Train on 180 days
  test_window: 30         # Test on 30 days
  step_size: 30           # Move forward 30 days
  min_trades: 20          # Require 20 trades per window
```

---

## Performance Metrics

After backtesting, you'll see:

| Metric | Good Value | Excellent |
|--------|------------|-----------|
| Sharpe Ratio | > 1.0 | > 2.0 |
| Sortino Ratio | > 1.0 | > 2.0 |
| Max Drawdown | < 20% | < 10% |
| Win Rate | > 50% | > 60% |
| Profit Factor | > 1.5 | > 2.0 |
| Calmar Ratio | > 1.0 | > 2.0 |

---

## Common Errors

### Invalid Signal
```
Error: Unknown signal 'rsi_super'
Fix: Check signal name spelling
```

### Missing Parameter
```
Error: Signal 'sma' requires 'period' parameter
Fix: Add period, e.g., sma(50)
```

### Logic Error
```
Error: Entry condition can never be true
Fix: Review your logic combinations
```

### Insufficient Data
```
Error: Not enough historical data for backtest
Fix: Reduce required history or choose different symbols
```

---

## Tips

### Performance
- Keep conditions simple and clear
- Test one change at a time
- Avoid over-optimization (curve fitting)
- Use out-of-sample testing

### Risk Management
- Always use stop losses
- Don't over-leverage
- Size positions appropriately
- Set daily loss limits

### Common Mistakes
- Over-optimizing to historical data
- Ignoring transaction costs
- Too many conditions
- Insufficient testing

---

*This reference covers the most common signals and patterns. For advanced features, consult the full API documentation.*
