Forex Algo Trader
Sign In Register
Market Resources Tools Autotrading Algo Jobs
Building a Double Top and Double Bottom Trading Robot in MQL5
Resource

Building a Double Top and Double Bottom Trading Robot in MQL5

Build an MQL5 Expert Advisor that finds double tops and double bottoms from confirmed swing pivots, filters them by peak tolerance, leg balance and spacing, then trades the neckline break or pullback with measured-move or reward-to-risk targets and a trailing stop.
Forex Algo-Trader Verified
@forex_algo_trader
1 month ago 170 views 0 comments 24 min read 2 files

Twice is a pattern

A single failed push to a new high means little on its own. Price does that constantly. But when it fails at the same high twice, something has changed: the buyers who were strong enough to get there once could not do it again, and the sellers who showed up the second time are, for the moment, in charge. That is a double top. Flip it upside down over a floor instead of a ceiling and you have a double bottom, where sellers fail a second attempt at a low and buyers take over.

The hard part is not recognizing the shape when you already know how the story ends. It is deciding, in real time and without hindsight, whether two peaks are "close enough" to count, whether the dip between them is deep enough to matter, and whether the eventual break of that dip is real or just noise. This article builds an MQL5 Expert Advisor that answers all three questions with fixed arithmetic instead of a glance at the chart. It finds confirmed swing pivots, pairs two of the same kind within a tolerance scaled to the pattern's own size, derives a neckline from the pivot between them, and only then watches for the break, or an optional pullback to it, before risking anything.

What counts as a pattern here

Before any code, it helps to fix the rules the program enforces, because every function below exists to serve one of them.

  • A swing pivot is only confirmed once an equal number of bars have closed on both sides of it without a higher high (for a swing high) or lower low (for a swing low) appearing among them.
  • Two pivots of the same kind pair into a pattern only when they sit within a tolerance expressed as a percentage of the pattern's own height, so one setting behaves consistently on a tall pattern and a shallow one.
  • The neckline is the single most extreme opposite pivot found between the two peaks, and nothing else, the lowest low between two highs for a top, the highest high between two lows for a bottom.
  • A shape is rejected when the two peaks sit too close together in bars, when the two legs either side of the neckline are too unequal in length, or, optionally, when there is no real trend leading into it.
  • The trade only triggers on a bar closing through the neckline, with an optional wait for price to pull back to it afterwards, and the whole idea is abandoned if price instead breaks through the paired extreme first, or if too much time passes.

With the rules fixed, everything that follows is that list expressed as code.

The skeleton: enums, inputs and memory

Three enumerations describe every choice the trader can make, and a single state machine tracks where an in-progress pattern stands.

enum LotSizingMode
  {
   LOTS_FIXED,        // Fixed lot size
   LOTS_RISK_PERCENT  // Risk percent of balance (auto lot)
  };

enum TakeProfitMode
  {
   TP_MEASURED_MOVE,  // Project the pattern height from the neckline
   TP_REWARD_RISK     // Multiple of the stop distance
  };

enum SetupState
  {
   STATE_IDLE,        // No active pattern
   STATE_ARMED,       // Pattern found, waiting for the neckline break
   STATE_RETEST       // Break confirmed, waiting for the pullback
  };

LotSizingMode is a straightforward switch between a fixed lot and a risk-percentage lot. TakeProfitMode is more interesting: it lets the target be either a measured move, the pattern's own height projected from the neckline, which scales the target to the size of the structure that produced the signal, or a plain reward-to-risk multiple of the stop distance. SetupState is the backbone of everything that follows: idle means nothing is happening, armed means a valid pattern is waiting for its neckline to break, and retest means the break has happened and the robot is waiting for one more touch of the level before it commits money.

The inputs are organized into seven groups: general (magic number, sizing, comment), pattern (the working timeframe, swing length, peak tolerance, minimum spacing, leg balance, and the prior-trend switch), stop loss, take profit, entry (pullback toggle and the two patience limits), trailing stop, logging, and visuals. A SwingPoint structure holds one confirmed pivot: whether it is a high or a low, its price and its time. Everything the state machine needs to carry a pattern from first detection to a filled order lives in a block of globals: the swing history, the setup's direction, its neckline and extreme, both peak times and prices, an optional leading trend leg, and a counter of bars spent in the current stage.

The pulse: three small gatekeepers

Three tiny functions get called constantly and decide almost nothing on their own, but nothing else works without them.

void Log(string message)
  {
   if(InpShowLogs)
      Print(InpLogPrefix, message);
  }

bool VisualsAllowed()
  {
   if(!InpDrawVisuals) return false;
   if(MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_VISUAL_MODE)) return false;
   return true;
  }

bool IsNewBar()
  {
   datetime time = iTime(_Symbol, InpEntryTimeframe, 0);
   if(time != lastBarTime) { lastBarTime = time; return true; }
   return false;
  }

