//+------------------------------------------------------------------+
//|                                              SK-System Suite.mq5 |
//| Unofficial tool by a fan - not affiliated with, sponsored or     |
//| endorsed by Stefan Kassing or Crypto Wall Street.                |
//|                                                                  |
//| MQL5 port of the Pine Script v6 indicator "SK-System Suite".     |
//|                                                                  |
//| Five parts on one chart: the SK sequences, the all-time high,    |
//| liquidation levels, imbalances and moving averages.              |
//|                                                                  |
//| SK sequences - found by itself on every chart, nested:           |
//| - Long: the largest long SK sequence from the all-time low that  |
//|   is not complete / failed yet (dark green);                     |
//| - Short: the same, short from the all-time high (red);           |
//| - Long 2: from the lowest low after the all-time high (lime) -   |
//|   not drawn when that low is the all-time low itself ("= Long"); |
//| - Short 2: from the highest high after that low (orange).        |
//| Each is played on the finest candles there are for each stretch  |
//| of time: weekly for the whole history, then D1, H4, H1, M30,     |
//| M15, M5 and M1 for their last 1000 candles each.                 |
//|                                                                  |
//| A sequence from 0 and A (long - short mirrored):                 |
//| - forming: every higher high moves A up, the SK box (0.5 - 0.667 |
//|   of 0 -> A, dashed) grows until the price comes near 0.5:       |
//|   confirmed, A fixed;                                            |
//| - B: the lowest low after A until a high beyond A - that high    |
//|   activates it: trend break line, extension box 1.618 - 2 from B |
//|   ("C" in its middle) and the next correction box;               |
//| - the extension's 1.618 reached: the GKL box (0 -> the high);    |
//| - failed: after activation the price clearly beyond B; complete: |
//|   back in the GKL box, then the 1.618 again; invalid: beyond 0   |
//|   before activation. Failed or complete: the next larger         |
//|   sequence takes over until one is still open.                   |
//+------------------------------------------------------------------+
#property copyright "Unofficial fan tool"
#property version   "1.00"
#property description "SK-System Suite (unofficial tool for Crypto Wall Street fans) - MQL5 port"
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots   4
#property indicator_type1   DRAW_LINE
#property indicator_type2   DRAW_LINE
#property indicator_type3   DRAW_LINE
#property indicator_type4   DRAW_LINE
#property indicator_label1  "MA 1"
#property indicator_label2  "MA 2"
#property indicator_label3  "MA 3"
#property indicator_label4  "MA 4"

//---------------------------------------------------------------- enums
enum ENUM_SK_MA    { SK_EMA = 0, // EMA
                     SK_SMA = 1  // SMA
                   };
enum ENUM_IMB_FILL { IMB_CLOSE = 0, // Close: a candle closed beyond its middle line
                     IMB_FULL  = 1, // Full: the price went through the whole gap
                     IMB_MID   = 2, // Mid: the price reached its middle line
                     IMB_NEVER = 3  // Never: it stays
                   };
enum ENUM_IMB_PICK { IMB_NEAREST = 0, // Nearest
                     IMB_NEWEST  = 1  // Newest
                   };
enum ENUM_IMB_COUNT { IC_1 = 1,   // 1
                      IC_2 = 2,   // 2
                      IC_3 = 3,   // 3
                      IC_5 = 5,   // 5
                      IC_10 = 10, // 10
                      IC_20 = 20, // 20
                      IC_ALL = 0  // all open ones
                    };

//---------------------------------------------------------------- inputs
input group "Sequences"
input bool   onL    = true;               // Long from the all-time low
input color  colL   = C'27,122,58';       // Long colour
input bool   onS    = true;               // Short from the all-time high
input color  colS   = C'239,83,80';       // Short colour
input bool   onL2   = true;               // Long 2 from the low after the ATH
input color  colL2  = C'198,255,0';       // Long 2 colour
input bool   onS2   = true;               // Short 2 from the high after that low
input color  colS2  = C'255,152,0';       // Short 2 colour

input group "Look"
input bool   showAth      = true;          // All-time high line
input color  colAth       = C'38,166,154'; // All-time high colour
input bool   showLevels   = true;          // Level numbers
input bool   showInner    = true;          // Lines inside the boxes (0.559, 0.618, 1.809)
input bool   showPath     = true;          // Connecting lines (0 - A - B - C)
input bool   showStatus   = true;          // Status box
input bool   showCheck    = false;         // Check line (debug)
input double minHoursIn   = 1.0;           // Smallest sequence: 0 to B at least (hours, 0 = any)
input int    minCandlesIn = 10;            // Hide sequences shorter than (chart candles, 0 = all)
input double tolPctIn     = 2.0;           // Zero tolerance (% of 0 -> A)

input group "Alerts"
input bool   al500    = true;              // Alert: price near 0.5
input bool   al559    = false;             // Alert: price near 0.559
input bool   al618    = false;             // Alert: price near 0.618
input bool   al667    = false;             // Alert: price near 0.667
input bool   al786    = false;             // Alert: price near 0.786
input bool   alEvents = true;              // Sequence events (confirmed, activated, 1.618 reached, new)
input bool   alPush   = false;             // Also send push notifications

input group "Liquidation levels (a row: on, the two prices, colour)"
input int    liqLookback = 300;            // Touches counted over the last (candles, 10-5000)
input bool   liqOn1 = false;  input double liqA1 = 0.0; input double liqB1 = 0.0; input color liqC1 = C'255,235,59';
input bool   liqOn2 = false;  input double liqA2 = 0.0; input double liqB2 = 0.0; input color liqC2 = C'255,235,59';
input bool   liqOn3 = false;  input double liqA3 = 0.0; input double liqB3 = 0.0; input color liqC3 = C'255,235,59';
input bool   liqOn4 = false;  input double liqA4 = 0.0; input double liqB4 = 0.0; input color liqC4 = C'255,235,59';
input bool   liqOn5 = false;  input double liqA5 = 0.0; input double liqB5 = 0.0; input color liqC5 = C'255,235,59';
input bool   liqOn6 = false;  input double liqA6 = 0.0; input double liqB6 = 0.0; input color liqC6 = C'255,235,59';
input bool   liqOn7 = false;  input double liqA7 = 0.0; input double liqB7 = 0.0; input color liqC7 = C'255,235,59';
input bool   liqOn8 = false;  input double liqA8 = 0.0; input double liqB8 = 0.0; input color liqC8 = C'255,235,59';

input group "Imbalances - row: searched timeframe, ticked: shown on charts of that column"
input bool           imbOn    = true;        // Imbalances
input color          imbColIn = clrGray;     // Imbalance colour
input ENUM_IMB_FILL  imbFill  = IMB_CLOSE;   // Gone when
input ENUM_IMB_PICK  imbPick  = IMB_NEAREST; // Show
input ENUM_IMB_COUNT imbCount = IC_3;        // How many (per searched timeframe and side)
input bool           imbNames = true;        // Name at the right end ("Imbalance 4h")
input bool imb_15m_15m = false; // 15m gaps on 15m chart
input bool imb_15m_30m = false; // 15m gaps on 30m chart
input bool imb_15m_1h  = false; // 15m gaps on 1h chart
input bool imb_15m_4h  = false; // 15m gaps on 4h chart
input bool imb_15m_1d  = false; // 15m gaps on 1D chart
input bool imb_15m_1w  = false; // 15m gaps on 1W chart
input bool imb_30m_15m = false; // 30m gaps on 15m chart
input bool imb_30m_30m = false; // 30m gaps on 30m chart
input bool imb_30m_1h  = false; // 30m gaps on 1h chart
input bool imb_30m_4h  = false; // 30m gaps on 4h chart
input bool imb_30m_1d  = false; // 30m gaps on 1D chart
input bool imb_30m_1w  = false; // 30m gaps on 1W chart
input bool imb_1h_15m  = false; // 1h gaps on 15m chart
input bool imb_1h_30m  = false; // 1h gaps on 30m chart
input bool imb_1h_1h   = true;  // 1h gaps on 1h chart
input bool imb_1h_4h   = false; // 1h gaps on 4h chart
input bool imb_1h_1d   = false; // 1h gaps on 1D chart
input bool imb_1h_1w   = false; // 1h gaps on 1W chart
input bool imb_4h_15m  = false; // 4h gaps on 15m chart
input bool imb_4h_30m  = false; // 4h gaps on 30m chart
input bool imb_4h_1h   = false; // 4h gaps on 1h chart
input bool imb_4h_4h   = true;  // 4h gaps on 4h chart
input bool imb_4h_1d   = false; // 4h gaps on 1D chart
input bool imb_4h_1w   = false; // 4h gaps on 1W chart
input bool imb_1d_15m  = false; // 1D gaps on 15m chart
input bool imb_1d_30m  = false; // 1D gaps on 30m chart
input bool imb_1d_1h   = false; // 1D gaps on 1h chart
input bool imb_1d_4h   = false; // 1D gaps on 4h chart
input bool imb_1d_1d   = false; // 1D gaps on 1D chart
input bool imb_1d_1w   = false; // 1D gaps on 1W chart
input bool imb_1w_15m  = false; // 1W gaps on 15m chart
input bool imb_1w_30m  = false; // 1W gaps on 30m chart
input bool imb_1w_1h   = false; // 1W gaps on 1h chart
input bool imb_1w_4h   = false; // 1W gaps on 4h chart
input bool imb_1w_1d   = false; // 1W gaps on 1D chart
input bool imb_1w_1w   = false; // 1W gaps on 1W chart

input group "Moving averages"
input bool       ma1On   = true;          // MA 1 on
input ENUM_SK_MA ma1Type = SK_EMA;        // MA 1 type
input int        ma1Len  = 50;            // MA 1 length
input color      ma1Col  = C'66,165,245'; // MA 1 colour
input int        ma1W    = 1;             // MA 1 width
input bool       ma2On   = true;          // MA 2 on
input ENUM_SK_MA ma2Type = SK_EMA;        // MA 2 type
input int        ma2Len  = 200;           // MA 2 length
input color      ma2Col  = C'171,71,188'; // MA 2 colour
input int        ma2W    = 2;             // MA 2 width
input bool       ma3On   = true;          // MA 3 on
input ENUM_SK_MA ma3Type = SK_SMA;        // MA 3 type
input int        ma3Len  = 50;            // MA 3 length
input color      ma3Col  = C'255,167,38'; // MA 3 colour
input int        ma3W    = 1;             // MA 3 width
input bool       ma4On   = true;          // MA 4 on
input ENUM_SK_MA ma4Type = SK_SMA;        // MA 4 type
input int        ma4Len  = 200;           // MA 4 length
input color      ma4Col  = C'239,83,80';  // MA 4 colour
input int        ma4W    = 2;             // MA 4 width

input group "MT5"
input int    InpMaxChartBars = 20000;     // Chart candles used (TradingView loads about 20 000)
input int    InpRecalcMs     = 1000;      // Recalculate at most every (ms)
input int    InpFontNormal   = 9;         // Font size: names
input int    InpFontSmall    = 7;         // Font size: level numbers / status
input int    InpFontTiny     = 6;         // Font size: imbalance names / check line

input group "On/Off button"
input bool             InpBtnShow   = true;               // Show the On/Off button
input ENUM_BASE_CORNER InpBtnCorner = CORNER_LEFT_LOWER;  // Button corner
input int              InpBtnX      = 10;                 // Button X offset (px from the corner)
input int              InpBtnY      = 30;                 // Button Y offset (px from the corner)
input int              InpBtnW      = 90;                 // Button width (px)
input int              InpBtnH      = 22;                 // Button height (px)

