Vizion-Trading-EA/VZ_Sessions.mq5
SahrJohn SahrJohn 526860b9cd EA: sync live build (Jul-Nov 2026) — trade report direction/setup fix, VZ indicators, risk modules
- AIGateway/profitgtx: report_trade takes direction and setup from the position's
  opening deal ("dir_src":"entry"); the closing deal inverted every direction and
  restarts lost the setup (99% "auto")
- add MATheory, RiskGuards, RiskSizing, TradePolicy (setup blocklist, strict AI gate)
- add VZ_Core + VZ_Features/MFIB/Regime/Setups/Sessions indicators, VZ_FeaturesExport
  service, VZ_DumpMA, VZ_TogglePause
- margin-aware sizing, news, labels and session updates since 2026-07-14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:48:22 -06:00
//+------------------------------------------------------------------+
//| VZ_Sessions.mq5 |
//| QuarterTheory x VIZION |
//| |
//| Session clock, the levels each session leaves behind, and the |
//| AMD (accumulation / manipulation / distribution) cycle built on |
//| top of them. |
//| |
//| Everything is computed on a fixed anchor timeframe (default M5) |
//| rather than the chart timeframe, so the output is identical no |
//| matter what chart the consumer is attached to. |
//| |
//| Session windows are defined in GMT. Broker server time is |
//| converted with a fixed base offset plus an optional EU/US DST |
//| rule. Nothing reads wall-clock time — every value derives from |
//| bar timestamps, so live and Strategy Tester agree. |
//| |
//| ── Look-ahead discipline ───────────────────────────────────── |
//| While a session is open its high/low is the running extreme up |
//| to that bar and nothing further; it freezes when the session |
//| closes. London/NY opens stay EMPTY_VALUE until they happen. |
//| |
//| AMD_PHASE is what was knowable at each bar, written once and |
//| never revised. AMD_PHASE_RETRO is the hindsight labelling and |
//| back-fills the manipulation leg onto bars that looked like |
//| nothing at the time. Consumers read AMD_PHASE. RETRO is for |
//| looking at the chart — the visual gap between the two arrow |
//| markers is the real-world confirmation lag. |
//+------------------------------------------------------------------+
#property copyright "QuarterTheory x VIZION"
#property version "1.10"
#property strict
#property indicator_chart_window
#property indicator_buffers 19
#property indicator_plots 19
#include "VZ_SessionsDefs.mqh"
//--- 1: session id (data only)
#property indicator_label1 "SessionID"
#property indicator_type1 DRAW_NONE
//--- 2/3: Asia accumulation range
#property indicator_label2 "AsiaHigh"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrGold
#property indicator_width2 1
#property indicator_label3 "AsiaLow"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrGold
#property indicator_width3 1
//--- 4/5: running extremes of the live session
#property indicator_label4 "SessionHigh"
#property indicator_type4 DRAW_LINE
#property indicator_color4 clrSteelBlue
#property indicator_style4 STYLE_DOT
#property indicator_label5 "SessionLow"
#property indicator_type5 DRAW_LINE
#property indicator_color5 clrSteelBlue
#property indicator_style5 STYLE_DOT
//--- 6/7/8: previous day
#property indicator_label6 "PrevDayHigh"
#property indicator_type6 DRAW_LINE
#property indicator_color6 clrIndianRed
#property indicator_style6 STYLE_DASH
#property indicator_label7 "PrevDayLow"
#property indicator_type7 DRAW_LINE
#property indicator_color7 clrIndianRed
#property indicator_style7 STYLE_DASH
#property indicator_label8 "PrevDayClose"
#property indicator_type8 DRAW_LINE
#property indicator_color8 clrDimGray
#property indicator_style8 STYLE_DASHDOT
//--- 9/10: session opens
#property indicator_label9 "LondonOpen"
#property indicator_type9 DRAW_LINE
#property indicator_color9 clrMediumSeaGreen
#property indicator_label10 "NYOpen"
#property indicator_type10 DRAW_LINE
#property indicator_color10 clrMediumPurple
//--- 11: Asia range / daily ATR (data only)
#property indicator_label11 "AsiaRangeATR"
#property indicator_type11 DRAW_NONE
//--- 12..16: AMD scalars (data only)
#property indicator_label12 "AMD_Phase"
#property indicator_type12 DRAW_NONE
#property indicator_label13 "AMD_PhaseRetro"
#property indicator_type13 DRAW_NONE
#property indicator_label14 "AMD_Bias"
#property indicator_type14 DRAW_NONE
#property indicator_label15 "AMD_Confidence"
#property indicator_type15 DRAW_NONE
#property indicator_label16 "AMD_SweepLevel"
#property indicator_type16 DRAW_NONE
//--- 17: invalidation level
#property indicator_label17 "AMD_Invalidation"
#property indicator_type17 DRAW_LINE
#property indicator_color17 clrOrangeRed
#property indicator_style17 STYLE_DOT
//--- 18/19: markers — confirmed vs hindsight
#property indicator_label18 "AMD_Confirmed"
#property indicator_type18 DRAW_ARROW
#property indicator_color18 clrAqua
#property indicator_width18 2
#property indicator_label19 "AMD_SweepRetro"
#property indicator_type19 DRAW_ARROW
#property indicator_color19 clrDimGray
#property indicator_width19 1
//+------------------------------------------------------------------+
//| Inputs |
//+------------------------------------------------------------------+
input ENUM_TIMEFRAMES InpAnchorTF = PERIOD_M5; // Anchor timeframe (all output derives from this)
input int InpHistoryDays = 60; // Days of history to compute
input int InpATRPeriodD1 = 14; // ATR period (D1) for range ratios
input group "Broker clock"
// 99 = auto-detect at init from TimeGMT() vs TimeTradeServer(). Auto-detect is
// unreliable inside the Strategy Tester — pin the real value once you know it.
input int InpBrokerGMTOffset = 99; // Broker base GMT offset, hours (99 = auto)
input ENUM_VZ_DST InpBrokerDST = VZ_DST_EU; // Broker daylight-saving rule
input group "Session windows (GMT, whole hours)"
// Defaults tile the full 24h with no gaps:
// 23-07 Asia | 07-12 London | 12-16 Overlap | 16-21 NY | 21-23 Off
input int InpAsiaStartGMT = 23;
input int InpAsiaEndGMT = 7;
input int InpLondonStartGMT = 7;
input int InpLondonEndGMT = 16;
input int InpNYStartGMT = 12; // FX convention, not the 14:30 equity open
input int InpNYEndGMT = 21;
input int InpDayStartGMT = 0; // Boundary for "previous day" H/L/C
input group "AMD detection"
// Every threshold below is a starting point, not a calibrated value. Review
// the chart markers for a few weeks before trusting or wiring any of it.
input double InpMaxAsiaRangeATR = 0.55; // Asia range / ATR(D1) above this = not accumulation
input double InpSweepBufferPct = 0.05; // Sweep must exceed the boundary by this fraction of the Asia range
input int InpManipWindowHours = 6; // Hours after Asia close in which a sweep still counts
input int InpMaxReclaimBars = 12; // Anchor bars allowed between sweep and reclaim
input double InpDistDisplaceATR = 0.35; // Displacement from sweep extreme (x ATR D1) confirming distribution
//+------------------------------------------------------------------+
//| Buffers |
//+------------------------------------------------------------------+
double BufSessionID[];
double BufAsiaHigh[];
double BufAsiaLow[];
double BufSessionHigh[];
double BufSessionLow[];
double BufPrevDayHigh[];
double BufPrevDayLow[];
double BufPrevDayClose[];
double BufLondonOpen[];
double BufNYOpen[];
double BufAsiaRangeATR[];
double BufAmdPhase[];
double BufAmdPhaseRetro[];
double BufAmdBias[];
double BufAmdConfidence[];
double BufAmdSweepLevel[];
double BufAmdInvalidation[];
double BufAmdMarkConf[];
double BufAmdMarkRetro[];
//+------------------------------------------------------------------+
//| Anchor-timeframe result table |
//+------------------------------------------------------------------+
struct AnchorRow
{
datetime t;
double sid;
double asiaH, asiaL;
double sesH, sesL;
double pdH, pdL, pdC;
double lonO, nyO;
double arATR;
double amdPhase, amdRetro;
double amdBias, amdConf;
double sweepLevel, invalidation;
double markConf, markRetro;
};
AnchorRow g_rows[];
int g_rowCount = 0;
datetime g_lastAnchor = 0;
bool g_remapAll = true;
int g_hATR_D1 = INVALID_HANDLE;
int g_baseOff = 0; // broker base GMT offset in hours, DST excluded
// Windows as minutes-from-midnight GMT
int g_asiaS, g_asiaE, g_lonS, g_lonE, g_nyS, g_nyE, g_dayS;
//+------------------------------------------------------------------+
//| Calendar helpers |
//+------------------------------------------------------------------+
int DaysInMonth(const int y, const int m)
{
int d[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
if(m == 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0))
return 29;
return d[m - 1];
}
datetime MakeGMT(const int y, const int mon, const int day, const int hour)
{
MqlDateTime t;
ZeroMemory(t);
t.year = y; t.mon = mon; t.day = day; t.hour = hour;
return StructToTime(t);
}
// Nth Sunday of a month at a given UTC hour (n = 1 for first, 2 for second...).
datetime NthSunday(const int y, const int mon, const int n, const int hour)
{
int found = 0;
int dim = DaysInMonth(y, mon);
for(int d = 1; d <= dim; ++d)
{
datetime dt = MakeGMT(y, mon, d, hour);
MqlDateTime chk;
TimeToStruct(dt, chk);
if(chk.day_of_week == 0)
{
found++;
if(found == n) return dt;
}
}
return 0;
}
datetime LastSunday(const int y, const int mon, const int hour)
{
int dim = DaysInMonth(y, mon);
for(int d = dim; d >= 1; --d)
{
datetime dt = MakeGMT(y, mon, d, hour);
MqlDateTime chk;
TimeToStruct(dt, chk);
if(chk.day_of_week == 0) return dt;
}
return 0;
}
// EU: last Sunday of March 01:00 UTC .. last Sunday of October 01:00 UTC.
bool IsEUDST(const datetime gmt)
{
MqlDateTime t;
TimeToStruct(gmt, t);
datetime s = LastSunday(t.year, 3, 1);
datetime e = LastSunday(t.year, 10, 1);
return (gmt >= s && gmt < e);
}
// US: 2nd Sunday of March 02:00 EST (07:00 UTC) .. 1st Sunday of November
// 02:00 EDT (06:00 UTC).
bool IsUSDST(const datetime gmt)
{
MqlDateTime t;
TimeToStruct(gmt, t);
datetime s = NthSunday(t.year, 3, 2, 7);
datetime e = NthSunday(t.year, 11, 1, 6);
return (gmt >= s && gmt < e);
}
// Server -> GMT. DST is evaluated against the approximate GMT obtained from
// the base offset alone; that can be off by at most one hour in the hour
// surrounding a transition, which no session boundary depends on.
int OffsetSeconds(const datetime server)
{
int base = g_baseOff * 3600;
datetime approx = server - base;
bool dst = false;
if(InpBrokerDST == VZ_DST_EU) dst = IsEUDST(approx);
else if(InpBrokerDST == VZ_DST_US) dst = IsUSDST(approx);
return base + (dst ? 3600 : 0);
}
datetime ToGMT(const datetime server) { return server - OffsetSeconds(server); }
int MinuteOfDay(const datetime g)
{
MqlDateTime t;
TimeToStruct(g, t);
return t.hour * 60 + t.min;
}
datetime DateOnly(const datetime g) { return (datetime)(g - (g % 86400)); }
// Half-open [start, end); handles windows that wrap past midnight.
bool InWindow(const int m, const int s, const int e)
{
if(s == e) return false;
if(s < e) return (m >= s && m < e);
return (m >= s || m < e);
}
int SessionOf(const int m)
{
bool lon = InWindow(m, g_lonS, g_lonE);
bool ny = InWindow(m, g_nyS, g_nyE);
if(lon && ny) return VZ_SESS_OVERLAP;
if(lon) return VZ_SESS_LONDON;
if(ny) return VZ_SESS_NY;
if(InWindow(m, g_asiaS, g_asiaE)) return VZ_SESS_ASIA;
return VZ_SESS_OFF;
}
// The AMD cycle is named for the day its Asia session *ends*, so when the Asia
// window wraps midnight the pre-midnight portion belongs to the next date.
datetime CycleDay(const datetime g)
{
datetime d = DateOnly(g);
if(g_asiaS > g_asiaE && MinuteOfDay(g) >= g_asiaS)
d += 86400;
return d;
}
datetime DayBucket(const datetime g)
{
datetime d = DateOnly(g);
if(MinuteOfDay(g) < g_dayS)
d -= 86400;
return d;
}
double AtrD1At(const datetime t)
{
double b[];
if(CopyBuffer(g_hATR_D1, 0, t, 1, b) < 1) return 0.0;
return b[0];
}
double Clamp01(const double x) { return MathMax(0.0, MathMin(1.0, x)); }
//+------------------------------------------------------------------+
//| Build the anchor-timeframe table in one forward pass |
//+------------------------------------------------------------------+
bool BuildTables()
{
MqlRates r[];
ArraySetAsSeries(r, false); // oldest first
int barsPerDay = (int)(86400 / PeriodSeconds(InpAnchorTF));
int want = InpHistoryDays * barsPerDay + 600;
int n = CopyRates(_Symbol, InpAnchorTF, 0, want, r);
if(n < 100) return false;
if(ArrayResize(g_rows, n) != n) return false;
g_rowCount = n;
int manipWindowBars = (int)((double)InpManipWindowHours * 3600.0 / PeriodSeconds(InpAnchorTF));
if(manipWindowBars < 1) manipWindowBars = 1;
// ── session state ──
datetime cycle = 0, bucket = 0;
int sidPrev = -1;
double asiaH = 0.0, asiaL = 0.0;
bool asiaStarted = false, asiaFrozen = false;
double sesH = 0.0, sesL = 0.0;
double dayH = 0.0, dayL = 0.0, dayC = 0.0;
bool dayStarted = false;
double pdH = EMPTY_VALUE, pdL = EMPTY_VALUE, pdC = EMPTY_VALUE;
double lonO = EMPTY_VALUE, nyO = EMPTY_VALUE;
double arATR = EMPTY_VALUE;
// ── AMD state ──
int phase = VZ_AMD_NONE;
int bias = 0;
double conf = 0.0;
double cycAtr = 0.0;
double sweepLevel = EMPTY_VALUE, sweepExt = EMPTY_VALUE;
int sweepDir = 0, sweepBar = -1, sweepExtBar = -1;
bool inSweep = false, manipDone = false;
int barsSinceAsia = 0;
for(int i = 0; i < n; ++i)
{
datetime ts = r[i].time;
datetime g = ToGMT(ts);
int m = MinuteOfDay(g);
int sid = SessionOf(m);
double markConf = EMPTY_VALUE, markRetro = EMPTY_VALUE;
// ---- previous-day levels ----
datetime b = DayBucket(g);
if(b != bucket)
{
if(dayStarted) { pdH = dayH; pdL = dayL; pdC = dayC; }
dayH = r[i].high; dayL = r[i].low; dayC = r[i].close;
dayStarted = true;
bucket = b;
}
else
{
dayH = MathMax(dayH, r[i].high);
dayL = MathMin(dayL, r[i].low);
dayC = r[i].close;
}
// ---- AMD cycle rollover (coincides with Asia open by construction) ----
datetime c = CycleDay(g);
if(c != cycle)
{
cycle = c;
asiaStarted = false;
asiaFrozen = false;
asiaH = 0.0; asiaL = 0.0;
lonO = EMPTY_VALUE;
nyO = EMPTY_VALUE;
arATR = EMPTY_VALUE;
phase = VZ_AMD_NONE;
bias = 0;
conf = 0.0;
cycAtr = 0.0;
sweepLevel = EMPTY_VALUE;
sweepExt = EMPTY_VALUE;
sweepDir = 0; sweepBar = -1; sweepExtBar = -1;
inSweep = false; manipDone = false;
barsSinceAsia = 0;
}
// ---- Asia accumulation range: running, then frozen at close ----
bool inAsia = InWindow(m, g_asiaS, g_asiaE);
if(inAsia)
{
if(!asiaStarted)
{
asiaH = r[i].high; asiaL = r[i].low;
asiaStarted = true;
}
else
{
asiaH = MathMax(asiaH, r[i].high);
asiaL = MathMin(asiaL, r[i].low);
}
phase = VZ_AMD_ACCUMULATION;
}
else if(asiaStarted && !asiaFrozen)
{
// Asia just closed — freeze the range and gate on its width.
asiaFrozen = true;
cycAtr = AtrD1At(ts);
arATR = (cycAtr > 0.0) ? (asiaH - asiaL) / cycAtr : EMPTY_VALUE;
// A range wider than a normal day's ATR fraction was a trend, not
// accumulation. ATR unavailable = don't gate, just proceed.
if(cycAtr > 0.0 && arATR > InpMaxAsiaRangeATR)
phase = VZ_AMD_NO_SETUP;
else
phase = VZ_AMD_PENDING;
}
// ---- session opens: first bar inside the window this cycle ----
if(lonO == EMPTY_VALUE && InWindow(m, g_lonS, g_lonE)) lonO = r[i].open;
if(nyO == EMPTY_VALUE && InWindow(m, g_nyS, g_nyE)) nyO = r[i].open;
// ---- AMD state machine (only after Asia has closed cleanly) ----
if(asiaFrozen && phase != VZ_AMD_NO_SETUP)
{
barsSinceAsia++;
double range = asiaH - asiaL;
double buf = MathMax(range * InpSweepBufferPct, _Point * 2.0);
if(phase == VZ_AMD_PENDING && barsSinceAsia <= manipWindowBars)
{
if(!inSweep)
{
// Look for an excursion beyond either boundary.
if(r[i].high > asiaH + buf)
{
inSweep = true; sweepDir = 1;
sweepLevel = asiaH; sweepExt = r[i].high;
sweepBar = i; sweepExtBar = i;
}
else if(r[i].low < asiaL - buf)
{
inSweep = true; sweepDir = -1;
sweepLevel = asiaL; sweepExt = r[i].low;
sweepBar = i; sweepExtBar = i;
}
}
else
{
// Track how far the excursion ran.
if(sweepDir > 0 && r[i].high > sweepExt) { sweepExt = r[i].high; sweepExtBar = i; }
if(sweepDir < 0 && r[i].low < sweepExt) { sweepExt = r[i].low; sweepExtBar = i; }
bool reclaimed = (sweepDir > 0) ? (r[i].close < asiaH) : (r[i].close > asiaL);
int age = i - sweepBar;
if(reclaimed && age <= InpMaxReclaimBars)
{
// Manipulation confirmed HERE — not at the sweep bar.
phase = VZ_AMD_MANIPULATION;
bias = -sweepDir;
manipDone = true;
inSweep = false;
double excursion = (sweepDir > 0) ? (sweepExt - asiaH) : (asiaL - sweepExt);
double tight = (cycAtr > 0.0 && InpMaxAsiaRangeATR > 0.0)
? Clamp01(1.0 - (arATR / InpMaxAsiaRangeATR)) : 0.5;
double depth = (range > 0.0) ? Clamp01(excursion / (0.25 * range)) : 0.0;
double speed = Clamp01(1.0 - ((double)age / (double)InpMaxReclaimBars));
double timing = Clamp01(1.0 - ((double)barsSinceAsia / (double)manipWindowBars));
conf = 100.0 * (0.30 * tight + 0.25 * depth + 0.25 * speed + 0.20 * timing);
markConf = (bias > 0) ? r[i].low : r[i].high;
// Hindsight: back-fill the whole sweep leg as manipulation,
// and mark the extreme bar. This is the repainting half.
for(int j = sweepBar; j <= i; ++j)
g_rows[j].amdRetro = (double)VZ_AMD_MANIPULATION;
if(sweepExtBar >= 0)
g_rows[sweepExtBar].markRetro = (bias > 0) ? r[sweepExtBar].low
: r[sweepExtBar].high;
}
else if(age > InpMaxReclaimBars)
{
// Broke out and kept going: a trend day, not a Judas swing.
// Deliberately no bias — let the trend machinery own this.
phase = VZ_AMD_EXPANSION;
bias = 0;
inSweep = false;
}
}
}
else if(phase == VZ_AMD_PENDING && barsSinceAsia > manipWindowBars)
{
// Window elapsed with no qualifying sweep.
phase = VZ_AMD_NONE;
}
else if(manipDone && (phase == VZ_AMD_MANIPULATION || phase == VZ_AMD_DISTRIBUTION))
{
// Invalidation: price closed back through the sweep extreme.
bool dead = (bias > 0) ? (r[i].close < sweepExt) : (r[i].close > sweepExt);
if(dead)
{
phase = VZ_AMD_INVALIDATED;
bias = 0;
}
else if(phase == VZ_AMD_MANIPULATION)
{
double disp = (bias > 0) ? (r[i].close - sweepExt) : (sweepExt - r[i].close);
bool crossed = (bias > 0) ? (r[i].close > asiaH) : (r[i].close < asiaL);
if(crossed || (cycAtr > 0.0 && disp > InpDistDisplaceATR * cycAtr))
phase = VZ_AMD_DISTRIBUTION;
}
}
}
// ---- running extremes of whichever session this bar sits in ----
if(sid != sidPrev)
{
sesH = r[i].high; sesL = r[i].low;
sidPrev = sid;
}
else
{
sesH = MathMax(sesH, r[i].high);
sesL = MathMin(sesL, r[i].low);
}
g_rows[i].t = ts;
g_rows[i].sid = (double)sid;
g_rows[i].asiaH = asiaStarted ? asiaH : EMPTY_VALUE;
g_rows[i].asiaL = asiaStarted ? asiaL : EMPTY_VALUE;
g_rows[i].sesH = sesH;
g_rows[i].sesL = sesL;
g_rows[i].pdH = pdH;
g_rows[i].pdL = pdL;
g_rows[i].pdC = pdC;
g_rows[i].lonO = lonO;
g_rows[i].nyO = nyO;
g_rows[i].arATR = arATR;
g_rows[i].amdPhase = (double)phase;
g_rows[i].amdRetro = (double)phase; // may be overwritten by back-fill
g_rows[i].amdBias = (double)bias;
g_rows[i].amdConf = manipDone ? conf : 0.0;
g_rows[i].sweepLevel = sweepLevel;
g_rows[i].invalidation = manipDone ? sweepExt : EMPTY_VALUE;
g_rows[i].markConf = markConf;
g_rows[i].markRetro = markRetro;
}
return true;
}
// Last anchor row at or before t; -1 when t predates the table.
int FindRow(const datetime t)
{
if(g_rowCount == 0 || t < g_rows[0].t) return -1;
int lo = 0, hi = g_rowCount - 1;
while(lo < hi)
{
int mid = (lo + hi + 1) / 2;
if(g_rows[mid].t <= t) lo = mid;
else hi = mid - 1;
}
return lo;
}
void SetEmpty(const int i)
{
BufSessionID[i] = EMPTY_VALUE;
BufAsiaHigh[i] = EMPTY_VALUE;
BufAsiaLow[i] = EMPTY_VALUE;
BufSessionHigh[i] = EMPTY_VALUE;
BufSessionLow[i] = EMPTY_VALUE;
BufPrevDayHigh[i] = EMPTY_VALUE;
BufPrevDayLow[i] = EMPTY_VALUE;
BufPrevDayClose[i] = EMPTY_VALUE;
BufLondonOpen[i] = EMPTY_VALUE;
BufNYOpen[i] = EMPTY_VALUE;
BufAsiaRangeATR[i] = EMPTY_VALUE;
BufAmdPhase[i] = (double)VZ_AMD_NONE;
BufAmdPhaseRetro[i] = (double)VZ_AMD_NONE;
BufAmdBias[i] = 0.0;
BufAmdConfidence[i] = 0.0;
BufAmdSweepLevel[i] = EMPTY_VALUE;
BufAmdInvalidation[i] = EMPTY_VALUE;
BufAmdMarkConf[i] = EMPTY_VALUE;
BufAmdMarkRetro[i] = EMPTY_VALUE;
}
//+------------------------------------------------------------------+
//| OnInit |
//+------------------------------------------------------------------+
int OnInit()
{
SetIndexBuffer(VZ_BUF_SESSION_ID, BufSessionID, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_ASIA_HIGH, BufAsiaHigh, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_ASIA_LOW, BufAsiaLow, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_SESSION_HIGH, BufSessionHigh, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_SESSION_LOW, BufSessionLow, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_PREV_DAY_HIGH, BufPrevDayHigh, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_PREV_DAY_LOW, BufPrevDayLow, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_PREV_DAY_CLOSE, BufPrevDayClose, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_LONDON_OPEN, BufLondonOpen, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_NY_OPEN, BufNYOpen, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_ASIA_RANGE_ATR, BufAsiaRangeATR, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_PHASE, BufAmdPhase, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_PHASE_RETRO, BufAmdPhaseRetro, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_BIAS, BufAmdBias, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_CONFIDENCE, BufAmdConfidence, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_SWEEP_LEVEL, BufAmdSweepLevel, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_INVALIDATION, BufAmdInvalidation, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_MARK_CONF, BufAmdMarkConf, INDICATOR_DATA);
SetIndexBuffer(VZ_BUF_AMD_MARK_RETRO, BufAmdMarkRetro, INDICATOR_DATA);
for(int p = 0; p < VZ_BUF_COUNT; ++p)
PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(VZ_BUF_AMD_MARK_CONF, PLOT_ARROW, 233); // filled up-arrow
PlotIndexSetInteger(VZ_BUF_AMD_MARK_RETRO, PLOT_ARROW, 159); // small dot
IndicatorSetString(INDICATOR_SHORTNAME,
"VZ_Sessions(" + EnumToString(InpAnchorTF) + ")");
IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
// Window sanity: whole hours, 0..24.
if(InpAsiaStartGMT < 0 || InpAsiaStartGMT > 24 ||
InpAsiaEndGMT < 0 || InpAsiaEndGMT > 24 ||
InpLondonStartGMT < 0 || InpLondonStartGMT > 24 ||
InpLondonEndGMT < 0 || InpLondonEndGMT > 24 ||
InpNYStartGMT < 0 || InpNYStartGMT > 24 ||
InpNYEndGMT < 0 || InpNYEndGMT > 24 ||
InpDayStartGMT < 0 || InpDayStartGMT > 23)
{
Print("VZ_Sessions: session window hours must be 0..24");
return INIT_PARAMETERS_INCORRECT;
}
if(InpMaxReclaimBars < 1 || InpManipWindowHours < 1 ||
InpSweepBufferPct < 0.0 || InpMaxAsiaRangeATR <= 0.0)
{
Print("VZ_Sessions: AMD detection parameters out of range");
return INIT_PARAMETERS_INCORRECT;
}
g_asiaS = InpAsiaStartGMT * 60;
g_asiaE = InpAsiaEndGMT * 60;
g_lonS = InpLondonStartGMT * 60;
g_lonE = InpLondonEndGMT * 60;
g_nyS = InpNYStartGMT * 60;
g_nyE = InpNYEndGMT * 60;
g_dayS = InpDayStartGMT * 60;
// Broker clock
if(InpBrokerGMTOffset == 99)
{
datetime srv = TimeTradeServer();
datetime utc = TimeGMT();
int raw = (int)MathRound((double)(srv - utc) / 3600.0);
bool dst = false;
if(InpBrokerDST == VZ_DST_EU) dst = IsEUDST(utc);
else if(InpBrokerDST == VZ_DST_US) dst = IsUSDST(utc);
g_baseOff = raw - (dst ? 1 : 0);
PrintFormat("VZ_Sessions: auto-detected broker base GMT offset = %+d h "
"(raw %+d, DST rule %s currently %s)",
g_baseOff, raw, EnumToString(InpBrokerDST), dst ? "ON" : "OFF");
if(MQLInfoInteger(MQL_TESTER))
Print("VZ_Sessions: WARNING — auto-detect is unreliable in the "
"Strategy Tester. Pin InpBrokerGMTOffset to the real value.");
}
else
{
g_baseOff = InpBrokerGMTOffset;
PrintFormat("VZ_Sessions: broker base GMT offset pinned to %+d h (DST rule %s)",
g_baseOff, EnumToString(InpBrokerDST));
}
g_hATR_D1 = iATR(_Symbol, PERIOD_D1, InpATRPeriodD1);
if(g_hATR_D1 == INVALID_HANDLE)
{
Print("VZ_Sessions: failed to create D1 ATR handle");
return INIT_FAILED;
}
g_rowCount = 0;
g_lastAnchor = 0;
g_remapAll = true;
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
if(g_hATR_D1 != INVALID_HANDLE)
IndicatorRelease(g_hATR_D1);
g_hATR_D1 = INVALID_HANDLE;
}
//+------------------------------------------------------------------+
//| OnCalculate |
//+------------------------------------------------------------------+
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 < 10) return 0;
// Rebuild the anchor table whenever a new anchor bar has formed. One linear
// pass over ~InpHistoryDays of anchor bars — cheap enough to redo wholesale
// rather than maintain incrementally, and the retro back-fill needs the
// whole array addressable anyway.
datetime newest = (datetime)SeriesInfoInteger(_Symbol, InpAnchorTF, SERIES_LASTBAR_DATE);
if(newest != g_lastAnchor || g_rowCount == 0)
{
if(!BuildTables())
return prev_calculated; // anchor history not ready yet; try next tick
g_lastAnchor = newest;
g_remapAll = true;
}
int start = (prev_calculated > 1 && !g_remapAll) ? prev_calculated - 1 : 0;
g_remapAll = false;
int period_sec = PeriodSeconds(_Period);
for(int i = start; i < rates_total; ++i)
{
// Value as of the end of this chart bar. For the forming bar this
// resolves to the most recent completed anchor bar, i.e. "as of now".
int k = FindRow(time[i] + period_sec - 1);
if(k < 0)
{
SetEmpty(i);
continue;
}
BufSessionID[i] = g_rows[k].sid;
BufAsiaHigh[i] = g_rows[k].asiaH;
BufAsiaLow[i] = g_rows[k].asiaL;
BufSessionHigh[i] = g_rows[k].sesH;
BufSessionLow[i] = g_rows[k].sesL;
BufPrevDayHigh[i] = g_rows[k].pdH;
BufPrevDayLow[i] = g_rows[k].pdL;
BufPrevDayClose[i] = g_rows[k].pdC;
BufLondonOpen[i] = g_rows[k].lonO;
BufNYOpen[i] = g_rows[k].nyO;
BufAsiaRangeATR[i] = g_rows[k].arATR;
BufAmdPhase[i] = g_rows[k].amdPhase;
BufAmdPhaseRetro[i] = g_rows[k].amdRetro;
BufAmdBias[i] = g_rows[k].amdBias;
BufAmdConfidence[i] = g_rows[k].amdConf;
BufAmdSweepLevel[i] = g_rows[k].sweepLevel;
BufAmdInvalidation[i] = g_rows[k].invalidation;
BufAmdMarkConf[i] = g_rows[k].markConf;
BufAmdMarkRetro[i] = g_rows[k].markRetro;
}
return rates_total;
}
//+------------------------------------------------------------------+