diff --git a/Alert VOL Strong Candle CME.txt b/Alert VOL Strong Candle CME.txt new file mode 100644 index 0000000..cbe1d2b --- /dev/null +++ b/Alert VOL Strong Candle CME.txt @@ -0,0 +1,199 @@ +//@version=5 +// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ +// © godfather +// update vwap + +indicator('Alert VOL Strong Candle CME', shorttitle='Alert VOL Strong Candle CME', overlay=true, format=format.price, precision=2, max_boxes_count=500, max_bars_back=500, max_lines_count=500, max_labels_count = 500) + + +MaxLabel=input.int(title="Số Nến Hiện Tín Hiệu", defval=100, minval=5, maxval=10000, step=1) + + +groupVolume = '📈 Cấu Hình Thông Số Đầu Vào Cho Volume CME 📉' +showBarcolorVol = input.bool(defval=true, title="Hiện Màu Nến Vol Bất Thường" , group = groupVolume) +adaptive = input.string(title="Market Type ", options=["AUTO", "OTHERS"], defval="AUTO", group = groupVolume) +symbol_manual = input.symbol(defval="COMEX_DL:GC1!", group = groupVolume) + +sCode1 = + syminfo.root == "XAUUSD" ? "COMEX_DL:GC1!" : + syminfo.root == "AUDUSD" ? "CME_DL:6A1!" : + syminfo.root == "USDCAD" ? "CME_DL:6C1!" : + syminfo.root == "GBPUSD" ? "CME_DL:6B1!" : + syminfo.root == "EURUSD" ? "CME_DL:6E1!" : + syminfo.root == "USDJPY" ? "CME_DL:6J1!" : + syminfo.root == "USDCHF" ? "CME_DL:6S1!" : + syminfo.root == "NZDUSD" ? "CME_DL:6N1!" : + syminfo.root == "BTCUSDT" ? "CME_DL:BTC1!" : + syminfo.root == "ETHUSDT" ? "CME_DL:ETH1!" : + syminfo.root == "XAGUSD" ? "COMEX_DL:SI1!" : + syminfo.root == "US30" ? "CBOT_MINI_DL:YM1!" : + "" + +float _volume = na +string code_futures = na + +if (adaptive=="AUTO" and sCode1 != "") + code_futures := sCode1 +else + code_futures := "" + +volFuture = request.security(code_futures, timeframe.period, volume, lookahead=barmerge.lookahead_on) + +if (adaptive=="AUTO" and code_futures != "" ) + _volume:= volFuture +if (adaptive=="OTHERS" or code_futures == "") + _volume:= volume + +//showMA = input(defval=false, title='Show Volume Moving Average') +lengthVolumeMA = input(defval=20, title='Length of MA applied on Volume', group = groupVolume) +ratioUltraVolume = input(defval=2.2, title='Ultra High Volume Ratio', group = groupVolume) +ratioVeryHighVolume = input(defval=1.8, title='Very High Volume Ratio', group = groupVolume) +ratioHighVolume = input(defval=1.2, title='High Volume Ratio', group = groupVolume) +ratioNormalVolume = input(defval=0.8, title='Normal Volume Ratio', group = groupVolume) +ratioLowVolume = input(defval=0.4, title='Low Volume Ratio', group = groupVolume) +ratioVeryLowVolume = input(defval=0.4, title='Very Low Volume Ratio', group = groupVolume) + + +// WILDERS MA +float volumeMA = 0 +volumeMA := nz(volumeMA[1]) + (_volume - nz(volumeMA[1])) / lengthVolumeMA +float volumeMA_default = 0 +volumeMA_default := nz(volumeMA_default[1]) + (volume - nz(volumeMA_default[1])) / lengthVolumeMA + +ultraHighVolumeMin = volumeMA * ratioUltraVolume +veryHighVolumeMin = volumeMA * ratioVeryHighVolume + +ultraHighVolumeMin_default = volumeMA_default * ratioUltraVolume +veryHighVolumeMin_default = volumeMA_default * ratioVeryHighVolume + +highVolumeMin = volumeMA * ratioHighVolume +normalVolumeMin = volumeMA * ratioNormalVolume +lowVolumeMin = volumeMA * ratioLowVolume +veryLowVolumeMin = volumeMA * ratioVeryLowVolume + + +volUltraHigh = _volume >= ultraHighVolumeMin ? true : false +volVeryHigh = _volume >= veryHighVolumeMin and _volume < ultraHighVolumeMin ? true : false + +volUltraHigh_default = volume >= ultraHighVolumeMin_default ? true : false +volVeryHigh_default = volume >= veryHighVolumeMin_default and volume < ultraHighVolumeMin_default ? true : false + +volHigh = _volume >= highVolumeMin and _volume < veryHighVolumeMin ? true : false +volNormal = _volume >= normalVolumeMin and _volume < highVolumeMin ? true : false +volLow = _volume >= lowVolumeMin and _volume < normalVolumeMin ? true : false +volVeryLow = _volume < lowVolumeMin ? true : false + +// ... (existing code from the linked script) + +// Determine bullish and bearish candles +isBullish = close > open +isBearish = close < open + +// Set candle color based on conditions +//barcolor(volUltraHigh and isBullish ? color.rgb(6, 114, 96) : volUltraHigh and isBearish ? color.red : na) +//barcolor(volVeryHigh and isBullish ? color.rgb(125, 199, 127) : volVeryHigh and isBearish ? color.rgb(221, 161, 161) : na) +barcolor(showBarcolorVol and volUltraHigh and isBullish ? color.rgb(23, 109, 41) : showBarcolorVol and volUltraHigh and isBearish? color.rgb(173, 20, 20) : na) +barcolor(showBarcolorVol and volVeryHigh and isBullish ? color.rgb(173, 218, 183) : showBarcolorVol and volVeryHigh and isBearish ? color.rgb(236, 128, 128) : na) + + + +//========================================Begin Flase Break - TRAP============================================ +groupTrap = '📈 Cấu Hình Signal Trap 📉' +bool showTrap = input(false, 'Hiện Signal TRAP', group = groupTrap) +lookbackTRAP=input.int(title="Kiểm Tra Bao Nhiêu Cây Nến", defval=3, minval=1, maxval=10, step=1, group = groupTrap) +bool showSignalUltra = input(true, 'Get Break Vol Ultra', group = groupTrap) +bool showSignalVery = input(false, 'Get Break Vol Very', group = groupTrap) +bool alertTrap = input(true, 'Thông Báo Tín Hiệu', group = groupTrap) + +//======================= +bool firstTrapSell = false +var highTrapSell = high +//================================= +bool firstTrapBuy = false +var lowTrapBuy = low + +////////////////////////////////////////////////////////////////Code Sell + +for ii = 1 to lookbackTRAP by 1 + //Tìm thấy tín hiệu trước đó bỏ qua + // if(firstTrapBuy[ii]) + // lowTrapBuy := low + // break + + //Kill vol ultra high + if(showSignalUltra and volUltraHigh[ii]) + lowTrapBuy :=low[ii] + break + else + lowTrapBuy := low + + //Kill vol very ultra + if(showSignalVery and volVeryHigh[ii]) + lowTrapBuy :=low[ii] + break + else + lowTrapBuy := low + + + +trapBuy = ta.crossunder(close, lowTrapBuy) + +if(volUltraHigh or volVeryHigh) + trapBuy := false + + +if last_bar_index - bar_index < MaxLabel + if(showTrap and trapBuy) + label.new(bar_index, high, text="", yloc = yloc.abovebar, style=label.style_label_down, textcolor=color.white, size=size.tiny, color=color.rgb(204, 169, 13)) +firstTrapBuy := trapBuy +//plotshape(trapBuy , title="Sell False Break signal", style=shape.labeldown, size=size.small, color=color.rgb(218, 169, 8), location= location.abovebar, text="T", textcolor=color.white) + +////////////////////////////////////////////////////////////////Code Buy + +for ii = 1 to lookbackTRAP by 1 + //Tìm thấy tín hiệu trước đó bỏ qua + // if(firstTrapSell[ii]) + // highTrapSell := high + // break + + //Vol ultra high bị kill + if(showSignalUltra and volUltraHigh[ii]) + highTrapSell :=high[ii] + break + else + highTrapSell := high + + //Vol very high bị kill + if(showSignalVery and volVeryHigh[ii]) + highTrapSell :=high[ii] + break + else + highTrapSell := high + + +trapSell = ta.crossover(close, highTrapSell) + +if(volUltraHigh or volVeryHigh) + trapSell := false + + +if last_bar_index - bar_index < MaxLabel + if(showTrap and trapSell) + label.new(bar_index, low, text="", yloc = yloc.belowbar, style=label.style_label_up, textcolor=color.white, size=size.tiny, color=color.rgb(28, 169, 204)) +firstTrapSell := trapSell +//plotshape(_showTrapEntrytime and showTrap and trapSell , title="Buy False Break signal", style=shape.labelup, size=size.small, color=color.rgb(28, 169, 204), location= location.belowbar, text="T", textcolor=color.white) + +checkForAlert(trapBuy, trapSell)=> + alertMsg = "" + if (trapBuy) + alertMsg += str.format("Canh Sell {0} M{1} !\n", syminfo.tickerid,timeframe.period) + if (trapSell) + alertMsg += str.format("Canh Buy {0} M{1} !\n", syminfo.tickerid,timeframe.period) + alertMsg + +if(alertTrap and showSignalUltra or alertTrap and showSignalVery) + // if(EntryTimePhienA or EntryTimePhienAu or EntryTimePhienMy) + msg = checkForAlert(trapBuy, trapSell) + if str.length(msg) > 0 + alert(msg, alert.freq_once_per_bar_close) +//=============================================================================End Begin Flase Break IB - TRAP==================================================================== diff --git a/Alligator.mq5 b/Alligator.mq5 new file mode 100644 index 0000000..acaa02e --- /dev/null +++ b/Alligator.mq5 @@ -0,0 +1,148 @@ +//+------------------------------------------------------------------+ +//| Alligator.mq5 | +//| Copyright 2009-2020, MetaQuotes Software Corp. | +//| http://www.mql5.com | +//+------------------------------------------------------------------+ +#property copyright "2009-2020, MetaQuotes Software Corp." +#property link "http://www.mql5.com" + +//--- indicator settings +#property indicator_chart_window +#property indicator_buffers 3 +#property indicator_plots 3 +#property indicator_type1 DRAW_LINE +#property indicator_type2 DRAW_LINE +#property indicator_type3 DRAW_LINE +#property indicator_color1 Blue +#property indicator_color2 Red +#property indicator_color3 Lime +#property indicator_width1 1 +#property indicator_width2 1 +#property indicator_width3 1 +#property indicator_label1 "Jaws" +#property indicator_label2 "Teeth" +#property indicator_label3 "Lips" +//--- input parameters +input int InpJawsPeriod=13; // Jaws period +input int InpJawsShift=8; // Jaws shift +input int InpTeethPeriod=8; // Teeth period +input int InpTeethShift=5; // Teeth shift +input int InpLipsPeriod=5; // Lips period +input int InpLipsShift=3; // Lips shift +input ENUM_MA_METHOD InpMAMethod=MODE_SMMA; // Moving average method +input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_MEDIAN; // Applied price +//--- indicator buffers +double ExtJaws[]; +double ExtTeeth[]; +double ExtLips[]; +//--- handles for moving averages +int ExtJawsHandle; +int ExtTeethHandle; +int ExtLipsHandle; +//--- bars minimum for calculation +int ExtBarsMinimum; +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +void OnInit() + { +//--- indicator buffers mapping + SetIndexBuffer(0,ExtJaws,INDICATOR_DATA); + SetIndexBuffer(1,ExtTeeth,INDICATOR_DATA); + SetIndexBuffer(2,ExtLips,INDICATOR_DATA); +//--- set accuracy + IndicatorSetInteger(INDICATOR_DIGITS,_Digits); +//--- sets first bar from what index will be drawn + PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpJawsPeriod-1); + PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,InpTeethPeriod-1); + PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,InpLipsPeriod-1); +//--- line shifts when drawing + PlotIndexSetInteger(0,PLOT_SHIFT,InpJawsShift); + PlotIndexSetInteger(1,PLOT_SHIFT,InpTeethShift); + PlotIndexSetInteger(2,PLOT_SHIFT,InpLipsShift); +//--- name for DataWindow + PlotIndexSetString(0,PLOT_LABEL,"Jaws("+string(InpJawsPeriod)+")"); + PlotIndexSetString(1,PLOT_LABEL,"Teeth("+string(InpTeethPeriod)+")"); + PlotIndexSetString(2,PLOT_LABEL,"Lips("+string(InpLipsPeriod)+")"); +//--- get MA's handles + ExtJawsHandle=iMA(NULL,0,InpJawsPeriod,0,InpMAMethod,InpAppliedPrice); + ExtTeethHandle=iMA(NULL,0,InpTeethPeriod,0,InpMAMethod,InpAppliedPrice); + ExtLipsHandle=iMA(NULL,0,InpLipsPeriod,0,InpMAMethod,InpAppliedPrice); +//--- bars minimum for calculation + ExtBarsMinimum=InpJawsPeriod+InpJawsShift; + if(ExtBarsMinimum<(InpTeethPeriod+InpTeethShift)) + ExtBarsMinimum=InpTeethPeriod+InpTeethShift; + if(ExtBarsMinimum<(InpLipsPeriod+InpLipsPeriod)) + ExtBarsMinimum=InpLipsPeriod+InpLipsPeriod; + } +//+------------------------------------------------------------------+ +//| Alligator OnCalculate function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) + { + if(rates_totalrates_total || prev_calculated<0) + to_copy=rates_total; + else + { + to_copy=rates_total-prev_calculated; + if(prev_calculated>0) + to_copy++; + } +//--- get ma buffers + if(IsStopped()) // checking for stop flag + return(0); + if(CopyBuffer(ExtJawsHandle,0,0,to_copy,ExtJaws)<=0) + { + Print("getting ExtJawsHandle is failed! Error ",GetLastError()); + return(0); + } + if(IsStopped()) // checking for stop flag + return(0); + if(CopyBuffer(ExtTeethHandle,0,0,to_copy,ExtTeeth)<=0) + { + Print("getting ExtTeethHandle is failed! Error ",GetLastError()); + return(0); + } + if(IsStopped()) // checking for stop flag + return(0); + if(CopyBuffer(ExtLipsHandle,0,0,to_copy,ExtLips)<=0) + { + Print("getting ExtLipsHandle is failed! Error ",GetLastError()); + return(0); + } +//--- return value of prev_calculated for next call + return(rates_total); + } +//+------------------------------------------------------------------+ diff --git a/BB_stops.mq5 b/BB_stops.mq5 new file mode 100644 index 0000000..18b81dd Binary files /dev/null and b/BB_stops.mq5 differ diff --git a/BetterVolume 1.5 Alerts.ex5 b/BetterVolume 1.5 Alerts.ex5 new file mode 100644 index 0000000..3891f3d Binary files /dev/null and b/BetterVolume 1.5 Alerts.ex5 differ diff --git a/Bollinger Squeeze Basic.mq5 b/Bollinger Squeeze Basic.mq5 new file mode 100644 index 0000000..15fb6c7 --- /dev/null +++ b/Bollinger Squeeze Basic.mq5 @@ -0,0 +1,215 @@ +//+--------------------------------------------------------------------------+ +//| Bollinger Squeeze Basic.mq5 | +//| Copyright © 2022, EarnForex.com | +//| https://www.earnforex.com/metatrader-indicators/Bollinger-Squeeze-Basic/ | +//+--------------------------------------------------------------------------+ +#property copyright "Copyright © 2022, EarnForex.com" +#property link "https://www.earnforex.com/metatrader-indicators/Bollinger-Squeeze-Basic/" +#property version "1.00" + +#property description "Bollinger Squeeze Basic shows the change of momentum histogram and BB / Keltner channel dots." +#property description "Red dots are shown when Bollinger bands are outside of the Keltner channel." +#property description "Blue dots are shown when Bollinger bands are inside the Keltner channel." + +#property indicator_separate_window +#property indicator_buffers 4 +#property indicator_plots 2 +#property indicator_type1 DRAW_COLOR_HISTOGRAM +#property indicator_color1 clrLimeGreen, clrIndianRed, clrLightGreen, clrLightPink +#property indicator_width1 2 +#property indicator_label1 "Momentum Histo" +#property indicator_type2 DRAW_COLOR_ARROW +#property indicator_width2 1 +#property indicator_color2 clrBlue, clrRed +#property indicator_label2 "BB/Keltner" + +enum enum_candle_to_check +{ + Current, + Previous +}; + +input int MaxBars = 300; +input int BB_Period = 20; // BB Period +input double BB_Deviation = 1.6185; // BB Deviation +input ENUM_MA_METHOD BB_MA_Method = MODE_SMA; +input ENUM_APPLIED_PRICE BB_Price = PRICE_CLOSE; +input int Keltner_Period = 20; // Keltner Period +input double Keltner_Factor = 1.5; // Keltner Factor +input int Momentum_Period = 12; // Momentum Period +input ENUM_APPLIED_PRICE Momentum_Price = PRICE_CLOSE; +input int SqueezeWingDingsCode = 167; +input bool EnableNativeAlerts = false; +input bool EnableEmailAlerts = false; +input bool EnablePushAlerts = false; +input enum_candle_to_check TriggerCandle = Previous; + +// Indicator buffers: +double Histogram[]; +double Histogram_Color[]; +double Arrows[]; +double Arrows_Color[]; + +// Internal intidcator buffers: +double Momentum_Buffer[]; +double ATR_Buffer[]; +double StdDev_Buffer[]; + +// Global variables: +int Momentum_Handle, ATR_Handle, StdDev_Handle; +datetime LastAlertTime = D'01.01.1970'; +int LastAlertDirection = 0; + +//+------------------------------------------------------------------+ +//| Получение таймфрейма в виде строки | +//+------------------------------------------------------------------+ +string GetStringTimeframe(ENUM_TIMEFRAMES timeframe) + {return(StringSubstr(EnumToString(timeframe),7,-1));} + +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +void OnInit() +{ + SetIndexBuffer(0, Histogram, INDICATOR_DATA); + SetIndexBuffer(1, Histogram_Color, INDICATOR_COLOR_INDEX); + SetIndexBuffer(2, Arrows, INDICATOR_DATA); + SetIndexBuffer(3, Arrows_Color, INDICATOR_COLOR_INDEX); + + PlotIndexSetInteger(1, PLOT_ARROW, SqueezeWingDingsCode); // Arrow code. + + ArraySetAsSeries(Histogram, true); + ArraySetAsSeries(Histogram_Color, true); + ArraySetAsSeries(Arrows, true); + ArraySetAsSeries(Arrows_Color, true); + + Momentum_Handle = iMomentum(Symbol(), Period(), Momentum_Period, Momentum_Price); + ATR_Handle = iATR(Symbol(), Period(), Keltner_Period); + StdDev_Handle = iStdDev(Symbol(), Period(), BB_Period, BB_MA_Method, 0, BB_Price); + + ArraySetAsSeries(Momentum_Buffer, true); + ArraySetAsSeries(ATR_Buffer, true); + ArraySetAsSeries(StdDev_Buffer, true); + +//---- инициализации переменной для короткого имени индикатора +//---- initializing a variable for the short name of the indicator + string shortName="["+GetStringTimeframe(_Period)+"] [" + Symbol() + "] Bollinger Squeeze Basic"; + +//--- создание имени для отображения в отдельном подокне и во всплывающей подсказке +//--- creating a name to display in a separate subwindow and in a tooltip + IndicatorSetString(INDICATOR_SHORTNAME,shortName); + +//--- определение точности отображения значений индикатора + IndicatorSetInteger(INDICATOR_DIGITS,_Digits); +} + +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &Time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) +{ + ArraySetAsSeries(Time, true); + + int limit = MaxBars; + if (limit > rates_total) limit = rates_total; + + double d = 0, prev_d = 0; + + if (CopyBuffer(Momentum_Handle, 0, 0, limit, Momentum_Buffer) != limit) return 0; // Data not ready yet. + if (CopyBuffer(ATR_Handle, 0, 0, limit, ATR_Buffer) != limit) return 0; // Data not ready yet. + if (CopyBuffer(StdDev_Handle, 0, 0, limit, StdDev_Buffer) != limit) return 0; // Data not ready yet. + + for (int shift = limit - 1; shift >= 0; shift--) + { + d = Momentum_Buffer[shift] - 100; + + if (d > 0) + { + if (d >= prev_d) + { + Histogram_Color[shift] = 0; + } + else + { + Histogram_Color[shift] = 2; + } + Histogram[shift] = d; + } + else if (d < 0) + { + + if (d <= prev_d) + { + Histogram_Color[shift] = 1; + } + else + { + Histogram_Color[shift] = 3; + } + Histogram[shift] = d; + } + else + { + Histogram[shift] = 0; + Histogram_Color[shift] = 0; + } + prev_d = d; + + double diff = ATR_Buffer[shift] * Keltner_Factor; + double std = StdDev_Buffer[shift]; + double bbs = BB_Deviation * std / diff; + + Arrows[shift] = 0; + if (bbs < 1) + { + Arrows_Color[shift] = 0; + } + else + { + Arrows_Color[shift] = 1; + } + } + + if (((TriggerCandle > 0) && (Time[0] > LastAlertTime)) || (TriggerCandle == 0)) + { + string Text; + // Outside Alert + if ((Arrows_Color[TriggerCandle] == 1) && (LastAlertDirection != 1)) + { + if (LastAlertDirection != 0) // Skip actual alerts if it is the first run after attachment. + { + Text = "BB Squeeze: " + Symbol() + " - " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7) + " - BB Outside Keltner."; + if (EnableNativeAlerts) Alert(Text); + if (EnableEmailAlerts) SendMail("BB Squeeze Alert", Text); + if (EnablePushAlerts) SendNotification(Text); + } + LastAlertTime = Time[0]; + LastAlertDirection = 1; + } + // Inside Alert + if ((Arrows_Color[TriggerCandle] == 0) && (LastAlertDirection != -1)) + { + if (LastAlertDirection != 0) // Skip actual alerts if it is the first run after attachment. + { + Text = "BB Squeeze: " + Symbol() + " - " + StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7) + " - BB Inside Keltner."; + if (EnableNativeAlerts) Alert(Text); + if (EnableEmailAlerts) SendMail("BB Squeeze Alert", Text); + if (EnablePushAlerts) SendNotification(Text); + } + LastAlertTime = Time[0]; + LastAlertDirection = -1; + } + } + + return rates_total; +} +//+------------------------------------------------------------------+ \ No newline at end of file diff --git a/Bollinger_bands_1b.mq5 b/Bollinger_bands_1b.mq5 new file mode 100644 index 0000000..dba073d --- /dev/null +++ b/Bollinger_bands_1b.mq5 @@ -0,0 +1,93 @@ +//+------------------------------------------------------------------+ +//| Bollinger bands %b.mq5 | +//| Copyright 2014, mohsen khashei | +//| mkhashei@gmail.com | +//+------------------------------------------------------------------+ +#property copyright "Copyright 2014, mohsen khashei" +#property link "mkhashei@gmail.com" +#property version "1.10" +#property indicator_separate_window +#property indicator_buffers 4 +#property indicator_plots 1 +//--- plot Label1 +#property indicator_label1 "Bollinger bands %b" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrYellow +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 +#property indicator_level1 0.0 +#property indicator_level2 0.5 +#property indicator_level3 1.0 + +//---- input parameters +input int BBPeriod=20; //Period +input int BBShift=0; // Shift +input double StdDeviation=2.0; //Standard Deviation +input ENUM_APPLIED_PRICE appliedprc=PRICE_CLOSE; //Applied Price +//--- indicator buffers +double UpperBuffer[]; +double LowerBuffer[]; +double MiddleBuffer[]; +double BLGBuffer[]; +int bbhandle; + +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() + { +//--- indicator buffers mapping + SetIndexBuffer(0,BLGBuffer,INDICATOR_DATA); + SetIndexBuffer(1,MiddleBuffer,INDICATOR_CALCULATIONS); + SetIndexBuffer(2,UpperBuffer ,INDICATOR_CALCULATIONS); + SetIndexBuffer(3,LowerBuffer ,INDICATOR_CALCULATIONS); + ArraySetAsSeries(BLGBuffer,true); + ArraySetAsSeries(MiddleBuffer,true); + ArraySetAsSeries(UpperBuffer,true); + ArraySetAsSeries(LowerBuffer,true); + if(Bars(_Symbol,_Period)<60) + { + Alert("We have less than 60 bars for Indicator exited now!!"); + return (-1); + + } + bbhandle=iBands(NULL,0,BBPeriod,BBShift,StdDeviation,appliedprc); + if(bbhandle<0){ + Alert("Can not create handle ",GetLastError(),"!!"); + return (-1); + } + //--- + return(INIT_SUCCEEDED); + } +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) + { +//--- + ArraySetAsSeries(close,true); + if(BarsCalculated(bbhandle)= 0 && CopyBuffer(handle,bufnum,i,1,Buffer) <= 0) + { + retries--; + } + + return Buffer[0]; +} +//+------------------------------------------------------------------+ +//| Triple Exponential Moving Average | +//+------------------------------------------------------------------+ +int limit; +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) + { + + limit = prev_calculated <= 0 ? 0 : prev_calculated-1; + limit = MathMax(limit, rates_total-1-bars); + limit = MathMax(limit, BBPeriod+1); + limit = MathMax(limit, StdDevPeriod+1); + limit = MathMax(limit, InversePeriod+1); + + for(int i=limit;i +#include + +enum ENUM_TRADE_SIGNAL{ + SIGNAL_BUY=1, //BUY + SIGNAL_SELL=-1, //SELL + SIGNAL_NEUTRAL=0 //NEUTRAL +}; + +enum ENUM_CANDLE_TO_CHECK{ + CURRENT_CANDLE=0, //CURRENT CANDLE + CLOSED_CANDLE=1 //PREVIOUS CANDLE +}; + +enum ENUM_ALERT_SIGNAL{ + RSI_BREAK_OUT=0, //RSI BREAKS OUT THE LIMITS + RSI_COMES_IN=1 //RSI RETURNS IN THE LIMITS +}; + +input string Comment1="========================"; //MQLTA RSI With Alert +input string IndicatorName="MQLTA-RSIWA"; //Indicator Short Name + +input string Comment2="========================"; //Indicator Parameters +input int RSIPeriod=14; //RSI Period +input int RSIHighLimit=70; //RSI High Limit +input int RSILowLimit=30; //RSI Low Limit +input ENUM_APPLIED_PRICE RSIAppliedPrice=PRICE_CLOSE; //RSI Applied Price +input ENUM_ALERT_SIGNAL AlertSignal=RSI_COMES_IN; //Alert Signal When +input ENUM_CANDLE_TO_CHECK CandleToCheck=CURRENT_CANDLE; //Candle To Use For Analysis +input int BarsToScan=500; //Number Of Candles To Analyse + +input string Comment_3="===================="; //Notification Options +input bool EnableNotify=false; //Enable Notifications Feature +input bool SendAlert=true; //Send Alert Notification +input bool SendApp=true; //Send Notification to Mobile +input bool SendEmail=true; //Send Notification via Email +input int WaitTimeNotify=5; //Wait time between notifications (Minutes) + +input string Comment_4="===================="; //Drawing Options +input bool EnableDrawArrows=true; //Draw Signal Arrows +input int ArrowBuy=241; //Buy Arrow Code +input int ArrowSell=242; //Sell Arrow Code +input int ArrowSize=3; //Arrow Size (1-5) +input color ArrowBuyColor=clrGreen; //Buy Arrow Color +input color ArrowSellColor=clrRed; //Sell Arrow Color + + +double BufferMain[]; + +int BufferMainHandle; + +double Open[],Close[],High[],Low[]; +datetime Time[]; + +datetime LastNotificationTime; +int Shift=0; + + +int OnInit(void){ + + IndicatorSetString(INDICATOR_SHORTNAME,IndicatorName); + + OnInitInitialization(); + if(!OnInitPreChecksPass()){ + return(INIT_FAILED); + } + + InitialiseHandles(); + InitialiseBuffers(); + + return(INIT_SUCCEEDED); +} + + +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]){ + + bool IsNewCandle=CheckIfNewCandle(); + int i,pos,upTo; + + pos=0; + if(prev_calculated==0 || IsNewCandle) + upTo=BarsToScan-1; + else + upTo=0; + + if(IsStopped()) return(0); + if(CopyBuffer(BufferMainHandle,0,0,upTo+1,BufferMain)<=0){ + Print("Failed to create the Indicator! Error ",GetLastErrorText(GetLastError())," - ",GetLastError()); + return(0); + } + + for(i=pos; i<=upTo && !IsStopped(); i++){ + Open[i]=iOpen(Symbol(),PERIOD_CURRENT,i); + Low[i]=iLow(Symbol(),PERIOD_CURRENT,i); + High[i]=iHigh(Symbol(),PERIOD_CURRENT,i); + Close[i]=iClose(Symbol(),PERIOD_CURRENT,i); + Time[i]=iTime(Symbol(),PERIOD_CURRENT,i); + } + + if(IsNewCandle || prev_calculated==0){ + if(EnableDrawArrows) DrawArrows(); + } + + if(EnableDrawArrows) + DrawArrow(0); + + if(EnableNotify) + NotifyHit(); + + return(rates_total); +} + + +void OnDeinit(const int reason){ + CleanChart(); +} + + +void OnInitInitialization(){ + LastNotificationTime=TimeCurrent(); + Shift=CandleToCheck; +} + + +bool OnInitPreChecksPass(){ + if(RSIPeriod<=0 || RSIHighLimit>100 || RSIHighLimit<0 || RSILowLimit>100 || RSILowLimit<0 || RSILowLimit>RSIHighLimit){ + Print("Wrong input parameter"); + return false; + } + if(Bars(Symbol(),PERIOD_CURRENT)=0;i--){ + if(StringFind(ObjectName(0,i),IndicatorName,0)>=0){ + ObjectDelete(0,ObjectName(0,i)); + } + } +} + + +void InitialiseHandles(){ + BufferMainHandle=iRSI(Symbol(),PERIOD_CURRENT,RSIPeriod,RSIAppliedPrice); + ArrayResize(Open,BarsToScan); + ArrayResize(High,BarsToScan); + ArrayResize(Low,BarsToScan); + ArrayResize(Close,BarsToScan); + ArrayResize(Time,BarsToScan); +} + + +void InitialiseBuffers(){ + IndicatorSetInteger(INDICATOR_DIGITS,_Digits); + ArraySetAsSeries(BufferMain,true); + SetIndexBuffer(0,BufferMain,INDICATOR_DATA); + IndicatorSetDouble(INDICATOR_LEVELVALUE,indicator_level1,(double)RSILowLimit); + IndicatorSetDouble(INDICATOR_LEVELVALUE,indicator_level2,(double)RSIHighLimit); +} + + +datetime NewCandleTime=TimeCurrent(); +bool CheckIfNewCandle(){ + if(NewCandleTime==iTime(Symbol(),0,0)) return false; + else{ + NewCandleTime=iTime(Symbol(),0,0); + return true; + } +} + + +//Check if it is a trade Signla 0 - Neutral, 1 - Buy, -1 - Sell +ENUM_TRADE_SIGNAL IsSignal(int i){ + int j=i+Shift; + if(AlertSignal==RSI_BREAK_OUT){ + if(BufferMain[j+1]RSIHighLimit) return SIGNAL_BUY; + if(BufferMain[j+1]>RSILowLimit && BufferMain[j]RSILowLimit) return SIGNAL_BUY; + if(BufferMain[j+1]>RSIHighLimit && BufferMain[j]BarsToScan) MaxBars=BarsToScan; + for(int i=MaxBars-2;i>=1;i--){ + DrawArrow(i); + } +} + + +void RemoveArrows(){ + int Window=-1; + for(int i=ObjectsTotal(ChartID(),Window,-1)-1;i>=0;i--){ + if(StringFind(ObjectName(0,i),IndicatorName+"-ARWS-",0)>=0){ + ObjectDelete(0,ObjectName(0,i)); + } + } +} + +int SignalWidth=0; + +void DrawArrow(int i){ + RemoveArrowCurr(); + if(!EnableDrawArrows){ + RemoveArrows(); + return; + } + ENUM_TRADE_SIGNAL Signal=IsSignal(i); + if(Signal==SIGNAL_NEUTRAL) return; + datetime ArrowDate=iTime(Symbol(),0,i); + string ArrowName=IndicatorName+"-ARWS-"+IntegerToString(ArrowDate); + double ArrowPrice=0; + ENUM_OBJECT ArrowType=OBJ_ARROW; + color ArrowColor=0; + int ArrowAnchor=0; + string ArrowDesc=""; + if(Signal==SIGNAL_BUY){ + ArrowPrice=Low[i]; + ArrowType=(ENUM_OBJECT)ArrowBuy; + ArrowColor=ArrowBuyColor; + ArrowAnchor=ANCHOR_TOP; + ArrowDesc="BUY"; + } + if(Signal==SIGNAL_SELL){ + ArrowPrice=High[i]; + ArrowType=(ENUM_OBJECT)ArrowSell; + ArrowColor=ArrowSellColor; + ArrowAnchor=ANCHOR_BOTTOM; + ArrowDesc="SELL"; + } + ObjectCreate(0,ArrowName,OBJ_ARROW,0,ArrowDate,ArrowPrice); + ObjectSetInteger(0,ArrowName,OBJPROP_COLOR,ArrowColor); + ObjectSetInteger(0,ArrowName,OBJPROP_SELECTABLE,false); + ObjectSetInteger(0,ArrowName,OBJPROP_HIDDEN,true); + ObjectSetInteger(0,ArrowName,OBJPROP_ANCHOR,ArrowAnchor); + ObjectSetInteger(0,ArrowName,OBJPROP_ARROWCODE,ArrowType); + SignalWidth=ArrowSize; + ObjectSetInteger(0,ArrowName,OBJPROP_WIDTH,SignalWidth); + ObjectSetInteger(0,ArrowName,OBJPROP_STYLE,STYLE_SOLID); + ObjectSetInteger(0,ArrowName,OBJPROP_BGCOLOR,ArrowColor); + ObjectSetString(0,ArrowName,OBJPROP_TEXT,ArrowDesc); + datetime CurrTime=iTime(Symbol(),0,0); + +} + + +void RemoveArrowCurr(){ + datetime ArrowDate=iTime(Symbol(),0,Shift); + string ArrowName=IndicatorName+"-ARWS-"+IntegerToString(ArrowDate); + ObjectDelete(0,ArrowName); +} + diff --git a/MQLTA MT5 RSI With Alert.zip b/MQLTA MT5 RSI With Alert.zip new file mode 100644 index 0000000..b3216cc Binary files /dev/null and b/MQLTA MT5 RSI With Alert.zip differ diff --git a/MT5-MT4-Telegram-API-Bot-master.zip b/MT5-MT4-Telegram-API-Bot-master.zip new file mode 100644 index 0000000..6ae9804 Binary files /dev/null and b/MT5-MT4-Telegram-API-Bot-master.zip differ diff --git a/Moving Average Bands - extended BT.mq5 b/Moving Average Bands - extended BT.mq5 new file mode 100644 index 0000000..89bf9f0 Binary files /dev/null and b/Moving Average Bands - extended BT.mq5 differ diff --git a/OGT Trend Dashboard v1.2.ex5 b/OGT Trend Dashboard v1.2.ex5 new file mode 100644 index 0000000..efa27fb Binary files /dev/null and b/OGT Trend Dashboard v1.2.ex5 differ diff --git a/Symbol Changer.mq5 b/Symbol Changer.mq5 new file mode 100644 index 0000000..631320b --- /dev/null +++ b/Symbol Changer.mq5 @@ -0,0 +1,214 @@ +// More information about this indicator can be found at: +// http://fxcodebase.com/code/viewtopic.php?f=38&t=69358 +// More information about this indicator can be found at: +//http://fxcodebase.com/code/viewtopic.php?f=38&t=69358 + +//+------------------------------------------------------------------+ +//| Copyright © 2020, Gehtsoft USA LLC | +//| http://fxcodebase.com | +//+------------------------------------------------------------------+ +//| Developed by : Mario Jemic | +//| mario.jemic@gmail.com | +//| https://AppliedMachineLearning.systems | +//+------------------------------------------------------------------+ +//| Support our efforts by donating | +//| Paypal : https://goo.gl/9Rj74e | +//+------------------------------------------------------------------+ +//| Patreon : https://goo.gl/GdXWeN | +//| BitCoin : 15VCJTLaz12Amr7adHSBtL9v8XomURo9RF | +//| BitCoin Cash : 1BEtS465S3Su438Kc58h2sqvVvHK9Mijtg | +//| Ethereum : 0x8C110cD61538fb6d7A2B47858F0c0AaBd663068D | +//| LiteCoin : LLU8PSY2vsq7B9kRELLZQcKf5nJQrdeqwD | +//+------------------------------------------------------------------+ + +#property copyright "Copyright © 2020, Gehtsoft USA LLC" +#property link "http://fxcodebase.com" +#property version "1.0" +#property strict + +input string Comment1 = "- Comma Separated Pairs - Ex: EURUSD,EURJPY,GBPUSD - "; +input string Pairs = "EURUSD,EURJPY,USDJPY,GBPUSD"; +input color button_with_trades_color = Green; // Color of button with trades +input ENUM_BASE_CORNER corner = CORNER_RIGHT_UPPER; // Corner +input int x_start = 50; +input int y_start = 20; +int button_width = 50; +int button_height = 20; + +string IndicatorName; +string IndicatorObjPrefix; +string GenerateIndicatorName(const string target) +{ + string name = target; + return name; +} + +string _symbols[]; +void split(string& arr[], string str, string sym) +{ + ArrayResize(arr, 0); + int len = StringLen(str); + for (int i=0; i < len;) + { + int pos = StringFind(str, sym, i); + if (pos == -1) + pos = len; + + string item = StringSubstr(str, i, pos-i); + StringTrimLeft(item); + StringTrimRight(item); + + int size = ArraySize(arr); + ArrayResize(arr, size+1); + arr[size] = item; + + i = pos+1; + } +} + +int OnInit(void) +{ + IndicatorName = GenerateIndicatorName("Symbol Changer"); + IndicatorObjPrefix = "__" + IndicatorName + "__"; + IndicatorSetString(INDICATOR_SHORTNAME, IndicatorName); + IndicatorSetInteger(INDICATOR_DIGITS, Digits()); + + split(_symbols, Pairs, ","); + + DoInit(); + + return INIT_SUCCEEDED; +} + +void DoInit() +{ + guiCreate(); + guiRefresh(); +} + +void OnDeinit(const int reason) +{ + ObjectsDeleteAll(0, IndicatorObjPrefix); +} + +int OnCalculate(const int rates_total, // size of input time series + const int prev_calculated, // number of handled bars at the previous call + const datetime& time[], // Time array + const double& open[], // Open array + const double& high[], // High array + const double& low[], // Low array + const double& close[], // Close array + const long& tick_volume[], // Tick Volume array + const long& volume[], // Real Volume array + const int& spread[] // Spread array +) +{ + guiRefresh(); + + return rates_total; +} + +bool TradesExist(string symbol) +{ + for (int i = PositionsTotal() - 1; i >= 0; i--) + { + if (PositionGetSymbol(i) == symbol) + { + return true; + } + } + return false; +} + +void guiRefresh() +{ + for (int i = 0; i < ArraySize(_symbols); ++i) + { + string item = _symbols[i]; + if (_Symbol == item) + ObjectSetInteger(0, IndicatorObjPrefix + "_BT_" + item, OBJPROP_STATE, true); + else + ObjectSetInteger(0, IndicatorObjPrefix + "_BT_" + item, OBJPROP_STATE, false); + if (TradesExist(item)) + { + ObjectSetInteger(0, IndicatorObjPrefix + "_BT_" + item, OBJPROP_BGCOLOR, button_with_trades_color); + } + else + { + ObjectSetInteger(0, IndicatorObjPrefix + "_BT_" + item, OBJPROP_BGCOLOR, clrLightGray); + } + } +} + +void guiCreate() +{ + for (int i = 0; i < ArraySize(_symbols); ++i) + { + string item = _symbols[i]; + ButtonCreate(IndicatorObjPrefix + "_BT_" + item, x_start + (button_width * i), y_start, button_width, button_height, item); + } +} + +void OnChartEvent(const int id, + const long &lparam, + const double &dparam, + const string &sparam + ) +{ + if (id == CHARTEVENT_OBJECT_CLICK) + { + if (StringFind(sparam,"_BT_",0) != -1) + { + for (int i = 0; i < ArraySize(_symbols); ++i) + { + string item = _symbols[i]; + if (StringFind(sparam, item, 0) != -1) + { + ChartSetSymbolPeriod(0, item, _Period); + return; + } + } + } + } +} + +bool ButtonCreate(const string name = "Button", // button name + const int x=10, // X coordinate + const int y=10, // Y coordinate + const int width=20, // button width + const int height=20, // button height + const string text="", // text + const string tooltip="\n", // tooltip + const int font_size=8, // font size + const string font="Arial", // font + const color clr=clrBlack, // text color + const color back_clr=clrLightGray // background color + ) +{ + ResetLastError(); + if(ObjectFind(0,name)>-1) + return(false); + + if(!ObjectCreate(0,name,OBJ_BUTTON,0,0,0)) + { + Print(__FUNCTION__, + ": failed to create button! Error code = ",GetLastError()); + return(false); + } + ObjectCreate(0,name,OBJ_BUTTON,0,0,0); + ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x); + ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y); + ObjectSetInteger(0,name,OBJPROP_XSIZE,width); + ObjectSetInteger(0,name,OBJPROP_YSIZE,height); + ObjectSetInteger(0,name,OBJPROP_CORNER, corner); + ObjectSetString(0,name,OBJPROP_FONT,font); + ObjectSetInteger(0,name,OBJPROP_COLOR,clr); + ObjectSetString(0,name,OBJPROP_TEXT,text); + ObjectSetInteger(0,name,OBJPROP_FONTSIZE,font_size); + ObjectSetInteger(0,name,OBJPROP_BGCOLOR,back_clr); + ObjectSetInteger(0,name,OBJPROP_BACK,false); + ObjectSetInteger(0,name,OBJPROP_STATE,false); + ObjectSetInteger(0,name,OBJPROP_ZORDER,10); + ObjectSetString(0,name,OBJPROP_TOOLTIP,tooltip); + return(true); +} \ No newline at end of file diff --git a/VP-v6.ex5 b/VP-v6.ex5 new file mode 100644 index 0000000..a2baf77 Binary files /dev/null and b/VP-v6.ex5 differ diff --git a/WPR with Bollinger bands.mq5 b/WPR with Bollinger bands.mq5 new file mode 100644 index 0000000..c6b32f2 Binary files /dev/null and b/WPR with Bollinger bands.mq5 differ diff --git a/Weighted deviation bands.mq5 b/Weighted deviation bands.mq5 new file mode 100644 index 0000000..e8efdbe Binary files /dev/null and b/Weighted deviation bands.mq5 differ diff --git a/ama-smoothed-rsi.ex5 b/ama-smoothed-rsi.ex5 new file mode 100644 index 0000000..860b879 Binary files /dev/null and b/ama-smoothed-rsi.ex5 differ diff --git a/bb_price_on_channel.mq5 b/bb_price_on_channel.mq5 new file mode 100644 index 0000000..95c75a4 --- /dev/null +++ b/bb_price_on_channel.mq5 @@ -0,0 +1,116 @@ +//+------------------------------------------------------------------+ +//| BB_Price_on_channel.mq5 | +//| Copyright 2009, MetaQuotes Software Corp. | +//| http://www.mql5.com | +//+------------------------------------------------------------------+ +#property copyright "2009, MetaQuotes Software Corp." +#property link "http://www.mql5.com" +#property version "1.00" + +#property indicator_separate_window +#property indicator_buffers 8 +#property indicator_plots 3 +//---- plot MA +#property indicator_label1 "Bollinger High" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrRed +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 + +#property indicator_label2 "Open;High;Low;Close" +#property indicator_type2 DRAW_BARS +#property indicator_color2 clrBlue +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +#property indicator_label3 "Bollinger Low" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrRed +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 +#property indicator_level1 50 +#property indicator_level2 -50 + +//--- input parameters +input int period=15; +input double deviation=2; +input ENUM_APPLIED_PRICE price=PRICE_WEIGHTED; + +//--- indicator buffers +double MABuffer[]; +double MABuffer2[]; +double BolingerBuffer[]; +double BolingerBuffer_l[]; +double BarsBuffer1[]; +double BarsBuffer2[]; +double BarsBuffer3[]; +double BarsBuffer4[]; +int ma_handle; +string symbol; +int indx1=100000; +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() + { +//--- indicator buffers mapping + SetIndexBuffer(0,BolingerBuffer,INDICATOR_DATA); + SetIndexBuffer(1,BarsBuffer1,INDICATOR_DATA); + SetIndexBuffer(2,BarsBuffer2,INDICATOR_DATA); + SetIndexBuffer(3,BarsBuffer3,INDICATOR_DATA); + SetIndexBuffer(4,BarsBuffer4,INDICATOR_DATA); + SetIndexBuffer(5,BolingerBuffer_l,INDICATOR_DATA); + IndicatorSetInteger(INDICATOR_DIGITS,0); + + SetIndexBuffer(6,MABuffer,INDICATOR_CALCULATIONS); + SetIndexBuffer(7,MABuffer2,INDICATOR_CALCULATIONS); + + symbol=_Symbol; +//--- set short name + IndicatorSetString(INDICATOR_SHORTNAME,"Bolkinger View ("+symbol+"): "" "); +//--- + ma_handle=iBands(Symbol(),0,period,0,deviation,price); + return(0); + } +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) + { +//--- check if all data calculated + if(BarsCalculated(ma_handle)rates_total || prev_calculated<=0) to_copy=rates_total; + else + { + to_copy=rates_total-prev_calculated; + //--- last value is always copied + to_copy++; + } +//--- try to copy + CopyBuffer(ma_handle,0,0,to_copy,MABuffer); + CopyBuffer(ma_handle,1,0,to_copy,MABuffer2); +//--- calculate + for(int i=0;i +//+-----------------------------------+ +//---- declaration of the CXMA class variables from the SmoothAlgorithms.mqh file +CXMA XMA1; +//+-----------------------------------+ +//| Declaration of enumerations | +//+-----------------------------------+ +enum Applied_price_ // Type of constant + { + PRICE_CLOSE_ = 1, // Close + PRICE_OPEN_, // Open + PRICE_HIGH_, // High + PRICE_LOW_, // Low + PRICE_MEDIAN_, // Median Price (HL/2) + PRICE_TYPICAL_, // Typical Price (HLC/3) + PRICE_WEIGHTED_, // Weighted Close (HLCC/4) + PRICE_SIMPLE, // Simple Price (OC/2) + PRICE_QUARTER_, // Quarted Price (HLOC/4) + PRICE_TRENDFOLLOW0_, // TrendFollow_1 Price + PRICE_TRENDFOLLOW1_ // TrendFollow_2 Price + }; +/*enum Smooth_Method - enumeration is declared in the SmoothAlgorithms.mqh file + { + MODE_SMA_, // SMA + MODE_EMA_, // EMA + MODE_SMMA_, // SMMA + MODE_LWMA_, // LWMA + MODE_JJMA, // JJMA + MODE_JurX, // JurX + MODE_ParMA, // ParMA + MODE_T3, // T3 + MODE_VIDYA, // VIDYA + MODE_AMA, // AMA + }; */ +//+-----------------------------------+ +//| Indicator input parameters | +//+-----------------------------------+ +input Smooth_Method BB_Method=MODE_EMA_; // Histogram smoothing method +input int BB_Period = 20; // Bollinger Bands period +input int BB_Phase= 100; // Bollinger Bands smoothing parameter +input double BB_Deviation=2.0; // Number of deviations +input Applied_price_ AppliedPrice=PRICE_CLOSE_; // Applied price +input double ATR_Period=20; // ATR period +input double ATR_Factor=1.5; // ATR ratio +//+-----------------------------------+ +//---- declaration of the integer variables for the start of data calculation +int min_rates_total,min_rates_xma; +//---- declaration of global variables +int Count[]; +double Xma[]; +//---- declaration of integer variables for the indicators handles +int ATR_Handle,STD_Handle; +//---- declaration of dynamic arrays that +//---- will be used as indicator buffers +double UpHistBuffer[],DnHistBuffer[],UpArrBuffer[],DnArrBuffer[]; +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() + { +//---- initialization of variables of the start of data calculation + min_rates_xma=XMA1.GetStartBars(BB_Method,BB_Period,BB_Phase); + min_rates_total=int(MathMax(min_rates_xma,ATR_Period)); + +//---- getting handle of the iStdDev indicator + STD_Handle=iStdDev(NULL,0,BB_Period,0,MODE_SMA,PRICE_CLOSE); + if(STD_Handle==INVALID_HANDLE) + { + Print(" Failed to get handle of the iStdDev indicator"); + return(1); + } + +//---- getting handle of the ATR indicator + ATR_Handle=iATR(NULL,0,15); + if(ATR_Handle==INVALID_HANDLE) + { + Print(" Failed to get handle of the iATR indicator"); + return(1); + } + +//---- memory distribution for variables' arrays + if(ArrayResize(Count,BB_Period)rates_total || prev_calculated<=0)// checking for the first start of the indicator calculation + limit=rates_total-1; // starting index for calculation of all bars + else limit=rates_total-prev_calculated; // starting index for calculation of new bars + +//---- calculation of the necessary amount of data to be copied + to_copy=limit+1; +//---- copy the newly appeared data into the STD[] and ATR[] arrays + if(CopyBuffer(STD_Handle,0,0,to_copy,STD)<=0) return(RESET); + if(CopyBuffer(ATR_Handle,0,0,to_copy,ATR)<=0) return(RESET); + +//---- indexing elements in arrays as time series + ArraySetAsSeries(STD,true); + ArraySetAsSeries(ATR,true); + ArraySetAsSeries(high,true); + ArraySetAsSeries(low,true); + ArraySetAsSeries(open,true); + ArraySetAsSeries(close,true); + +//---- main indicator calculation loop + for(bar=limit; bar>=0 && !IsStopped(); bar--) + { + price_=PriceSeries(AppliedPrice,bar,open,low,high,close); + Xma[Count[0]]=XMA1.XMASeries(maxbar,prev_calculated,rates_total,BB_Method,BB_Phase,BB_Period,price_,bar,true); + if(bar>maxbar1) + { + Recount_ArrayZeroPos(Count,BB_Period); + continue; + } + + lregress=LinearRegressionValue(BB_Period,bar,open,low,high,close); + + if(lregress<0) + { + UpHistBuffer[bar]=EMPTY_VALUE; + DnHistBuffer[bar]=lregress; + } + else + { + UpHistBuffer[bar]=lregress; + DnHistBuffer[bar]=EMPTY_VALUE; + } + + bbs=BB_Deviation*STD[bar]/(ATR[bar]*ATR_Factor); + + if(bbs<1) + { + DnArrBuffer[bar]=0; + UpArrBuffer[bar]=EMPTY_VALUE; + } + else + { + UpArrBuffer[bar]=0; + DnArrBuffer[bar]=EMPTY_VALUE; + } + + if(bar) Recount_ArrayZeroPos(Count,BB_Period); + } +//---- + return(rates_total); + } +//+------------------------------------------------------------------+ +//| Linear regression calculation | +//+------------------------------------------------------------------+ +double LinearRegressionValue(int Len, + int index, + const double &Open[], + const double &Low[], + const double &High[], + const double &Close[]) + { +//---- + double SumBars,Sum1,Sum2,SumY,Slope,SumSqrBars; + double dxma,Num1,Num2,HH,LL,Intercept,LinearRegValue; + + SumY=0; + Sum1=0; +//---- + SumBars=Len *(Len-1)*0.5; + SumSqrBars=(Len-1)*Len *(2*Len-1)/6; +//---- + for(int x=0; xMax1) numb-=Max2; + CoArr[iii]=numb; + } +//---- + } +//+------------------------------------------------------------------+ diff --git a/bollinger_fibo_bands.mq5 b/bollinger_fibo_bands.mq5 new file mode 100644 index 0000000..8ce4a67 Binary files /dev/null and b/bollinger_fibo_bands.mq5 differ diff --git a/breakout-zones-indicator.ex5 b/breakout-zones-indicator.ex5 new file mode 100644 index 0000000..11d532c Binary files /dev/null and b/breakout-zones-indicator.ex5 differ diff --git a/color MACD (mtf).mq5 b/color MACD (mtf).mq5 new file mode 100644 index 0000000..1b2687b Binary files /dev/null and b/color MACD (mtf).mq5 differ diff --git a/gann signal.ex5 b/gann signal.ex5 new file mode 100644 index 0000000..f6a26bc Binary files /dev/null and b/gann signal.ex5 differ diff --git a/ibbfill2.mq5 b/ibbfill2.mq5 new file mode 100644 index 0000000..c7cc35f --- /dev/null +++ b/ibbfill2.mq5 @@ -0,0 +1,175 @@ +//+------------------------------------------------------------------+ +//| iBBFill.mq5 | +//| Copyright Integer | +//| http://dmffx.com | +//+------------------------------------------------------------------+ +#property copyright "Integer" +#property link "http://dmffx.com" +#property version "1.00" +#property indicator_chart_window +#property indicator_buffers 10 +#property indicator_plots 6 +//--- plot Label1 +#property indicator_label1 "UpTrend" +#property indicator_type1 DRAW_FILLING +#property indicator_color1 C'10,10,70' +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 +//--- plot Label2 +#property indicator_label2 "DnTrend" +#property indicator_type2 DRAW_FILLING +#property indicator_color2 C'70,10,10' +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 +//--- plot Label3 +#property indicator_label3 "Flat" +#property indicator_type3 DRAW_FILLING +#property indicator_color3 C'50,50,50' +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 +//--- plot Label4 +#property indicator_label4 "BB MA" +#property indicator_type4 DRAW_LINE +#property indicator_color4 Yellow +#property indicator_style4 STYLE_SOLID +#property indicator_width4 1 +//--- plot Label5 +#property indicator_label5 "BB Upper" +#property indicator_type5 DRAW_LINE +#property indicator_color5 DodgerBlue +#property indicator_style5 STYLE_SOLID +#property indicator_width5 1 +//--- plot Label6 +#property indicator_label6 "BB Lower" +#property indicator_type6 DRAW_LINE +#property indicator_color6 Red +#property indicator_style6 STYLE_SOLID +#property indicator_width4 1 +//--- input parameters +input int BBPeriod = 20; // BB +input double BBDeviation = 2; // BB +input ENUM_APPLIED_PRICE BBPrice = PRICE_CLOSE; // BB +//--- indicator buffers +double Upper1[]; +double Lower1[]; +double Upper2[]; +double Lower2[]; +double Upper3[]; +double Lower3[]; +double BCBuf[]; +double BUBuf[]; +double BLBuf[]; +double Trend[]; +int BBHand; +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() + { + SetIndexBuffer(0,Upper1,INDICATOR_DATA); + SetIndexBuffer(1,Lower1,INDICATOR_CALCULATIONS); + SetIndexBuffer(2,Upper2,INDICATOR_DATA); + SetIndexBuffer(3,Lower2,INDICATOR_CALCULATIONS); + SetIndexBuffer(4,Upper3,INDICATOR_DATA); + SetIndexBuffer(5,Lower3,INDICATOR_CALCULATIONS); + SetIndexBuffer(6,BCBuf,INDICATOR_DATA); + SetIndexBuffer(7,BUBuf,INDICATOR_DATA); + SetIndexBuffer(8,BLBuf,INDICATOR_DATA); + SetIndexBuffer(9,Trend,INDICATOR_CALCULATIONS); + + BBHand=iBands(NULL,PERIOD_CURRENT,BBPeriod,0,BBDeviation,BBPrice); + + return(0); + } +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) + { + int limit=0,limit1=0; + if(prev_calculated>0) + { + limit=prev_calculated-1; + limit1=limit; + } + else + { + limit=0; + limit1=1; + } + + CopyBuffer(BBHand,0,0,rates_total-limit,BCBuf); + CopyBuffer(BBHand,1,0,rates_total-limit,BUBuf); + CopyBuffer(BBHand,2,0,rates_total-limit,BLBuf); + + for(int i=limit1;iBCBuf[i]) + { + Trend[i]=0; + } + + if(close[i]>BUBuf[i]) + { + Trend[i]=1; + } + if(close[i] +#include +#include +#include + +//--- +input double InpLots = 0.1; // Size of lots for each position +input int InpAllowedRetracementPercent = 50; // Allowed retracement for gaining position (in percent) +input int IntMaxNumberOfRetracement = 2; // Maximum number of allowed retracement before placing a close stop loss. +input int InpMACDOpenLevel = 3; // MACD open level (in pips) +input int InpMACDCloseLevel = 2; // MACD close level (in pips) +input int InpMA20TrendPeriod = 20; // Long MA trend period +input int InpMA6TrendPeriod = 6; // Short MA trend period + +//--- +int ExtTimeOut=10; // time out in seconds between trade operations + +//+------------------------------------------------------------------+ +//| CMacdExpert class | +//+------------------------------------------------------------------+ +class CMacdExpert +{ + protected: + double m_adjusted_point; // point value adjusted for 3 or 5 points + CTrade m_trade; // trading object + CSymbolInfo m_symbol; // symbol info object + CPositionInfo m_position; // trade position object + CAccountInfo m_account; // account info wrapper + + //--- indicators + int m_handle_macd; // MACD indicator handle + int m_handle_ema20; // long moving average indicator handle + int m_handle_ema6; // short moving average indicator handle + + //--- indicator buffers + double m_buff_MACD_main[]; // MACD indicator main buffer + double m_buff_MACD_signal[]; // MACD indicator signal buffer + double m_buff_EMA[]; // EMA indicator buffer + + //--- indicator data for processing + double m_macd_current; + double m_macd_previous; + double m_signal_current; + double m_signal_previous; + double m_ema_current; + double m_ema_previous; + + //--- + double m_macd_open_level; + double m_macd_close_level; + double m_traling_stop; + double m_take_profit; + + public: + CMacdExpert(void); + ~CMacdExpert(void); + bool Init(void); + void Deinit(void); + bool Processing(void); + + protected: + bool InitCheckParameters(const int digits_adjust); + bool InitIndicators(void); + bool LongClosed(void); + bool ShortClosed(void); + bool LongModified(void); + bool ShortModified(void); + bool LongOpened(void); + bool ShortOpened(void); +}; + +//--- global expert +CMacdExpert ExtExpert; + +//+------------------------------------------------------------------+ +//| Constructor | +//+------------------------------------------------------------------+ +CMacdExpert::CMacdExpert(void) : m_adjusted_point(0), + m_handle_macd(INVALID_HANDLE), + m_handle_ema20(INVALID_HANDLE), + m_handle_ema6(INVALID_HANDLE), + m_macd_current(0), + m_macd_previous(0), + m_signal_current(0), + m_signal_previous(0), + m_ema_current(0), + m_ema_previous(0), + m_macd_open_level(0), + m_macd_close_level(0), + m_traling_stop(0), + m_take_profit(0) +{ + ArraySetAsSeries(m_buff_MACD_main, true); + ArraySetAsSeries(m_buff_MACD_signal, true); + ArraySetAsSeries(m_buff_EMA, true); +} + +//+------------------------------------------------------------------+ +//| Destructor | +//+------------------------------------------------------------------+ +CMacdExpert::~CMacdExpert(void) +{ +} + +//+------------------------------------------------------------------+ +//| Initialization and checking for input parameters | +//+------------------------------------------------------------------+ +bool CMacdExpert::Init(void) +{ + //--- initialize common information + m_symbol.Name(Symbol()); // symbol + m_trade.SetExpertMagicNumber(0xcafebabe); // magic + + //--- tuning for 3 or 5 digits + int digits_adjust=1; + if (m_symbol.Digits() == 3 || m_symbol.Digits() == 5) + { + digits_adjust = 10; + } + m_adjusted_point = m_symbol.Point() * digits_adjust; + + //--- set default deviation for trading in adjusted points + m_macd_open_level = InpMACDOpenLevel * m_adjusted_point; + m_macd_close_level= InpMACDCloseLevel * m_adjusted_point; + m_traling_stop = InpTrailingStop * m_adjusted_point; + m_take_profit = InpTakeProfit * m_adjusted_point; + + //--- set default deviation for trading in adjusted points + m_trade.SetDeviationInPoints(3 * digits_adjust); + + if (!InitCheckParameters(digits_adjust)) + { + return(false); + } + if (!InitIndicators()) + { + return(false); + } + + return(true); +} + +//+------------------------------------------------------------------+ +//| Checking for input parameters | +//+------------------------------------------------------------------+ +bool CMacdExpert::InitCheckParameters(const int digits_adjust) +{ + //--- initial data checks + if (InpTakeProfit * digits_adjust < m_symbol.StopsLevel()) + { + printf("Take Profit must be greater than %d", m_symbol.StopsLevel()); + return(false); + } + if (InpTrailingStop * digits_adjust < m_symbol.StopsLevel()) + { + printf("Trailing Stop must be greater than %d", m_symbol.StopsLevel()); + return(false); + } + + //--- check for right lots amount + if (InpLots < m_symbol.LotsMin() || InpLots > m_symbol.LotsMax()) + { + printf("Lots amount must be in the range from %f to %f", m_symbol.LotsMin(), m_symbol.LotsMax()); + return(false); + } + if (MathAbs(InpLots / m_symbol.LotsStep() - MathRound(InpLots / m_symbol.LotsStep())) > 1.0E - 10) + { + printf("Lots amount is not corresponding with lot step %f", m_symbol.LotsStep()); + return(false); + } + + //--- warning + if (InpTakeProfit <= InpTrailingStop) + { + printf("Warning: Trailing Stop must be less than Take Profit"); + } + + return(true); +} + +//+------------------------------------------------------------------+ +//| Initialization of the indicators | +//+------------------------------------------------------------------+ +bool CMacdExpert::InitIndicators(void) +{ + //--- create MACD indicator + if (m_handle_macd == INVALID_HANDLE) + { + if ((m_handle_macd = iMACD(NULL, 0, 12, 26, 9, PRICE_CLOSE)) == INVALID_HANDLE) + { + printf("Error creating MACD indicator"); + return(false); + } + } + + //--- create EMA 20 indicator and add it to collection + if (m_handle_ema20 == INVALID_HANDLE) + { + if ((m_handle_ema20 = iMA(NULL, 0, InpMA20TrendPeriod, 0, MODE_EMA, PRICE_CLOSE)) == INVALID_HANDLE) + { + printf("Error creating EMA indicator"); + return(false); + } + } + + //--- create EMA 6 indicator and add it to collection + if (m_handle_ema6== INVALID_HANDLE) + { + if ((m_handle_ema6 = iMA(NULL, 0, InpMA6TrendPeriod, 0, MODE_EMA, PRICE_CLOSE)) == INVALID_HANDLE) + { + printf("Error creating EMA indicator"); + return(false); + } + } + + return(true); +} + +//+------------------------------------------------------------------+ +//| Check for long position closing | +//+------------------------------------------------------------------+ +bool CMacdExpert::LongClosed(void) +{ + bool res = false; + + //--- should it be closed? + if (m_macd_current > 0) + { + if ((m_macd_current < m_signal_current) && (m_macd_previous > m_signal_previous)) + { + if (m_macd_current > m_macd_close_level) + { + //--- close position + if (m_trade.PositionClose(Symbol())) + { + printf("Long position by %s to be closed",Symbol()); + } + else + { + printf("Error closing position by %s : '%s'", Symbol(), m_trade.ResultComment()); + } + //--- processed and cannot be modified + res = true; + } + } + } + + return(res); +} + +//+------------------------------------------------------------------+ +//| Check for short position closing | +//+------------------------------------------------------------------+ +bool CMacdExpert::ShortClosed(void) +{ + bool res=false; + + //--- should it be closed? + if (m_macd_current < 0) + { + if ((m_macd_current > m_signal_current) && (m_macd_previous < m_signal_previous)) + { + if (MathAbs(m_macd_current) > m_macd_close_level) + { + //--- close position + if (m_trade.PositionClose(Symbol())) + { + printf("Short position by %s to be closed",Symbol()); + } + else + { + printf("Error closing position by %s : '%s'", Symbol(), m_trade.ResultComment()); + } + //--- processed and cannot be modified + res = true; + } + } + } + + return(res); +} + +//+------------------------------------------------------------------+ +//| Check for long position modifying | +//+------------------------------------------------------------------+ +bool CMacdExpert::LongModified(void) +{ + bool res = false; + + //--- check for trailing stop + if (InpTrailingStop > 0) + { + if ((m_symbol.Bid() - m_position.PriceOpen()) > (m_adjusted_point * InpTrailingStop)) + { + double sl = NormalizeDouble(m_symbol.Bid() - m_traling_stop, m_symbol.Digits()); + double tp = m_position.TakeProfit(); + + if ((m_position.StopLoss() < sl) || (m_position.StopLoss() == 0.0)) + { + //--- modify position + if (m_trade.PositionModify(Symbol(), sl, tp)) + { + printf("Long position by %s to be modified",Symbol()); + } + else + { + printf("Error modifying position by %s : '%s'", Symbol(), m_trade.ResultComment()); + printf("Modify parameters : SL=%f,TP=%f", sl, tp); + } + //--- modified and must exit from expert + res = true; + } + } + } + + return(res); +} + +//+------------------------------------------------------------------+ +//| Check for short position modifying | +//+------------------------------------------------------------------+ +bool CMacdExpert::ShortModified(void) +{ + bool res = false; + + //--- check for trailing stop + if (InpTrailingStop > 0) + { + if ((m_position.PriceOpen() - m_symbol.Ask()) > (m_adjusted_point * InpTrailingStop)) + { + double sl = NormalizeDouble(m_symbol.Ask() + m_traling_stop, m_symbol.Digits()); + double tp = m_position.TakeProfit(); + + if ((m_position.StopLoss() > sl) || (m_position.StopLoss() == 0.0)) + { + //--- modify position + if (m_trade.PositionModify(Symbol(), sl, tp)) + { + printf("Short position by %s to be modified",Symbol()); + } + else + { + printf("Error modifying position by %s : '%s'",Symbol(), m_trade.ResultComment()); + printf("Modify parameters : SL=%f,TP=%f", sl, tp); + } + //--- modified and must exit from expert + res=true; + } + } + } + //--- result + return(res); +} +//+------------------------------------------------------------------+ +//| Check for long position opening | +//+------------------------------------------------------------------+ +bool CMacdExpert::LongOpened(void) +{ + bool res = false; + + //--- check for long position (BUY) possibility + if (m_macd_current < 0) + { + if (m_macd_current > m_signal_current && m_macd_previous m_macd_open_level) && (m_ema_current > m_ema_previous)) + { + double price=m_symbol.Ask(); + double tp =m_symbol.Bid() + m_take_profit; + + //--- check for free money + if (m_account.FreeMarginCheck(Symbol(), ORDER_TYPE_BUY, InpLots, price) < 0.0) + { + printf("We have no money. Free Margin = %f",m_account.FreeMargin()); + } + else + { + //--- open position + if (m_trade.PositionOpen(Symbol(), ORDER_TYPE_BUY, InpLots, price, 0.0, tp)) + printf("Position by %s to be opened", Symbol()); + else + { + printf("Error opening BUY position by %s : '%s'", Symbol(), m_trade.ResultComment()); + printf("Open parameters : price=%f,TP=%f", price, tp); + } + } + //--- in any case we must exit from expert + res = true; + } + } + } + + return(res); +} + +//+------------------------------------------------------------------+ +//| Check for short position opening | +//+------------------------------------------------------------------+ +bool CMacdExpert::ShortOpened(void) +{ + bool res = false; + + //--- check for short position (SELL) possibility + if (m_macd_current > 0) + { + if (m_macd_current < m_signal_current && m_macd_previous > m_signal_previous) + { + if (m_macd_current > (m_macd_open_level) && m_ema_current < m_ema_previous) + { + double price = m_symbol.Bid(); + double tp = m_symbol.Ask() - m_take_profit; + + //--- check for free money + if (m_account.FreeMarginCheck(Symbol(), ORDER_TYPE_SELL, InpLots, price) < 0.0) + { + printf("We have no money. Free Margin = %f",m_account.FreeMargin()); + } + else + { + //--- open position + if (m_trade.PositionOpen(Symbol(), ORDER_TYPE_SELL, InpLots, price, 0.0, tp)) + { + printf("Position by %s to be opened",Symbol()); + } + else + { + printf("Error opening SELL position by %s : '%s'", Symbol(), m_trade.ResultComment()); + printf("Open parameters : price=%f,TP=%f", price, tp); + } + } + //--- in any case we must exit from expert + res = true; + } + } + } + + //--- result + return(res); +} + +//+------------------------------------------------------------------+ +//| main function returns true if any position processed | +//+------------------------------------------------------------------+ +bool CMacdExpert::Processing(void) +{ + //--- refresh rates + if (!m_symbol.RefreshRates()) + { + return(false); + } + + //--- refresh indicators + if (BarsCalculated(m_handle_macd) < 2 || BarsCalculated(m_handle_ema20) < 2 || BarsCalculated(m_handle_ema6) < 2) + { + return(false); + } + + if (CopyBuffer(m_handle_macd, 0, 0, 2, m_buff_MACD_main) != 2 || + CopyBuffer(m_handle_macd, 1, 0, 2, m_buff_MACD_signal)!= 2 || + CopyBuffer(m_handle_ema6, 0, 0, 2, m_buff_EMA) != 2 || + CopyBuffer(m_handle_ema20, 0, 0, 2, m_buff_EMA) != 2) + { + return(false); + } + + // m_indicators.Refresh(); + //--- to simplify the coding and speed up access + //--- data are put into internal variables + m_macd_current = m_buff_MACD_main[0]; + m_macd_previous = m_buff_MACD_main[1]; + m_signal_current = m_buff_MACD_signal[0]; + m_signal_previous= m_buff_MACD_signal[1]; + m_ema_current = m_buff_EMA[0]; + m_ema_previous = m_buff_EMA[1]; + + //--- it is important to enter the market correctly, + //--- but it is more important to exit it correctly... + //--- first check if position exists - try to select it + if (m_position.Select(Symbol())) + { + if (m_position.PositionType() == POSITION_TYPE_BUY) + { + //--- try to close or modify long position + if (LongClosed()) + { + return(true); + } + if (LongModified()) + { + return(true); + } + } + else + { + //--- try to close or modify short position + if (ShortClosed()) + { + return(true); + } + if (ShortModified()) + { + return(true); + } + } + } + //--- no opened position identified + else + { + //--- check for long position (BUY) possibility + if (LongOpened()) + { + return(true); + } + //--- check for short position (SELL) possibility + if (ShortOpened()) + { + return(true); + } + } + + //--- exit without position processing + return(false); +} +//+------------------------------------------------------------------+ +//| Expert initialization function | +//+------------------------------------------------------------------+ +int OnInit(void) +{ + //--- create all necessary objects + if (!ExtExpert.Init()) + { + return(INIT_FAILED); + } + + return(INIT_SUCCEEDED); +} + +//+------------------------------------------------------------------+ +//| Expert new tick handling function | +//+------------------------------------------------------------------+ +void OnTick(void) +{ + static datetime limit_time = 0; // last trade processing time + timeout + + //--- don't process if timeout + if (TimeCurrent() >= limit_time) + { + //--- check for data + if (Bars(Symbol(), Period()) > 2 * InpMA20TrendPeriod) + { + //--- change limit time by timeout in seconds if processed + if (ExtExpert.Processing()) + { + limit_time = TimeCurrent() + ExtTimeOut; + } + } + } +} +//+------------------------------------------------------------------+ \ No newline at end of file diff --git a/macd_anytimeframe.mq5 b/macd_anytimeframe.mq5 new file mode 100644 index 0000000..666c02d --- /dev/null +++ b/macd_anytimeframe.mq5 @@ -0,0 +1,122 @@ +//+------------------------------------------------------------------+ +//| MACD_AnyTimeFrame.mq5 | +//| Copyright 2010, Slacktrader | +//+------------------------------------------------------------------+ +#property copyright "Slacktrader" +#property description "Moving Average Convergence/Divergence - Any higher timeframe" +//--- indicator settings +#property indicator_separate_window +#property indicator_buffers 2 +#property indicator_plots 2 +#property indicator_type1 DRAW_HISTOGRAM +#property indicator_type2 DRAW_LINE +#property indicator_color1 Silver +#property indicator_color2 Red +#property indicator_width1 2 +#property indicator_width2 1 +#property indicator_label1 "MACD" +#property indicator_label2 "Signal" +//--- input parameters +input ENUM_TIMEFRAMES ANY_TIMEFRAME = PERIOD_H1; //Timeframe of MACD which we want to see instead of current Period + //It has to be a higher timeframe as currently displayed +input int InpFastEMA=12; // Fast EMA period +input int InpSlowEMA=26; // Slow EMA period +input int InpSignalSMA=9; // Signal SMA period +input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price +//--- indicator buffers +double ExtMacdBuffer[]; +double ExtSignalBuffer[]; +double ExtMacdBuffer2pom[]; +double ExtSignalBuffer2pom[]; +//--- MACD Handle +int MacdHandle; +//--- variable to hold ratio between current chart timeframe and MACD timeframe +int PeriodRatio; +//+------------------------------------------------------------------+ +//| PeriodStr | +//+------------------------------------------------------------------+ +string PeriodStr(int val) + { + int i; +//--- arrays to convert ENUM_TIMEFRAMES to string + static string _p_str[]= + { + "M1","M2","M3","M4","M5","M6","M10","M12","M15","M20","M30", + "H1","H2","H3","H4","H6","H12","D1","W1","MN","UNKNOWN" + }; + static int _p_int[]={1,2,3,4,5,6,10,12,15,20,30,0x4001,0x4002,0x4003,0x4004,0x4006,0x400c,0x4018,0x8001,0xc001}; +//--- checking + if(val<0) return("ERROR"); +//--- + if(val==(int)PERIOD_CURRENT) val=ChartPeriod(); + for(i=0;i<20;i++) + if(val==_p_int[i]) + { + break; + } +//--- + return(_p_str[i]); + } +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() + { +//--- indicator buffers mapping + SetIndexBuffer(0,ExtMacdBuffer,INDICATOR_DATA); + SetIndexBuffer(1,ExtSignalBuffer,INDICATOR_DATA); + + MacdHandle=iMACD(NULL,ANY_TIMEFRAME,InpFastEMA,InpSlowEMA,InpSignalSMA,InpAppliedPrice); + + PeriodRatio=PeriodSeconds(ANY_TIMEFRAME)/PeriodSeconds(); + IndicatorSetString(INDICATOR_SHORTNAME,"MACD - Any Timeframe - "+PeriodStr(ANY_TIMEFRAME)); + + Comment(""); + + if(PeriodRatio<1) + { + Comment("Variable ANY_TIMEFRAME has to be a Timeframe equal or higher then current chart!","Please coose right timeframe!"); + return(-1); + } + + return(0); +//--- initialization done + } +//+------------------------------------------------------------------+ +//| Moving Averages Convergence/Divergence | +//+------------------------------------------------------------------+ +int OnCalculate (const int rates_total, // size of the price[] array + const int prev_calculated, // bars handled on a previous call + const int begin, // where the significant data start from + const double& price[]) // array to calculate + { +//--- check if all data calculated + if(BarsCalculated(MacdHandle)rates_total || prev_calculated<=0) to_copy=rates_total; + else + { + to_copy=rates_total-prev_calculated; + //--- last value is always copied + to_copy++; + } + + CopyBuffer(MacdHandle,0,0,to_copy/PeriodRatio,ExtMacdBuffer2pom); + CopyBuffer(MacdHandle,1,0,to_copy/PeriodRatio,ExtSignalBuffer2pom); + + ArrayResize(ExtMacdBuffer,ArraySize(ExtMacdBuffer2pom)*PeriodRatio); + + for(int i=0; iprev_calculated || bIsFirstRun) + { + ArrayResize(nPriceArr,rates_total); + ArrayResize(nTotalTPV,rates_total); + ArrayResize(nTotalVol,rates_total); + + if(Enable_Daily) {nIdx = nIdxDaily; nSumDailyTPV = 0; nSumDailyVol = 0;} + if(Enable_Weekly) {nIdx = nIdxWeekly; nSumWeeklyTPV = 0; nSumWeeklyVol = 0;} + if(Enable_Monthly) {nIdx = nIdxMonthly; nSumMonthlyTPV = 0; nSumMonthlyVol = 0;} + + for(; nIdx=nIdxDaily)) + { + nSumDailyTPV += nTotalTPV[nIdx]; + nSumDailyVol += nTotalVol[nIdx]; + + if(nSumDailyVol) + VWAP_Buffer_Daily[nIdx]=(nSumDailyTPV/nSumDailyVol); + + if((sDailyStr!="VWAP Daily: "+(string)NormalizeDouble(VWAP_Buffer_Daily[nIdx],_Digits)) && Show_Daily_Value) + { + sDailyStr="VWAP Daily: "+(string)NormalizeDouble(VWAP_Buffer_Daily[nIdx],_Digits); + ObjectSetString(0,"VWAP_Daily",OBJPROP_TEXT,sDailyStr); + } + } + + if(Enable_Weekly && (nIdx>=nIdxWeekly)) + { + nSumWeeklyTPV += nTotalTPV[nIdx]; + nSumWeeklyVol += nTotalVol[nIdx]; + + if(nSumWeeklyVol) + VWAP_Buffer_Weekly[nIdx]=(nSumWeeklyTPV/nSumWeeklyVol); + + if((sWeeklyStr!="VWAP Weekly: "+(string)NormalizeDouble(VWAP_Buffer_Weekly[nIdx],_Digits)) && Show_Weekly_Value) + { + sWeeklyStr="VWAP Weekly: "+(string)NormalizeDouble(VWAP_Buffer_Weekly[nIdx],_Digits); + ObjectSetString(0,"VWAP_Weekly",OBJPROP_TEXT,sWeeklyStr); + } + } + + if(Enable_Monthly && (nIdx>=nIdxMonthly)) + { + nSumMonthlyTPV += nTotalTPV[nIdx]; + nSumMonthlyVol += nTotalVol[nIdx]; + + if(nSumMonthlyVol) + VWAP_Buffer_Monthly[nIdx]=(nSumMonthlyTPV/nSumMonthlyVol); + + if((sMonthlyStr!="VWAP Monthly: "+(string)NormalizeDouble(VWAP_Buffer_Monthly[nIdx],_Digits)) && Show_Monthly_Value) + { + sMonthlyStr="VWAP Monthly: "+(string)NormalizeDouble(VWAP_Buffer_Monthly[nIdx],_Digits); + ObjectSetString(0,"VWAP_Monthly",OBJPROP_TEXT,sMonthlyStr); + } + } + + dtLastDay=CreateDateTime(DAILY,time[nIdx]); + dtLastWeek=CreateDateTime(WEEKLY,time[nIdx]); + dtLastMonth=CreateDateTime(MONTHLY,time[nIdx]); + } + + if(Enable_Level_01) + { + int nStartPos=(prev_calculated>VWAP_Level_01_Period) ?(prev_calculated-VWAP_Level_01_Period) : VWAP_Level_01_Period; + for(nIdx=nStartPos; nIdxVWAP_Level_02_Period) ?(prev_calculated-VWAP_Level_02_Period) : VWAP_Level_02_Period; + for(nIdx=nStartPos; nIdxVWAP_Level_03_Period) ?(prev_calculated-VWAP_Level_03_Period) : VWAP_Level_03_Period; + for(nIdx=nStartPos; nIdxVWAP_Level_04_Period) ?(prev_calculated-VWAP_Level_04_Period) : VWAP_Level_04_Period; + for(nIdx=nStartPos; nIdxVWAP_Level_05_Period) ?(prev_calculated-VWAP_Level_05_Period) : VWAP_Level_05_Period; + for(nIdx=nStartPos; nIdx