Skip to content
← Back to the research library
MQL5 SOURCE COLLECTION / Mean Reversion

Stock Mean Reversion: Multi-Symbol

Scans a hard-coded equity-symbol universe for daily declines and attempts discounted long entries with trend and time-exit rules.

MT5 / MQL5Original sourceBroker mapping required

D1 / multi-symbol scan · Published 28 October 2026

Source inspectionLimited static review
MetaEditor compilationNot performed
Backtest / live recordNot supplied

How the source is structured

  1. Look for a previous daily close more than 3% below that day's open.
  2. Calculate an entry below that close using ATR, with an optional daily EMA filter; use a buy limit or market buy depending on the current ask.
  3. Manage pending-order age, percentage stops, an ATR target, a time stop and a separate price-based exit.

Default inputs

As supplied; these are not optimized or recommended settings.
Daily drop threshold3% from the day's open
Entry / target ATR factors0.9 / 0.5
Stop / risk input4% / 1% per trade
Order expiry / time stop1 / 10 daily bars
Trend / volatilityD1 EMA 200 / ATR 5
Symbol limit0 = no input limit
BEFORE YOU TEST

Source-review notes

These observations come from reading this uploaded version. They are not compiler output or a complete code audit. The download retains the source as supplied.

SOURCE LINES 61–70, 95–124

The symbol list is hard-coded with names such as AAPL.NAS and MSFT.NAS. It must be mapped to the broker's actual instrument names.

SOURCE LINES 22, 29, 190–258

The risk input applies per trade. The source has no explicit portfolio-wide exposure cap across the scanned instruments.

SOURCE LINES 56–59, 211–228, 316–328

Indicator buffers are shared across symbols, while refresh timestamps are per-symbol. Buffer reuse between symbols needs review before testing.

Dependencies

Broker data for the supplied equity-symbol list; built-in EMA and ATR; MetaTrader 5 standard trade libraries.

Source & attribution

Source copyright: Tatiana Zyrianova. Header version: 1.10. Original author notices are retained. Link from original header ↗

Included in the Edge Quant source collection with existing notices preserved. Free download does not imply a new license grant.

Original filename: Stock Mean Reversion system.mq5
Encoding: UTF-16

Inspect the original source

The browser preview is decoded for reading; the download keeps the original file bytes.