Log is a one-line wrapper that respects the logging switch. VisualsAllowed refuses to draw during a non-visual backtest, so a thousand-trade optimization run is never slowed down by chart objects nobody will see. IsNewBar is the gate that everything heavier sits behind: it compares the current bar's open time with the last one it saw, and only reports true once per bar, which is what keeps pattern detection running on settled data instead of a candle that is still forming.

Turning risk into a lot size

Two short functions convert a risk percentage, or a flat lot, into a broker-legal volume.

double LotsByRisk(double entry, double stop)
  {
   double riskMoney  = AccountInfoDouble(ACCOUNT_BALANCE) * InpRiskPercent / 100.0;
   double stopPoints = MathAbs(entry - stop) / symbolPoint;
   if(stopPoints <= 0) return 0;
   double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tickSize  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   if(tickValue <= 0 || tickSize <= 0) return 0;
   double valuePerPoint = tickValue / tickSize * symbolPoint;
   if(valuePerPoint <= 0) return 0;
   double lots = riskMoney / (stopPoints * valuePerPoint);
   double volumeMin  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double volumeMax  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double volumeStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   if(volumeStep > 0) lots = MathFloor(lots / volumeStep) * volumeStep;
   return NormalizeDouble(MathMax(volumeMin, MathMin(volumeMax, lots)), 2);
  }

double ResolveLots(double entry, double stop)
  {
   double lots = (InpLotSizingMode == LOTS_FIXED) ? InpFixedLots : LotsByRisk(entry, stop);
   double volumeMin  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double volumeMax  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double volumeStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   if(volumeStep > 0) lots = MathFloor(lots / volumeStep) * volumeStep;
   return NormalizeDouble(MathMax(volumeMin, MathMin(volumeMax, lots)), 2);
  }

LotsByRisk takes the money value of the chosen risk percentage, divides it by the stop distance expressed in money per point, and returns the lot size that makes a full stop-out cost exactly that much. Every exit is guarded: a zero stop distance, a missing tick value or a zero per-point value all return zero rather than a nonsensical size, and the caller treats zero as "do not trade." ResolveLots is the one function the rest of the program actually calls. It picks between the fixed input and the risk calculation, then applies the same volume-step and min/max clamp either way, so a badly chosen fixed lot cannot slip past the broker's rules any more than a calculated one could.

Reading the market into pivots

The entire pattern search is built on top of a rolling history of confirmed swing points, so that history has to be assembled first.

void AddSwing(bool isHigh, double price, datetime time)
  {
   int n = ArraySize(swings);
   for(int i = 0; i < n; i++)
      if(swings[i].time == time && swings[i].isHigh == isHigh) return;
   ArrayResize(swings, n + 1);
   swings[n].isHigh = isHigh; swings[n].price = price; swings[n].time = time;
   if(ArraySize(swings) > 80)
     {
      for(int i = 0; i < ArraySize(swings) - 1; i++) swings[i] = swings[i + 1];
      ArrayResize(swings, ArraySize(swings) - 1);
     }
  }

void DetectSwings()
  {
   int length = InpSwingLength;
   int candidate = length + 1;
   if(iBars(_Symbol, InpEntryTimeframe) < 2 * length + 2) return;
   double candidateHigh = iHigh(_Symbol, InpEntryTimeframe, candidate);
   double candidateLow  = iLow(_Symbol, InpEntryTimeframe, candidate);
   bool isHigh = true, isLow = true;
   for(int k = 1; k <= length; k++)
     {
      if(iHigh(_Symbol, InpEntryTimeframe, candidate - k) >= candidateHigh ||
         iHigh(_Symbol, InpEntryTimeframe, candidate + k) >  candidateHigh) isHigh = false;
      if(iLow(_Symbol, InpEntryTimeframe, candidate - k) <= candidateLow ||
         iLow(_Symbol, InpEntryTimeframe, candidate + k) <  candidateLow) isLow = false;
     }
   datetime candidateTime = iTime(_Symbol, InpEntryTimeframe, candidate);
   if(isHigh) AddSwing(true, candidateHigh, candidateTime);
   if(isLow)  AddSwing(false, candidateLow, candidateTime);
  }

DetectSwings centers its test on a candidate bar sitting exactly InpSwingLength bars from the live edge, which guarantees it has the same number of confirmed bars on each side. It starts by assuming the candidate is both a swing high and a swing low, then knocks out either claim the moment any neighbor in the window matches or exceeds it. A bar can be confirmed as both at once, in which case AddSwing is called twice. AddSwing itself is simple bookkeeping: skip an exact duplicate, append, and once the buffer passes eighty entries, drop the oldest one so the history that the pattern search works from stays bounded no matter how long the EA runs.

The shape test

This is the function that does the actual recognizing. It is the longest in the program because it has to run the same logic twice, once for a double top built from two swing highs, once for a double bottom built from two swing lows, and apply every filter from the rules list along the way.

