bushido-tradingview-mcp 0.1.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 (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +479 -0
  3. package/build/analysisAlerts.js +85 -0
  4. package/build/analysisJournal.js +656 -0
  5. package/build/analysisOutcome.js +352 -0
  6. package/build/analysisOverlay.js +379 -0
  7. package/build/analysisPerformance.js +180 -0
  8. package/build/bojPolicyDecisionCollection.js +74 -0
  9. package/build/bookmapFlow.js +201 -0
  10. package/build/boundedResponse.js +66 -0
  11. package/build/businessDays.js +27 -0
  12. package/build/calendar.js +134 -0
  13. package/build/calibration.js +17 -0
  14. package/build/canonicalDefinition.js +29 -0
  15. package/build/carryPanelBootstrap.js +114 -0
  16. package/build/carryPanelDependence.js +82 -0
  17. package/build/carryPanelPreflight.js +68 -0
  18. package/build/carryPanelPrimaryReadiness.js +62 -0
  19. package/build/carryPanelPrimaryTest.js +248 -0
  20. package/build/cdp.js +209 -0
  21. package/build/chartHistory.js +74 -0
  22. package/build/chartOperationLock.js +120 -0
  23. package/build/chartTransaction.js +125 -0
  24. package/build/cmeDailyBulletin.js +109 -0
  25. package/build/collectionCli.js +75 -0
  26. package/build/compositeConditionStudy.js +630 -0
  27. package/build/correlationRegimes.js +60 -0
  28. package/build/costModel.js +19 -0
  29. package/build/cot.js +346 -0
  30. package/build/cotCrowdingUnwind.js +142 -0
  31. package/build/cotCrowdingUnwindOverlay.js +81 -0
  32. package/build/cotFirstSeenHistory.js +93 -0
  33. package/build/crossAssetShockOutcome.js +65 -0
  34. package/build/crossAssetShockPreflight.js +96 -0
  35. package/build/crossAssetShockState.js +150 -0
  36. package/build/dueAnalyses.js +72 -0
  37. package/build/dxyContextGate.js +13 -0
  38. package/build/effectiveMultiplicity.js +239 -0
  39. package/build/evaluate.js +55 -0
  40. package/build/evaluationLog.js +189 -0
  41. package/build/evaluationMetrics.js +10 -0
  42. package/build/evaluationPipeline.js +118 -0
  43. package/build/eventAftershockRetestStudy.js +230 -0
  44. package/build/eventStudyFalsificationAudit.js +246 -0
  45. package/build/eventStudyFalsificationCli.js +76 -0
  46. package/build/executionSnapshot.js +370 -0
  47. package/build/exploratoryCarrySigns.js +48 -0
  48. package/build/externalLabelStudy.js +274 -0
  49. package/build/failedBreakoutStudy.js +152 -0
  50. package/build/falsificationAudit.js +157 -0
  51. package/build/featureOutcomeFalsificationAudit.js +47 -0
  52. package/build/featureOutcomePowerAudit.js +165 -0
  53. package/build/featureOutcomeRelationships.js +846 -0
  54. package/build/firstSeenCollection.js +76 -0
  55. package/build/firstSeenStore.js +219 -0
  56. package/build/futuresFlowContext.js +340 -0
  57. package/build/futuresOpenInterestCmeCleanupMigration.js +46 -0
  58. package/build/futuresOpenInterestHistory.js +233 -0
  59. package/build/futuresOpenInterestMigration.js +46 -0
  60. package/build/fvgRetestStudy.js +361 -0
  61. package/build/fxCsvFeatureScanCli.js +227 -0
  62. package/build/fxCsvM1Aggregation.js +154 -0
  63. package/build/fxCsvM1AggregationCli.js +132 -0
  64. package/build/fxHistoricalArchive.js +81 -0
  65. package/build/fxHistoryCollectionCli.js +41 -0
  66. package/build/index.js +41 -0
  67. package/build/indicatorAudit.js +34 -0
  68. package/build/instrumentMetadata.js +11 -0
  69. package/build/leadLagFalsificationAudit.js +66 -0
  70. package/build/leadLagRelationships.js +770 -0
  71. package/build/macroEvent60mCli.js +43 -0
  72. package/build/macroEvent60mPreflight.js +98 -0
  73. package/build/macroEvent60mPreflightCli.js +46 -0
  74. package/build/macroEvent60mStudy.js +100 -0
  75. package/build/macroEventResponse.js +498 -0
  76. package/build/macroEventResponseCli.js +71 -0
  77. package/build/macroSurpriseCoverage.js +106 -0
  78. package/build/macroSurpriseCoverageCli.js +35 -0
  79. package/build/macroSurpriseEvidence.js +342 -0
  80. package/build/marketRegimes.js +177 -0
  81. package/build/marketSnapshot.js +212 -0
  82. package/build/migrateFuturesOiCmeCleanupCli.js +12 -0
  83. package/build/migrateFuturesOiDatesCli.js +12 -0
  84. package/build/oandaFlow.js +169 -0
  85. package/build/oandaFlowCollectionCli.js +55 -0
  86. package/build/oandaHistoricalFx.js +247 -0
  87. package/build/officialMacroActualCollectionCli.js +33 -0
  88. package/build/officialMacroActualSources.js +109 -0
  89. package/build/officialMacroEventCollectionCli.js +32 -0
  90. package/build/officialMacroEventSources.js +242 -0
  91. package/build/officialPolicyRateCollectionCli.js +36 -0
  92. package/build/officialPolicyRateSources.js +528 -0
  93. package/build/openInterestReconciliation.js +50 -0
  94. package/build/outcomeLabel.js +8 -0
  95. package/build/pineAudit.js +24 -0
  96. package/build/policyRateCollection.js +20 -0
  97. package/build/policyRateCollectionCli.js +71 -0
  98. package/build/policyRateCollectionHeartbeat.js +96 -0
  99. package/build/policyRateContext.js +35 -0
  100. package/build/policyRateHistory.js +118 -0
  101. package/build/policyRateOfficialHistory.js +196 -0
  102. package/build/policyRateOfficialHistoryContext.js +41 -0
  103. package/build/policyRateOfficialRawArchive.js +91 -0
  104. package/build/positionSize.js +197 -0
  105. package/build/priceActionContext.js +455 -0
  106. package/build/priceActionTrapReproduction.js +229 -0
  107. package/build/priceActionTrapReproductionCli.js +56 -0
  108. package/build/rbaHistoricalF1Xls.js +257 -0
  109. package/build/realYield.js +414 -0
  110. package/build/realYieldHistory.js +140 -0
  111. package/build/redact.js +12 -0
  112. package/build/researchCollectionCli.js +246 -0
  113. package/build/researchCollectionHeartbeat.js +112 -0
  114. package/build/researchProtocol.js +112 -0
  115. package/build/scanner.js +229 -0
  116. package/build/server.js +8611 -0
  117. package/build/sessionAuctionStudy.js +691 -0
  118. package/build/sessionHandoffStudy.js +303 -0
  119. package/build/sessionProfile.js +338 -0
  120. package/build/strategyExperiment.js +104 -0
  121. package/build/strategyRegimeEvaluation.js +314 -0
  122. package/build/strategyResearchJournal.js +714 -0
  123. package/build/strategyStress.js +350 -0
  124. package/build/strategyWalkForward.js +242 -0
  125. package/build/strategyWalkForwardFalsificationAudit.js +219 -0
  126. package/build/syntheticNullSeries.js +225 -0
  127. package/build/tradeDecisionContext.js +402 -0
  128. package/build/tradePlan.js +206 -0
  129. package/build/tradingEconomicsMacroConsensus.js +124 -0
  130. package/build/tradingEconomicsMacroConsensusCli.js +50 -0
  131. package/build/tradingview.js +2309 -0
  132. package/build/volumeProfileContext.js +227 -0
  133. package/build/volumeProfileReactionStudy.js +756 -0
  134. package/build/walkForward.js +10 -0
  135. package/build/walkForwardCli.js +25 -0
  136. package/build/walkForwardReport.js +7 -0
  137. package/build/yieldPriceNonconfirmation.js +446 -0
  138. package/package.json +88 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tedorigawa001
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,479 @@
1
+ # TradingView-MCP
2
+
3
+ **Let an AI inspect your TradingView Desktop app and help analyze your charts.**
4
+
5
+ **100+ MCP tools** for chart inspection and control, indicators, Pine Script, backtesting, market research, falsification audits, point-in-time evidence, and cross-market analysis.
6
+
7
+ Register this server with an AI agent such as Claude Code, Codex, or Antigravity, and the agent can read the chart you are currently viewing. Your signed-in account, saved layouts, and purchased custom indicators remain available in the Desktop app.
8
+
9
+ ## What You Can Do
10
+
11
+ Example requests:
12
+
13
+ - "**Analyze the current chart.**" -> combine the chart image, candles, and indicator values.
14
+ - "**Read this indicator's signals.**" -> retrieve BUY/SELL labels and support/resistance values.
15
+ - "**Assess the market on both the daily and four-hour timeframes.**" -> retrieve multiple-timeframe evidence without moving the chart.
16
+ - "**Find Japanese stocks with RSI below 30.**" -> search the market scanner.
17
+ - "**Check every symbol in my watchlist.**" -> retrieve quotes for the complete list.
18
+
19
+ ## How It Works
20
+
21
+ TradingView Desktop is an Electron application. When launched with its debugging endpoint enabled, an external program can inspect the chart. This MCP server provides that bridge.
22
+
23
+ ```
24
+ AI agent <-> tradingview-mcp <-> TradingView Desktop (your chart)
25
+ <-> TradingView public APIs (quotes and scanner)
26
+ ```
27
+
28
+ ## Requirements
29
+
30
+ - macOS and [TradingView Desktop](https://www.tradingview.com/desktop/) (the free plan is sufficient)
31
+ - [Node.js](https://nodejs.org/) 22 or later (check with `node --version`; Node 20 is EOL)
32
+ - An AI agent such as [Claude Code](https://claude.com/claude-code), [Codex](https://developers.openai.com/codex), or [Antigravity](https://antigravity.google/)
33
+
34
+ Publishing from source additionally requires a JDK because `prepublishOnly`
35
+ runs the complete Node.js and Bookmap add-on test suites before npm accepts a
36
+ release. npm users do not need Java.
37
+
38
+ ## Setup in Three Steps
39
+
40
+ ### Step 1: Install the Server
41
+
42
+ In a terminal:
43
+
44
+ ```bash
45
+ npm install --global bushido-tradingview-mcp
46
+ ```
47
+
48
+ The installed command is `tradingview-mcp`. You normally do not run it by
49
+ itself; the AI agent starts it as an MCP stdio server. Node.js is the only
50
+ requirement; the Java add-on in this repository is not part of the package.
51
+
52
+ ### Step 2: Launch TradingView in Debug Mode
53
+
54
+ **Important:** The AI cannot inspect TradingView when it is launched normally from the app icon. If TradingView is running, quit it with Cmd+Q, then run:
55
+
56
+ ```bash
57
+ open -a TradingView --args --remote-debugging-port=9222
58
+ ```
59
+
60
+ To avoid typing the full command each time, add an alias and launch it with `tv`:
61
+
62
+ ```bash
63
+ echo 'alias tv="open -a TradingView --args --remote-debugging-port=9222"' >> ~/.zshrc
64
+ source ~/.zshrc
65
+ ```
66
+
67
+ ### Step 3: Register the MCP Server
68
+
69
+ Choose the instructions for your agent. The examples use `npx`, so a global
70
+ installation is optional and the agent can launch the published package
71
+ directly.
72
+
73
+ <details>
74
+ <summary><b>Claude Code</b></summary>
75
+
76
+ Run one command:
77
+
78
+ ```bash
79
+ claude mcp add tradingview -- npx -y bushido-tradingview-mcp
80
+ ```
81
+
82
+ Verify by running `/mcp` in Claude Code and confirming that `tradingview` appears.
83
+
84
+ </details>
85
+
86
+ <details>
87
+ <summary><b>Codex (OpenAI)</b></summary>
88
+
89
+ Option 1 - add it with the CLI:
90
+
91
+ ```bash
92
+ codex mcp add tradingview -- npx -y bushido-tradingview-mcp
93
+ ```
94
+
95
+ Option 2 - add it directly to `~/.codex/config.toml`:
96
+
97
+ ```toml
98
+ [mcp_servers.tradingview]
99
+ command = "npx"
100
+ args = ["-y", "bushido-tradingview-mcp"]
101
+ ```
102
+
103
+ Verify by running `/mcp` in Codex and confirming that `tradingview` appears.
104
+
105
+ </details>
106
+
107
+ <details>
108
+ <summary><b>Antigravity (Google)</b></summary>
109
+
110
+ Create or update `~/.gemini/config/mcp_config.json`:
111
+
112
+ ```json
113
+ {
114
+ "mcpServers": {
115
+ "tradingview": {
116
+ "command": "npx",
117
+ "args": ["-y", "bushido-tradingview-mcp"]
118
+ }
119
+ }
120
+ }
121
+ ```
122
+
123
+ From the IDE, open the same file from `...` -> `MCP Servers` -> `Manage MCP Servers` -> `View raw config` in the upper-right corner of the agent panel. Saving reloads it automatically.
124
+
125
+ </details>
126
+
127
+ ## Try It
128
+
129
+ With TradingView running in debug mode, ask your AI agent:
130
+
131
+ > Analyze the current chart.
132
+
133
+ The agent can combine tools such as `get_chart_context` (what is displayed), `get_chart_screenshot` (visual evidence), and `get_ohlcv` (numeric evidence).
134
+
135
+ ## Tools (101 Total)
136
+
137
+ The AI selects the appropriate tools automatically; you do not need to memorize them.
138
+
139
+ **Read charts**
140
+
141
+ | Tool | Description |
142
+ |---|---|
143
+ | `get_chart_context` | Lists the symbol, timeframe, and indicators for every visible chart |
144
+ | `get_chart_screenshot` | Captures the chart; `chart_index` can crop one chart at high resolution |
145
+ | `get_ohlcv` | Candle data with ISO timestamps and a `forming` flag for the live bar |
146
+ | `get_indicator_values` | Indicator plot values such as signals and bands |
147
+ | `get_indicator_inputs` | Indicator input names, current values, and defaults |
148
+ | `get_indicator_graphics` | Indicator labels, lines, and boxes, including Elliott Wave counts |
149
+ | `get_indicator_tables` | Indicator tables, such as MTF trend grids, reconstructed as cell matrices |
150
+ | `get_key_levels` | Aggregates sourced support and resistance within +/-N% of price |
151
+ | `load_more_history` | Loads additional historical candles without moving the viewport |
152
+
153
+ **Operate charts**
154
+
155
+ | Tool | Description |
156
+ |---|---|
157
+ | `set_symbol` | Changes the selected pane's symbol; defaults to the active pane and rolls back on failure |
158
+ | `set_timeframe` | Changes the selected pane's timeframe with the same rollback behavior |
159
+ | `set_indicator_input` | Temporarily changes indicator or strategy inputs without saving them |
160
+ | `get_replay_status` | Reads Bar Replay availability, state, and historical cursor time |
161
+ | `start_chart_replay` | Verifies symbol/timeframe and starts Replay after dry-run and confirmation |
162
+ | `step_chart_replay` | Advances a paused Replay by 1-100 bars and verifies time advancement |
163
+ | `stop_chart_replay` | Stops Replay after dry-run and confirmation and returns to real time |
164
+
165
+ **Data outside the chart**
166
+
167
+ | Tool | Description |
168
+ |---|---|
169
+ | `get_quotes` | Quotes and technicals such as RSI and aggregate ratings |
170
+ | `get_mtf_overview` | Batch snapshots for multiple symbols and timeframes without chart interference |
171
+ | `scan_market` | Market screening, for example Japanese stocks with RSI below 30 sorted by volume |
172
+ | `get_economic_events` | Economic calendar filtered by country and importance |
173
+ | `get_watchlist` | Your TradingView watchlist |
174
+ | `list_alerts` | Read-only list of your price alerts |
175
+ | `create_analysis_alerts` | Previews and idempotently creates expiring Confirmation, Invalidation, and Target 1 alerts after explicit confirmation |
176
+
177
+ **Market context and evaluation**
178
+
179
+ | Tool | Description |
180
+ |---|---|
181
+ | `get_market_snapshot` | Combines multiple markets, timeframes, and events in one acquisition window with explicit quality status |
182
+ | `get_execution_snapshot` | Normalizes bid/ask, spread, pip/tick, and feed mode; reports ready only after observing a post-request price update |
183
+ | `get_trade_decision_context` | Binds chart, OHLC, levels, MTF, events, COT, real yield, and bid/ask to one `snapshot_id`; blocks live execution evidence during Replay |
184
+ | `get_aligned_history` | Strictly aligns closed bars from multiple charts by UTC timestamp without forward filling |
185
+ | `compute_market_features` | Deterministically computes returns, ATR, volatility, and correlation from aligned history |
186
+ | `compute_market_regimes` | Classifies closed OHLC as trend/range/transition and low/normal/high volatility using only prior evidence and explicit thresholds; it does not optimize or recommend trades |
187
+ | `compute_correlation_regimes` | Classifies rolling return correlation between two exact chart bindings; uses closed bars matched by UTC timestamp without forward filling |
188
+ | `run_strategy_regime_analysis` | Runs an exact saved strategy temporarily, joins its full ledger to labels closed before entry, and reports PF, expectancy, win rate, drawdown, and coverage by directional, volatility, combined, and optional DST-aware session regimes; verifies cleanup and chart restoration |
189
+ | `run_strategy_regime_matrix` | Serially evaluates up to 12 symbol/timeframe/strategy jobs under one regime/session contract, optionally loading up to 20,000 bars per job; isolates failures, restores after every job, stops after restoration failure, and does not rank or pool currencies |
190
+ | `run_market_event_study` | Runs closed-OHLC event studies with exclusive branches, decision-time-correct session handoffs, same-timestamp policy, Bonferroni reference, returns, MFE/MAE, folds, confidence intervals, declared trials, and optional prior price/volatility regimes; FVG populations can be frozen by time window, direction, and regime |
191
+ | `run_event_study_falsification_audit` | Calibrates frozen FVG retest, session auction, and event-aftershock candidate rules against white-noise, regime-switching-volatility, and bid-ask-bounce synthetic OHLC; it does not access charts, networks, or journals or pool rates across models |
192
+ | `register_event_study_hypothesis` | Registers an immutable event-study or feature-study hypothesis and outcome contract in the local append-only research journal |
193
+ | `get_event_study_journal` | Lists hash-bound event-study evidence or compares exact selected records without accessing a chart |
194
+ | `get_dxy_context_gate_template` | Returns the fixed Pine template that reads confirmed DXY daily data with `lookahead_off` and exposes its return and gate plots |
195
+ | `run_yield_price_nonconfirmation_study` | Uses two exact charts to detect a target that fails to follow a confirmed driver and then breaks structure in the opposite direction; returns multi-horizon and fold-level return/MFE/MAE without exact-time matching or forward fill |
196
+ | `run_external_label_study` | Measures outcomes after caller-supplied point labels such as daily OI; requires at least one-bar lag, rejects zero lag, supports daily/weekly data, and guarantees point-in-time behavior only for the join, not the supplied labels |
197
+ | `compute_lead_lag_relationships` | Joins closed returns by exact UTC time and reports every lag from -N to +N, Fisher-z intervals, and fold sign stability. Default v3 causally standardizes each series by the preceding 20-return RMS. It reports Bonferroni and empirical family-wise p-values without selecting a best lag. Because the shared clustered-volatility null still exceeded nominal 5%, `candidateEligible` and journal recording remain fail-closed pending recalibration. `return_standardization: none` exists only to reproduce raw-return v2. |
198
+ | `run_lead_lag_falsification_audit` | Runs the frozen lead-lag gate against paired synthetic nulls and returns a fully resolved, hash-bound calibration configuration without reading TradingView |
199
+ | `run_feature_outcome_falsification_audit` | Runs the actual `candidateEligible` rule against three deterministic synthetic nulls, including fixed 1,000-repetition empirical-null calibration, and reports per-model candidate rates, Wilson intervals, and unevaluable seeds |
200
+ | `run_feature_outcome_power_audit` | Injects a signed next-bar effect after a frozen body-direction bucket and reports detection, Wilson interval, and miss rate by effect and model; it preserves signal-bar shape but does not establish market alpha or profitability |
201
+ | `compute_feature_outcome_relationships` | Classifies ATR compression, body direction, wick imbalance, streak, range position, and gaps using only contemporaneously available evidence, with outcomes and fold distributions by bucket. Optional selection compares against all bars in the same time/regime population. Empirical calibration uses a fixed 1,000-repetition circular moving-block null and requires Newey-West, Bonferroni, and family-wise empirical tests at horizon 1; it does not optimize thresholds or recommend trades |
202
+ | `compute_session_profile` | Computes DST-aware, cross-midnight session ranges, returns, opening-range extension, high/low times, VWAP behavior, prior-session level tests, holiday/short-session quality, gaps/overlaps, and volume coverage; TradingView volume is explicitly unverified tick/exchange volume |
203
+ | `get_price_action_context_template` | Returns the audited close-confirmed Pine template for pin bars, engulfing bars, and 20-bar sweeps |
204
+ | `get_price_action_context` | Reads the latest price-action plots only after verifying the exact saved template, on-chart instance, inputs, symbol, and timeframe |
205
+ | `run_price_action_pattern_study` | Descriptively measures naked-entry outcomes for the three frozen price-action patterns and reports same-clock-hour baselines |
206
+ | `get_volume_profile_context_template` | Returns the audited Pine proxy for completed prior-session POC, VAH, and VAL derived from chart-bar volume allocation |
207
+ | `get_volume_profile_context` | Reads completed profile levels only after exact source, version, placement, input, symbol, and timeframe verification |
208
+ | `run_volume_profile_reaction_study` | Runs the frozen 60- or 240-minute VAH/VAL reaction study with same-prior-regime controls; it does not claim order-flow evidence |
209
+ | `run_volume_profile_poc_reversion_study` | Runs the separately frozen 60-minute POC-reversion study and keeps its population separate from VAH/VAL reactions |
210
+ | `compute_round_trip_cost` | Computes round-trip spread, slippage, and commission under explicit assumptions |
211
+ | `compute_position_size` | Floors position size from loss limit, Entry/Stop, costs, quantity constraints, and fresh FX conversion evidence |
212
+ | `evaluate_due_analyses` | Previews due nonterminal journal analyses, then after confirmation temporarily switches the selected chart, evaluates, records, and restores it |
213
+ | `get_analysis_performance` | Aggregates the live journal into outcomes, gross/net R, MFE/MAE, and time-to-hit with explicit populations and exclusions |
214
+ | `validate_trade_plan` | Validates direction, expiry, current price, evidence freshness, event blackout, and net reward/risk without touching the chart |
215
+ | `get_cme_gold_open_interest` | Reads `TOTAL GC FUT` all-contract OI from the CME Daily Bulletin and records first-seen preliminary/final state without mixing chart contract baskets |
216
+ | `reconcile_gold_open_interest` | Reconciles COT gold OI with locally first-seen CME `TOTAL GC FUT` on exact dates only, with no nearest-date interpolation |
217
+ | `get_positioning_context` | Returns CFTC COT history, OI normalization, weekly change, and three-year percentile; when first-seen storage exists, `available_at` is the observed time rather than an estimate |
218
+ | `get_futures_flow_context` | Combines directed CME/COMEX daily futures price/volume Z-score with weekly COT. Chart OI is the default; `cme_daily_bulletin` is XAUUSD-only, keeps preliminary/final and contract baskets separate, records prospective first-seen revisions, never fills missing CME dates from chart data, and supports `as_of` vintages |
219
+ | `get_real_yield_context` | U.S. Treasury 10-year par real CMT, restricted to locally first-seen versions when `as_of` is supplied |
220
+ | `get_policy_rate_context` | Returns first-seen policy rates for eight currencies as of a requested time, requiring both conservative `available_at` and observed `first_seen_at` |
221
+ | `get_exploratory_policy_rate_history` | Returns isolated official revised policy-rate history for exploration only; it makes no historical-availability claim and cannot support prospective/OOS evidence |
222
+ | `carry_panel_preflight` | Checks common policy-rate start, non-overlapping anchors, OOS remainder, and gaps for a frozen pair/period/horizon; it never backfills uncollected history and reports `not_evaluable` below the requirement |
223
+ | `estimate_carry_panel_effective_sample` | Estimates correlation-adjusted effective sample size from frozen carry returns using date-level circular moving-block bootstrap; it does not select or optimize |
224
+ | `measure_carry_panel_dependence` | Temporarily acquires a daily FX panel and reports observed pairwise rho and block-bootstrap design effect on exact non-overlapping dates; dynamic official-rate signs remain exploratory and non-point-in-time |
225
+ | `get_carry_core_primary_readiness` | Reads the frozen carry primary-test readiness from first-seen rates and complete collection heartbeats without switching a chart |
226
+ | `run_carry_core_primary_test` | Runs the frozen five-pair carry panel with first-seen rates, pair fixed effects, and anchor-date block bootstrap; remains `not_evaluable` below 60 complete clusters |
227
+ | `get_oanda_flow_collection_readiness` | Reports whether the local OANDA retail-flow collector is configured without making a request or exposing its token |
228
+ | `get_cot_crowding_unwind_overlay_template` | Returns the audited Pine overlay for supplied COT crowding context and prior daily structure; it does not fetch or infer orders or stops |
229
+ | `get_cot_crowding_unwind_context` | Describes a daily EURUSD/USDJPY leveraged-money crowding and price-break proxy without claiming observed execution flow |
230
+ | `preflight_cross_asset_shock` | Verifies exact closed-bar coverage for an EURUSD/USDJPY, DXY, US10Y, and XAUUSD shock study while restoring the temporary auxiliary chart |
231
+ | `classify_cross_asset_shocks` | Classifies frozen same-UTC cross-asset shock states without producing outcomes, candidates, or trade instructions |
232
+ | `evaluate_cross_asset_shock_outcomes` | Measures descriptive 15/30/60/120-minute outcomes for non-overlapping frozen shock states without producing a candidate |
233
+ | `preflight_bookmap_flow_price_join` | Reads one bounded local Bookmap Collector JSONL and verifies conservative receipt-time coverage against active EURUSD M1/M5; CME flow remains a single-venue futures proxy |
234
+ | `audit_pine_indicator` | Statically audits a user-owned Pine indicator for repainting risks |
235
+ | `compare_indicator_observations` | Detects changes in the same-bar values before and after reload |
236
+
237
+ ### First-seen collection CLI
238
+
239
+ `npm run collect:first-seen -- --cot-symbol OANDA:EURUSD --cot-symbol OANDA:XAUUSD` collects COT, the U.S. 10-year real yield, and all-contract GC open interest from the CME Daily Bulletin into append-only first-seen logs. `npm run coverage:first-seen` reports collection days, revisions, and first/last observation dates for COT, real yield, futures OI, and policy rates as JSON. Set scheduled COT symbols with `TRADINGVIEW_MCP_COLLECTION_COT_SYMBOLS=OANDA:EURUSD,OANDA:USDJPY,OANDA:XAUUSD`, or pass `--cot-symbol` per symbol as the launchd example does. Naming them matters: with neither, the CLI collects only its two-symbol default, and a symbol added once by hand stops being collected without any error.
240
+
241
+ `npm run collect:research-hypotheses` appends a run record to `~/.tradingview-mcp/research-collection-heartbeats.jsonl` whether or not a hypothesis fired, because the evidence file only grows on a closed event and the frozen hypotheses produce roughly one every ten days. Without it a quiet week and a dead collector are the same record, and the second cannot be filled in afterwards. Override the path with `TRADINGVIEW_MCP_RESEARCH_COLLECTION_HEARTBEAT_PATH`. Coverage reports run count, maximum gap in hours, latest-run age, chart-restoration failures, and per-hypothesis attempts against events.
242
+
243
+ `npm run collect:policy-rates` reads `ECONOMICS:*INTR` for USD/EUR/JPY/GBP/AUD/NZD/CAD/CHF in sequence and appends changes to `~/.tradingview-mcp/policy-rate-first-seen.jsonl`. Every run that successfully acquires all eight currencies, persists values, and restores the chart is also recorded in `~/.tradingview-mcp/policy-rate-collection-heartbeats.jsonl`, whether or not a value changed. This lets the primary test verify first-seen values and collection continuity separately. Override the heartbeat path with `TRADINGVIEW_MCP_POLICY_RATE_COLLECTION_HEARTBEAT_PATH`. Coverage reports distinct run days, same-day reruns, maximum business-day age between runs, intervals beyond the frozen five-day limit, and latest-run age. The script uses the same cross-process chart lock as the MCP server, passes the approved `--confirm-chart-switch`, and verifies restoration after every currency. Because TradingView's 00:00 UTC bar is not a release timestamp, `available_at` is conservatively set to 00:00 UTC on the next business day. This reproducible boundary prevents meeting-day lookahead but is not the actual publication time.
244
+
245
+ `npm run collect:official-policy-rates` writes to a separate exploration-only official-history store. Sources include the ECB Deposit Facility SDMX CSV; BoC Valet `V39079`; the exclusive date splice of FRED `DFEDTAR` with the midpoint of `DFEDTARL`/`DFEDTARU` from 2008-12-16; RBA F1 `FIRMMCRTD`, joining the official legacy XLS (1990-08-02 through 2010-12-31) to the current daily CSV from 2011-01-04; the SNB policy rate and legacy Libor target-range midpoint; and a frozen BoJ meeting-decision manifest. BoJ periods without a single short-rate target are stored as `value: null` so an obsolete rate is not carried forward. Effective market rates are not substituted for policy targets. Unchanged observations are reduced to change points, while raw snapshots retain original row count and first/last dates to distinguish missing data from unchanged values. Raw bodies retain `raw_sha256`, retrieval time, and Last-Modified vintage and are stored owner-only at `~/.tradingview-mcp/policy-rate-official-raw/<sha256>.raw`; reused hashes are revalidated. This is revised history and must not support prospective/OOS evidence, the primary test, or adoption decisions.
246
+
247
+ `npm run collect:fx-history -- --from 2022-01-01T00:00:00.000Z --to 2026-01-01T00:00:00.000Z` reads `OANDA_FX_HISTORY_ACCOUNT_ID` and `OANDA_FX_HISTORY_ACCESS_TOKEN` only from the environment and retrieves confirmed OANDA v20 `EUR_USD` midpoint M15 candles. Choose `practice` (default) or `live`; credentials and account IDs are never written to stdout, manifests, or raw evidence. Requests are paged at no more than 4,000 bars and timeouts, 429s, and 5xx responses are retried up to three times per page. Successful pages are archived before checkpoints are appended to `~/.tradingview-mcp/fx-history-m15-manifest.jsonl.checkpoints`, so rerunning the same range revalidates archived raw data and resumes from the first incomplete page. Raw responses are stored owner-only by content hash under `~/.tradingview-mcp/fx-history-raw/<sha256>.raw`. The manifest records range, retrieval time, raw and normalized hashes, counts, first/last bars, boundary duplicates, and weekday discontinuities. Equal duplicates are removed; conflicting duplicates stop the run. This revised official history is not a first-seen series and currently supports exploratory long-run CPI/NFP/FOMC research only, not existing OOS adoption gates.
248
+
249
+ On macOS, register `com.tradingview-mcp.policy-rate-collection` for weekdays at 10:45 JST without `RunAtLoad`, so login and MCP restart do not immediately move the chart. External first-seen collection runs at 10:30 and 22:30 JST on weekdays to create two observation windows for preliminary-to-final CME OI revisions; this schedule does not guarantee the final publication. Both jobs share the chart-operation lock, so they wait or fail during MCP use rather than restoring another process's temporary symbol.
250
+
251
+ ### Macro surprise forward collection
252
+
253
+ `npm run coverage:macro-surprise -- --events CPI_ARTIFACT --events NFP_ARTIFACT --events FOMC_ARTIFACT --confirm-local-import` reconciles official release artifacts with local first-seen evidence and separately reports pre-collection events, missed forward consensus/actual values, releases still inside the 15-minute actual-capture window, and evaluable surprises. Revised official history does not prove that historical consensus was known, so `events_before_collection` is not a gap. A nonzero `missing_forward_consensus` or `missing_forward_actual` blocks the directional study.
254
+
255
+ macOS examples are provided for [daily consensus collection](docs/launchd/com.tradingview-mcp.macro-consensus-collection.plist.example), [five-minute actual collection](docs/launchd/com.tradingview-mcp.macro-actual-collection.plist.example), and [daily coverage checks](docs/launchd/com.tradingview-mcp.macro-surprise-coverage.plist.example). Actual collection fetches official documents only within 15 minutes of release. Set `TRADINGVIEW_MCP_TRADING_ECONOMICS_API_KEY` in the launchd environment before loading the consensus job. The examples reference real 2016-2026 artifacts; update all three paths to the same artifact set each year. Keep the mapping JSON private and outside Git.
256
+
257
+ ### Event-study falsification audit CLI
258
+
259
+ `npm run audit:event-studies -- --config fvg-audit.json` calibrates a frozen event-study definition against synthetic nulls. Defaults are 400 replications per model, 5,000 bars, nominal alpha 5%, and three folds; white noise, regime-switching volatility, and bid-ask bounce are reported **separately**. The audit never accesses TradingView, the network, or local journals. For a quick smoke test, override with `--model white_noise --replications 20 --bars 1200`.
260
+
261
+ The configuration contains only the study definition and candidate rule. For example:
262
+
263
+ ```json
264
+ {
265
+ "study": {
266
+ "type": "fvg_retest",
267
+ "definition": {
268
+ "symbol": "SYNTH:FVG_RETEST",
269
+ "timeframe": "15",
270
+ "minimumGapBps": 10,
271
+ "retestWithinBars": 24,
272
+ "minImpulseBodyRatio": 0.5,
273
+ "requireBoundaryHold": true,
274
+ "horizons": [1, 4, 8],
275
+ "targetReturnBps": 20,
276
+ "minimumEvents": 30,
277
+ "eventLimit": 0,
278
+ "confidenceLevel": 0.95,
279
+ "configurationTrials": 1,
280
+ "regime": null,
281
+ "branchFilter": "bearish"
282
+ }
283
+ },
284
+ "candidate": {
285
+ "branch": "fvg_retest_bearish",
286
+ "horizon": 4,
287
+ "minimumEvents": 30,
288
+ "minimumFoldEvents": 5,
289
+ "folds": 3
290
+ }
291
+ }
292
+ ```
293
+
294
+ Each model's Wilson interval is used to assess whether its candidate rate exceeds nominal alpha. This does not prove profitability or future edge; it audits how often the adoption rule fires on a series with no signal.
295
+
296
+ For an event-aftershock-retest audit, provide `eventSchedule` instead of real economic-event times. `firstBar`, `everyBars`, and `maximumEvents` define a relative exogenous schedule within each synthetic series; they do not predict, substitute for, or reproduce real events.
297
+
298
+ ### Periodic research-hypothesis collection
299
+
300
+ `npm run collect:research-hypotheses` serially collects three prospective hypotheses: XAUUSD M15 bearish FVG x `trend_down`, daily EURUSD/U.S. 10-year nonconfirmation, and EURUSD M50 lower-wick x `trend_down`. It refuses to run during Bar Replay, temporarily switches the two existing panes, and restores their original symbols and timeframes after success or failure. It does not modify orders, alerts, Pine scripts, or studies.
301
+
302
+ Only aggregates are stored in `~/.tradingview-mcp/research-collection.jsonl`, and a record is appended only when the primary horizon has at least one closed event. Startup verifies that all three hypothesis IDs are preregistered in the research journal. The MCP server and CLI share one owner-only chart-operation lock. In stdout, `collection_status` describes execution and `research_status` describes evidence sufficiency; either being `partial` makes the top-level status partial. For scheduled macOS operation, copy and load the launchd examples for [research hypotheses](docs/launchd/com.tradingview-mcp.research-hypotheses.plist.example), [external first-seen collection](docs/launchd/com.tradingview-mcp.first-seen-collection.plist.example), and [policy rates](docs/launchd/com.tradingview-mcp.policy-rate-collection.plist.example). TradingView must be running with CDP enabled. The research example runs hourly to reduce visible chart interference.
303
+
304
+ Required history is frozen per job: 5,000 bars for FVG, 1,000 per series for the daily rate nonconfirmation, and 500 for the M50 feature study. Missing bars are loaded on the same temporary chart, and `coverage` records initial, added, and final counts, provider capacity, and sufficiency. If the requirement cannot be met, `insufficient_loaded_history` stops analysis and evidence recording; short history is never presented as complete evidence.
305
+
306
+ `get_execution_snapshot` first reads `bid`, `ask`, `lp_time`, session state, real-time load state, and price increment from open TradingView charts. `lp_time` is the last-price time in the same quote snapshot, not an exchange timestamp for each bid/ask. A chart quote is `ready` only when it is no more than five seconds old by default and is streaming, in an active session, and real-time loaded. If the symbol is not open, the tool falls back to the scanner. The scanner has no market-side bid/ask timestamp or session calendar, so receipt time is never substituted for market time; the fallback is ready only after observing a bid/ask change within the default 1.2-second window. No movement returns `wait`. This does not guarantee fillability or liquidity and does not change accounts, orders, or charts.
307
+
308
+ `compute_position_size` returns instrument units, not broker-specific lots. Supply `quantity_step`, `minimum_quantity`, and where needed `maximum_quantity` and `contract_multiplier` according to the execution venue. Loss includes Entry-to-Stop distance plus explicit round-trip cost such as `compute_round_trip_cost.total_price_per_unit`, converted to account currency. When quote and account currencies differ, size is returned only with a fresh account-currency/quote-currency rate, symbol, and observation time. The tool does not connect to an account, read balances, place orders, or persist positions.
309
+
310
+ Real-yield first-seen history is appended to `~/.tradingview-mcp/real-yield-first-seen.jsonl` by default; override it with `TRADINGVIEW_MCP_REAL_YIELD_HISTORY_PATH`. Historical rows fetched on first startup are not backdated to past publication times and become eligible for backtests only after the time they were actually stored.
311
+
312
+ Futures-OI first-seen history is appended to `~/.tradingview-mcp/futures-open-interest-first-seen-v3.jsonl` by default; override it with `TRADINGVIEW_MCP_FUTURES_OI_HISTORY_PATH`. Chart-derived OI is recorded when read by `get_futures_flow_context`, and official CME all-contract GC OI is recorded by `get_cme_gold_open_interest` and the collection CLI. Chart proxies and official CME values remain separate. Pre-collection vintages cannot be reconstructed: historical values downloaded today are revised values, not necessarily what was visible at the time.
313
+
314
+ If a process crashes while writing history and leaves a `.lock`, history access stops rather than deleting it automatically. Confirm that no other TradingView-MCP process is running before deleting only the adjacent `.lock` file.
315
+
316
+ The evaluation CLI uses the snapshot's `request_completed_at` as evaluation time and binds `evaluation_context.real_yield_10y` only to a version first seen by that time. It never falls back to the current value or a later revision.
317
+
318
+ ```bash
319
+ npm run evaluate -- --log evaluation.jsonl --snapshot snapshot.json
320
+ ```
321
+
322
+ Use `--real-yield-history PATH` for an isolated store. If the snapshot has no completion time, supply canonical UTC with `--as-of 2026-07-01T12:00:00.000Z`. An `--as-of` later than `request_completed_at` is rejected as lookahead. Missing history is not imputed and records `point_in_time_status=blocked`; corrupt history or lock failure prevents the snapshot itself from being appended.
323
+
324
+ **Pine scripts (user-owned only)**
325
+
326
+ | Tool | Description |
327
+ |---|---|
328
+ | `list_pine_scripts` | Lists saved user-owned Pine scripts and the chart indicators that use them |
329
+ | `get_pine_source` | Retrieves full source for a user-owned script, optionally by version for recovery |
330
+ | `save_pine_script` | Saves AI-modified source; **dry-run without confirmation**, creates only a new script or version, never overwrites history |
331
+ | `add_pine_to_chart` | Adds a user-owned script to the chart; removal is separate |
332
+ | `remove_owned_study` | Verifies `USER;` Pine ID, chart, and internal study ID before removing one instance; **dry-run without confirmation** |
333
+ | `evaluate_analysis_overlay_outcome` | Evaluates an audited analysis on later closed bars, optionally using a temporary evidence timeframe; appends to the journal only with `record:true` |
334
+ | `get_analysis_journal` | Reads definitions and latest evaluations without allowing a later stale `ongoing` record to reverse a completed result |
335
+ | `get_analysis_calibration` | Reports Brier score and realized rates by confidence band, using Target-first as positive and Stop-first as negative with explicit exclusions |
336
+ | `get_analysis_overlay_status` | Validates expiry, current-price geometry, and drawing count; returns `unconfigured` or `blocked` without changing the chart |
337
+ | `get_analysis_overlay_template` | Returns the fixed Pine template for Entry, Invalidation, Stop, Targets, and analysis time |
338
+ | `ensure_analysis_overlay` | Idempotently reuses, installs, or after confirmation migrates a legacy 14-input overlay to the context-bound 18-input version; **dry-run without confirmation** |
339
+ | `apply_analysis_overlay` | Applies structured analysis with symbol/timeframe and optional snapshot/strategy version, verifies fail-closed readback, and journals after success; **dry-run without confirmation** |
340
+
341
+ To overlay analysis on the chart, save the template once with `save_pine_script`, then use `ensure_analysis_overlay` to place, update, and obtain its `study_id`. An existing current version is reused without writing, so each analysis does not create another script or study. If a legacy migration preview returns `contextBindingRequired:true`, confirmation binds that analysis to the currently verified symbol/timeframe. Expired analyses remain visible as `EXPIRED`. Template defaults are not treated as analysis and return `unconfigured`. After application, status rechecks inputs, current-price geometry, and drawings; a chart that differs from the stored context returns `stale_context` and `trusted:false`.
342
+
343
+ Current-price geometry does not establish historical hit order. `evaluate_analysis_overlay_outcome` evaluates closed OHLC after the analysis, excluding both the analysis-time bar and the forming bar. After Entry, an optional Confirmation must occur on a later bar; Invalidation before confirmation cancels the setup. Once active, Target 1 versus Stop is evaluated first-hit. This does not prove fills or P&L: touching opposing levels in one bar or opening across a terminal returns `ambiguous`. If history is short, load more or request a shorter `evaluation_timeframe`. The latter keeps the `expected_timeframe` overlay contract, temporarily switches only the selected chart, verifies symbol/resolution/bar evidence, and restores it. If `chartState.restored` is false, inspect `currentTimeframe` and restore manually. Daily and weekly aliases are supported; calendar-month `M` is `not_evaluable` because its duration varies.
344
+
345
+ The analysis journal defaults to `~/.tradingview-mcp/analysis-journal.jsonl`; override it with `TRADINGVIEW_MCP_ANALYSIS_JOURNAL_PATH`. `apply_analysis_overlay(confirm:true)` records the definition after verified readback, while outcome evaluation appends only with explicit `record:true`. The same ID and definition are idempotent; reusing an ID for a different definition or assigning conflicting completed labels is rejected. A definition conflict requires a new `analysis_id`, not a retry. If only journal writing fails, the application/evaluation result remains available with `journal.recorded:false` and a warning. Calibration uses only `target_before_stop=1` and `stop_before_target=0`; all other outcomes are counted by exclusion reason.
346
+
347
+ The journal reclaims a `.lock` only when it is older than 60 seconds and its recorded owner PID no longer exists. A live, unverifiable, or recent lock is never stolen, and the timeout names its path. Before manually deleting that lock, confirm that no TradingView-MCP process is using it.
348
+
349
+ This enables a read -> modify -> save -> backtest improvement loop:
350
+
351
+ > Read the BushidoScalp source, implement a change that reduces false signals, save it, backtest it on USDJPY 4H, and compare it with the original.
352
+
353
+ **Backtesting**
354
+
355
+ | Tool | Description |
356
+ |---|---|
357
+ | `run_backtest` | Temporarily applies a user-owned strategy, retrieves results, and removes it, leaving the chart unchanged |
358
+ | `get_strategy_report` | Reads net profit, win rate, PF, drawdown, and recent trades for the active strategy |
359
+ | `get_strategy_trade_ledger` | Pages the full Strategy Tester ledger in batches of up to 500, binds it to a SHA-256 ID, rejects cross-page recomputation, exposes available costs/run-up/drawdown/inputs/Pine version, and separates the trailing mark-to-market open row |
360
+ | `run_strategy_experiment` | Serially compares baseline and candidate on one chart; dry-run by default, then after confirmation reports exact Pine versions, ledger IDs, inputs, minimum trades, condition match, and metric deltas before removing both |
361
+ | `run_backtest_matrix` | Runs up to 24 explicit symbol/timeframe/input combinations with a 30-minute soft deadline, per-row full-ledger IDs, insufficiency/failure reasons, and verified restoration; it does not rank results |
362
+ | `run_strategy_walk_forward` | Splits full ledgers for 2-8 candidates into 2-12 explicit train/embargo/test windows, selects on train only, and returns OOS only for the selected candidate with anchored/rolling, tie, minimum-trade, quality, and coverage checks |
363
+ | `validate_research_protocol` | Validates an exact Pine version and frozen protocol, classifying IS/OOS overlap, future windows, forming bars, trial count, minimum trades, missing costs, static Pine risks, and post-OOS changes as blocked or warning |
364
+ | `stress_test_strategy` | Binds to a frozen protocol and stress-tests full ledgers under cost/time/bootstrap models plus up to eight explicit Pine input reruns, evaluating delays, Stop/Target, and nearby parameters through the strategy itself with cleanup, restoration, failures, and degradation rates |
365
+ | `register_strategy_hypothesis` | Registers a hypothesis and prospective evaluation contract in a local append-only research journal separate from live analysis |
366
+ | `record_strategy_experiment` | Binds experiment ID, Pine version, ledger ID, known metrics, guardrails, and decision to the hypothesis |
367
+ | `compare_strategy_experiments` | Compares exact experiment IDs and evidence hashes and rejects population, symbol, timeframe, or methodology mismatches |
368
+
369
+ ## Troubleshooting
370
+
371
+ | Symptom | Cause and resolution |
372
+ |---|---|
373
+ | `TradingView desktop app is not reachable` | TradingView is not in debug mode. Quit it and relaunch it with the Step 2 command |
374
+ | Tools do not appear in the AI | Reconnect or restart the agent and confirm that `npm run build` has been run |
375
+ | Behavior does not change after rebuilding | The MCP process keeps the startup build; reconnect the agent session |
376
+ | `no tradingview.com/chart page found` | Open a chart tab in TradingView |
377
+
378
+ ## Security
379
+
380
+ See [docs/security-review.md](docs/security-review.md) for the full review. At minimum:
381
+
382
+ - While the debug port is open, any program on the same machine can control the signed-in TradingView session. Launch in debug mode **only while using the AI**, use normal mode otherwise, and do not use this setup on a shared machine.
383
+ - The server is **read-oriented**. Writes are limited to non-destructive user-owned Pine versioning, adding/changing/removing verified owned studies, creating expiring alerts from audited analysis, and starting/stepping/stopping Bar Replay. Confirmation gates protect the relevant tools. Orders, Replay Trading, Replay autoplay, modification/resume/deletion of existing alerts, webhooks, watchlist changes, and Pine-library deletion are intentionally absent.
384
+ - `get_chart_screenshot` sends everything visible on screen, including watchlists, to the AI provider.
385
+
386
+ ## Development
387
+
388
+ ### From Source
389
+
390
+ The published package provides the MCP server only. Every `npm run` command in
391
+ this document - the collectors, the coverage reports, the studies and the audits
392
+ - is a script in this repository and needs a clone:
393
+
394
+ ```bash
395
+ git clone https://github.com/tedorigawa001/TradingView-MCP.git
396
+ cd TradingView-MCP
397
+ npm install
398
+ npm run build
399
+ ```
400
+
401
+ Opening Claude Code in the clone registers the server from the bundled
402
+ `.mcp.json`, which runs `build/index.js` from the repository rather than the
403
+ published package. That is what you want while developing: it picks up your
404
+ build, not the last release.
405
+
406
+ ### Testing
407
+
408
+ ```bash
409
+ npm test # Node unit tests + Bookmap Java tests
410
+ npm run test:integration # Integration tests (requires the app in debug mode)
411
+ npm run test:e2e # Real-app E2E over MCP stdio (configuration below)
412
+ ```
413
+
414
+ `npm test` does not require TradingView. With the complete Bookmap SDK installed locally, it also runs the Collector, signal-engine, and Bookmap-adapter Java tests. With no or partial SDK, it builds and tests only the SDK-free `FlowSignalEngine` for Java 17 and explicitly skips adapter tests.
415
+
416
+ On pull requests and pushes, GitHub Actions runs `npm test` on Node.js 22 and 24, including the SDK-free signal engine. A separate `npm audit` job rejects high or critical vulnerabilities.
417
+
418
+ ### Publishing
419
+
420
+ `prepublishOnly` runs `npm test`, which includes the Bookmap Java tests, so
421
+ **publishing requires a JDK that supports `--release 17`** even though the
422
+ published package contains no Java. That is deliberate: a release should not go
423
+ out on a suite that was skipped. The Bookmap SDK itself is not needed - without
424
+ it the Java step builds and tests the SDK-free engine and marker and skips the
425
+ adapters.
426
+
427
+ `prepack` runs `build:package` (`tsc --sourceMap false`) rather than `build`, and
428
+ `files` is limited to `build/**/*.js`. Source maps would otherwise be about half
429
+ the package while pointing at `src/` files it does not ship.
430
+
431
+ Integration tests temporarily change symbols and timeframes and restore them afterward.
432
+
433
+ For walk-forward E2E, set `TRADINGVIEW_WALK_FORWARD_E2E_CONFIG` to JSON matching the current chart and saved strategy. Do not include `confirm`; the test owns confirmation.
434
+
435
+ ```bash
436
+ TRADINGVIEW_WALK_FORWARD_E2E_CONFIG='{"expected_symbol":"OANDA:USDJPY","expected_timeframe":"240","candidates":[{"pine_id":"USER;YOUR_PINE_ID","inputs":[{"id":"in_20","value":false}]},{"pine_id":"USER;YOUR_PINE_ID","inputs":[{"id":"in_20","value":true}]}],"folds":[{"fold_id":"f1","train_from":"2025-03-01T00:00:00.000Z","train_to":"2025-09-01T00:00:00.000Z","test_from":"2025-09-02T00:00:00.000Z","test_to":"2025-12-01T00:00:00.000Z"},{"fold_id":"f2","train_from":"2025-03-01T00:00:00.000Z","train_to":"2025-12-01T00:00:00.000Z","test_from":"2025-12-02T00:00:00.000Z","test_to":"2026-03-01T00:00:00.000Z"}],"mode":"anchored","embargo_bars":1,"minimum_train_trades":5,"minimum_test_trades":3,"selection_metric":"expectancy","max_runtime_seconds":180}' npm run test:e2e
437
+ ```
438
+
439
+ For analysis-alert E2E, set `TRADINGVIEW_ANALYSIS_ALERTS_E2E_CONFIG` to match the installed analysis overlay.
440
+
441
+ ```bash
442
+ TRADINGVIEW_ANALYSIS_ALERTS_E2E_CONFIG='{"pine_id":"USER;YOUR_PINE_ID","expected_symbol":"OANDA:USDJPY","expected_timeframe":"4H","analysis_id":"USDJPY-20260724-001","confirm":false}' npm run test:e2e
443
+ ```
444
+
445
+ For Fair Value Gap Retest event-study E2E, set `TRADINGVIEW_FVG_RETEST_E2E_CONFIG` to match the chart.
446
+
447
+ ```bash
448
+ TRADINGVIEW_FVG_RETEST_E2E_CONFIG='{"expected_symbol":"OANDA:EURUSD","expected_timeframe":"60","count":5000,"condition":{"type":"fair_value_gap_retest","minimum_gap_bps":10,"retest_within_bars":24,"min_impulse_body_ratio":0.5,"require_boundary_hold":true},"horizons":[1,2,4,8],"target_return_bps":20,"minimum_events":1,"event_limit":50,"confidence_level":0.95,"configuration_trials":1}' npm run test:e2e
449
+ ```
450
+
451
+ Futures-flow E2E requires `open_interest_study_id`, `open_interest_plot_title`, and an `open_interest_scope` that freezes the value's meaning in `TRADINGVIEW_FUTURES_FLOW_E2E_CONFIG`. Scope must be paired with explicit OI data or study selection and cannot accompany pure autodetection, which reads only TradingView's official front-month Open Interest study. Otherwise a front-month value could be mislabeled as an aggregate. Missing OI fails explicitly so a broken first-seen collector cannot pass silently. The test redirects collection to a temporary file and does not contaminate production logs.
452
+
453
+ ```bash
454
+ TRADINGVIEW_FUTURES_FLOW_E2E_CONFIG='{"target_symbol":"OANDA:XAUUSD","futures_chart_index":1,"expected_futures_symbol":"COMEX_DL:GC1!","count":250,"observation_limit":0,"minimum_observations":100,"cot_weeks":1,"open_interest_study_id":"YOUR_STUDY_ID","open_interest_plot_title":"Total OI","open_interest_scope":"all_months_aggregated"}' npm run test:e2e
455
+ ```
456
+
457
+ E2E verifies rejection of incorrect chart binding, deterministic dry-runs, train-only selection, suppression of unselected candidates' OOS results, protocol validation, ledger stress, seeded bootstrap, real alert creation and ownership naming, bounded responses, and complete chart restoration. Missing configuration causes a skip.
458
+
459
+ ### Repository Layout
460
+
461
+ - `src/` - TypeScript source
462
+ - `cdp.ts` - CDP connection, evaluation, and screenshots
463
+ - `tradingview.ts` - in-page TradingView API layer
464
+ - `scanner.ts` - public scanner API client
465
+ - `server.ts` - dependency-injected MCP tool definitions
466
+ - `index.ts` - stdio entry point
467
+ - `test/unit/` - unit tests with mock CDP and scanner
468
+ - `test/e2e/` - configuration-driven E2E from MCP stdio to the real app
469
+ - `test/smoke.mjs` - integration smoke test against the real app
470
+ - `build/` - ignored TypeScript output
471
+ - `bookmap-addon/` - Java Bookmap add-on. `FlowSignalEngine` and `FlowSignalMarker` import nothing from the Bookmap SDK and are built and tested everywhere, including CI; `FlowCollector` and `FlowSignalResearch` need the locally installed SDK and are skipped without it. `dist/` is ignored
472
+ - `docs/` - design and research documentation
473
+
474
+ ### Documentation
475
+
476
+ - [docs/STRATEGY.md](docs/STRATEGY.md) - overall strategy and progress
477
+ - [docs/phase0-findings.md](docs/phase0-findings.md) / [phase3](docs/phase3-findings.md) / [phase4](docs/phase4-findings.md) / [phase5](docs/phase5-findings.md) - internal API research
478
+ - [docs/security-review.md](docs/security-review.md) - security review
479
+ - [docs/BACKLOG.md](docs/BACKLOG.md) - future improvements
@@ -0,0 +1,85 @@
1
+ import { createHash } from "node:crypto";
2
+ import { normalizeResolution } from "./analysisOverlay.js";
3
+ function ownershipToken(analysisId) {
4
+ return createHash("sha256").update(analysisId, "utf8").digest("hex").slice(0, 16);
5
+ }
6
+ export function analysisAlertOwnershipName(analysisId, kind) {
7
+ return `BUSHIDO-MCP:${ownershipToken(analysisId)}:${kind}`;
8
+ }
9
+ export function buildAnalysisAlertPlans(analysis, symbol, timeframe, now = new Date()) {
10
+ if (analysis.bias === "neutral")
11
+ throw new Error("neutral analyses do not have directional alert semantics");
12
+ if (analysis.expiresAt === null)
13
+ throw new Error("analysis expires_at is required for bounded monitoring alerts");
14
+ const expirationMs = Date.parse(analysis.expiresAt);
15
+ if (!Number.isFinite(expirationMs) || expirationMs <= now.getTime()) {
16
+ throw new Error("analysis expires_at must be in the future");
17
+ }
18
+ if (analysis.targets.length === 0)
19
+ throw new Error("analysis Target 1 is required");
20
+ const bullish = analysis.bias === "bullish";
21
+ const definitions = [
22
+ { kind: "confirmation", level: analysis.confirmation, operator: bullish ? "cross_up" : "cross_down" },
23
+ { kind: "invalidation", level: analysis.invalidation, operator: bullish ? "cross_down" : "cross_up" },
24
+ { kind: "target_1", level: analysis.targets[0], operator: bullish ? "cross_up" : "cross_down" },
25
+ ];
26
+ return definitions
27
+ .filter((definition) => definition.level !== null)
28
+ .map((definition) => ({
29
+ kind: definition.kind,
30
+ ownershipName: analysisAlertOwnershipName(analysis.analysisId, definition.kind),
31
+ symbol: symbol.toUpperCase(),
32
+ resolution: normalizeResolution(timeframe),
33
+ operator: definition.operator,
34
+ level: definition.level,
35
+ expiration: new Date(expirationMs).toISOString(),
36
+ message: `Bushido ${definition.kind} ${symbol.toUpperCase()} @ ${definition.level}`,
37
+ }));
38
+ }
39
+ function conditionShape(alert) {
40
+ const condition = alert.condition;
41
+ if (condition === null || typeof condition !== "object" || Array.isArray(condition)) {
42
+ return { operator: null, level: null };
43
+ }
44
+ const object = condition;
45
+ const series = Array.isArray(object.series) ? object.series : [];
46
+ const valueSeries = series.find((item) => item !== null && typeof item === "object" && !Array.isArray(item) && item.type === "value");
47
+ return {
48
+ operator: object.type,
49
+ level: valueSeries && typeof valueSeries === "object"
50
+ ? valueSeries.value
51
+ : null,
52
+ };
53
+ }
54
+ export function matchExistingAnalysisAlerts(plans, alerts) {
55
+ return plans.map((plan) => {
56
+ const candidates = alerts.filter((alert) => alert.name === plan.ownershipName);
57
+ if (candidates.length === 0)
58
+ return { plan, status: "missing", alert: null, mismatches: [] };
59
+ if (candidates.length > 1) {
60
+ return {
61
+ plan,
62
+ status: "conflict",
63
+ alert: null,
64
+ mismatches: ["multiple_owned_alerts_with_same_name"],
65
+ };
66
+ }
67
+ const alert = candidates[0];
68
+ const condition = conditionShape(alert);
69
+ const mismatches = [];
70
+ if (alert.symbol.toUpperCase() !== plan.symbol)
71
+ mismatches.push("symbol");
72
+ if (alert.resolution === null || normalizeResolution(alert.resolution) !== plan.resolution)
73
+ mismatches.push("resolution");
74
+ if (condition.operator !== plan.operator)
75
+ mismatches.push("operator");
76
+ if (typeof condition.level !== "number" || condition.level !== plan.level)
77
+ mismatches.push("level");
78
+ if (!alert.active)
79
+ mismatches.push("active");
80
+ if (alert.expiration === null || Math.abs(Date.parse(String(alert.expiration)) - Date.parse(plan.expiration)) > 1_000) {
81
+ mismatches.push("expiration");
82
+ }
83
+ return { plan, status: mismatches.length === 0 ? "exact" : "conflict", alert, mismatches };
84
+ });
85
+ }