Gold Weekend Gap Map
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «goldweekendgapmap.mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Gold Weekend Gap Map — индикатор для MetaTrader 5, предназначенный для анализа и визуализации выходных разрывов цен на графике выбранного символа. Он обнаруживает все паузы в котировках, превышающие заданную длительность, и отображает их в виде зон на графике с информацией о размере разрыва в цене и в ADR.
Для каждого разрыва индикатор рассчитывает средний дневной диапазон (ADR) за заданный период и показывает, был ли разрыв заполнен, а также за какое время. Открытые разрывы могут сопровождаться пунктирной линией уровня закрытия пятницы.
Информационная панель в углу графика содержит статистику по недавним разрывам: медиану, перцентили, процент заполнения за различные периоды и количество открытых разрывов. Внизу панели отображается мини-гистограмма последних разрывов с высотой столбцов, пропорциональной размеру в ADR.
Индикатор поддерживает настраиваемые оповещения при открытии недели с крупным разрывом, включая возможность отправки push-уведомлений. Индикатор предназначен только для отображения и не выполняет торговых операций.
Настройки программы
| Настройка | Описание |
|---|---|
| InpMinBreakHours | Минимальная длительность паузы в котировках, при которой считается разрыв. Задаётся в часах. |
| InpWeekendOnly | Учитывать только разрывы, открытые в воскресенье или понедельник. |
| InpAdrDays | Количество завершённых дневных баров для расчёта среднего дневного диапазона (ADR). |
| InpStatsWeeks | Количество недель истории для расчёта статистики заполнения разрывов. |
| InpFillDays | Максимальное окно в торговых днях, в котором учитывается заполнение разрыва в таблице. |
| InpDrawGaps | Количество последних разрывов, отображаемых на графике. |
| InpShowLabels | Отображать подписи с размером и статусом заполнения рядом с каждым разрывом. |
| InpMinZoneHours | Минимальная ширина зоны разрыва, отображаемой на графике, в часах. |
| InpShowOpenTarget | Отображать пунктирную линию закрытия пятницы для открытого разрыва. |
| InpAlertNewGap | Отправлять уведомление при открытии недели с крупным разрывом. |
| InpAlertAdr | Порог размера разрыва для уведомления, выраженный в ADR. |
| InpAlertPush | Дополнительно отправлять push-уведомление. |
| InpShowPanel | Отображать информационную панель со статистикой. |
| InpPanelX | Горизонтальное смещение панели в пикселях. |
| InpPanelY | Вертикальное смещение панели в пикселях. |
| InpFontSize | Размер шрифта текста на графике и в панели. |
| InpFontName | Название шрифта для текста на графике и в панели. |
| InpColUp | Цвет разрыва, при котором цена открылась выше предыдущего закрытия. |
| InpColDown | Цвет разрыва, при котором цена открылась ниже предыдущего закрытия. |
| InpColTarget | Цвет пунктирной линии закрытия пятницы для открытого разрыва. |
| InpColPanelBg | Цвет фона информационной панели. |
| InpColHeaderBg | Цвет фона заголовка панели. |
| InpColBorder | Цвет рамки и акцентных элементов панели. |
| InpColText | Цвет основного текста в панели. |
| InpColDim | Цвет дополнительного (второстепенного) текста в панели. |
Поиск по коду файла
#property version "1.00"
#property description "Gold Weekend Gap Map: every weekend gap of the symbol on one chart,"
#property description "its size in price and in ADR, whether and how fast it was filled,"
#property description "and the fill statistics of recent weeks. Display only, it does not trade."
#property indicator_chart_window
#property indicator_plots 0
#property indicator_buffers 0
input group "1. Gap detection"
input int InpMinBreakHours = 36; // A gap is a pause in quotes of at least N hours
input bool InpWeekendOnly = true; // Count only openings on Sunday or Monday
input int InpAdrDays = 14; // ADR period, completed daily bars
input int InpStatsWeeks = 104; // Statistics lookback, number of gaps
input int InpFillDays = 5; // Longest fill window counted in the table, trading days
input group "2. Chart marks"
input int InpDrawGaps = 12; // Gaps drawn on the chart (latest)
input bool InpShowLabels = true; // Size and fill labels next to each gap
input int InpMinZoneHours = 24; // Minimum drawn width of a gap zone, hours
input bool InpShowOpenTarget = true; // Dashed line at Friday close while a gap is open
input group "3. Alert"
input bool InpAlertNewGap = false; // Alert when the week opens with a large gap
input double InpAlertAdr = 0.20; // Alert threshold, gap size in ADR
input bool InpAlertPush = false; // Also send a push notification
input group "4. Panel"
input bool InpShowPanel = true; // Show the information panel
input int InpPanelX = 12; // Panel X offset, pixels
input int InpPanelY = 24; // Panel Y offset, pixels
input int InpFontSize = 8; // Font size
input string InpFontName = "Consolas"; // Font
input group "5. Colors"
input color InpColUp = C'46,178,120'; // Up gap
input color InpColDown = C'214,86,86'; // Down gap
input color InpColTarget = C'224,184,74'; // Open gap target (Friday close)
input color InpColPanelBg = C'7,26,20'; // Panel background
input color InpColHeaderBg = C'11,61,46'; // Panel header
input color InpColBorder = C'212,175,55'; // Panel border and accent
input color InpColText = C'234,246,239'; // Panel text
input color InpColDim = C'138,168,152'; // Panel secondary text
#define PFX "GWGM_"
struct GapInfo
{
datetime t_prev; // last bar before the pause
datetime t_open; // first bar after the pause
double prev_close;
double open;
double gap; // open - prev_close
double adr; // ADR before the gap (0 if unknown)
int fill_bars; // H1 bars until filled (0 = first hour), -1 = not yet
datetime t_fill;
int bars_since; // H1 bars available after the open
};
GapInfo g_gaps[];
datetime g_last_build = 0;
datetime g_last_alert_gap = 0;
int OnInit()
{
// код доступен только после оплаты
}
void OnDeinit(const int reason)
{
EventKillTimer();
ObjectsDeleteAll(0,PFX);
ChartRedraw();
}
void OnTimer()
{
Build();
}
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[])
{
// код доступен только после оплаты
}
double AdrBefore(const MqlRates &d1[],const int n,const datetime t)
{
const datetime day=t-(t%86400);
double sum=0.0;
int cnt=0;
for(int i=n-1;i>=0 && cnt<InpAdrDays;i--)
{
if(d1[i].time>=day)
continue;
sum+=d1[i].high-d1[i].low;
cnt++;
}
return(cnt==InpAdrDays ? sum/cnt : 0.0);
}
bool Build()
{
g_last_build=TimeCurrent();
const int want=MathMin((InpStatsWeeks+4)*130+InpFillDays*24+200,200000);
MqlRates h1[];
ArraySetAsSeries(h1,false);
const int n=CopyRates(_Symbol,PERIOD_H1,0,want,h1);
if(n<200)
return(false);
MqlRates d1[];
ArraySetAsSeries(d1,false);
const int nd=CopyRates(_Symbol,PERIOD_D1,0,MathMin((InpStatsWeeks+4)*7+InpAdrDays+20,20000),d1);
if(nd<InpAdrDays+2)
return(false);
ArrayResize(g_gaps,0);
const int pause=InpMinBreakHours*3600;
for(int i=1;i<n;i++)
{
if(h1[i].time-h1[i-1].time<pause)
continue;
MqlDateTime dt;
TimeToStruct(h1[i].time,dt);
if(InpWeekendOnly && dt.day_of_week!=0 && dt.day_of_week!=1)
continue;
GapInfo g;
g.t_prev=h1[i-1].time;
g.t_open=h1[i].time;
g.prev_close=h1[i-1].close;
g.open=h1[i].open;
g.gap=g.open-g.prev_close;
g.adr=AdrBefore(d1,nd,g.t_open);
g.fill_bars=-1;
g.t_fill=0;
g.bars_since=n-i;
for(int k=i;k<n;k++)
{
const bool hit=(g.gap>=0.0) ? (h1[k].low<=g.prev_close) : (h1[k].high>=g.prev_close);
if(hit)
{
g.fill_bars=k-i;
g.t_fill=h1[k].time;
break;
}
}
const int sz=ArraySize(g_gaps);
ArrayResize(g_gaps,sz+1);
g_gaps[sz]=g;
}
Draw(h1[n-1].time,SymbolInfoDouble(_Symbol,SYMBOL_BID));
CheckAlert();
return(true);
}
string Fmt(const double v,const int digits)
{
return(DoubleToString(v,digits));
}
string Signed(const double v,const int digits)
{
return((v>=0.0 ? "+" : "")+DoubleToString(v,digits));
}
string FillText(const GapInfo &g)
{
if(g.fill_bars<0)
return("open");
if(g.fill_bars==0)
return("filled in 1st hour");
if(g.fill_bars<24)
return("filled in "+IntegerToString(g.fill_bars+1)+"h");
return("filled in "+DoubleToString((g.fill_bars+1)/24.0,1)+"d");
}
string ShortFill(const GapInfo &g)
{
if(g.fill_bars<0)
return("OPEN");
if(g.fill_bars<24)
return("filled "+IntegerToString(g.fill_bars+1)+"h");
return("filled "+DoubleToString((g.fill_bars+1)/24.0,1)+"d");
}
void SetText(const string name,const datetime t,const double p,const string txt,const color c,const ENUM_ANCHOR_POINT a)
{
if(ObjectFind(0,name)<0)
ObjectCreate(0,name,OBJ_TEXT,0,t,p);
ObjectSetInteger(0,name,OBJPROP_TIME,0,t);
ObjectSetDouble(0,name,OBJPROP_PRICE,0,p);
ObjectSetString(0,name,OBJPROP_TEXT,txt);
ObjectSetString(0,name,OBJPROP_FONT,InpFontName);
ObjectSetInteger(0,name,OBJPROP_FONTSIZE,InpFontSize);
ObjectSetInteger(0,name,OBJPROP_COLOR,c);
ObjectSetInteger(0,name,OBJPROP_ANCHOR,a);
ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
}
void SetRect(const string name,const datetime t1,const double p1,const datetime t2,const double p2,const color c,const bool fill)
{
if(ObjectFind(0,name)<0)
ObjectCreate(0,name,OBJ_RECTANGLE,0,t1,p1,t2,p2);
ObjectSetInteger(0,name,OBJPROP_TIME,0,t1);
ObjectSetDouble(0,name,OBJPROP_PRICE,0,p1);
ObjectSetInteger(0,name,OBJPROP_TIME,1,t2);
ObjectSetDouble(0,name,OBJPROP_PRICE,1,p2);
ObjectSetInteger(0,name,OBJPROP_COLOR,c);
ObjectSetInteger(0,name,OBJPROP_FILL,fill);
ObjectSetInteger(0,name,OBJPROP_BACK,true);
ObjectSetInteger(0,name,OBJPROP_WIDTH,1);
ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
}
void SetLine(const string name,const datetime t1,const datetime t2,const double p,const color c)
{
if(ObjectFind(0,name)<0)
ObjectCreate(0,name,OBJ_TREND,0,t1,p,t2,p);
ObjectSetInteger(0,name,OBJPROP_TIME,0,t1);
ObjectSetDouble(0,name,OBJPROP_PRICE,0,p);
ObjectSetInteger(0,name,OBJPROP_TIME,1,t2);
ObjectSetDouble(0,name,OBJPROP_PRICE,1,p);
ObjectSetInteger(0,name,OBJPROP_COLOR,c);
ObjectSetInteger(0,name,OBJPROP_STYLE,STYLE_DASH);
ObjectSetInteger(0,name,OBJPROP_RAY_RIGHT,false);
ObjectSetInteger(0,name,OBJPROP_BACK,true);
ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
}
color Mix(const color a,const color b,const double w)
{
const int ra=(int)(a&0xFF),ga=(int)((a>>8)&0xFF),ba=(int)((a>>16)&0xFF);
const int rb=(int)(b&0xFF),gb=(int)((b>>8)&0xFF),bb=(int)((b>>16)&0xFF);
const int r=(int)MathRound(ra*(1.0-w)+rb*w);
const int g=(int)MathRound(ga*(1.0-w)+gb*w);
const int bl=(int)MathRound(ba*(1.0-w)+bb*w);
return((color)(r|(g<<8)|(bl<<16)));
}
void Draw(const datetime last_time,const double bid)
{
ObjectsDПоказано первые 50% кода (символов: 14283)