Lesson 5 of 683% Complete

Introduction to Algorithmic Trading (EAs/Bots) & MQL4/5 Concepts ๐Ÿค–

Advanced24 min2025

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

๐Ÿค– What an EA Does for You

Algorithmic Trading = Pre-programmed computer instructions to automatically place trades based on your analytical and risk criteria.

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

FactorManual TradingAlgo Trading (EA)
EmotionConstant battleZero emotion
Discipline80-90% rule adherence100% rule adherence
MonitoringLimited hours24/5 continuous
Execution SpeedSecondsMilliseconds
Multi-Pair1-2 pairs max focus10+ pairs simultaneously
FatigueYes (mistakes increase)Never tired
ConsistencyVariablePerfect
Learning CurveModerateHigh (coding required)
Initial SetupQuickTime-intensive
FlexibilityHigh (adapt quickly)Low (need to recode)

The Truth:

  • Manual = flexible but emotional
  • Automated = rigid but flawless
  • Best approach: Combine both
Pro Tip

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.

Ready to practice?

Test with virtual funds

2Chapter 2: Expert Advisors vs. Indicators

๐Ÿ“Š Custom Indicators

Understanding the difference between EAs and Indicators is fundamental to MetaTrader automation.

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.

Test EA on Demo

Practice these calculations with a demo account.

3Chapter 3: Introduction to MQL4 and MQL5

๐Ÿ’ป MQL4 vs. MQL5

MQL (MetaQuotes Language) is the programming language for creating EAs and indicators on MetaTrader.

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
Pro Tip

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.

Practice with EAs

Test with virtual funds

4Chapter 4: The Advantages and Dangers of Algorithmic Trading

โœ… The Six Major Advantages

Automation is powerful but comes with both massive advantages and serious dangers.

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.

Apply What You've Learned โ€” Master Accumulator Compounding in Action

Practice calculating your trade size based on your risk tolerance

Powered by Deriv โ€” Trusted by 3M+ traders worldwide since 1999

Practice Accumulator Compounding Now โ€” Free $10,000 Demo
FREE
Free $10,000 virtual funds
No risk, unlimited practice

or upgrade anytime to live trading

Practice Accumulator Compounding Now โ€” Free $10,000 Demo
FREE
Free $10,000 virtual funds
No risk, unlimited practice

or upgrade anytime to live trading

100% Bonus

Trading involves risk. Start with a demo to build confidence before going live.

5Chapter 5: Getting Started with Algorithmic Trading

๐Ÿš€ 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
Pro Tip

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.

Start Your Automation Journey

Practice these calculations with a demo account.

6Chapter 6: Summary, Quiz & Next Steps

Summary & Conclusion

Summary & Conclusion

Algorithmic trading transforms proven strategies into 24/5 execution machines.

Key Principles (0/14)

Algo trading = computerized execution
Based entirely on your predefined rules
Expert Advisors (EAs)
Place trades, manage positions, calculate risk
Custom Indicators
Display info, cannot trade
MQL4 for MT4
MQL5 for MT5 (more powerful)
Key functions
OnTick (main logic), OrderSend (place trades)
Advantages: Perfect discipline
24/5 monitoring, zero emotion
Dangers: Amplifies everything
Bad strategy โ†’ faster losses
Technical failures possible
VPS downtime, coding bugs, crashes
Only automate proven strategies
200+ manual trades first
Mandatory safeguards
Daily loss limits, max DD, kill switch
Daily monitoring required
EA is tool, YOU are manager
VPS hosting recommended
$20-50/month for 24/5 uptime
Learn or hire
100-300 hours self-learn OR $500-2000 hire
Hybrid approach for beginners
Manual entry, EA manages trade

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:

Answer:

Expert Advisors can EXECUTE trades automatically (place orders, modify SL/TP, close positions, calculate risk). Custom Indicators can only DISPLAY information (draw lines, boxes, values). Indicators help YOU decide; EAs decide AND execute. An OB highlighter indicator shows you where OBs are, but YOU click buy. An OB EA sees the OB, calculates lot size, places order, manages SLโ€”all automatically.

The most critical prerequisite before automating a trading strategy with an EA is:

Answer:

NEVER automate an unproven strategy. Automation is force multiplier: profitable strategy โ†’ amplified profits, losing strategy โ†’ amplified losses (at machine speed). You must: 1) Prove edge manually (200+ trades), 2) Validate with backtest/forward test, 3) Document 100% objective rules, 4) THEN code EA. Automating before proving edge = losing money faster. Python/ML, large accounts, and licenses are optional. Proven edge is mandatory.

In MQL4/MQL5, the OnTick() function is special because it:

Answer:

OnTick() is the HEART of every EAโ€”it runs on EVERY price tick (every price change, often multiple times per second). This is where you code: 'Check if H4 uptrend? Check if MSS? Check if at OB? If ALL yes โ†’ execute trade.' This function runs thousands of times per day, constantly monitoring for your exact entry conditions. OnInit() runs once (startup), OnDeinit() runs once (shutdown). OnTick() runs continuously during market hours.

Which safety measure is absolutely essential to code into any trading EA to prevent catastrophic account loss?

Answer:

Maximum daily/total loss limit is THE critical safety feature. Code example: 'if (dailyLoss >= equity ร— 0.03) { CloseAllPositions(); StopTrading = true; }' This prevents: 1) Bug causing repeated losses, 2) Market condition destroying strategy, 3) Account blowup while you're sleeping. Real scenario: EA has bug, opens 50 trades instantly, -30% account. Without loss limit: account destroyed. With 3% daily limit: EA stops after -3%, saves 90% of capital.

Call to Action

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:

  1. Master manual trading first (200+ profitable trades)
  2. Document strategy with 100% objective rules
  3. Learn MQL basics (if coding yourself)
  4. Start with simple indicator (OB highlighter)
  5. Progress to semi-automation (manual entry, EA manages)
  6. Only then full automation (after extensive testing)

Automation amplifies your edge. Make sure your edge is positive first.

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.

Explore Algorithmic Trading

Transform your proven strategy into 24/5 automated execution. Learn to build EAs, code in MQL4/MQL5, and safely automate your edge. Only after manual mastery.

POPULAR
Deriv logo

Deriv

(4.9)
  • Zero-spread accounts for tighter entries
  • Swap-free (Islamic) available
Instant setupFast KYCLocal payments24/7 support
100% BONUS
XM logo

XM

(4.8)
  • Consistently low spreads on majors
  • Micro accounts โ€” start with a smaller risk
  • Swap-free (Islamic) available
  • No trading commission
Instant setupFast KYCLocal payments24/7 support
Deriv: Zero-spread ยท Accumulators ยท Fast KYC
XM: Micro accounts ยท Low spreads ยท Bonus
Tip: Start on Demo, switch to Live after 3 consistent weeks.
SSL EncryptedInstant ActivationFree Training Included24/7 Support

Links are partner (sponsored) links. You'll open a new tab to our partner using our referral ID.

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.

Related Lessons You Might Like