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:
- Auto BUY/SELL on EMA 9/21 crossover
- ATR-based Stop Loss with 1:2 risk/reward Take Profit
- One trade at a time — closes opposite position before opening new
- Magic number tracking — only manages its own trades
- Safety features — max spread filter, daily loss limit
The Strategy: EMA Crossover
The Exponential Moving Average (EMA) crossover is one of the oldest and simplest trend-following strategies:
- EMA 9 (fast) tracks recent price action
- EMA 21 (slow) tracks the broader trend
- When EMA 9 crosses above EMA 21 = BUY signal (bullish momentum)
- When EMA 9 crosses below EMA 21 = SELL signal (bearish momentum)
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 logicThis 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/rewardWhen the market is volatile, stops are wider. When it is calm, stops are tighter. This adapts to conditions automatically.
Safety Features
- Max spread filter — Skip trades when the spread is abnormally wide (news events, low liquidity)
- Daily loss limit — Stop trading entirely if losses exceed $50 in a day
- One trade at a time — Prevents overexposure
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:
- Backtesting — Run the strategy against historical data to measure win rate and drawdown
- Multi-indicator confirmation — Add MACD and Bollinger Bands to filter signals
- Trailing stop loss — Lock in profits as trades move in your favor
- Multi-timeframe analysis — Check H1 trend before taking M5 signals
- Dashboard panel — On-chart GUI showing live stats, open P/L, and trade history
Key Takeaways
-
MQL5 is approachable if you know any C-like language. The learning curve is in understanding MT5's indicator system and trade execution model.
-
Start with signals, then automate. Building a signal-only bot first lets you validate the strategy before risking capital.
-
Risk management is the product. The strategy is simple — the value is in how you manage risk, position sizing, and safety limits.
-
Demo accounts are your sandbox. Test everything with fake money first. The MetaQuotes demo gives you $10,000 to experiment with.
-
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.