Uses .env files for configuration management, allowing secure storage of MetaTrader5 broker credentials through environment variables.
Leverages pandas_ta library to provide technical indicators (SMA, EMA, RSI, MACD, Stochastic, Bollinger Bands) for market data analysis and charting.
Provides access to MetaTrader5 terminal functionality including market data retrieval, historical rates, tick data, symbol information, and real-time market streaming through Python integration.
MetaTrader5 MCP Server
A Model Context Protocol (MCP) server that provides access to MetaTrader5 market data and trading functionality.
Features
- Connect to MetaTrader5 terminal
- Retrieve symbol information and market data
- Get historical rates (OHLCV) for any timeframe
- Access tick data and market depth (DOM)
- Real-time market data streaming
- Support for all major trading instruments
Installation
- Install the MetaTrader5 terminal.
- Install Python dependencies:
Configuration
You can configure the server by creating a .env
file in the project root. This is optional, as the server can connect to an already running and logged-in MetaTrader5 terminal.
To pre-configure credentials, create a .env
file and add the following:
Timezone Configuration:
- If your MT5 server time is not UTC, set
MT5_TIME_OFFSET_MINUTES
in the.env
file to the offset in minutes (can be negative). - Example: For UTC+2, use
MT5_TIME_OFFSET_MINUTES=120
. For UTC-4, useMT5_TIME_OFFSET_MINUTES=-240
. - All timestamps are normalized to UTC using this offset.
Usage
Starting the MCP Server
The server exposes tools that can be called programmatically or via the command-line interface (cli.py
).
Available Tools (CLI)
The following tools are available via python cli.py <command>
:
Market Data
symbols_list [--search-term TERM] [--limit N]
- Smart search for trading symbols.symbols_list_groups [--search-term TERM] [--limit N]
- Get available symbol groups.symbols_describe <symbol>
- Get detailed symbol information.data_fetch_candles <symbol> [--timeframe TF] [--limit N]
- Get historical OHLCV data.data_fetch_ticks <symbol> [--limit N]
- Get tick data.market_depth_fetch <symbol>
- Get market depth (DOM).indicators_list
- List available technical indicators. (Uselist_capabilities --sections indicators --include-details true
for JSON details.)- CSV: grouped rows (category shown once per group): category,name Momentum,RSI ,MACD ,Stoch
- JSON: grouped by category
{ "categories": { "Momentum": ["RSI", ...], ... } }
indicators_describe <name>
- Get detailed information for a specific indicator.denoise_list_methods
- List available denoising methods and their parameters.patterns_detect_candlesticks <symbol> [--timeframe TF] [--limit N]
- Detect candlestick patterns.pivot_compute_points <symbol> [--timeframe TF] [--method METHOD]
- Compute pivot point levels.forecast_generate <symbol> [--timeframe TF] [--method METHOD] [--horizon N] ...
- Generate price forecasts.forecast_volatility_estimate <symbol> [--timeframe TF] [--horizon N] [--method METHOD] [--proxy PROXY]
- Forecast volatility using direct estimators, GARCH, or general forecasters on a proxy.report_generate <symbol> [--horizon N] [--template basic|advanced|scalping|intraday|swing|position]
- One-stop consolidated report rendered as Markdown (context, pivots, vol, backtest->best forecast, MC barriers; advanced adds regimes, HAR-RV, conformal). Templates infer timeframes.- Default horizons per template: scalping=8 bars, intraday=12, swing=24, position=30, basic/advanced=12. Override with
--horizon
or--params "horizon=..."
if needed.
- Default horizons per template: scalping=8 bars, intraday=12, swing=24, position=30, basic/advanced=12. Override with
list_capabilities [--sections ...] [--include-details true|false]
- Consolidated features: frameworks, forecast/volatility methods, denoise, indicators, dimred, and pattern_search backends.
(Note: Programmatic access uses function names like get_symbols
, get_rates
, etc.)
Example Usage
Sample Trade Guides
- Beginner flow: docs/SAMPLE-TRADE.md
- Advanced flow (regimes, HAR-RV, conformal, MC barriers, risk controls): docs/SAMPLE-TRADE-ADVANCED.md
One-Stop Consolidated Report
Fetching Data
Data Simplification
The data_fetch_candles
and data_fetch_ticks
commands support a powerful --simplify
and --simplify-params
option to downsample or transform data.
Modes & Methods:
1. SELECT Mode (Default)
lttb
(Largest Triangle Three Buckets): General-purpose downsampling preserving chart shaperdp
(Ramer-Douglas-Peucker): Error-tolerance based simplificationpla
(Piecewise Linear Approximation): Linear segment approximationapca
(Adaptive Piecewise Constant Approximation): Constant segment approximation
2. RESAMPLE Mode
- Buckets data into fixed time intervals
- Parameters:
bucket_seconds
(time window in seconds)
3. ENCODE Mode
envelope
: High/Low bands with Open/Close position encodingdelta
: Integer or character-encoded deltas of O/H/L/C vs previous close- Parameters:
bits
(precision),as_chars
(character output),alphabet
(custom symbols),scale
(delta tick size)
4. SEGMENT Mode (ZigZag)
zigzag
(alias:zz
): Detects price turning points and trend changes- Parameters:
threshold_pct
(minimum % change),value_col
(price column to analyze) - Preserves all original columns at pivot rows and adds:
value
,direction
,change_pct
.
5. SYMBOLIC Mode
sax
(Symbolic Aggregate approXimation): Converts time series to symbolic patterns- Parameters:
paa
(segments),alphabet
(symbol set),znorm
(z-normalization) - Preserves all requested columns via per-segment aggregation (mean for numeric columns). Time is represented by
start_time
andend_time
.
6. APPROXIMATE Mode
- Aggregates data into segments based on selected points
Simplify Method Comparison
Method | Best For | Output Size | Key Parameters |
---|---|---|---|
lttb | General downsampling | User-controlled | points , ratio |
rdp | Shape preservation | Varies | epsilon (tolerance) |
zigzag | Swing/trend analysis | Varies | threshold_pct |
sax | Pattern recognition | Fixed segments | paa , alphabet |
envelope /delta | Compact storage | Fixed | bits , as_chars , scale |
resample | Regular intervals | Time-based | bucket_seconds |
Notes:
- Encode preserves all requested columns (e.g., indicators, volumes); it replaces OHLC with envelope positions or deltas.
- When a transform changes columns, the response includes the exact output headers in metadata.
CLI Examples:
Forecasting
Generate point forecasts for the next horizon
bars. The server supports lightweight classical models, Monte Carlo/HMM simulation, and optional integrations with modern forecasting frameworks.
- Discover methods:
python cli.py list_capabilities --sections forecast
- Run forecast:
python cli.py forecast_generate <symbol> --timeframe <TF> --method <name> --horizon <N> [--params JSON]
- Rolling backtest:
python cli.py forecast_backtest_run <symbol> --timeframe <TF> --horizon <N> [--steps S --spacing K --methods ...]
- Volatility forecasts: use
forecast_volatility_estimate
with methods likeewma
,parkinson
,har_rv
,garch
, or generalarima
/ets
with a--proxy
(e.g.,log_r2
).
Classical example
HAR-RV volatility (daily RV from M5 returns)
Monte Carlo forecasts (distribution + bands)
Barrier analytics (TP/SL odds from MC paths)
For advanced usage, pattern-based signals, Monte Carlo/HMM details, and barrier analytics, see docs/FORECAST.md
.
Regime & Change-Points
Detect significant structural changes and market regimes to adapt strategies:
Use cp_prob
and change_points
from BOCPD to reset models/sizes after structural breaks; use state
/state_probabilities
from HMM/MS-AR to switch playbooks (trend vs. range) and adjust risk.
Conformal Prediction (Valid Intervals)
Build statistically valid prediction intervals around any base method:
This runs a rolling backtest to calibrate per-step residual quantiles and then returns point forecast + conformal bands.
Triple-Barrier Labeling
Create labels (+1 TP first, -1 SL first, 0 neither) for supervised learning and signal analysis:
Use these labels to train meta-models or to evaluate rule performance across regimes.
Closed-Form Barrier (GBM)
Compute single-barrier hit probability using GBM formulas (fast sanity check vs. MC):
Dimensionality Reduction (Pattern Search)
- Discover reducers:
python cli.py list_capabilities --sections dimred
- Use PCA quickly:
--pca-components 8
- Flexible:
--dimred-method pca|kpca|umap|isomap|diffusion|dreams_cne|dreams_cne_fast --dimred-params "key=value,..."
- Notes:
- Prefer reducers with transform support for online queries (e.g., PCA, KPCA, UMAP, parametric DREAMS-CNE).
- t-SNE/Laplacian embeddings cannot transform new queries; avoid for pattern_search.
- DREAMS-CNE requires installation from source;
dreams_cne_fast
uses lighter defaults for speed.
Optional Framework Integrations
You can extend forecasting with additional frameworks. Install as needed; methods will appear under forecast_methods
in list_capabilities
once available.
- StatsForecast (classical, fast):
pip install statsforecast
- Methods:
sf_autoarima
,sf_theta
,sf_autoets
,sf_seasonalnaive
- Methods:
- MLForecast (tree/GBMs over lags):
pip install mlforecast scikit-learn
(andlightgbm
for LGBM)- Methods:
mlf_rf
,mlf_lightgbm
- Methods:
- NeuralForecast (deep learning):
pip install neuralforecast[torch]
- Methods:
nhits
,nbeatsx
,tft
,patchtst
- Methods:
- Foundation models (Transformers/Chronos/TimesFM):
pip install transformers torch accelerate
(pluschronos-forecasting
ortimesfm
if desired)- Methods:
chronos_bolt
,timesfm
,lag_llama
- Methods:
See detailed examples and parameters in docs/FORECAST.md
under Framework Integrations.
Denoising
Apply smoothing algorithms to data columns.
- Methods:
ema
,sma
,median
,lowpass_fft
,wavelet
,emd
,eemd
,ceemdan
. - Discover methods:
python cli.py denoise_list_methods
Intelligent Symbol Search
The symbols_list
command uses a smart 3-tier search strategy:
- Group name match (e.g.,
Majors
,Forex
) - Symbol name match (e.g.,
EUR
→ EURUSD, JPYEUR, ...) - Description match (symbol or group path)
Date Inputs
The start
and end
parameters for data_fetch_candles
use dateparser
for flexible date/time parsing.
- Natural language:
yesterday 14:00
,2 days ago
- Common formats:
2025-08-29
,2025/08/29 14:30
Requirements
- Windows OS (MetaTrader5 requirement)
- MetaTrader5 terminal installed and running
- Python 3.8+
- Active internet connection
Optional dependencies (uncomment in requirements.txt
):
- Forecast frameworks:
statsforecast
,mlforecast
,lightgbm
,neuralforecast
- Foundation models:
transformers
,accelerate
,torch
,chronos-forecasting
,timesfm
- Pattern search backends:
hnswlib
,tslearn
,dtaidistance
- Dimensionality reduction:
scikit-learn
,umap-learn
,pydiffmap
,pykeops
, and DREAMS-CNE from source
Error Handling
All functions return a JSON object with a success
flag. If success
is false
, an error
field will contain the error message.
Security Notes
- For unattended use, store credentials securely in a
.env
file. - Do not commit
.env
files to version control. - Use demo accounts for testing.
License
MIT License
This server cannot be installed
local-only server
The server can only run on the client's local machine because it depends on local resources.
Enables access to MetaTrader5 market data and trading functionality, including real-time quotes, historical OHLCV data, tick data, symbol information, and technical indicators for forex and other trading instruments.
Related MCP Servers
- AsecurityAlicenseAqualityProvides real-time and historical cryptocurrency market data through integration with major exchanges. This server enables LLMs like Claude to fetch current prices, analyze market trends, and access detailed trading information.Last updated -754MIT License
- AsecurityFlicenseAqualityProvides real-time cryptocurrency price data from OKX exchange through a Model Context Protocol interface, allowing access to historical candlestick data and current market prices for any trading instrument.Last updated -2414
Twelve Data MCP Serverofficial
AsecurityAlicenseAqualityProvides integration with Twelve Data API to access financial market data including historical time series, real-time quotes, and instrument metadata for stocks, forex pairs, and cryptocurrencies.Last updated -3533MIT License