# Stratex API — Agent Skill (How to Use)

This document describes how to use the Stratex API for **backtesting** and **setup-trigger alerts**. It is a user guide for AI agents; it does not expose internal implementation details.

**See also:** [API Reference](/docs/api-reference.md) (full endpoints and errors) · [Quickstart](/docs/quickstart.md) (sign up → key → backtest → webhook).

---

## Purpose

- **Backtesting:** Run historical backtests for a saved setup and retrieve full trade lists, summary stats, and optionally a summary chart image.
- **Alerts:** Create setups that are evaluated on bar close; receive triggers via **webhook** (primary) or **polling** (fallback).

---

## Authentication

Use an **API key** on every request.

- **Header (preferred):** `Authorization: Bearer <your-api-key>`
- **Alternative:** `X-Api-Key: <your-api-key>`

Keys are created in the account dashboard after signup. Never expose the key in client-side or public code.

---

## Workflow

1. **Discover markets** (GET /api/v1/markets, **auth required**): list ready backtest markets with human labels, date ranges, and timeframes from the live catalog. Count = whatever data is ingested — not a fixed placeholder.
2. **Create a setup** (POST /api/v1/service/setups) with structured parameters. Response includes `setupId` and a plain-English `description`.
3. **Backtest:** POST /api/v1/backtest/run with `setupId` and a window. Recommended: `endDate` + `lookbackBars` (the server resolves the start date on the setup timeframe and caps to available data with a `warnings[]` note instead of failing); `startDate` + `endDate` also works. Optionally call GET /api/v1/backtest/estimate first to preview bar cost vs allowance. Response includes `runId`, full trade list, summary, optional `warnings[]`, and optionally `chartImageBase64`.
4. **Alerts:** For live triggers, set `webhookUrl` (and optionally `webhookSecret`) on the setup when creating it. The service will POST to that URL when the setup fires. If you do not set a webhook, use **polling:** GET /api/v1/alerts/pending (with optional `?since=<iso8601>`). Each call returns pending alerts and marks them as delivered for polling.
5. **Fetch backtest later:** GET /api/v1/backtest/list or GET /api/v1/backtest/:id using the run `id`.

---

## Endpoints

| Method | Path | Description |
|--------|------|-------------|
| GET    | /api/v1/markets | Discover ready backtest markets (labels, ranges, timeframes). **Auth required.** |
| POST   | /api/v1/service/setups | Create setup (structured params). Optional: webhookUrl, webhookSecret. |
| GET    | /api/v1/service/setups | List your setups. |
| GET    | /api/v1/service/setups/:id | Get one setup. |
| PATCH  | /api/v1/service/setups/:id | Update **webhookUrl** and/or **webhookSecret** only. For any other field, create a new setup. |
| DELETE | /api/v1/service/setups/:id | Delete (soft) a setup. |
| POST   | /api/v1/backtest/run | Run backtest (body: setupId, symbol, timeframe, and either endDate+lookbackBars or startDate+endDate). Optional: includeChartImage. |
| GET    | /api/v1/backtest/estimate | Preview resolved range + bar cost (query: market, timeframe, endDate+lookbackBars or startDate+endDate). |
| GET    | /api/v1/backtest/list | List your backtest runs. |
| GET    | /api/v1/backtest/:id | Get one backtest run (full trades, summary). |
| GET    | /api/v1/alerts/pending | Poll pending triggers. Optional query: ?since=<iso8601>. |
| GET    | /api/v1/usage | Current billing period usage (bars processed, setup evaluations by timeframe). Requires API key. |
| GET    | /api/v1/agent-info | Discovery: capabilities, pricing summary, doc URLs, `marketsUrl`. No auth (markets **data** still requires auth). |

---

## Setup creation (structured schema only)

You send a **structured** JSON body. The server validates and stores the setup; internal strategy representation is not exposed.

**Example request (minimal):**

