> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hyperoru.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Program Strategies

> Write deterministic Python trading strategies in a secure sandbox

Program strategies are Python scripts that run in a WASM sandbox. They provide deterministic, backtestable logic for systematic trading — complementing the flexibility of prompt-based strategies.

## How it works

Your Python code implements a `should_trade` function that receives market data and returns a trading decision. The function runs inside Eryx (CPython 3.14 compiled to WASM) with restricted access for security.

```mermaid theme={null}
graph LR
    A[Market Data] --> B[WASM Sandbox]
    B --> C[Python Execution]
    C --> D[Decision Object]
    D --> E[Validation & Execution]
```

## Writing a strategy

A minimal strategy class:

```python theme={null}
class Strategy:
    def should_trade(self, data):
        price = data.get_price("BTC")
        rsi = data.get_indicator("BTC", "rsi", 14)

        if rsi < 30:
            return Decision(
                operation="long",
                symbol="BTC",
                leverage=3,
                take_profit_pct=5.0,
                stop_loss_pct=2.0,
                reasoning="RSI oversold"
            )

        if rsi > 70:
            return Decision(
                operation="short",
                symbol="BTC",
                leverage=3,
                take_profit_pct=5.0,
                stop_loss_pct=2.0,
                reasoning="RSI overbought"
            )

        return Decision(operation="hold")
```

## MarketData API

The `data` parameter passed to `should_trade` provides these methods:

| Method                                | Parameters                                              | Returns                      |
| ------------------------------------- | ------------------------------------------------------- | ---------------------------- |
| `get_price(symbol)`                   | Symbol name                                             | Current price as `float`     |
| `get_klines(symbol, interval, limit)` | Symbol, timeframe (`1m`, `5m`, `1h`, `4h`, `1d`), count | List of OHLCV candles        |
| `get_indicator(symbol, name, period)` | Symbol, indicator name, lookback period                 | Indicator value(s)           |
| `get_positions()`                     | —                                                       | List of open positions       |
| `get_balance()`                       | —                                                       | Available account balance    |
| `get_regime(symbol)`                  | Symbol name                                             | Current market regime string |
| `get_factor(symbol, factor_name)`     | Symbol, factor expression name                          | Factor value as `float`      |

### Supported indicators

```python theme={null}
data.get_indicator("BTC", "rsi", 14)        # Relative Strength Index
data.get_indicator("BTC", "macd", 26)       # MACD line, signal, histogram
data.get_indicator("BTC", "bbands", 20)     # Bollinger Bands (upper, mid, lower)
data.get_indicator("BTC", "ema", 50)        # Exponential Moving Average
data.get_indicator("BTC", "sma", 200)       # Simple Moving Average
data.get_indicator("BTC", "atr", 14)        # Average True Range
```

## Decision fields

The `Decision` object returned by `should_trade`:

| Field             | Type     | Required    | Description                                |
| ----------------- | -------- | ----------- | ------------------------------------------ |
| `operation`       | `string` | Yes         | `"long"`, `"short"`, or `"hold"`           |
| `symbol`          | `string` | If not hold | Trading pair symbol                        |
| `leverage`        | `float`  | If not hold | Position leverage multiplier               |
| `take_profit_pct` | `float`  | No          | Take-profit percentage from entry          |
| `stop_loss_pct`   | `float`  | No          | Stop-loss percentage from entry            |
| `size_pct`        | `float`  | No          | Percentage of available balance to use     |
| `reasoning`       | `string` | No          | Human-readable explanation of the decision |

## Security sandbox

Programs run inside a restricted WASM environment with multiple safety layers:

<CardGroup cols={2}>
  <Card title="Forbidden imports" icon="ban">
    `os`, `sys`, `subprocess`, `socket`, `http`, `urllib`, and other system/network modules are blocked.
  </Card>

  <Card title="Restricted builtins" icon="lock">
    `exec`, `eval`, `compile`, `__import__`, `open`, and file I/O builtins are removed.
  </Card>

  <Card title="Execution timeout" icon="clock">
    Each execution is capped at **30 seconds**. Strategies that exceed this limit are terminated.
  </Card>

  <Card title="No filesystem access" icon="folder-xmark">
    The WASM sandbox has no access to the host filesystem. All data comes through the MarketData API.
  </Card>
</CardGroup>

<Warning>
  The sandbox prevents arbitrary code execution. If your strategy needs external data, fetch it through the platform's market data endpoints or factor engine rather than attempting network calls.
</Warning>

## Creating and binding a program

<Steps>
  <Step title="Create the program">
    ```bash theme={null}
    curl -X POST https://api.production.hyperoru.com/api/programs \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "RSI Mean Reversion",
        "code": "class Strategy:\n    def should_trade(self, data):\n        rsi = data.get_indicator(\"BTC\", \"rsi\", 14)\n        if rsi < 30:\n            return Decision(operation=\"long\", symbol=\"BTC\", leverage=3, take_profit_pct=5.0, stop_loss_pct=2.0)\n        return Decision(operation=\"hold\")"
      }'
    ```
  </Step>

  <Step title="Bind to a trader">
    ```bash theme={null}
    curl -X POST https://api.production.hyperoru.com/api/bindings \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "trader_id": "trader-uuid",
        "program_id": "program-uuid",
        "trigger_type": "scheduled",
        "interval_minutes": 5,
        "symbols": ["BTC", "ETH"]
      }'
    ```
  </Step>

  <Step title="Backtest">
    Validate your strategy against historical data before going live. See [Backtesting](/trading/backtesting).
  </Step>
</Steps>
