#property strict
#property version "1.00"
#property description "Edge Quant Turtle PDF study EA: PDF 20/10 and original Faith modes"

#include <Trade/Trade.mqh>

// https://howtotrade.com/wp-content/uploads/2024/10/The-Turtle-Trading-strategy.pdf
// https://www.tradingwithrayner.com/wp-content/uploads/2014/11/OriginalTurtleRules.pdf
enum TurtleMode { PDF20_10 = 0, FaithS1 = 1, FaithS2 = 2 };
enum CapitalMode { CurrentEquity = 0, ClosedBalance = 1, AnnualNotional = 2 };
input TurtleMode InpMode = PDF20_10;
input string InpBrokerSymbols = "";        // Blank = chart symbol. Otherwise comma-separated exact Market Watch names.
input uint InpPollMilliseconds = 250;      // Poll supplementary symbols at this interval.
input bool InpUseTimerInTester = false;    // Disable by default to avoid billions of timer events in long tests.
input double InpUnitPercent = 0.0;         // One N. Zero uses 0.5% for PDF or 1% for Faith.
input CapitalMode InpCapital = CurrentEquity;
input double InpAccountAllocation = 100.0;
input double InpYearNotional = 0.0;        // AnnualNotional only. Zero uses the allocated first observed balance.
input bool InpReduceNotionalOnLoss = true; // AnnualNotional only.
input bool InpWeeklySizingSheet = false;   // Faith sheet alternative; default refreshes N each completed session.
input int InpMaxUnits = 4;
input int InpMaxDirectionUnits = 0;        // Zero uses no PDF cap or 12 for Faith.
input string InpCloseGroups = "";          // Groups separated by semicolons; symbols within a group by commas.
input string InpLooseGroups = "";
input ulong InpMagic = 85112028;
input double InpMaxSpreadN = 0.15;         // Zero disables spread cap.
input double InpMarginPctFree = 50.0;
input uint InpDeviationPoints = 10;
input bool InpAllowOrdersOutsideTester = false;

struct Bands
{
   double hi10, lo10, hi20, lo20, hi55, lo55;
};

struct SymbolState
{
   string name, key;
   int digits;
   double point, tick_size;
   bool chart_last;
   Bands bands;
   double daily_n, sizing_n, previous, campaign_n, last_fill;
   double shadow_price, shadow_n;
   int shadow_side, campaign_side, used_units;
   bool previous_winner, restored, exit_all;
   datetime day, week;
   long last_msc;
   double last_bid, last_ask, last_trade;
};

CTrade g_trade;
SymbolState g_symbols[];
SymbolState g_state;
double g_year_balance, g_year_notional, g_worst_year_loss;
int g_year;
bool g_tester, g_hedging;
string g_account_key, g_lock;
string g_close_groups[], g_loose_groups[];

string GroupKey(string group)
{
   StringReplace(group, " ", "");
   StringToUpper(group);
   return "," + group + ",";
}

uint NameHash(const string value)
{
   uint result = 2166136261;
   for(int i = 0; i < StringLen(value); ++i)
      result = (uint)((result ^ (uint)StringGetCharacter(value, i)) * 16777619);
   return result;
}

void SplitGroups(const string value, string &groups[])
{
   if(StringLen(value) > 0)
      StringSplit(value, ';', groups);
   for(int i = 0; i < ArraySize(groups); ++i)
      groups[i] = GroupKey(groups[i]);
}

int ActiveUnitLimit()
{
   return InpMode == PDF20_10 ? 1 : InpMaxUnits;
}