input group "Dashboard (status box)"
input ENUM_BASE_CORNER InpDashCorner = CORNER_RIGHT_UPPER; // Dashboard corner
input int              InpDashX      = 10;                 // Dashboard X offset (px from the corner)
input int              InpDashY      = 20;                 // Dashboard Y offset (px from the corner)

//---------------------------------------------------------------- rules
#define NAI  INT_MIN
#define NAL  LONG_MIN
#define PREFIX "SKS_"

const double BOX_LO     = 0.5;
const double BOX_HI     = 0.667;
const double LINE_786   = 0.786;
const double EXT_LO     = 1.618;
const double EXT_HI     = 2.0;
const double EXT_TARGET = 1.618;
const double EXT_DONE   = 3.0;                  // touched the extension box, then here: it ends
const double NEAR_SHARE = 0.5 * (0.559 - 0.5);  // "near 0.5": half the 0.5 -> 0.559 distance
const int    MAX_BOXES  = 20;
const int    BOX_PAST   = 5;                    // an open box reaches this far past the newest candle
const int    MAX_STEPS  = 60;                   // larger sequences followed at most until an open one
const int    PLAY_KEEP  = 1000;                 // candles kept per ladder timeframe
const int    WEEK_KEEP  = 5000;                 // weekly: the whole history
const int    SLIM_CANDLES = 2;
const int    IMB_LOOK   = 1000;
const int    LIQ_REACH  = 10;
const int    LIQ_LINGER = 10;
const int    LIQ_MAX_PIECES = 40;

double RET_MARKS[4] = {0.5, 0.559, 0.618, 0.667};
double EXT_MARKS[3] = {1.618, 1.809, 2.0};
long   LADDER_MS[8] = {60000, 300000, 900000, 1800000, 3600000, 14400000, 86400000, 604800000};
string LADDER_NAMES[8] = {"1m", "5m", "15m", "30m", "1h", "4h", "1D", "1W"};
int    IMB_SECS[6]  = {900, 1800, 3600, 14400, 86400, 604800};
string IMB_NAMES[6] = {"15m", "30m", "1h", "4h", "1D", "1W"};
bool   IMB_SHOW[36];

// label styles (TradingView label.style_*)
#define ST_UP    0   // label_up: text under the point
#define ST_DOWN  1   // label_down: text above the point
#define ST_LEFT  2   // label_left: text right of the point
#define ST_NONE  3   // centred
#define SZ_NORMAL 0
#define SZ_SMALL  1
#define SZ_TINY   2

//---------------------------------------------------------------- globals
double MaBuf1[], MaBuf2[], MaBuf3[], MaBuf4[];
int    maH[4] = {INVALID_HANDLE, INVALID_HANDLE, INVALID_HANDLE, INVALID_HANDLE};

double gO[], gH[], gL[], gC[];
long   gT[];          // chart candle open times in ms
int    gN = 0;
long   CHART_MS = 0;
long   gTime = 0;     // newest chart candle's open time (ms)
double tolIn = 0.02;
bool   gDirty = true;
bool   gIncomplete = false;
int    gObjN = 0;
color  gBg = clrBlack;
double gLastPMax = 0.0;
double gLastPMin = 0.0;
long   gLastPxH  = 0;
double gPricePerPx = 0.0;
double gLabStep  = 0.0;
double gWickGap  = 0.0;
bool   gMaSynced = false;

int    LAB_X[];
double LAB_Y[];
double LAB_TOL = 0.0;

string prevKeys[4] = {"", "", "", ""};
long   evtAlertBar[4] = {0, 0, 0, 0};
string evtAlertKeys[4] = {"", "", "", ""};
long   lvlAlertBar[4][5];

string DOT;
bool   gOn = true;                 // the On/Off button's state
const string BTN = "SKSbtn";       // not under PREFIX: kept when the drawing is cleared
bool   maOnIn[4];

//---------------------------------------------------------------- small helpers
bool IsRightCorner(ENUM_BASE_CORNER c) { return c == CORNER_RIGHT_UPPER || c == CORNER_RIGHT_LOWER; }
bool IsLowerCorner(ENUM_BASE_CORNER c) { return c == CORNER_LEFT_LOWER || c == CORNER_RIGHT_LOWER; }

// The On/Off button: its corner and X / Y offsets are px from that corner to the button's nearest edges.
void UpdateButton()
  {
   if(!InpBtnShow)
     {
      ObjectDelete(0, BTN);
      return;
     }
   if(ObjectFind(0, BTN) < 0)
     {
      if(!ObjectCreate(0, BTN, OBJ_BUTTON, 0, 0, 0)) return;
      ObjectSetInteger(0, BTN, OBJPROP_STATE, gOn);
     }
   ObjectSetInteger(0, BTN, OBJPROP_CORNER, InpBtnCorner);
   ObjectSetInteger(0, BTN, OBJPROP_XDISTANCE, IsRightCorner(InpBtnCorner) ? InpBtnX + InpBtnW : InpBtnX);
   ObjectSetInteger(0, BTN, OBJPROP_YDISTANCE, IsLowerCorner(InpBtnCorner) ? InpBtnY + InpBtnH : InpBtnY);
   ObjectSetInteger(0, BTN, OBJPROP_XSIZE, InpBtnW);
   ObjectSetInteger(0, BTN, OBJPROP_YSIZE, InpBtnH);
   ObjectSetString(0, BTN, OBJPROP_FONT, "Arial");
   ObjectSetInteger(0, BTN, OBJPROP_FONTSIZE, 8);
   ObjectSetString(0, BTN, OBJPROP_TEXT, gOn ? "SK-Suite ON" : "SK-Suite OFF");
   ObjectSetInteger(0, BTN, OBJPROP_COLOR, clrWhite);
   ObjectSetInteger(0, BTN, OBJPROP_BGCOLOR, gOn ? C'27,122,58' : clrDimGray);
   ObjectSetInteger(0, BTN, OBJPROP_BORDER_COLOR, clrGray);
   ObjectSetInteger(0, BTN, OBJPROP_STATE, gOn);
   ObjectSetInteger(0, BTN, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, BTN, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, BTN, OBJPROP_ZORDER, 10);
  }

// Off: the moving averages hidden too.
void ApplyMaVisibility()
  {
   for(int i = 0; i < 4; i++)
      PlotIndexSetInteger(i, PLOT_DRAW_TYPE, (gOn && maOnIn[i]) ? DRAW_LINE : DRAW_NONE);
  }
int  IMax(int a, int b) { return a > b ? a : b; }
int  IMin(int a, int b) { return a < b ? a : b; }
long LMax(long a, long b) { return a > b ? a : b; }
int  IRound(double x) { return (int)MathRound(x); }

void PushD(double &a[], double v) { int n = ArraySize(a); ArrayResize(a, n + 1, 64); a[n] = v; }
void PushI(int &a[], int v)       { int n = ArraySize(a); ArrayResize(a, n + 1, 64); a[n] = v; }
void PushB(bool &a[], bool v)     { int n = ArraySize(a); ArrayResize(a, n + 1, 64); a[n] = v; }

string NumStr(double r)
  {
   string s = DoubleToString(r, 3);
   while(StringLen(s) > 1 && StringGetCharacter(s, StringLen(s) - 1) == '0')
      s = StringSubstr(s, 0, StringLen(s) - 1);
   if(StringGetCharacter(s, StringLen(s) - 1) == '.')
      s = StringSubstr(s, 0, StringLen(s) - 1);
   return s;
  }

string PeriodStr()
  {
   string s = EnumToString((ENUM_TIMEFRAMES)_Period);
   StringReplace(s, "PERIOD_", "");
   return s;
  }

// color.new(c, transp): MT5 objects have no alpha - blended toward the chart background.
color Fade(color c, int transp)
  {
   if(transp <= 0 || c == clrNONE)
      return c;
   double t = transp / 100.0;
   int r1 = (int)(c & 0xFF), g1 = (int)((c >> 8) & 0xFF), b1 = (int)((c >> 16) & 0xFF);
   int r2 = (int)(gBg & 0xFF), g2 = (int)((gBg >> 8) & 0xFF), b2 = (int)((gBg >> 16) & 0xFF);
   int r = (int)MathRound(r1 * (1 - t) + r2 * t);
   int g = (int)MathRound(g1 * (1 - t) + g2 * t);
   int b = (int)MathRound(b1 * (1 - t) + b2 * t);
   return (color)(r | (g << 8) | (b << 16));
  }

int FontOf(int sz) { return sz == SZ_NORMAL ? InpFontNormal : sz == SZ_SMALL ? InpFontSmall : InpFontTiny; }

//---------------------------------------------------------------- types
struct Pt
  {
   int    index;
   double price;
  };
Pt   MkPt(int i, double p) { Pt x; x.index = i; x.price = p; return x; }
Pt   PtNA() { Pt x; x.index = NAI; x.price = 0.0; return x; }
bool IsNa(const Pt &p) { return p.index == NAI; }

// A candle series: the chart's own or one rung of the timeframe ladder (times in ms).
class Cs
  {
public:
   double o[], h[], l[], c[];
   long   t[];
   long   spanMs;
   bool   coarse;
   string name;
   long   sp[];     // a stitched series: each candle's length
   bool   hasSp;
                     Cs() { spanMs = 0; coarse = false; name = ""; hasSp = false; }
   int               Size() { return ArraySize(t); }
   void              Push(double vo, double vh, double vl, double vc, long vt, long vs)
     {
      int n = ArraySize(t);
      ArrayResize(o, n + 1, 1024); ArrayResize(h, n + 1, 1024); ArrayResize(l, n + 1, 1024);
      ArrayResize(c, n + 1, 1024); ArrayResize(t, n + 1, 1024);
      o[n] = vo; h[n] = vh; l[n] = vl; c[n] = vc; t[n] = vt;
      if(hasSp) { ArrayResize(sp, n + 1, 1024); sp[n] = vs; }
     }
   void              Resize(int n)
     {
      ArrayResize(o, n); ArrayResize(h, n); ArrayResize(l, n); ArrayResize(c, n); ArrayResize(t, n);
      if(hasSp) ArrayResize(sp, n);
     }
  };

// A box: the retracement of base -> top.
class Bx
  {
public:
   double base;
   Pt     top;
   bool   fixed;
   int    fixedIndex;
   Pt     low;
   int    breakIndex;
   int    lastTouch;
   int    x1;
   int    x2;
   long   notBefore;
                     Bx() { base = 0; top = PtNA(); fixed = false; fixedIndex = NAI; low = PtNA(); breakIndex = NAI; lastTouch = NAI; x1 = NAI; x2 = NAI; notBefore = NAL; }
  };

class Geo
  {
public:
   int    poolIdx;
   Cs    *cs;
   bool   lng;
   Pt     zero, second, a, b, bTent;
   int    confirmedIndex, breakIndex;
   Bx    *boxes[];
   Bx    *gkl;
   int    targetIndex, endIndex, invalidIndex, failedIndex, completedIndex;
   int    cFrom, cTo, cMid;
   long   minMs;
   Geo   *before;
   int    floor;
                     Geo()
     {
      poolIdx = -1; cs = NULL; lng = true; zero = PtNA(); second = PtNA(); a = PtNA(); b = PtNA(); bTent = PtNA();
      confirmedIndex = NAI; breakIndex = NAI; gkl = NULL; targetIndex = NAI; endIndex = NAI; invalidIndex = NAI;
      failedIndex = NAI; completedIndex = NAI; cFrom = NAI; cTo = NAI; cMid = NAI; minMs = 0; before = NULL; floor = 0;
     }
                    ~Geo()
     {
      for(int i = 0; i < ArraySize(boxes); i++)
         if(CheckPointer(boxes[i]) == POINTER_DYNAMIC) delete boxes[i];
      if(CheckPointer(gkl) == POINTER_DYNAMIC) delete gkl;
     }
   int               NBoxes() { return ArraySize(boxes); }
  };

