/ninjatrader:trade-replayfrom NinjaTrader
Reconstructs a single closed trade's MFE/MAE from bar OHLC and runs counterfactual exit scenarios (fixed R target, ATR trailing stop, breakeven, time-based). For NinjaTrader users analyzing trade execution quality.
Ships in NinjaTrader. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Answer deep questions about ONE closed trade, or a small set of them. Where did the trade peak? How close did MAE come to the stop? What do four alternate exit rules return, on the same bar window?
Demo (simulation) and live are two separate MCP servers. Account names are unique to one server. Once a workflow resolves an account on a server, every downstream call must go through that same server. This includes my_portfolio, market_snapshot, place_order, create_alert, history tools, etc. Cross-routing fails or hits the wrong environment.
Tool names below are bare. The NinjaTrader MCP server provides them. Your client adds its own prefix. See AGENTS.md at the repo root.
position_history — closed-position pairs
with entry/exit prices and timesfill_history — fill-level timestamps for
trades not fully covered by position_historymarket_history — bar OHLC across the trade
lifetime + a short lookback after for counterfactual runssearch_contracts — tickSize,
valuePerPoint for the trademarket-context's atr.py — ATR for atr_trail scenariostrade-journal's streaks.py — if the user references a trade
that is not in position_history's aggregation, use this to pair
fills into tradesThe user names a trade by date/time/symbol or picks from a recent list. Resolve via position_history:
position_history(
account=<acct>,
startDate=<YYYY-MM-DD>,
endDate=<YYYY-MM-DD>
)
(startDate and endDate are date-level. They use YYYY-MM-DD or a natural term like "yesterday", never a timestamp.)
Take avgBuyPrice / avgSellPrice (or buyPrice / sellPrice), boughtTimestamp / soldTimestamp, pairedQty, symbol — derive direction from the sign of netPos. Fetch contract specs via search_contracts for tickSize + valuePerPoint.
The caller must also know planned_stop_points — the stop distance the user chose at trade entry. This value denominates the R-multiple outputs and adverse_used_pct_of_stop. A wrong guess silently mis-scales every counterfactual. Source options, in order of preference:
pretrade-risk's recorded output (if the trade went through
that skill).Descriptive asks do not block on the stop value. A descriptive ask is a question such as "how far did it go my way / against me?" or MFE/MAE. For such an ask, run the replay immediately, without planned_stop_points. excursion.py handles its absence and emits null R-fields. Report excursion in points and dollars. Note "no stop distance on record — R-multiples omitted". Offer to recompute in R, if the user supplies the stop. Only R-denominated outputs and stop-referencing counterfactuals, such as breakeven_after, atr_trail, and R-targets, need a value up front.
market_history(
symbol=<sym>,
barType="Minute",
barSize=1,
from=<entry_time - 1min, ISO-8601>,
to=<exit_time + 15min, ISO-8601> # buffer for what-ifs that might exit later
)
(from requires to. If you pass only one, it errors.)
The 15-min post-exit buffer lets counterfactuals explore "what if I'd held longer", so the bar scan does not run out of data.
Save the trade-with-bars payload to a file. Pass its path with --file. Never re-type or inline a large JSON payload in the command.
python3 scripts/excursion.py --file trade_with_bars.json
Output fields:
realized.{points,dollars,R} — actual trade P&Lmfe.{points,dollars,R,at_timestamp,at_price} — peak favorablemae.{points,dollars,R,at_timestamp,at_price} — peak adversederived.giveback_from_mfe_pct — (mfe − realized) / mfe × 100derived.realized_vs_mfe_pct — realized / mfe × 100derived.adverse_used_pct_of_stop — mae / planned_stop × 100derived.hold_minutesChoose a scenario based on user intent. See references/replay-patterns.md for the catalog:
| User phrasing | Script invocation |
|---|---|
| "What if 2R target?" | whatif.py --scenario r_target --r-target 2.0 |
| "What if a 1×ATR trail?" | whatif.py --scenario atr_trail --atr-points <atr> --atr-multiple 1.0 |
| "What if breakeven after 1R?" | whatif.py --scenario breakeven_after --trigger-R 1.0 |
| "What if I'd held 30 min?" | whatif.py --scenario time_exit --minutes 30 |
Each run produces:
exit.{triggered,time,price,reason} — whether the scenario fired
and whererealized.{points,dollars,R} — simulated P&Lvs_actual.{delta_points,delta_dollars,delta_R} — vs the user's
actual exit, when the trade input includes actual_exit_priceFor "which rule would have won?" questions, run each scenario in sequence. Rank the results by vs_actual.delta_dollars. There is no batch.py script. Just call whatif.py N times in the workflow:
for spec in \
"r_target --r-target 2.0" \
"r_target --r-target 3.0" \
"atr_trail --atr-points 8 --atr-multiple 1.0" \
"breakeven_after --trigger-R 1.0"; do
python3 scripts/whatif.py --file trade_with_bars.json --scenario $spec
done
When the user's question implies a rule they might adopt ("should I start using 2R targets?"), include the survivorship caveat from references/survivorship-caveat.md:
"One-trade counterfactual. For a rule-level evaluation across your book, route through
trade-debrief."
For descriptive-only asks ("how far did it go?"), skip the caveat.
MFE + giveback:
"Long 4 ES @ 7150, exited 7164 (+$2,800 / 1.75R). MFE +22.5 pts (+$4,500 / 2.8R) at 14:02 — left $1,700 on the table. MAE only 1 pt (used 12% of your 8-pt stop). Held 47 min."
Single what-if:
"With a 2R target (7166), you'd have exited at 13:52 for +$3,200 — $400 better than your actual $2,800. One-trade counterfactual, not a rule endorsement."
Multi-scenario compare:
"Ranked by $ vs your actual $2,800:
- time_exit 30min (exit 14:02 @ 7168.75): +$3,750 (+$950)
- r_target 2.0 (exit 13:52 @ 7166): +$3,200 (+$400)
- atr_trail 1×ATR (exit 14:07 @ 7164.50): +$2,900 (+$100)
- r_target 3.0 (never hit, fell through): +$2,250 (−$550)
- breakeven_after 1R (armed, fell through): +$2,250 (−$550)
Patient rules (time_exit, r_target 2.0) beat your actual exit by $400-950. Tighter rules (atr_trail) roughly matched. Breakeven pin was tied with the hopeful 3R target at the bottom — classic wait-too-long pattern. Still just one trade — run across N trades in
trade-debriefif you're serious about a rule change."
trade-journal: journal is many-trades descriptive —
streaks, hold times, slippage.
Replay is a one-trade deep dive.
For "how far did trade #3 go today?", use replay.
For "how did I trade today?", use journal.trade-debrief: debrief synthesizes mistake, pattern, and
rule mining across a whole session, with the trade-debrief prompt
library. Replay gives numeric counterfactuals on one trade. Use
debrief when the user asks for prescriptive rules.position-watchdog: watchdog's what-if runs on the
currently OPEN position (live). Replay covers closed trades. Do
not use replay on an open position. The bars are not all there
yet.planned_stop_points.
Explain this to the user.scripts/excursion.py — MFE/MAE + derived metrics for one trade.
Same math family as trade-debrief/scripts/compute_derived.py.
Keep them in sync when the math evolves. Returns realized, mfe,
mae, and a derived sub-object.scripts/whatif.py — counterfactual exit simulator. Four scenarios:
r_target, atr_trail, breakeven_after, time_exit. Input is
one trade plus bars. Output is the hypothetical exit, the realized
stats, and the delta vs actual.scripts/fixtures/es_long_trade.json — one ES long trade (4 @ 7150
→ 7164 in 47 min) with 11 1-min bars covering entry through 15min
post-exit. The skill uses it to smoke-test all four scenarios.references/replay-patterns.md — the 7-entry what-if library with
script invocations, common parameter values, and interpretation
notes. Load it when you choose a what-if scenario.references/survivorship-caveat.md — mandatory framing for rule-
shaped what-ifs. When NOT to cite it and what to route the user to
instead (trade-journal, trade-debrief).What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
trade-analysis, mfe-mae, counterfactual-exits, ninjatrader, trading
13 skills in this plugin
/alerts-composerTranslates natural-language alert intent into a validated Tradovate alert-DSL expression. Submits the expression via create_alert.expression. Covers 37 numeric functions across Account (netLiq, dollarOpenPL, dailyLossLimit, ...) and Contract (lastPrice, percentChange, settlementPrice, ...) entities. Also covers Position (netPos, posOpenPLUsd, posInitMarginUsd, ...) and Currency (currentRate) entities. Supports arithmetic (plus, minus, times, divide, parens), comparison (gt, gte, lt, lte, eq, neq), and top-level AND/OR/XOR logic. Validates the expression offline (subject syntax, function catalog, paren balance, flat-logic rule) before submission. Use when the user says "alert", "notify", "notify me", "watch for", "wake me when", "tell me when", "heads up when", "ping me if", "set a trigger", or "let me know if". Also use when the user asks about a sibling skill's proposed alert expression. position-watchdog, event-watch, and pretrade-risk also submit their proposed expressions through this skill./chart-renderThis skill renders three static PNG charts, with Matplotlib. Candlestick charts, with VWAP, fill-marker, and price-level overlays. Horizontal volume-profile histograms, with POC, VAH, and VAL lines. Cumulative-P&L equity curves, with optional drawdown shading. Chart data comes from market_history bars, fill_history fills, market-context analytics, and trade-journal round-trip trades. Use it when the user asks to "chart", "plot", "draw", "visualize", or "render". Also use it when the user wants a picture of the bars, fills, equity, or profile. Also use it for a qualified "show", such as "show the chart", "show me the bars", or "show my equity curve". A bare "show me my positions" is NOT a chart request. Route it to position-watchdog or my_portfolio. It produces PNG output at a specified path. It is never interactive. This skill requires matplotlib (install with `pip install matplotlib`)./contract-intelSymbol discovery, front-month resolution, rollover-imminence classification, and product-family awareness (full ↔ micro pairs like ES/MES) for futures contracts. Resolves bare product codes like "ES" or "NQ" to the actual tradeable front-month contract (e.g., ESU6) by open-interest rank across maturities. Classifies rollover status as not_imminent / approaching / imminent / rolled, with calendar-spread candidate flag when both legs are liquid. Use when the user asks "what symbol", "which contract to trade", "front month", "roll" or "rollover", "micro" or "full", or "calendar spread". Also use when the user gives a bare product code (ES, NQ, YM, CL, GC, etc.) without a maturity. Also handles product-family metadata via search_contracts includeFamilySiblings flag./correlation-hedgeCompute historical Pearson correlation and OLS regression beta between two futures symbols, on log-returns. Turn that result into a dollar-neutral hedge proposal for an open position. Covers cross-underlying relationships — ES vs NQ, CL vs NG, GC vs SI, bonds vs stocks, and currencies vs DX. For same-underlying siblings like ES/MES, use contract-intel instead. Produces sized hedge candidates with raw qty, rounded qty, residual exposure percentage, and coverage percentage. Always informational — never emits order payloads. Use when the user asks about "correlation between X and Y", "hedge this", "how do I hedge", "what could I short to offset", "beta", "X vs Y correlation", "cross-asset", "co-move", "correlated exposure", or "am I already long the market"./event-watchCovers a high-volatility economic event calendar — FOMC, CPI, NFP, EIA, and OPEC. Also covers earnings-season awareness and session-boundary context — globex open, NY cash open, settlement, and EIA release windows. Reports upcoming events and filters them by the user's current positions. Explains a move after it happens (for example, "ES +24pts in 8min matches the hot CPI print"). Computes historical reaction-size magnitudes from prior releases. Proposes reaction-window bracket alerts via alerts-composer. It is strictly reactive, with no timer-based push. Use when the user asks "what's coming up", "economic calendar", "why did it move", "NY cash open", or "session open". Also use when the user names a specific event — CPI, FOMC, NFP, EIA, OPEC, or earnings./market-contextComputes market metrics for futures from market_history output. Metrics include session VWAP, POC/VAH/VAL (value area), bar-level delta, cumulative delta, order-flow imbalance, ATR(N), realized volatility, and cross-symbol relative strength. It produces narrative summaries of market structure and the volatility regime. Use when the user asks about VWAP, POC, market profile, or value area. Also use for ATR, realized volatility, delta, cumulative delta, or order-flow imbalance. Also use for the volatility regime, or for intra-day relative strength between related symbols (e.g., ES vs NQ vs RTY). position-watchdog, pretrade-risk, scale-manager, chart-render, trade-replay, and trade-debrief consume this skill's output as input.npx claudepluginhub nt-ninjatrader/mcp-skills --plugin ninjatraderOther plugins' skills for the same job