void TryDetectPattern()
  {
   if(setupState != STATE_IDLE) return;
   int n = ArraySize(swings);
   if(n < 3) return;
   SwingPoint latest = swings[n - 1];
   double tolerance = InpPeakTolerancePercent / 100.0;
   if(latest.isHigh)
     {
      int priorHigh = -1;
      for(int i = n - 2; i >= 0; i--) if(swings[i].isHigh) { priorHigh = i; break; }
      if(priorHigh < 0) return;
      if(swings[priorHigh].time < lastPatternEndTime) return;
      double neckline = 0; datetime neckTime = 0; bool found = false;
      for(int i = priorHigh + 1; i < n - 1; i++)
         if(!swings[i].isHigh && (!found || swings[i].price < neckline)) { neckline = swings[i].price; neckTime = swings[i].time; found = true; }
      if(!found) return;
      double peak1 = swings[priorHigh].price, peak2 = latest.price;
      double height = (peak1 + peak2) / 2.0 - neckline;
      if(height <= 0) return;
      if(MathAbs(peak1 - peak2) > tolerance * height) return;
      int shiftPeakOne = iBarShift(_Symbol, InpEntryTimeframe, swings[priorHigh].time, false);
      int shiftNeck    = iBarShift(_Symbol, InpEntryTimeframe, neckTime, false);
      int shiftPeakTwo = iBarShift(_Symbol, InpEntryTimeframe, latest.time, false);
      if(InpMinPatternBars > 0 && (shiftPeakOne - shiftPeakTwo) < InpMinPatternBars) return;
      if(InpLegBalancePercent > 0)
        {
         double legA = (double)(shiftPeakOne - shiftNeck);
         double legB = (double)(shiftNeck - shiftPeakTwo);
         if(legA <= 0 || legB <= 0) return;
         if(100.0 * MathMin(legA, legB) / MathMax(legA, legB) < InpLegBalancePercent) return;
        }
      bool lead = false; datetime lTime = 0; double lPrice = 0;
      for(int i = priorHigh - 1; i >= 0; i--) if(!swings[i].isHigh) { lead = true; lTime = swings[i].time; lPrice = swings[i].price; break; }
      if(InpRequirePriorTrend && (!lead || lPrice >= neckline)) return;
      ArmPattern(-1, neckline, neckTime, MathMax(peak1, peak2), swings[priorHigh].time, peak1, latest.time, peak2, lead, lTime, lPrice);
     }
   else
     {
      int priorLow = -1;
      for(int i = n - 2; i >= 0; i--) if(!swings[i].isHigh) { priorLow = i; break; }
      if(priorLow < 0) return;
      if(swings[priorLow].time < lastPatternEndTime) return;
      double neckline = 0; datetime neckTime = 0; bool found = false;
      for(int i = priorLow + 1; i < n - 1; i++)
         if(swings[i].isHigh && (!found || swings[i].price > neckline)) { neckline = swings[i].price; neckTime = swings[i].time; found = true; }
      if(!found) return;
      double trough1 = swings[priorLow].price, trough2 = latest.price;
      double height = neckline - (trough1 + trough2) / 2.0;
      if(height <= 0) return;
      if(MathAbs(trough1 - trough2) > tolerance * height) return;
      int shiftTroughOne = iBarShift(_Symbol, InpEntryTimeframe, swings[priorLow].time, false);
      int shiftNeck      = iBarShift(_Symbol, InpEntryTimeframe, neckTime, false);
      int shiftTroughTwo = iBarShift(_Symbol, InpEntryTimeframe, latest.time, false);
      if(InpMinPatternBars > 0 && (shiftTroughOne - shiftTroughTwo) < InpMinPatternBars) return;
      if(InpLegBalancePercent > 0)
        {
         double legA = (double)(shiftTroughOne - shiftNeck);
         double legB = (double)(shiftNeck - shiftTroughTwo);
         if(legA <= 0 || legB <= 0) return;
         if(100.0 * MathMin(legA, legB) / MathMax(legA, legB) < InpLegBalancePercent) return;
        }
      bool lead = false; datetime lTime = 0; double lPrice = 0;
      for(int i = priorLow - 1; i >= 0; i--) if(swings[i].isHigh) { lead = true; lTime = swings[i].time; lPrice = swings[i].price; break; }
      if(InpRequirePriorTrend && (!lead || lPrice <= neckline)) return;
      ArmPattern(1, neckline, neckTime, MathMin(trough1, trough2), swings[priorLow].time, trough1, latest.time, trough2, lead, lTime, lPrice);
     }
  }

Walk through the top-pattern branch and the bottom-pattern branch mirrors it exactly. The function only runs while idle, and it always treats the newest stored swing as the pattern's second peak, which means detection is reactive: it looks backward from whatever has just been confirmed, never forward. It then searches for the nearest earlier swing of the same kind to serve as the first peak, and refuses to reuse ground already claimed by the previous pattern (lastPatternEndTime).