// Pools - everything made in one run is freed at its end.
Geo *gGeoPool[];
Cs  *gCsPool[];

Geo *NewGeo()
  {
   Geo *g = new Geo();
   int n = ArraySize(gGeoPool);
   ArrayResize(gGeoPool, n + 1, 256);
   gGeoPool[n] = g;
   g.poolIdx = n;
   return g;
  }
void FreeGeo(Geo *g)
  {
   if(g == NULL) return;
   if(g.poolIdx >= 0 && g.poolIdx < ArraySize(gGeoPool)) gGeoPool[g.poolIdx] = NULL;
   delete g;
  }
Cs *NewCs()
  {
   Cs *c = new Cs();
   int n = ArraySize(gCsPool);
   ArrayResize(gCsPool, n + 1, 16);
   gCsPool[n] = c;
   return c;
  }
void FreeAll()
  {
   for(int i = 0; i < ArraySize(gGeoPool); i++)
      if(CheckPointer(gGeoPool[i]) == POINTER_DYNAMIC) delete gGeoPool[i];
   ArrayFree(gGeoPool);
   for(int i = 0; i < ArraySize(gCsPool); i++)
      if(CheckPointer(gCsPool[i]) == POINTER_DYNAMIC) delete gCsPool[i];
   ArrayFree(gCsPool);
  }

//---------------------------------------------------------------- sequence maths
double Ext(Cs *cs, int k, bool lng) { return lng ? cs.h[k] : cs.l[k]; } // in the move's direction
double Tow(Cs *cs, int k, bool lng) { return lng ? cs.l[k] : cs.h[k]; } // against it
bool   Bey(double x, double y, bool lng) { return lng ? x > y : x < y; }
double Lvl(double base, double top, double r) { return top - r * (top - base); }

long SpanAt(Cs *cs, int k) { return cs.hasSp ? cs.sp[k] : cs.spanMs; }

string TfName(long ms)
  {
   int sec = (int)(ms / 1000);
   if(sec < 3600)   return IntegerToString(sec / 60) + "m";
   if(sec < 86400)  return IntegerToString(sec / 3600) + "h";
   if(sec < 604800) return IntegerToString(sec / 86400) + "D";
   if(sec == 604800) return "1W";
   return PeriodStr();
  }

bool NearHalf(Cs *cs, int k, Bx *b, bool lng)
  {
   double level = Lvl(b.base, b.top.price, 0.5);
   double dist = NEAR_SHARE * MathAbs(b.top.price - b.base);
   return lng ? Tow(cs, k, lng) <= level + dist : Tow(cs, k, lng) >= level - dist;
  }

bool TouchesBand(Cs *cs, int k, double base, double top)
  {
   double p1 = Lvl(base, top, BOX_LO);
   double p2 = Lvl(base, top, BOX_HI);
   return cs.l[k] <= MathMax(p1, p2) && cs.h[k] >= MathMin(p1, p2);
  }

Bx *NewBox(double base, const Pt &top)
  {
   Bx *b = new Bx();
   b.base = base;
   b.top = MkPt(top.index, top.price);
   return b;
  }

void Step(Bx *b, Cs *cs, int k, bool lng)
  {
   if(b.breakIndex != NAI) return;
   if(!b.fixed)
     {
      // (A candle making the new high doesn't count as coming near too - which came first in it is unknown.)
      if(Bey(Ext(cs, k, lng), b.top.price, lng))
         b.top = MkPt(k, Ext(cs, k, lng));
      else if(NearHalf(cs, k, b, lng) && (b.notBefore == NAL || cs.t[k] >= b.notBefore))
        {
         b.fixed = true;
         b.fixedIndex = k;
         b.low = MkPt(k, Tow(cs, k, lng));
         if(TouchesBand(cs, k, b.base, b.top.price))
            b.lastTouch = k;
        }
     }
   else
     {
      if(Bey(Ext(cs, k, lng), b.top.price, lng))
         b.breakIndex = k;
      else
        {
         if(Bey(b.low.price, Tow(cs, k, lng), lng))
            b.low = MkPt(k, Tow(cs, k, lng));
         if(TouchesBand(cs, k, b.base, b.top.price))
            b.lastTouch = k;
        }
     }
  }

// The sequence from the candles at i and j (either order), played up to `until`.
Geo *Geometry(Cs *cs, int i, int j, int until, bool lng, double tol, long minMs = 0)
  {
   int i0 = IMin(i, j);
   int iA = IMax(i, j);
   int last = IMin(until, cs.Size() - 1);
   Pt zero = MkPt(i0, Tow(cs, i0, lng));
   Pt start = MkPt(iA, Ext(cs, iA, lng));
   Bx *box1 = NewBox(zero.price, start);
   // A bounce sooner than minMs after the 0 confirms nothing - A runs on.
   if(minMs > 0)
      box1.notBefore = cs.t[i0] + minMs;
   Bx *boxes[];
   ArrayResize(boxes, 1, MAX_BOXES);
   boxes[0] = box1;
   double sgn = lng ? 1.0 : -1.0;
   Bx *gkl = NULL;
   Pt hiSince = PtNA();
   int targetIndex = NAI, invalidIndex = NAI, failedIndex = NAI, gklTouched = NAI, completedIndex = NAI;
   bool extTouched = false;
   int extEnd = NAI;
   bool extOvershot = false;
   int beyondZero = NAI;
   if(iA < last)
     {
      for(int k = iA + 1; k <= last; k++)
        {
         Bx *cur = boxes[ArraySize(boxes) - 1];
         Step(cur, cs, k, lng);
         // Really beyond 0: past it by more than `tol` of 0 -> A.
         bool pastZero = Bey(zero.price - sgn * tol * MathAbs(box1.top.price - zero.price), Tow(cs, k, lng), lng);
         if(box1.breakIndex == NAI)
           {
            if(box1.fixed && pastZero)
              {
               invalidIndex = k;
               break;
              }
            continue;
           }
         double xk = Ext(cs, k, lng);
         if(IsNa(hiSince) || Bey(xk, hiSince.price, lng))
            hiSince = MkPt(k, xk);
         if(beyondZero == NAI && pastZero)
            beyondZero = k;
         double move = box1.top.price - zero.price;
         // The extension box runs to the newest candle - unless touched then 3 reached, or beyond 0.
         if(extEnd == NAI)
           {
            double e0 = box1.low.price + EXT_LO * move;
            double e1 = box1.low.price + EXT_HI * move;
            if(extTouched && !Bey(box1.low.price + EXT_DONE * move, xk, lng))
              {
               extEnd = k;
               extOvershot = true;
              }
            else if(pastZero)
               extEnd = k;
            else if(cs.l[k] <= MathMax(e0, e1) && cs.h[k] >= MathMin(e0, e1))
               extTouched = true;
           }
         double target = box1.low.price + EXT_TARGET * move;
         if(gkl != NULL)
           {
            Step(gkl, cs, k, lng);
            // Complete: into the GKL box, then the 1.618 again. Or a high beyond its fixed top without
            // having come into it: the next larger sequence takes over.
            if(gklTouched == NAI)
              {
               if(gkl.lastTouch != NAI)
                  gklTouched = k;
               else if(gkl.breakIndex == k)
                 {
                  completedIndex = k;
                  break;
                 }
              }
            else if(!Bey(target, xk, lng))
              {
               completedIndex = k;
               break;
              }
           }
         else
           {
            // A box broken: the next one from here on - B -> the new high.
            if(cur.breakIndex != NAI && cur.breakIndex == k && ArraySize(boxes) < MAX_BOXES)
              {
               int nb = ArraySize(boxes);
               ArrayResize(boxes, nb + 1, MAX_BOXES);
               boxes[nb] = NewBox(box1.low.price, MkPt(k, xk));
              }
            if(!Bey(target, xk, lng))
              {
               // 1.618 reached: the GKL box. The correction box still running drops.
               targetIndex = k;
               gkl = NewBox(zero.price, hiSince);
               int nb = ArraySize(boxes);
               Bx *lastBox = boxes[nb - 1];
               if(nb > 1 && lastBox.breakIndex == NAI)
                 {
                  delete lastBox;
                  ArrayResize(boxes, nb - 1);
                 }
              }
           }
         // Failed only after the activation, and only clearly beyond B.
         if(k > box1.breakIndex && !IsNa(box1.low))
           {
            if(Bey(box1.low.price, Tow(cs, k, lng), lng))
              {
               failedIndex = k;
               break;
              }
           }
        }
     }
   Pt a = box1.top;
   Pt b = box1.low;
   int brk = box1.breakIndex;
   // Not confirmed yet (no B): where B would be now - the lowest low since A.
   Pt bTent = PtNA();
   if(IsNa(b) && invalidIndex == NAI && a.index < last)
     {
      for(int k = a.index + 1; k <= last; k++)
        {
         double tk = Tow(cs, k, lng);
         if(IsNa(bTent) || Bey(bTent.price, tk, lng))
            bTent = MkPt(k, tk);
        }
     }
   int cFrom = NAI, cTo = NAI, cMid = NAI;
   if(brk != NAI)
     {
      cFrom = brk;
      int cEnd = IMax(brk + 1, extEnd != NAI ? extEnd : failedIndex != NAI ? failedIndex : last);
      cTo = (extEnd == NAI && failedIndex == NAI) ? IMax(cEnd, last + BOX_PAST) : cEnd;
      cMid = IRound((brk + cEnd) / 2.0);
     }
   // Drawn from the candle after its top to the last one touching it before its break.
   int nbx = ArraySize(boxes);
   for(int n = 0; n < nbx; n++)
     {
      Bx *bx = boxes[n];
      int lim = bx.breakIndex != NAI ? bx.breakIndex : (n == 0 && invalidIndex != NAI) ? invalidIndex : failedIndex != NAI ? failedIndex : last + BOX_PAST;
      bx.x1 = bx.top.index + 1;
      bx.x2 = IMax(bx.x1 + 1, bx.lastTouch == NAI ? lim : IMin(bx.lastTouch, lim));
     }
   if(gkl != NULL)
     {
      gkl.x1 = gkl.top.index + 1;
      int right = extOvershot ? (beyondZero == NAI ? last : beyondZero) : cTo;
      gkl.x2 = IMax(gkl.top.index + 2, right);
     }
   Geo *g = NewGeo();
   g.cs = cs; g.lng = lng; g.zero = zero; g.second = start; g.a = a; g.b = b; g.bTent = bTent;
   g.confirmedIndex = box1.fixedIndex; g.breakIndex = brk;
   ArrayResize(g.boxes, nbx);
   for(int n = 0; n < nbx; n++) g.boxes[n] = boxes[n];
   g.gkl = gkl; g.targetIndex = targetIndex; g.endIndex = last; g.invalidIndex = invalidIndex;
   g.failedIndex = failedIndex; g.completedIndex = completedIndex;
   g.cFrom = cFrom; g.cTo = cTo; g.cMid = cMid; g.minMs = minMs;
   return g;
  }

double SpanOf(Geo *g) { return MathAbs(g.a.price - g.zero.price); }
double ExtOf(Geo *g, double r) { return g.b.price + r * (g.a.price - g.zero.price); }

