DEV Community

How I Built an MT5 Trading Bot with Python and Smart Money Concept

Why Python over MQL5?

While MQL5 runs natively inside MetaTrader 5, Python offers a much richer ecosystem:

  • Machine learning libraries (scikit-learn, PyTorch) for signal scoring
  • Easy integration with Telegram, databases, and web dashboards
  • Better debugging with modern IDEs

The official MetaTrader5 Python package lets you connect directly to the terminal:

import MetaTrader5 as mt5

if not mt5.initialize():
    print("Connection failed:", mt5.last_error())
    quit()

# Get latest candles
rates = mt5.copy_rates_from_pos('XAUUSD', mt5.TIMEFRAME_M15, 0, 100)

The Core Architecture

My bot has four main components:

  • Data layer - connects to MT5, fetches real-time prices and historical candles
  • Signal logic - analyzes market using Smart Money Concept (Order Blocks, FVG, BOS)
  • Risk management - calculates position size based on account risk percentage
  • Execution - places orders with proper SL/TP via the API

Smart Money Concept for Entries

Instead of traditional indicators, I use SMC to identify institutional footprints:

  • Order Blocks - zones where big players placed orders before strong moves
  • Fair Value Gaps - price imbalances that often get filled
  • Liquidity Sweeps - stop hunts before real reversals

The key insight: a valid Order Block requires the impulse candle after it to be significantly larger than average (1.5-1.8x), not just slightly bigger.

Position Sizing Done Right

A common mistake is hardcoding lot calculation for one symbol. The correct approach uses tick_value and tick_size from MT5, which works universally across gold, forex pairs, and indices:

info = mt5.symbol_info(symbol)
risk_usd = balance * risk_percent
n_ticks = sl_distance / info.trade_tick_size
lot = risk_usd / (n_ticks * info.trade_tick_value)

Adding a Machine Learning Layer

The most interesting part: I log every trade's context (ATR, RSI, session, entry position in the Order Block) along with its outcome. A simple logistic regression model then learns which setups have higher win probability, filtering out low-quality signals. With 200+ trades of data, the model starts recognizing patterns like "this setup wins more during London session when RSI is below 40."

Lessons Learned

  • Rigid entry conditions kill opportunities - I initially required BOS + sweep simultaneously, which made the bot miss most valid setups. Relaxing to weighted signals improved results significantly.
  • Feature sync matters - ML features must stay identical between the bot's inference and the training pipeline, or you get silent failures.
  • Backtest properly - walk-forward testing on out-of-sample data is essential to avoid overfitting.

Full Documentation

I've written detailed guides (in Vietnamese) covering each topic in depth:

  • Complete MT5 Python Bot Guide
  • Smart Money Concept Explained
  • Risk Management Fundamentals
  • AI & Machine Learning for Trading

Disclaimer: Trading forex and CFDs carries high risk. This content is educational, not financial advice.

Comments

No comments yet. Start the discussion.