The neckline search is a plain scan between the two peaks for the single most extreme opposite pivot. Once found, the pattern height is the distance from the average of the two peaks down to the neckline, and that height becomes the yardstick for everything after it: the peak-tolerance test divides the peaks' own price difference by that height, so a setting of 10 means the same thing whether the pattern spans five pips or five hundred. Bar shifts are then resolved for all three anchors, which drives two independent filters, a minimum spacing between the peaks, and a leg-balance ratio comparing the shorter leg to the longer one in bar count. Finally, an optional prior-trend check looks one swing further back for a leg that led into the pattern from the correct side. Only a shape that survives every one of these checks reaches ArmPattern, with its extreme set to the more extreme of the two peaks, since that is what the eventual stop will sit beyond.

Locking in a find

void ArmPattern(int direction, double neckline, datetime neckTime, double extreme, datetime t1, double p1, datetime t2, double p2, bool lead, datetime lTime, double lPrice)
  {
   patternDirection = direction;
   necklineLevel = neckline; necklineTime = neckTime;
   patternExtreme = extreme;
   peakOneTime = t1; peakOnePrice = p1;
   peakTwoTime = t2; peakTwoPrice = p2;
   hasLead = lead; leadTime = lTime; leadPrice = lPrice;
   lastPatternEndTime = t2;
   necklineStartTime = t1;
   if(hasLead && MathAbs(p1 - lPrice) > 0)
     {
      double ratio = (neckline - lPrice) / (p1 - lPrice);
      if(ratio > 0 && ratio < 1)
         necklineStartTime = lTime + (datetime)((double)(t1 - lTime) * ratio);
     }
   setupState = STATE_ARMED; barsInState = 0;
   Log((direction < 0 ? "Double top" : "Double bottom") + " armed | neckline " +
       DoubleToString(neckline, symbolDigits) + " | waiting for the break");
   DrawPattern();
  }

Everything TryDetectPattern worked out gets copied into the global state here, the direction, the neckline and its pivot time, the extreme that will anchor the stop, both peaks, and the optional leading leg. Stamping lastPatternEndTime to the second peak is what stops the next search from reusing bars this pattern already claimed. The one piece of real math inside an otherwise mechanical function is the neckline's drawing start: rather than beginning the horizontal line flatly at the first peak, the code interpolates the point along the leading leg where its price would have equaled the neckline, so the line meets the trend that fed into the pattern at the right spot instead of floating above or below it.

From armed to filled

The journey from an armed pattern to a filled order, or to nothing at all, is handled by one function and supported by a second that can tighten the standard for a late break.

void ResetSetup(string reason)
  {
   if(setupState != STATE_IDLE)
      Log((patternDirection < 0 ? "Double top" : "Double bottom") + " reset: " + reason + ".");
   setupState = STATE_IDLE;
   patternDirection = 0;
   barsInState = 0;
  }

bool BreakLegBalanced()
  {
   int shiftPeakOne = iBarShift(_Symbol, InpEntryTimeframe, peakOneTime, false);
   int shiftNeck    = iBarShift(_Symbol, InpEntryTimeframe, necklineTime, false);
   int shiftPeakTwo = iBarShift(_Symbol, InpEntryTimeframe, peakTwoTime, false);
   double legA = (double)(shiftPeakOne - shiftNeck);
   double legB = (double)(shiftNeck - shiftPeakTwo);
   double legC = (double)(shiftPeakTwo - 1);
   if(legA <= 0 || legB <= 0 || legC <= 0) return false;
   double shortest = MathMin(legA, MathMin(legB, legC));
   double longest  = MathMax(legA, MathMax(legB, legC));
   return (100.0 * shortest / longest >= InpLegBalancePercent);
  }

