MS

0
Skip to main content

Building My First Algorithmic Trading Bot with MQL5: A Developer's Journey

March 31, 2026 (1d ago)

I have been writing software for 4.5 years — React Native apps, Node.js backends, full stack SaaS products. But I had never touched algorithmic trading. This week, I decided to change that.

In a single session, I went from opening MetaTrader 5 for the first time to having a working auto-trading bot placing real trades on a demo account. Here is everything I learned, the code I wrote, and the mistakes I made along the way.

Why Algorithmic Trading?

As a software engineer, trading bots sit at an interesting intersection: real-time data processing, mathematical models, risk management, and automation. The same principles I use to build production apps — clean architecture, safety checks, modular code — apply directly to trading systems.

MetaTrader 5 (MT5) is the most widely used platform for retail algorithmic trading. It uses MQL5, a C-like language that runs inside the platform. If you know C, C++, or even JavaScript, picking up MQL5 is straightforward.

What I Built

I built three bots, each more capable than the last:

1. SignalBot (Strict)

The first bot — a signal-only EA that alerts you when trading conditions are met but does not place any trades.

Strategy: EMA 9/21 crossover + RSI 14 filter + candle close confirmation

This was intentionally strict. All three conditions had to align simultaneously, which meant signals were rare. Good for accuracy, but I needed something more responsive to verify the bot was actually working.

2. SignalBotLite (Loose)

A relaxed version that fires on any EMA crossover without requiring RSI confirmation or candle close checks. The key addition: historical scanning — on startup, it scans the last 200 bars and draws arrows on past signals so you can immediately see the strategy in action.

This was the "aha" moment. Seeing green and red arrows populate across the chart made the strategy tangible.

3. AutoTrader (Full Auto)

The final bot — takes the EMA crossover strategy and adds real trade execution:

The Strategy: EMA Crossover

The Exponential Moving Average (EMA) crossover is one of the oldest and simplest trend-following strategies:

bool bullishCross = (fastPrev <= slowPrev) && (fastCurr > slowCurr);
bool bearishCross = (fastPrev >= slowPrev) && (fastCurr < slowCurr);

Simple, but it works as a foundation. The key is what you layer on top — RSI filters, ATR-based stops, position management.

MQL5 Fundamentals I Learned

The Three Core Functions

Every Expert Advisor (EA) in MQL5 has three functions:

int OnInit()     // Runs once when EA starts — setup indicators
void OnDeinit()  // Runs when EA is removed — cleanup
void OnTick()    // Runs on every price tick — your main logic

This is similar to React's component lifecycle (useEffect mount/unmount) or a game loop. OnTick is where all the action happens.

Indicator Handles

MQL5 uses a handle-based system for indicators. You create a handle once in OnInit(), then read values from it in OnTick():

// Create handle (once)
int handle = iMA(_Symbol, PERIOD_M5, 9, 0, MODE_EMA, PRICE_CLOSE);
 
// Read values (every tick)
double values[];
CopyBuffer(handle, 0, 1, 3, values);

This is efficient — the platform calculates indicator values internally and you just read the buffer.

The CTrade Library

MQL5 provides a built-in CTrade class that simplifies order execution:

#include <Trade\Trade.mqh>
 
CTrade trade;
trade.SetExpertMagicNumber(123456);
trade.Buy(0.01, _Symbol, ask, sl, tp, "My trade");
trade.Sell(0.01, _Symbol, bid, sl, tp, "My trade");
trade.PositionClose(ticket);

The magic number is crucial — it lets your EA identify which trades belong to it, so multiple EAs can run on the same account without interfering.

Risk Management: The Non-Negotiable

The most important lesson: risk management is not optional. My bot includes:

ATR-Based Stop Loss

Instead of fixed pip values, I use the Average True Range (ATR) to set stops dynamically based on market volatility:

double slDistance = atrValue * 1.5;  // 1.5x ATR
double tpDistance = slDistance * 2.0; // 2x SL = 1:2 risk/reward

When the market is volatile, stops are wider. When it is calm, stops are tighter. This adapts to conditions automatically.

Safety Features

Mistakes I Made

1. MT5 on Mac Has Quirks

Copy-paste does not work reliably in MetaEditor on macOS. I had to save the file externally and open it directly. If you are on Mac, save your .mq5 files in the MT5 data folder and open from there.

2. Strict Conditions = No Signals

My first bot required EMA crossover + RSI in range + candle close confirmation. On M5, this combination is rare. I waited and saw nothing. The fix: make conditions configurable and start loose for testing.

3. Confusing MQL5 Login with Broker Login

MT5 has two separate logins — your broker account (for trading) and your MQL5 community account (for the marketplace). They are completely independent. The broker login is what matters for trading.

What is Next

This is day one. The bot works, but it is basic. Here is what I plan to build next:

Key Takeaways

  1. MQL5 is approachable if you know any C-like language. The learning curve is in understanding MT5's indicator system and trade execution model.

  2. Start with signals, then automate. Building a signal-only bot first lets you validate the strategy before risking capital.

  3. Risk management is the product. The strategy is simple — the value is in how you manage risk, position sizing, and safety limits.

  4. Demo accounts are your sandbox. Test everything with fake money first. The MetaQuotes demo gives you $10,000 to experiment with.

  5. The same engineering principles apply. Clean code, modular functions, input validation, error handling — the same TypeScript best practices and engineering discipline that make good production apps also make good trading bots.

If you are a developer curious about algorithmic trading, just start. Open MT5, create a demo account, and write your first EA. The barrier to entry is lower than you think.


I am Manjodh Singh Saran, a Senior Software Engineer building products across web, mobile, and now algorithmic trading. Follow my journey on LinkedIn.

Related Articles

MS
Manjodh Singh Saran

Full Stack Developer · Ludhiana, India

Read more articles · View portfolio