int OnInit()
{
   if(InpUnitPercent < 0 || InpUnitPercent > 100 || InpAccountAllocation <= 0 || InpAccountAllocation > 100 ||
      InpYearNotional < 0 || InpMaxUnits < 1 || InpMaxUnits > 4 || InpMaxDirectionUnits < 0 ||
      InpMaxDirectionUnits > 12 || InpMagic == 0 || InpMaxSpreadN < 0 || InpMarginPctFree <= 0 ||
      InpMarginPctFree > 100 || InpPollMilliseconds < 100 || InpPollMilliseconds > 10000)
      return INIT_PARAMETERS_INCORRECT;
   g_hedging = AccountInfoInteger(ACCOUNT_MARGIN_MODE) == ACCOUNT_MARGIN_MODE_RETAIL_HEDGING;
   if(!g_hedging && InpMode != PDF20_10)
   {
      Print("Edge Quant Turtle: select an MT5 hedging account for separate unit stops.");
      return INIT_FAILED;
   }
   g_tester = MQLInfoInteger(MQL_TESTER) != 0;
   g_account_key = StringFormat("EQT.%I64d.%I64u.%08X", AccountInfoInteger(ACCOUNT_LOGIN), InpMagic,
                                NameHash(AccountInfoString(ACCOUNT_SERVER)));
   g_lock = g_account_key + ".lock";
   SplitGroups(InpCloseGroups, g_close_groups);
   SplitGroups(InpLooseGroups, g_loose_groups);
   g_trade.SetExpertMagicNumber(InpMagic);
   g_trade.SetDeviationInPoints(InpDeviationPoints);
   g_trade.SetAsyncMode(false);
   g_trade.SetMarginMode();
   if(!g_tester && InpAllowOrdersOutsideTester && !GlobalVariableCheck(g_lock) &&
      !GlobalVariableTemp(g_lock) && !GlobalVariableCheck(g_lock))
      return INIT_FAILED;

   string requested[];
   StringSplit(StringLen(InpBrokerSymbols) > 0 ? InpBrokerSymbols : _Symbol, ',', requested);
   for(int i = 0; i < ArraySize(requested); ++i)
   {
      string symbol = requested[i];
      StringTrimLeft(symbol);
      StringTrimRight(symbol);
      if(StringLen(symbol) == 0)
         continue;
      int used = ArraySize(g_symbols);
      bool duplicate = false;
      for(int j = 0; j < used && !duplicate; ++j)
         duplicate = g_symbols[j].name == symbol;
      if(duplicate)
         continue;
      SymbolState initial = {};
      initial.name = symbol;
      if(!SymbolSelect(symbol, true))
      {
         PrintFormat("Edge Quant Turtle: cannot select broker symbol %s.", symbol);
         return INIT_PARAMETERS_INCORRECT;
      }
      initial.chart_last = SymbolInfoInteger(symbol, SYMBOL_CHART_MODE) == SYMBOL_CHART_MODE_LAST;
      initial.tick_size = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
      initial.digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
      initial.point = SymbolInfoDouble(symbol, SYMBOL_POINT);
      initial.key = g_account_key + StringFormat(".%08X", NameHash(symbol));
      if(initial.tick_size <= 0 || initial.point <= 0)
      {
         PrintFormat("Edge Quant Turtle: missing trade properties for %s.", symbol);
         return INIT_PARAMETERS_INCORRECT;
      }
      ArrayResize(g_symbols, used+1);
      g_symbols[used] = initial;
   }
   if(ArraySize(g_symbols) == 0)
      return INIT_PARAMETERS_INCORRECT;
   if((!g_tester || InpUseTimerInTester) && (ArraySize(g_symbols) > 1 || g_symbols[0].name != _Symbol) &&
      !EventSetMillisecondTimer((int)InpPollMilliseconds))
      return INIT_FAILED;
   PrintFormat("Edge Quant Turtle: %d symbol(s) on broker D1 bars. Account currency: %s.",
               ArraySize(g_symbols), AccountInfoString(ACCOUNT_CURRENCY));
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   EventKillTimer();
}

bool TradingEnabled()
{
   return g_tester || (InpAllowOrdersOutsideTester && TerminalInfoInteger(TERMINAL_CONNECTED) &&
          TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED) &&
          AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) && AccountInfoInteger(ACCOUNT_TRADE_EXPERT));
}

double TrueRange(const MqlRates &bar, const double previous_close)
{
   return MathMax(bar.high - bar.low, MathMax(bar.high - previous_close, previous_close - bar.low));
}