void ProgressSetup()
  {
   if(setupState == STATE_IDLE) return;
   barsInState++;
   double closePrice = iClose(_Symbol, InpEntryTimeframe, 1);
   double highPrice  = iHigh(_Symbol, InpEntryTimeframe, 1);
   double lowPrice   = iLow(_Symbol, InpEntryTimeframe, 1);
   if(setupState == STATE_ARMED)
     {
      if(patternDirection < 0 && highPrice > patternExtreme) { ResetSetup("price broke above the pattern"); return; }
      if(patternDirection > 0 && lowPrice < patternExtreme) { ResetSetup("price broke below the pattern"); return; }
      if(barsInState > InpMaxConfirmBars) { ResetSetup("no neckline break in time"); return; }
      ExtendNeckline();
      bool confirmed = (patternDirection < 0) ? (closePrice < necklineLevel) : (closePrice > necklineLevel);
      if(confirmed)
        {
         if(InpIncludeBreakLeg && InpLegBalancePercent > 0 && !BreakLegBalanced())
           { ResetSetup("break leg fails balance"); return; }
         Log((patternDirection < 0 ? "Double top" : "Double bottom") + " confirmed: neckline broken at " +
             DoubleToString(necklineLevel, symbolDigits));
         breakoutTime = iTime(_Symbol, InpEntryTimeframe, 1);
         if(VisualsAllowed())
           {
            string bid = IntegerToString((int)peakTwoTime);
            color bcolor = (patternDirection < 0) ? InpBearColor : InpBullColor;
            DrawTrend("DTB_Break_" + bid, peakTwoTime, peakTwoPrice, breakoutTime, necklineLevel, bcolor, STYLE_SOLID, 2);
            DrawLabel("DTB_Breakt_" + bid, breakoutTime, necklineLevel, " Breakout", bcolor,
                      patternDirection < 0 ? ANCHOR_LEFT_UPPER : ANCHOR_LEFT_LOWER);
           }
         if(!InpTradePullback) { OpenTrade(patternDirection > 0); return; }
         pullbackExtremeTime  = breakoutTime;
         pullbackExtremePrice = (patternDirection < 0) ? lowPrice : highPrice;
         setupState = STATE_RETEST; barsInState = 0;
        }
      return;
     }
   if(setupState == STATE_RETEST)
     {
      if(patternDirection < 0 && highPrice > patternExtreme) { ResetSetup("pattern extreme violated before pullback"); return; }
      if(patternDirection > 0 && lowPrice < patternExtreme) { ResetSetup("pattern extreme violated before pullback"); return; }
      if(barsInState > InpMaxRetestBars) { ResetSetup("no pullback in time"); return; }
      ExtendNeckline();
      if(patternDirection < 0 && lowPrice < pullbackExtremePrice)
        { pullbackExtremePrice = lowPrice; pullbackExtremeTime = iTime(_Symbol, InpEntryTimeframe, 1); }
      if(patternDirection > 0 && highPrice > pullbackExtremePrice)
        { pullbackExtremePrice = highPrice; pullbackExtremeTime = iTime(_Symbol, InpEntryTimeframe, 1); }
      if(patternDirection < 0 && highPrice >= necklineLevel) { DrawPullback(); OpenTrade(false); }
      else if(patternDirection > 0 && lowPrice <= necklineLevel) { DrawPullback(); OpenTrade(true); }
     }
  }

ResetSetup is deliberately boring: clear the state, log why if something was actually active. Routing every abandonment through it means the Journal always explains itself, whether the reason is a timeout, a violated extreme, or a filled order.

ProgressSetup is the state machine's engine, called once per bar. In the armed stage it first checks for pattern failure: if price has broken through the paired extreme before ever closing through the neckline, the whole idea is dead, because the structure that was supposed to hold has not held. Failing that, a patience limit eventually gives up on a break that never comes. A confirmed close through the neckline can face one more optional test, BreakLegBalanced, which extends the ordinary two-leg balance idea to a third leg, from the second peak all the way to the breakout bar, and rejects a break that arrives too lopsidedly early or late relative to the pattern that produced it. Past that, the function either fires the trade immediately or, if a pullback is requested, seeds a tracked extreme and switches to the retest stage. That stage repeats the same two failure modes, extreme violation and timeout, while continuously updating the deepest (or highest) point price has reached since the breakout, and fires the trade the moment price touches back at the neckline.

Pulling the trigger

void OpenTrade(bool isBull)
  {
   double buffer = InpStopBufferPoints * symbolPoint;
   double entry = isBull ? NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), symbolDigits)
                         : NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), symbolDigits);
   double stop = isBull ? patternExtreme - buffer : patternExtreme + buffer;
   if(InpMinStopPoints > 0 && MathAbs(entry - stop) / symbolPoint < InpMinStopPoints)
     { ResetSetup("stop below minimum"); return; }
   long   stopsLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   long   spread     = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
   double minPoints  = (double)MathMax(stopsLevel, spread);
   if(minPoints < 1) minPoints = 1;
   double minDistance = minPoints * symbolPoint;
   if(isBull) { if(entry - stop < minDistance) stop = entry - minDistance; }
   else       { if(stop - entry < minDistance) stop = entry + minDistance; }
   stop = NormalizeDouble(stop, symbolDigits);
   double riskDistance = MathAbs(entry - stop);
   if(riskDistance <= 0) { ResetSetup("invalid risk distance"); return; }
   double height = MathAbs(patternExtreme - necklineLevel);
   double takeProfit;
   if(InpTakeProfitMode == TP_MEASURED_MOVE)
      takeProfit = isBull ? necklineLevel + height : necklineLevel - height;
   else
      takeProfit = isBull ? entry + InpRewardRiskRatio * riskDistance
                          : entry - InpRewardRiskRatio * riskDistance;
   if(isBull) { if(takeProfit - entry < minDistance) takeProfit = entry + minDistance; }
   else       { if(entry - takeProfit < minDistance) takeProfit = entry - minDistance; }
   takeProfit = NormalizeDouble(takeProfit, symbolDigits);
   double lots = ResolveLots(entry, stop);
   if(lots <= 0) { ResetSetup("lot calc error"); return; }
   bool ok = isBull ? trade.Buy(lots, _Symbol, entry, stop, takeProfit, InpOrderComment)
                    : trade.Sell(lots, _Symbol, entry, stop, takeProfit, InpOrderComment);
   if(ok)
     {
      datetime now = iTime(_Symbol, InpEntryTimeframe, 0);
      DrawTradeLevels(isBull, now, entry, stop, takeProfit);
      Log((isBull ? "BUY" : "SELL") + " filled @ " + DoubleToString(entry, symbolDigits) +
          "  SL=" + DoubleToString(stop, symbolDigits) + "  TP=" + DoubleToString(takeProfit, symbolDigits) +
          "  lots=" + DoubleToString(lots, 2));
     }
   else
      Log("Open failed: " + trade.ResultRetcodeDescription());
   ResetSetup("filled");
  }

