---
name: strategy-builder
description: "Strategy builder — turn natural language trading ideas into compliant FEP v2.0 strategy packages (fep.yaml + scripts/strategy.py), with validation and L1/L2 routing."
metadata:
  openclaw:
    emoji: "🏗️"
---

# Strategy Builder (FEP v2.0)

Turn natural language trading ideas into **FEP v2.0** strategy packages. Generates `fep.yaml` + `scripts/strategy.py` (and optional `risk_manager.py`, `indicators.py`), validates against the spec.

## Prerequisites (tool profile)

This skill needs **read** (read files) and **exec** (run shell commands). Ensure the agent has the **coding** tool profile: set `tools.profile: "coding"` or `tools.alsoAllow: ["read", "exec", "write", "edit"]`.

**No subagent required.** Do strategy creation in the **current session**: use read/write/edit to create `fep.yaml` and `scripts/strategy.py`, and exec for zip/validate.

## When to Use

**USE this skill when:**

- "help me create a strategy" / "build a strategy"
- "I want to DCA into BTC every week, buy more when it dips"
- "make me a trend following strategy for ETH"
- "generate a FEP strategy package" / "生成回测策略包"
- "I have a trading idea but don't know how to code it"
- "create a strategy for sideways crypto markets"
- "turn this idea into a backtest-ready package"

## When NOT to Use

**DON'T use this skill when:**

- User wants to backtest an existing strategy — use skill_publish
- User wants to Fork/download a strategy from Hub — use skill_fork
- User wants to execute a live trade — use trading tools
- User wants portfolio analysis — use portfolio tools

## Tools

### Strategy Tools (from this plugin)

| Tool                   | Purpose                                        |
| ---------------------- | ---------------------------------------------- |
| `skill_validate`       | Validate strategy package directory (FEP v2.0) |
| `skill_publish`        | Publish strategy ZIP to Hub                    |
| `skill_publish_verify` | Query publish status and backtest report       |

### Market Data Tools (for symbol validation)

| Tool        | Purpose                              |
| ----------- | ------------------------------------ |
| `fin_price` | Check current price, validate symbol |
| `fin_kline` | Get historical K-line data           |

---

## Strategy Package Structure (FEP v2.0)

**Required:**

```
<strategy-dir>/
├── fep.yaml           # 策略配置 (必需)
├── scripts/
│   └── strategy.py    # 策略入口 (必需)
└── .created-meta.json # 本地元数据 (必需)
```

**Optional:**

```
├── scripts/
│   ├── risk_manager.py   # 风控模块
│   └── indicators.py      # 自定义指标
└── data/                 # 自定义数据
```

**Packaging:** `cd <strategy-dir> && zip -r ../<id>-<version>.zip fep.yaml scripts/`

---

## fep.yaml (FEP v2.0)

### Minimal Example

```yaml
fep: "2.0"

identity:
  id: fin-dca-basic-test
  type: strategy
  name: "DCA Basic Test Strategy"
  version: "1.0.0"
  style: dca
  visibility: public
  summary: "Simple DCA strategy for BTC"
  description: "A simple DCA strategy that buys BTC periodically"
  license: MIT
  tags: [dca, btc, crypto]
  author:
    name: "OpenFinClaw"
  changelog:
    - version: "1.0.0"
      date: "2026-01-01"
      changes: "Initial release"

parameters:
  - name: base_amount
    default: 100
    type: number
    label: "基础定投金额"
    range: { min: 10, max: 10000 }

backtest:
  symbol: "BTC/USDT"
  timeframe: 1d
  defaultPeriod:
    startDate: "2025-01-01"
    endDate: "2026-01-01"
  initialCapital: 10000

classification:
  archetype: systematic
  market: Crypto
  assetClasses: [crypto]
  frequency: daily
  riskProfile: medium
```

### Identity Fields (必填)

| Field         | Description                       |
| ------------- | --------------------------------- | ---------------- | ------------- | ----- | -------- |
| `id`          | 策略唯一标识（英文 + 连字符）     |
| `name`        | 策略显示名称                      |
| `version`     | 语义化版本号（如 `"1.0.0"`）      |
| `style`       | `trend`                           | `mean-reversion` | `momentum`    | `dca` | `hybrid` |
| `visibility`  | `public`                          | `private`        | `unlisted`    |
| `summary`     | 一句话策略描述                    |
| `description` | 详细策略说明                      |
| `license`     | `MIT`                             | `CC-BY-4.0`      | `proprietary` |
| `tags`        | 标签数组，如 `[dca, btc, crypto]` |
| `author`      | 对象，必须包含 `name` 字段        |
| `changelog`   | 变更日志数组                      |

