Video summary

Build This $2800 Forex Trading Bot From Scratch (Full Code) – Part 2 || Structure and First Trade

Main summary

Key takeaways

Technology

Summary of technological concepts / product features (Part 2: structure + first trade)

What the bot is

A multi-currency grid trading EA (“multi-currency grid management system”) with advanced features such as:

  • Grid formation/maintenance logic
  • TP/SL calculation (including “smart” TP/SL ideas)
  • Starting the grid from a chosen level
  • Options like:
    • News filter
    • Drawdown controls
    • Additional trading restrictions
  • A custom UI/panel in the EA (mentioned as a “pretty looking panel”)

Series workflow (tutorial structure)

  • This is Part 2 of a multi-video build series.
  • The video emphasizes that building the EA requires understanding the EA’s strategy first (from Part 1).
  • Planned step-by-step build order in later parts:
    1. Backbone → skeleton structure
    2. Open the first trade
    3. Implement grid logic, smart grid distancing, lot sizing methods, TP/SL logic
    4. Add safety layers (drawdown rules, FTMO-related options, news filter, restrictions)
    5. Finalize internal TP/SL management (“hide TP”) rather than broker-side placement

Product/course packaging / expectation setting

  • Mentions an existing EA on the MQL Marketplace priced around $2,800 with:
    • Consistent profitable performance (stated as consecutive months)
    • Full documentation (installation, requirements, risk settings, strategy, etc.)
  • The presenter provides course/code for reference but warns it’s not a guaranteed quick path to wealth (tool analogy).

Code architecture built in this part (MQL5)

Core EA event functions

Uses the standard MQL5 lifecycle:

  • OnInit: initialization of EA, indicators, timers
  • OnDeinit: cleanup when removed
  • OnTick: runs on price updates
  • Adds OnTimer:
    • In live environment, timer interval is set to 5 seconds to refresh data.

Trade operation helpers

  • Includes Trade.mqh and uses:
    • CTrade for order/position operations
    • CPositionInfo for position-related data
    • COrderInfo for order-related data (likely for future use)

User-configurable system via enums

Adds multiple enums to drive behavior from EA inputs, including:

  • Lot sizing enum
    • Low/mid/significant/high risk options, dynamic lots, fixed lots
  • Allow buy/sell enum
    • Buy-only, sell-only, both
  • Drawdown action enums
    • Prohibit new grids until restart
    • Prohibit opening new grid
    • Close all trades and stop until restart
    • Close trades and stop trading for 24 hours
  • Drawdown scope enum
    • Drawdown computed for strategy-only vs entire account

Symbol data structure (per-currency state container)

Creates a structure (e.g., symbol information) per symbol/currency pair containing runtime fields, such as:

  • Symbol name/timeframe update timestamps
  • Buy/sell permission flags (bool flags)
  • Whether grid is open / OPO triggered
  • Smart multiplier, Bollinger Band width, weekday tracking
  • Last grid open times for buy/sell
  • TP levels and other state variables

EA input parameters (major categories)

This part defines most EA input variables, including:

Risk / trade controls

  • Lot sizing method + fixed/dynamic lot settings (including a “fixed initial deposit” testing mode)
  • Max lot / auto-split behavior (if calculated lot exceeds broker max)
  • Max spread and slippage constraints
  • Max number of symbols with active grids simultaneously
  • Hedging rules: allow buy+sell grids simultaneously or not
  • Holiday trading rule (disabled during Dec 25–Jan 3)
  • Minimum free margin, maximum drawdown (percentage and money)
  • Actions upon drawdown trigger

Strategy / indicator parameters

  • Symbols list (comma-separated)
  • Trading start/stop hours
  • Bollinger settings (period used later in TP logic)
  • RSI settings:
    • RSI period
    • RSI threshold behavior (mid RSI around 50; buys use lower band logic, sells use upper band logic)

TP/SL settings (partially defined in inputs; TP/SL logic later)

  • Initial TP; weighted TP option based on lot weights
  • Grid TP differences per grid level
  • Break-even after a certain grid level
  • “Hide TP” option:
    • Keep TP/SL internal instead of sending to the broker
  • OPO method (open-price-only logic):
    • Close when candle closes above TP (described even if not fully implemented yet)
  • “Smart TP” concept:
    • Dynamic TP derived from Bollinger Bands width
  • Stop loss options:
    • Hide or grid stop loss concept
  • Grid distance:
    • Base distance between grid levels
    • Smart distance multiplier based on volatility ratio (ATR fast / ATR slow)
  • Lot multiplier / martingale-like behavior by grid level
  • Grid level to start:
    • Start with dummy minimum-lot trades until a chosen grid level, then begin full sizing

