@the-staq/tradestaq-mcp 0.3.8 → 0.6.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.
- package/CHANGELOG.md +66 -0
- package/README.md +16 -4
- package/VERSION +1 -1
- package/dist/api.d.ts +19 -3
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +44 -8
- package/dist/api.js.map +1 -1
- package/dist/helpers.d.ts +23 -0
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +48 -8
- package/dist/helpers.js.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/tools/backtest.d.ts.map +1 -1
- package/dist/tools/backtest.js +34 -15
- package/dist/tools/backtest.js.map +1 -1
- package/dist/tools/bot.d.ts.map +1 -1
- package/dist/tools/bot.js +816 -56
- package/dist/tools/bot.js.map +1 -1
- package/dist/tools/copy-trading.d.ts.map +1 -1
- package/dist/tools/copy-trading.js +22 -13
- package/dist/tools/copy-trading.js.map +1 -1
- package/dist/tools/market.d.ts.map +1 -1
- package/dist/tools/market.js +56 -12
- package/dist/tools/market.js.map +1 -1
- package/dist/tools/portfolio.d.ts.map +1 -1
- package/dist/tools/portfolio.js +23 -12
- package/dist/tools/portfolio.js.map +1 -1
- package/dist/tools/strategy-lab.d.ts +28 -0
- package/dist/tools/strategy-lab.d.ts.map +1 -0
- package/dist/tools/strategy-lab.js +264 -0
- package/dist/tools/strategy-lab.js.map +1 -0
- package/dist/tools/strategy.d.ts.map +1 -1
- package/dist/tools/strategy.js +168 -15
- package/dist/tools/strategy.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,71 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- **`update_bot` edits the whole bot.** New fields: `name`; `strategyId` (ID or slug, resolved through the strategy route); `presetId` (ID or slug, applied by the server: the preset's strategy, parameter overrides, timeframe, execution mode / interval and version, with explicit fields on top); `versionChannel` and `pinnedVersionId`; `timeframe`; `executionMode` and `spinIntervalSeconds`; `parameterOverrides` (merged into the current ones, `null` removes a key) and `resetParameterOverrides`. Everything goes in one PATCH, so a strategy switch is never half-applied.
|
|
7
|
+
- **Merge rules.** `spinConfig` is fetched and merged like `positionSizing` (only the explicit keys go with a preset, so the preset's fill the rest). Parameter overrides merge onto the bot's current ones on the same strategy; a strategy switch starts from none and also clears the old preset and pin (stable channel unless given). Size and leverage are only sent when `positionSizePercent` / `leverage` are given.
|
|
8
|
+
- **Flat-only changes.** A strategy or timeframe change on a bot that holds a position (GET's `openTradesCount` / `openPosition`) is refused with `OPEN_POSITION` before anything is sent; the server's own 409 `OPEN_POSITION` (it also counts working orders) comes back with the same advice: pause with `stopAfterClose: true`, wait until flat, retry.
|
|
9
|
+
- **Result.** Every edit except a `stopAfterClose`-only call now returns JSON: `message`, the resulting `bot` config read back from GET /api/bots/:id (strategy id and name, version channel and the version it runs, preset, timeframe, mode, interval, up to 40 parameter overrides, sizing, status, paper/live, open position) and the server's `warnings` (e.g. candle history supply), plus a note to `start_bot` a paused bot after a switch.
|
|
10
|
+
- **Scope.** Unchanged and server-enforced: a paper bot needs `mcp:paper`, any change to a live bot `mcp:live`. An `INSUFFICIENT_SCOPE` on a live bot says so.
|
|
11
|
+
- README lists `start_bot` and `delete_bot`.
|
|
12
|
+
- Ship this only after the TradeStaq web release with PATCH `applyPreset` and the strategy-switch guard is live. Against an older server a `presetId` call fails with `PRESET_UNSUPPORTED` (the server ignores the field) instead of reporting success, and the client-side open-position check still blocks a switch on a holding bot.
|
|
13
|
+
|
|
14
|
+
## [0.5.0] - 2026-10-14
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- **`get_bot_logs`.** Explains what a strategy bot has been doing run by run. Sections (`include`, default `runs` + `spinLogs`): `runs` from the new GET /api/bots/:id/runs (outcome kind `k` = skipped_bar / skipped_other / no_signal / signal_queued / signal_dropped / error, reason code, bar, price, emitted / queued / dropped counts, `why` codes, folded skip count, executor result, spin number and run duration, plus pending skips, last spin (`at`, `status`, `nextAt`, `lastProcessedCandle`) and early-exit counts by UTC day and reason code for today and yesterday), `spinLogs` (stored per-run records) and `live` (recent in-memory runs with each run's outcome in the same format, and today's summary). `limit` 1-100 (default 25) and an optional `kind` filter for runs. The three requests run in parallel and each section reports its own error, so one failing route does not hide the others. Output fields are allowlisted: raw worker log text, state tokens, job ids, balances and stack traces are never returned, and `err` / error messages are cut at 300 characters. An unknown outcome kind is dropped.
|
|
18
|
+
- **`update_bot` `stopAfterClose`.** `true`: the bot keeps managing its open position (SL/TP, DCA exits, strategy exits, close signals), opens no new entries, and pauses itself once flat (immediately if already flat), notifying the owner once; `false`: cancel. Only an active bot can be set, and any status change (start_bot / stop_bot) cancels it. It is sent as-is in the PATCH body, so a `stopAfterClose`-only call no longer does the fetch-and-merge GET first. The reply says whether the bot is waiting for its position to close or was already flat and is now in its resting status (`paused` for strategy bots, `stopped` for signal bots).
|
|
19
|
+
- **`deploy_bot` `timeframe`.** Optional. Leave it out and the bot trades on the strategy's own timeframe (nothing is sent, so the server picks it); pass one (e.g. `4h`) only to override that. Your plan may limit which timeframes you can use.
|
|
20
|
+
- **`get_bot_status` shows `stopAfterClose`** (`enabled`, `requestedAt`, `completedAt`) when the bot has it.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
- **`deploy_bot` `name` is optional in practice.** Leave it out (or pass an empty one) and nothing is sent, so the server names the bot. Ship this only after the TradeStaq web release that gives unnamed bots a default name is live.
|
|
24
|
+
- **`stop_bot` text corrected.** It said the bot "stops opening new positions"; it actually stops the bot entirely and leaves its open positions unmanaged. It now points to `update_bot stopAfterClose` for a graceful stop.
|
|
25
|
+
- Ship `stopAfterClose` only after the TradeStaq web release with stop-after-close is live (older servers reject the field with `Field "stopAfterClose" is not allowed`).
|
|
26
|
+
- Ship `get_bot_logs` only after the TradeStaq web release with /api/bots/[id]/runs and the log-route auth fix is live (older servers have no /runs route, and the spin-logs / live-spins routes reject MCP tokens).
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
- **Preset search on multi-pair runs (text only, no request changes).** `symbols` no longer says it is not combinable with `searchPresets`: once an admin prices the multi-pair preset search, every preset candidate is tested on every pair, each searched profile costs the per-profile price plus an extra charge per extra pair (under `presetSearch` / `costBreakdown.presetSearch` in the quoteId estimate, which already pass through), and it is billed only if the search finishes. Until then the server refuses it with `preset_search_single_pair_only`, as today.
|
|
30
|
+
- **`profilesThatFit` on `basket_too_slow`.** When a multi-pair run with `searchPresets` is too slow, the server now also says how many risk profiles still fit at the same pairs and window (`0` = drop `searchPresets`), and its message suggests searching fewer profiles. It is added to the allowlisted basket error details, so an agent is no longer steered only toward fewer pairs.
|
|
31
|
+
- Ship this only after the TradeStaq web release with the basket preset search is live.
|
|
32
|
+
|
|
33
|
+
### Fixed
|
|
34
|
+
- **`get_candles` returned nothing.** It sent `exchange` (the route only reads `exchangeId`, so every call was a 400) and read `data.candles` (the route returns `{ success, data: { candles } }`). It now always sends `exchangeId`; with no `exchange` given it uses your first active exchange account from /api/exchanges and falls back to the public `binance` feed only when you have none (a bare platform name makes the route pick any user's account of that name). It returns the `exchangeId` used, the latest candle's OHLCV fields only, and `usingFallback` / `fallbackExchange` (cut at 40 characters) when the server served public data instead.
|
|
35
|
+
- Tool count in README / package.json corrected to 46 (it still said 31).
|
|
36
|
+
- **Basket quote fields are shape-checked, not just allowlisted.** `quoteId` must be the server's UUID, `assets` 1-8 pair symbols (no whitespace, max 64 chars), `resolved` two ISO dates, `costBreakdown` only its numeric `experiments` / `perExperiment` / `presetSearch` and `perExtraAsset` (number or null), the counts finite numbers, and `presetSearch` only `requested` / `cost` / known `profiles`. Anything else is dropped, so server text can no longer reach the agent through these fields.
|
|
37
|
+
- **Basket 400 codes are allowlisted.** Only the codes the server's POST /api/strategy-lab documents (`invalid_symbols_param`, `baskets_unavailable`, `too_many_assets`, `preset_search_single_pair_only`, `invalid_symbols`, `mixed_basket`, `invalid_run_window`, `basket_window_too_long`, `basket_too_slow`, `basket_preset_search_unavailable`) are returned; any other 400 is `HTTP_400` without details. `mixed_basket` also returns its `symbol` when it is a pair symbol.
|
|
38
|
+
- **Error codes for every tool.** `api()` now also reads a top-level `code` when there is no `error.code`, and accepts either only when it matches `^[a-z0-9_]{1,64}$` (otherwise `HTTP_<status>`). Strategy Lab errors go through the shared error format (`ApiError.fields` + `errorResult`) instead of a second copy of it.
|
|
39
|
+
- **`symbol` with `symbols` is checked.** A `symbol` that is not one of `symbols` is now refused with `symbol_not_in_symbols` before anything is quoted, instead of being silently ignored.
|
|
40
|
+
- **`symbols` cleanup.** Entries are trimmed, empty ones dropped and duplicates removed case-insensitively after trimming; a list that comes down to one pair is a single-pair run, and one with no pairs left is refused with `no_symbols`.
|
|
41
|
+
- The estimate message is chosen by the number of pairs sent, not by whether a `quoteId` came back. The `symbols` cap stays 8, the server's hard maximum (the plan cap and the admin-set system cap, 5 by default, are enforced server side), and its text now says so.
|
|
42
|
+
|
|
43
|
+
## [0.4.0] - 2026-10-09
|
|
44
|
+
|
|
45
|
+
### Added
|
|
46
|
+
- **Multi-pair (basket) Strategy Lab runs.** `start_optimization_run` takes `symbols` (1-8 pairs, primary first, same exchange account and market type), so every candidate is tested on every pair instead of being tuned to one chart. Pairs are deduped case-insensitively; `symbol` only picks the primary when it is one of `symbols` (in `symbol`'s spelling, as the server does) and is otherwise ignored, so no unlisted pair is ever added; more than one pair sends `symbols` only, one pair sends a plain scalar `symbol`. The tool text covers the per-plan cap (Free 1 / Pro 3 / Trader 4 / Whale 5, system cap 5), the pricing (base per experiment plus an extra charge per extra pair per experiment, billed per pair actually evaluated), and the pass bar (beat the original on most pairs, wreck no pair, lose money out of sample on no pair; otherwise held).
|
|
47
|
+
- **Quote consent.** New `quoteId` and `acknowledgedCost` params are forwarded only when given. A multi-pair request always returns a `cost_estimate` first; the agent shows the pairs, the maximum cost and the time estimate, then re-sends the same arguments with `acknowledgeCost: true` and the `quoteId`. The bill is never above the quote.
|
|
48
|
+
- **Quote fields on `cost_estimate`:** `quoteId`, `resolved`, `assets`, `assetCount`, `experimentsQuoted`, `clampedFrom`, `estimatedMinutes`, `expectedExperimentsWithinBudget` and `costBreakdown`, each only when the server sends it. Every 0.3.9 field is kept; other server keys are not passed through.
|
|
49
|
+
- **`quote_changed` handling.** A 409 `quote_changed` now comes back as a normal `cost_estimate` result with `quoteChanged: true`, the new `quoteId` and `reason` (only `params_changed`, `price_increased`, `quote_expired` or `foreign_quote`), to show the user and confirm again.
|
|
50
|
+
- **Basket error details.** A 400 with a server `code` (e.g. `too_many_assets`, `baskets_unavailable`, `invalid_symbols`, `basket_too_slow`) returns that code plus only the allowlisted `maxAssets`, `upgrade {tierName, maxAssets}`, `invalidSymbols`, `maxDaysAtTimeframe`, `maxAssetsThatFit` and `maxDaysThatFit`. `ApiError` gained an optional `details` (the parsed JSON error body; never set on the sanitised `insufficient_scope` path, and never added to the generic error text).
|
|
51
|
+
- **Per-pair status.** `get_optimization_status` requests `detail=summary` (`experiments[].perAsset` kept only on the best and latest experiment) and its text explains `progress.basket`, `baselinePerAsset` / `bestPerAsset` (W/T/L/cured), `validation.perAsset` / `validation.breadth`, `autoPromote.untestedPairs` and the `queue {position, etaMinutes}` of a waiting run. `start_optimization_run` also passes `queue` through when the server returns it.
|
|
52
|
+
|
|
53
|
+
### Changed
|
|
54
|
+
- The `symbol` default (`BTC/USDT`) moved from the zod schema into the handler. Omitting `symbols` sends exactly the 0.3.9 request body.
|
|
55
|
+
- `server.json` versions brought up to date (they were stale at 0.3.1).
|
|
56
|
+
|
|
57
|
+
Ship this only after the TradeStaq web release with basket runs is live. Multi-pair runs stay unavailable (400 `baskets_unavailable`) until the server enables them; single-pair runs are unchanged.
|
|
58
|
+
|
|
59
|
+
## [0.3.9] - 2026-10-08
|
|
60
|
+
|
|
61
|
+
### Changed
|
|
62
|
+
- **Strategy Lab tool descriptions now match how runs finish (text only, no request or response changes).** The server now checks a run's best version out of sample before moving the strategy's `latestVersion`, and the old text promised that "improvements are saved to the strategy's latestVersion as they're found", which is no longer true.
|
|
63
|
+
- `start_optimization_run`: the best version becomes `latestVersion` only if it passes the out-of-sample check (single-pair runs: also when the check is inconclusive). Otherwise the version is held, `latestVersion` and the bots following it stay as they were, and `get_optimization_status` shows `progress.verdict`, `progress.heldBecause` and `progress.heldVersionId` (with no `savedVersionId`). The strategy author can accept a held version in the web app ("Use this version anyway").
|
|
64
|
+
- `autoPromote`: requires a passing verdict, profitable out-of-sample results and no regression against the current stable version. An inconclusive check never auto-promotes.
|
|
65
|
+
- `get_optimization_status`: explains `verdict`, `heldVersionId` / `heldBecause`, `cancelled` and `stopReason`, and that `savedVersionId` during a run is not yet `latestVersion`.
|
|
66
|
+
- `cancel_optimization_run`: a cancelled run's best version is kept but held, not saved to `latestVersion`.
|
|
67
|
+
- Ship this only after the matching TradeStaq web release (held runs and the out-of-sample verdict) is live.
|
|
68
|
+
|
|
3
69
|
## [0.3.8] - 2026-07-10
|
|
4
70
|
|
|
5
71
|
### Fixed
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
**[Website](https://tradestaq.com)** · **[Docs](https://tradestaq.com/docs)** · **[MCP / AI Tools](https://tradestaq.com/mcp)** · **[Pricing](https://tradestaq.com/pricing)**
|
|
7
7
|
|
|
8
|
-
**
|
|
8
|
+
**46 AI-powered trading tools for Claude, Cursor, and any MCP client.**
|
|
9
9
|
|
|
10
10
|
Create strategies, backtest them, deploy trading bots, copy top traders, monitor positions, and manage your crypto portfolio, all from conversation. Supports Binance, Bybit, OKX, Bitget, Hyperliquid, dYdX, and more.
|
|
11
11
|
|
|
@@ -142,11 +142,23 @@ Credentials never enter the chat when using the browser flow. Token is stored lo
|
|
|
142
142
|
|------|-------------|
|
|
143
143
|
| `list_bots` | All bots with status and performance |
|
|
144
144
|
| `get_bot_status` | Detailed bot metrics and config |
|
|
145
|
+
| `get_bot_logs` | Run-by-run history: why a bot did or did not trade, dropped signals, errors |
|
|
145
146
|
| `deploy_bot` | Deploy a strategy as a trading bot |
|
|
146
|
-
| `
|
|
147
|
+
| `update_bot` | Edit a bot: rename, switch strategy or apply a preset, timeframe, execution mode, strategy parameters, version channel, risk settings, notifications, `stopAfterClose` |
|
|
148
|
+
| `start_bot` | Start a paused or stopped bot |
|
|
149
|
+
| `stop_bot` | Stop a running bot now (open positions are left unmanaged) |
|
|
150
|
+
| `delete_bot` | Delete a bot (refused while it has an open trade) |
|
|
147
151
|
| `close_position` | Close an open position (full or partial) |
|
|
148
152
|
|
|
149
|
-
`deploy_bot` defaults to paper trading. Pass `live: true` for real money.
|
|
153
|
+
`deploy_bot` defaults to paper trading. Pass `live: true` for real money. The bot trades on the strategy's own timeframe; pass `timeframe` (e.g. `4h`) only to override it. Leave out `name` and the server names the bot.
|
|
154
|
+
|
|
155
|
+
`update_bot` sends everything you pass in one update, after merging it onto the bot's current settings (position sizing, spin settings and parameter overrides are never wiped by a partial change). Size and leverage change only when you pass them. `strategyId` and `presetId` take an ID or a slug (`trade-wind`, `trade-wind-long-short`). A strategy or timeframe change needs the bot to be flat: pause it with `stopAfterClose: true` first, wait until `get_bot_status` shows no open position, then switch, then `start_bot`. A live bot needs the `mcp:live` scope for any change; a paper bot `mcp:paper`. The reply is the resulting config (strategy, version, timeframe, mode, overrides, size, leverage, status) plus server warnings.
|
|
156
|
+
|
|
157
|
+
For example, switching a paused 15m GhostRider bot to Trade Wind on 4h with its Long & Short preset, and renaming it:
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
{ "id": "6ab7c2d60014ba19b0c54258", "presetId": "trade-wind-long-short", "timeframe": "4h", "name": "Trade Wind · SUI · 4h" }
|
|
161
|
+
```
|
|
150
162
|
|
|
151
163
|
### Trade History
|
|
152
164
|
|
|
@@ -194,7 +206,7 @@ MCP resources provide browsable data that AI clients can read directly:
|
|
|
194
206
|
┌──────────────┐◄──────────►┐ ┌────────────────►┌──────────────┐
|
|
195
207
|
│Claude Desktop│ │ │ │ │
|
|
196
208
|
│Cursor / CLI │ │ tradestaq-mcp │ Bearer JWT │ TradeStaq │
|
|
197
|
-
└──────────────┘ │
|
|
209
|
+
└──────────────┘ │ 46 tools │◄────────────────│ API │
|
|
198
210
|
│ 3 prompts │ │ │
|
|
199
211
|
┌──────────────┐ HTTP+SSE │ 3 resources │ └──────────────┘
|
|
200
212
|
│ Any MCP │◄──────────►│ │
|
package/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.
|
|
1
|
+
0.6.0
|
package/dist/api.d.ts
CHANGED
|
@@ -3,11 +3,27 @@ export declare class ApiError extends Error {
|
|
|
3
3
|
code: string;
|
|
4
4
|
retryable: boolean;
|
|
5
5
|
retryAfterMs?: number | undefined;
|
|
6
|
-
|
|
6
|
+
details?: Record<string, unknown> | undefined;
|
|
7
|
+
fields?: Record<string, unknown> | undefined;
|
|
8
|
+
constructor(status: number, code: string, message: string, retryable?: boolean, retryAfterMs?: number | undefined, details?: Record<string, unknown> | undefined, fields?: Record<string, unknown> | undefined);
|
|
7
9
|
}
|
|
8
|
-
|
|
10
|
+
/** A server-provided error code safe to put in front of the agent: a short identifier, nothing else. */
|
|
11
|
+
export declare function isSafeErrorCode(code: unknown): code is string;
|
|
12
|
+
export interface ApiOptions {
|
|
9
13
|
method?: string;
|
|
10
14
|
body?: unknown;
|
|
15
|
+
/** Abort after this many ms (default 30s). */
|
|
11
16
|
timeout?: number;
|
|
12
|
-
|
|
17
|
+
/**
|
|
18
|
+
* false: send the request exactly ONCE. No retry on a timeout, 429, 5xx or network error,
|
|
19
|
+
* and every error it throws has retryable: false, so the agent is never told to retry
|
|
20
|
+
* either. For non-idempotent writes (closing a position, creating a bot), where a resend
|
|
21
|
+
* after a timeout or a gateway 5xx can repeat an action the server already carried out.
|
|
22
|
+
* The one 401 -> token refresh -> resend still happens: a 401 means the server did nothing.
|
|
23
|
+
*/
|
|
24
|
+
retry?: boolean;
|
|
25
|
+
/** Extra request headers. They never replace Authorization, Content-Type or X-MCP-Source. */
|
|
26
|
+
headers?: Record<string, string>;
|
|
27
|
+
}
|
|
28
|
+
export declare function api<T = unknown>(path: string, options?: ApiOptions): Promise<T>;
|
|
13
29
|
//# sourceMappingURL=api.d.ts.map
|
package/dist/api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAGA,qBAAa,QAAS,SAAQ,KAAK;IAExB,MAAM,EAAE,MAAM;IACd,IAAI,EAAE,MAAM;IAEZ,SAAS,EAAE,OAAO;IAClB,YAAY,CAAC,EAAE,MAAM;
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAGA,qBAAa,QAAS,SAAQ,KAAK;IAExB,MAAM,EAAE,MAAM;IACd,IAAI,EAAE,MAAM;IAEZ,SAAS,EAAE,OAAO;IAClB,YAAY,CAAC,EAAE,MAAM;IAGrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIjC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;gBAXhC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,EACR,SAAS,GAAE,OAAe,EAC1B,YAAY,CAAC,EAAE,MAAM,YAAA,EAGrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,YAAA,EAIjC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,YAAA;CAK1C;AAMD,wGAAwG;AACxG,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,MAAM,CAE7D;AAkHD,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,8CAA8C;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,6FAA6F;IAC7F,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC;AAaD,wBAAsB,GAAG,CAAC,CAAC,GAAG,OAAO,EACnC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,UAAe,GACvB,OAAO,CAAC,CAAC,CAAC,CAoIZ"}
|
package/dist/api.js
CHANGED
|
@@ -5,16 +5,32 @@ export class ApiError extends Error {
|
|
|
5
5
|
code;
|
|
6
6
|
retryable;
|
|
7
7
|
retryAfterMs;
|
|
8
|
-
|
|
8
|
+
details;
|
|
9
|
+
fields;
|
|
10
|
+
constructor(status, code, message, retryable = false, retryAfterMs,
|
|
11
|
+
// The parsed JSON error body, for callers that read structured fields (e.g. the
|
|
12
|
+
// Strategy Lab quote_changed envelope). Never dumped into the generic error text.
|
|
13
|
+
details,
|
|
14
|
+
// Extra structured fields to show the agent next to code/message (withErrorHandling
|
|
15
|
+
// adds them to the error object). Callers put only allowlisted, shape-checked values
|
|
16
|
+
// here; never a raw server body.
|
|
17
|
+
fields) {
|
|
9
18
|
super(message);
|
|
10
19
|
this.status = status;
|
|
11
20
|
this.code = code;
|
|
12
21
|
this.retryable = retryable;
|
|
13
22
|
this.retryAfterMs = retryAfterMs;
|
|
23
|
+
this.details = details;
|
|
24
|
+
this.fields = fields;
|
|
14
25
|
this.name = 'ApiError';
|
|
15
26
|
}
|
|
16
27
|
}
|
|
17
28
|
const MAX_RETRIES = 2;
|
|
29
|
+
const SAFE_ERROR_CODE = /^[a-z0-9_]{1,64}$/i;
|
|
30
|
+
/** A server-provided error code safe to put in front of the agent: a short identifier, nothing else. */
|
|
31
|
+
export function isSafeErrorCode(code) {
|
|
32
|
+
return typeof code === 'string' && SAFE_ERROR_CODE.test(code);
|
|
33
|
+
}
|
|
18
34
|
// Backoff between retries. Skipped under Vitest so the test suite stays fast
|
|
19
35
|
// while production still waits out rate limits / transient 5xx.
|
|
20
36
|
function sleep(ms) {
|
|
@@ -131,6 +147,16 @@ function parseRetryAfter(res) {
|
|
|
131
147
|
const secs = Number(raw);
|
|
132
148
|
return Number.isFinite(secs) && secs >= 0 ? Math.min(secs * 1000, 30_000) : undefined;
|
|
133
149
|
}
|
|
150
|
+
// Headers api() always sets itself; a caller's `headers` cannot replace them.
|
|
151
|
+
const FIXED_HEADERS = new Set(['authorization', 'content-type', 'x-mcp-source']);
|
|
152
|
+
function extraHeaders(headers) {
|
|
153
|
+
const out = {};
|
|
154
|
+
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
155
|
+
if (!FIXED_HEADERS.has(name.toLowerCase()))
|
|
156
|
+
out[name] = value;
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
134
160
|
export async function api(path, options = {}) {
|
|
135
161
|
const store = requestContext.getStore();
|
|
136
162
|
// Stdio mode: proactively rotate BEFORE reading the token, so an expired
|
|
@@ -149,6 +175,9 @@ export async function api(path, options = {}) {
|
|
|
149
175
|
: 'Not authenticated. Run the authenticate tool first.');
|
|
150
176
|
}
|
|
151
177
|
const url = `${config.baseUrl}${path}`;
|
|
178
|
+
// retry: false → one send. Its errors are never retryable (below), so the loop only goes
|
|
179
|
+
// round again for the 401 refresh resend.
|
|
180
|
+
const retry = options.retry !== false;
|
|
152
181
|
let lastErr;
|
|
153
182
|
let recovered401 = false;
|
|
154
183
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
@@ -163,6 +192,7 @@ export async function api(path, options = {}) {
|
|
|
163
192
|
const res = await fetch(url, {
|
|
164
193
|
method: options.method ?? 'GET',
|
|
165
194
|
headers: {
|
|
195
|
+
...extraHeaders(options.headers),
|
|
166
196
|
Authorization: `Bearer ${token}`,
|
|
167
197
|
'Content-Type': 'application/json',
|
|
168
198
|
'X-MCP-Source': 'tradestaq-mcp',
|
|
@@ -182,7 +212,7 @@ export async function api(path, options = {}) {
|
|
|
182
212
|
parseOk = false;
|
|
183
213
|
}
|
|
184
214
|
if (!res.ok) {
|
|
185
|
-
const retryable = res.status === 429 || res.status >= 500;
|
|
215
|
+
const retryable = retry && (res.status === 429 || res.status >= 500);
|
|
186
216
|
const retryAfterMs = retryable ? parseRetryAfter(res) : undefined;
|
|
187
217
|
// OAuth insufficient_scope (RFC 6749 §5.2). The server-provided
|
|
188
218
|
// `scope` and `error_description` fields end up in LLM context
|
|
@@ -196,11 +226,17 @@ export async function api(path, options = {}) {
|
|
|
196
226
|
const safeScope = rawScope.find((s) => KNOWN.has(s)) || 'a broader scope';
|
|
197
227
|
throw new ApiError(403, 'INSUFFICIENT_SCOPE', `This action requires ${safeScope === 'a broader scope' ? safeScope : `the '${safeScope}' OAuth scope`}. The current token does not grant it. Surface this to the user — do not re-authenticate without explicit user approval, since broader scopes expand what automated tools can do on their account.`, false);
|
|
198
228
|
}
|
|
199
|
-
|
|
229
|
+
// The machine-readable code: `error.code` (nested envelope) or a top-level `code`
|
|
230
|
+
// (e.g. the Strategy Lab basket 400s). It reaches the agent's context, so only a
|
|
231
|
+
// short identifier is accepted; anything else falls back to HTTP_<status>.
|
|
232
|
+
const code = (parseOk ? [data?.error?.code, data?.code].find(isSafeErrorCode) : undefined) ?? `HTTP_${res.status}`;
|
|
200
233
|
const message = parseOk
|
|
201
234
|
? (data?.error?.message ?? data?.error ?? data?.message ?? `API returned ${res.status}`)
|
|
202
235
|
: `API returned ${res.status} with a non-JSON response`;
|
|
203
|
-
|
|
236
|
+
const details = parseOk && data && typeof data === 'object' && !Array.isArray(data)
|
|
237
|
+
? data
|
|
238
|
+
: undefined;
|
|
239
|
+
throw new ApiError(res.status, code, message, retryable, retryAfterMs, details);
|
|
204
240
|
}
|
|
205
241
|
// 2xx with an unparseable body: treat empty/no-content as an empty
|
|
206
242
|
// object (common for write endpoints); the caller reads fields defensively.
|
|
@@ -210,8 +246,8 @@ export async function api(path, options = {}) {
|
|
|
210
246
|
const apiErr = err instanceof ApiError
|
|
211
247
|
? err
|
|
212
248
|
: err.name === 'AbortError'
|
|
213
|
-
? new ApiError(408, 'TIMEOUT', 'Request timed out',
|
|
214
|
-
: new ApiError(0, 'NETWORK_ERROR', `Failed to reach TradeStaq API: ${err.message}`,
|
|
249
|
+
? new ApiError(408, 'TIMEOUT', 'Request timed out', retry)
|
|
250
|
+
: new ApiError(0, 'NETWORK_ERROR', `Failed to reach TradeStaq API: ${err.message}`, retry);
|
|
215
251
|
// stdio: a 401 despite the proactive refresh (token revoked, clock skew,
|
|
216
252
|
// or an expiry we missed) — try ONE rotation, then retry with the new
|
|
217
253
|
// token. Bounded by recovered401 so a persistently-rejected token can't loop.
|
|
@@ -226,7 +262,7 @@ export async function api(path, options = {}) {
|
|
|
226
262
|
}
|
|
227
263
|
}
|
|
228
264
|
// Retry transient failures (429 / 5xx / timeout / network) with backoff.
|
|
229
|
-
if (apiErr.retryable && attempt < MAX_RETRIES) {
|
|
265
|
+
if (retry && apiErr.retryable && attempt < MAX_RETRIES) {
|
|
230
266
|
lastErr = apiErr;
|
|
231
267
|
continue;
|
|
232
268
|
}
|
|
@@ -237,6 +273,6 @@ export async function api(path, options = {}) {
|
|
|
237
273
|
}
|
|
238
274
|
}
|
|
239
275
|
// Retries exhausted.
|
|
240
|
-
throw lastErr ?? new ApiError(0, 'NETWORK_ERROR', 'Request failed after retries',
|
|
276
|
+
throw lastErr ?? new ApiError(0, 'NETWORK_ERROR', 'Request failed after retries', retry);
|
|
241
277
|
}
|
|
242
278
|
//# sourceMappingURL=api.js.map
|
package/dist/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA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IAAI,QAAQ,CAAC,GAAG,EAAE,SAAS,EAAE,mBAAmB,EAAE,KAAK,CAAC;oBAC1D,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAC,EAAE,eAAe,EAAE,kCAAmC,GAAa,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAA;YAE3G,yEAAyE;YACzE,sEAAsE;YACtE,8EAA8E;YAC9E,IAAI,MAAM,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,CAAC,YAAY,IAAI,UAAU,EAAE,CAAC,YAAY,EAAE,CAAC;gBAClF,YAAY,GAAG,IAAI,CAAA;gBACnB,IAAI,MAAM,YAAY,EAAE,EAAE,CAAC;oBACzB,MAAM,OAAO,GAAG,UAAU,EAAE,CAAC,KAAK,CAAA;oBAClC,IAAI,OAAO,EAAE,CAAC;wBACZ,KAAK,GAAG,OAAO,CAAA;wBACf,SAAQ;oBACV,CAAC;gBACH,CAAC;YACH,CAAC;YAED,yEAAyE;YACzE,IAAI,KAAK,IAAI,MAAM,CAAC,SAAS,IAAI,OAAO,GAAG,WAAW,EAAE,CAAC;gBACvD,OAAO,GAAG,MAAM,CAAA;gBAChB,SAAQ;YACV,CAAC;YACD,MAAM,MAAM,CAAA;QACd,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAA;QACrB,CAAC;IACH,CAAC;IAED,qBAAqB;IACrB,MAAM,OAAO,IAAI,IAAI,QAAQ,CAAC,CAAC,EAAE,eAAe,EAAE,8BAA8B,EAAE,KAAK,CAAC,CAAA;AAC1F,CAAC"}
|
package/dist/helpers.d.ts
CHANGED
|
@@ -4,5 +4,28 @@ export declare function jsonResult(data: unknown): {
|
|
|
4
4
|
text: string;
|
|
5
5
|
}[];
|
|
6
6
|
};
|
|
7
|
+
/**
|
|
8
|
+
* Best-effort strategy name lookup, owner-authoritative first with a
|
|
9
|
+
* marketplace fallback (same pattern get_strategy uses in strategy.ts).
|
|
10
|
+
* Never throws -- callers that just want a human-readable label for
|
|
11
|
+
* something else (e.g. naming a backtest) shouldn't fail the whole
|
|
12
|
+
* operation because a name lookup 403'd or 404'd. Falls back to the raw ID.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveStrategyName(id: string): Promise<string>;
|
|
15
|
+
/**
|
|
16
|
+
* The one error result shape every tool returns: `{ error: { code, message, retryable,
|
|
17
|
+
* retryAfterMs?, ...fields } }`. `fields` must already be allowlisted by the caller.
|
|
18
|
+
*/
|
|
19
|
+
export declare function errorResult(code: string, message: string, { retryable, retryAfterMs, fields }?: {
|
|
20
|
+
retryable?: boolean;
|
|
21
|
+
retryAfterMs?: number;
|
|
22
|
+
fields?: Record<string, unknown>;
|
|
23
|
+
}): {
|
|
24
|
+
isError: boolean;
|
|
25
|
+
content: {
|
|
26
|
+
type: "text";
|
|
27
|
+
text: string;
|
|
28
|
+
}[];
|
|
29
|
+
};
|
|
7
30
|
export declare function withErrorHandling<T extends (...args: any[]) => Promise<any>>(handler: T): T;
|
|
8
31
|
//# sourceMappingURL=helpers.d.ts.map
|
package/dist/helpers.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO;;;;;EAIvC;AAED,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO;;;;;EAIvC;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAiBrE;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,EAAE,SAAiB,EAAE,YAAY,EAAE,MAAM,EAAE,GAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAO;;;;;;EAYnI;AAED,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,CAoB3F"}
|
package/dist/helpers.js
CHANGED
|
@@ -1,9 +1,55 @@
|
|
|
1
|
-
import { ApiError } from './api.js';
|
|
1
|
+
import { api, ApiError } from './api.js';
|
|
2
2
|
export function jsonResult(data) {
|
|
3
3
|
return {
|
|
4
4
|
content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
|
|
5
5
|
};
|
|
6
6
|
}
|
|
7
|
+
/**
|
|
8
|
+
* Best-effort strategy name lookup, owner-authoritative first with a
|
|
9
|
+
* marketplace fallback (same pattern get_strategy uses in strategy.ts).
|
|
10
|
+
* Never throws -- callers that just want a human-readable label for
|
|
11
|
+
* something else (e.g. naming a backtest) shouldn't fail the whole
|
|
12
|
+
* operation because a name lookup 403'd or 404'd. Falls back to the raw ID.
|
|
13
|
+
*/
|
|
14
|
+
export async function resolveStrategyName(id) {
|
|
15
|
+
try {
|
|
16
|
+
const raw = await api(`/api/user-strategies/${id}`);
|
|
17
|
+
const name = (raw.data || raw)?.name;
|
|
18
|
+
if (name)
|
|
19
|
+
return name;
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
if (err instanceof ApiError && (err.status === 403 || err.status === 404)) {
|
|
23
|
+
try {
|
|
24
|
+
const raw = await api(`/api/tradedroid/strategies/${id}`);
|
|
25
|
+
const name = (raw.doc || raw)?.name;
|
|
26
|
+
if (name)
|
|
27
|
+
return name;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// Fall through to the ID below.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return id;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The one error result shape every tool returns: `{ error: { code, message, retryable,
|
|
38
|
+
* retryAfterMs?, ...fields } }`. `fields` must already be allowlisted by the caller.
|
|
39
|
+
*/
|
|
40
|
+
export function errorResult(code, message, { retryable = false, retryAfterMs, fields } = {}) {
|
|
41
|
+
const error = { code, message, retryable,
|
|
42
|
+
...(retryable ? { retryAfterMs: retryAfterMs ?? 5000 } : {}) };
|
|
43
|
+
// Extra fields never replace the core ones.
|
|
44
|
+
for (const [k, v] of Object.entries(fields ?? {})) {
|
|
45
|
+
if (!(k in error) && v !== undefined)
|
|
46
|
+
error[k] = v;
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
isError: true,
|
|
50
|
+
content: [{ type: 'text', text: JSON.stringify({ error }, null, 2) }],
|
|
51
|
+
};
|
|
52
|
+
}
|
|
7
53
|
export function withErrorHandling(handler) {
|
|
8
54
|
return (async (...args) => {
|
|
9
55
|
try {
|
|
@@ -11,13 +57,7 @@ export function withErrorHandling(handler) {
|
|
|
11
57
|
}
|
|
12
58
|
catch (err) {
|
|
13
59
|
if (err instanceof ApiError) {
|
|
14
|
-
return {
|
|
15
|
-
isError: true,
|
|
16
|
-
content: [{ type: 'text', text: JSON.stringify({
|
|
17
|
-
error: { code: err.code, message: err.message, retryable: err.retryable,
|
|
18
|
-
...(err.retryable ? { retryAfterMs: err.retryAfterMs ?? 5000 } : {}) }
|
|
19
|
-
}, null, 2) }],
|
|
20
|
-
};
|
|
60
|
+
return errorResult(err.code, err.message, { retryable: err.retryable, retryAfterMs: err.retryAfterMs, fields: err.fields });
|
|
21
61
|
}
|
|
22
62
|
// Non-ApiError (unexpected internal fault). Cap the raw message so a
|
|
23
63
|
// large/exotic error string can't flood the agent's context.
|
package/dist/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;
|
|
1
|
+
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAExC,MAAM,UAAU,UAAU,CAAC,IAAa;IACtC,OAAO;QACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;KAC1E,CAAA;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,EAAU;IAClD,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,GAAG,CAAM,wBAAwB,EAAE,EAAE,CAAC,CAAA;QACxD,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,CAAA;QACpC,IAAI,IAAI;YAAE,OAAO,IAAI,CAAA;IACvB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,GAAG,YAAY,QAAQ,IAAI,CAAC,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,EAAE,CAAC;YAC1E,IAAI,CAAC;gBACH,MAAM,GAAG,GAAG,MAAM,GAAG,CAAM,8BAA8B,EAAE,EAAE,CAAC,CAAA;gBAC9D,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,IAAI,CAAA;gBACnC,IAAI,IAAI;oBAAE,OAAO,IAAI,CAAA;YACvB,CAAC;YAA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AC,SAAS,EAAE,YAAY,EAAE,GAAG,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAA;YAC7H,CAAC;YACD,qEAAqE;YACrE,6DAA6D;YAC7D,MAAM,UAAU,GAAI,GAAa,EAAE,OAAO,IAAI,eAAe,CAAA;YAC7D,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,CAAA;YACrF,OAAO;gBACL,OAAO,EAAE,IAAI;gBACb,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;4BACtD,KAAK,EAAE,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE;yBAC7D,CAAC,EAAE,CAAC;aACN,CAAA;QACH,CAAC;IACH,CAAC,CAAM,CAAA;AACT,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,7 @@ import { registerAuthTools } from './tools/auth.js';
|
|
|
11
11
|
import { registerMarketTools } from './tools/market.js';
|
|
12
12
|
import { registerPortfolioTools } from './tools/portfolio.js';
|
|
13
13
|
import { registerStrategyTools } from './tools/strategy.js';
|
|
14
|
+
import { registerStrategyLabTools } from './tools/strategy-lab.js';
|
|
14
15
|
import { registerBacktestTools } from './tools/backtest.js';
|
|
15
16
|
import { registerBotTools } from './tools/bot.js';
|
|
16
17
|
import { registerTradeTools } from './tools/trades.js';
|
|
@@ -28,6 +29,7 @@ function createServer(transport) {
|
|
|
28
29
|
registerMarketTools(server);
|
|
29
30
|
registerPortfolioTools(server);
|
|
30
31
|
registerStrategyTools(server);
|
|
32
|
+
registerStrategyLabTools(server);
|
|
31
33
|
registerBacktestTools(server);
|
|
32
34
|
registerBotTools(server);
|
|
33
35
|
registerTradeTools(server);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WAAW,CAAC,CAAA;IACtB,CAAC,CAAC,CAAA;IAEF,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE;QACtC,OAAO,CAAC,GAAG,CAAC,yBAAyB,OAAO,iCAAiC,IAAI,EAAE,CAAC,CAAA;QACpF,OAAO,CAAC,GAAG,CAAC,8BAA8B,IAAI,MAAM,CAAC,CAAA;QACrD,OAAO,CAAC,GAAG,CAAC,4BAA4B,IAAI,SAAS,CAAC,CAAA;IACxD,CAAC,CAAC,CAAA;AACJ,CAAC;KAAM,CAAC;IACN,wEAAwE;IACxE,MAAM,MAAM,GAAG,YAAY,CAAC,OAAO,CAAC,CAAA;IACpC,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAA;IAC5C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AACjC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"backtest.d.ts","sourceRoot":"","sources":["../../src/tools/backtest.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;
|
|
1
|
+
{"version":3,"file":"backtest.d.ts","sourceRoot":"","sources":["../../src/tools/backtest.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AAmBxE,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,QAyFtD"}
|
package/dist/tools/backtest.js
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { api, ApiError } from '../api.js';
|
|
3
|
-
import { jsonResult, withErrorHandling } from '../helpers.js';
|
|
3
|
+
import { jsonResult, withErrorHandling, resolveStrategyName } from '../helpers.js';
|
|
4
|
+
// GET /api/backtests/:id returns the real metrics flat under `metrics`, not
|
|
5
|
+
// nested in a `results` wrapper (that field doesn't exist on the response at
|
|
6
|
+
// all) -- and the metric keys are totalReturnPercent/maxDrawdownPercent, not
|
|
7
|
+
// roi/maxDrawdown. Reading `result.results || result` then `.roi`/`.maxDrawdown`
|
|
8
|
+
// silently produced an all-undefined metrics object on every real backtest.
|
|
9
|
+
function extractMetrics(result) {
|
|
10
|
+
const m = result?.metrics || {};
|
|
11
|
+
return {
|
|
12
|
+
totalReturnPercent: m.totalReturnPercent,
|
|
13
|
+
winRate: m.winRate,
|
|
14
|
+
totalTrades: m.totalTrades,
|
|
15
|
+
maxDrawdownPercent: m.maxDrawdownPercent,
|
|
16
|
+
sharpeRatio: m.sharpeRatio,
|
|
17
|
+
profitFactor: m.profitFactor,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
4
20
|
export function registerBacktestTools(server) {
|
|
5
21
|
server.tool('what_if_backtest', 'Run a backtest on a strategy. Async, may take 30-120 seconds. Returns full performance metrics.', {
|
|
6
22
|
strategyId: z.string().describe('Strategy ID to backtest'),
|
|
@@ -14,7 +30,12 @@ export function registerBacktestTools(server) {
|
|
|
14
30
|
const months = { '1m': 1, '3m': 3, '6m': 6, '1y': 12 };
|
|
15
31
|
const startDate = new Date(now);
|
|
16
32
|
startDate.setMonth(startDate.getMonth() - (months[period] || 3));
|
|
17
|
-
|
|
33
|
+
// Real strategy name, not a generic placeholder -- this is what shows up
|
|
34
|
+
// in the completion Telegram notification and the dashboard backtest
|
|
35
|
+
// list, and "MCP Backtest ETH/USDT:USDT 3m" told the user nothing about
|
|
36
|
+
// which strategy actually ran.
|
|
37
|
+
const strategyName = await resolveStrategyName(strategyId);
|
|
38
|
+
const name = `${strategyName} — ${symbol} ${period}`;
|
|
18
39
|
const job = await api('/api/backtests', {
|
|
19
40
|
method: 'POST',
|
|
20
41
|
body: { name, strategyId, exchangeId, symbol, timeframe, startDate: startDate.toISOString(), endDate: now.toISOString(), initialBalance },
|
|
@@ -29,12 +50,15 @@ export function registerBacktestTools(server) {
|
|
|
29
50
|
await new Promise(r => setTimeout(r, 3000));
|
|
30
51
|
try {
|
|
31
52
|
const result = await api(`/api/backtests/${jobId}`);
|
|
32
|
-
if (result.status === 'completed'
|
|
33
|
-
const
|
|
53
|
+
if (result.status === 'completed') {
|
|
54
|
+
const metrics = extractMetrics(result);
|
|
55
|
+
const end = typeof metrics.totalReturnPercent === 'number'
|
|
56
|
+
? initialBalance * (1 + metrics.totalReturnPercent / 100)
|
|
57
|
+
: undefined;
|
|
34
58
|
return jsonResult({
|
|
35
59
|
status: 'completed', strategy: strategyId, symbol, period,
|
|
36
|
-
metrics
|
|
37
|
-
equity: { start: initialBalance, end
|
|
60
|
+
metrics,
|
|
61
|
+
equity: { start: initialBalance, end },
|
|
38
62
|
});
|
|
39
63
|
}
|
|
40
64
|
if (result.status === 'failed') {
|
|
@@ -53,11 +77,10 @@ export function registerBacktestTools(server) {
|
|
|
53
77
|
jobId: z.string().describe('Backtest job ID'),
|
|
54
78
|
}, withErrorHandling(async ({ jobId }) => {
|
|
55
79
|
const result = await api(`/api/backtests/${jobId}`);
|
|
56
|
-
if (result.status === 'completed'
|
|
57
|
-
const r = result.results || result;
|
|
80
|
+
if (result.status === 'completed') {
|
|
58
81
|
return jsonResult({
|
|
59
82
|
status: 'completed',
|
|
60
|
-
metrics:
|
|
83
|
+
metrics: extractMetrics(result),
|
|
61
84
|
});
|
|
62
85
|
}
|
|
63
86
|
return { content: [{ type: 'text', text: `Status: ${result.status || 'pending'}. Try again in a few seconds.` }] };
|
|
@@ -66,17 +89,13 @@ export function registerBacktestTools(server) {
|
|
|
66
89
|
id: z.string().describe('Backtest ID'),
|
|
67
90
|
}, withErrorHandling(async ({ id }) => {
|
|
68
91
|
const result = await api(`/api/backtests/${id}`);
|
|
69
|
-
if (result.status !== 'completed'
|
|
92
|
+
if (result.status !== 'completed') {
|
|
70
93
|
return { content: [{ type: 'text', text: `Backtest ${id} is not completed yet (status: ${result.status || 'unknown'}). Wait for completion before exporting.` }] };
|
|
71
94
|
}
|
|
72
|
-
const r = result.results || result;
|
|
73
95
|
return jsonResult({
|
|
74
96
|
id,
|
|
75
97
|
status: 'completed',
|
|
76
|
-
metrics:
|
|
77
|
-
roi: r.roi, totalPnl: r.totalPnl, maxDrawdown: r.maxDrawdown,
|
|
78
|
-
winRate: r.winRate, sharpeRatio: r.sharpeRatio, totalTrades: r.totalTrades,
|
|
79
|
-
},
|
|
98
|
+
metrics: extractMetrics(result),
|
|
80
99
|
exportLinks: {
|
|
81
100
|
csv: `/api/backtests/${id}/export/csv`,
|
|
82
101
|
pdf: `/api/backtests/${id}/export/pdf`,
|