You've reached the frontier of modern trading: Algorithmic Trading. If your strategy has 100% objective rules, a computer can execute it perfectly, 24/5, without emotion. Automation executes your rules with flawless discipline—every tick, every time—eliminating psychological risk and maximizing your edge.
Welcome to Lesson 66
You've designed, validated, and optimized a robust trading strategy. You understand risk management, position sizing, and psychological challenges. The final evolution is automation—letting a computer execute your proven edge while you sleep.
Algorithmic Trading, executed through Expert Advisors (EAs) or Bots, is computerized execution of your rule-based strategy.
The Automation Promise: Eliminate greed, fear, revenge trading. Ensure flawless 1% Risk Rule adherence. Monitor multiple pairs simultaneously. Execute at 3 AM while sleeping. This is algorithmic trading power.
But automation is not magic—it's a force multiplier. If your strategy has positive Expectancy, automation amplifies profits. If poorly designed, automation amplifies losses at machine speed.
This lesson introduces algorithmic trading, focusing on MQL4 and MQL5—programming languages for MetaTrader platforms dominating retail forex.
Lesson Chapters
1Chapter 1: Algorithmic Trading — What It Is & Why It Matters⏱️ ~5 min
Algorithmic Trading = Pre-programmed computer instructions to automatically place trades based on your analytical and risk criteria.
🤖 What an EA Does for You
Think of Expert Advisor as tireless assistant:
1. Monitors Markets 24/5
- Watches multiple pairs simultaneously
- Never sleeps, never breaks
- Catches setups at 3 AM
- Monitors every tick (milliseconds)
2. Analyzes Per Your Rules
- Checks H4 trend (HH + HL)
- Identifies MSS on M15
- Locates un-mitigated Order Blocks
- Measures Fair Value Gaps
- All based on YOUR defined criteria
3. Executes Without Emotion
- No fear after 3 losses
- No greed for quick profits
- No revenge trading
- No hesitation on valid setups
- Pure mechanical execution
4. Manages Risk Perfectly
- Calculates exact lot size for 1% risk
- Places SL at precise level
- Moves SL to BE at 1:1 R:R
- Scales out at targets
- Trails stops per rules
- Never violates risk rules
5. Runs Despite Your Absence
- Holiday? EA trading
- Sick? EA monitoring
- Asleep? EA executing
- 24/5 operation
⚖️ Manual vs. Automated Trading
Factor | Manual Trading | Algo Trading (EA) |
---|---|---|
Emotion | Constant battle | Zero emotion |
Discipline | 80-90% rule adherence | 100% rule adherence |
Monitoring | Limited hours | 24/5 continuous |
Execution Speed | Seconds | Milliseconds |
Multi-Pair | 1-2 pairs max focus | 10+ pairs simultaneously |
Fatigue | Yes (mistakes increase) | Never tired |
Consistency | Variable | Perfect |
Learning Curve | Moderate | High (coding required) |
Initial Setup | Quick | Time-intensive |
Flexibility | High (adapt quickly) | Low (need to recode) |
The Truth:
- Manual = flexible but emotional
- Automated = rigid but flawless
- Best approach: Combine both
Critical Prerequisite: Only automate strategies that are: 1) 100% objective rules (no discretion), 2) Proven profitable through backtesting/forward testing, 3) Simple enough to code accurately. Never automate a losing or untested strategy.
2Chapter 2: Expert Advisors vs. Indicators⏱️ ~4 min
Understanding the difference between EAs and Indicators is fundamental to MetaTrader automation.
📊 Custom Indicators
What Indicators Do:
- Display information on charts
- Calculate values (RSI, MA, custom metrics)
- Draw lines, boxes, arrows
- Cannot place trades
- Cannot manage risk
Examples:
- RSI showing 35 (oversold)
- Moving Average line on chart
- Custom Order Block highlighter
- Fair Value Gap box drawer
- Visual aids only
Use Cases:
- Mark Order Blocks automatically
- Highlight FVG zones
- Show MSS/BOS signals
- Calculate OTE zones
- Help YOU make decisions
🤖 Expert Advisors (EAs)
What EAs Do:
- Execute trades automatically
- Place orders (market, limit, stop)
- Manage positions (modify SL/TP, close)
- Calculate lot sizes
- Monitor multiple pairs
- Run 24/5 without supervision
Examples:
- Order Block EA (enters at OB zones)
- Grid trading bot
- Scalping EA
- SMC automation system
- Full automation
Use Cases:
- Automate proven strategy
- Remove emotion from execution
- Trade while sleeping
- Monitor 10+ pairs simultaneously
- Let computer do the work
🔄 How They Work Together
Common Setup:
Indicator (Visual Aid):
- Shows you where Order Blocks are
- Highlights Fair Value Gaps
- Marks MSS/BOS events
- YOU decide to trade
EA (Execution Engine):
- Monitors for OB + MSS + OTE conditions
- Automatically enters when ALL met
- Manages SL, BE, TP per rules
- EA decides AND executes
Hybrid Approach (Recommended for Beginners):
- Use indicators to identify setups
- EA only manages trade after YOU enter manually
- You control entries, EA controls risk management
Professional Advice: Start with custom indicators for visual confirmation. Graduate to semi-automated EAs (you approve entries). Only move to full automation after 6+ months of manual profitable trading.
3Chapter 3: Introduction to MQL4 and MQL5⏱️ ~6 min
MQL (MetaQuotes Language) is the programming language for creating EAs and indicators on MetaTrader.
💻 MQL4 vs. MQL5
MQL4:
- For MetaTrader 4 platform
- Simpler syntax
- Easier for beginners
- Large community, many resources
- Still widely used
MQL5:
- For MetaTrader 5 platform
- More powerful, object-oriented
- Faster execution
- Better for complex strategies
- Modern standard
Which to Learn:
- MT4 user → MQL4
- MT5 user → MQL5
- New to both → MQL5 (future-proof)
- Both similar enough to transfer knowledge
🔧 Core MQL Concepts
Key Functions Every EA Uses:
1. OnInit() — Runs once when EA starts
Use for: Setup, initialization, parameter validation
Example: Check if account has enough margin
2. OnTick() — Runs every price tick
Use for: Main strategy logic, check entry conditions
Example: "Is there MSS + OB + OTE? → Enter"
This runs thousands of times per day
3. OnDeinit() — Runs when EA stops
Use for: Cleanup, close positions if needed
Example: Close all trades when EA removed from chart
4. OrderSend() — Places new trade order
Use for: Executing buy/sell orders
Parameters: Symbol, Type, Lots, Price, Slippage, SL, TP
Example: Buy 0.5 lots EUR/USD at market
5. OrderModify() — Changes existing order
Use for: Moving SL to break-even, adjusting TP
Example: At 1:1 R:R, move SL to entry price
6. OrderClose() — Closes position
Use for: Taking profit, cutting loss, scaling out
Example: Close 50% at T1, let 50% run
📝 Simple EA Structure Example
Basic EA Logic:
void OnTick() {
// 1. Check if we already have open position
if (OrdersTotal() > 0) {
ManageOpenTrades(); // Move SL, check TP
return;
}
// 2. Check entry conditions
bool trendBullish = CheckH4Trend();
bool mssConfirmed = CheckM15MSS();
bool atOrderBlock = CheckOBZone();
// 3. If ALL conditions met
if (trendBullish && mssConfirmed && atOrderBlock) {
double lotSize = CalculatePositionSize(); // 1% risk
double sl = CalculateStopLoss(); // Below OB
double tp = CalculateTakeProfit(); // Liquidity pool
OrderSend(Symbol(), OP_BUY, lotSize, Ask, 3, sl, tp);
}
}
What This Does:
- Every tick: Checks if position open
- If yes: Manage it per rules
- If no: Check entry conditions
- If ALL met: Execute trade with calculated risk
- Fully automated Order Block trading
Learning Path: 1) Understand trading first (200+ manual trades), 2) Learn MQL basics (variables, functions), 3) Code simple indicator, 4) Code semi-automated EA, 5) Full automation only after mastery.
4Chapter 4: The Advantages and Dangers of Algorithmic Trading⏱️ ~6 min
Automation is powerful but comes with both massive advantages and serious dangers.
✅ The Six Major Advantages
1. Perfect Discipline
- Human: Skip valid setup due to fear after 3 losses
- EA: Takes setup #4 mechanically
- Result: Full expectancy realized
2. No Emotional Trading
- Human: Revenge trade after bad loss
- EA: Continues following rules regardless
- Result: No emotional mistakes
3. 24/5 Market Coverage
- Human: Sleep 8 hours, miss Asian session
- EA: Monitors all sessions, catches 3 AM setup
- Result: More opportunities captured
4. Multi-Pair Monitoring
- Human: Focus on 1-2 pairs realistically
- EA: Monitor 10+ pairs simultaneously
- Result: Diversification without overload
5. Flawless Risk Management
- Human: Calculate 0.47 lots, enter 0.50 by mistake
- EA: Calculates 0.4738, enters exactly that
- Result: Perfect 1% risk every trade
6. Backtesting Validation
- Human: Can't perfectly replicate historical trades
- EA: Same code for backtest and live = perfect match
- Result: Live mirrors backtest
⚠️ The Six Major Dangers
1. Garbage In, Garbage Out
- Bad strategy automated = faster losses
- EA can't fix poor logic
- Automation amplifies your edge (positive OR negative)
2. Technical Failures
- Internet disconnection during trade
- Platform crash mid-execution
- VPS server downtime
- Result: Unmanaged positions, potential disaster
3. Coding Errors
- Bug in lot size calculation (risk 10% instead of 1%)
- SL placed wrong side of market
- Infinite loop opening trades
- Result: Account blown in minutes
4. Over-Optimization
- Tweak EA to perfection on historical data
- Overfit to noise
- Live performance collapses
5. Black Swan Events
- Algorithm can't handle unprecedented events
- Swiss Franc depeg (2015): many EAs destroyed
- Flash crashes trigger all stops
- Need manual override capability
6. False Confidence
- "It's automated, can't fail!"
- Stop monitoring
- Miss warning signs
- Result: Undetected problems compound
🛡️ Risk Mitigation for Algo Trading
Mandatory Safeguards:
1. Maximum Daily Loss Limit (Coded):
if (dailyLoss >= accountEquity * 0.03) {
CloseAllPositions();
StopTrading = true;
SendAlertEmail();
}
2. Maximum Drawdown Limit:
- Code hard stop at -12% from peak
- EA shuts down completely
- Requires manual restart after review
3. Max Open Positions:
- Never more than 3-4 positions
- Prevents runaway exposure
- Coded limit
4. Daily Monitoring (You):
- Check EA performance every 24 hours
- Review all trades taken
- Verify risk calculations correct
- EA is tool, YOU are manager
5. VPS Monitoring:
- Uptime alerts
- Connection health checks
- Automatic failover
- Infrastructure reliability
6. Kill Switch:
- Ability to instantly disable EA
- Close all positions remotely
- Emergency stop capability
Critical Reality: Algorithmic trading is NOT "set and forget." It's "set and MONITOR." You must review EA performance daily. Automation handles execution; you handle oversight.
5Chapter 5: Getting Started with Algorithmic Trading⏱️ ~4 min
🚀 Your Automation Roadmap
Phase 1: Foundation (Months 1-6)
- Master manual trading first
- Prove strategy profitable (200+ trades)
- Document every rule objectively
- No coding yet
Phase 2: Learning MQL (Months 7-9)
- Learn MQL4/MQL5 basics
- Code simple indicator (OB highlighter)
- Study existing EA code
- Build programming foundation
Phase 3: Semi-Automation (Months 10-12)
- Code EA that manages trades only
- YOU enter manually
- EA manages SL, BE, TP, scaling
- Hybrid approach
Phase 4: Full Automation (Month 13+)
- Code complete EA with entry logic
- Extensive backtesting (500+ trades)
- 3-month forward test on demo
- VPS setup and monitoring
- Full automation with oversight
🛠️ Essential Resources
Learning Resources:
- MQL4/5 Official Documentation (mql4.com, mql5.com)
- MQL4 Tutorial for Beginners (free course)
- YouTube: "The MQL5 Guy," "Kirill Eremenko"
- Forums: MQL5 Community
Development Tools:
- MetaEditor (built into MT4/MT5) — Free IDE
- Visual Studio Code (with MQL extensions)
- Strategy Tester (for EA testing)
Hiring Option:
- Freelancer.com, MQL5 Freelance
- Hire coder to build EA from your rules
- Cost: $200-2000 depending on complexity
- Faster but requires clear documentation
💰 Cost-Benefit Analysis
To Build EA Yourself:
- Time: 100-300 hours learning + building
- Cost: $0 (free tools)
- Benefit: Full control, can modify anytime
To Hire Coder:
- Time: 20-40 hours (writing specifications)
- Cost: $500-2000
- Benefit: Professional code, faster deployment
Ongoing Costs:
- VPS: $20-50/month
- MT4/MT5: Free
- Monitoring time: 30 min/day
- Total: $240-600/year
ROI:
- If EA executes strategy with 0.3R expectancy
- 20 trades/month = 6R/month
- On $10K account, 1% risk = $100/trade
- 6R = $600/month additional profit
- VPS pays for itself in first month
Beginner Path: Don't learn to code just to automate. First prove you can trade profitably manually (6-12 months). Then decide if automation worth the effort. Many profitable manual traders never automate.
6Chapter 6: Summary, Quiz & Next Steps⏱️ ~5 min
Summary & Conclusion
Algorithmic trading transforms proven strategies into 24/5 execution machines.
Key Principles (0/14)
The Professional Truth: Automation is force multiplier, not magic bullet. Multiply profitable strategy → more profit. Multiply losing strategy → faster ruin. Prove edge manually first, then automate.
Quiz
The primary function of an Expert Advisor (EA) that distinguishes it from a Custom Indicator is:
The most critical prerequisite before automating a trading strategy with an EA is:
In MQL4/MQL5, the OnTick() function is special because it:
Which safety measure is absolutely essential to code into any trading EA to prevent catastrophic account loss?
Call to Action
🤖 Automation is the future, but mastery is the present.
Don't rush to automate. First, prove you can trade profitably manually. Then, automate to scale your proven edge.
Your Action Steps:
- Master manual trading first (200+ profitable trades)
- Document strategy with 100% objective rules
- Learn MQL basics (if coding yourself)
- Start with simple indicator (OB highlighter)
- Progress to semi-automation (manual entry, EA manages)
- Only then full automation (after extensive testing)
Automation amplifies your edge. Make sure your edge is positive first.
Call to Action
Manage a book, not a bet. Make correlation checks and risk caps part of your routine.

Deriv
- ✅Zero-spread accounts for tighter entries
- ✅Swap-free (Islamic) available

XM
- ✅Consistently low spreads on majors
- ✅Micro accounts — start with a smaller risk
- ✅Swap-free (Islamic) available
- ✅No trading commission
Remember: A profitable manual trader who automates becomes more profitable. An unprofitable manual trader who automates loses money faster. Prove it manually first.
Master the strategy. Then automate the execution.
Prerequisites
Before studying this lesson, ensure you've mastered these foundational concepts:
Ready to scale your edge with automation? Master manual trading first, then let algorithms execute flawlessly.
Ready to continue?
Mark this lesson as complete to track your progress.