// The next larger sequence, only after this one failed or completed.
Geo *LargerOf(Cs *cs, Geo *g, int until, double tol)
  {
   Geo *result = NULL;
   int overIndex = g.failedIndex != NAI ? g.failedIndex : g.completedIndex;
   if(overIndex == NAI)
      return NULL;
   bool lng = g.lng;
   double span = SpanOf(g);
   int grownA = NAI;
   if(g.failedIndex != NAI)
      grownA = g.breakIndex;
   else if(g.gkl != NULL)
      grownA = g.gkl.top.index;
   Geo *grownOk = NULL;
   if(grownA != NAI && grownA != g.zero.index)
     {
      Geo *grown = Geometry(cs, g.zero.index, grownA, until, lng, tol, g.minMs);
      if(SpanOf(grown) > span)
         grownOk = grown;
      else
         FreeGeo(grown);
     }
   bool grownHolds = (grownOk != NULL && grownOk.failedIndex == NAI);
   if(grownHolds)
      result = grownOk;
   else
     {
      Geo *deeper = NULL;
      int stop = IMin(overIndex, cs.Size() - 1);
      int z = g.zero.index - 1;
      // The furthest extreme from z + 1 to `stop`, grown by one candle per step back.
      int best = NAI;
      if(stop >= g.zero.index)
         for(int k = g.zero.index; k <= stop; k++)
           {
            if(best == NAI)
               best = k;
            else if(Bey(Ext(cs, k, lng), Ext(cs, best, lng), lng))
               best = k;
           }
      while(z >= g.floor && deeper == NULL)
        {
         if(Bey(g.zero.price, Tow(cs, z, lng), lng))
           {
            int e = z;
            if(best != NAI && stop > z)
               if(Bey(Ext(cs, best, lng), Ext(cs, z, lng), lng))
                  e = best;
            Geo *cand = Geometry(cs, z, e, until, lng, tol, g.minMs);
            if(SpanOf(cand) > span)
               deeper = cand;
            else
               FreeGeo(cand);
           }
         if(best == NAI)
            best = z;
         else if(!Bey(Ext(cs, best, lng), Ext(cs, z, lng), lng))
            best = z;
         z--;
        }
      if(deeper != NULL)
        {
         if(grownOk != NULL) FreeGeo(grownOk);
         result = deeper;
        }
      else
         result = grownOk;
     }
   if(result != NULL)
      result.floor = g.floor;
   return result;
  }

//---------------------------------------------------------------- finding them
// The first candle at or after t (the series' size: none).
int IdxAtOrAfter(Cs *cs, long t)
  {
   int lo = 0, hi = cs.Size() - 1, found = cs.Size();
   while(lo <= hi)
     {
      int mid = (lo + hi) / 2;
      if(cs.t[mid] >= t) { found = mid; hi = mid - 1; }
      else lo = mid + 1;
     }
   return found;
  }

// The extreme's candle from `from` on: long the lowest low, short the highest high (-1: none).
int ExtremeFrom(Cs *cs, int from, bool lng)
  {
   int best = -1;
   int n = cs.Size();
   for(int k = from; k < n; k++)
     {
      if(best < 0)
         best = k;
      else if(Bey(Tow(cs, best, lng), Tow(cs, k, lng), lng))
         best = k;
     }
   return best;
  }

// The largest sequence from the extreme that is not complete or failed. Invalid or none left: NULL.
Geo *OpenFrom(Cs *cs, int from, bool lng)
  {
   Geo *res = NULL;
   int i0 = ExtremeFrom(cs, from, lng);
   int last = cs.Size() - 1;
   if(i0 >= 0 && i0 < last)
     {
      Geo *g = Geometry(cs, i0, i0 + 1, last, lng, tolIn, (long)(minHoursIn * 3600000.0));
      g.floor = from;
      int n = 0;
      while(n < MAX_STEPS)
        {
         if(g.failedIndex == NAI && g.completedIndex == NAI)
           {
            if(g.invalidIndex == NAI)
               res = g;
            break;
           }
         Geo *nx = LargerOf(cs, g, last, tolIn);
         if(nx == NULL)
            break;
         nx.before = g;
         g = nx;
         n++;
        }
     }
   return res;
  }

long ZeroTimeOf(Geo *g) { return g.cs.t[g.zero.index]; }
long ZeroEndOf(Geo *g)  { return g.cs.t[g.zero.index] + SpanAt(g.cs, g.zero.index); }

// One series of the finest candles there are for each stretch of time.
Cs *Stitch(Cs *&tiers[], long maxMs)
  {
   Cs *res = NULL;
   for(int i = ArraySize(tiers) - 1; i >= 0; i--)
     {
      Cs *x = tiers[i];
      if(x.spanMs <= maxMs && x.Size() > 1)
        {
         if(res == NULL)
           {
            res = NewCs();
            res.hasSp = true;
            for(int k = 0; k < x.Size(); k++)
               res.Push(x.o[k], x.h[k], x.l[k], x.c[k], x.t[k], x.spanMs);
            res.spanMs = x.spanMs;
            res.coarse = x.coarse;
            res.name = x.name;
           }
         else
           {
            int b = IdxAtOrAfter(res, x.t[0]);
            if(b < res.Size())
              {
               int from = IdxAtOrAfter(x, res.t[b]);
               if(from < x.Size())
                 {
                  res.Resize(b);
                  for(int k = from; k < x.Size(); k++)
                     res.Push(x.o[k], x.h[k], x.l[k], x.c[k], x.t[k], x.spanMs);
                  res.spanMs = x.spanMs;
                  res.coarse = x.coarse;
                  res.name = TfName(res.sp[0]) + "-" + x.name;
                 }
              }
           }
        }
     }
   return res;
  }

Geo *FindKind(Cs *cs, bool lng, long fromTime)
  {
   return OpenFrom(cs, fromTime == NAL ? 0 : IdxAtOrAfter(cs, fromTime), lng);
  }

//---------------------------------------------------------------- chart time helpers
// The opening time of the chart candle holding time t (before the chart's first candle: t itself).
long ChartOpenAt(long t)
  {
   int lo = 0, hi = gN - 1, found = -1;
   while(lo <= hi)
     {
      int mid = (lo + hi) / 2;
      if(gT[mid] <= t) { found = mid; lo = mid + 1; }
      else hi = mid - 1;
     }
   return found >= 0 ? gT[found] : t;
  }

// A candle's time; past the newest one: further on in chart candles. A coarse series' newest candle is now.
long XtRaw(Cs *cs, int k)
  {
   int n = cs.Size();
   if(k >= n - 1 && (cs.coarse || k >= n))
      return gTime + (long)(k - n + 1) * CHART_MS;
   return SpanAt(cs, k) < CHART_MS ? ChartOpenAt(cs.t[k]) : cs.t[k];
  }
long Xt(Cs *cs, int k) { return LMax(XtRaw(cs, k), gT[0]); }
bool Seen(Cs *cs, int k) { return XtRaw(cs, k) >= gT[0]; }

// The chart candle index of time t (past the newest one: further on in chart candles).
int BarAt(long t)
  {
   if(t > gT[gN - 1])
      return gN - 1 + (int)MathRound((double)(t - gT[gN - 1]) / (double)CHART_MS);
   int lo = 0, hi = gN - 1, found = 0;
   while(lo <= hi)
     {
      int mid = (lo + hi) / 2;
      if(gT[mid] <= t) { found = mid; lo = mid + 1; }
      else hi = mid - 1;
     }
   return found;
  }
// A chart candle index to its time (past the newest one: further on).
long IdxTime(int k)
  {
   if(k < 0) return gT[0];
   if(k < gN) return gT[k];
   return gT[gN - 1] + (long)(k - gN + 1) * CHART_MS;
  }

//---------------------------------------------------------------- too small for this chart
long SpanMsOf(Geo *g)
  {
   Cs *cs = g.cs;
   int k = g.gkl != NULL ? g.gkl.top.index : g.breakIndex != NAI ? g.cMid : !IsNa(g.b) ? g.b.index : g.a.index;
   return cs.t[IMin(k, cs.Size() - 1)] - cs.t[g.zero.index];
  }
bool ShownHere(Geo *g) { return minCandlesIn <= 0 || SpanMsOf(g) >= (long)minCandlesIn * CHART_MS; }
bool SlimHere(Geo *g)  { return !ShownHere(g) && SpanMsOf(g) >= (long)SLIM_CANDLES * CHART_MS; }

string HiddenNote(Geo *g)
  {
   string upTo = "";
   for(int i = 0; i < 8; i++)
      if(SpanMsOf(g) >= (long)minCandlesIn * LADDER_MS[i])
         upTo = LADDER_NAMES[i];
   string full = upTo == "" ? "" : ", full up to " + upTo;
   if(ShownHere(g)) return "";
   return SlimHere(g) ? " " + DOT + " only its path on " + TfName(CHART_MS) + full
          : " " + DOT + " too small for " + TfName(CHART_MS) + full;
  }

//---------------------------------------------------------------- chart objects
string NewName() { return PREFIX + IntegerToString(gObjN++); }
datetime Dt(long ms) { return (datetime)(ms / 1000); }

void MkLine(long t1, double p1, long t2, double p2, color c, int width, ENUM_LINE_STYLE st)
  {
   string n = NewName();
   if(!ObjectCreate(0, n, OBJ_TREND, 0, Dt(t1), p1, Dt(t2), p2)) return;
   ObjectSetInteger(0, n, OBJPROP_COLOR, c);
   // MT5 draws dashes / dots with width 1 only
   ObjectSetInteger(0, n, OBJPROP_WIDTH, st == STYLE_SOLID ? width : 1);
   ObjectSetInteger(0, n, OBJPROP_STYLE, st);
   ObjectSetInteger(0, n, OBJPROP_RAY_RIGHT, false);
   ObjectSetInteger(0, n, OBJPROP_RAY_LEFT, false);
   ObjectSetInteger(0, n, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, n, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, n, OBJPROP_BACK, false);
  }

// A box: a filled rectangle (behind the candles) and its border.
void MkBox(long t1, double top, long t2, double bot, color border, int width, ENUM_LINE_STYLE st, color fill)
  {
   if(fill != clrNONE)
     {
      string n = NewName();
      if(ObjectCreate(0, n, OBJ_RECTANGLE, 0, Dt(t1), top, Dt(t2), bot))
        {
         ObjectSetInteger(0, n, OBJPROP_COLOR, fill);
         ObjectSetInteger(0, n, OBJPROP_FILL, true);
         ObjectSetInteger(0, n, OBJPROP_BACK, true);
         ObjectSetInteger(0, n, OBJPROP_SELECTABLE, false);
         ObjectSetInteger(0, n, OBJPROP_HIDDEN, true);
        }
     }
   if(border != clrNONE)
     {
      string n = NewName();
      if(ObjectCreate(0, n, OBJ_RECTANGLE, 0, Dt(t1), top, Dt(t2), bot))
        {
         ObjectSetInteger(0, n, OBJPROP_COLOR, border);
         ObjectSetInteger(0, n, OBJPROP_FILL, false);
         ObjectSetInteger(0, n, OBJPROP_BACK, false);
         ObjectSetInteger(0, n, OBJPROP_WIDTH, st == STYLE_SOLID ? width : 1);
         ObjectSetInteger(0, n, OBJPROP_STYLE, st);
         ObjectSetInteger(0, n, OBJPROP_SELECTABLE, false);
         ObjectSetInteger(0, n, OBJPROP_HIDDEN, true);
        }
     }
  }

