tradelab 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +188 -328
  3. package/bin/tradelab-mcp.js +7 -0
  4. package/bin/tradelab.js +29 -0
  5. package/dist/cjs/data.cjs +149 -26
  6. package/dist/cjs/index.cjs +1917 -1005
  7. package/dist/cjs/live.cjs +536 -25
  8. package/dist/cjs/ta.cjs +339 -0
  9. package/docs/README.md +32 -66
  10. package/docs/api-reference.md +283 -112
  11. package/docs/backtest-engine.md +210 -252
  12. package/docs/data-reporting-cli.md +114 -156
  13. package/docs/examples.md +6 -6
  14. package/docs/live-trading.md +263 -92
  15. package/docs/mcp.md +285 -0
  16. package/docs/research.md +157 -0
  17. package/examples/liveDashboard.js +33 -0
  18. package/examples/llmSignal.js +33 -0
  19. package/examples/mcpLiveTrading.js +77 -0
  20. package/examples/optimize.js +25 -0
  21. package/package.json +26 -4
  22. package/src/engine/asyncSignal.js +28 -0
  23. package/src/engine/backtest.js +13 -1
  24. package/src/engine/backtestAsync.js +27 -0
  25. package/src/engine/backtestTicks.js +13 -2
  26. package/src/engine/barSystemRunner.js +96 -41
  27. package/src/engine/execution.js +39 -0
  28. package/src/engine/grid.js +15 -0
  29. package/src/engine/llmSignal.js +84 -0
  30. package/src/engine/optimize.js +110 -0
  31. package/src/engine/optimizeWorker.js +67 -0
  32. package/src/engine/portfolio.js +4 -1
  33. package/src/engine/walkForward.js +1 -0
  34. package/src/index.js +9 -0
  35. package/src/live/dashboard/server.js +179 -0
  36. package/src/live/engine/liveEngine.js +2 -2
  37. package/src/live/engine/paperEngine.js +5 -0
  38. package/src/live/index.js +3 -0
  39. package/src/live/session.js +402 -0
  40. package/src/mcp/liveTools.js +179 -0
  41. package/src/mcp/schemas.js +167 -0
  42. package/src/mcp/server.js +35 -0
  43. package/src/mcp/tools.js +265 -0
  44. package/src/metrics/annualize.js +32 -0
  45. package/src/metrics/benchmark.js +55 -0
  46. package/src/metrics/buildMetrics.js +34 -13
  47. package/src/metrics/finite.js +17 -0
  48. package/src/research/combinations.js +18 -0
  49. package/src/research/cpcv.js +47 -0
  50. package/src/research/deflatedSharpe.js +35 -0
  51. package/src/research/index.js +6 -0
  52. package/src/research/monteCarlo.js +88 -0
  53. package/src/research/pbo.js +69 -0
  54. package/src/research/stats.js +78 -0
  55. package/src/strategies/builtins.js +96 -0
  56. package/src/strategies/index.js +30 -0
  57. package/src/ta/channels.js +67 -0
  58. package/src/ta/index.js +16 -0
  59. package/src/ta/oscillators.js +70 -0
  60. package/src/ta/trend.js +78 -0
  61. package/src/utils/random.js +33 -0
  62. package/templates/dashboard.html +661 -0
  63. package/types/index.d.ts +179 -0
  64. package/types/live.d.ts +114 -0
  65. package/types/mcp.d.ts +17 -0
  66. package/types/ta.d.ts +45 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,112 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.2.0] - 2026-06-26
