Indicator Collection

Indicator Collection
This commit is contained in:
Coding for Dummies
2024-08-27 23:35:50 +07:00
parent 9e0d2e94d8
commit 9003b29674
41 changed files with 3253 additions and 0 deletions
+199
View File
@@ -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====================================================================
+148
View File
@@ -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_total<ExtBarsMinimum)
return(0);
//--- not all data may be calculated
int calculated=BarsCalculated(ExtJawsHandle);
if(calculated<rates_total)
{
Print("Not all data of ExtJawsHandle is calculated (",calculated," bars). Error ",GetLastError());
return(0);
}
calculated=BarsCalculated(ExtTeethHandle);
if(calculated<rates_total)
{
Print("Not all data of ExtTeethHandle is calculated (",calculated," bars). Error ",GetLastError());
return(0);
}
calculated=BarsCalculated(ExtLipsHandle);
if(calculated<rates_total)
{
Print("Not all data of ExtLipsHandle is calculated (",calculated," bars). Error ",GetLastError());
return(0);
}
//--- we can copy not all data
int to_copy;
if(prev_calculated>rates_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);
}
//+------------------------------------------------------------------+
BIN
View File
Binary file not shown.
Binary file not shown.
+215
View File
@@ -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;
}
//+------------------------------------------------------------------+
+93
View File
@@ -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)<rates_total) return(0);
if(CopyBuffer(bbhandle,0,0,rates_total,MiddleBuffer)<=0) return (0);
if(CopyBuffer(bbhandle,1,0,rates_total,UpperBuffer)<=0) return (0);
if(CopyBuffer(bbhandle,2,0,rates_total,LowerBuffer)<=0) return (0);
int pos=prev_calculated-1;
if(pos<0) pos=0;
for(int i=pos; i<rates_total-(BBPeriod+BBShift+1); i++)
{
BLGBuffer[i]=(close[i]-LowerBuffer[i])/(UpperBuffer[i]-LowerBuffer[i]);
}
return(rates_total);
}
//+------------------------------------------------------------------+
BIN
View File
Binary file not shown.
+143
View File
@@ -0,0 +1,143 @@
//+------------------------------------------------------------------+
//| PEMA.mq5 |
//+------------------------------------------------------------------+
#property copyright "2022 IonOne"
#property link "forex-station.com"
#property version "1.00"
#property description "Inverse BB"
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_width1 2
#property indicator_label1 "Main"
#property indicator_type2 DRAW_LINE
#property indicator_color2 Yellow
#property indicator_width2 2
#property indicator_label2 "Top"
#property indicator_type3 DRAW_LINE
#property indicator_color3 Orange
#property indicator_width3 2
#property indicator_label3 "Bot"
input int bars = 10000;
input int BBPeriod = 200;
input ENUM_MA_METHOD BBMAMode = MODE_SMA;
input ENUM_APPLIED_PRICE BBPrice = PRICE_CLOSE;
input int StdDevPeriod = 200;
input ENUM_MA_METHOD StdDevMAMode = MODE_SMA;
input ENUM_APPLIED_PRICE StdDevPrice = PRICE_CLOSE;
input double StdDevMul = 1.0;
input int InversePeriod = 200;
double BBMain[];
double BBTop[];
double BBBot[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int HandleMA;
int HandleStdDev;
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,BBMain,INDICATOR_DATA);
SetIndexBuffer(1,BBTop,INDICATOR_DATA);
SetIndexBuffer(2,BBBot,INDICATOR_DATA);
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,2);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrRed);
PlotIndexSetInteger(0,PLOT_LINE_STYLE,STYLE_SOLID);
PlotIndexSetInteger(1,PLOT_LINE_WIDTH,2);
PlotIndexSetInteger(1,PLOT_LINE_COLOR,clrYellow);
PlotIndexSetInteger(1,PLOT_LINE_STYLE,STYLE_SOLID);
PlotIndexSetInteger(2,PLOT_LINE_WIDTH,2);
PlotIndexSetInteger(2,PLOT_LINE_COLOR,clrOrange);
PlotIndexSetInteger(2,PLOT_LINE_STYLE,STYLE_SOLID);
IndicatorSetString(INDICATOR_SHORTNAME,"Inverse BB");
HandleMA = iMA(NULL,0,BBPeriod,0,BBMAMode,BBPrice);
HandleStdDev = iStdDev(NULL,0,StdDevPeriod,0,StdDevMAMode,StdDevPrice);
//--- initialization done
}
double GetIndi(int i, int bufnum, int handle)
{
double Buffer[1];
Buffer[0] = 0;
int retries = 5;
while (retries >= 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<rates_total && !IsStopped();i++)
{
static datetime tim;
if (tim != iTime(NULL,0,rates_total-1-i))
{
int shift = rates_total-1-i+1;
double ma0 = GetIndi(shift,0,HandleMA);
double stdDev0 = GetIndi(shift,0,HandleStdDev);
double ma = 0;
for (int j = 0; j < InversePeriod; j++)
{
double stdDev = GetIndi(shift+j,0,HandleStdDev);
ma += stdDev;
}
ma /= double(InversePeriod);
BBMain[i-1] = ma0;
BBTop[i-1] = BBMain[i-1] + StdDevMul * (ma - (stdDev0 - ma));
BBBot[i-1] = BBMain[i-1] - StdDevMul * (ma + (ma - stdDev0));
BBMain[i] = EMPTY_VALUE;
BBTop[i] = EMPTY_VALUE;
BBBot[i] = EMPTY_VALUE;
}
}
return(rates_total);
}
//+------------------------------------------------------------------+
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+332
View File
@@ -0,0 +1,332 @@
#property link "https://www.earnforex.com/metatrader-indicators/moving-average-crossover-alert/"
#property version "1.02"
#property strict
#property copyright "EarnForex.com - 2020-2021"
#property description "The RSI Indicator With Alert"
#property description " "
#property description "WARNING : You use this software at your own risk."
#property description "The creator of these plugins cannot be held responsible for damage or loss."
#property description " "
#property description "Find More on EarnForex.com"
#property icon "\\Files\\EF-Icon-64x64px.ico"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_color1 Blue
#property indicator_type1 DRAW_LINE
#property indicator_width1 1
#property indicator_label1 "RSI"
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_level1 30
#property indicator_level2 70
#include <MQLTA ErrorHandling.mqh>
#include <MQLTA Utils.mqh>
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)<RSIPeriod){
Print("Not Enough Historical Candles");
return false;
}
return true;
}
void CleanChart(){
int Window=0;
for(int i=ObjectsTotal(ChartID(),Window,-1)-1;i>=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 && BufferMain[j]>RSIHighLimit) return SIGNAL_BUY;
if(BufferMain[j+1]>RSILowLimit && BufferMain[j]<RSILowLimit) return SIGNAL_SELL;
}
if(AlertSignal==RSI_COMES_IN){
if(BufferMain[j+1]<RSILowLimit && BufferMain[j]>RSILowLimit) return SIGNAL_BUY;
if(BufferMain[j+1]>RSIHighLimit && BufferMain[j]<RSIHighLimit) return SIGNAL_SELL;
}
return SIGNAL_NEUTRAL;
}
datetime LastNotification=TimeCurrent()-WaitTimeNotify*60;
void NotifyHit(){
if(!EnableNotify || TimeCurrent()<(LastNotification+WaitTimeNotify*60)) return;
if(!SendAlert && !SendApp && !SendEmail) return;
if(Time[0]==LastNotificationTime) return;
ENUM_TRADE_SIGNAL Signal=IsSignal(0);
if(Signal==SIGNAL_NEUTRAL) return;
string EmailSubject=IndicatorName+" "+Symbol()+" Notification ";
string EmailBody="\r\n"+AccountCompany()+" - "+AccountName()+" - "+IntegerToString(AccountNumber())+"\r\n\r\n"+IndicatorName+" Notification for "+Symbol()+"\r\n\r\n";
string AlertText=IndicatorName+" - "+Symbol()+" Notification\r\n";
string AppText=AccountCompany()+" - "+AccountName()+" - "+IntegerToString(AccountNumber())+" - "+IndicatorName+" - "+Symbol()+" - ";
string Text="";
if(Signal!=SIGNAL_NEUTRAL){
Text+="The RSI indicator triggered a signal";
}
EmailBody+=Text+"\r\n\r\n";
AlertText+=Text+"\r\n";
AppText+=Text+"";
if(SendAlert) Alert(AlertText);
if(SendEmail){
if(!SendMail(EmailSubject,EmailBody)) Print("Error sending email "+IntegerToString(GetLastError()));
}
if(SendApp){
if(!SendNotification(AppText)) Print("Error sending notification "+IntegerToString(GetLastError()));
}
LastNotification=TimeCurrent();
Print(IndicatorName+"-"+Symbol()+" last notification sent "+TimeToString(LastNotification));
}
void DrawArrows(){
RemoveArrows();
if(!EnableDrawArrows || BarsToScan==0) return;
int MaxBars=Bars(Symbol(),PERIOD_CURRENT);
if(MaxBars>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);
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+214
View File
@@ -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);
}
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+116
View File
@@ -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) return(0);
//--- we can copy not all data
int to_copy;
if(prev_calculated>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<rates_total && !IsStopped();i++)
{
BolingerBuffer[i]=(MABuffer2[i]-MABuffer[i])*indx1;
BolingerBuffer_l[i]=-BolingerBuffer[i];
BarsBuffer1[i]=(open[i]-MABuffer[i])*indx1;
BarsBuffer2[i]=(high[i]-MABuffer[i])*indx1;
BarsBuffer3[i]=(low[i]-MABuffer[i])*indx1;
BarsBuffer4[i]=(close[i]-MABuffer[i])*indx1;
}
return(rates_total);
}
//+------------------------------------------------------------------+
+365
View File
@@ -0,0 +1,365 @@
//+------------------------------------------------------------------+
//| BBSqueeze.mq5 |
//| Copyright © 2005, Nick Bilak |
//| beluck[AT]gmail.com |
//+------------------------------------------------------------------+
//| Place the SmoothAlgorithms.mqh file |
//| to the terminal_data_folder\MQL5\Include |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, Nick Bilak"
#property link "http://metatrader.50webs.com/"
//---- indicator version
#property version "1.00"
//---- drawing the indicator in a separate window
#property indicator_separate_window
//---- number of indicator buffers 4
#property indicator_buffers 4
//---- 4 plots are used
#property indicator_plots 4
//+-----------------------------------+
//| Declaration of constants |
//+-----------------------------------+
#define RESET 0 // the constant for getting the command for the indicator recalculation back to the terminal
//+-----------------------------------+
//| Indicator drawing parameters |
//+-----------------------------------+
//---- drawing the indicator as a histogram
#property indicator_type1 DRAW_HISTOGRAM
//---- teal color is used
#property indicator_color1 Teal
//---- indicator line is a solid one
#property indicator_style1 STYLE_SOLID
//---- indicator line width is equal to 2
#property indicator_width1 2
//---- displaying the indicator label
#property indicator_label1 "Uptrend"
//---- drawing the indicator as a histogram
#property indicator_type2 DRAW_HISTOGRAM
//---- magenta color is used
#property indicator_color2 Magenta
//---- indicator line is a solid one
#property indicator_style2 STYLE_SOLID
//---- indicator line width is equal to 2
#property indicator_width2 2
//---- displaying the indicator label
#property indicator_label2 "Downtrend"
//+-----------------------------------+
//| Indicator drawing parameters |
//+-----------------------------------+
//---- drawing the indicator as labels
#property indicator_type3 DRAW_ARROW
//---- blue color is used
#property indicator_color3 Blue
//---- indicator line width is equal to 2
#property indicator_width3 2
//---- displaying the indicator label
#property indicator_label3 "Strong trend"
//+-----------------------------------+
//| Indicator drawing parameters |
//+-----------------------------------+
//---- drawing the indicator as labels
#property indicator_type4 DRAW_ARROW
//---- MediumPurple color is used
#property indicator_color4 MediumPurple
//---- indicator line width is equal to 2
#property indicator_width4 2
//---- displaying the indicator label
#property indicator_label4 "Weak trend"
//+-----------------------------------+
//| Smoothings classes description |
//+-----------------------------------+
#include <SmoothAlgorithms.mqh>
//+-----------------------------------+
//---- 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)<BB_Period) Print("Failed to distribute the memory for Count[] array");
if(ArrayResize(Xma,BB_Period)<BB_Period) Print("Failed to distribute the memory for Xma[] array");
ArrayInitialize(Count,0);
ArrayInitialize(Xma,0);
//---- set UpHistBuffer[] dynamic array as an indicator buffer
SetIndexBuffer(0,UpHistBuffer,INDICATOR_DATA);
//---- performing the shift of the beginning of the indicator drawing
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,min_rates_total);
//---- setting the indicator values that won't be visible on a chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE);
//---- indexing the elements in the buffer as timeseries
ArraySetAsSeries(UpHistBuffer,true);
//---- set DnHistBuffer[] dynamic array as an indicator buffer
SetIndexBuffer(1,DnHistBuffer,INDICATOR_DATA);
//---- performing the shift of the beginning of the indicator drawing
PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,min_rates_total);
//---- setting the indicator values that won't be visible on a chart
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,EMPTY_VALUE);
//---- indexing the elements in the buffer as timeseries
ArraySetAsSeries(DnHistBuffer,true);
//---- set UpArrBuffer[] dynamic array as an indicator buffer
SetIndexBuffer(2,UpArrBuffer,INDICATOR_DATA);
//---- performing the shift of the beginning of the indicator drawing
PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,min_rates_total);
//---- setting the indicator values that won't be visible on a chart
PlotIndexSetDouble(2,PLOT_EMPTY_VALUE,EMPTY_VALUE);
//---- indicator symbol
PlotIndexSetInteger(2,PLOT_ARROW,159);
//---- indexing the elements in the buffer as timeseries
ArraySetAsSeries(UpArrBuffer,true);
//---- set DnArrBuffer[] dynamic array as an indicator buffer
SetIndexBuffer(3,DnArrBuffer,INDICATOR_DATA);
//---- performing the shift of the beginning of the indicator drawing
PlotIndexSetInteger(3,PLOT_DRAW_BEGIN,min_rates_total);
//---- setting the indicator values that won't be visible on a chart
PlotIndexSetDouble(3,PLOT_EMPTY_VALUE,EMPTY_VALUE);
//---- indicator symbol
PlotIndexSetInteger(3,PLOT_ARROW,159);
//---- indexing the elements in the buffer as timeseries
ArraySetAsSeries(DnArrBuffer,true);
//--- creation of the name to be displayed in a separate sub-window and in a tooltip
IndicatorSetString(INDICATOR_SHORTNAME,"BBSqueeze");
//--- determination of accuracy of displaying the indicator values
IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//---- initialization end
return(0);
}
//+------------------------------------------------------------------+
//| Custom iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total, // number of bars in history at the current tick
const int prev_calculated,// number of bars calculated at previous call
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[])
{
//---- checking the number of bars to be enough for the calculation
if(BarsCalculated(ATR_Handle)<rates_total
|| BarsCalculated(STD_Handle)<rates_total
|| rates_total<min_rates_total) return(RESET);
//---- declarations of local variables
int to_copy,limit,bar,maxbar,maxbar1;
double STD[],ATR[],lregress,bbs,price_;
maxbar=rates_total-1;
maxbar1=maxbar-min_rates_xma-2*BB_Period;
//---- calculation of the 'limit' starting index for the bars recalculation loop
if(prev_calculated>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; x<Len;x++)
{
HH=Low[index+x];
LL=High[index+x];
for(int y=x; y<x+Len; y++)
{
HH=MathMax(HH,High[index+y]);
LL=MathMin(LL,Low[index+y]);
}
dxma=Close[index+x]-((HH+LL)/2+Xma[Count[x]])/2;
Sum1+=x*dxma;
SumY+=dxma;
}
Sum2=SumBars*SumY;
Num1=Len*Sum1-Sum2;
Num2=SumBars*SumBars-Len*SumSqrBars;
//----
if(Num2!=0.0) Slope=Num1/Num2;
else Slope=0;
Intercept=(SumY-Slope*SumBars)/Len;
LinearRegValue=Intercept+Slope*(Len-1);
//----
return(LinearRegValue);
}
//+------------------------------------------------------------------+
//| Recalculation of position of the newest element in the array |
//+------------------------------------------------------------------+
void Recount_ArrayZeroPos(int &CoArr[],// Return the current value of the price series by the link
uint Size)
{
//----
int numb,Max1,Max2;
static int count=1;
Max1=int(Size-1);
Max2=int(Size);
count--;
if(count<0) count=Max1;
for(int iii=0; iii<Max2; iii++)
{
numb=iii+count;
if(numb>Max1) numb-=Max2;
CoArr[iii]=numb;
}
//----
}
//+------------------------------------------------------------------+
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+175
View File
@@ -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;i<rates_total;i++)
{
Trend[i]=Trend[i-1];
Upper1[i]=0;
Lower1[i]=0;
Upper2[i]=0;
Lower2[i]=0;
Upper3[i]=0;
Lower3[i]=0;
if(Trend[i]==1 && close[i]<BCBuf[i])
{
Trend[i]=0;
}
if(Trend[i]==-1 && close[i]>BCBuf[i])
{
Trend[i]=0;
}
if(close[i]>BUBuf[i])
{
Trend[i]=1;
}
if(close[i]<BLBuf[i])
{
Trend[i]=-1;
}
switch((int)Trend[i])
{
case 1:
Upper1[i]=BUBuf[i];
Lower1[i]=BLBuf[i];
if(Trend[i-1]!=1)
{
Upper1[i-1]=BUBuf[i-1];
Lower1[i-1]=BLBuf[i-1];
}
break;
case -1:
Upper2[i]=BUBuf[i];
Lower2[i]=BLBuf[i];
if(Trend[i-1]!=-1)
{
Upper2[i-1]=BUBuf[i-1];
Lower2[i-1]=BLBuf[i-1];
}
break;
case 0:
Upper3[i]=BUBuf[i];
Lower3[i]=BLBuf[i];
if(Trend[i-1]!=0)
{
Upper3[i-1]=BUBuf[i-1];
Lower3[i-1]=BLBuf[i-1];
}
break;
}
}
return(rates_total);
}
//+------------------------------------------------------------------+
+579
View File
@@ -0,0 +1,579 @@
//+------------------------------------------------------------------+
//| MACD Sample.mq5 |
//| Copyright 2009-2013, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014 Semet Gaetan"
#property link "http://www.xeberon.net/gaetan"
#property version "1.0"
#property description "Gaetan Semet Expert Advisor"
#property description "This expert advisor triggers position on MACD and"
#property description "crossing Moving Averages. After a bid is placed"
#property description "it is qualified as 'gaining' or loosing'. If loosing,"
#property description "the stop will triggered to stop losses. If gaining,"
#property description "a trailing stop will be placed that allow a retracement"
#property description "of N percents. Only a small number of retracement is"
#property description "allowed, after a stop loss will be placed."
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
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_signal_previous)
{
if ((MathAbs(m_macd_current) > 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;
}
}
}
}
//+------------------------------------------------------------------+
+122
View File
@@ -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/PeriodRatio) return(0);
//--- we can copy not all data
int to_copy;
if(prev_calculated>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; i<ArraySize(ExtMacdBuffer2pom); i++)
for(int j=0; j<PeriodRatio; j++)
ExtMacdBuffer[int(fmod(to_copy,PeriodRatio))+i*PeriodRatio+j]=ExtMacdBuffer2pom[i];
ArrayResize(ExtSignalBuffer,ArraySize(ExtSignalBuffer2pom)*PeriodRatio);
for(int i=0; i<ArraySize(ExtSignalBuffer2pom); i++)
for(int j=0; j<PeriodRatio; j++)
ExtSignalBuffer[int(fmod(to_copy,PeriodRatio))+i*PeriodRatio+j]=ExtSignalBuffer2pom[i];
return(rates_total);
}
//+------------------------------------------------------------------+
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+552
View File
@@ -0,0 +1,552 @@
//+------------------------------------------------------------------+
//| VWAP.mq5 |
//| Copyright 2015, SOL Digital Consultoria LTDA |
//| http://www.soldigitalconsultoria.com.br |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, SOL Digital Consultoria LTDA"
#property link "http://www.soldigitalconsultoria.com.br"
#property version "1.47"
#property indicator_chart_window
#property indicator_buffers 8
#property indicator_plots 8
//--- plot VWAP
#property indicator_label1 "VWAP Daily"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_DASH
#property indicator_width1 2
#property indicator_label2 "VWAP Weekly"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrBlue
#property indicator_style2 STYLE_DASH
#property indicator_width2 2
#property indicator_label3 "VWAP Monthly"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrGreen
#property indicator_style3 STYLE_DASH
#property indicator_width3 2
#property indicator_label4 "VWAP Level 01"
#property indicator_type4 DRAW_LINE
#property indicator_color4 clrGray
#property indicator_style4 STYLE_DASH
#property indicator_width4 2
#property indicator_label5 "VWAP Level 02"
#property indicator_type5 DRAW_LINE
#property indicator_color5 clrYellow
#property indicator_style5 STYLE_DASH
#property indicator_width5 2
#property indicator_label6 "VWAP Level 03"
#property indicator_type6 DRAW_LINE
#property indicator_color6 clrGreen
#property indicator_style6 STYLE_DASH
#property indicator_width6 2
#property indicator_label7 "VWAP Level 04"
#property indicator_type7 DRAW_LINE
#property indicator_color7 clrBlack
#property indicator_style7 STYLE_DASH
#property indicator_width7 2
#property indicator_label8 "VWAP Level 05"
#property indicator_type8 DRAW_LINE
#property indicator_color8 clrBlue
#property indicator_style8 STYLE_DASH
#property indicator_width8 2
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum DATE_TYPE
{
DAILY,
WEEKLY,
MONTHLY
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum PRICE_TYPE
{
OPEN,
CLOSE,
HIGH,
LOW,
OPEN_CLOSE,
HIGH_LOW,
CLOSE_HIGH_LOW,
OPEN_CLOSE_HIGH_LOW
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
datetime CreateDateTime(DATE_TYPE nReturnType=DAILY,datetime dtDay=D'2000.01.01 00:00:00',int pHour=0,int pMinute=0,int pSecond=0)
{
datetime dtReturnDate;
MqlDateTime timeStruct;
TimeToStruct(dtDay,timeStruct);
timeStruct.hour = pHour;
timeStruct.min = pMinute;
timeStruct.sec = pSecond;
dtReturnDate=(StructToTime(timeStruct));
if(nReturnType==WEEKLY)
{
while(timeStruct.day_of_week!=0)
{
dtReturnDate=(dtReturnDate-86400);
TimeToStruct(dtReturnDate,timeStruct);
}
}
if(nReturnType==MONTHLY)
{
timeStruct.day=1;
dtReturnDate=(StructToTime(timeStruct));
}
return dtReturnDate;
}
sinput string Indicator_Name="Volume Weighted Average Price (VWAP)";
input PRICE_TYPE Price_Type = CLOSE_HIGH_LOW;
input bool Enable_Daily = true;
input bool Enable_Weekly = true;
input bool Enable_Monthly = true;
input bool Enable_Level_01 = false;
input int VWAP_Level_01_Period = 5;
input bool Enable_Level_02 = false;
input int VWAP_Level_02_Period = 13;
input bool Enable_Level_03 = false;
input int VWAP_Level_03_Period = 20;
input bool Enable_Level_04 = false;
input int VWAP_Level_04_Period = 30;
input bool Enable_Level_05 = false;
input int VWAP_Level_05_Period = 40;
bool Show_Daily_Value = true;
bool Show_Weekly_Value = true;
bool Show_Monthly_Value = true;
double VWAP_Buffer_Daily[];
double VWAP_Buffer_Weekly[];
double VWAP_Buffer_Monthly[];
double VWAP_Buffer_01[];
double VWAP_Buffer_02[];
double VWAP_Buffer_03[];
double VWAP_Buffer_04[];
double VWAP_Buffer_05[];
double nPriceArr[];
double nTotalTPV[];
double nTotalVol[];
double nSumDailyTPV = 0, nSumWeeklyTPV = 0, nSumMonthlyTPV = 0;
double nSumDailyVol = 0, nSumWeeklyVol = 0, nSumMonthlyVol = 0;
int nIdxDaily=0,nIdxWeekly=0,nIdxMonthly=0,nIdx=0;
bool bIsFirstRun=true;
ENUM_TIMEFRAMES LastTimePeriod=PERIOD_MN1;
string sDailyStr = "";
string sWeeklyStr = "";
string sMonthlyStr = "";
string sLevel01Str = "";
string sLevel02Str = "";
string sLevel03Str = "";
string sLevel04Str = "";
string sLevel05Str = "";
datetime dtLastDay=CreateDateTime(DAILY),dtLastWeek=CreateDateTime(WEEKLY),dtLastMonth=CreateDateTime(MONTHLY);
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int OnInit()
{
IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
SetIndexBuffer(0,VWAP_Buffer_Daily,INDICATOR_DATA);
SetIndexBuffer(1,VWAP_Buffer_Weekly,INDICATOR_DATA);
SetIndexBuffer(2,VWAP_Buffer_Monthly,INDICATOR_DATA);
SetIndexBuffer(3,VWAP_Buffer_01,INDICATOR_DATA);
SetIndexBuffer(4,VWAP_Buffer_02,INDICATOR_DATA);
SetIndexBuffer(5,VWAP_Buffer_03,INDICATOR_DATA);
SetIndexBuffer(6,VWAP_Buffer_04,INDICATOR_DATA);
SetIndexBuffer(7,VWAP_Buffer_05,INDICATOR_DATA);
ObjectCreate(0,"VWAP_Daily",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Daily",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Daily",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Daily",OBJPROP_YDISTANCE,40);
ObjectSetInteger(0,"VWAP_Daily",OBJPROP_COLOR,indicator_color1);
ObjectSetInteger(0,"VWAP_Daily",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Daily",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Daily",OBJPROP_TEXT," ");
ObjectCreate(0,"VWAP_Weekly",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Weekly",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Weekly",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Weekly",OBJPROP_YDISTANCE,60);
ObjectSetInteger(0,"VWAP_Weekly",OBJPROP_COLOR,indicator_color2);
ObjectSetInteger(0,"VWAP_Weekly",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Weekly",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Weekly",OBJPROP_TEXT," ");
ObjectCreate(0,"VWAP_Monthly",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Monthly",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Monthly",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Monthly",OBJPROP_YDISTANCE,80);
ObjectSetInteger(0,"VWAP_Monthly",OBJPROP_COLOR,indicator_color3);
ObjectSetInteger(0,"VWAP_Monthly",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Monthly",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Monthly",OBJPROP_TEXT," ");
ObjectCreate(0,"VWAP_Level_01",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Level_01",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Level_01",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Level_01",OBJPROP_YDISTANCE,100);
ObjectSetInteger(0,"VWAP_Level_01",OBJPROP_COLOR,indicator_color4);
ObjectSetInteger(0,"VWAP_Level_01",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Level_01",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Level_01",OBJPROP_TEXT," ");
ObjectCreate(0,"VWAP_Level_02",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Level_02",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Level_02",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Level_02",OBJPROP_YDISTANCE,120);
ObjectSetInteger(0,"VWAP_Level_02",OBJPROP_COLOR,indicator_color5);
ObjectSetInteger(0,"VWAP_Level_02",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Level_02",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Level_02",OBJPROP_TEXT," ");
ObjectCreate(0,"VWAP_Level_03",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Level_03",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Level_03",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Level_03",OBJPROP_YDISTANCE,140);
ObjectSetInteger(0,"VWAP_Level_03",OBJPROP_COLOR,indicator_color6);
ObjectSetInteger(0,"VWAP_Level_03",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Level_03",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Level_03",OBJPROP_TEXT," ");
ObjectCreate(0,"VWAP_Level_04",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Level_04",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Level_04",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Level_04",OBJPROP_YDISTANCE,160);
ObjectSetInteger(0,"VWAP_Level_04",OBJPROP_COLOR,indicator_color7);
ObjectSetInteger(0,"VWAP_Level_04",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Level_04",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Level_04",OBJPROP_TEXT," ");
ObjectCreate(0,"VWAP_Level_05",OBJ_LABEL,0,0,0);
ObjectSetInteger(0,"VWAP_Level_05",OBJPROP_CORNER,3);
ObjectSetInteger(0,"VWAP_Level_05",OBJPROP_XDISTANCE,180);
ObjectSetInteger(0,"VWAP_Level_05",OBJPROP_YDISTANCE,180);
ObjectSetInteger(0,"VWAP_Level_05",OBJPROP_COLOR,indicator_color8);
ObjectSetInteger(0,"VWAP_Level_05",OBJPROP_FONTSIZE,7);
ObjectSetString(0,"VWAP_Level_05",OBJPROP_FONT,"Verdana");
ObjectSetString(0,"VWAP_Level_05",OBJPROP_TEXT," ");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnDeinit(const int pReason)
{
ObjectDelete(0,"VWAP_Daily");
ObjectDelete(0,"VWAP_Weekly");
ObjectDelete(0,"VWAP_Monthly");
ObjectDelete(0,"VWAP_Level_01");
ObjectDelete(0,"VWAP_Level_02");
ObjectDelete(0,"VWAP_Level_03");
ObjectDelete(0,"VWAP_Level_04");
ObjectDelete(0,"VWAP_Level_05");
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
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(PERIOD_CURRENT!=LastTimePeriod)
{
bIsFirstRun=true;
LastTimePeriod=PERIOD_CURRENT;
}
if(rates_total>prev_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<rates_total; nIdx++)
{
if(CreateDateTime(DAILY,time[nIdx])!=dtLastDay)
{
nIdxDaily=nIdx;
nSumDailyTPV = 0;
nSumDailyVol = 0;
}
if(CreateDateTime(WEEKLY,time[nIdx])!=dtLastWeek)
{
nIdxWeekly=nIdx;
nSumWeeklyTPV = 0;
nSumWeeklyVol = 0;
}
if(CreateDateTime(MONTHLY,time[nIdx])!=dtLastMonth)
{
nIdxMonthly=nIdx;
nSumMonthlyTPV = 0;
nSumMonthlyVol = 0;
}
nPriceArr[nIdx] = 0;
nTotalTPV[nIdx] = 0;
nTotalVol[nIdx] = 0;
switch(Price_Type)
{
case OPEN:
nPriceArr[nIdx]=open[nIdx];
break;
case CLOSE:
nPriceArr[nIdx]=close[nIdx];
break;
case HIGH:
nPriceArr[nIdx]=high[nIdx];
break;
case LOW:
nPriceArr[nIdx]=low[nIdx];
break;
case HIGH_LOW:
nPriceArr[nIdx]=(high[nIdx]+low[nIdx])/2;
break;
case OPEN_CLOSE:
nPriceArr[nIdx]=(open[nIdx]+close[nIdx])/2;
break;
case CLOSE_HIGH_LOW:
nPriceArr[nIdx]=(close[nIdx]+high[nIdx]+low[nIdx])/3;
break;
case OPEN_CLOSE_HIGH_LOW:
nPriceArr[nIdx]=(open[nIdx]+close[nIdx]+high[nIdx]+low[nIdx])/4;
break;
default:
nPriceArr[nIdx]=(close[nIdx]+high[nIdx]+low[nIdx])/3;
break;
}
if(tick_volume[nIdx])
{
nTotalTPV[nIdx] = (nPriceArr[nIdx] * tick_volume[nIdx]);
nTotalVol[nIdx] = (double)tick_volume[nIdx];
} else if(volume[nIdx]) {
nTotalTPV[nIdx] = (nPriceArr[nIdx] * volume[nIdx]);
nTotalVol[nIdx] = (double)volume[nIdx];
}
if(Enable_Daily && (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; nIdx<rates_total; nIdx++)
{
double nSumTotalTPV = 0;
double nSumTotalVol = 0;
VWAP_Buffer_01[nIdx] = EMPTY_VALUE;
for(int nSubIdx=1; nSubIdx<VWAP_Level_01_Period; nSubIdx++)
{
nSumTotalTPV += nTotalTPV[nIdx - nSubIdx];
nSumTotalVol += nTotalVol[nIdx - nSubIdx];
}
if(nSumTotalVol)
VWAP_Buffer_01[nIdx]=(nSumTotalTPV/nSumTotalVol);
else
VWAP_Buffer_01[nIdx]=0;
if(sLevel01Str!="VWAP Level 01 ("+(string)VWAP_Level_01_Period+"): "+(string)NormalizeDouble(VWAP_Buffer_01[nIdx],_Digits))
{
sLevel01Str = "VWAP Level 01 (" + (string)VWAP_Level_01_Period + "): " + (string)NormalizeDouble(VWAP_Buffer_01[nIdx], _Digits);
ObjectSetString(0,"VWAP_Level_01",OBJPROP_TEXT,sLevel01Str);
}
}
}
if(Enable_Level_02)
{
int nStartPos=(prev_calculated>VWAP_Level_02_Period) ?(prev_calculated-VWAP_Level_02_Period) : VWAP_Level_02_Period;
for(nIdx=nStartPos; nIdx<rates_total; nIdx++)
{
double nSumTotalTPV = 0;
double nSumTotalVol = 0;
VWAP_Buffer_02[nIdx] = EMPTY_VALUE;
for(int nSubIdx=1; nSubIdx<VWAP_Level_02_Period; nSubIdx++)
{
nSumTotalTPV += nTotalTPV[nIdx - nSubIdx];
nSumTotalVol += nTotalVol[nIdx - nSubIdx];
}
if(nSumTotalVol)
VWAP_Buffer_02[nIdx]=(nSumTotalTPV/nSumTotalVol);
else
VWAP_Buffer_02[nIdx]=0;
if(sLevel02Str!="VWAP Level 02 ("+(string)VWAP_Level_02_Period+"): "+(string)NormalizeDouble(VWAP_Buffer_02[nIdx],_Digits))
{
sLevel02Str = "VWAP Level 02 (" + (string)VWAP_Level_02_Period + "): " + (string)NormalizeDouble(VWAP_Buffer_02[nIdx], _Digits);
ObjectSetString(0,"VWAP_Level_02",OBJPROP_TEXT,sLevel02Str);
}
}
}
if(Enable_Level_03)
{
int nStartPos=(prev_calculated>VWAP_Level_03_Period) ?(prev_calculated-VWAP_Level_03_Period) : VWAP_Level_03_Period;
for(nIdx=nStartPos; nIdx<rates_total; nIdx++)
{
double nSumTotalTPV = 0;
double nSumTotalVol = 0;
VWAP_Buffer_03[nIdx] = EMPTY_VALUE;
for(int nSubIdx=1; nSubIdx<VWAP_Level_03_Period; nSubIdx++)
{
nSumTotalTPV += nTotalTPV[nIdx - nSubIdx];
nSumTotalVol += nTotalVol[nIdx - nSubIdx];
}
if(nSumTotalVol)
VWAP_Buffer_03[nIdx]=(nSumTotalTPV/nSumTotalVol);
else
VWAP_Buffer_03[nIdx]=0;
if(sLevel03Str!="VWAP Level 03 ("+(string)VWAP_Level_03_Period+"): "+(string)NormalizeDouble(VWAP_Buffer_03[nIdx],_Digits))
{
sLevel03Str = "VWAP Level 03 (" + (string)VWAP_Level_03_Period + "): " + (string)NormalizeDouble(VWAP_Buffer_03[nIdx], _Digits);
ObjectSetString(0,"VWAP_Level_03",OBJPROP_TEXT,sLevel03Str);
}
}
}
if(Enable_Level_04)
{
int nStartPos=(prev_calculated>VWAP_Level_04_Period) ?(prev_calculated-VWAP_Level_04_Period) : VWAP_Level_04_Period;
for(nIdx=nStartPos; nIdx<rates_total; nIdx++)
{
double nSumTotalTPV = 0;
double nSumTotalVol = 0;
VWAP_Buffer_04[nIdx] = EMPTY_VALUE;
for(int nSubIdx=1; nSubIdx<VWAP_Level_04_Period; nSubIdx++)
{
nSumTotalTPV += nTotalTPV[nIdx - nSubIdx];
nSumTotalVol += nTotalVol[nIdx - nSubIdx];
}
if(nSumTotalVol)
VWAP_Buffer_04[nIdx]=(nSumTotalTPV/nSumTotalVol);
else
VWAP_Buffer_04[nIdx]=0;
if(sLevel04Str!="VWAP Level 04 ("+(string)VWAP_Level_04_Period+"): "+(string)NormalizeDouble(VWAP_Buffer_04[nIdx],_Digits))
{
sLevel04Str = "VWAP Level 04 (" + (string)VWAP_Level_04_Period + "): " + (string)NormalizeDouble(VWAP_Buffer_04[nIdx], _Digits);
ObjectSetString(0,"VWAP_Level_04",OBJPROP_TEXT,sLevel04Str);
}
}
}
if(Enable_Level_05)
{
int nStartPos=(prev_calculated>VWAP_Level_05_Period) ?(prev_calculated-VWAP_Level_05_Period) : VWAP_Level_05_Period;
for(nIdx=nStartPos; nIdx<rates_total; nIdx++)
{
double nSumTotalTPV = 0;
double nSumTotalVol = 0;
VWAP_Buffer_05[nIdx] = EMPTY_VALUE;
for(int nSubIdx=1; nSubIdx<VWAP_Level_05_Period; nSubIdx++)
{
nSumTotalTPV += nTotalTPV[nIdx - nSubIdx];
nSumTotalVol += nTotalVol[nIdx - nSubIdx];
}
if(nSumTotalVol)
VWAP_Buffer_05[nIdx]=(nSumTotalTPV/nSumTotalVol);
else
VWAP_Buffer_05[nIdx]=0;
if(sLevel05Str!="VWAP Level 05 ("+(string)VWAP_Level_05_Period+"): "+(string)NormalizeDouble(VWAP_Buffer_05[nIdx],_Digits))
{
sLevel05Str = "VWAP Level 05 (" + (string)VWAP_Level_05_Period + "): " + (string)NormalizeDouble(VWAP_Buffer_05[nIdx], _Digits);
ObjectSetString(0,"VWAP_Level_05",OBJPROP_TEXT,sLevel05Str);
}
}
}
bIsFirstRun=false;
}
return(rates_total);
}
//+------------------------------------------------------------------+