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

# Strategies

> Create, backtest, and optimize trading strategies

## Overview

Strategies define the logic for automated trading. They combine technical indicators with entry/exit rules to generate buy and sell signals.

```mermaid theme={null}
graph LR
    Create[Create Strategy] --> Template[Apply Template]
    Template --> Indicators[Add Indicators]
    Indicators --> Backtest[Backtest]
    Backtest --> Hyperopt[Optimize]
    Hyperopt --> Deploy[Deploy to Trader]
```

## Creating a Strategy

Create a strategy with base parameters:

```bash theme={null}
curl -X POST https://api.cryptorobot.ai/strategies \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "BTC Momentum",
    "interval": "1m",
    "stoploss": -0.036,
    "exit_profit_only": true,
    "exit_profit_offset": 10,
    "exit_sell_signal": true
  }'
```

```json Response theme={null}
{
  "_id": "684b2f...",
  "name": "BTC Momentum",
  "interval": "1m",
  "stoploss": -0.036,
  "exit_profit_only": true,
  "exit_profit_offset": 10,
  "exit_sell_signal": true,
  "configured": false,
  "createdAt": "2024-01-15T10:00:00.000Z",
  "updatedAt": "2024-01-15T10:00:00.000Z"
}
```

## Templates

Templates provide pre-configured strategy types (e.g., `BbandRsi`, `MacdCrossover`). When you assign a `templateId`, the template's values propagate to the strategy on the **first** patch only.

### List Templates

```bash theme={null}
curl https://api.cryptorobot.ai/strategies/templates \
  -H "Authorization: Bearer $TOKEN"
```

```json Response theme={null}
{
  "data": [
    {
      "_id": "tmpl-1",
      "name": "Bollinger RSI",
      "type": "BbandRsi",
      "description": "Bollinger Band breakout with RSI confirmation",
      "values": {
        "stoploss": -0.077,
        "interval": "1m",
        "timeinforce": "GTC",
        "exit_profit_only": false,
        "exit_profit_offset": 20,
        "exit_sell_signal": false
      }
    }
  ]
}
```

### Apply Template with Indicators

Patching with `templateId` + `indicators` generates the strategy file and sets `configured: true`:

```bash theme={null}
curl -X PATCH https://api.cryptorobot.ai/strategies/684b2f... \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "templateId": "tmpl-1",
    "indicators": [
      {
        "_id": "ta.rsi",
        "alias": "rsi",
        "name": "RSI",
        "group": "Momentum Indicators",
        "description": "Relative Strength Index",
        "optInputs": [
          { "name": "optInTimePeriod", "displayName": "Time Period", "defaultValue": 14, "type": "integer_range" }
        ]
      },
      {
        "_id": "qtpylib.bb_upperband",
        "name": "Bollinger Band (High)",
        "group": "Bollinger Bands",
        "alias": "bb_upperband",
        "optInputs": []
      },
      {
        "_id": "qtpylib.bb_lowerband",
        "name": "Bollinger Band (Lower)",
        "group": "Bollinger Bands",
        "alias": "bb_lowerband",
        "optInputs": []
      }
    ]
  }'
```

```json Response theme={null}
{
  "_id": "684b2f...",
  "name": "BTC Momentum",
  "interval": "1m",
  "stoploss": -0.077,
  "configured": true,
  "templateId": "tmpl-1",
  "file": { "id": "strategies/684b2f...py" },
  "strategies/indicators": [
    { "_id": "ta.rsi", "name": "RSI" },
    { "_id": "qtpylib.bb_upperband", "name": "Bollinger Band (High)" },
    { "_id": "qtpylib.bb_lowerband", "name": "Bollinger Band (Lower)" }
  ],
  "strategies/templates": {
    "_id": "tmpl-1",
    "name": "Bollinger RSI",
    "type": "BbandRsi"
  }
}
```

<Note>
  Once `configured: true`, subsequent patches **will not** re-apply template values. You can freely tune `interval`, `stoploss`, and other fields without overwrite.
</Note>

## Updating Parameters

After initial configuration, tune strategy parameters independently:

```bash theme={null}
curl -X PATCH https://api.cryptorobot.ai/strategies/684b2f... \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "interval": "30m",
    "stoploss": -0.001,
    "exit_profit_offset": 12
  }'
```

## Protections

Protections safeguard against rapid losses. Add them via patch:

```bash theme={null}
curl -X PATCH https://api.cryptorobot.ai/strategies/684b2f... \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "protections": [
      { "enabled": true, "type": "coolDownPeriod", "method": "CooldownPeriod", "stop_duration_candles": 2 },
      { "enabled": true, "type": "maxDrawdown", "method": "MaxDrawdown", "stop_duration_candles": 4, "lookback_period_candles": 48, "trade_limit": 20, "max_allowed_drawdown": 0.2 },
      { "enabled": true, "type": "stoplossGuard", "method": "StoplossGuard", "stop_duration_candles": 2, "lookback_period_candles": 24, "trade_limit": 4, "only_per_pair": false },
      { "enabled": true, "type": "lowProfitPairs", "method": "LowProfitPairs", "stop_duration_candles": 60, "lookback_period_candles": 6, "trade_limit": 2, "required_profit": "2" }
    ]
  }'
```

