/ninjatrader:correlation-hedgefrom NinjaTrader
Computes historical Pearson correlation and OLS regression beta between two futures symbols on log-returns, then sizes a dollar-neutral hedge proposal for an open position. Covers cross-underlying pairs like ES/NQ, CL/NG, GC/SI, bonds/stocks, currencies/DX.
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.
Two linked jobs:
Symbol/market data only — no account binding. A sibling skill's account resolution might already pin the session to demo (simulation) or live. If so, stay on that same MCP server.
Tool names below are bare. The NinjaTrader MCP server provides them. Your client adds its own prefix. See AGENTS.md at the repo root.
market_history — aligned bar closes for two symbols over the lookback windowmy_portfolio — open positions for hedge-mode input (qty, netPrice). Prune with fields=["positions[].symbol","positions[].netPos","positions[].netPrice","account.netLiq"].market_snapshot — valuePerPoint, tickSize, current mark for the hedge candidate. Prune with fields=["snapshots[].symbol","snapshots[].valuePerPoint","snapshots[].tickSize","snapshots[].lastPrice"].search_contracts — resolve bare product codes to contract symbols for both legsuser_profile — discover available account names when the account is unknown| User phrasing | Mode |
|---|---|
| "correlation between X and Y", "X vs Y", "how correlated" | correlation only |
| "hedge my ES", "what should I short to offset" | correlation → hedge sizing |
| "am I already long the market?" | correlation + portfolio cross-check |
| "beta of NQ on ES" | correlation (β output) |
Pick a lookback (default 30–90 sessions for cross-family, 5–30 sessions for within-family):
market_history(symbol=SYM_A, barType="Daily", barSize=1, from=<ISO-8601>, to=<ISO-8601>)
market_history(symbol=SYM_B, barType="Daily", barSize=1, from=<ISO-8601>, to=<ISO-8601>)
For hourly bars use barType="Minute", barSize=60. from requires to. For "last N bars", pass count= instead of a range.
Bar-size choice matters:
Save the two symbols' market_history responses to a file (shape {"series": {SYM_A: [...], SYM_B: [...]}}) and pass its path with --file. Never re-type or inline the bar arrays into the command.
python3 scripts/correlation.py --file series.json --window 30
The script aligns bars on shared timestamps, computes log returns, then reports:
pearson_r — linear correlation of returns (−1 to 1)beta_B_on_A — OLS slope of B's returns regressed on A's. Use A as the position symbol, B as the hedge candidate.vol_A, vol_B — return stdev of eachrolling (optional, with --window) — current r vs rolling mean/stdev + regime flag (tightening/loosening/stable)Compare to priors in references/hedge-patterns.md. If the live r is way outside the typical range for that pair, call it out. The cause may be a regime shift, a data quality issue, or a rare moment.
Account resolution. Position data (qty, direction, basis) comes from my_portfolio(account=<name>) — the MCP requires account=. If the account name is unknown, call user_profile() first and pull accounts[].name to discover available accounts.
Pull the position + hedge candidate market snapshot, then:
python3 scripts/hedge_sizing.py --file hedge_input.json
where hedge_input.json holds the position + hedge candidate:
{
"position": {
"symbol": "ESU6", "direction": "long", "qty": 4,
"price": 7170.0, "value_per_point": 50.0
},
"hedge_candidate": {
"symbol": "NQU6", "price": 22640.0, "value_per_point": 20.0,
"beta": 2.59
}
}
Output fields:
hedge.side — Buy or Sell. Opposite of the position side when β > 0 (typical); same side when β < 0 (stock/bond hedge).hedge.raw_qty — unrounded contracts (e.g., 3.4 NQ)hedge.rounded_qty — whole contracts at --round mode (nearest/up/down)hedge.residual_pct — |raw - rounded| / raw × 100coverage.coverage_pct — how much of the $ exposure the rounded hedge actually coverscoverage.residual_exposure_dollars — uncovered $ per 1%When rounded_qty = 0 or residual_pct > 30%, the script emits a note that suggests a micro (MES/MNQ/MCL/MGC) for finer sizing. Surface that verbatim.
Run hedge_sizing.py N times with different candidates. Rank by coverage_pct near 100% with low residual_pct. Pick the best trade-off between coverage and rounding precision.
This skill ships no basket.py script. Loop over the candidates instead:
for cand in 'NQ 22640 20 2.59' 'MES 7170 5 1.0' 'YM 43500 5 0.9' 'RTY 2400 50 0.7'; do
# build JSON, pipe to hedge_sizing.py, collect coverage_pct
done
Pair the sizing output with the live correlation, so the user sees the assumption behind it. See references/regime-caveat.md for framing patterns.
Correlation-only:
"ES/NQ over last 16 daily bars: Pearson r 0.99 (very tight), β_NQ_on_ES = 2.59 (NQ moves ~2.6× ES in log returns over this window). Rolling 8-bar window shows r stable at 0.99. This is slightly above the typical 0.85-0.95 range — tight regime."
Hedge proposal:
"You're long 4 ES @ 7170 ($14,340 per 1% ES move).
Short 1 NQ at 22640 covers 82% ($11,739 offset). Residual $2,601 long ES. One-NQ rounds down from raw 1.22; a second NQ would over-hedge. Consider 1 NQ + 2 MNQ for finer coverage.
Math assumes ES/NQ correlation holds (0.99 tight right now, but pairs can decouple in regime shifts). This isn't a guaranteed protection — it's a dollar-neutral offset conditional on the correlation staying similar."
Portfolio cross-check:
"You're long 4 ES AND long 2 NQ. With β=2.59, the 2 NQ longs are effectively +5.2 ES-equivalents of additional exposure — you're 9.2 ES-equivalents long the market, not 6. If that's not intended, consider flattening one or adjusting size."
contract-intel: contract-intel handles SAME-underlying pairs (ES vs MES — fungible siblings). correlation-hedge handles CROSS-underlying (ES vs NQ, CL vs NG). Different math, different use cases.market-context's cross_symbol.py: that script does INTRADAY relative strength (who led today). correlation-hedge does HISTORICAL correlation over a lookback window. Distinct semantics — do not mix them.scale-manager: this skill is informational (what is the hedge?). scale-manager converts a hedge decision into exact place_order payloads. Run correlation-hedge first, then route the chosen hedge through scale-manager for the execution plan.position-watchdog: watchdog reports current position health per-symbol. correlation-hedge reports cross-symbol exposure interactions. They are complementary.references/regime-caveat.md).event-watch for event-window alert sizing instead.scripts/correlation.py — time-aligned Pearson r + OLS β on log returns of two symbols. Supports --window N for rolling r with regime flagging. Requires ≥3 overlapping bars minimum.scripts/hedge_sizing.py — dollar-neutral hedge sizing from position + hedge candidate + β. Reports raw/rounded qty, coverage %, residual $ exposure. Flags rounded=0 and residual>30% with micro-contract suggestion. Supports --round nearest|up|down.scripts/fixtures/es_nq_synthetic.json — a 17-bar ES+NQ fixture that produces a near-perfect correlation, for smoke testing.references/hedge-patterns.md — typical correlation ranges for 7 product families (equity indexes, energy, metals, bonds, currencies, grains, cross-family). Priors only — always validate with live data. Load it when you compare a live r or β to the typical range.references/regime-caveat.md — the stationarity-assumption framing. It explains how to narrate a hedge honestly, when to flag a regime shift, and why tail risk matters. Load it when you narrate a hedge recommendation.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub nt-ninjatrader/mcp-skills --plugin ninjatrader13 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./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./position-watchdogReports the live health of open futures positions. Output covers open P&L in dollars and R, and distance to stop (ticks, dollars, % of the daily loss budget). It also covers R-achieved to target, time in trade, and margin utilization. It also lists guardrail flags (no stop attached, a stop moved against entry, correlated index exposure). It also gives informational what-if math — move stop, extend target, go breakeven. It also detects stop drift from order history. A trailed stop means less risk. A widened stop means more risk. Use when the user asks "how am I doing", "what's my P&L", "how much am I up", "am I up or down", "position health", "my positions", "where's my stop", or "how close to stop". Also use when the user asks "am I in trouble", "daily loss", "margin usage", "am I safe", "what if I move my stop to X", "what if I extend target", "should I go breakeven", or "has my stop been moved". For closed-position analysis use trade-replay. For exact order payloads to execute, use scale-manager.Other plugins' skills for the same job