OpenTrade gets exactly one attempt per armed setup. It enters at the market and anchors the stop beyond the paired extreme by a fixed buffer, the structural statement that if price revisits the whole pattern's outer edge, the reversal thesis has failed outright. A personal minimum-stop guard, which defaults to off, can reject trades whose stop sits too close to be worth the spread and commission, and a broker-aware guard separately widens either the stop or the target if either falls inside the symbol's minimum stop distance or current spread, so the order is never rejected by the terminal.

The target calculation is where the two TakeProfitMode options genuinely differ in spirit. Measured move treats the pattern's own height as the expected payoff, projected from the neckline in the trade's direction, under the classic technical-analysis assumption that a reversal travels about as far as the structure that preceded it. Reward-to-risk ignores the pattern's shape entirely and simply multiplies whatever the stop distance happens to be. Whichever one it uses, the function finishes the same way: resolve the lot size, send the order, draw the result if it filled, log either the fill or the rejection reason, and reset the setup regardless of outcome.

Staying in the trade

void ManageTrailing()
  {
   if(!InpUseTrailingStop) return;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0 || !PositionSelectByTicket(ticket)) continue;
      if(PositionGetInteger(POSITION_MAGIC) != InpMagicNumber) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      bool   isBull  = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY);
      double entry   = PositionGetDouble(POSITION_PRICE_OPEN);
      double curStop = PositionGetDouble(POSITION_SL);
      double curTP   = PositionGetDouble(POSITION_TP);
      double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      double profitPoints = isBull ? (bid - entry) / symbolPoint : (entry - ask) / symbolPoint;
      if(profitPoints >= InpMinProfitPoints + InpTrailPoints)
        {
         double newStop = isBull ? bid - InpTrailPoints * symbolPoint : ask + InpTrailPoints * symbolPoint;
         newStop = NormalizeDouble(newStop, symbolDigits);
         bool improves = isBull ? (newStop > curStop) : (curStop == 0 || newStop < curStop);
         if(improves) trade.PositionModify(ticket, newStop, curTP);
        }
     }
  }

This loop touches only positions carrying the EA's own magic number on the current symbol, so a hand-placed trade or another robot's position is left alone. For each of ours, profit is measured in points using the price that would actually close the position, the bid for a long and the ask for a short. Trailing only engages once that profit clears both the minimum-profit cushion and the trail distance combined, at which point a new stop one trail distance behind current price is proposed, and it is applied only if it genuinely tightens protection. That one-way ratchet, visible in the improves check, is what stops the stop from ever loosening on a pullback within an otherwise winning trade.

Putting it on the chart

Every visual in the program routes through a small kit of create-or-move primitives, plus three composite functions that assemble a full pattern, its extended neckline, and its pullback path.

void DrawTrend(string name, datetime t1, double p1, datetime t2, double p2, color clr, ENUM_LINE_STYLE style, int width)
  {
   if(ObjectFind(0, name) < 0)
      ObjectCreate(0, name, OBJ_TREND, 0, t1, p1, t2, p2);
   else
     {
      ObjectMove(0, name, 0, t1, p1);
      ObjectMove(0, name, 1, t2, p2);
     }
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_STYLE, style);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, width);
   ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, false);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
  }

void DrawLabel(string name, datetime time, double price, string text, color clr, ENUM_ANCHOR_POINT anchor)
  {
   if(ObjectFind(0, name) < 0)
     {
      ObjectCreate(0, name, OBJ_TEXT, 0, time, price);
      ObjectSetString(0, name, OBJPROP_FONT, "Arial Bold");
      ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 9);
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
     }
   ObjectSetString(0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, anchor);
   ObjectMove(0, name, 0, time, price);
  }

void DrawMarker(string name, datetime time, double price, bool up, color clr, int anchor)
  {
   if(ObjectFind(0, name) < 0)
      ObjectCreate(0, name, OBJ_TEXT, 0, time, price);
   else
      ObjectMove(0, name, 0, time, price);
   ObjectSetString(0, name, OBJPROP_FONT, "Wingdings 3");
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, InpMarkerSize);
   ObjectSetString(0, name, OBJPROP_TEXT, up ? "p" : "q");
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, anchor);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
  }

