{"id":51079067,"url":"https://github.com/maxgfr/ai-strategy-backtester","last_synced_at":"2026-06-23T16:33:10.591Z","repository":{"id":341384300,"uuid":"1169929637","full_name":"maxgfr/ai-strategy-backtester","owner":"maxgfr","description":"Crypto strategy backtester with AI generation: describe a trading strategy in plain English, get a JSON strategy file, and backtest it across 50+ technical indicators, multiple timeframes, and date ranges. Generates HTML reports with Sharpe ratio, win rate, and drawdown metrics.","archived":false,"fork":false,"pushed_at":"2026-03-09T09:58:09.000Z","size":545,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-09T14:24:04.835Z","etag":null,"topics":["ai-generated","backtesting","binance","candlestick","cryptocurrency","html-report","json-strategy","macd","nodejs","rsi","sharpe-ratio","strategy","technical-analysis","trading-bot","typescript","worker-pool"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/maxgfr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-01T12:53:06.000Z","updated_at":"2026-03-09T09:58:12.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/maxgfr/ai-strategy-backtester","commit_stats":null,"previous_names":["maxgfr/ai-strategy-backtester"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/maxgfr/ai-strategy-backtester","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxgfr%2Fai-strategy-backtester","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxgfr%2Fai-strategy-backtester/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxgfr%2Fai-strategy-backtester/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxgfr%2Fai-strategy-backtester/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/maxgfr","download_url":"https://codeload.github.com/maxgfr/ai-strategy-backtester/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxgfr%2Fai-strategy-backtester/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34698696,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-23T02:00:07.161Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-generated","backtesting","binance","candlestick","cryptocurrency","html-report","json-strategy","macd","nodejs","rsi","sharpe-ratio","strategy","technical-analysis","trading-bot","typescript","worker-pool"],"created_at":"2026-06-23T16:33:10.484Z","updated_at":"2026-06-23T16:33:10.578Z","avatar_url":"https://github.com/maxgfr.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AI Strategy Backtester\n\nCrypto strategy backtester using Binance historical data. Define trading strategies as declarative JSON, backtest them across multiple timeframes and date ranges, and compare results in an HTML report. AI can generate strategies from natural language.\n\n## Features\n\n- **51 technical indicators** — RSI, MACD, Supertrend, Bollinger Bands, Ichimoku, KDJ, StochRSI, HMA, Choppiness Index, Ultimate Oscillator, and more\n- **Declarative JSON strategies** — no code required, compose indicators with buy/sell/short/cover conditions\n- **Timeframe auto-scaling** — indicator periods automatically adapt based on running timeframe (4h reference)\n- **AI strategy generation** — describe a strategy in natural language, get a validated JSON file\n- **Per-strategy configuration** — each strategy has its own timeframes, stop loss, trailing stop, circuit breaker, and risk-per-trade settings\n- **Shorting \u0026 leverage** — strategies can short sell with configurable leverage (1x-125x)\n- **Maker/taker fee split** — separate fees for entries (maker/limit) and exits (taker/market)\n- **Circuit breaker** — stop opening new positions when drawdown exceeds configurable threshold\n- **Risk-per-trade position sizing** — fractional capital allocation based on risk% / stop_loss%, with reserve capital management\n- **Funding fees \u0026 liquidation** — realistic perpetual futures simulation with 8h funding, funding-eroded margin for liquidation detection, intra-candle liquidation\n- **Walk-forward validation** — automatic train/test date range splitting to detect overfitting\n- **Data validation** — NaN/non-positive price filtering, OHLC consistency auto-fix, duplicate timestamp removal on both fetch and cache read\n- **Buy \u0026 Hold benchmark** — alpha calculation (strategy return vs B\u0026H), drawdown duration analysis, MAE/MFE tracking\n- **Advanced metrics** — annualized Sharpe/Sortino/Calmar, Recovery Factor, Expectancy, consecutive W/L, long/short breakdown, MAE/MFE ratio\n- **Sensitivity analysis** — estimated P\u0026L impact if fees or slippage were doubled\n- **Statistical analysis** — t-test significance, percentage-based Monte Carlo simulation (1000 iterations) with ruin probability\n- **Parallel execution** — worker pool dispatches simulations across all CPU cores\n- **HTML report** — ranked results with category comparison (Long-Only vs Shorting), filter buttons, Calmar column, detailed modal with funding/MAE-MFE/Monte Carlo\n\n## Requirements\n\n- Node.js \u003e= 24\n- pnpm \u003e= 10\n\n## Quick Start\n\n```bash\npnpm install\n\n# Full matrix backtest (all strategies x timeframes x symbols)\npnpm backtest\n\n# Full matrix + open HTML report in browser\npnpm backtest:report\n\n# Targeted backtest\npnpm backtest ETHUSDT 4h 2022-01-01 2026-02-01 rsi-macd-trend-ride\n\n# Targeted + open report\npnpm backtest --report ETHUSDT 4h 2022-01-01 2026-02-01 rsi-macd-trend-ride\n```\n\n## Strategies\n\nAll strategies live as `.json` files in `strategies/`. They are auto-discovered on each run. No prefix conventions — all names are plain kebab-case.\n\n### Available Strategies (24)\n\n| Strategy | Description |\n|----------|-------------|\n| `rsi-macd-trend-ride` | RSI oversold + MACD, RSI \u003e 80 exit (best performer) |\n| `turtle` | 200-period Donchian breakout + trailing stop |\n| `supertrend-pullback-momentum` | Supertrend dip buyer + RSI pullback |\n| `supertrend` | ATR-based trend following |\n| `confluence` | Multi-indicator score mode (PMAX gate + 9 scored conditions, threshold 4) |\n| `pmax` | EMA + ATR-based Supertrend |\n| `breakout-volume` | Donchian breakout + ADX + volume |\n| `stochrsi-trend-filter` | StochRSI K/D crossover + Supertrend + ADX + MACD |\n| `kdj-extreme-recovery` | KDJ J-line recovery in uptrend |\n| `bollinger-squeeze` | BB squeeze breakout + MACD + ADX |\n| `ichimoku-cloud` | Ichimoku cloud trend following |\n| `fast-supertrend` | Fast Supertrend + RSI + ADX |\n| `vwap-momentum` | VWAP-gated score mode |\n| `cci-williams-momentum` | CCI zero-cross + Williams %R + Supertrend |\n| `hull-chop-momentum` | HMA trend + Choppiness filter + UO oversold dip + ADX |\n| `vwma-chop-breakout` | VWMA/SMA divergence + Choppiness breakout |\n| `coppock-bottom` | Coppock Curve zero-cross + McGinley Dynamic bottom picker |\n| `aroon-trend-rider` | Aroon trend detection + RSI pullback + ADX filter |\n| `keltner-breakout` | Keltner channel breakout + MACD + ADX |\n| `psar-momentum` | Parabolic SAR + ROC momentum + RSI filter |\n| `elder-impulse` | Elder Ray bull/bear power + EMA trend + ADX |\n| `dpo-rsi-pullback` | DPO cycle detection + RSI pullback + close \u003e Supertrend |\n| `adaptive-momentum-reversal` | Asymmetric long/short: RSI+MACD bottoms + Supertrend+MACD+ADX shorts (2x leverage) |\n| `trend-momentum-rider` | Supertrend + MACD momentum filter, patient Supertrend-only exit (top performer) |\n\n### Creating a Strategy\n\nWrite a JSON file in `strategies/`:\n\n```json\n{\n  \"name\": \"my-strategy\",\n  \"description\": \"Buy when RSI oversold and MACD positive\",\n  \"leverage\": 2,\n  \"indicators\": {\n    \"rsi\": { \"period\": 14 },\n    \"macd\": { \"fast\": 12, \"slow\": 26, \"signal\": 9 }\n  },\n  \"buy\": {\n    \"mode\": \"all\",\n    \"conditions\": [[\"rsi\", \"\u003c\", 30], [\"macd.histogram\", \"\u003e\", 0]]\n  },\n  \"sell\": {\n    \"mode\": \"any\",\n    \"conditions\": [[\"rsi\", \"\u003e\", 70]]\n  },\n  \"short\": {\n    \"mode\": \"all\",\n    \"conditions\": [[\"rsi\", \"\u003e\", 75], [\"macd.histogram\", \"\u003c\", 0]]\n  },\n  \"cover\": {\n    \"mode\": \"any\",\n    \"conditions\": [[\"rsi\", \"\u003c\", 35]]\n  }\n}\n```\n\n**Signal modes:** `all` (AND), `any` (OR), `score` (count-based with threshold + optional required conditions).\n\n**Shorting:** Optional `short` + `cover` blocks (both required if either present). **Leverage:** Optional `leverage` field (1-125, default 1).\n\n**Auto-scaling:** Tune indicator periods for 4h (reference timeframe). The engine automatically scales periods for other timeframes using sqrt dampening.\n\nSee [`STRATEGY_PROMPT.md`](STRATEGY_PROMPT.md) for the full specification: JSON schema, all 51 indicators with parameters, value reference syntax, anti-patterns, and examples.\n\n### AI Generation\n\nSet `generation.enabled` to `true` in `config.json` and add your API key to `.env`:\n\n```\nGENERATION_API_KEY=sk-...\n```\n\n```bash\npnpm generate-strategy \"Buy when RSI is oversold and volume spikes above average\"\n```\n\n## Configuration\n\nAll settings in `config.json` with a flat format. Validated at startup via Zod.\n\n### Top-Level Fields\n\n| Field | Required | Default | Description |\n|---|---|---|---|\n| `fees` | Yes | — | Trading fees (e.g., `0.0026` = 0.26%). Fallback when `makerFee`/`takerFee` not set |\n| `makerFee` | No | = `fees` | Maker fee for entries (buy, short). Overrides `fees` for limit orders |\n| `takerFee` | No | = `fees` | Taker fee for exits (sell, cover, stops). Overrides `fees` for market orders |\n| `fundingRate` | No | `0` | Perpetual futures funding rate, applied every 8h during open positions. `0.0001` = 0.01% |\n| `slippage` | No | `0` | Slippage per trade. Buy/cover at `price*(1+slippage)`, sell/short at `price*(1-slippage)`. `0.001` = 0.1% |\n| `initialCapital` | Yes | — | Starting capital for each simulation run |\n| `symbols` | Yes | — | Trading pairs array (e.g., `[\"ETHUSDT\", \"SOLUSDT\"]`). Matrix across all strategies |\n| `dates` | Yes | — | Date ranges: `[{\"start\": \"YYYY-MM-DD\", \"end\": \"YYYY-MM-DD\"}]`. Special value `\"now\"` = current date |\n\n**Valid timeframes:** `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `6h`, `8h`, `12h`, `1d`, `3d`, `1w`\n\n### Per-Strategy Configuration (`strategies.\u003cname\u003e`)\n\n| Field | Required | Default | Description |\n|---|---|---|---|\n| `timeframes` | Yes | — | Timeframes to test (e.g., `[\"4h\", \"6h\"]`) |\n| `stop_loss_pct` | No | _(none)_ | Stop loss: exit when price moves against entry by this %. `0.08` = 8%. Checked intra-candle |\n| `trailing_stop_pct` | No | _(none)_ | Trailing stop: exit when price retraces from peak/trough by this %. `0.12` = 12% retrace |\n| `max_drawdown_pct` | No | _(none)_ | Circuit breaker: permanently stop opening new positions when drawdown exceeds threshold. `0.25` = 25%. Existing positions are NOT closed |\n| `risk_per_trade` | No | _(none)_ | Fractional position sizing: invest `risk_per_trade / stop_loss_pct` of capital per trade. Remainder in reserve. **Requires `stop_loss_pct`**. `0.02` with SL=8% → 25% invested, 75% reserved |\n\n**Parameter interactions:**\n- `stop_loss_pct` + `trailing_stop_pct` can coexist — whichever triggers first exits\n- `risk_per_trade` has no effect without `stop_loss_pct`\n- `max_drawdown_pct` is cumulative — once tripped, no more trades even if equity recovers\n- Stops are checked before strategy signals each candle and execute with slippage + taker fee\n\n### Other Sections\n\n| Section | Fields | Description |\n|---|---|---|\n| `defaults` | `timeframes`, `stop_loss_pct`, `trailing_stop_pct`, `max_drawdown_pct`, `risk_per_trade` | Optional defaults for all strategies. Per-strategy values override these defaults. Strategies can use `{}` to inherit all defaults |\n| `walkForward` | `enabled` (bool), `trainRatio` (0.1–0.9) | Train/test date split. Only test period results are kept |\n| `generation` | `enabled`, `model`, `baseUrl`, `maxTokens`, `temperature` (0–2) | AI strategy generation via `pnpm generate-strategy` |\n\n### Complete Example\n\n```json\n{\n  \"fees\": 0.0025,\n  \"makerFee\": 0.001,\n  \"takerFee\": 0.003,\n  \"fundingRate\": 0.0001,\n  \"slippage\": 0.001,\n  \"initialCapital\": 10000,\n  \"symbols\": [\"ETHUSDT\", \"SOLUSDT\"],\n  \"dates\": [\n    { \"start\": \"2022-01-01\", \"end\": \"2024-06-01\" },\n    { \"start\": \"2024-06-01\", \"end\": \"now\" }\n  ],\n  \"defaults\": {\n    \"timeframes\": [\"6h\", \"12h\"],\n    \"stop_loss_pct\": 0.1,\n    \"trailing_stop_pct\": 0.15,\n    \"max_drawdown_pct\": 0.3,\n    \"risk_per_trade\": 0.02\n  },\n  \"strategies\": {\n    \"trend-momentum-rider\": {},\n    \"supertrend\": {},\n    \"adaptive-momentum-reversal\": {\n      \"timeframes\": [\"4h\", \"6h\"]\n    }\n  },\n  \"walkForward\": { \"enabled\": true, \"trainRatio\": 0.7 },\n  \"generation\": {\n    \"enabled\": false,\n    \"model\": \"mistral-small-latest\",\n    \"baseUrl\": \"https://api.mistral.ai/v1\",\n    \"maxTokens\": 4096,\n    \"temperature\": 0.7\n  }\n}\n```\n\n## Reports\n\n```bash\n# Regenerate HTML report from existing db/ results\npnpm report\n```\n\nThe report includes:\n- Best strategy cards (Long-Only vs Shorting comparison, with Calmar Ratio + long/short breakdown)\n- Filter buttons to toggle by category (All / Long-Only / Shorting)\n- Full rankings table with Strategy Return, Buy \u0026 Hold, Alpha, Sharpe, Sortino, Calmar, significance\n- Modal with Calmar, DD Duration, MAE/MFE ratio, consecutive W/L, long/short trades, funding paid, Monte Carlo range, ruin probability, sensitivity analysis\n- Equity curve overlay (gold line) in chart modal with SHORT entry markers (purple arrows) and orange COVER markers\n- Strategy averages across timeframes\n\n## Development\n\n```bash\npnpm test              # Vitest unit tests\npnpm lint              # Biome lint\npnpm format:check      # Biome format check\npnpm typecheck         # TypeScript type check\n```\n\nSee `CLAUDE.md` for full architecture reference and AI assistance guidelines.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxgfr%2Fai-strategy-backtester","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaxgfr%2Fai-strategy-backtester","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxgfr%2Fai-strategy-backtester/lists"}