void MkText(long t, double p, string s, int st, color c, int sz)
  {
   string n = NewName();
   if(!ObjectCreate(0, n, OBJ_TEXT, 0, Dt(t), p)) return;
   ObjectSetString(0, n, OBJPROP_TEXT, st == ST_LEFT ? " " + s : s);
   ObjectSetString(0, n, OBJPROP_FONT, "Arial");
   ObjectSetInteger(0, n, OBJPROP_FONTSIZE, FontOf(sz));
   ObjectSetInteger(0, n, OBJPROP_COLOR, c);
   ENUM_ANCHOR_POINT an = st == ST_UP ? ANCHOR_UPPER : st == ST_DOWN ? ANCHOR_LOWER : st == ST_LEFT ? ANCHOR_LEFT : ANCHOR_CENTER;
   ObjectSetInteger(0, n, OBJPROP_ANCHOR, an);
   ObjectSetInteger(0, n, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, n, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, n, OBJPROP_BACK, false);
  }

double LabelCenterY(double py, int st, double step)
  {
   if(st == ST_DOWN) return py + 0.5 * step;
   if(st == ST_UP)   return py - 0.5 * step;
   return py;
  }

// A name (normal size): offset from the wick and moved out of the way by one screen line height per
// colliding label within 2 candles - away from its point (above: up, under: down, centred: down).
void Txt(long x, double y, string s, int st, color c, int sz = SZ_NORMAL)
  {
   double py = y;
   if(sz == SZ_NORMAL)
     {
      double step = gLabStep > 0.0 ? gLabStep : LAB_TOL;
      if(st == ST_DOWN)      py = y + gWickGap;
      else if(st == ST_UP)   py = y - gWickGap;
      int bx = BarAt(x);
      if(step > 0.0)
        {
         for(int tries = 0; tries < 10; tries++)
           {
            double cy = LabelCenterY(py, st, step);
            bool hit = false;
            for(int i = 0; i < ArraySize(LAB_X); i++)
               if(MathAbs(LAB_X[i] - bx) <= 2 && MathAbs(LAB_Y[i] - cy) < 0.92 * step)
                 {
                  hit = true;
                  break;
                 }
            if(!hit) break;
            py = st == ST_DOWN ? py + step : py - step;
           }
        }
      PushI(LAB_X, bx);
      PushD(LAB_Y, LabelCenterY(py, st, step));
     }
   MkText(x, py, s, st, c, sz);
  }

//---------------------------------------------------------------- drawing the sequences
// A box 0.5 - 0.667 of a retracement, its levels named right outside, 0.786 as a line.
void DrawBand(Cs *cs, double base, double top, int x1, int x2, color ink, bool dashed)
  {
   long t1 = Xt(cs, x1);
   long t2 = LMax(Xt(cs, x2), t1 + CHART_MS);
   double p1 = Lvl(base, top, BOX_LO);
   double p2 = Lvl(base, top, BOX_HI);
   MkBox(t1, MathMax(p1, p2), t2, MathMin(p1, p2), ink, 2, dashed ? STYLE_DASH : STYLE_SOLID, Fade(ink, 95));
   long tick = t2 + CHART_MS;
   for(int i = 0; i < 4; i++)
     {
      double r = RET_MARKS[i];
      double p = Lvl(base, top, r);
      if(showInner && r != BOX_LO && r != BOX_HI)
         MkLine(t1, p, t2, p, Fade(ink, 25), 1, STYLE_DASH);
      MkLine(t2, p, tick, p, ink, 1, STYLE_SOLID);
      if(showLevels)
         Txt(tick, p, NumStr(r), ST_LEFT, ink, SZ_SMALL);
     }
   double p786 = Lvl(base, top, LINE_786);
   MkLine(t1, p786, t2, p786, Fade(ink, 40), 1, STYLE_DASH);
   MkLine(t2, p786, tick, p786, ink, 1, STYLE_SOLID);
   if(showLevels)
      Txt(tick, p786, NumStr(LINE_786), ST_LEFT, ink, SZ_SMALL);
  }

void DrawGeo(Geo *g, color ink, bool firstAsGkl = false, bool hideFirst = false, bool skip0A = false,
             bool dashedPath = false, string cName = "C", bool slim = false)
  {
   Cs *cs = g.cs;
   bool lng = g.lng;
   int under = lng ? ST_UP : ST_DOWN;
   int above = lng ? ST_DOWN : ST_UP;
   if(!slim)
     {
      for(int n = 0; n < g.NBoxes(); n++)
        {
         Bx *bx = g.boxes[n];
         if(!(n == 0 && hideFirst))
            DrawBand(cs, bx.base, bx.top.price, bx.x1, bx.x2, ink, n == 0 && g.breakIndex == NAI && g.invalidIndex == NAI && !firstAsGkl);
        }
      if(g.breakIndex != NAI)
        {
         // The trend break: from A to the candle beyond it. Then the extension box 1.618 - 2.
         MkLine(Xt(cs, g.a.index), g.a.price, Xt(cs, g.breakIndex), g.a.price, ink, 2, STYLE_DASH);
         double e0 = ExtOf(g, EXT_LO);
         double e1 = ExtOf(g, EXT_HI);
         long c1 = Xt(cs, g.cFrom);
         long c2 = LMax(Xt(cs, g.cTo), c1 + CHART_MS);
         MkBox(c1, MathMax(e0, e1), c2, MathMin(e0, e1), Fade(ink, 30), 1, STYLE_SOLID, Fade(ink, 88));
         long cTick = c2 + CHART_MS;
         for(int i = 0; i < 3; i++)
           {
            double r = EXT_MARKS[i];
            double p = ExtOf(g, r);
            if(showInner && r != EXT_LO && r != EXT_HI)
               MkLine(c1, p, c2, p, Fade(ink, 25), 1, STYLE_DASH);
            MkLine(c2, p, cTick, p, ink, 1, STYLE_SOLID);
            if(showLevels)
               Txt(cTick, p, NumStr(r), ST_LEFT, ink, SZ_SMALL);
           }
         // C: the high the 1.618 was reached with once it is, else the middle of the extension box.
         if(g.gkl != NULL)
            Txt(Xt(cs, g.gkl.top.index), g.gkl.top.price, cName, above, ink);
         else
            Txt(Xt(cs, g.cMid), ExtOf(g, 1.809), cName, ST_NONE, ink);
        }
      if(g.gkl != NULL)
        {
         DrawBand(cs, g.gkl.base, g.gkl.top.price, g.gkl.x1, g.gkl.x2, ink, false);
         double mid = (Lvl(g.gkl.base, g.gkl.top.price, BOX_LO) + Lvl(g.gkl.base, g.gkl.top.price, BOX_HI)) / 2;
         Txt(Xt(cs, IRound((g.gkl.x1 + g.gkl.x2) / 2.0)), mid, "GKL", ST_NONE, ink);
        }
     }
   // 0 -> A -> B -> C
   long   ptT[];
   double ptP[];
   ArrayResize(ptT, 0, 4);
   ArrayResize(ptP, 0, 4);
   int np = 0;
   ArrayResize(ptT, 2); ArrayResize(ptP, 2);
   ptT[0] = XtRaw(cs, g.zero.index); ptP[0] = g.zero.price;
   ptT[1] = XtRaw(cs, g.a.index);    ptP[1] = g.a.price;
   np = 2;
   if(!IsNa(g.b))
     {
      ArrayResize(ptT, np + 1); ArrayResize(ptP, np + 1);
      ptT[np] = XtRaw(cs, g.b.index); ptP[np] = g.b.price; np++;
     }
   if(g.breakIndex != NAI)
     {
      ArrayResize(ptT, np + 1); ArrayResize(ptP, np + 1);
      if(g.gkl != NULL) { ptT[np] = XtRaw(cs, g.gkl.top.index); ptP[np] = g.gkl.top.price; }
      else              { ptT[np] = XtRaw(cs, g.cMid);          ptP[np] = ExtOf(g, 1.809); }
      np++;
     }
   // skip0A: a larger one grown from the drawn smaller one's GKL box - its 0 -> A is that one's path to C.
   int firstSeg = skip0A ? 2 : 1;
   if(showPath)
     {
      long first = gT[0];
      for(int n = firstSeg; n < np; n++)
        {
         long x1 = ptT[n - 1];
         double y1 = ptP[n - 1];
         long x2 = ptT[n];
         double y2 = ptP[n];
         if(x2 > first)
           {
            if(x1 < first)
              {
               y1 = y1 + (y2 - y1) * (double)(first - x1) / (double)(x2 - x1);
               x1 = first;
              }
            MkLine(x1, y1, x2, y2, Fade(ink, 15), 2, dashedPath ? STYLE_DASH : STYLE_SOLID);
           }
        }
     }
   // The 0 names the timeframe it was played on.
   if(Seen(cs, g.zero.index) && !skip0A)
      Txt(Xt(cs, g.zero.index), g.zero.price, "0 (" + TfName(SpanAt(cs, g.zero.index)) + ")", under, ink);
   if(!slim)
     {
      if(Seen(cs, g.a.index) && !skip0A)
         Txt(Xt(cs, g.a.index), g.a.price, "A", above, ink);
      // B's name: "B" only once activated; before, "B?" in the SK box - or under the low once beyond its 0.667.
      if(!IsNa(g.b) && g.breakIndex != NAI)
         Txt(Xt(cs, g.b.index), g.b.price, "B", under, ink);
      else
        {
         Pt bLow = IsNa(g.b) ? g.bTent : g.b;
         Bx *first = g.boxes[0];
         double edge = Lvl(first.base, first.top.price, BOX_HI);
         bool deeper = false;
         if(!IsNa(bLow))
            deeper = Bey(edge, bLow.price, lng);
         double mid = (Lvl(first.base, first.top.price, BOX_LO) + edge) / 2;
         if(deeper)
            Txt(Xt(cs, bLow.index), bLow.price, "B?", under, ink);
         if(firstAsGkl)
            Txt(Xt(cs, IRound((first.x1 + first.x2) / 2.0)), mid, "GKL", ST_NONE, ink);
         else if(!deeper && !hideFirst)
            Txt(Xt(cs, IRound((first.x1 + first.x2) / 2.0)), mid, "B?", ST_NONE, Fade(ink, 30));
        }
      // Not confirmed yet: B as it would be now - faint, dotted to the newest candle.
      if(IsNa(g.b) && !IsNa(g.bTent))
         MkLine(Xt(cs, g.bTent.index), g.bTent.price, Xt(cs, g.endIndex), g.bTent.price, Fade(ink, 60), 1, STYLE_DOT);
     }
  }

// Until it is activated, the smaller one it took over from (only a completed one - a failed one goes).
Geo *BesideOf(Geo *g)
  {
   Geo *p = g.breakIndex == NAI ? g.before : NULL;
   if(p != NULL && p.failedIndex != NAI)
      p = NULL;
   return p;
  }

void DrawShown(Geo *g, color ink)
  {
   Geo *p = BesideOf(g);
   bool pFull = (p != NULL && ShownHere(p));
   bool fromGkl = false;
   if(pFull && p.gkl != NULL)
      fromGkl = (p.zero.index == g.zero.index && p.gkl.top.index == g.second.index);
   if(ShownHere(g) || SlimHere(g))
     {
      DrawGeo(g, p != NULL ? Fade(ink, 60) : ink, false, fromGkl, fromGkl, p != NULL, "C", !ShownHere(g));
      if(pFull || (p != NULL && SlimHere(p)))
         DrawGeo(p, ink, false, false, false, false, fromGkl ? "c, A" : "C", !pFull);
     }
  }

string StateOf(Geo *g)
  {
   return g.gkl != NULL ? "1.618 reached (GKL box)" : g.breakIndex != NAI ? "activated" : g.confirmedIndex != NAI ? "confirmed" : "forming";
  }