void DrawTradeLevels(bool isBull, datetime time, double entry, double stop, double takeProfit)
  {
   if(!VisualsAllowed()) return;
   string id = "DTB_Ent_" + IntegerToString((int)time);
   datetime endTime = time + (datetime)(PeriodSeconds(InpEntryTimeframe) * 30);
   DrawTrend(id + "_e",  time, entry,      endTime, entry,      clrDodgerBlue, STYLE_SOLID, 2);
   DrawTrend(id + "_sl", time, stop,       endTime, stop,       C'220,60,60',  STYLE_DASH,  1);
   DrawTrend(id + "_tp", time, takeProfit, endTime, takeProfit, C'0,200,80',   STYLE_DASH,  1);
   double barHigh = iHigh(_Symbol, InpEntryTimeframe, 1);
   double barLow  = iLow(_Symbol, InpEntryTimeframe, 1);
   DrawMarker(id + "_a", time, isBull ? barLow : barHigh, isBull, isBull ? InpBullColor : InpBearColor,
              isBull ? ANCHOR_UPPER : ANCHOR_LOWER);
  }

void DrawPattern()
  {
   if(!VisualsAllowed()) return;
   string id = IntegerToString((int)peakTwoTime);
   color patternColor = (patternDirection < 0) ? InpBearColor : InpBullColor;
   bool topPattern = (patternDirection < 0);
   datetime now = iTime(_Symbol, InpEntryTimeframe, 0);
   if(hasLead)
      DrawTrend("DTB_Lead_" + id, leadTime, leadPrice, peakOneTime, peakOnePrice, InpTrendColor, STYLE_DOT, 1);
   DrawTrend("DTB_LegA_" + id, peakOneTime, peakOnePrice, necklineTime, necklineLevel, patternColor, STYLE_SOLID, 2);
   DrawTrend("DTB_LegB_" + id, necklineTime, necklineLevel, peakTwoTime, peakTwoPrice, patternColor, STYLE_SOLID, 2);
   DrawTrend("DTB_Neck_" + id, necklineStartTime, necklineLevel, now, necklineLevel, InpNecklineColor, STYLE_DASH, 1);
   DrawLabel("DTB_Neckt_" + id, necklineStartTime, necklineLevel, " Neckline", InpNecklineColor,
             topPattern ? ANCHOR_LEFT_LOWER : ANCHOR_LEFT_UPPER);
   DrawMarker("DTB_P1_" + id, peakOneTime, peakOnePrice, !topPattern, patternColor, topPattern ? ANCHOR_LOWER : ANCHOR_UPPER);
   DrawMarker("DTB_P2_" + id, peakTwoTime, peakTwoPrice, !topPattern, patternColor, topPattern ? ANCHOR_LOWER : ANCHOR_UPPER);
   DrawMarker("DTB_N_"  + id, necklineTime, necklineLevel, topPattern, InpNecklineColor, topPattern ? ANCHOR_UPPER : ANCHOR_LOWER);
   DrawLabel("DTB_P1t_" + id, peakOneTime, peakOnePrice, topPattern ? " First Top" : " First Bottom",
             patternColor, topPattern ? ANCHOR_LEFT_LOWER : ANCHOR_LEFT_UPPER);
   DrawLabel("DTB_P2t_" + id, peakTwoTime, peakTwoPrice, topPattern ? " Second Top" : " Second Bottom",
             patternColor, topPattern ? ANCHOR_LEFT_LOWER : ANCHOR_LEFT_UPPER);
  }

void ExtendNeckline()
  {
   if(!VisualsAllowed()) return;
   string id = IntegerToString((int)peakTwoTime);
   datetime now = iTime(_Symbol, InpEntryTimeframe, 0);
   DrawTrend("DTB_Neck_" + id, necklineStartTime, necklineLevel, now, necklineLevel, InpNecklineColor, STYLE_DASH, 1);
  }

void DrawPullback()
  {
   if(!VisualsAllowed()) return;
   string id = IntegerToString((int)peakTwoTime);
   datetime touchTime = iTime(_Symbol, InpEntryTimeframe, 1);
   color patternColor = (patternDirection < 0) ? InpBearColor : InpBullColor;
   DrawTrend("DTB_PBa_" + id, breakoutTime, necklineLevel, pullbackExtremeTime, pullbackExtremePrice, patternColor, STYLE_DASH, 1);
   DrawTrend("DTB_PBb_" + id, pullbackExtremeTime, pullbackExtremePrice, touchTime, necklineLevel, patternColor, STYLE_DASH, 1);
   DrawLabel("DTB_PBt_" + id, touchTime, necklineLevel, " Pullback", patternColor,
             patternDirection < 0 ? ANCHOR_LEFT_LOWER : ANCHOR_LEFT_UPPER);
  }