### Backtest Fields (必填)

| Field                     | Description              |
| ------------------------- | ------------------------ |
| `symbol`                  | 交易品种（自动推断市场） |
| `defaultPeriod.startDate` | 回测开始日期             |
| `defaultPeriod.endDate`   | 回测结束日期             |
| `initialCapital`          | 初始资金                 |

### Symbol 格式

| 格式          | 市场   | 示例                     |
| ------------- | ------ | ------------------------ |
| `XXX/YYY`     | Crypto | `BTC/USDT`, `ETH/BTC`    |
| `6位数.SZ/SH` | A股    | `000001.SZ`, `600519.SH` |
| `5位数.HK`    | 港股   | `00700.HK`               |
| `1-5大写字母` | 美股   | `AAPL`, `NVDA`           |

---

## scripts/strategy.py — Mandatory Contract

### 单标的策略：compute() 函数

```python
def compute(data, context=None):
    """
    Args:
        data: pandas DataFrame, 包含 OHLCV 列
        context: dict with equity, cash, position, bar_index
    Returns:
        dict: {"action": "buy"|"sell"|"hold", ...}
    """
    close = data["close"].values
    current_price = float(close[-1])

    return {
        "action": "buy",
        "amount": 100.0,
        "price": current_price,
        "reason": f"Buy at ${current_price:.2f}",
    }
```

### 信号返回格式

| action | 必填字段      | 说明          |
| ------ | ------------- | ------------- |
| `buy`  | amount, price | 按金额买入    |
| `sell` | —             | 无参数=全仓卖 |
| `hold` | —             | 不操作        |

### Allowed Imports

`numpy`, `pandas`, `math`, `statistics`, `datetime`, `collections`, `ta`

### Forbidden

`import os/subprocess/sys/socket/shutil/ctypes/...`, `eval()`, `exec()`, `open()`, `datetime.now()`

---

## Builder Pipeline

### Step 1: Intent Collection

Extract key dimensions:

| Dimension      | Example                     |
| -------------- | --------------------------- |
| Asset          | BTC, ETH, AAPL              |
| Frequency      | daily, weekly               |
| Core idea      | buy dips, trend follow, DCA |
| Capital        | $10,000                     |
| Risk tolerance | 25% max drawdown            |
| Time horizon   | 2025-01-01 to 2026-01-01    |

### Step 2: Technical Design

Propose: strategy archetype, indicators, entry/exit logic, position sizing, risk controls. **Wait for user confirmation** before generating code.

### Step 2.5: Determine Target Directory

**Standard path:**

```
~/.openfinclaw/workspace/strategies/{YYYY-MM-DD}/{slugified-name}/
```

Example: `~/.openfinclaw/workspace/strategies/2026-03-19/btc-adaptive-dca/`

### Step 3: Code Generation

Generate:

1. **fep.yaml** — 完整的 FEP v2.0 配置
2. **scripts/strategy.py** — 实现 `compute(data)` 函数
3. **.created-meta.json** — 本地元数据

### Step 4: Self-Validation

1. **Structure:** 检查必需文件
2. **fep.yaml:** 验证必填字段
3. **strategy.py:** 检查函数签名和禁止的导入
4. 调用 `skill_validate(dirPath)` 验证

### Step 5: Delivery

Present the package and next steps:

- 本地验证通过后，可用 `skill_publish` 发布到 Hub
- 发布后用 `skill_publish_verify` 查询回测结果

---

## Strategy Templates

| Template      | style          | market |
| ------------- | -------------- | ------ |
| Simple DCA    | dca            | Crypto |
| EMA Crossover | trend          | Crypto |
| RSI Bounce    | mean-reversion | Crypto |
| Grid Trading  | hybrid         | Crypto |

---

## Response Guidelines

1. Understand the user's idea; ask questions if vague
2. Present technical design and wait for confirmation
3. Show generated package structure
4. Run validation and report pass/fail
5. End with clear next steps (publish, iterate)