//---------------------------------------------------------------- alerts
void Notify(string msg)
  {
   Alert(msg);
   if(alPush)
      SendNotification(msg);
  }

void AlertsFor(Geo *g, int slot, string name)
  {
   string key = g == NULL ? "none"
                : DoubleToString(g.zero.price, _Digits) + "|"
                  + (g.confirmedIndex == NAI ? "forming" : DoubleToString(SpanOf(g), _Digits) + "|" + StateOf(g));
   string prev = prevKeys[slot];
   if(evtAlertBar[slot] != gTime)
     {
      evtAlertBar[slot] = gTime;
      evtAlertKeys[slot] = "";
     }
   if(alEvents && prev != "" && key != prev && g != NULL)
     {
      string token = "|" + key + "|";
      if(StringFind(evtAlertKeys[slot], token) < 0)
        {
         evtAlertKeys[slot] += token;
         Notify(_Symbol + " " + PeriodStr() + ": SK " + name + " - " + StateOf(g));
        }
     }
   prevKeys[slot] = key;
   if(g == NULL || gN < 2)
      return;
   Bx *cur = NULL;
   if(g.gkl != NULL)
      cur = g.gkl;
   else
     {
      Bx *lb = g.boxes[g.NBoxes() - 1];
      if(lb.breakIndex == NAI)
         cur = lb;
     }
   if(cur == NULL)
      return;
   double lvls[5] = {0.5, 0.559, 0.618, 0.667, 0.786};
   bool   ons[5];
   ons[0] = al500; ons[1] = al559; ons[2] = al618; ons[3] = al667; ons[4] = al786;
   // "Near": half the 0.5 -> 0.559 distance before the level, on the side the price comes from.
   double dist = NEAR_SHARE * MathAbs(cur.top.price - cur.base);
   double low = gL[gN - 1], high = gH[gN - 1], prevLow = gL[gN - 2], prevHigh = gH[gN - 2];
   for(int i = 0; i < 5; i++)
     {
      if(!ons[i]) continue;
      double p = Lvl(cur.base, cur.top.price, lvls[i]);
      bool nowNear = g.lng ? low <= p + dist : high >= p - dist;
      bool wasAway = g.lng ? prevLow > p + dist : prevHigh < p - dist;
      if(nowNear && wasAway && lvlAlertBar[slot][i] != gTime)
        {
         lvlAlertBar[slot][i] = gTime;
         Notify(_Symbol + " " + PeriodStr() + ": SK " + name + " - price near " + NumStr(lvls[i]) + " (" + DoubleToString(p, _Digits) + ")");
        }
     }
  }

//---------------------------------------------------------------- liquidation levels
// A zone between two prices: every candle of the last liqLookback takes the prices it touched out of the
// parts still untouched; the rest reaches past the newest candle with "Liq" at its right end.
void DrawLiq(double pa, double pb, color ink)
  {
   if(!(pa > 0 && pb > 0 && pa != pb))
      return;
   double top = MathMax(pa, pb);
   double bot = MathMin(pa, pb);
   int last = gN - 1;
   int look = IMax(10, IMin(5000, liqLookback));
   int start = IMax(0, last - look + 1);
   double uLo[], uHi[], eLo[], eHi[];
   int eAt[];
   PushD(uLo, bot);
   PushD(uHi, top);
   int eatenAt = NAI;
   for(int k = start; k <= last; k++)
     {
      double ch = gH[k];
      double cl = gL[k];
      double nLo[], nHi[];
      for(int i = 0; i < ArraySize(uLo); i++)
        {
         double lo = uLo[i];
         double hi = uHi[i];
         if(cl > hi || ch < lo)
           {
            PushD(nLo, lo);
            PushD(nHi, hi);
           }
         else
           {
            if(ArraySize(eAt) < LIQ_MAX_PIECES)
              {
               PushD(eLo, MathMax(lo, cl));
               PushD(eHi, MathMin(hi, ch));
               PushI(eAt, k);
              }
            if(lo < cl) { PushD(nLo, lo); PushD(nHi, cl); }
            if(hi > ch) { PushD(nLo, ch); PushD(nHi, hi); }
           }
        }
      ArrayFree(uLo); ArrayFree(uHi);
      if(ArraySize(nLo) > 0) { ArrayCopy(uLo, nLo); ArrayCopy(uHi, nHi); }
      if(ArraySize(uLo) == 0)
        {
         eatenAt = k;
         break;
        }
     }
   if(eatenAt == NAI || last - eatenAt <= LIQ_LINGER)
     {
      color fill = Fade(ink, 87);
      for(int i = 0; i < ArraySize(eLo); i++)
         MkBox(IdxTime(start), eHi[i], IdxTime(IMax(eAt[i], start + 1)), eLo[i], clrNONE, 1, STYLE_SOLID, fill);
      double bigLo = 0, bigHi = 0;
      bool haveBig = false;
      for(int i = 0; i < ArraySize(uLo); i++)
        {
         double lo = uLo[i], hi = uHi[i];
         MkBox(IdxTime(start), hi, IdxTime(last + LIQ_REACH), lo, clrNONE, 1, STYLE_SOLID, fill);
         if(!haveBig || hi - lo > bigHi - bigLo)
           {
            bigLo = lo; bigHi = hi; haveBig = true;
           }
        }
      if(haveBig)
         MkText(IdxTime(last + LIQ_REACH), (bigLo + bigHi) / 2, "Liq", ST_LEFT, ink, SZ_SMALL);
     }
  }

//---------------------------------------------------------------- imbalances
bool ImbGone(Cs *cs, int k, bool up, double top, double bot, double mid)
  {
   if(imbFill == IMB_CLOSE) return up ? cs.c[k] < mid : cs.c[k] > mid;
   if(imbFill == IMB_FULL)  return up ? cs.l[k] <= bot : cs.h[k] >= top;
   if(imbFill == IMB_MID)   return up ? cs.l[k] <= mid : cs.h[k] >= mid;
   return false;
  }

// The still open gaps of a series, then the ones to show: Nearest - imbCount above and below the price;
// Newest - the newest imbCount (0: all). Each from the gap's first candle to the newest.
void DrawImbalances(Cs *cs, string name)
  {
   double mids[], tops[], bots[];
   bool   ups[];
   int    at[];
   int n = cs.Size();
   int k0 = IMax(2, n - IMB_LOOK);
   if(n > 2)
      for(int k = k0; k < n; k++)
        {
         if(imbFill != IMB_NEVER && ArraySize(mids) > 0)
            for(int i = ArraySize(mids) - 1; i >= 0; i--)
               if(at[i] + 3 <= k && ImbGone(cs, k, ups[i], tops[i], bots[i], mids[i]))
                 {
                  ArrayRemove(mids, i, 1); ArrayRemove(tops, i, 1); ArrayRemove(bots, i, 1);
                  ArrayRemove(ups, i, 1); ArrayRemove(at, i, 1);
                 }
         double aH = cs.h[k - 2], aL = cs.l[k - 2], cH = cs.h[k], cL = cs.l[k];
         if(cL > aH || cH < aL)
           {
            bool up = cL > aH;
            double top = up ? cL : aL;
            double bot = up ? aH : cH;
            PushD(mids, (top + bot) / 2);
            PushD(tops, top);
            PushD(bots, bot);
            PushB(ups, up);
            PushI(at, k - 2);
           }
        }
   int m = ArraySize(mids);
   if(m == 0)
      return;
   int cnt = (int)imbCount;
   bool keep[];
   ArrayResize(keep, m);
   bool keepAll = (cnt == 0 || m <= cnt);
   for(int i = 0; i < m; i++) keep[i] = keepAll;
   if(cnt > 0 && m > cnt)
     {
      if(imbPick == IMB_NEWEST)
         for(int i = m - cnt; i < m; i++) keep[i] = true;
      else
        {
         double price = gC[gN - 1];
         for(int side = 0; side <= 1; side++)
            for(int j = 1; j <= cnt; j++)
              {
               int best = -1;
               for(int i = 0; i < m; i++)
                 {
                  double d = mids[i];
                  bool onSide = side == 0 ? d > price : d <= price;
                  if(onSide && !keep[i])
                     if(best < 0 || MathAbs(d - price) < MathAbs(mids[best] - price))
                        best = i;
                 }
               if(best >= 0)
                  keep[best] = true;
              }
        }
     }
   long x2 = gTime + CHART_MS;
   color col = Fade(imbColIn, 20);
   for(int i = 0; i < m; i++)
      if(keep[i])
        {
         double y = mids[i];
         MkLine(Xt(cs, at[i]), y, x2, y, col, 1, STYLE_DASH);
         if(imbNames)
            MkText(x2, y, "Imbalance " + name, ST_LEFT, col, SZ_TINY);
        }
  }

//---------------------------------------------------------------- status box
string gStatTxt[];
color  gStatCol[];
int    gStatSz[];

void StatusAdd(string s, color c, int sz)
  {
   int n = ArraySize(gStatTxt);
   ArrayResize(gStatTxt, n + 1); ArrayResize(gStatCol, n + 1); ArrayResize(gStatSz, n + 1);
   gStatTxt[n] = s; gStatCol[n] = c; gStatSz[n] = sz;
  }