| Protection       | Description                                             |
| ---------------- | ------------------------------------------------------- |
| `CooldownPeriod` | Wait N candles after a trade before opening new ones    |
| `MaxDrawdown`    | Pause trading if drawdown exceeds threshold             |
| `StoplossGuard`  | Pause if too many stoplosses trigger in lookback period |
| `LowProfitPairs` | Stop trading pairs with low profit in recent candles    |

## Backtesting

Test strategy performance against historical data. Requires data download first.

### Download Data

```bash theme={null}
curl -X POST https://api.cryptorobot.ai/exchanges/download \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "exchangeId": "683a1f...",
    "overrides": {
      "timerange": "20240101-",
      "timeframes": ["5m"]
    }
  }'
```

### Run Backtest

```bash theme={null}
curl -X POST https://api.cryptorobot.ai/strategies/backtest \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "strategyId": "684b2f...",
    "traderId": "685c3a...",
    "exchangeId": "683a1f...",
    "overrides": {
      "max_open_trades": 10,
      "dry_run_wallet": 10000
    },
    "options": {
      "eps": true,
      "protections": true
    },
    "start": "20240101",
    "end": "20240115"
  }'
```

```json Response theme={null}
{
  "_id": "bt-789",
  "strategyId": "684b2f...",
  "traderId": "685c3a...",
  "exchangeId": "683a1f...",
  "status": "SUCCEEDED",
  "results": {
    "total_trades": 87,
    "trade_count_long": 52,
    "trade_count_short": 35,
    "profit_total": 0.452,
    "profit_mean": 0.0052,
    "profit_median": 0.003,
    "total_volume": 150000,
    "avg_stake_amount": 1724,
    "best_pair": "ETH/USDT",
    "worst_pair": "DOGE/USDT",
    "results_per_pair": [...],
    "exit_reason_summary": [...],
    "locks": [...]
  },
  "took": 12500
}
```

## Hyperparameter Optimization

Find optimal strategy parameters automatically:

```bash theme={null}
curl -X POST https://api.cryptorobot.ai/strategies/hyperopt \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "strategyId": "684b2f...",
    "traderId": "685c3a...",
    "exchangeId": "683a1f...",
    "function": "OnlyProfitHyperOptLoss",
    "epochs": 500,
    "overrides": {
      "max_open_trades": 10,
      "dry_run_wallet": 10000
    },
    "options": {
      "eps": true,
      "protections": true
    },
    "days": 20
  }'
```

## AI Generation

Generate a strategy from a natural language prompt:

```bash theme={null}
curl -X POST https://api.cryptorobot.ai/strategies/generate \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Generate a momentum and mean-reversion strategy with 4+ distinct indicators",
    "context": "freqtrade strategy",
    "auto": {
      "hyperopt": {
        "enabled": true,
        "function": "OnlyProfitHyperOptLoss",
        "epochs": 500,
        "overrides": { "max_open_trades": 10, "dry_run_wallet": 10000 },
        "options": { "eps": true, "protections": true },
        "days": 20,
        "exchangeId": "683a1f...",
        "traderId": "685c3a..."
      }
    }
  }'
```

```json Response theme={null}
{
  "_id": "gen-101",
  "prompt": "Generate a momentum and mean-reversion strategy with 4+ distinct indicators",
  "context": "freqtrade strategy",
  "status": "SUCCEEDED",
  "templateId": "tmpl-gen-1",
  "strategyId": "684c4b..."
}
```

## Key Fields

| Field                | Type    | Description                                                  |
| -------------------- | ------- | ------------------------------------------------------------ |
| `name`               | string  | Strategy display name                                        |
| `interval`           | string  | Candle timeframe: `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d` |
| `stoploss`           | number  | Stop-loss as negative decimal (e.g. `-0.036` = -3.6%)        |
| `exit_profit_only`   | boolean | Only exit on profit                                          |
| `exit_profit_offset` | number  | Minimum profit offset before allowing exit                   |
| `exit_sell_signal`   | boolean | Allow exit on sell signal                                    |
| `timeinforce`        | string  | Order time-in-force (e.g. `GTC`)                             |
| `templateId`         | string  | Applied template ID                                          |
| `configured`         | boolean | Whether strategy file has been generated                     |
| `indicators`         | array   | Technical indicators attached to the strategy                |
| `protections`        | array   | Risk management protections                                  |
| `file`               | object  | Generated strategy file reference                            |