```json
{
  "name": "My GOLD BUY setup",
  "symbol": "GOLD",
  "direction": "BUY",
  "timeframe": "5m",
  "webhookUrl": "https://your-server.com/webhooks/stratex",
  "webhookSecret": "optional-secret-for-signature-verification"
}
```

Optional: `entry` / `exit` (or `entryExpression` / `exitExpression`), `briefDescription`, `description`. Entry/exit are condition definitions; the server translates them internally. Invalid or unsupported values result in a generic validation error (no internal details).

**Example response:**

```json
{
  "success": true,
  "setupId": "507f1f77bcf86cd799439011",
  "description": "BUY setup on GOLD 5m: My GOLD BUY setup. Entry and exit conditions as configured.",
  "data": {
    "setupId": "507f1f77bcf86cd799439011",
    "name": "My GOLD BUY setup",
    "symbol": "GOLD",
    "direction": "BUY",
    "timeframe": "5m",
    "description": "...",
    "status": "live",
    "webhookUrl": "https://your-server.com/webhooks/stratex"
  }
}
```

---

## Backtest response format

- **Full trade list:** Array of executed trades (entry/exit, P&L, timestamps, etc.).
- **Summary:** Aggregate stats (win rate, total return, max drawdown).
- **Agent-facing fields:** `summary`, `suggested_user_message` for explaining results to the end user.
- **Optional chart:** If you sent `includeChartImage: true`, the response includes a base64-encoded PNG (e.g. win/loss summary chart) in a field such as `chartImageBase64`.

---

## Webhook vs polling

- **Webhook (primary):** Set `webhookUrl` on create (POST) or change it later with **PATCH** `/api/v1/service/setups/:id` (webhook fields only). When the setup triggers, the service POSTs a minimal JSON payload to that URL. You may set `webhookSecret`; the service then sends `X-Webhook-Signature: sha256=<hex>` (HMAC-SHA256 of the body) so you can verify the request. Retries use exponential backoff. On success, the trigger is marked delivered and will not appear in polling.
- **Polling (fallback):** If no webhook is set or delivery fails, call GET /api/v1/alerts/pending. You can use `?since=<iso8601>` to get triggers after a time. The same trigger is not returned again after a successful poll (marked delivered).

**Webhook payload (minimal):**

```json
{
  "triggered": true,
  "setupId": "...",
  "symbol": "GOLD",
  "timeframe": "5m",
  "timestamp": "2025-02-28T12:00:00.000Z",
  "triggerType": "SETUP_ENTRY_TRIGGER"
}
```

---

## Error handling

- **401 Unauthorized:** Missing or invalid API key. Check header and key value.
- **403 Forbidden:** Authenticated but not allowed (e.g. over limit, no subscription). Body may include `reason`, `currentCount`, `max`, etc.
- **400 Bad Request:** Invalid body or query (e.g. missing required field, invalid date). Message is generic.
- **404 Not Found:** Resource (setup, run) not found or not owned by you.
- **429 Too Many Requests:** Rate limited; retry after the indicated delay.
- **Setup validation failure:** If setup creation fails validation, you receive a generic error message (e.g. "name is required", "direction must be BUY or SELL"). Internal validation details are not exposed.

---

## Quick reference

- **Discovery (no auth):** GET /api/v1/agent-info  
- **Create setup:** POST /api/v1/service/setups (structured body; optional webhookUrl, webhookSecret)  
- **Webhook URL/secret:** PATCH /api/v1/service/setups/:id with JSON `{ "webhookUrl": "...", "webhookSecret": "..." }` (omit either key to leave unchanged; empty string or null clears).  
- **Run backtest:** POST /api/v1/backtest/run (setupId, etc.; optional includeChartImage)  
- **Get runs:** GET /api/v1/backtest/list, GET /api/v1/backtest/:id  
- **Alerts:** Webhook (set on setup) or GET /api/v1/alerts/pending?since=...  
- **Usage:** GET /api/v1/usage (API key required)