Bands PreviousBands(const MqlRates &bars[], const int end)
{
   Bands bands;
   bands.hi10 = bands.hi20 = bands.hi55 = bars[end-1].high;
   bands.lo10 = bands.lo20 = bands.lo55 = bars[end-1].low;
   for(int i = 2; i <= 55 && i <= end; ++i)
   {
      double hi = bars[end-i].high;
      double lo = bars[end-i].low;
      if(i <= 10)
      {
         bands.hi10 = MathMax(bands.hi10, hi);
         bands.lo10 = MathMin(bands.lo10, lo);
      }
      if(i <= 20)
      {
         bands.hi20 = MathMax(bands.hi20, hi);
         bands.lo20 = MathMin(bands.lo20, lo);
      }
      bands.hi55 = MathMax(bands.hi55, hi);
      bands.lo55 = MathMin(bands.lo55, lo);
   }
   return bands;
}

datetime WeekKey(const datetime day)
{
   MqlDateTime stamp = {};
   TimeToStruct(day, stamp);
   int after_monday = (stamp.day_of_week + 6) % 7;
   stamp.hour = stamp.min = stamp.sec = 0;
   return StructToTime(stamp) - after_monday * 86400;
}

double LongTrigger(const double high) { return high + g_state.tick_size; }
double ShortTrigger(const double low) { return low - g_state.tick_size; }
bool AtOrAbove(const double value, const double level) { return value >= level - g_state.tick_size * 1e-6; }
bool AtOrBelow(const double value, const double level) { return value <= level + g_state.tick_size * 1e-6; }

void SettleShadow(const bool winner)
{
   g_state.shadow_side = 0;
   g_state.previous_winner = winner;
}

void StartShadow(const int side, const double price, const double n)
{
   g_state.shadow_side = side;
   g_state.shadow_price = price;
   g_state.shadow_n = n;
}

void SeedShadowDay(const MqlRates &bar, const Bands &bands, const double n)
{
   if(g_state.shadow_side != 0)
   {
      double stop = g_state.shadow_price - g_state.shadow_side * 2.0 * g_state.shadow_n;
      if(g_state.shadow_side == 1)
      {
         double channel = ShortTrigger(bands.lo10);
         if(AtOrBelow(bar.open, MathMax(stop, channel)))
            SettleShadow(bar.open > g_state.shadow_price);
         else if(AtOrBelow(bar.low, MathMax(stop, channel)))
            SettleShadow(channel > g_state.shadow_price);
      }
      else
      {
         double channel = LongTrigger(bands.hi10);
         if(AtOrAbove(bar.open, MathMin(stop, channel)))
            SettleShadow(bar.open < g_state.shadow_price);
         else if(AtOrAbove(bar.high, MathMin(stop, channel)))
            SettleShadow(channel < g_state.shadow_price);
      }
      return;
   }
   double up = LongTrigger(bands.hi20), down = ShortTrigger(bands.lo20);
   bool hit_up = AtOrAbove(bar.high, up), hit_down = AtOrBelow(bar.low, down);
   // An opening gap establishes sequence. Otherwise skip a historical day with both breakouts.
   int side = AtOrAbove(bar.open, up) || (hit_up && !hit_down) ? 1 :
              (AtOrBelow(bar.open, down) || (hit_down && !hit_up) ? -1 : 0);
   if(side == 0)
      return;
   double entry = side == 1 ? MathMax(bar.open, up) : MathMin(bar.open, down);
   StartShadow(side, entry, n);
   // A same-day touch of the adverse barrier is assumed to follow the historical entry.
   if(side == 1 && AtOrBelow(bar.low, MathMax(entry-2*n, ShortTrigger(bands.lo10))))
      SettleShadow(false);
   if(side == -1 && AtOrAbove(bar.high, MathMin(entry+2*n, LongTrigger(bands.hi10))))
      SettleShadow(false);
}