void StatusDraw()
  {
   int n = ArraySize(gStatTxt);
   if(n == 0) return;
   int maxW = 0, totalH = 0;
   int hs[];
   ArrayResize(hs, n);
   for(int i = 0; i < n; i++)
     {
      uint w = 0, h = 0;
      TextSetFont("Arial", -FontOf(gStatSz[i]) * 10);
      TextGetSize(gStatTxt[i], w, h);
      if((int)w > maxW) maxW = (int)w;
      hs[i] = (int)h + 4;
      totalH += hs[i];
     }
   // Placed by "Dashboard corner" and its X / Y offsets (px from that corner to the box's nearest edges).
   int pad = 6;
   int boxW = maxW + 2 * pad, boxH = totalH + 2 * pad;
   bool right = IsRightCorner(InpDashCorner), lower = IsLowerCorner(InpDashCorner);
   int bx = right ? InpDashX + boxW : InpDashX;
   int by = lower ? InpDashY + boxH : InpDashY;
   string bg = NewName();
   if(ObjectCreate(0, bg, OBJ_RECTANGLE_LABEL, 0, 0, 0))
     {
      ObjectSetInteger(0, bg, OBJPROP_CORNER, InpDashCorner);
      ObjectSetInteger(0, bg, OBJPROP_XDISTANCE, bx);
      ObjectSetInteger(0, bg, OBJPROP_YDISTANCE, by);
      ObjectSetInteger(0, bg, OBJPROP_XSIZE, boxW);
      ObjectSetInteger(0, bg, OBJPROP_YSIZE, boxH);
      ObjectSetInteger(0, bg, OBJPROP_BGCOLOR, Fade(clrBlack, 80));
      ObjectSetInteger(0, bg, OBJPROP_BORDER_TYPE, BORDER_FLAT);
      ObjectSetInteger(0, bg, OBJPROP_COLOR, Fade(clrBlack, 80));
      ObjectSetInteger(0, bg, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, bg, OBJPROP_HIDDEN, true);
      ObjectSetInteger(0, bg, OBJPROP_BACK, false);
     }
   int cum = 0;
   for(int i = 0; i < n; i++)
     {
      string nm = NewName();
      if(ObjectCreate(0, nm, OBJ_LABEL, 0, 0, 0))
        {
         ObjectSetInteger(0, nm, OBJPROP_CORNER, InpDashCorner);
         ObjectSetInteger(0, nm, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
         ObjectSetInteger(0, nm, OBJPROP_XDISTANCE, right ? bx - pad : bx + pad);
         ObjectSetInteger(0, nm, OBJPROP_YDISTANCE, lower ? by - pad - cum : by + pad + cum);
         ObjectSetString(0, nm, OBJPROP_TEXT, gStatTxt[i]);
         ObjectSetString(0, nm, OBJPROP_FONT, "Arial");
         ObjectSetInteger(0, nm, OBJPROP_FONTSIZE, FontOf(gStatSz[i]));
         ObjectSetInteger(0, nm, OBJPROP_COLOR, gStatCol[i]);
         ObjectSetInteger(0, nm, OBJPROP_SELECTABLE, false);
         ObjectSetInteger(0, nm, OBJPROP_HIDDEN, true);
        }
      cum += hs[i];
     }
  }

string DateOf(long t)
  {
   string s = TimeToString(Dt(t), TIME_DATE | TIME_MINUTES);
   StringReplace(s, ".", "-");
   return s;
  }

// A long text in lines of about `width` characters.
void WrapLines(string s, int width, string &out[])
  {
   ArrayFree(out);
   string words[];
   int nw = StringSplit(s, ' ', words);
   string line = "";
   for(int i = 0; i < nw; i++)
     {
      string w = words[i];
      if(StringLen(line) > 0 && StringLen(line) + 1 + StringLen(w) > width)
        {
         int n = ArraySize(out); ArrayResize(out, n + 1); out[n] = line;
         line = w;
        }
      else
         line = StringLen(line) > 0 ? line + " " + w : w;
     }
   if(StringLen(line) > 0) { int n = ArraySize(out); ArrayResize(out, n + 1); out[n] = line; }
  }

void StatusRow(bool on, Geo *g, string name, color ink, string none)
  {
   if(!showStatus || !on) return;
   string note = "";
   if(g != NULL)
     {
      Geo *p = BesideOf(g);
      note = !ShownHere(g) ? HiddenNote(g) : (p != NULL && !ShownHere(p)) ? " " + DOT + " smaller one" + HiddenNote(p) : "";
     }
   string s = name + " " + DOT + " " + (g == NULL ? none : StateOf(g) + " (" + TfName(SpanAt(g.cs, g.zero.index)) + ")" + note);
   StatusAdd(s, g == NULL ? clrGray : ink, SZ_SMALL);
  }

//---------------------------------------------------------------- the timeframe ladder
Cs *CsFromChart(string name)
  {
   Cs *c = NewCs();
   ArrayCopy(c.o, gO); ArrayCopy(c.h, gH); ArrayCopy(c.l, gL); ArrayCopy(c.c, gC); ArrayCopy(c.t, gT);
   c.spanMs = CHART_MS; c.coarse = false; c.name = name;
   return c;
  }

// One rung of the ladder (NULL: no candles). The chart's own timeframe: the chart's candles stand for it.
// Coarser than the chart: its newest candle built from the chart's own.
Cs *TierOf(ENUM_TIMEFRAMES tf, string name, int keep)
  {
   int sec = PeriodSeconds(tf);
   int chartSec = PeriodSeconds(_Period);
   if(sec == chartSec)
      return CsFromChart(name);
   MqlRates r[];
   ArraySetAsSeries(r, false);
   int got = CopyRates(_Symbol, tf, 0, keep, r);
   if(got <= 0)
     {
      gIncomplete = true;
      return NULL;
     }
   Cs *res = NewCs();
   res.spanMs = (long)sec * 1000;
   res.name = name;
   if(sec < chartSec)
     {
      for(int i = 0; i < got; i++)
         res.Push(r[i].open, r[i].high, r[i].low, r[i].close, (long)r[i].time * 1000, 0);
      res.coarse = false;
      return res;
     }
   long spanMs = (long)sec * 1000;
   long lastTfMs = (long)r[got - 1].time * 1000;
   long periodStart = gTime >= lastTfMs + spanMs ? lastTfMs + ((gTime - lastTfMs) / spanMs) * spanMs : lastTfMs;
   for(int i = 0; i < got; i++)
     {
      long t = (long)r[i].time * 1000;
      if(t >= periodStart) break;
      res.Push(r[i].open, r[i].high, r[i].low, r[i].close, t, 0);
     }
   // the current period rebuilt from the chart's candles
   int s = gN;
   {
    int lo = 0, hi = gN - 1;
    while(lo <= hi)
      {
       int mid = (lo + hi) / 2;
       if(gT[mid] >= periodStart) { s = mid; hi = mid - 1; }
       else lo = mid + 1;
      }
   }
   if(s < gN)
     {
      double hv = gH[s], lv = gL[s];
      for(int k = s; k < gN; k++)
        {
         hv = MathMax(hv, gH[k]);
         lv = MathMin(lv, gL[k]);
        }
      res.Push(gO[s], hv, lv, gC[gN - 1], periodStart, 0);
     }
   if(res.Size() == 0)
      return NULL;
   res.coarse = true;
   return res;
  }

// The ladder fine -> coarse.
void AddTier(Cs *&tiers[], Cs *cs)
  {
   if(cs == NULL) return;
   int n = ArraySize(tiers);
   int at = n;
   for(int i = 0; i < n; i++)
      if(tiers[i].spanMs > cs.spanMs) { at = i; break; }
   ArrayResize(tiers, n + 1);
   for(int i = n; i > at; i--) tiers[i] = tiers[i - 1];
   tiers[at] = cs;
  }

int IndexOfSec(int sec)
  {
   for(int i = 0; i < 6; i++) if(IMB_SECS[i] == sec) return i;
   return -1;
  }

//---------------------------------------------------------------- run
void Recalc()
  {
   gIncomplete = false;
   MqlRates cr[];
   ArraySetAsSeries(cr, false);
   int n = CopyRates(_Symbol, _Period, 0, IMax(100, InpMaxChartBars), cr);
   if(n < 3)
     {
      gDirty = true;
      return;
     }
   ArrayResize(gO, n); ArrayResize(gH, n); ArrayResize(gL, n); ArrayResize(gC, n); ArrayResize(gT, n);
   for(int i = 0; i < n; i++)
     {
      gO[i] = cr[i].open; gH[i] = cr[i].high; gL[i] = cr[i].low; gC[i] = cr[i].close;
      gT[i] = (long)cr[i].time * 1000;
     }
   gN = n;
   CHART_MS = (long)PeriodSeconds(_Period) * 1000;
   gTime = gT[n - 1];
   gBg = (color)ChartGetInteger(0, CHART_COLOR_BACKGROUND);
   gLastPMax = ChartGetDouble(0, CHART_PRICE_MAX);
   gLastPMin = ChartGetDouble(0, CHART_PRICE_MIN);
   gLastPxH  = ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);

   ObjectsDeleteAll(0, PREFIX);
   gObjN = 0;
   ArrayFree(LAB_X);
   ArrayFree(LAB_Y);
   ArrayFree(gStatTxt); ArrayFree(gStatCol); ArrayFree(gStatSz);
   // "The same spot" for names: one screen line height (fallback: 2.5 % of the last 300 chart candles).
   int labSpan = IMin(300, n);
   double mx = gH[n - labSpan], mn = gL[n - labSpan];
   for(int i = n - labSpan; i < n; i++) { mx = MathMax(mx, gH[i]); mn = MathMin(mn, gL[i]); }
   LAB_TOL = 0.025 * (mx - mn);
   if(gLastPxH > 0 && gLastPMax > gLastPMin)
      gPricePerPx = (gLastPMax - gLastPMin) / (double)gLastPxH;
   else
      gPricePerPx = (mx > mn) ? (mx - mn) / 500.0 : _Point * 10.0;
   uint tw = 0, th = 0;
   TextSetFont("Arial", -FontOf(SZ_NORMAL) * 10);
   TextGetSize("Ag", tw, th);
   int linePx = th > 0 ? (int)th + 3 : 16;
   gLabStep = linePx * gPricePerPx;
   gWickGap = 5.0 * gPricePerPx;
   if(gLabStep > 0.0)
      LAB_TOL = gLabStep;

   // The liquidation zones first: behind everything else.
   if(liqOn1) DrawLiq(liqA1, liqB1, liqC1);
   if(liqOn2) DrawLiq(liqA2, liqB2, liqC2);
   if(liqOn3) DrawLiq(liqA3, liqB3, liqC3);
   if(liqOn4) DrawLiq(liqA4, liqB4, liqC4);
   if(liqOn5) DrawLiq(liqA5, liqB5, liqC5);
   if(liqOn6) DrawLiq(liqA6, liqB6, liqC6);
   if(liqOn7) DrawLiq(liqA7, liqB7, liqC7);
   if(liqOn8) DrawLiq(liqA8, liqB8, liqC8);

   Cs *ch = CsFromChart("");
   Cs *tiers[];
   AddTier(tiers, TierOf(PERIOD_M1,  "1m",  PLAY_KEEP));
   AddTier(tiers, TierOf(PERIOD_M5,  "5m",  PLAY_KEEP));
   AddTier(tiers, TierOf(PERIOD_M15, "15m", PLAY_KEEP));
   AddTier(tiers, TierOf(PERIOD_M30, "30m", PLAY_KEEP));
   AddTier(tiers, TierOf(PERIOD_H1,  "1h",  PLAY_KEEP));
   AddTier(tiers, TierOf(PERIOD_H4,  "4h",  PLAY_KEEP));
   AddTier(tiers, TierOf(PERIOD_D1,  "1D",  PLAY_KEEP));
   AddTier(tiers, TierOf(PERIOD_W1,  "1W",  WEEK_KEEP));
   if(ArraySize(tiers) == 0 || tiers[ArraySize(tiers) - 1].spanMs < 7LL * 86400 * 1000)
      AddTier(tiers, CsFromChart(PeriodStr()));
   Cs *wk = tiers[ArraySize(tiers) - 1];

   // Imbalances: behind the sequences. The chart's column of the matrix.
   if(imbOn)
     {
      int col = IndexOfSec(PeriodSeconds(_Period));
      if(col >= 0)
         for(int i = 0; i < ArraySize(tiers); i++)
           {
            int row = IndexOfSec((int)MathRound(tiers[i].spanMs / 1000.0));
            if(row >= 0 && IMB_SHOW[row * 6 + col])
               DrawImbalances(tiers[i], IMB_NAMES[row]);
           }
     }

   // The sequences on one stitched series of all of them.
   Cs *played = Stitch(tiers, wk.spanMs);
   Geo *gLg = NULL, *gSg = NULL, *gL2 = NULL, *gS2 = NULL;
   bool sameL2 = false, sameS2 = false;
   if(played != NULL)
     {
      if(onL) gLg = FindKind(played, true, NAL);
      if(onS || onL2 || onS2) gSg = FindKind(played, false, NAL);
      if((onL2 || onS2) && gSg != NULL)
         gL2 = FindKind(played, true, ZeroEndOf(gSg));
      // The low after the ATH is the all-time low: not drawn twice.
      if(gL2 != NULL)
        {
         int iLow = ExtremeFrom(wk, 0, true);
         if(iLow >= 0)
           {
            double atl = MathMin(wk.l[iLow], gL[ExtremeFrom(ch, 0, true)]);
            sameL2 = MathAbs(gL2.zero.price - atl) <= MathAbs(atl) * 1e-9;
           }
        }
      if(onS2 && gL2 != NULL)
         gS2 = FindKind(played, false, ZeroEndOf(gL2));
      if(gS2 != NULL)
        {
         int iHigh = ExtremeFrom(wk, 0, false);
         if(iHigh >= 0)
           {
            double ath = MathMax(wk.h[iHigh], gH[ExtremeFrom(ch, 0, false)]);
            sameS2 = MathAbs(gS2.zero.price - ath) <= MathAbs(ath) * 1e-9;
           }
        }
      // The larger ones first: the nested ones lie over them.
      if(onL && gLg != NULL) DrawShown(gLg, colL);
      if(onS && gSg != NULL) DrawShown(gSg, colS);
      if(onL2 && gL2 != NULL && !sameL2) DrawShown(gL2, colL2);
      if(onS2 && gS2 != NULL && !sameS2) DrawShown(gS2, colS2);
     }

   // The all-time high: from its candle to the newest.
   if(showAth)
     {
      int iw = ExtremeFrom(wk, 0, false);
      if(iw >= 0)
        {
         double athPrice = wk.h[iw];
         long athTime = wk.t[iw];
         int ic = ExtremeFrom(ch, 0, false);
         if(gT[0] <= athTime || gH[ic] >= athPrice)
           {
            athPrice = MathMax(athPrice, gH[ic]);
            athTime = gT[ic];
           }
         MkLine(LMax(athTime, gT[0]), athPrice, gTime, athPrice, colAth, 1, STYLE_SOLID);
         MkText(gTime, athPrice, "ATH " + DoubleToString(athPrice, _Digits), ST_LEFT, colAth, SZ_SMALL);
        }
     }

   // Shown ones only.
   Geo *shS = onS ? gSg : NULL;
   Geo *shL2 = (onL2 && !sameL2) ? gL2 : NULL;
   Geo *shS2 = (onS2 && !sameS2) ? gS2 : NULL;
   StatusRow(onL, gLg, "Long (ATL)", colL, "none open");
   StatusRow(onS, shS, "Short (ATH)", colS, "none open");
   StatusRow(onL2, shL2, "Long 2", colL2, sameL2 ? "= Long" : "none open");
   StatusRow(onS2, shS2, "Short 2", colS2, sameS2 ? "= Short" : "none open");
   if(showStatus)
     {
      bool missing = (onL && gLg == NULL) || (onS && shS == NULL) || (onL2 && shL2 == NULL && !sameL2) || (onS2 && shS2 == NULL && !sameS2);
      if(showCheck || missing)
        {
         string zeros = (gLg == NULL ? "" : " " + DOT + " Long 0 " + DateOf(ZeroTimeOf(gLg)))
                        + (gSg == NULL ? "" : " " + DOT + " Short 0 " + DateOf(ZeroTimeOf(gSg)))
                        + (gL2 == NULL ? "" : " " + DOT + " Long 2 0 " + DateOf(ZeroTimeOf(gL2)))
                        + (gS2 == NULL ? "" : " " + DOT + " Short 2 0 " + DateOf(ZeroTimeOf(gS2)));
         string chk = played == NULL ? "Check: no candles"
                      : "Check: " + IntegerToString(played.Size()) + " candles " + played.name + " from " + DateOf(played.t[0]) + zeros;
         if(gIncomplete) chk += " " + DOT + " (history still loading)";
         string lines[];
         WrapLines(chk, 90, lines);
         for(int i = 0; i < ArraySize(lines); i++)
            StatusAdd(lines[i], clrGray, SZ_TINY);
        }
      StatusDraw();
     }
   // Alerts only on complete data (a ladder rung still loading would look like a new sequence).
   if(!gIncomplete)
     {
      AlertsFor(gLg, 0, "Long (ATL)");
      AlertsFor(shS, 1, "Short (ATH)");
      AlertsFor(shL2, 2, "Long 2");
      AlertsFor(shS2, 3, "Short 2");
     }
   // Off: worked out all the same (the alerts stay on), nothing left on the chart.
   if(!gOn)
      ObjectsDeleteAll(0, PREFIX);
   FreeAll();
   ChartRedraw(0);
   if(gIncomplete)
      gDirty = true;   // retry on the next timer tick
  }

