//+------------------------------------------------------------------+
//|                                            KagiLineReversal.mq5   |
//|                                                          Algobot  |
//|                                       https://www.algobot.live    |
//+------------------------------------------------------------------+
//  Kagi-chart trend-reversal system driven by yang/yin thickness flips.
//
//  Like Renko / Point-&-Figure / Three-Line-Break, the Kagi line discards
//  time and price noise: it keeps extending in its current direction as
//  price makes new extremes, and only REVERSES when price retraces by an
//  ATR-scaled "reversal amount" (so the chart auto-adapts to volatility).
//
//  Each reversal stamps a turning point:
//    * an up-line that reverses down leaves a "shoulder" (local peak),
//    * a down-line that reverses up leaves a "waist"    (local trough).
//
//  Tradable signal = Kagi line THICKNESS change (strictly alternating):
//    * rising line clears the prior shoulder -> thin(yin)->thick(yang) -> BUY
//    * falling line breaks the prior waist   -> thick(yang)->thin(yin) -> SELL
//
//  Behaves as a clean stop-and-reverse engine. SL/TP are ATR multiples
//  anchored at the fill.
//+------------------------------------------------------------------+
#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

#include <Trade\Trade.mqh>
CTrade trade;

//--- inputs -------------------------------------------------------------------
input double ReversalMult = 1.0;    // Kagi reversal amount = ReversalMult * ATR (bigger => fewer, larger swings)
input int    AtrPeriod    = 14;     // ATR lookback (sizes reversal amount AND stop/target distances)
input double StopAtrMult  = 2.5;    // Protective stop distance, in ATRs, from entry
input double TpAtrMult    = 4.0;    // Take-profit distance, in ATRs, from entry
input double Lots         = 0.10;   // Trade volume
input long   Magic        = 7413;   // Magic number

//--- indicator handles --------------------------------------------------------
int g_atr = INVALID_HANDLE;

//--- Kagi chart state (persists across bars) ----------------------------------
int    g_dir         = 0;      // current line direction: 0 = unseeded, +1 up, -1 down
double g_tip         = 0.0;    // current line tip (running extreme in the active direction)
double g_seedClose   = 0.0;    // reference close used to establish the very first direction
bool   g_hasSeed     = false;  // stands in for _seedClose == NaN
double g_prevShoulder= 0.0;    // last peak  (up->down turning point)
bool   g_hasShoulder = false;  // stands in for _prevShoulder == NaN
double g_prevWaist   = 0.0;    // last trough(down->up turning point)
bool   g_hasWaist    = false;  // stands in for _prevWaist == NaN
int    g_thick       = 0;      // current thickness: +1 yang(bull), -1 yin(bear), 0 neutral

//+------------------------------------------------------------------+
//| Expert initialization                                            |
//+------------------------------------------------------------------+
int OnInit()
{
    trade.SetExpertMagicNumber(Magic);

    g_atr = iATR(_Symbol, _Period, AtrPeriod);
    if(g_atr == INVALID_HANDLE)
    {
        Print("KagiLineReversal: failed to create ATR handle");
        return INIT_FAILED;
    }

    // reset Kagi state (mirrors OnInit in the C# source)
    g_dir          = 0;
    g_tip          = 0.0;
    g_seedClose    = 0.0;
    g_hasSeed      = false;
    g_prevShoulder = 0.0;
    g_hasShoulder  = false;
    g_prevWaist    = 0.0;
    g_hasWaist     = false;
    g_thick        = 0;

    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert deinitialization                                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    if(g_atr != INVALID_HANDLE) IndicatorRelease(g_atr);
}

//+------------------------------------------------------------------+
//| Tick handler � acts once per freshly closed bar                  |
//+------------------------------------------------------------------+
void OnTick()
{
    if(!IsNewBar()) return;

    // Need a full ATR window before the Kagi reversal amount is meaningful.
    if(Bars(_Symbol, _Period) < AtrPeriod + 2) return;

    // ATR aligned to the just-closed bar (shift 1), mirroring the C# buffer
    // whose newest element is ctx.Bar(sym,tf,1).
    double atrBuf[];
    ArraySetAsSeries(atrBuf, true);
    if(CopyBuffer(g_atr, 0, 0, 3, atrBuf) < 3) return;
    double atr = atrBuf[1];
    if(atr <= 0.0) return;

    double reversal = ReversalMult * atr;
    if(reversal <= 0.0) return;

    // Close of the bar that just closed (shift 1).
    double closed = iClose(_Symbol, _Period, 1);

    bool buySignal  = false;
    bool sellSignal = false;
    UpdateKagi(closed, reversal, buySignal, sellSignal);

    if(buySignal)
        EnterLong(atr);
    else if(sellSignal)
        EnterShort(atr);
}

