XU ZZ1 LINE
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «xu zz1 line.mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
XU ZZ1 LINE — аналитический индикатор для MetaTrader 5, реализующий логику ZigZag для выявления значимых опорных точек (пивотов) на графике цены. Индикатор рассчитывает локальные максимумы и минимумы на основе заданной глубины поиска, минимального отклонения и шага очистки, отображая их в виде двух линий: пунктирной для неподтверждённых пивотов и сплошной для подтверждённых.
Индикатор поддерживает механизм подтверждения пивотов через заданное количество баров ожидания, а также режим непрерывности, при котором между пивотами отрисовывается соединяющая линия в рамках текущего тренда. Доступны настройки цветов, система уведомлений с звуковыми и текстовыми оповещениями, а также режим отладки для разработки и тестирования.
Настройки программы
| Настройка | Описание |
|---|---|
| ZZ_Depth | Количество баров вперёд и назад от текущего бара, в которых ищутся опорные точки (локальные максимумы и минимумы) для подтверждения пивотов. |
| ZZ_Deviation | Минимальное движение цены в пунктах (умноженное на значение точки символа), необходимое для признания бара значимым пивотом. |
| ZZ_Backstep | Количество баров назад от нового пивота, в которых удаляются менее значимые предыдущие пивоты (обнуляются). |
| ConfirmationBars | Количество баров ожидания после обнаружения пивота, прежде чем он будет promoted из неподтверждённых в подтверждённые. |
| ShowTentative | Определяет, отображать ли пунктирной линией неподтверждённые пивоты на графике. При отключении показываются только подтверждённые пивоты. |
| EnableContinuity | Включает отрисовку соединяющей линии между пивотами, поддерживающей визуальную непрерывность тренда между значимыми точками. |
| MaxContinuityBars | Максимальное количество баров, в течение которых линия непрерывности поддерживается без появления нового пивота. При превышении линия сбрасывается. |
| LogContinuity | Логирует изменения состояния непрерывности (сброс, новое состояние, истечение) в журнал для отладки. |
| TentativeColor | Цвет пунктирной линии, отображающей неподтверждённые (временные) пивоты на графике. |
| ConfirmedColor | Цвет сплошной линии, отображающей подтверждённые пивоты на графике. |
| alertsOn | Включает или отключает всю систему уведомлений о событиях пивотов. При отключении ни текстовые, ни звуковые уведомления не срабатывают. |
| alertsOnCurrent | При значении true уведомления срабатывают для текущего (живого) бара, что может приводить к перерисовке. Для продакшена рекомендуется установить false. |
| alertsMessage | Включает отображение всплывающих текстовых сообщений-уведомлений при обнаружении подтверждённых пивотов. |
| alertsSound | Включает воспроизведение звукового сигнала при обнаружении подтверждённого пивота. Используется файл, указанный в AlertSoundFile. |
| AlertSoundFile | Имя звукового файла, который воспроизводится при срабатывании звукового уведомления о новом пивоте. |
| AlertDecayMinutes | Время в минутах до автоматического сброса состояния уведомлений, предотвращающее повторные срабатывания одной и той же сигнализации. |
| DebugMode | Включает режим отладки с дополнительными выводами в журнал. Снижает производительность; для продакшена рекомендуется отключать. |
Поиск по коду файла
/*
███████╗ ██████╗ ██████╗ ███████╗██╗ ██╗ ███████╗████████╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗
██╔════╝██╔═══██╗██╔══██╗██╔════╝╚██╗██╔╝ ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║
█████╗ ██║ ██║██████╔╝█████╗ ╚███╔╝█████╗███████╗ ██║ ███████║ ██║ ██║██║ ██║██╔██╗ ██║
██╔══╝ ██║ ██║██╔══██╗██╔══╝ ██╔██╗╚════╝╚════██║ ██║ ██╔══██║ ██║ ██║██║ ██║██║╚██╗██║
██║ ╚██████╔╝██║ ██║███████╗██╔╝ ██╗ ███████║ ██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║
╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
*/
#property version "2.13"
#property indicator_chart_window
#property indicator_buffers 6
#property indicator_plots 2
#property indicator_label1 "ZZ1 Tentative"
#property indicator_type1 DRAW_SECTION
#property indicator_color1 clrLightSteelBlue
#property indicator_style1 STYLE_DASH
#property indicator_width1 1
#property indicator_label2 "ZZ1 Confirmed"
#property indicator_type2 DRAW_SECTION
#property indicator_color2 clrRoyalBlue
#property indicator_style2 STYLE_SOLID
#property indicator_width2 2
#define ZZ_EMPTY_VALUE DBL_MAX
enum ENUM_XU_STATE
{
STATE_DOWN = -1,
STATE_NEUTRAL = 0,
STATE_UP = 1
};
input group "=== ZZ1 Core Settings ==="
input int ZZ_Depth = 59; // Bars to look ahead/behind for pivot confirmation
input int ZZ_Deviation = 500; // Minimum movement in points * GetSymbolPoint()
input int ZZ_Backstep = 3; // Bars to clear weaker pivots behind
input group "=== Epistemic Settings ==="
input int ConfirmationBars = 3; // Bars to wait before promoting to confirmed
input bool ShowTentative = true; // Show dashed unconfirmed pivots?
input group "=== Continuity Settings ==="
input bool EnableContinuity = true; // Enable VWAP-style continuity between pivots
input int MaxContinuityBars = 50; // Max bars to maintain continuity without new pivot
input bool LogContinuity = false; // Log continuity state changes
input group "=== Visual Customization ==="
input color TentativeColor = clrLightSteelBlue;
input color ConfirmedColor = clrRoyalBlue;
input group "=== Alert Settings ==="
input bool alertsOn = true;
input bool alertsOnCurrent = false; // Set to false for production!
input bool alertsMessage = true;
input bool alertsSound = false;
input string AlertSoundFile = "alert.wav";
input int AlertDecayMinutes = 60;
input group "=== Debug ==="
input bool DebugMode = false;
double ZZTentativeBuffer[]; // Plot 0: Dashed line (unconfirmed)
double ZZConfirmedBuffer[]; // Plot 1: Solid line (confirmed)
double ZZHighCalc[]; // Current high pivots
double ZZLowCalc[]; // Current low pivots
double ZZPrevHighCalc[]; // Previous high pivots
double ZZPrevLowCalc[]; // Previous low pivots
double ZZHighMap[];
double ZZLowMap[];
int ZZLastHighPos = -1;
int ZZLastLowPos = -1;
double ZZLastHighVal = 0;
double ZZLastLowVal = 0;
ENUM_XU_STATE g_continuityState = STATE_NEUTRAL;
int g_continuityStartBar = -1;
double g_continuityStartPrice = 0;
int g_continuityDuration = 0;
bool g_continuityActive = false;
int g_lastZZChangeBar = -1;
bool g_zzStateChanged = false;
string alertedTrend = "";
datetime alertedTrendTime = 0;
int alertedTrendBar = -1;
datetime alertResetTime = 0;
string IndicatorID;
static int InstanceCounter = 0;
string g_lastSymbol = "";
double g_cachedPoint = 0;
datetime g_lastPointRefresh = 0;
int g_lastRatesTotal = 0;
bool g_isFirstRun = true;
const int DEBUG_INTERVAL_SECONDS = 5;
const int MAX_DEBUG_PER_INTERVAL = 3;
#define DBG_PRINT(msg) \
if(DebugMode) \
{ \
static int _localDebugCounter = 0; \
static datetime _localLastTime = 0; \
datetime _now = TimeCurrent(); \
if(_now - _localLastTime >= DEBUG_INTERVAL_SECONDS) \
{ \
_localLastTime = _now; \
_localDebugCounter = 0; \
} \
if(_localDebugCounter < MAX_DEBUG_PER_INTERVAL) \
{ \
_localDebugCounter++; \
Print(__FUNCTION__, " | ", msg); \
} \
}
string GenerateUniqueID()
{
InstanceCounter++;
return "XUZZ1_" + IntegerToString(InstanceCounter) + "_" +
IntegerToString((int)TimeLocal()) + "_";
}
double GetSymbolPoint()
{
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
if(point > 0) return point;
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
if(digits > 0) return MathPow(10, -digits);
string symbol = _Symbol;
if(StringFind(symbol, "JPY") >= 0 || StringFind(symbol, "XAG") >= 0) return 0.01;
if(StringFind(symbol, "BTC") >= 0 || StringFind(symbol, "ETH") >= 0) return 0.1;
if(StringFind(symbol, "XAU") >= 0 || StringFind(symbol, "GOLD") >= 0) return 0.01;
if(StringFind(symbol, "SPX") >= 0 || StringFind(symbol, "NDX") >= 0) return 0.1;
if(StringFind(symbol, "US30") >= 0 || StringFind(symbol, "DJI") >= 0) return 0.1;
return 0.0001;
}
double GetCachedPoint()
{
datetime now = TimeCurrent();
if(now - g_lastPointRefresh > 60 || g_cachedPoint == 0)
{
g_cachedPoint = GetSymbolPoint();
g_lastPointRefresh = now;
if(DebugMode && g_lastPointRefresh > 0)
DBG_PRINT("Point value refreshed: " + DoubleToString(g_cachedPoint));
}
return g_cachedPoint;
}
bool CheckSymbolChange()
{
if(_Symbol != g_lastSymbol)
{
g_cachedPoint = GetSymbolPoint();
g_lastPointRefresh = TimeCurrent();
g_lastSymbol = _Symbol;
DBG_PRINT("Symbol changed to: " + _Symbol + " | Point: " + DoubleToString(g_cachedPoint));
ZZLastHighPos = -1; ZZLastLowPos = -1;
ZZLastHighVal = 0; ZZLastLowVal = 0;
g_continuityState = STATE_NEUTRAL;
g_continuityActive = false;
g_lastRatesTotal = 0;
g_isFirstRun = true;
return true;
}
return false;
}
void StorePreviousState(int rates_total)
{
if(rates_total <= 0) return;
int prevSizeHigh = ArraySize(ZZPrevHighCalc);
int prevSizeLow = ArraySize(ZZPrevLowCalc);
if(prevSizeHigh < rates_total)
{
ArrayResize(ZZPrevHighCalc, rates_total);
for(int i = prevSizeHigh; i < rates_total; i++)
ZZPrevHighCalc[i] = 0;
}
if(prevSizeLow < rates_total)
{
ArrayResize(ZZPrevLowCalc, rates_total);
for(int i = prevSizeLow; i < rates_total; i++)
ZZPrevLowCalc[i] = 0;
}
int copySizeHigh = MathMin(rates_total, ArraySize(ZZHighCalc));
for(int i = 0; i < copySizeHigh; i++)
ZZPrevHighCalc[i] = ZZHighCalc[i];
int copySizeLow = MathMin(rates_total, ArraySize(ZZLowCalc));
for(int i = 0; i < copySizeLow; i++)
ZZPrevLowCalc[i] = ZZLowCalc[i];
}
int DetectZZRecalcRange(int rates_total)
{
int earliestChange = rates_total;
g_zzStateChanged = false;
if(ArraySize(ZZPrevHighCalc) < rates_total || ArraySize(ZZPrevLowCalc) < rates_total)
{
ArrayResize(ZZPrevHighCalc, rates_total);
ArrayResize(ZZPrevLowCalc, rates_total);
ArrayInitialize(ZZPrevHighCalc, 0);
ArrayInitialize(ZZPrevLowCalc, 0);
for(int i = 0; i < rates_total; i++)
{
if(i < ArraySize(ZZHighCalc)) ZZPrevHighCalc[i] = ZZHighCalc[i];
if(i < ArraySize(ZZLowCalc)) ZZPrevLowCalc[i] = ZZLowCalc[i];
}
return 0;
}
int checkRange = MathMin(rates_total, ArraySize(ZZHighCalc));
checkRange = MathMin(checkRange, ArraySize(ZZPrevHighCalc));
for(int i = checkRange - 1; i >= 0; i--)
{
bool highChanged = false;
bool lowChanged = false;
if(i < ArraySize(ZZHighCalc) && i < ArraySize(ZZPrevHighCalc))
{
double diff = MathAbs(ZZHighCalc[i] - ZZPrevHighCalc[i]);
if(diff > GetCachedPoint() ||
(ZZHighCalc[i] == 0 && ZZPrevHighCalc[i] != 0) ||
(ZZHighCalc[i] != 0 && ZZPrevHighCalc[i] == 0))
{
highChanged = true;
}
}
if(i < ArraySize(ZZLowCalc) && i < ArraySize(ZZPrevLowCalc))
{
double diff = MathAbs(ZZLowCalc[i] - ZZPrevLowCalc[i]);
if(diff > GetCachedPoint() ||
(ZZLowCalc[i] == 0 && ZZPrevLowCalc[i] != 0) ||
(ZZLowCalc[i] != 0 && ZZPrevLowCalc[i] == 0))
{
lowChanged = true;
}
}
if(highChanged || lowChanged)
{
earliestChange = i;
g_zzStateChanged = true;
g_lastZZChangeBar = i;
if(DebugMode)
{
string changeType = highChanged ? (lowChanged ? "BOTH" : "HIGH") : "LOW";
Print("ZZ RECALC DETECTED at bar ", i, " | Type: ", changeType);
}
break;
}
}
return earliestChange;
}
void UpdateContinuityState(int currentBar, double price)
{
if(!EnableContinuity) return;
if(g_zzStateChanged && g_lastZZChangeBar >= 0 &&
MathAbs(currentBar - g_lastZZChangeBar) < ZZ_Depth)
{
if(LogContinuity && DebugMode)
Print("CONTINUITY RESET: ZigZag changed near bar ", currentBar);
g_continuityState = STATE_NEUTRAL;
g_continuityActive = false;
g_continuityDuration = 0;
return;
}
ENUM_XU_STATE detectedState = STATE_NEUTRAL;
int lastHigh = -1, lastLow = -1;
int searchRange = MathMin(ZZ_Depth, currentBar);
searchRange = MathMin(searchRange, ArraySize(ZZHighCalc));
searchRange = MathMin(searchRange, ArraySize(ZZLowCalc));
for(int i = 0; i < searchRange; i++)
{
if(i < ArraySize(ZZHighCalc) && ZZHighCalc[i] != 0 && lastHigh == -1)
lastHigh = i;
if(i < ArraySize(ZZLowCalc) && ZZLowCalc[i] != 0 && lastLow == -1)
lastLow = i;
if(lastHigh != -1 && lastLow != -1) break;
}
if(lastHigh != -1 && lastLow != -1)
{
detectedState = (lastHigh < lastLow) ? STATE_DOWN : STATE_UP;
}
else if(lastHigh != -1)
{
detectedState = STATE_DOWN;
}
else if(lastLow != -1)
{
detectedState = STATE_UP;
}
if(detectedState != STATE_NEUTRAL)
{
if(g_continuityState != detectedState)
{
g_continuityState = detectedState;
g_continuityStartBar = currentBar;
g_continuityStartPrice = price;
g_continuityDuration = 0;
g_continuityActive = true;
if(LogContinuity && DebugMode)
{
string stateName = (detectedState == STATE_UP) ? "UP" : "DOWN";
Print("CONTINUITY NEW STATE: ", stateName, " at bar ", currentBar);
}
}
else
{
g_continuityDuration++;
if(g_continuityDuration > MaxContinuityBars)
{
g_continuityActive = false;
if(LogContinuity && DebugMode)
Print("CONTINUITY EXPIRED: No new pivot for ", g_continuityDuration, " bars");
}
else
{
g_continuityActive = true;
}
}
}
else
{
g_continuityDuration = MathMax(0, g_continuityDuration - 1);
if(g_continuityDuration == 0)
g_continuityActive = false;
}
}
bool ResizeInternalBuffers(int size)
{
if(size <= 0) return false;
int oldHighSize = ArraySize(ZZHighMap);
int oldLowSize = ArraySize(ZZLowMap);
if(ArrayResize(ZZHighMap, size) < 0)
{
Print("ERROR: Failed to resize ZZHighMap to size ", size);
return false;
}
if(ArrayResize(ZZLowMap, size) < 0)
{
Print("ERROR: Failed to resize ZZLowMap to size ", size);
return false;
}
if(size > oldHighSize)
{
for(int i = oldHighSize; i < size; i++)
ZZHighMap[i] = 0;
}
if(size > oldLowSize)
{
for(int i = oldLowSize; i < size; i++)
ZZLowMap[i] = 0;
}
return true;
}
void UpdateConfirmationStatus(int rates_total)
{
if(rates_total <= 0) return;
int maxCheck = MathMin(ConfirmationBars + 5, rates_total);
maxCheck = MathMin(maxCheck, ArraySize(ZZTentativeBuffer));
maxCheck = MathMin(maxCheck, ArraySize(ZZConfirmedBuffer));
for(int i = 0; i < maxCheck; i++)
{
if(i >= ArraySize(ZZTentativeBuffer) || i >= ArraySize(ZZConfirmedBuffer))
break;
if(ZZTentativeBuffer[i] != ZZ_EMPTY_VALUE && ZZTentativeBuffer[i] != 0)
{
int barsOld = i;
if(barsOld >= ConfirmationBars && ConfirmationBars > 0)
{
ZZConfirmedBuffer[i] = ZZTentativeBuffer[i];
ZZTentativeBuffer[i] = ZZ_EMPTY_VALUE;
DBG_PRINT("Pivot at bar " + IntegerToString(i) + " CONFIRMED after " +
IntegerToString(barsOld) + " bars");
}
}
}
}
void ResetAllBuffers(int size)
{
if(size <= 0) return;
ArrayInitialize(ZZTentativeBuffer, ZZ_EMPTY_VALUE);
ArrayInitialize(ZZConfirmedBuffer, ZZ_EMPTY_VALUE);
ArrayInitialize(ZZHighCalc, 0);
ArrayInitialize(ZZLowCalc, 0);
ArrayInitialize(ZZHighMap, 0);
ArrayInitialize(ZZLowMap, 0);
ArrayInitialize(ZZPrevHighCalc, 0);
ArrayInitialize(ZZPrevLowCalc, 0);
g_lastRatesTotal = 0;
}
void ClearBufferRange(int start, int end, int rates_total)
{
int clearStart = MathMax(0, start);
int clearEnd = MathMin(rates_total - 1, end);
clearEnd = MathMin(clearEnd, ArraySize(ZZTentativeBuffer) - 1);
clearEnd = MathMin(clearEnd, ArraySize(ZZConfirmedBuffer) - 1);
clearEnd = MathMin(clearEnd, ArraySize(ZZHighCalc) - 1);
clearEnd = MathMin(clearEnd, ArraySize(ZZLowCalc) - 1);
clearEnd = MathMin(clearEnd, ArraySize(ZZHighMap) - 1);
clearEnd = MathMin(clearEnd, ArraySize(ZZLowMap) - 1);
if(clearStart > clearEnd) return;
for(int i = clearStart; i <= clearEnd; i++)
{
ZZTentativeBuffer[i] = ZZ_EMPTY_VALUE;
ZZConfirmedBuffer[i] = ZZ_EMPTY_VALUE;
ZZHighCalc[i] = 0;
ZZLowCalc[i] = 0;
ZZHighMap[i] = 0;
ZZLowMap[i] = 0;
}
}
int SafeArrayMax(const double &array[], int count, int start, int totalSize)
{
if(count <= 0 || start < 0 || start >= totalSize) return(-1);
if(start + count > totalSize) count = totalSize - start;
if(count <= 0) return(-1);
int max_idx = start;
int end = start + count;
for(int i = start + 1; i < end; i++)
if(array[i] > array[max_idx]) max_idx = i;
return max_idx;
}
int SafeArrayMin(const double &array[], int count, int start, int totalSize)
{
if(count <= 0 || start < 0 || start >= totalSize) return(-1);
if(start + count > totalSize) count = totalSize - start;
if(count <= 0) return(-1);
int min_idx = start;
int end = start + count;
for(int i = start + 1; i < end; i++)
if(array[i] < array[min_idx]) min_idx = i;
return min_idx;
}
double CalculateAverage(const double &data[], int start, int depth, int rates_total)
{
double sum = 0;
int validCount = 0;
if(start < 0 || start >= rates_total) return 0;
for(int k = 1; k <= depth && (start + k) < rates_total; k++)
{
if(start + k >= 0 && start + k < ArraySize(data))
{
sum += data[start + k];
validCount++;
}
}
return (validCount > 0) ? sum / validCount : 0;
}
int OnInit()
{
// код доступен только после оплаты
}
IndicatorID = GenerateUniqueID();
if(ZZ_Depth < 2)
{
Alert("ERROR: ZZ_Depth must be >= 2. You provided: ", ZZ_Depth);
return(INIT_PARAMETERS_INCORRECT);
}
if(ZZ_Deviation <= 0)
{
Alert("ERROR: ZZ_Deviation must be positive");
return(INIT_PARAMETERS_INCORRECT);
}
if(ZZ_Backstep < 0 || ZZ_Backstep >= ZZ_Depth)
{
Alert("ERROR: ZZ_Backstep must satisfy 0 <= backstep < depth");
Показано первые 50% кода (символов: 22866)