OnTick ignores the indicator-update function's failure result before subsequent code reads indicator buffers.
Intraday Volatility Breakout · v1
Breakout bands around the previous daily close, with narrow-day, range-contraction and trend filters.
How the source is structured
- Place thresholds at the previous close plus or minus 0.33 times daily ATR.
- Require the enabled narrow-day, contraction and SMA-direction filters before entering a break.
- Use an ATR stop, a daily entry cap and a server-time closing window; there is no fixed take-profit.
Default inputs
| Daily ATR period | 14 |
|---|---|
| Breakout / stop ATR multipliers | 0.33 / 0.33 |
| Risk input / fixed-volume fallback | 1% / 0.01 lot |
| Maximum trades per day | 1 |
| Trading hours / SMA period | 00:00–23:00 server time / 50 |
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.
The nonzero RiskPerc input activates calculated volume; the fixed lot input is a fallback. Default inputs are not validated settings.
Dependencies
Built-in daily ATR and SMA; MetaTrader 5 standard trade libraries.
Source & attribution
Source copyright: Tatiana Zyrianova. Header version: 1.00. 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.
Inspect the original source
The browser preview is decoded for reading; the download keeps the original file bytes.
Expand full MQL5 source · 317 lines
//+------------------------------------------------------------------+//| Intraday Volatility Breakout.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.00"// ---#include <Trade\AccountInfo.mqh>#include <Trade\SymbolInfo.mqh>#include <Trade\PositionInfo.mqh>#include <Trade\Trade.mqh>CAccountInfo acc;CSymbolInfo smb;CPositionInfo psn;CTrade trd;// ---input int ATRPeriod = 14; // ATR periodinput double BreakoutMult = 0.33; // Breakout multiplierinput double SLMult = 0.33; // SL multiplierinput double FixLotSize = 0.01; // Fixed lot sizeinput double RiskPerc = 1.0; // Risk % (0-disabled)input int MaxTrdPerDay = 1; // Maximum trades per dayinput int TradingStartHour = 0; // Trading start hourinput int TradingEndHour = 23; // Trading end hourinput bool NarrowDayFilt = true; // Narrow day fitlerinput double NarrowDayThreshold = 0.7; // Narrow day thresholdinput bool RangeContraction = true; // Range contraction filterinput double ContrThreshold = 0.9; // Contraction thresholdinput bool TrendFilt = true; // Trend filterinput int MAPeriod = 50; // SMA periodinput int Magic = 18036; // Magic number// ---ulong ord_ticket;int NmbBuy, NmbSell;double SL, Lot;datetime LastTimeInd, LastTime;int ATR_h, MA_h;double ATR_Val[], MA_Val[];//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+int OnInit(){ // --- if (!smb.Name(_Symbol)) return(INIT_FAILED); smb.Refresh(); // --- trd.SetExpertMagicNumber(Magic); // --- LastTimeInd = iTime(smb.Name(), PERIOD_D1, 1); // --- ATR_h = iATR(smb.Name(), PERIOD_D1, ATRPeriod); if (ATR_h == INVALID_HANDLE) { Print("Error creating ATR handle!"); return(INIT_FAILED); } if (TrendFilt) { MA_h = iMA(smb.Name(), PERIOD_D1, MAPeriod, 0, MODE_SMA, PRICE_CLOSE); if (MA_h == INVALID_HANDLE) { Print("Error creating MA handle!"); return(INIT_FAILED); } } // --- ArraySetAsSeries(ATR_Val, true); ArraySetAsSeries(MA_Val, true); return(INIT_SUCCEEDED);}//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+void OnDeinit(const int reason){ // --- IndicatorRelease(ATR_h); if (TrendFilt) IndicatorRelease(MA_h);}//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+void OnTick(){ // --- smb.RefreshRates(); CountTrades(); datetime DayStartTime = StartDayServTime(); // --- UpdatingIndVal(); // --- if (NmbBuy+NmbSell > 0) { if (TimeCurrent() >= DayStartTime+TradingEndHour*3600) { CloseAllPos(smb.Name(), Magic); CountTrades(); } } // --- if (NmbBuy+NmbSell == 0) { if (TimeCheck(DayStartTime+TradingStartHour*3600, DayStartTime+TradingEndHour*3600)) { if (LastTime == 0 || iBarShift(smb.Name(), PERIOD_M1, LastTime) > 0) { if (NmbHistDayTrd(DayStartTime) < MaxTrdPerDay) { double ClsD1 = iClose(smb.Name(), PERIOD_D1, 1); double DnLvl = ClsD1 - ATR_Val[1]*BreakoutMult; double UpLvl = ClsD1 + ATR_Val[1]*BreakoutMult; if (SignalBuy(UpLvl)) { SL = NormalizeDouble(smb.Ask()-ATR_Val[1]*SLMult, smb.Digits()); if (RiskPerc <= 0) Lot = NL(FixLotSize); else Lot = NL(GetLot(acc.Balance(), RiskPerc, int((smb.Ask()-SL)/smb.Point()))); if (CheckMoneyForTrade(ORDER_TYPE_BUY, Lot, smb.Ask())) { if (trd.Buy(Lot, smb.Name(), smb.Ask(), SL, 0)) { ord_ticket = trd.ResultOrder(); if (ord_ticket > 0) { NmbBuy++; LastTime = TimeCurrent(); } else Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order."); } else Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order."); } else Print("Not enough funds to open an order with a lot size of "+DoubleToString(Lot, 2)+"."); } if (SignalSell(DnLvl)) { SL = NormalizeDouble(smb.Bid()+ATR_Val[1]*SLMult, smb.Digits()); if (RiskPerc <= 0) Lot = NL(FixLotSize); else Lot = NL(GetLot(acc.Balance(), RiskPerc, int((SL-smb.Bid())/smb.Point()))); if (CheckMoneyForTrade(ORDER_TYPE_SELL, Lot, smb.Bid())) { if (trd.Sell(Lot, smb.Name(), smb.Bid(), SL, 0)) { ord_ticket = trd.ResultOrder(); if (ord_ticket > 0) { NmbSell++; LastTime = TimeCurrent(); } else Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order."); } else Print("Error #"+IntegerToString(GetLastError())+" occurred while opening an order."); } else Print("Not enough funds to open an order with a lot size of "+DoubleToString(Lot, 2)+"."); } } } } }}//+------------------------------------------------------------------+void CountTrades(){ NmbBuy = 0; NmbSell = 0; for (int i=PositionsTotal()-1; i>=0; i--) { if (psn.SelectByIndex(i) && psn.Symbol() == smb.Name() && psn.Magic() == Magic) { if (psn.PositionType() == POSITION_TYPE_BUY) NmbBuy++; if (psn.PositionType() == POSITION_TYPE_SELL) NmbSell++; } }}//+------------------------------------------------------------------+void CloseAllPos(string symbol = "", int magic = -1, ENUM_POSITION_TYPE pos_type = WRONG_VALUE){ 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)) { trd.PositionClose(psn.Ticket()); } }}//+------------------------------------------------------------------+bool SignalBuy(double lvl){ if (smb.Bid() >= lvl && (iOpen(smb.Name(), PERIOD_M1, 0) < lvl || iClose(smb.Name(), PERIOD_M1, 1) < lvl)) { double prev_day_size = iHigh(smb.Name(), PERIOD_D1, 1)-iLow(smb.Name(), PERIOD_D1, 1); if (!NarrowDayFilt || prev_day_size <= ATR_Val[1]*NarrowDayThreshold) { if (!RangeContraction || prev_day_size <= (iHigh(smb.Name(), PERIOD_D1, 2)-iLow(smb.Name(), PERIOD_D1, 2))*ContrThreshold) { if (!TrendFilt || smb.Bid() >= MA_Val[1]) return(true); } } } return(false);}//+------------------------------------------------------------------+bool SignalSell(double lvl){ if (smb.Bid() <= lvl && (iOpen(smb.Name(), PERIOD_M1, 0) > lvl || iClose(smb.Name(), PERIOD_M1, 1) > lvl)) { double prev_day_size = iHigh(smb.Name(), PERIOD_D1, 1)-iLow(smb.Name(), PERIOD_D1, 1); if (!NarrowDayFilt || prev_day_size <= ATR_Val[1]*NarrowDayThreshold) { if (!RangeContraction || prev_day_size <= (iHigh(smb.Name(), PERIOD_D1, 2)-iLow(smb.Name(), PERIOD_D1, 2))*ContrThreshold) { if (!TrendFilt || smb.Bid() <= MA_Val[1]) return(true); } } } return(false);}//+------------------------------------------------------------------+bool UpdatingIndVal(){ if (LastTimeInd == 0 || iBarShift(smb.Name(), PERIOD_D1, LastTimeInd) > 0) { int buff_size = 2; if (CopyBuffer(ATR_h, 0, 0, buff_size, ATR_Val) != buff_size || ArraySize(ATR_Val) != buff_size) return(false); if (TrendFilt) { if (CopyBuffer(MA_h, 0, 0, buff_size, MA_Val) != buff_size || ArraySize(MA_Val) != buff_size) return(false); } LastTimeInd = TimeCurrent(); } return(true);}//+------------------------------------------------------------------+double NL(double lot){ return(MathMin(MathMax(MathRound(lot/smb.LotsStep())*smb.LotsStep(),smb.LotsMin()),smb.LotsMax()));}//+------------------------------------------------------------------+double GetLot(double free, double risk, int sl = 0){ if (sl <= 0 || smb.TickValue() <= 0) return(free/1000*smb.LotsMin()*risk); return((free*risk/100)/(sl*(smb.Point()*smb.TickValue()/smb.TickSize())));}//+------------------------------------------------------------------+bool CheckMoneyForTrade(ENUM_ORDER_TYPE type,double volume,double price){ double margin = 0; double marginFree = acc.FreeMargin(); if (!OrderCalcMargin(type,smb.Name(),volume,price,margin)) return false; if (margin > marginFree) return false; return true;}//+------------------------------------------------------------------+int NmbHistDayTrd(datetime daystarttime){ int nmb = 0; ulong deal_ticket = 0; HistorySelect(daystarttime,TimeCurrent()); int total = HistoryDealsTotal(); for (int i=0; i<total; i++) { if ((deal_ticket=HistoryDealGetTicket(i)) == 0) continue; long deal_type = HistoryDealGetInteger(deal_ticket,DEAL_TYPE); if (deal_type != DEAL_TYPE_BUY && deal_type != DEAL_TYPE_SELL) continue; string deal_symbol = HistoryDealGetString(deal_ticket, DEAL_SYMBOL); long deal_entry = HistoryDealGetInteger(deal_ticket, DEAL_ENTRY); long deal_magic = HistoryDealGetInteger(deal_ticket, DEAL_MAGIC); if (deal_symbol == smb.Name() && deal_magic == Magic && deal_entry == DEAL_ENTRY_IN) nmb++; } return(nmb);}//+------------------------------------------------------------------+datetime StartDayServTime(){ MqlDateTime str1; datetime CurrTime = TimeTradeServer(str1); datetime StartDayTime = CurrTime-(str1.hour*3600+str1.min*60+str1.sec); return(StartDayTime);}//+------------------------------------------------------------------+bool TimeCheck(datetime starttime, datetime stoptime){ datetime currtime = TimeCurrent(); if ((starttime < stoptime && currtime >= starttime && currtime < stoptime) || (starttime >= stoptime && (currtime >= starttime || currtime < stoptime))) return(true); return(false);}//+------------------------------------------------------------------+Educational source material, not investment advice. No profitability, execution quality or live-readiness claim is made for this upload.