//---------------------------------------------------------------- moving averages / events
void SetupMa(int idx, double &buf[], bool on, ENUM_SK_MA typ, int len, color col, int w)
  {
   int period = IMax(1, IMin(1000, len));
   SetIndexBuffer(idx, buf, INDICATOR_DATA);
   ArraySetAsSeries(buf, true);
   PlotIndexSetDouble(idx, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(idx, PLOT_LINE_COLOR, col);
   PlotIndexSetInteger(idx, PLOT_LINE_WIDTH, IMax(1, IMin(4, w)));
   PlotIndexSetInteger(idx, PLOT_DRAW_BEGIN, period - 1);
   PlotIndexSetString(idx, PLOT_LABEL, (typ == SK_EMA ? "EMA " : "SMA ") + IntegerToString(period));
   if(on)
     {
      PlotIndexSetInteger(idx, PLOT_DRAW_TYPE, DRAW_LINE);
      maH[idx] = iMA(_Symbol, _Period, period, 0, typ == SK_EMA ? MODE_EMA : MODE_SMA, PRICE_CLOSE);
     }
   else
     {
      PlotIndexSetInteger(idx, PLOT_DRAW_TYPE, DRAW_NONE);
      maH[idx] = INVALID_HANDLE;
     }
  }

int OnInit()
  {
   DOT = ShortToString(0x00B7);
   tolIn = MathMax(0.0, MathMin(50.0, tolPctIn)) / 100.0;
   for(int s = 0; s < 4; s++)
      for(int i = 0; i < 5; i++)
         lvlAlertBar[s][i] = 0;
   IMB_SHOW[0]  = imb_15m_15m; IMB_SHOW[1]  = imb_15m_30m; IMB_SHOW[2]  = imb_15m_1h; IMB_SHOW[3]  = imb_15m_4h; IMB_SHOW[4]  = imb_15m_1d; IMB_SHOW[5]  = imb_15m_1w;
   IMB_SHOW[6]  = imb_30m_15m; IMB_SHOW[7]  = imb_30m_30m; IMB_SHOW[8]  = imb_30m_1h; IMB_SHOW[9]  = imb_30m_4h; IMB_SHOW[10] = imb_30m_1d; IMB_SHOW[11] = imb_30m_1w;
   IMB_SHOW[12] = imb_1h_15m;  IMB_SHOW[13] = imb_1h_30m;  IMB_SHOW[14] = imb_1h_1h;  IMB_SHOW[15] = imb_1h_4h;  IMB_SHOW[16] = imb_1h_1d;  IMB_SHOW[17] = imb_1h_1w;
   IMB_SHOW[18] = imb_4h_15m;  IMB_SHOW[19] = imb_4h_30m;  IMB_SHOW[20] = imb_4h_1h;  IMB_SHOW[21] = imb_4h_4h;  IMB_SHOW[22] = imb_4h_1d;  IMB_SHOW[23] = imb_4h_1w;
   IMB_SHOW[24] = imb_1d_15m;  IMB_SHOW[25] = imb_1d_30m;  IMB_SHOW[26] = imb_1d_1h;  IMB_SHOW[27] = imb_1d_4h;  IMB_SHOW[28] = imb_1d_1d;  IMB_SHOW[29] = imb_1d_1w;
   IMB_SHOW[30] = imb_1w_15m;  IMB_SHOW[31] = imb_1w_30m;  IMB_SHOW[32] = imb_1w_1h;  IMB_SHOW[33] = imb_1w_4h;  IMB_SHOW[34] = imb_1w_1d;  IMB_SHOW[35] = imb_1w_1w;

   SetupMa(0, MaBuf1, ma1On, ma1Type, ma1Len, ma1Col, ma1W);
   SetupMa(1, MaBuf2, ma2On, ma2Type, ma2Len, ma2Col, ma2W);
   SetupMa(2, MaBuf3, ma3On, ma3Type, ma3Len, ma3Col, ma3W);
   SetupMa(3, MaBuf4, ma4On, ma4Type, ma4Len, ma4Col, ma4W);
   maOnIn[0] = ma1On; maOnIn[1] = ma2On; maOnIn[2] = ma3On; maOnIn[3] = ma4On;
   // The button kept through timeframe / settings changes: its state carries over.
   gOn = true;
   if(InpBtnShow && ObjectFind(0, BTN) >= 0)
      gOn = (bool)ObjectGetInteger(0, BTN, OBJPROP_STATE);
   UpdateButton();
   ApplyMaVisibility();
   IndicatorSetString(INDICATOR_SHORTNAME, "SK-Suite");
   IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
   EventSetMillisecondTimer(IMax(200, InpRecalcMs));
   gDirty = true;
   return INIT_SUCCEEDED;
  }

void OnDeinit(const int reason)
  {
   EventKillTimer();
   ObjectsDeleteAll(0, PREFIX);
   if(reason == REASON_REMOVE)
      ObjectDelete(0, BTN);
   for(int i = 0; i < 4; i++)
      if(maH[i] != INVALID_HANDLE) IndicatorRelease(maH[i]);
   FreeAll();
   ChartRedraw(0);
  }

bool CopyMa(int idx, double &buf[], int rates_total, int prev_calculated)
  {
   ArraySetAsSeries(buf, true);
   int toCopy = (prev_calculated <= 0 || prev_calculated > rates_total) ? rates_total : rates_total - prev_calculated + 1;
   if(maH[idx] == INVALID_HANDLE)
     {
      for(int i = 0; i < toCopy; i++) buf[i] = EMPTY_VALUE;
      return true;
     }
   if(BarsCalculated(maH[idx]) < rates_total)
      return false;
   return CopyBuffer(maH[idx], 0, 0, toCopy, buf) == toCopy;
  }

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 ok = true;
   ok = CopyMa(0, MaBuf1, rates_total, prev_calculated) && ok;
   ok = CopyMa(1, MaBuf2, rates_total, prev_calculated) && ok;
   ok = CopyMa(2, MaBuf3, rates_total, prev_calculated) && ok;
   ok = CopyMa(3, MaBuf4, rates_total, prev_calculated) && ok;
   gMaSynced = ok;
   gDirty = true;   // the drawing is worked out on the timer (throttled)
   if(!ok)
      return 0;
   return rates_total;
  }

void OnTimer()
  {
   if(!gMaSynced)
     {
      int total = ArraySize(MaBuf1);
      if(total > 0)
        {
         bool ok = true;
         ok = CopyMa(0, MaBuf1, total, 0) && ok;
         ok = CopyMa(1, MaBuf2, total, 0) && ok;
         ok = CopyMa(2, MaBuf3, total, 0) && ok;
         ok = CopyMa(3, MaBuf4, total, 0) && ok;
         if(ok)
           {
            gMaSynced = true;
            ChartRedraw(0);
           }
        }
     }
   if(!gDirty) return;
   gDirty = false;
   Recalc();
  }

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
  {
   if(id == CHARTEVENT_OBJECT_CLICK && sparam == BTN)
     {
      gOn = (bool)ObjectGetInteger(0, BTN, OBJPROP_STATE);
      UpdateButton();
      ApplyMaVisibility();
      gDirty = false;
      Recalc();
     }
   else if(id == CHARTEVENT_CHART_CHANGE)
     {
      color  bg   = (color)ChartGetInteger(0, CHART_COLOR_BACKGROUND);
      double pMax = ChartGetDouble(0, CHART_PRICE_MAX);
      double pMin = ChartGetDouble(0, CHART_PRICE_MIN);
      long   pxH  = ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
      if(bg != gBg || pxH != gLastPxH || MathAbs(pMax - gLastPMax) > 1e-12 || MathAbs(pMin - gLastPMin) > 1e-12)
         gDirty = true;
     }
  }
//+------------------------------------------------------------------+