//+------------------------------------------------------------------+
//| Core Kagi state machine                                          |
//|  Extends the line on new extremes, reverses on a full counter-   |
//|  move of `reversal`, stamps shoulders/waists, toggles yang/yin.  |
//+------------------------------------------------------------------+
void UpdateKagi(double c, double reversal, bool &buySignal, bool &sellSignal)
{
    buySignal  = false;
    sellSignal = false;

    // Establish the first direction from a seed close.
    if(g_dir == 0)
    {
        if(!g_hasSeed) { g_seedClose = c; g_hasSeed = true; return; }
        if(c >= g_seedClose + reversal)      { g_dir = +1; g_tip = c; }
        else if(c <= g_seedClose - reversal) { g_dir = -1; g_tip = c; }
        return; // direction only just born � no shoulder/waist yet, so no signal
    }

    if(g_dir == +1)
    {
        if(c > g_tip)
        {
            g_tip = c;                      // extend the up-line
        }
        else if(c <= g_tip - reversal)
        {
            g_prevShoulder = g_tip;         // this peak is now a shoulder
            g_hasShoulder  = true;
            g_dir = -1;
            g_tip = c;                      // start the down-line
        }
    }
    else // g_dir == -1
    {
        if(c < g_tip)
        {
            g_tip = c;                      // extend the down-line
        }
        else if(c >= g_tip + reversal)
        {
            g_prevWaist = g_tip;            // this trough is now a waist
            g_hasWaist  = true;
            g_dir = +1;
            g_tip = c;                      // start the up-line
        }
    }

    // Thickness rule: rising line clearing the prior shoulder => yang (buy);
    // falling line breaking the prior waist => yin (sell). Strictly alternating.
    if(g_dir == +1 && g_hasShoulder && g_tip > g_prevShoulder && g_thick != +1)
    {
        g_thick   = +1;
        buySignal = true;
    }
    else if(g_dir == -1 && g_hasWaist && g_tip < g_prevWaist && g_thick != -1)
    {
        g_thick    = -1;
        sellSignal = true;
    }
}

//+------------------------------------------------------------------+
//| Open a long (fresh yang): stop-and-reverse                       |
//+------------------------------------------------------------------+
void EnterLong(double atr)
{
    CloseSide(POSITION_TYPE_SELL);                 // close any short first
    if(HasPositionSide(POSITION_TYPE_BUY)) return; // already aligned

    double entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double sl    = NormalizeDouble(entry - StopAtrMult * atr, _Digits);
    double tp    = NormalizeDouble(entry + TpAtrMult   * atr, _Digits);

    if(trade.Buy(Lots, _Symbol, 0.0, sl, tp, "KagiYang"))
        PrintFormat("Kagi yang (thin->thick) long @ %.5f SL %.5f TP %.5f", entry, sl, tp);
    else
        PrintFormat("Kagi yang long failed: %d", trade.ResultRetcode());
}

//+------------------------------------------------------------------+
//| Open a short (fresh yin): stop-and-reverse                       |
//+------------------------------------------------------------------+
void EnterShort(double atr)
{
    CloseSide(POSITION_TYPE_BUY);                   // close any long first
    if(HasPositionSide(POSITION_TYPE_SELL)) return; // already aligned

    double entry = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double sl    = NormalizeDouble(entry + StopAtrMult * atr, _Digits);
    double tp    = NormalizeDouble(entry - TpAtrMult   * atr, _Digits);

    if(trade.Sell(Lots, _Symbol, 0.0, sl, tp, "KagiYin"))
        PrintFormat("Kagi yin (thick->thin) short @ %.5f SL %.5f TP %.5f", entry, sl, tp);
    else
        PrintFormat("Kagi yin short failed: %d", trade.ResultRetcode());
}

//+------------------------------------------------------------------+
//| True if this EA holds a position of the given side on _Symbol    |
//+------------------------------------------------------------------+
bool HasPositionSide(ENUM_POSITION_TYPE ptype)
{
    for(int i = PositionsTotal()-1; i >= 0; i--)
    {
        ulong t = PositionGetTicket(i);
        if(PositionSelectByTicket(t) &&
           PositionGetString(POSITION_SYMBOL) == _Symbol &&
           PositionGetInteger(POSITION_MAGIC) == Magic &&
           (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == ptype)
            return true;
    }
    return false;
}

//+------------------------------------------------------------------+
//| Close every position of the given side owned by this EA          |
//+------------------------------------------------------------------+
void CloseSide(ENUM_POSITION_TYPE ptype)
{
    for(int i = PositionsTotal()-1; i >= 0; i--)
    {
        ulong t = PositionGetTicket(i);
        if(PositionSelectByTicket(t) &&
           PositionGetString(POSITION_SYMBOL) == _Symbol &&
           PositionGetInteger(POSITION_MAGIC) == Magic &&
           (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == ptype)
            trade.PositionClose(t);
    }
}

//+------------------------------------------------------------------+
//| New-bar detector                                                 |
//+------------------------------------------------------------------+
bool IsNewBar()
{
    static datetime last = 0;
    datetime cur = iTime(_Symbol, _Period, 0);
    if(cur != last){ last = cur; return true; }
    return false;
}
//+------------------------------------------------------------------+
