-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·1437 lines (1116 loc) · 39.6 KB
/
server.py
File metadata and controls
executable file
·1437 lines (1116 loc) · 39.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
TradingView MCP Server - Professional Multi-Asset Trading Assistant
Provides real-time market data, technical analysis, and trading recommendations
via Model Context Protocol (MCP) for Claude Desktop integration.
Supported Assets:
- Forex (22+ pairs + gold)
- Stocks (US equities)
- Crypto (BTC, ETH, and major cryptocurrencies)
Data Sources:
- Alpha Vantage API for real-time quotes and historical data
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
from typing import Any, Dict, List
# Setup logging
log_dir = Path(__file__).parent.parent / "logs"
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.StreamHandler(sys.stderr),
logging.FileHandler(log_dir / "tradingview_mcp.log"),
],
)
logger = logging.getLogger(__name__)
# Add project root to path
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP
# Load environment variables
load_dotenv(PROJECT_ROOT / ".env")
# Validate environment setup
import os
# Import our refactored modules
from tradingview_mcp.api import AlphaVantageClient
from tradingview_mcp.config import (
CRYPTO_SYMBOLS,
DEFAULT_SPREAD,
FOREX_PAIRS,
HIGH_RISK_PAIRS,
KNOWN_CORRELATIONS,
MAJOR_PAIRS,
POPULAR_STOCKS,
TYPICAL_SPREADS,
)
from tradingview_mcp.indicators import (
calculate_adx,
calculate_atr,
calculate_bollinger_bands,
calculate_cci,
calculate_fibonacci_levels,
calculate_ichimoku,
calculate_macd,
calculate_market_profile,
calculate_moving_averages,
calculate_pivot_points,
calculate_rsi,
calculate_stochastic,
calculate_volume_profile,
calculate_vwap,
calculate_williams_r,
detect_gaps,
detect_support_resistance,
)
# Import Pine Script modules
from tradingview_mcp.pine_script import (
ErrorExplainer,
PineAutocomplete,
PineDocumentation,
PineSandbox,
PineScriptValidator,
VersionConverter,
VersionDetector,
)
from tradingview_mcp.utils import (
detect_asset_type,
format_error_response,
format_success_response,
validate_api_key,
)
api_key = os.getenv("ALPHA_VANTAGE_API_KEY")
if api_key:
is_valid, error_msg = validate_api_key(api_key)
if not is_valid:
logger.warning(f"API key validation warning: {error_msg}")
else:
logger.error("ALPHA_VANTAGE_API_KEY not set. Server will not function properly.")
# Initialize API client
api_client = AlphaVantageClient()
# Initialize Pine Script components
pine_validator = PineScriptValidator()
pine_docs = PineDocumentation()
pine_sandbox = PineSandbox()
pine_errors = ErrorExplainer()
pine_version_detector = VersionDetector()
pine_version_converter = VersionConverter()
pine_autocomplete = PineAutocomplete()
# Initialize MCP server
mcp = FastMCP(
name="TradingView Multi-Asset Trading Assistant",
instructions=(
"Professional trading assistant providing real-time market data, "
"technical analysis, and trading recommendations for multiple asset classes. "
"Supports Forex (22+ pairs), Stocks (US equities), and Crypto (BTC, ETH, etc). "
"Includes advanced tools: Volume Profile, Market Profile, VWAP, Fibonacci, "
"Bollinger Bands, MACD, Moving Averages, ATR, Support/Resistance, Pivot Points, "
"Stochastic, ADX, Ichimoku Cloud, and more. "
"\n\n"
"PINE SCRIPT SUPPORT: Comprehensive Pine Script development tools including "
"real-time syntax validation, function documentation, code testing sandbox, "
"error explanations, version detection (v1-v6), version conversion, and "
"intelligent autocomplete. Full support for Pine Script v6 with type, enum, and map!"
),
)
logger.info("TradingView MCP Server initialized")
# ===== HELPER FUNCTIONS =====
def get_quote(symbol: str) -> Dict[str, Any]:
"""
Universal quote fetcher for all asset types.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
Returns:
Quote data or error
"""
asset_type, formatted_symbol = detect_asset_type(symbol)
logger.info(f"Fetching quote for {symbol} (type: {asset_type})")
if asset_type == "forex":
return api_client.get_forex_quote(formatted_symbol)
elif asset_type == "crypto":
return api_client.get_crypto_quote(formatted_symbol)
else: # stock
return api_client.get_stock_quote(formatted_symbol)
def get_historical_data(
symbol: str, timeframe: str = "1h", outputsize: str = "compact"
) -> Dict[str, Any]:
"""
Get historical data for any asset type.
Args:
symbol: Symbol to fetch
timeframe: Timeframe (5m, 15m, 30m, 1h, 4h, 1d)
outputsize: 'compact' or 'full'
Returns:
Historical OHLCV data or error
"""
asset_type, formatted_symbol = detect_asset_type(symbol)
logger.info(f"Fetching historical data for {symbol} ({timeframe})")
# Route to appropriate API method based on asset type
if asset_type == "forex":
return api_client.get_historical_data_forex(
formatted_symbol, timeframe, outputsize
)
elif asset_type == "crypto":
return api_client.get_historical_data_crypto(
formatted_symbol, timeframe, outputsize
)
else: # stock
return api_client.get_historical_data_stock(
formatted_symbol, timeframe, outputsize
)
def get_spread(pair: str) -> float:
"""Get typical spread for a pair."""
return TYPICAL_SPREADS.get(pair, DEFAULT_SPREAD)
# ===== MCP TOOLS: SERVER MANAGEMENT =====
@mcp.tool()
def health_check() -> dict:
"""
Check server health and API connectivity status.
Returns:
Server health information including version, cache stats, and API status
"""
# Check API key configuration
api_key_configured = bool(api_client.api_key)
# Get cache statistics
cache_stats = api_client.cache.get_stats()
# Server version (from pyproject.toml)
version = "3.3.0"
return {
"status": "healthy" if api_key_configured else "degraded",
"version": version,
"api_key_configured": api_key_configured,
"cache": {
"size": cache_stats["size"],
"max_size": cache_stats["max_size"],
"hit_rate": cache_stats["hit_rate"],
"utilization": cache_stats["utilization"],
"evictions": cache_stats["evictions"],
},
"total_api_calls": api_client._total_calls,
"warnings": (
[]
if api_key_configured
else ["API key not configured - server will not function properly"]
),
}
# ===== MCP TOOLS: MARKET DATA =====
@mcp.tool()
def get_price(symbol: str) -> dict:
"""
Get current price for any asset (Forex, Stock, or Crypto).
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC', 'TSLA')
Returns:
Current price, bid/ask, asset type, and additional data
"""
quote = get_quote(symbol)
if "error" in quote:
return quote
return {
"symbol": quote.get("symbol", symbol),
"asset_type": quote.get("asset_type", "unknown"),
"price": quote.get("price"),
"bid": quote.get("bid"),
"ask": quote.get("ask"),
"timestamp": quote.get("timestamp"),
**{
k: v
for k, v in quote.items()
if k not in ["symbol", "asset_type", "price", "bid", "ask", "timestamp"]
},
}
@mcp.tool()
def get_multiple_prices(symbols: List[str]) -> list:
"""
Get current prices for multiple symbols at once.
Args:
symbols: List of symbols (e.g., ['EURUSD', 'AAPL', 'BTC'])
Returns:
List of price quotes for each symbol
"""
results = []
for symbol in symbols:
results.append(get_price(symbol))
return results
@mcp.tool()
def list_available_pairs() -> dict:
"""
List all available forex pairs organized by category.
Returns:
Dictionary with majors, crosses, exotics, and commodities
"""
majors = [p for p in MAJOR_PAIRS if p in FOREX_PAIRS]
exotics = ["USDTRY", "USDZAR", "USDMXN", "USDBRL"]
commodities = ["XAUUSD"]
crosses = [
p
for p in FOREX_PAIRS
if p not in majors and p not in exotics and p not in commodities
]
return {
"total_pairs": len(FOREX_PAIRS),
"majors": majors,
"crosses": crosses,
"exotics": exotics,
"commodities": commodities,
"all_pairs": FOREX_PAIRS,
}
@mcp.tool()
def list_supported_assets() -> dict:
"""
List all supported assets by category.
Returns:
Forex pairs, popular stocks, cryptocurrencies
"""
return {
"forex": {
"count": len(FOREX_PAIRS),
"majors": FOREX_PAIRS[:7],
"crosses": FOREX_PAIRS[7:16],
"exotics": FOREX_PAIRS[16:20],
"commodities": ["XAUUSD"],
},
"stocks": {
"count": len(POPULAR_STOCKS),
"popular": POPULAR_STOCKS[:20],
"etfs": ["SPY", "QQQ", "IWM", "DIA"],
},
"crypto": {
"count": len(CRYPTO_SYMBOLS),
"major": CRYPTO_SYMBOLS[:8],
"altcoins": CRYPTO_SYMBOLS[8:],
},
"note": "Any valid symbol can be queried - these are just popular examples",
}
# ===== MCP TOOLS: TECHNICAL ANALYSIS =====
@mcp.tool()
def analyze_pair(symbol: str, timeframe: str = "1h") -> dict:
"""
Comprehensive technical analysis for any symbol.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
Detailed analysis including price, indicators, and trading recommendation
"""
# Get current price
quote = get_quote(symbol)
if "error" in quote:
return quote
asset_type = quote.get("asset_type", "unknown")
# Get historical data for analysis
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
# Return basic quote if can't get historical data
return {
"symbol": symbol,
"asset_type": asset_type,
"timeframe": timeframe,
"current_price": quote["price"],
"bid": quote["bid"],
"ask": quote["ask"],
"timestamp": quote["timestamp"],
"note": "Limited analysis - historical data unavailable",
}
# Calculate indicators
ma = calculate_moving_averages(hist_data["data"])
bb = calculate_bollinger_bands(hist_data["data"])
# Generate signals and recommendation
signals = []
recommendation = "NEUTRAL"
# Analyze Bollinger Bands
if "percent_b" in bb:
if bb["percent_b"] > 1:
signals.append("Price above upper Bollinger Band (overbought)")
recommendation = "SELL"
elif bb["percent_b"] < 0:
signals.append("Price below lower Bollinger Band (oversold)")
recommendation = "BUY"
# Risk classification
if asset_type == "forex" and symbol in HIGH_RISK_PAIRS:
risk_level = "HIGH"
elif asset_type == "forex" and symbol in MAJOR_PAIRS:
risk_level = "LOW"
else:
risk_level = "MEDIUM"
return {
"symbol": symbol,
"asset_type": asset_type,
"timeframe": timeframe,
"current_price": quote["price"],
"bid": quote["bid"],
"ask": quote["ask"],
"timestamp": quote["timestamp"],
"moving_averages": ma,
"bollinger_bands": bb,
"signals": signals,
"recommendation": recommendation,
"risk_level": risk_level,
}
@mcp.tool()
def calculate_correlation(pair1: str, pair2: str, period: int = 30) -> dict:
"""
Calculate correlation between two forex pairs.
Args:
pair1: First forex pair
pair2: Second forex pair
period: Number of days to analyze (default 30)
Returns:
Correlation coefficient and relationship strength
"""
pair1 = pair1.upper().replace("/", "").replace("_", "")
pair2 = pair2.upper().replace("/", "").replace("_", "")
# Check known correlations
correlation = KNOWN_CORRELATIONS.get((pair1, pair2)) or KNOWN_CORRELATIONS.get(
(pair2, pair1)
)
if correlation is None:
correlation = 0.0 # Unknown correlation
# Determine strength
abs_corr = abs(correlation)
if abs_corr > 0.8:
strength = "VERY STRONG"
elif abs_corr > 0.6:
strength = "STRONG"
elif abs_corr > 0.4:
strength = "MODERATE"
elif abs_corr > 0.2:
strength = "WEAK"
else:
strength = "VERY WEAK"
relationship = (
"POSITIVE" if correlation > 0 else "NEGATIVE" if correlation < 0 else "NEUTRAL"
)
return {
"pair1": pair1,
"pair2": pair2,
"correlation": round(correlation, 3),
"strength": strength,
"relationship": relationship,
"period_days": period,
"interpretation": f"{pair1} and {pair2} have a {strength} {relationship} correlation ({correlation:.2f})",
}
# ===== MCP TOOLS: FIBONACCI & PIVOT POINTS =====
@mcp.tool()
def get_fibonacci_retracement(symbol: str, timeframe: str = "1h") -> dict:
"""
Calculate Fibonacci retracement levels.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
Fibonacci levels (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%)
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
levels = calculate_fibonacci_levels(hist_data["data"])
if "error" in levels:
return levels
return {
"symbol": symbol,
"timeframe": timeframe,
"levels": levels,
"interpretation": "Key retracement levels where price may find support/resistance",
}
@mcp.tool()
def get_pivot_points(symbol: str, timeframe: str = "1h") -> dict:
"""
Calculate pivot points for intraday trading.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
Pivot point, 3 resistance levels, 3 support levels
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
pivots = calculate_pivot_points(hist_data["data"])
if "error" in pivots:
return pivots
return {"symbol": symbol, "timeframe": timeframe, **pivots}
# ===== MCP TOOLS: TREND INDICATORS =====
@mcp.tool()
def get_moving_averages(symbol: str, timeframe: str = "1h") -> dict:
"""
Calculate multiple moving averages (20, 50, 100, 200 period SMA/EMA).
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
SMAs and EMAs for 20, 50, 100, 200 periods and current price
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
mas = calculate_moving_averages(hist_data["data"])
return {
"symbol": symbol,
"timeframe": timeframe,
**mas,
"interpretation": "Compare current price to MA levels to identify trend direction",
}
@mcp.tool()
def get_macd(symbol: str, timeframe: str = "1h") -> dict:
"""
Calculate MACD (Moving Average Convergence Divergence).
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
MACD line, signal line, histogram, and trading signal
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
macd = calculate_macd(hist_data["data"])
if "error" in macd:
return macd
return {
"symbol": symbol,
"timeframe": timeframe,
**macd,
"interpretation": f"MACD is {macd['signal']}. Histogram: {macd['histogram']:.5f}",
}
@mcp.tool()
def get_adx(symbol: str, timeframe: str = "1h", period: int = 14) -> dict:
"""
Calculate ADX (Average Directional Index) - trend strength indicator.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
period: Period for calculation (default 14)
Returns:
ADX value, +DI, -DI, and trend strength classification
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
adx = calculate_adx(hist_data["data"], period)
if "error" in adx:
return adx
return {
"symbol": symbol,
"timeframe": timeframe,
**adx,
"interpretation": f"Trend strength is {adx['trend_strength']} (ADX: {adx['adx']:.1f})",
}
@mcp.tool()
def get_ichimoku_cloud(symbol: str, timeframe: str = "1h") -> dict:
"""
Calculate Ichimoku Cloud components.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
Tenkan-sen, Kijun-sen, Senkou Span A/B, cloud position
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
ichimoku = calculate_ichimoku(hist_data["data"])
if "error" in ichimoku:
return ichimoku
return {"symbol": symbol, "timeframe": timeframe, **ichimoku}
# ===== MCP TOOLS: MOMENTUM INDICATORS =====
@mcp.tool()
def get_stochastic(symbol: str, timeframe: str = "1h", period: int = 14) -> dict:
"""
Calculate Stochastic Oscillator.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
period: Period for calculation (default 14)
Returns:
%K and %D values, signal (OVERBOUGHT/OVERSOLD/NEUTRAL)
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
stoch = calculate_stochastic(hist_data["data"], period)
if "error" in stoch:
return stoch
return {"symbol": symbol, "timeframe": timeframe, **stoch}
@mcp.tool()
def get_rsi(symbol: str, timeframe: str = "1h", period: int = 14) -> dict:
"""
Calculate RSI (Relative Strength Index).
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
period: Period for calculation (default 14)
Returns:
RSI value and signal (OVERBOUGHT/OVERSOLD/NEUTRAL)
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
rsi = calculate_rsi(hist_data["data"], period)
if "error" in rsi:
return rsi
return {"symbol": symbol, "timeframe": timeframe, **rsi}
@mcp.tool()
def get_cci(symbol: str, timeframe: str = "1h", period: int = 20) -> dict:
"""
Calculate CCI (Commodity Channel Index).
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
period: Period for calculation (default 20)
Returns:
CCI value and signal (OVERBOUGHT/OVERSOLD/NEUTRAL)
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
cci = calculate_cci(hist_data["data"], period)
if "error" in cci:
return cci
return {"symbol": symbol, "timeframe": timeframe, **cci}
@mcp.tool()
def get_williams_r(symbol: str, timeframe: str = "1h", period: int = 14) -> dict:
"""
Calculate Williams %R.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
period: Period for calculation (default 14)
Returns:
Williams %R value and signal (OVERBOUGHT/OVERSOLD/NEUTRAL)
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
williams = calculate_williams_r(hist_data["data"], period)
if "error" in williams:
return williams
return {"symbol": symbol, "timeframe": timeframe, **williams}
# ===== MCP TOOLS: VOLATILITY INDICATORS =====
@mcp.tool()
def get_bollinger_bands(symbol: str, timeframe: str = "1h", period: int = 20) -> dict:
"""
Calculate Bollinger Bands.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
period: Period for calculation (default 20)
Returns:
Upper band, middle band (SMA), lower band, and %B indicator
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
bb = calculate_bollinger_bands(hist_data["data"], period)
if "error" in bb:
return bb
return {"symbol": symbol, "timeframe": timeframe, **bb}
@mcp.tool()
def get_atr(symbol: str, timeframe: str = "1h", period: int = 14) -> dict:
"""
Calculate Average True Range (ATR) - volatility indicator.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
period: Period for calculation (default 14)
Returns:
ATR value and percentage
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
atr = calculate_atr(hist_data["data"], period)
if "error" in atr:
return atr
return {"symbol": symbol, "timeframe": timeframe, **atr}
# ===== MCP TOOLS: VOLUME INDICATORS =====
@mcp.tool()
def get_vwap(symbol: str, timeframe: str = "1h") -> dict:
"""
Calculate VWAP (Volume Weighted Average Price).
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
VWAP value and current price comparison
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
vwap = calculate_vwap(hist_data["data"])
# Get current price
current_quote = get_quote(symbol)
if "error" in current_quote:
return current_quote
current_price = current_quote["price"]
deviation = ((current_price - vwap) / vwap) * 100 if vwap > 0 else 0
return {
"symbol": symbol,
"timeframe": timeframe,
"vwap": round(vwap, 5),
"current_price": current_price,
"deviation_percent": round(deviation, 2),
"signal": "ABOVE_VWAP" if current_price > vwap else "BELOW_VWAP",
"interpretation": f"Price is {abs(deviation):.2f}% {'above' if deviation > 0 else 'below'} VWAP. "
f"{'Bullish' if deviation > 0 else 'Bearish'} pressure indicated.",
}
@mcp.tool()
def get_volume_profile(
symbol: str, timeframe: str = "1h", num_levels: int = 20
) -> dict:
"""
Get volume profile analysis.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
num_levels: Number of price levels to analyze (default 20)
Returns:
Volume profile with POC, high/low volume nodes, and price levels
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
profile = calculate_volume_profile(hist_data["data"], num_levels)
if "error" in profile:
return profile
return {
"symbol": symbol,
"timeframe": timeframe,
**profile,
"interpretation": f"POC at {profile['poc']:.5f} shows highest traded volume. "
f"High volume nodes indicate support/resistance zones.",
}
@mcp.tool()
def get_market_profile(symbol: str, timeframe: str = "1h") -> dict:
"""
Get market profile analysis with TPO, POC, and value areas.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
Market profile with POC, value area high/low, and TPO data
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
profile = calculate_market_profile(hist_data["data"])
if "error" in profile:
return profile
return {"symbol": symbol, "timeframe": timeframe, **profile}
# ===== MCP TOOLS: SUPPORT/RESISTANCE =====
@mcp.tool()
def get_support_resistance(symbol: str, timeframe: str = "1h") -> dict:
"""
Detect support and resistance levels automatically.
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
Top 3 support and resistance levels
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
sr = detect_support_resistance(hist_data["data"])
return {"symbol": symbol, "timeframe": timeframe, **sr}
@mcp.tool()
def detect_unfilled_gaps(symbol: str, timeframe: str = "1h") -> dict:
"""
Detect unfilled price gaps (unfinished business areas).
Args:
symbol: Symbol (e.g., 'EURUSD', 'AAPL', 'BTC')
timeframe: Time interval ('5m', '15m', '1h', '4h', '1d')
Returns:
List of unfilled gaps with price levels and timestamps
"""
hist_data = get_historical_data(symbol, timeframe)
if not hist_data.get("success"):
return hist_data
gaps = detect_gaps(hist_data["data"])
# Get current price to check if gaps are still unfilled
current_quote = get_quote(symbol)
if "error" not in current_quote:
current_price = current_quote["price"]
for gap in gaps:
# Check if gap is filled
if gap["type"] == "gap_up" and current_price < gap["to_price"]:
gap["filled"] = True
elif gap["type"] == "gap_down" and current_price > gap["to_price"]:
gap["filled"] = True
unfilled_gaps = [g for g in gaps if not g["filled"]]
return {
"symbol": symbol,
"timeframe": timeframe,
"total_gaps": len(gaps),
"unfilled_gaps": len(unfilled_gaps),
"gaps": unfilled_gaps[:10], # Return top 10
"interpretation": f"Found {len(unfilled_gaps)} unfilled gaps. These often act as magnets for price action.",
}
# ===== MCP TOOLS: SYSTEM =====
@mcp.tool()
def get_server_stats() -> dict:
"""
Get server statistics including API usage and cache performance.
Returns:
Server statistics
"""
return {"status": "online", **api_client.get_stats()}