Direct .mq5 file ↓
Expand full MQL5 source · 372 lines
//+------------------------------------------------------------------+//|                                                        ksive.mq5 |//|                                                Tatiana Zyrianova |//|                        https://www.mql5.com/en/users/mqldiligent |//+------------------------------------------------------------------+#property copyright "Tatiana Zyrianova"#property link      "https://www.mql5.com/en/users/mqldiligent"#property version   "1.10"// ---#include <Trade\OrderInfo.mqh>#include <Trade\PositionInfo.mqh>#include <Trade\Trade.mqh>COrderInfo     ord;CPositionInfo  psn;CTrade         trd;// ---input group                "=== GENERAL SETTINGS ==="input double               LotSize           = 0.01;        // Fixed lot sizeinput double               RiskPerTrade      = 1.0;         // Risk per trade in % (0-disabled)input double               DDPercToOpen      = 3.0;         // Daily drop % for panic signalinput double               ATRMultToOpen     = 0.9;         // ATR mult for entry limitinput double               ATRMultToTP       = 0.5;         // ATR mult for TPinput double               SLInPerc          = 4.0;         // SL drop % from entryinput int                  NmbDaysToDlt      = 1;           // Days delay to entryinput int                  NmbDaysToCls      = 10;          // Days for time stopinput int                  MaxNmbOfSymbols   = 0;           // Max number of symbols (0-disabled)input group                "=== TREND FILTER ==="input bool                 UseTrendFilter    = true;        // Use filterinput int                  MA_Period         = 200;         // Periodinput ENUM_MA_METHOD       MA_Method         = MODE_EMA;    // Methodinput ENUM_APPLIED_PRICE   MA_Price          = PRICE_CLOSE; // Priceinput group                "=== ATR SETTINGS ==="input int                  ATR_Period        = 5;           // Periodulong ord_ticket;int NmbOfSymb;double Lot, Price, SL, TP, Ask, Bid;bool Testing;int Magic = 1772432;int s_digits[];double point[];double stoplevel[];double lotsstep[];double tickvalue[];double ticksize[];double lotsmin[];double lotsmax[];datetime LastTimeInd[];int MA_h[], ATR_h[];double MA_Val[], ATR_Val[];const string symbols[] = {"AAPL.NAS", "ABNB.NAS", "ADBE.NAS", "ADI.NAS", "ADP.NAS", "ADSK.NAS", "AEP.NAS", "AMAT.NAS", "AMD.NAS", "AMGN.NAS",                       "AMZN.NAS", "APP.NAS", "ARM.NAS", "ASML.NAS", "AVGO.NAS", "AXON.NAS", "AZN.NAS", "BIIB.NAS", "BKNG.NAS", "BKR.NAS",                       "CCEP.NAS", "CDNS.NAS", "CDW.NAS", "CEG.NAS", "CHTR.NAS", "CMCSA.NAS", "COST.NAS", "CPRT.NAS", "CRWD.NAS", "CSCO.NAS",                       "CSGP.NAS", "CSX.NAS", "CTAS.NAS", "CTSH.NAS", "DASH.NAS", "DDOG.NAS", "DXCM.NAS", "EA.NAS", "EXC.NAS", "FANG.NAS",                       "FAST.NAS", "FTNT.NAS", "GEHC.NAS", "GFS.NAS", "GILD.NAS", "GOOG.NAS", "GOOGL.NAS", "HON.NAS", "IDXX.NAS", "INTC.NAS",                       "INTU.NAS", "ISRG.NAS", "KDP.NAS", "KHC.NAS", "KLAC.NAS", "LIN.NAS", "LRCX.NAS", "LULU.NAS", "MAR.NAS", "MCHP.NAS",                       "MDLZ.NAS", "MELI.NAS", "MVRS.NAS", "MNST.NAS", "MRVL.NAS", "MSFT.NAS", "MSTR.NAS", "MU.NAS", "NFLX.NAS", "NVDA.NAS",                       "NXPI.NAS", "ODFL.NAS", "ON.NAS", "ORLY.NAS", "PANW.NAS", "PAYX.NAS", "PCAR.NAS", "PDD.NAS", "PEP.NAS", "PLTR.NAS",                       "PYPL.NAS", "QCOM.NAS", "REGN.NAS", "ROP.NAS", "ROST.NAS", "SBUX.NAS", "SHOP.NAS", "SNPS.NAS", "TEAM.NAS", "TMUS.NAS",                       "TRI.NAS", "TSLA.NAS", "TTD.NAS", "TTWO.NAS", "TXN.NAS", "VRSK.NAS", "VRTX.NAS", "WBD.NAS", "WDAY.NAS", "XEL.NAS", "ZS.NAS"};//+------------------------------------------------------------------+//| Expert initialization function                                   |//+------------------------------------------------------------------+int OnInit(){   // ---   NmbOfSymb = ArraySize(symbols);      // ---   ArrayResize(s_digits, NmbOfSymb);   ArrayResize(point, NmbOfSymb);   ArrayResize(stoplevel, NmbOfSymb);   ArrayResize(lotsstep, NmbOfSymb);   ArrayResize(tickvalue, NmbOfSymb);   ArrayResize(ticksize, NmbOfSymb);   ArrayResize(lotsmin, NmbOfSymb);   ArrayResize(lotsmax, NmbOfSymb);   ArrayResize(LastTimeInd, NmbOfSymb);   ArrayResize(MA_h, NmbOfSymb);   ArrayResize(ATR_h, NmbOfSymb);      // ---   bool flag = false;   int nmb = 0;   for (int i = 0; i < ArraySize(symbols) && (MaxNmbOfSymbols == 0 || i < MaxNmbOfSymbols); i++)   {      if (SymbolSelect(symbols[i], true))      {         if (UseTrendFilter)         {            MA_h[i] = iMA(symbols[i], PERIOD_D1, MA_Period, 0, MA_Method, MA_Price);            if (MA_h[i] == INVALID_HANDLE) Print("Error creating MA handle for "+symbols[i]+" symbol!");         }                  ATR_h[i] = iATR(symbols[i], PERIOD_D1, ATR_Period);         if (ATR_h[i] == INVALID_HANDLE) Print("Error creating ATR handle for "+symbols[i]+" symbol!");                  s_digits[i] = (int)SymbolInfoInteger(symbols[i], SYMBOL_DIGITS);         point[i] = SymbolInfoDouble(symbols[i], SYMBOL_POINT);         stoplevel[i] = SymbolInfoInteger(symbols[i], SYMBOL_TRADE_STOPS_LEVEL)*point[i];         lotsstep[i] = SymbolInfoDouble(symbols[i], SYMBOL_VOLUME_STEP);         tickvalue[i] = SymbolInfoDouble(symbols[i], SYMBOL_TRADE_TICK_VALUE);         ticksize[i] = SymbolInfoDouble(symbols[i], SYMBOL_TRADE_TICK_SIZE);         lotsmin[i] = SymbolInfoDouble(symbols[i], SYMBOL_VOLUME_MIN);         lotsmax[i] = SymbolInfoDouble(symbols[i], SYMBOL_VOLUME_MAX);                  LastTimeInd[i] = iTime(symbols[i], PERIOD_D1, 1);      }      else      {         Print("Error adding symbol: ", symbols[i]);         flag = true;         nmb++;      }   }   if (!flag) Print("All symbols have been successfully added to MarketWatch.");   else   {      if (MaxNmbOfSymbols == 0 || MaxNmbOfSymbols >= NmbOfSymb)      {         Print("===========================");         if (nmb < NmbOfSymb) Print(IntegerToString(NmbOfSymb-nmb)+" out of "+IntegerToString(NmbOfSymb)+" symbols were found.");         else Print("No symbols were found.");         Print("===========================");      }   }      // ---   trd.SetExpertMagicNumber(Magic);      // ---   Testing = MQLInfoInteger(MQL_TESTER);      // ---   ArraySetAsSeries(MA_Val, true);   ArraySetAsSeries(ATR_Val, true);      // ---   EventSetTimer(10);      return(INIT_SUCCEEDED);}//+------------------------------------------------------------------+//| Expert deinitialization function                                 |//+------------------------------------------------------------------+void OnDeinit(const int reason){   // ---   for (int i = 0; i < ArraySize(symbols) && (MaxNmbOfSymbols == 0 || i < MaxNmbOfSymbols); i++)   {      if (UseTrendFilter && MA_h[i] != INVALID_HANDLE) IndicatorRelease(MA_h[i]);      if (ATR_h[i] != INVALID_HANDLE) IndicatorRelease(ATR_h[i]);   }      // ---   EventKillTimer();}//+------------------------------------------------------------------+//| Expert tick function                                             |//+------------------------------------------------------------------+void OnTick(){   // ---   if (Testing) MainAlgo();}//+------------------------------------------------------------------+//| Expert timer function                                            |//+------------------------------------------------------------------+void OnTimer(){   // ---   if (!Testing) MainAlgo();}//+------------------------------------------------------------------+void MainAlgo(){   MqlDateTime time_str;   datetime CurrTime = TimeTradeServer(time_str);      for (int i = 0; i < ArraySize(symbols) && (MaxNmbOfSymbols == 0 || i < MaxNmbOfSymbols); i++)   {      bool PrintFlag = false;      if (IsMarketOpen(symbols[i], time_str))      {         // ---         DeleteOrders(symbols[i], Magic, ORDER_TYPE_BUY_LIMIT, true);                  // ---         CloseAllPositions(symbols[i], Magic, POSITION_TYPE_BUY, true);                  // ---         Bid = NormalizeDouble(SymbolInfoDouble(symbols[i], SYMBOL_BID), s_digits[i]);         CloseAllPositions(symbols[i], Magic, POSITION_TYPE_BUY, false, true, Bid);                  // ---         if (NumberOfPos(symbols[i], Magic, POSITION_TYPE_BUY) == 0 && NumberOfOrd(symbols[i], Magic, ORDER_TYPE_BUY_LIMIT) == 0)         {            double Cls1 = iClose(symbols[i], PERIOD_D1, 1);            if (Cls1 < iOpen(symbols[i], PERIOD_D1, 1)*(100.0-DDPercToOpen)/100)            {               bool UpdateFlag = true;               if (iBarShift(symbols[i], PERIOD_D1, LastTimeInd[i]) > 0)               {                  UpdateFlag = UpdatingInd(i);                  if (UpdateFlag) LastTimeInd[i] = CurrTime;               }                              if (UpdateFlag)               {                  Ask = NormalizeDouble(SymbolInfoDouble(symbols[i], SYMBOL_ASK), s_digits[i]);                                    Price = NormalizeDouble(Cls1-ATR_Val[1]*ATRMultToOpen, s_digits[i]);                  if (Ask < Price+stoplevel[i]) Price = Ask;                                    if (!UseTrendFilter || Price >= MA_Val[1])                  {                     SL = NormalizeDouble(Price*(100.0-SLInPerc)/100, s_digits[i]);                     TP = NormalizeDouble(Cls1+ATR_Val[1]*ATRMultToTP, s_digits[i]);                                          if (RiskPerTrade <= 0) Lot = NL(i, LotSize);                     else Lot = NL(i, GetLot(i, AccountInfoDouble(ACCOUNT_BALANCE), RiskPerTrade, int((Price-SL)/point[i])));                                          if (CheckMoneyForTrade(symbols[i], ORDER_TYPE_BUY, Lot, Price))                     {                        if (Price == Ask)                        {                           if (trd.Buy(Lot, symbols[i], Price, SL, TP, IntegerToString(iTime(symbols[i], PERIOD_D1, 0))))                           {                              ord_ticket = trd.ResultOrder();                              if (ord_ticket <= 0){ Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order on "+symbols[i]+"."); PrintFlag = true; }                           }                           else{ Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order on "+symbols[i]+"."); PrintFlag = true; }                        }                        else                        {                           if (trd.BuyLimit(Lot, Price, symbols[i], SL, TP, ORDER_TIME_GTC, 0, IntegerToString(iTime(symbols[i], PERIOD_D1, 0))))                           {                              ord_ticket = trd.ResultOrder();                              if (ord_ticket <= 0){ Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order on "+symbols[i]+"."); PrintFlag = true; }                           }                           else{ Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order on "+symbols[i]+"."); PrintFlag = true; }                        }                     }                     else{ Print("Not enough funds to open an order with a lot size of "+DoubleToString(Lot, 2)+" on "+symbols[i]+"."); PrintFlag = true; }                  }               }            }         }      }            if (PrintFlag) Print("===========================");   }}//+------------------------------------------------------------------+int NumberOfPos(string symbol = "", int magic = -1, ENUM_POSITION_TYPE pos_type = WRONG_VALUE){   int nmb = 0;   for (int i=PositionsTotal()-1; i>=0; i--)   {      if (psn.SelectByIndex(i) && (symbol == "" || psn.Symbol() == symbol) && (magic == -1 || psn.Magic() == magic) && (pos_type == WRONG_VALUE || psn.PositionType() == pos_type))         nmb++;   }   return(nmb);}//+------------------------------------------------------------------+int NumberOfOrd(string symbol = "", int magic = -1, ENUM_ORDER_TYPE ord_type = WRONG_VALUE){   int nmb = 0;   for (int i=OrdersTotal()-1; i>=0; i--)   {      if (ord.SelectByIndex(i) && (symbol == "" || ord.Symbol() == symbol) && (magic == -1 || ord.Magic() == magic) && (ord_type == WRONG_VALUE || ord.OrderType() == ord_type))         nmb++;   }   return(nmb);}//+------------------------------------------------------------------+void CloseAllPositions(string symbol = "", int magic = -1, ENUM_POSITION_TYPE pos_type = WRONG_VALUE, bool cls_flag1 = false, bool cls_flag2 = false, double bid = 0){   for (int i=PositionsTotal()-1; i>=0; i--)   {      if (psn.SelectByIndex(i) && (symbol == "" || psn.Symbol() == symbol) && (magic == -1 || psn.Magic() == magic) && (pos_type == WRONG_VALUE || psn.PositionType() == pos_type))      {         if (!cls_flag1 || iBarShift(symbol, PERIOD_D1, psn.Time()) >= NmbDaysToCls)         {            int bar = 0;            if (cls_flag2) bar = iBarShift(symbol, PERIOD_D1, (datetime)StringToInteger(psn.Comment()));            if (!cls_flag2 || (bar > 0 && bid >= iHigh(symbol, PERIOD_D1, bar)))               trd.PositionClose(psn.Ticket());         }      }   }}//+------------------------------------------------------------------+void DeleteOrders(string symbol = "", int magic = -1, ENUM_ORDER_TYPE ord_type = WRONG_VALUE, bool exp_flag = false){   for (int i=OrdersTotal()-1; i>=0; i--)   {      if (ord.SelectByIndex(i) && (symbol == "" || ord.Symbol() == symbol) && (magic == -1 || ord.Magic() == magic) && (ord_type == WRONG_VALUE || ord.OrderType() == ord_type))      {         if (!exp_flag || iBarShift(symbol, PERIOD_D1, ord.TimeSetup()) >= NmbDaysToDlt)            trd.OrderDelete(ord.Ticket());      }   }}//+------------------------------------------------------------------+bool UpdatingInd(int i){   int buff_size = 2;   if (UseTrendFilter)   {      if (MA_h[i] == INVALID_HANDLE) return(false);      if (CopyBuffer(MA_h[i], 0, 0, buff_size, MA_Val) != buff_size || ArraySize(MA_Val) != buff_size) return(false);   }      if (ATR_h[i] == INVALID_HANDLE) return(false);   if (CopyBuffer(ATR_h[i], 0, 0, buff_size, ATR_Val) != buff_size || ArraySize(ATR_Val) != buff_size) return(false);      return(true);}//+------------------------------------------------------------------+double NL(int i, double lot){   return(MathMin(MathMax(MathRound(lot/lotsstep[i])*lotsstep[i],lotsmin[i]),lotsmax[i]));}//+------------------------------------------------------------------+double GetLot(int i, double free, double risk, int sl = 0){   if (sl <= 0 || tickvalue[i] <= 0) return(free/1000*lotsmin[i]*risk);   return((free*risk/100)/(sl*(point[i]*tickvalue[i]/ticksize[i])));}//+------------------------------------------------------------------+bool CheckMoneyForTrade(string symbol, ENUM_ORDER_TYPE type,double volume,double price){   double margin = 0;   double marginFree = AccountInfoDouble(ACCOUNT_MARGIN_FREE);      if (!OrderCalcMargin(type,symbol,volume,price,margin))      return false;      if (margin > marginFree)      return false;      return true;}//+------------------------------------------------------------------+bool IsMarketOpen(string symbol, MqlDateTime &time_str){   datetime currentTime = time_str.sec + time_str.min*60 + time_str.hour*3600;   ENUM_DAY_OF_WEEK day = (ENUM_DAY_OF_WEEK)time_str.day_of_week;   uint index = 0;   datetime fromTime, toTime;   while (SymbolInfoSessionTrade(symbol, day, index, fromTime, toTime))   {      if (currentTime >= fromTime && currentTime < toTime)         return true;      index++;   }      return false;}//+------------------------------------------------------------------+

SHA-256: ce2deee20f88384c8ab8880abf3129bd3328d1aed46e7c1544bc7285572599b7

Educational source material, not investment advice. No profitability, execution quality or live-readiness claim is made for this upload.