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

# Write your own strategy

> Build, validate, inspect, and test a deterministic Hizz strategy from a JSON file.

Hizz strategies are declarative JSON files assembled from approved modules.
You describe the market, signal, filters, risk, sizing, data, and execution
policy; Hizz validates the file and compiles the same rules into a backtest
graph and an agent runtime. Strategy files never contain JavaScript, Python,
callbacks, shell commands, private keys, or arbitrary network requests.

<CardGroup cols={2}>
  <Card title="Download the canonical template" icon="download" href="https://hizz.io/api/v1/ai-trading/strategy-template">
    Start with the live schema returned by Hizz.
  </Card>

  <Card title="Browse complete examples" icon="file-code" href="/ai-trading/strategy-examples">
    Read and copy breakout, mean-reversion, and trend-following JSON.
  </Card>
</CardGroup>

## What you will build

Every directional strategy has this pipeline:

```text theme={null}
market data → one trigger → zero or more filters → one risk block
            → position sizing → optional entry throttle → execution policy
```

The ports are typed. Market data emits `candles`, triggers emit a directional
`bias`, filters emit a `gate`, risk emits a `bracket`, and sizing emits a
`position`. Hizz rejects unknown modules, missing inputs, and incompatible
connections instead of silently changing the strategy.

## 1. Create a minimal file

Save the following as `my-btc-strategy.json`:

```json theme={null}
{
  "name": "My BTC 4h EMA strategy",
  "thesis": "Follow confirmed four-hour BTC trend changes with a fixed ATR bracket.",
  "frequency": "medium",
  "definition": {
    "schemaVersion": 1,
    "slug": "my-btc-4h-ema",
    "symbol": "BTC-USD",
    "trigger": {
      "kind": "ema_cross",
      "timeframe": "base",
      "fast": 20,
      "slow": 50,
      "clock": "4h"
    },
    "filters": [],
    "risk": {
      "kind": "atr_bracket",
      "timeframe": "base",
      "atrPeriod": 14,
      "atrStopMult": 2,
      "riskReward": 2,
      "maxHoldHours": 96
    },
    "sizing": { "riskFraction": 0.15, "leverage": 1 },
    "entryPolicy": { "maxEntriesPerUtcDay": 1 },
    "feeBps": 13,
    "allowLong": true,
    "allowShort": true,
    "reverseOnOpposite": false
  },
  "data": {
    "provider": "pyth",
    "frames": {
      "base": {
        "interval": "4h",
        "lookbackDays": 600,
        "ticker": "Crypto.BTC/USD"
      }
    }
  }
}
```

This file uses one base timeframe, one trigger, no optional filters, and one
risk module. It is the best shape for a first validation because every added
module creates another assumption that must be tested.

## 2. Understand the top-level fields

| Field             | Purpose                                                                    |
| ----------------- | -------------------------------------------------------------------------- |
| `name`            | Human-readable strategy name                                               |
| `thesis`          | Plain-language explanation of what the rules are trying to capture         |
| `frequency`       | UI classification: `low`, `medium`, `high`, or `ultra`                     |
| `definition`      | Signal, filters, risk, sizing, directions, and generic per-fill cost       |
| `data`            | Historical provider and the `base`, `mid`, or `high` candle frames         |
| `executionPolicy` | Optional maker/taker behavior, retries, deadlines, and role-specific costs |

`schemaVersion` must currently be `1`. Use a lowercase, hyphenated `slug` and
keep it stable after a strategy is published so links and backtest records do
not change identity.

## 3. Choose a trigger

Exactly one trigger is required.

| `kind`                      | Use it for                            | Important fields                   |
| --------------------------- | ------------------------------------- | ---------------------------------- |
| `ema_cross`                 | Trend changes                         | `fast`, `slow`                     |
| `trend_continuation`        | Staying with an established trend     | `fast`, `slow`, `thresholdBps`     |
| `donchian_breakout`         | Range breakouts                       | `lookback`, `thresholdBps`         |
| `rsi_reversion`             | Oversold/overbought mean reversion    | `period`, `oversold`, `overbought` |
| `sma_deviation`             | Distance-from-mean reversion          | `window`, `thresholdBps`           |
| `structure_breakout_retest` | Breakout followed by a bounded retest | swing, retest, and volume fields   |

For every fast/slow pair, `fast` must be lower than `slow`. `thresholdBps` is
measured in basis points: `100bps = 1%`.

## 4. Add filters only when they have a job

Filters are combined as gates. An entry is allowed only when the trigger and
all configured filters agree.

```json theme={null}
"filters": [
  {
    "kind": "ema_trend",
    "timeframe": "high",
    "fast": 20,
    "slow": 50,
    "clock": "1d"
  },
  {
    "kind": "volume_surge",
    "timeframe": "base",
    "window": 20,
    "multiplier": 1.15,
    "clock": "4h"
  }
]
```

Available filter kinds are `ema_trend`, `macd_rsi`, `atr_expansion`,
`volume_surge`, and `bollinger_middle_break`. If a filter references `high`,
the matching `data.frames.high` frame must exist.