bool RefreshLevels()
{
   datetime day = iTime(g_state.name, PERIOD_D1, 0);
   if(day == 0)
      return false;
   if(day == g_state.day)
      return true;
   MqlRates bars[];
   int requested = (g_state.day == 0 && InpMode == FaithS1) ? 850 : 260;
   int count = CopyRates(g_state.name, PERIOD_D1, 1, requested, bars);
   int required = InpMode == PDF20_10 ? 21 : 55;
   if(count < required || bars[count-1].time >= day || !SeriesInfoInteger(g_state.name, PERIOD_D1, SERIES_SYNCHRONIZED))
      return false;
   double n = 0, weekly_n = 0;
   datetime prior_week = 0;
   for(int i = 1; i < count; ++i)
   {
      datetime week = WeekKey(bars[i].time);
      if(week != prior_week)
      {
         prior_week = week;
         weekly_n = n;
      }
      if(g_state.day == 0 && InpMode == FaithS1 && i >= 55 && n > 0)
         SeedShadowDay(bars[i], PreviousBands(bars, i), InpWeeklySizingSheet && weekly_n > 0 ? weekly_n : n);
      double tr = TrueRange(bars[i], bars[i-1].close);
      n = i <= 20 ? n + tr / 20.0 : (19.0 * n + tr) / 20.0;
   }
   if(n <= 0)
      return false;
   if(g_state.day == 0 && g_tester)
      g_state.previous = bars[count-1].close;
   g_state.bands = PreviousBands(bars, count);
   g_state.day = day;
   g_state.daily_n = n;
   datetime week = WeekKey(day);
   if(g_state.week != week)
   {
      g_state.week = week;
      g_state.sizing_n = InpWeeklySizingSheet && week == prior_week && weekly_n > 0 ? weekly_n : n;
   }
   if(!InpWeeklySizingSheet)
      g_state.sizing_n = g_state.daily_n;
   return g_state.sizing_n > 0;
}

int Breakout(const double quote, const double previous, const double high, const double low)
{
   double up = LongTrigger(high), down = ShortTrigger(low);
   if(!AtOrAbove(previous, up) && AtOrAbove(quote, up))
      return 1;
   if(!AtOrBelow(previous, down) && AtOrBelow(quote, down))
      return -1;
   return 0;
}

int UpdateShadow(const double quote, const double previous)
{
   if(g_state.shadow_side == 1)
   {
      if(AtOrBelow(quote, MathMax(g_state.shadow_price-2*g_state.shadow_n, ShortTrigger(g_state.bands.lo10))))
         SettleShadow(quote > g_state.shadow_price);
      return 0;
   }
   if(g_state.shadow_side == -1)
   {
      if(AtOrAbove(quote, MathMin(g_state.shadow_price+2*g_state.shadow_n, LongTrigger(g_state.bands.hi10))))
         SettleShadow(quote < g_state.shadow_price);
      return 0;
   }
   if(previous <= 0)
      return 0;
   int signal = Breakout(quote, previous, g_state.bands.hi20, g_state.bands.lo20);
   if(signal != 0)
      StartShadow(signal, quote, g_state.sizing_n);
   return signal;
}

int SelectUnits(ulong &tickets[], int &side)
{
   ArrayResize(tickets, 0);
   side = 0;
   for(int i = PositionsTotal()-1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0 || PositionGetString(POSITION_SYMBOL) != g_state.name)
         continue;
      if((ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic)
      {
         if(!g_hedging)
            return -1;
         continue;
      }
      string label = PositionGetString(POSITION_COMMENT);
      string own = StringFormat("OT-S%d-U", (int)InpMode);
      if(StringFind(label, "OT-S") == 0 && StringFind(label, own) != 0)
         return -1;
      int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
      if(side != 0 && side != direction)
         return -1;
      side = direction;
      int size = ArraySize(tickets);
      ArrayResize(tickets, size+1);
      tickets[size] = ticket;
   }
   return ArraySize(tickets);
}

bool AnyGroupAtLimit(const string &groups[], const string &open_symbols[], const int cap)
{
   string candidate = GroupKey(g_state.name);
   for(int i = 0; i < ArraySize(groups); ++i)
   {
      if(StringFind(groups[i], candidate) < 0)
         continue;
      int used = 0;
      for(int j = 0; j < ArraySize(open_symbols); ++j)
         if(StringFind(groups[i], GroupKey(open_symbols[j])) >= 0)
            used++;
      if(used >= cap)
         return true;
   }
   return false;
}