The four primitives share one habit worth naming: check with ObjectFind whether the object already exists, create it if not, otherwise just move it. That is what lets the program redraw a pattern on every bar without leaving behind a trail of duplicate objects, and every object is marked non-selectable and hidden from the object list so the chart's object panel stays usable. DrawTrend draws any two-point line, used for pattern legs, the neckline, the leading trend leg, and the breakout and pullback legs alike. DrawLabel draws and refreshes a text label. DrawMarker places a small up or down triangle using glyphs from the Wingdings 3 font, and DrawTradeLevels is the one used only once a trade is live, drawing the entry, stop and target lines and a direction arrow at the trigger bar.

DrawPattern is the composite that assembles the full picture once a pattern arms: both legs, the horizontal neckline with its label, the optional leading leg, and labeled markers on each peak and on the neckline pivot itself, all mirrored in color and orientation depending on whether the pattern is a top or a bottom. ExtendNeckline is called on every bar while a setup is live, simply redrawing the same neckline out to the current bar so the trigger level is always visible as price approaches it. DrawPullback draws the two-legged path from the breakout down (or up) to the pullback extreme and back to the neckline, which makes a retest entry easy to read after the fact, even though it only fires once, on the bar where the entry actually happens.

Wiring the handlers

int OnInit()
  {
   symbolDigits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
   symbolPoint  = _Point;
   trade.SetExpertMagicNumber(InpMagicNumber);
   trade.SetDeviationInPoints(20);
   ArrayResize(swings, 0);
   setupState = STATE_IDLE; patternDirection = 0;
   lastPatternEndTime = 0; necklineStartTime = 0;
   lastBarTime = iTime(_Symbol, InpEntryTimeframe, 0);
   Log("Double Top and Double Bottom EA ready on " + _Symbol + " | Magic " + IntegerToString(InpMagicNumber));
   return INIT_SUCCEEDED;
  }

void OnDeinit(const int reason)
  {
   if(reason == REASON_REMOVE || reason == REASON_CHARTCLOSE || reason == REASON_CLOSE)
      ObjectsDeleteAll(0, "DTB_");
   Comment("");
  }

void OnTick()
  {
   if(IsNewBar())
     {
      DetectSwings();
      TryDetectPattern();
      ProgressSetup();
      if(VisualsAllowed()) ChartRedraw(0);
     }
   ManageTrailing();
  }

OnInit caches the symbol's digits and point size, configures the trade object, clears the swing buffer and pattern state, seeds the bar guard, and logs that the robot is ready. OnDeinit removes only the EA's own DTB_-prefixed chart objects, and only on a genuine removal or chart close, so a settings tweak never wipes a chart's visuals. OnTick is the heartbeat: on every new bar it detects swings, searches for a pattern, and advances any pattern already in progress, in that exact order, since a pattern can only be found once the swings feeding it exist, and only one state-machine step should run per bar. Trailing sits outside that gate and runs on every tick, because protecting an open position should not wait for the next candle to close.

Running it

Drop the file into MQL5/Experts, compile and attach it to a chart. The pattern logic works on any timeframe, controlled independently by InpEntryTimeframe rather than the chart's own period. Start with InpSwingLength around 5, InpPeakTolerancePercent around 10, and leave the pullback option off for your first run, so every confirmed neckline break fires an order immediately rather than waiting on a retest that may never arrive.

Watch it in the Strategy Tester's visual mode first. Non-visual runs skip every drawing call, so visual mode is the only way to actually see a pattern get pieced together, watch it survive or fail the tolerance and balance filters, and see the neckline extend bar by bar until it breaks.


What to watch for

The two legs either side of the neckline are compared purely by bar count, not by price distance, so InpLegBalancePercent behaves differently on a choppy instrument than on a smooth-trending one. The optional break-leg balance test, InpIncludeBreakLeg, only ever rejects a confirmed break; it can never arm a pattern that the main filters already rejected. Because TryDetectPattern always treats the single newest pivot as the second peak, a pattern can only be found the bar after that pivot confirms, which, with a swing length of five, means detection always lags the actual turn by at least five bars. None of this removes the underlying risk of trading a reversal pattern: a confirmed neckline break can still fail, and the measured-move target assumes the pattern repeats its own height, which it will not always do.

Closing thoughts

The double top and double bottom are old patterns, older than algorithmic trading itself, and the temptation with old patterns is to trade them on feel. This program resists that by making every judgment a parameter: how close two peaks have to be, how balanced the two legs have to be, how far apart the peaks must sit, whether a trend has to lead into the shape, and whether the entry waits for a pullback or not. None of those choices are hidden in a human's eye for a chart; all of them are numbers you can see, change and test.

The complete source file is attached, with every rule described above exposed as an input.

For educational purposes only. Trading involves substantial risk, and backtested results do not guarantee future performance. Test thoroughly on a demo account and size your risk carefully before using any automated system live.
Attachments
double bot and top.set · 2.8 KB
Download
Double Top and Double Bottom.mq5 · 44.2 KB
Download
170 views
Discussions 0

No discussions yet

Be the first to share your thoughts on this resource.

Sign in to take part
Sign in or register to comment and report.
0%
Uploading…
Please don’t close this page