## 5. Define exits and sizing

Choose one risk block:

| `kind`          | Exit behavior                                               |
| --------------- | ----------------------------------------------------------- |
| `atr_bracket`   | ATR stop, fixed configured target, and maximum holding time |
| `trailing_stop` | Fixed-bps hard stop plus a ratcheting bps trail             |
| `atr_trailing`  | ATR-scaled initial stop plus an ATR-scaled trail            |

<Warning>
  `sizing.riskFraction` is the fraction of strategy capital allocated as
  margin. It is not the percentage of the account guaranteed to be lost at
  the stop. Leverage multiplies notional exposure and fee dollars.
</Warning>

For `atr_bracket`, `riskReward` is the configured initial target distance
divided by the initial stop distance. It is not the realized average-win to
average-loss ratio. Timeouts, reversals, gaps, fees, and unfilled maker orders
can make the realized payoff very different.

## 6. Select valid market data

The execution symbol and historical ticker use different namespaces:

| Purpose                   | Example          |
| ------------------------- | ---------------- |
| Strike strategy symbol    | `BTC-USD`        |
| Pyth historical ticker    | `Crypto.BTC/USD` |
| Binance historical ticker | `BTCUSDT`        |

Do not turn an arbitrary equity ticker into `Crypto.TICKER/USD`. Hizz only
backtests explicit market/provider mappings. Current mapped crypto examples
include ADA, BTC, ETH, HYPE, NEAR, NIGHT, SOL, XRP, and ZEC. The market picker
and API return the available provider coverage for each Strike symbol.

Supported intervals:

* Pyth: `1m`, `2m`, `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `6h`, `12h`, `1d`, `1w`, `1M`
* Binance: `1m`, `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `1d`
* Strike: `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `6h`, `8h`, `12h`, `1d`, `3d`, `1w`, `1M`

## 7. Add maker/taker execution when needed

Without an `executionPolicy`, Hizz validates the strategy with conservative
taker defaults. A post-only strategy can declare passive entries and routine
exits while keeping hard stops as taker orders:

```json theme={null}
"executionPolicy": {
  "schemaVersion": 1,
  "entryMode": "maker",
  "routineExitMode": "maker",
  "emergencyExitMode": "taker",
  "emergencyExitReasons": ["stop"],
  "maker": {
    "ttlSeconds": 180,
    "offsetBps": 0,
    "entryMaxAttempts": 2,
    "routineExitMaxAttempts": 2,
    "routineExitFallbackSeconds": 420
  },
  "costs": {
    "hizzFeeBps": 5,
    "strikeMakerFeeBps": 0,
    "strikeTakerFeeBps": 8
  }
}
```

Maker means post-only intent, not guaranteed execution. A historical candle
cannot reproduce queue position, cancellation latency, or every missed fill.
Keep current venue fees in your own assumptions instead of copying an old
example indefinitely.

## 8. Validate the file

```bash theme={null}
curl -X POST https://hizz.io/api/v1/ai-trading/strategies/validate \
  -H "Content-Type: application/json" \
  --data-binary @my-btc-strategy.json
```

A successful response contains:

```json theme={null}
{
  "valid": true,
  "strategy": { "name": "...", "definition": {}, "data": {} },
  "graph": { "nodes": [], "edges": [] }
}
```

If validation fails, fix every item in `issues`. Do not remove an unknown
module and assume the remaining strategy means the same thing.

## 9. Inspect the compiled graph

Open the [visual module workbench](https://hizz.io/ai-trading/modules) and
compare your composition with a published strategy. Every cable should connect
matching input/output data types. Hover a node for its responsibility; select
it to inspect parameters, ports, and immediate upstream/downstream modules.

## 10. Backtest and review

The anonymous v1 API runs bounded simulations for published slugs. Private
strategies saved under **My Strategy** can be backtested in the authenticated
Hizz application. Review several non-overlapping windows and stress the fee
assumption instead of selecting the single best period.

Before any live use, check:

* enough trades to interpret win rate and payoff
* maximum drawdown and mark-to-market equity, including open-position PnL
* realized average win/loss, not only configured `riskReward`
* maker/taker costs, missed-fill risk, leverage, and minimum order size
* long-only, short-only, and both-direction behavior separately
* paper results after the historical test window

<Warning>
  Validation proves that a file matches the runtime contract. A backtest proves
  only what the rules did on the selected historical data and assumptions.
  Neither is evidence that a strategy is safe or will be profitable.
</Warning>

## Use Codex or another AI to help

Give the agent the live OpenAPI document and a bounded task:

```text theme={null}
Read https://hizz.io/api/v1/ai-trading/openapi.json and the strategy template.
Create a BTC-USD 4h trend strategy using only approved modules. Use at most one
filter, 1x leverage, a 15% margin allocation, and explicit fees. Validate the
JSON, explain every validation issue, and do not deploy or place live orders.
```

An AI should return a file for review, not authority to move funds. Saving,
deploying, and arming an agent remain authenticated human actions.