bool CheckCaps(const int side, const int active)
{
   if(active >= ActiveUnitLimit())
      return false;
   string open_symbols[];
   for(int i = PositionsTotal()-1; i >= 0; --i)
   {
      if(PositionGetTicket(i) == 0 || (ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;
      int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
      if(direction != side)
         continue;
      int count = ArraySize(open_symbols);
      ArrayResize(open_symbols, count+1);
      open_symbols[count] = PositionGetString(POSITION_SYMBOL);
   }
   for(int i = OrdersTotal()-1; i >= 0; --i)
      if(OrderGetTicket(i) != 0 && ((ulong)OrderGetInteger(ORDER_MAGIC) == InpMagic ||
         (!g_hedging && OrderGetString(ORDER_SYMBOL) == g_state.name)))
         return false;
   int direction_cap = InpMaxDirectionUnits > 0 ? InpMaxDirectionUnits : (InpMode == PDF20_10 ? 0 : 12);
   return (direction_cap == 0 || ArraySize(open_symbols) < direction_cap) &&
          !AnyGroupAtLimit(g_close_groups, open_symbols, 6) &&
          !AnyGroupAtLimit(g_loose_groups, open_symbols, 10);
}

void UpdateYearlyLoss(const datetime now)
{
   MqlDateTime stamp = {};
   TimeToStruct(now, stamp);
   double balance = AccountInfoDouble(ACCOUNT_BALANCE);
   string year_key = g_account_key + StringFormat(".%d", stamp.year);
   if(g_year != stamp.year)
   {
      g_year = stamp.year;
      g_year_balance = balance;
      g_worst_year_loss = 0;
      if(!g_tester && !GlobalVariableGet(year_key+".bal", g_year_balance))
         GlobalVariableSet(year_key+".bal", g_year_balance = balance);
      g_year_notional = InpYearNotional > 0 ? InpYearNotional : g_year_balance * InpAccountAllocation / 100.0;
   }
   double prior = g_worst_year_loss;
   if(!g_tester)
      GlobalVariableGet(year_key+".loss", prior);
   double loss = g_year_balance-balance;
   g_worst_year_loss = loss <= 0 ? 0 : MathMax(prior, loss);
   if(!g_tester && prior != g_worst_year_loss)
      GlobalVariableSet(year_key+".loss", g_worst_year_loss);
}

double SizingCapital()
{
   double fraction = InpAccountAllocation / 100.0;
   if(InpCapital == CurrentEquity)
      return AccountInfoDouble(ACCOUNT_EQUITY) * fraction;
   if(InpCapital == ClosedBalance)
      return AccountInfoDouble(ACCOUNT_BALANCE) * fraction;
   double notional = g_year_notional;
   if(!InpReduceNotionalOnLoss)
      return notional;
   double threshold = 0;
   for(int i = 0; i < 50 && notional > 0; ++i)
   {
      threshold += .1 * notional;
      if(g_worst_year_loss < threshold)
         return notional;
      notional *= .8;
   }
   return 0;
}

double RoundStop(const double price, const int side)
{
   double ticks = price / g_state.tick_size;
   return NormalizeDouble((side == 1 ? MathFloor(ticks+1e-9) : MathCeil(ticks-1e-9)) * g_state.tick_size, g_state.digits);
}

bool ValidStop(const double stop, const int side, const MqlTick &tick, const bool modifies)
{
   long points = SymbolInfoInteger(g_state.name, SYMBOL_TRADE_STOPS_LEVEL);
   if(modifies)
      points = (long)MathMax(points, SymbolInfoInteger(g_state.name, SYMBOL_TRADE_FREEZE_LEVEL));
   double distance = side == 1 ? tick.bid-stop : stop-tick.ask;
   return stop > 0 && distance > 0 && distance >= points*g_state.point;
}

double UnitLots(const int side, const double n, const double quote)
{
   ENUM_ORDER_TYPE order = side == 1 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   double minimum = SymbolInfoDouble(g_state.name, SYMBOL_VOLUME_MIN);
   double maximum = SymbolInfoDouble(g_state.name, SYMBOL_VOLUME_MAX);
   double step = SymbolInfoDouble(g_state.name, SYMBOL_VOLUME_STEP);
   double unit_percent = InpUnitPercent > 0 ? InpUnitPercent : (InpMode == PDF20_10 ? 0.5 : 1.0);
   double target = SizingCapital() * unit_percent / 100.0;
   double free = AccountInfoDouble(ACCOUNT_MARGIN_FREE) * InpMarginPctFree / 100.0;
   double loss = 0, margin = 0;
   double adverse = quote - side*n;
   if(minimum <= 0 || step <= 0 || target <= 0 || free <= 0 || adverse <= 0 ||
      !OrderCalcProfit(order, g_state.name, minimum, quote, adverse, loss) || loss >= 0 ||
      !OrderCalcMargin(order, g_state.name, minimum, quote, margin) || margin <= 0)
      return 0;
   double unit_limit = MathMin(maximum, target * minimum / -loss);
   double broker_limit = SymbolInfoDouble(g_state.name, SYMBOL_VOLUME_LIMIT);
   if(broker_limit > 0)
   {
      double already = 0;
      for(int i = PositionsTotal()-1; i >= 0; --i)
         if(PositionGetTicket(i) != 0 && PositionGetString(POSITION_SYMBOL) == g_state.name &&
            (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1) == side)
            already += PositionGetDouble(POSITION_VOLUME);
      unit_limit = MathMin(unit_limit, broker_limit-already);
   }
   if(unit_limit < minimum)
      return 0;
   double lots = NormalizeDouble(minimum + MathFloor((unit_limit-minimum)/step+1e-9) * step, 8);
   if(!OrderCalcProfit(order, g_state.name, lots, quote, adverse, loss) || -loss > target+1e-8 ||
      !OrderCalcMargin(order, g_state.name, lots, quote, margin) || margin > free+1e-8)
      return 0;
   return lots;
}

void StoreCampaign()
{
   if(g_tester)
      return;
   GlobalVariableSet(g_state.key+".side", g_state.campaign_side);
   GlobalVariableSet(g_state.key+".last", g_state.last_fill);
   GlobalVariableSet(g_state.key+".n", g_state.campaign_n);
   GlobalVariableSet(g_state.key+".units", g_state.used_units);
   GlobalVariablesFlush();
}

void RestoreCampaign(const int side, const int active)
{
   if(g_state.restored)
      return;
   g_state.restored = true;
   if(g_tester || active == 0)
      return;
   double saved_side=0, n=0, last=0, units=0;
   if(GlobalVariableGet(g_state.key+".side", saved_side) && GlobalVariableGet(g_state.key+".n", n) &&
      GlobalVariableGet(g_state.key+".last", last) && GlobalVariableGet(g_state.key+".units", units) &&
      (int)saved_side == side && n > 0 && last > 0 && units >= active && units <= ActiveUnitLimit())
   {
      g_state.campaign_side = side;
      g_state.campaign_n = n;
      g_state.last_fill = last;
      g_state.used_units = (int)units;
   }
   else
      Print("Edge Quant Turtle: campaign add state unavailable. Existing stops and channel exits remain active.");
}

bool TradeDone(const bool sent)
{
   uint code = g_trade.ResultRetcode();
   return sent && (code == TRADE_RETCODE_DONE || code == TRADE_RETCODE_DONE_PARTIAL || code == TRADE_RETCODE_NO_CHANGES);
}

void CloseUnits(const ulong &tickets[])
{
   if(!g_trade.SetTypeFillingBySymbol(g_state.name))
      return;
   for(int i = 0; i < ArraySize(tickets); ++i)
      if(PositionSelectByTicket(tickets[i]) && !TradeDone(g_trade.PositionClose(tickets[i], InpDeviationPoints)))
         PrintFormat("Edge Quant Turtle close ticket %I64u: %u", tickets[i], g_trade.ResultRetcode());
}

bool AllowedOrder(const int side)
{
   long mode = SymbolInfoInteger(g_state.name, SYMBOL_TRADE_MODE);
   long flags = SymbolInfoInteger(g_state.name, SYMBOL_ORDER_MODE);
   return (mode == SYMBOL_TRADE_MODE_FULL || (side == 1 && mode == SYMBOL_TRADE_MODE_LONGONLY) ||
          (side == -1 && mode == SYMBOL_TRADE_MODE_SHORTONLY)) &&
          (flags & SYMBOL_ORDER_MARKET) != 0 && (flags & SYMBOL_ORDER_SL) != 0;
}

ulong FindNewTicket(const ulong &older[])
{
   for(int i = PositionsTotal()-1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0 || PositionGetString(POSITION_SYMBOL) != g_state.name ||
         (ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;
      bool seen = false;
      for(int j = 0; j < ArraySize(older) && !seen; ++j)
         seen = older[j] == ticket;
      if(!seen)
         return ticket;
   }
   return 0;
}

void AddUnit(const int side, const MqlTick &tick, const ulong &old_tickets[])
{
   int active = ArraySize(old_tickets);
   if(!AllowedOrder(side) || !CheckCaps(side, active) || !g_trade.SetTypeFillingBySymbol(g_state.name))
      return;
   double n = active == 0 ? g_state.sizing_n : g_state.campaign_n;
   double price = side == 1 ? tick.ask : tick.bid;
   if(n <= 0 || (InpMaxSpreadN > 0 && tick.ask-tick.bid > InpMaxSpreadN*n))
      return;
   double stop = RoundStop(price-side*2*n, side);
   double lots = ValidStop(stop, side, tick, false) ? UnitLots(side, n, price) : 0;
   if(lots <= 0)
      return;
   string comment = StringFormat("OT-S%d-U%d", (int)InpMode, active == 0 ? 1 : g_state.used_units+1);
   bool sent = side == 1 ? g_trade.Buy(lots, g_state.name, price, stop, 0, comment) :
                          g_trade.Sell(lots, g_state.name, price, stop, 0, comment);
   if(!TradeDone(sent))
   {
      PrintFormat("Edge Quant Turtle unit: %u %s", g_trade.ResultRetcode(), g_trade.ResultRetcodeDescription());
      // Some exchange venues acknowledge the order before filling. Disable adds until flat.
      if(g_trade.ResultRetcode() == TRADE_RETCODE_PLACED)
         g_state.campaign_n = 0;
      return;
   }
   if(active == 0)
   {
      g_state.campaign_n = n;
      g_state.campaign_side = side;
      g_state.used_units = 0;
   }
   g_state.used_units++;
   g_state.last_fill = g_trade.ResultPrice();
   ulong new_ticket = FindNewTicket(old_tickets);
   MqlTick latest = {};
   if(!SymbolInfoTick(g_state.name, latest))
      latest = tick;
   if(PositionSelectByTicket(new_ticket))
   {
      g_state.last_fill = PositionGetDouble(POSITION_PRICE_OPEN);
      double actual_stop = RoundStop(g_state.last_fill-side*2*n, side);
      if(MathAbs(actual_stop-PositionGetDouble(POSITION_SL)) >= g_state.tick_size*.5 &&
         (!ValidStop(actual_stop, side, latest, true) || !TradeDone(g_trade.PositionModify(new_ticket, actual_stop, 0))))
         g_state.exit_all = true;
   }
   if(g_state.last_fill <= 0 || new_ticket == 0)
      g_state.campaign_n = 0;
   for(int i=0; i<active; ++i)
   {
      if(!PositionSelectByTicket(old_tickets[i]))
         continue;
      double prior = PositionGetDouble(POSITION_SL);
      string prefix = StringFormat("OT-S%d-U", (int)InpMode);
      string label = PositionGetString(POSITION_COMMENT);
      int sequence = StringFind(label, prefix) == 0 ? (int)StringToInteger(StringSubstr(label, StringLen(prefix))) : 0;
      double unrounded = sequence > 0 && sequence < g_state.used_units ?
                         PositionGetDouble(POSITION_PRICE_OPEN) + side*(-2.0+.5*(g_state.used_units-sequence))*n :
                         prior+side*.5*n;
      double raised = RoundStop(unrounded, side);
      raised = side == 1 ? MathMax(raised, prior) : MathMin(raised, prior);
      if(prior > 0 && MathAbs(raised-prior) < g_state.tick_size*.5)
         continue;
      // Move each earlier stop by half N, even if the newest fill gapped.
      if(prior <= 0 || !ValidStop(raised, side, latest, true) ||
         !TradeDone(g_trade.PositionModify(old_tickets[i], raised, 0)))
         g_state.exit_all = true;
   }
   StoreCampaign();
   if(g_state.exit_all)
   {
      ulong current[];
      int direction = 0;
      if(SelectUnits(current, direction) > 0)
         CloseUnits(current);
   }
}

void PlaceWithCaps(const int side, const MqlTick &tick, const ulong &tickets[])
{
   if(!g_tester && !GlobalVariableSetOnCondition(g_lock, 1, 0))
      return;
   AddUnit(side, tick, tickets);
   if(!g_tester)
      GlobalVariableSet(g_lock, 0);
}

void ProcessSymbol()
{
   MqlTick tick = {};
   if(!SymbolInfoTick(g_state.name, tick) || tick.bid <= 0 || tick.ask < tick.bid)
      return;
   double quote = g_state.chart_last ? tick.last : tick.bid;
   if(quote <= 0 || (tick.time_msc == g_state.last_msc &&
      tick.bid == g_state.last_bid && tick.ask == g_state.last_ask && tick.last == g_state.last_trade))
      return;
   if(!RefreshLevels())
      return;
   g_state.last_msc = tick.time_msc;
   g_state.last_bid = tick.bid;
   g_state.last_ask = tick.ask;
   g_state.last_trade = tick.last;
   double previous = g_state.previous;
   g_state.previous = quote;
   int s1 = InpMode == FaithS1 ? UpdateShadow(quote, previous) : 0;
   if(!TradingEnabled())
      return;
   if(InpCapital == AnnualNotional)
      UpdateYearlyLoss(TimeCurrent());
   ulong tickets[];
   int side = 0;
   int active = SelectUnits(tickets, side);
   if(active < 0)
      return;
   RestoreCampaign(side, active);
   if(active > 0)
   {
      double exit_low = InpMode == FaithS2 ? g_state.bands.lo20 : g_state.bands.lo10;
      double exit_high = InpMode == FaithS2 ? g_state.bands.hi20 : g_state.bands.hi10;
      if(InpMode != PDF20_10)
      {
         exit_low = ShortTrigger(exit_low);
         exit_high = LongTrigger(exit_high);
      }
      if(g_state.exit_all || (side == 1 && AtOrBelow(quote, exit_low)) ||
         (side == -1 && AtOrAbove(quote, exit_high)))
      {
         g_state.exit_all = true;
         CloseUnits(tickets);
         return;
      }
      double add_trigger = g_state.last_fill + side*.5*g_state.campaign_n;
      // Compare on the traded side of the quote, and space all units from actual fills.
      bool add = side == 1 ? AtOrAbove(tick.ask, add_trigger) : AtOrBelow(tick.bid, add_trigger);
      if(g_state.campaign_side == side && g_state.campaign_n > 0 && g_state.used_units < ActiveUnitLimit() && add)
         PlaceWithCaps(side, tick, tickets);
      return;
   }
   g_state.exit_all = false;
   g_state.campaign_side = 0;
   g_state.campaign_n = g_state.last_fill = 0;
   g_state.used_units = 0;
   if(previous <= 0)
      return;
   int signal = 0;
   if(InpMode == PDF20_10)
      signal = Breakout(quote, previous, g_state.bands.hi20, g_state.bands.lo20);
   else if(InpMode == FaithS2 || g_state.previous_winner)
      signal = Breakout(quote, previous, g_state.bands.hi55, g_state.bands.lo55);
   else
      signal = s1;
   if(signal != 0)
      PlaceWithCaps(signal, tick, tickets);
}

void ProcessSymbols()
{
   for(int i = 0; i < ArraySize(g_symbols); ++i)
   {
      g_state = g_symbols[i];
      ProcessSymbol();
      g_symbols[i] = g_state;
   }
}

void OnTick()
{
   ProcessSymbols();
}

void OnTimer()
{
   ProcessSymbols();
}