Identity

  • EA trade comment and UID/magic number scheme for multiple instances.

Initialization: indicator handles + manual Bollinger

Indicator handle creation per symbol

For each configured symbol, creates handles for:

  • Moving Average and Standard Deviation (Bollinger components)
  • RSI
  • ATR 96 and ATR 672 (volatility comparison)

Multi-currency indicator management

  • Uses arrays of indicator handles per symbol index (three currency pairs by default from input parsing).
  • Adds validation to ensure indicators can load:
    • common failure mode: currencies not visible in Market Watch

Manual Bollinger Band calculation

Bollinger Bands are computed manually because:

  • “MQL struggles with updating Bollinger Band values for every currency” in multi-symbol scenarios.

Calculations:

  • BB upper = MA + 2 * StdDev
  • BB lower = MA - 2 * StdDev
  • Also computes Bollinger Band width (upper - lower) normalized by symbol digits.

Live trading logic implemented: gating + first order

New bar detection (per symbol)

  • OnTick checks whether a new candle has started on the fixed main timeframe (15-minute repeatedly referenced).
  • Trading logic runs only when a new bar is detected.

Trading allowed checks (composite filter)

The EA computes canTrade / can buy / can sell using many restrictions, including:

  • Terminal/broker/testing permissions:
    • TerminalTradeAllowed
    • AccountTradeExpertAllowed
    • BrokerTradeAllowed / trade mode
  • User input: allow opening new grids
  • Historical data checks:
    • disables trading if main timeframe has insufficient bars (threshold described as ~1000 symbols/bars)
  • Margin checks:
    • uses free margin thresholds and prints warnings periodically (throttled)
  • UID validity:
    • uid must be 0–9
  • Avoids trading immediately on first bars after initialization
  • Broker symbol trade mode constraints (buy-only / sell-only)
  • User allow buy/sell rules
  • Trading hours window (including overnight spans when start > stop)
  • Holiday filter (Dec 25–Jan 3)
  • 15-minute boundary check:
    • bar minutes must match expected multiples (patterns described like 00/20/15/30/45)
  • Drawdown check:
    • stubbed early in this part, but scaffolding exists for cooldown and triggers

RSI + recent high/low gating for first entry

Entry permission uses RSI buffer logic:

  • Buy: RSI below 50 - RSI_value
    • Example: RSI value 15 → threshold 35
  • Sell: RSI above 50 + RSI_value

Additional gating based on Bollinger/price extremes:

  • For buys: close price must be below a recent low
  • For sells: close must be above a recent high

Together, these decide whether can buy / can sell remains true.

Maximum active symbols with grids

  • Adds a function scaffold to limit how many symbols can simultaneously have active grids.
  • In this part, that check function is stubbed (returns false), so the limiter does not fully apply yet.

First trade: market order opening framework

Spread filtering

Before sending market orders:

  • Checks current spread vs configured maximum spread
  • Converts pip/point using symbol digits:
    • if digits are 3 or 5 → pip multiplier 10
    • else → multiplier 1

Hedging logic + grid existence checks (scaffolding)

  • If hedging is allowed:
    • can open both buy and sell grids (subject to grid-existence checks)
  • If hedging is not allowed:
    • opens only one direction unless no grid exists at all
    • (grid existence function not fully built yet in this part)

Retry loop + broker error handling

  • Order sending uses:
    • up to 10 attempts
  • Each attempt:
    • calculates lot size (currently stubbed to 0.01)
    • checks margin using broker margin calculation
    • fails fast (no retry) if errors are “fatal” (invalid volume, market closed, trade disabled, etc.)

Magic number / UID system

  • Magic numbers are deterministic:
    • base magic number hardcoded (e.g., 84570)
    • UID added (0–9)
    • direction appended (buy vs sell)
    • level encoded (base level vs subsequent grid levels)
  • Result: distinct magic number per trade instance, e.g.:
    • a base-multiplied scheme + direction + grid-level encoding

OPO flag and internal state updates

After successful initial market order:

  • Updates can buy/can sell (disables that direction)
  • Sets last grid time
  • Marks grid as open
  • Sets an OPO trigger flag for later internal TP/SL closure logic

Testing outcome stated

  • EA compiles and runs with:
    • lot size currently 0.01 (stub)
    • grid logic not implemented yet
  • As a result, it may repeatedly open trades on each new candle when RSI conditions are met.
  • Confirms the skeleton works and prepares later parts to implement:
    • real grid levels
    • grid management
    • smart TP/SL
    • lot sizing methods

Main speakers / sources

  • Speaker: referenced as “Mr. Caffrey” (builder of the EA via voice-over)
  • Source/EA referenced: an existing MQL Marketplace EA priced around $2,800 (video’s target clone/build)

Original video