9
+
10
+ ### Added
11
+
12
+ - **MCP agent trading (paper and live sessions)**
13
+ - New `TradingSession` class and `SessionManager` class exported from `tradelab/live`, enabling agents to manage real paper or live trading sessions programmatically.
14
+ - `SessionManager.create()` spins up a session backed by `PaperEngine` (default) or a credentialed live broker; `SessionManager.haltAll()` is the process-level kill-switch that flattens all positions and clears every session.
15
+ - `TradingSession.placeOrder()` supports risk-sized **bracket orders**: a single call with `stop` / `target` / `rr` fields submits the entry plus a protective stop and a profit target as OCO legs; a bar that straddles both stop and target no longer double-fills.
16
+ - Day-loss risk halts: `maxDailyLossPct` triggers an automatic halt via `RiskManager`; further `placeOrder()` calls throw until the session is stopped.
17
+ - Live-mode gating: live trading requires `TRADELAB_ALLOW_LIVE=true` (env var) **and** `confirmLive: true` passed to `create()`; paper is the default and needs no credentials or flags.
18
+
19
+ - **New MCP live-trading tools** (exposed via `tradelab-mcp`)
20
+ - `create_session` — create a paper or live session with equity, risk, and interval settings.
21
+ - `list_sessions` — list all active sessions and their current status.
22
+ - `session_status` — get a full refreshed snapshot (positions, open orders, equity, risk state).
23
+ - `feed_price` — push an OHLCV bar (or a single price) to advance paper simulation and trigger fills.
24
+ - `place_order` — place a market or limit order, optionally risk-sized with a bracket stop/target.
25
+ - `close_position` — close an open position via an opposite market order.
26
+ - `flatten` — flatten all positions and cancel all open orders in a session.
27
+ - `cancel_order` — cancel a specific open order.
28
+ - `account` — fetch broker account details (equity, cash, buying power).
29
+ - `positions` — list all open positions in a session.
30
+ - `recent_events` — retrieve recent session events (fills, risk changes, bars) for monitoring.
31
+ - `attach_strategy` — attach a named built-in strategy that auto-evaluates on each `feed_price` and places orders when flat.
32
+ - `halt_all` — emergency kill-switch: flattens all positions and stops every active session.
33
+
34
+ - **MCP research-plus tools** (exposed via `tradelab-mcp`)
35
+ - `analyze_robustness` — runs a backtest then Monte Carlo simulation and Deflated Sharpe ratio on the realized trade P&Ls; degrades gracefully with fewer than two trades.
36
+ - `optimize_strategy` — in-process grid sweep returning a leaderboard ranked by a chosen metric (default: `profitFactor`).
37
+ - `compare_strategies` — runs multiple named strategies on the same candle dataset and returns a ranked comparison.
38
+ - `candle_stats` — returns shape statistics (count, date range, price range, estimated interval) for a candle array or data spec; useful for sanity-checking data before backtesting.
39
+
40
+ - **Dashboard overhaul**
41
+ - Redesigned realtime cockpit with equity curve, KPI strip, positions/orders tables, severity-colored event feed, and a risk-halt banner.
42
+ - Live **Flatten / Stop / Cancel** controls in the dashboard UI via a new `POST /command` endpoint (whitelisted methods: `flatten`, `stop`, `closePosition`, `cancelOrder`).
43
+ - `GET /state` now calls `source.refresh()` before returning, so the state snapshot is always current.
44
+
45
+ ### Changed
46
+
47
+ - MCP server version is now read dynamically from `package.json` via `createRequire`; no separate version constant to update on release.
48
+
49
+ ### Fixed
50
+
51
+ - Paper-broker bracket orders: a price bar that straddled both the stop and the target could trigger a double-fill, flipping a position to the opposite side. The OCO cancel now runs before the sibling leg can fill.
52
+ - Dashboard equity curve color now reflects actual session P&L rather than a static value.
53
+
54
+ ## [1.1.0] - 2026-06-26
55
+
56
+ ### Added
57
+
58
+ - **Metrics correctness and annualization**
59
+ - `sharpeAnnualized` and `sortinoAnnualized` fields in `buildMetrics` output, scaled by `sqrt(periodsPerYear)`.
60
+ - `annualizationPeriods` field exposing the computed periods-per-year used for scaling.
61
+ - All ratio metrics (`profitFactor`, `sharpe`, `calmar`, etc.) now clamped to a finite sentinel via `clampFinite`; metrics JSON never emits `Infinity` or `NaN`.
62
+ - Benchmark statistics (`alpha`, `beta`, `correlation`, `informationRatio`, `trackingError`) available in `metrics.benchmark` when `benchmarkReturns` is passed to `buildMetrics`.
63
+ - New top-level exports: `clampFinite`, `BIG_NUMBER`, `periodsPerYear`, `benchmarkStats`.
64
+
65
+ - **`tradelab/ta` indicator namespace** (new subpath export)
66
+ - Oscillators: `rsi`, `macd`, `stochastic`.
67
+ - Channels: `bollinger`, `donchian`, `keltner`.
68
+ - Trend: `supertrend`, `vwap`.
69
+ - Re-exports from core: `ema`, `atr`, `swingHigh`, `swingLow`, `detectFVG`, `lastSwing`, `structureState`.
70
+ - All indicators return full-length arrays aligned to input (warmup positions are `undefined`).
71
+
72
+ - **Async and agent signals**
73
+ - `backtestAsync(options)` — async sibling of `backtest()` where `signal()` may return a `Promise`; accepts `signalBudgetMs` to race each bar's signal against a timeout.
74
+ - `LlmSignal` class — wraps an async `resolve(context)` function with per-bar caching, a configurable `budgetMs` timeout, a no-lookahead candle proxy, and a `log` array of every bar decision.
75
+ - `backtestTicks()` now accepts a `seed` option for reproducible probabilistic limit fills.
76
+ - `LiveEngine` awaits async signals, so `LlmSignal` can be used directly in live/paper execution.
77
+
78
+ - **`tradelab/mcp` MCP server** (new subpath export)
79
+ - `tradelab-mcp` binary — starts an MCP stdio server exposing tradelab tools to any MCP-capable agent (Claude Desktop, Cursor, etc.).
80
+ - Server exposes tools: `list_strategies`, `fetch_candles`, `run_backtest`, `walk_forward`.
81
+ - Name-addressable strategy registry: `listStrategies()`, `getStrategy(name)`, `registerStrategy(name, def)` (exported from `tradelab`).
82
+
83
+ - **Research and overfitting toolkit** (`research` namespace, re-exported from `tradelab`)
84
+ - `research.monteCarlo(returns, options)` — equity curve Monte Carlo simulation.
85
+ - `research.deflatedSharpe(sharpe, options)` — deflated Sharpe ratio (DSR) adjustment.
86
+ - `research.sweepHaircut(results, options)` — apply DSR haircut across a parameter sweep.
87
+ - `research.probabilityOfBacktestOverfitting(folds, options)` — CSCV/PBO overfitting probability.
88
+ - `research.combinatorialPurgedSplits(candles, options)` — combinatorial purged cross-validation (CPCV) split generator.
89
+
90
+ - **Parallel parameter optimization**
91
+ - `optimize(options)` — worker-thread pool that runs a parameter sweep in parallel; accepts `candles`, `signalModulePath`, `parameterSets`, `concurrency`, and `scoreBy`; returns `{ results, leaderboard, best }`.
92
+ - `grid(spec)` — helper that expands a `{ param: [v1, v2] }` spec into an array of parameter-set objects.
93
+
94
+ - **Carry and funding cost model**
95
+ - `costs.carry` — annualized borrow/margin cost (`longAnnualBps`, `shortAnnualBps`); deducted proportionally over hold time.
96
+ - `costs.funding` — perpetual futures funding (`rateBps`, `intervalMs`, `anchorMs`); positive rates charge longs and credit shorts.
97
+ - Closed positions include `exit.financing` (total financing cost already deducted from `exit.pnl`).
98
+
99
+ - **Live dashboard**
100
+ - `createDashboardServer(options)` exported from `tradelab/live` — zero-dependency SSE server using Node `node:http`.
101
+ - `--dashboard` and `--dashboardPort` CLI flags for `tradelab paper` and `tradelab live`.
102
+
103
+ - **Dependencies**: `@modelcontextprotocol/sdk` and `zod` added as runtime dependencies.
104
+
105
+ ### Fixed
106
+
107
+ - Metrics JSON no longer emits `Infinity` or `NaN`; all ratio metrics are clamped to `BIG_NUMBER` (1e9) or zero.
108
+ - Non-annualized Sharpe was not directly comparable across different timeframes; `sharpeAnnualized` provides a consistent cross-timeframe measure.
109
+
110
+ ## [1.0.1]
111
+
112
+ Prior release. See git history for details.