// CVT LT DRIOD BOT NO ERRORS | FLOWNEXUSFORGE
#property strict
#property copyright "LICENSED BY FLOWNEXUSFORGE"
#property description "CVT LT DRIOD BOT NO ERRORS | Closed-bar strategy fusion and adaptive positive trailing stops."
enum VectorWorkspace {
   VECTOR_CHART=0,     // Chart strategies and preset collection
   VECTOR_PORTFOLIO=1  // Multi-symbol trading console
};
input VectorWorkspace InpWorkspace=VECTOR_CHART; // Active workspace
input double ApexGate=0.10;   // Neural entry threshold
input double ApexRate=0.06;   // Neural learning rate (exponential sample weight)
input double ApexRetain=0.55; // Excursion retained before neural adjustment
input bool ApexPortfolioStructure=true; // Add three-bar structure profit lock to portfolio ultra mode
input double VectorArmR=0.75;        // Ultra lock activation in initial-risk multiples
input int VectorCostTicks=2;         // Extra estimated round-trip costs in trade ticks
input int VectorStepTicks=2;         // Minimum improvement for an ultra stop
input int VectorServerUTCMinutes=0;  // Broker server offset from UTC, in minutes
input bool VectorConsoleLock=true;   // Add ultra lock to portfolio trailing

input bool PrideUseMA=true; // Williams filter: above/below 20-period average
input bool PrideUseChop=true; // Williams filter: 12-bar choppiness below threshold
input bool PrideUseVolume=true; // Williams filter: tick volume above its 50-bar mean
input bool PrideUseBands=false; // Williams filter: relative band width above 50-bar mean
input bool PrideUseST=false; // Williams filter: Supertrend (10, 3)
input double PrideCI=38.2;
input bool PrideFriday=true; // Control and combined modes: flat after Friday 16:45 New York
input double PrideRetreat=0.30; // R retraced from peak before tightening
input double PrideKeep=0.72; // Fraction of peak targeted on retracement
input double PrideMaxSpreadATR=0.12; // New chart modes: max entry spread as fraction of ATR (0 disables)
input bool PrideConsolePeak=true; // Add peak retreat stop to portfolio ultra management
enum PrideAverage { PRIDE_EMA=0, PRIDE_SMA=1, PRIDE_WMA=2, PRIDE_HMA=3 };
input PrideAverage PrideMA=PRIDE_EMA; // UT confirmation moving average
input int PridePathBars=12; // Closed bars for directional efficiency
input double PrideTrendFloor=0.35; // Minimum directional efficiency for a trend entry
input int PrideMaxDelaySeconds=45; // Maximum delay from the signal close for automatic routed entries (0 disables)
input bool PridePortfolioLock=true; // Add the staged profit stop to portfolio ultra management
input bool PrideEnableRealAccounts=false; // Allow initialization on real-money accounts

// Signed efficiency ranges from -1 to 1. Series index 0 is the newest sample.
double PrideEfficiency(const double &values[],int shift,int span)
{
   if(span<2 || shift<0 || shift+span>=ArraySize(values)) return 0;
   double path=0;
   for(int j=shift;j<shift+span;j++) path+=MathAbs(values[j]-values[j+1]);
   return path>0 ? MathMax(-1.0,MathMin(1.0,(values[shift]-values[shift+span])/path)) : 0;
}

// Absolute route codes: 1 trend, 2 pivot reversal, 3 overnight, 4 gold. Zero holds.
int PrideRoute(int flip,int ma,int localBias,int hourBias,int asym,int pivot,int night,
              int gold,int rsiTurn,double efficiency,double threshold,double adx,double ratio,bool extended,bool flagConflict=false)
{
   if(extended || asym==0 || hourBias==0 || ratio<=0 || ratio>1.30 ||
      threshold<=0 || threshold>=1 || MathAbs(efficiency)>1 || !MathIsValidNumber(ratio+adx+efficiency)) return 0;
   int chosen=0;
   for(int d=-1;d<=1;d+=2) {
      bool aligned=ma==d && localBias==d && hourBias==d;
      bool trend=flip==d && aligned && asym==d && d*efficiency>=threshold && adx>=20;
      bool turn=pivot==d && rsiTurn==d && MathAbs(efficiency)<threshold && adx<25;
      bool overnight=night==d && ma==d && asym==d && d*efficiency>0 && ratio<=1.10;
      bool metal=d==1 && gold==1 && aligned && efficiency>=threshold;
      int route=metal ? 4 : trend ? 1 : turn ? 2 : overnight ? 3 : 0;
      if(route==0) continue;
      if(chosen!=0) return flagConflict ? 99 : 0;
      chosen=d*route;
   }
   return chosen;
}

// Use realized excursion, signed path efficiency, initial risk and executable bid/ask.
// All monetary inputs are price distances. A return of zero leaves the existing SL alone.
double PrideStagedStop(int side,double entry,double oldSL,double market,double peak,double risk,
                      double atr,double efficiency,double cost,double distance,double tick,double arm,int steps,
                      double retreat=0.0,double keep=0.0)
{
   if((side!=1 && side!=-1) || entry<=0 || oldSL<0 || market<=0 || peak<=0 || risk<=0 ||
      atr<=0 || cost<0 || distance<0 || tick<=0 || arm<=0 || steps<1 || MathAbs(efficiency)>1 ||
      !MathIsValidNumber(entry+oldSL+market+peak+risk+atr+efficiency+cost+distance+tick+arm)) return 0;
   double run=side*(peak-entry),eps=tick*1e-7;
   if(run+eps<arm*risk || side*(peak-market)<-eps) return 0;
   double support=MathMax(0.0,MathMin(1.0,side*efficiency));
   double covered=entry+side*(cost+tick);
   double floorPrice=tick*(side>0 ? MathCeil(covered/tick-1e-9) : MathFloor(covered/tick+1e-9));
   double gain=side*(floorPrice-entry);
   if(run+eps>=(arm+0.50)*risk) gain=MathMax(gain,(0.65-0.25*support)*run);
   if(run+eps>=(arm+1.25)*risk) gain=MathMax(gain,run-(0.75+support)*atr);
   if(!MathIsValidNumber(retreat+keep) || retreat<0 || keep<0 || keep>0.95) return 0;
   if(retreat>0 && keep>0 && run+eps>=(arm+0.25)*risk) {
      double stageShare=MathMin(keep,0.30+0.10*MathMax(0.0,run/risk-1.0));
      if(side*(peak-market)+eps>=retreat*risk) stageShare=keep;
      gain=MathMax(gain,run*stageShare);
   }
   double room=MathMax(tick,distance),edge=market-side*room,raw=entry+side*gain;
   raw=side>0 ? MathMin(raw,edge) : MathMax(raw,edge);
   double sl=tick*(side>0 ? MathFloor(raw/tick+1e-9) : MathCeil(raw/tick-1e-9));
   if(sl<=0 || side*(sl-entry)+eps<cost+tick || side*(market-sl)+eps<room ||
      (oldSL>0 && side*(sl-oldSL)+eps<steps*tick)) return 0;
   return sl;
}

// All distances below are in price units. Zero means keep the broker stop.
double VectorPositiveStop(int side,double entry,double oldStop,double market,double best,
                          double risk,double atr,double strength,double cost,double distance,
                          double tick,double arm,int stepTicks)
{
   if((side!=1 && side!=-1) || entry<=0 || market<=0 || best<=0 || risk<=0 ||
      atr<=0 || tick<=0 || distance<0 || cost<0 || arm<=0 || stepTicks<1) return 0;
   if(!MathIsValidNumber(entry+oldStop+market+best+risk+atr+strength+cost+distance+tick+arm)) return 0;
   double excursion=side*(best-entry);
   if(excursion<arm*risk) return 0;
   double strength01=MathMax(0.0,MathMin(1.0,(strength-15.0)/25.0));
   double retain=0.60-0.20*strength01;
   if(excursion>=2*risk) retain+=0.10;
   double floorGain=MathMax(tick,cost+tick);
   double lockGain=MathMax(floorGain,MathMax(retain*excursion,excursion-atr*(1.0+strength01)));
   double proposed=entry+side*lockGain;
   double legalEdge=market-side*MathMax(tick,distance);
   proposed=side>0 ? MathMin(proposed,legalEdge) : MathMax(proposed,legalEdge);
   double units=proposed/tick;
   double aligned=tick*(side>0 ? MathFloor(units+1e-9) : MathCeil(units-1e-9));
   double eps=tick*1e-7;
   if(aligned<=0 || side*(aligned-entry)+eps<floorGain ||
      side*(market-aligned)+eps<MathMax(tick,distance)) return 0;
   if(oldStop>0 && side*(aligned-oldStop)+eps<stepTicks*tick) return 0;
   return aligned;
}

double ApexProfitLock(int side,double entry,double oldStop,double market,double best,double risk,
                      double atr,double cost,double distance,double tick,double arm,int stepTicks,
                      double retain,double support,double structure,bool useStructure)
{
   if((side!=1 && side!=-1) || entry<=0 || market<=0 || best<=0 || risk<=0 || atr<=0 ||
      cost<0 || distance<0 || tick<=0 || arm<=0 || stepTicks<1 || retain<=0 || retain>=1) return 0;
   if(!MathIsValidNumber(entry+oldStop+market+best+risk+atr+cost+distance+tick+arm+retain+support+structure)) return 0;
   double excursion=side*(best-entry), floorGain=cost+tick;
   if(excursion<arm*risk) return 0;
   double gain;
   if(useStructure) {
      if(structure<=0) return 0;
      gain=side*(structure-entry)-0.15*atr;
      if(gain<floorGain) return 0;
   } else {
      double share=MathMax(0.25,MathMin(0.88,retain-0.16*side*support+(excursion>=2.0*risk ? 0.08 : 0.0)));
      gain=MathMax(floorGain,share*excursion);
   }
   double room=MathMax(tick,distance), edge=market-side*room,raw=entry+side*gain;
   raw=side>0 ? MathMin(raw,edge) : MathMax(raw,edge);
   double next=tick*(side>0 ? MathFloor(raw/tick+1e-9) : MathCeil(raw/tick-1e-9));
   double eps=1e-7*tick;
   if(next<=0 || side*(next-entry)+eps<floorGain || side*(market-next)+eps<room) return 0;
   if(oldStop>0 && side*(next-oldStop)+eps<stepTicks*tick) return 0;
   return next;
}

// CVT LT DRIOD BOT NO ERRORS Smart Trail blends peak excursion, closed-bar momentum,
// volatility and the most recent three-bar structure. It can only tighten
// an existing stop and only returns a stop that locks costs plus one tick.
double CVTLTDriodSmartStop(int side,double entry,double oldSL,double market,double peak,
                              double risk,double atr,double efficiency,double adx,double structure,
                              double cost,double distance,double tick,double arm,int steps)
{
   if((side!=1 && side!=-1) || entry<=0 || oldSL<0 || market<=0 || peak<=0 ||
      risk<=0 || atr<=0 || cost<0 || distance<0 || tick<=0 || arm<=0 || steps<1 ||
      MathAbs(efficiency)>1 || adx<0 || !MathIsValidNumber(entry+oldSL+market+peak+risk+atr+
      efficiency+adx+structure+cost+distance+tick+arm)) return 0;
   double excursion=side*(peak-entry),eps=tick*1e-7;
   if(excursion+eps<arm*risk || side*(peak-market)<-eps) return 0;
   double trend=MathMax(0.0,MathMin(1.0,side*efficiency));
   double strength=MathMax(0.0,MathMin(1.0,(adx-15.0)/25.0));
   double momentum=0.65*trend+0.35*strength;
   double floorGain=cost+tick;
   double gain=MathMax(floorGain,(0.42+0.30*momentum)*excursion);
   if(excursion+eps>=1.0*risk) gain=MathMax(gain,0.20*risk);
   if(excursion+eps>=1.5*risk) gain=MathMax(gain,0.38*risk);
   if(excursion+eps>=2.0*risk) gain=MathMax(gain,0.58*risk);
   if(excursion+eps>=3.0*risk) gain=MathMax(gain,0.78*risk);
   double atrCandidate=market-side*(1.35+1.10*momentum)*atr;
   double atrGain=side*(atrCandidate-entry);
   if(atrGain>=floorGain) gain=MathMax(gain,atrGain);
   if(structure>0) {
      double structureCandidate=structure-side*0.10*atr;
      double structureGain=side*(structureCandidate-entry);
      if(structureGain>=floorGain) gain=MathMax(gain,structureGain);
   }
   double room=MathMax(tick,distance),edge=market-side*room;
   double raw=entry+side*gain;
   raw=side>0 ? MathMin(raw,edge) : MathMax(raw,edge);
   double aligned=tick*(side>0 ? MathFloor(raw/tick+1e-9) : MathCeil(raw/tick-1e-9));
   if(aligned<=0 || side*(aligned-entry)+eps<floorGain || side*(market-aligned)+eps<room ||
      (oldSL>0 && side*(aligned-oldSL)+eps<steps*tick)) return 0;
   return aligned;
}

// Each confirmation tests a distinct property. A single ATR flip gets one trigger.
int VectorDecision(int flip,int maState,int priceBias,int hourBias,int asymState,
                   int pivot,int night,int gold,double adx,double atrRatio,bool extended)
{
   if(extended || atrRatio<=0 || atrRatio>1.30) return 0;
   int trend=0;
   if(flip!=0 && maState==flip && priceBias==flip && hourBias==flip &&
      adx>=20 && (asymState==flip || gold==flip)) trend=flip;
   int reversal=(pivot!=0 && asymState==pivot) ? pivot : 0;
   int overnight=(night!=0 && maState==night && asymState==night) ? night : 0;
   bool longSetup=trend>0 || reversal>0 || overnight>0;
   bool shortSetup=trend<0 || reversal<0 || overnight<0;
   if(longSetup==shortSetup) return 0;
   return longSetup ? 1 : -1;
}

bool VectorGoldSymbol(string symbol)
{
   string base=SymbolInfoString(symbol,SYMBOL_CURRENCY_BASE);
   string quote=SymbolInfoString(symbol,SYMBOL_CURRENCY_PROFIT);
   StringToUpper(base); StringToUpper(quote); StringToUpper(symbol);
   if(quote!="" && quote!="USD") return false;
   return (base=="XAU" && quote=="USD") || StringFind(symbol,"XAUUSD")>=0 ||
          (StringFind(symbol,"GOLD")>=0 && quote=="USD");
}

//+------------------------------------------------------------------+
//|                       CVT LT DRIOD BOT NO ERRORS                        |
//|                    LICENSED BY FLOWNEXUSFORGE                     |
//+------------------------------------------------------------------+
//| Smart multi-strategy robot trader for MetaTrader 4 and           |
//| MetaTrader 5 (one shared source). Named strategies, positive-    |
//| only trailing stop locks, regime / session / news intelligence,  |
//| adaptive lot sizing, equity protection, movable and resizable    |
//| themed dashboards and the CVT LT DRIOD BOT NO ERRORS robot mascot.         |
//| Trading carries risk. Test on a demo account before live use.    |
//+------------------------------------------------------------------+

#ifdef __MQL5__
#include <Trade\Trade.mqh>
CTrade g_trade;
#endif

#define CT_NAME      "CVT LT DRIOD BOT NO ERRORS"
#define CT_LICENSE   "LICENSED BY FLOWNEXUSFORGE"
#define CT_PFX       "VXRD_"
#define CT_COMMENT   "CVT LT DRIOD BOT NO ERRORS"
#define CT_MAXBARS   2000
#define CT_PANELS    4

//--- Strategies: every value carries its full descriptive name (shown in the inputs dropdown).
enum CTStrategy
  {
   STRAT_UT_EMA200=0,        // UT Bot ATR Trailing + 200 EMA Filter
   STRAT_UT_HTF_EMA_ADX=1,   // UT Bot + Higher-Timeframe 200 EMA + ADX Strength
   STRAT_UT_MA_VS_TRAIL=2,   // UT Bot Moving Average vs ATR Trailing Stop
   STRAT_UT_CLASSIC=3,       // UT Bot Classic ATR Trailing Stop Flip
   STRAT_UT_DUAL_ENGINE=4,   // UT Bot Dual-Engine Asymmetric Ceiling and Floor
   STRAT_UT_SNIPER=5,        // UT Sniper Reversal: Pivot + Bollinger Zone + ATR Spike Guard
   STRAT_SYNAPSE=6,          // Synapse Adaptive Ratchet Band Scalper
   STRAT_MTF_TRAIL=7,        // Multi-Timeframe ATR Trailing Stop Consensus
   STRAT_BB_TREND_SCALP=8,   // Bollinger Band Trend Scalper with ATR Sideways Filter
   STRAT_KALMAN_ST=9,        // Kalman Supertrend Flip
   STRAT_KALMAN_VWMA_REV=10, // Kalman Supertrend + VWMA Zone Reversal
   STRAT_CONFLUENCE=11,      // Smart Multi-Indicator Confluence Score
   STRAT_REGIME=12,          // Regime Adaptive Switch: Trend Engine or Range Engine
   STRAT_EMA_PULLBACK=13,    // EMA 21/50 Trend Pullback with RSI Reset
   STRAT_SQUEEZE=14,         // Bollinger-Keltner Squeeze Breakout
   STRAT_VECTOR=15,          // ATR Trend Pivot and Overnight Confluence
   STRAT_GOLD_STRICT=16,     // Gold M15 long with closed H1 EMA and ADX
   STRAT_PANDICH=17,         // Pandich asymmetric ATR 300 / 1
   STRAT_EXPRESS=18,         // New York overnight adaptive trail
   STRAT_NEURAL_TREND=19, // Neural Trend Continuation
   STRAT_NEURAL_TURN=20, // Neural Reversal Timing
   STRAT_NEURAL_AGREE=21, // Neural Horizon Agreement
   STRAT_HA_SAR=22, // Opening Session Heikin Ashi Parabolic SAR
   STRAT_FRACTAL_EMA=23, // Confirmed Fractal with Triple EMA Alignment
   STRAT_BIONICK_ELITE=24, // UT Momentum with EMA ADX and RSI Confirmation
   STRAT_BIONICK_BB=25, // Bollinger Reentry with RSI Confirmation
   STRAT_PRIDE=26, // Adaptive UT signal selection
   STRAT_ZONE=27, // Williams R zone
   STRAT_CONTROL=28, // UT momentum control
   STRAT_COMBINED=29 // CVT LT DRIOD BOT NO ERRORS Fusion
  };
#define CT_STRAT_COUNT 30

//--- Positive trailing stop modes: they only lock profit and never loosen a stop.
enum CTTrail
  {
   TRAIL_OFF=0,              // Off: initial stop loss only
   TRAIL_UT_ATR=1,           // UT Bot ATR Trailing Stop Lock
   TRAIL_MTF_ATR=2,          // Multi-Timeframe ATR Trailing Stop Lock
   TRAIL_KALMAN_ST=3,        // Kalman Supertrend Line Lock
   TRAIL_STEP_LOCK=4,        // Step-Lock Profit Ladder
   TRAIL_BREAKEVEN_PLUS=5,   // Breakeven Plus Buffer
   TRAIL_CHANDELIER=6,       // Chandelier Exit Lock
   TRAIL_SWING=7,            // Swing-Structure Lock
   TRAIL_VOL_ADAPTIVE=8,     // Volatility-Adaptive ATR Lock
   TRAIL_PERCENT=9,          // Percent-of-Price Trailing Lock
   TRAIL_SYNAPSE=10,         // Synapse EMA Ratchet Band Lock
   TRAIL_SMART_HYBRID=11,    // Smart Hybrid: tightest valid profit lock
   TRAIL_VECTOR_ULTRA=12,    // Ultra positive adaptive lock
   TRAIL_NEURAL=13, // Neural Excursion Profit Lock
   TRAIL_STRUCTURE_FLOOR=14, // Three-Bar Structure Profit Lock
   TRAIL_PRIDE=15, // Ultra smart positive trailing SL
   TRAIL_PEAK=16, // Ultra peak protection
   TRAIL_CVT_LT_DRIOD=17 // CVT LT DRIOD BOT NO ERRORS Smart Trail: momentum + ATR + structure + peak retention
  };
#define CT_TRAIL_COUNT 18

enum CTMode
  {
   MODE_AUTO=0,              // Automatic trading
   MODE_SEMI=1,              // Semi-automatic: manual entries, automatic management
   MODE_SIGNALS=2            // Signals and alerts only
  };

enum CTDirection
  {
   DIR_BOTH=0,               // Long and short
   DIR_LONG=1,               // Long only
   DIR_SHORT=2               // Short only
  };

enum CTLotMode
  {
   LOT_FIXED=0,              // Fixed lot
   LOT_RISK=1,               // Risk percent of equity
   LOT_ADAPTIVE=2            // Adaptive: risk percent scaled by confluence and drawdown
  };

enum CTSize
  {
   SIZE_XS=0,                // Extra small (75%)
   SIZE_S=1,                 // Small (88%)
   SIZE_M=2,                 // Medium (100%)
   SIZE_L=3,                 // Large (115%)
   SIZE_XL=4                 // Extra large (130%)
  };

//--- Colour themes: selectable by name and cycled by the THEME buttons.
enum CTTheme
  {
   THEME_ANDROID_GREEN=0,    // Android Green
   THEME_MIDNIGHT_NEON=1,    // Midnight Neon
   THEME_OCEAN_BLUE=2,       // Ocean Blue
   THEME_CARBON_GOLD=3,      // Carbon Gold
   THEME_LIGHT_MINT=4,       // Light Mint
   THEME_CYBER_VIOLET=5,     // Cyber Violet
   THEME_DROID_LIME=6,       // Droid Lime
   THEME_ROBOT_STEEL=7,      // Robot Steel
   THEME_ARCTIC_ICE=8,       // Arctic Ice
   THEME_SOLAR_FLARE=9,      // Solar Flare
   THEME_CRIMSON_PULSE=10,   // Crimson Pulse
   THEME_ROYAL_SAPPHIRE=11,  // Royal Sapphire
   THEME_EMERALD_MATRIX=12,  // Emerald Matrix
   THEME_GRAPHITE_ORANGE=13, // Graphite Orange
   THEME_SAKURA_PINK=14,     // Sakura Pink
   THEME_LAVENDER_DREAM=15,  // Lavender Dream
   THEME_DEEP_TEAL=16,       // Deep Ocean Teal
   THEME_DESERT_SAND=17,     // Desert Sand
   THEME_VOLCANIC_EMBER=18,  // Volcanic Ember
   THEME_AURORA=19,          // Aurora Borealis
   THEME_POLAR_NIGHT=20,     // Polar Night
   THEME_GOLDEN_HOUR=21,     // Golden Hour
   THEME_NEON_TOKYO=22,      // Neon Tokyo
   THEME_FOREST_MOSS=23,     // Forest Moss
   THEME_COBALT_CIRCUIT=24,  // Cobalt Circuit
   THEME_RUBY_NIGHT=25,      // Ruby Night
   THEME_AMBER_TERMINAL=26,  // Amber Terminal
   THEME_PASTEL_CANDY=27,    // Pastel Candy
   THEME_MONOCHROME_PRO=28,  // Monochrome Pro
   THEME_PAPER_WHITE=29,     // Paper White
   THEME_BLUEPRINT=30,       // Blueprint
   THEME_BUBBLEGUM_BOT=31,   // Bubblegum Bot
   THEME_MINT_CHOCOLATE=32,  // Mint Chocolate
   THEME_COPPER_PATINA=33,   // Copper Patina
   THEME_GALAXY_PURPLE=34,   // Galaxy Purple
   THEME_SUNSET_CORAL=35,    // Sunset Coral
   THEME_MATRIX_RAIN=36,     // Matrix Rain
   THEME_TITANIUM_SILVER=37, // Titanium Silver
   THEME_JADE_TEMPLE=38,     // Jade Temple
   THEME_FLOOR_AMBER=39,     // Trading Floor Amber
   THEME_NORDIC_FROST=40,    // Nordic Frost
   THEME_VAMPIRE_NIGHT=41,   // Vampire Night
   THEME_APEX_OBSIDIAN_JADE=42, // Obsidian Jade
   THEME_APEX_MIDNIGHT_IRIS=43, // Midnight Iris
   THEME_APEX_GRAPHITE_SAFFRON=44, // Graphite Saffron
   THEME_APEX_INK_AND_PORCELAIN=45, // Ink and Porcelain
   THEME_APEX_BLACK_OPAL=46, // Black Opal
   THEME_APEX_COCOA_ROSE=47, // Cocoa Rose
   THEME_APEX_DEEP_LAGOON=48, // Deep Lagoon
   THEME_APEX_COPPER_NIGHT=49, // Copper Night
   THEME_APEX_SILVER_BIRCH=50, // Silver Birch
   THEME_APEX_ORCHID_INK=51, // Orchid Ink
   THEME_APEX_DROID_ELECTRIC_CYAN=52, // Droid Electric Cyan
   THEME_APEX_DROID_MATRIX_PULSE=53, // Droid Matrix Pulse
   THEME_APEX_DROID_CYBER_GOLD=54, // Droid Cyber Gold
   THEME_APEX_DROID_NEON_VIOLET=55, // Droid Neon Violet
   THEME_APEX_DROID_EMERALD_GRID=56, // Droid Emerald Grid
   THEME_APEX_DROID_PLASMA_RED=57, // Droid Plasma Red
   THEME_APEX_DROID_DEEP_OCEAN=58, // Droid Deep Ocean
   THEME_APEX_DROID_TITANIUM_ICE=59, // Droid Titanium Ice
   THEME_APEX_DROID_SOLAR_FLARE=60, // Droid Solar Flare
   THEME_APEX_DROID_MIDNIGHT_COBALT=61, // Droid Midnight Cobalt
   THEME_APEX_DROID_HOLOGRAM_MINT=62, // Droid Hologram Mint
   THEME_APEX_DROID_CRIMSON_FORGE=63, // Droid Crimson Forge
   THEME_APEX_DROID_SAKURA_CYBER=64, // Droid Sakura Cyber
   THEME_APEX_DROID_OBSIDIAN_LIME=65, // Droid Obsidian Lime
   THEME_APEX_DROID_ROYAL_AMETHYST=66, // Droid Royal Amethyst
   THEME_APEX_DROID_DAYLIGHT_FROST=67, // Droid Daylight Frost
   THEME_LRX_AURORA_ION=68, // CVT LT DRIOD BOT NO ERRORS Aurora Ion
   THEME_LRX_PLASMA_VIOLET=69, // CVT LT DRIOD BOT NO ERRORS Plasma Violet
   THEME_LRX_QUANTUM_LIME=70, // CVT LT DRIOD BOT NO ERRORS Quantum Lime
   THEME_LRX_OBSIDIAN_COPPER=71, // CVT LT DRIOD BOT NO ERRORS Obsidian Copper
   THEME_LRX_ARCTIC_PULSE=72, // CVT LT DRIOD BOT NO ERRORS Arctic Pulse
   THEME_LRX_ROSE_CIRCUIT=73, // CVT LT DRIOD BOT NO ERRORS Rose Circuit
   THEME_LRX_SOLAR_GRAPHITE=74, // CVT LT DRIOD BOT NO ERRORS Solar Graphite
   THEME_LRX_DEEP_SIGNAL=75 // CVT LT DRIOD BOT NO ERRORS Deep Signal
  };
#define CT_THEME_COUNT 76

//================================ INPUTS ================================
sinput string     InpS0 = "CVT LT DRIOD BOT NO ERRORS | LICENSED BY FLOWNEXUSFORGE"; // Product
input CTStrategy  InpStrategy = STRAT_COMBINED;      // Strategy
input CTMode      InpMode = MODE_SIGNALS;                // Trading mode
input CTDirection InpDirection = DIR_BOTH;            // Allowed direction
input int         InpMagic = 6120571;                // Magic number
input string      InpPresetLabel = "CVT LT DRIOD BOT NO ERRORS";        // Preset label (information only)
sinput string     InpS1 = "--- UT Bot engines ---";   // UT Bot engines
input double      InpUTKey = 2.0;                     // UT Bot key value (sensitivity)
input int         InpUTATR = 10;                      // UT Bot ATR period
input bool        InpUTHeikin = false;                // UT Bot uses Heikin Ashi close
input int         InpUTMAPeriod = 8;                  // UT Bot MA period (MA vs ATR trail strategy)
input double      InpUTBuyKey = 2.0;                  // Dual engine: buy ceiling key
input int         InpUTBuyATR = 10;                   // Dual engine: buy ceiling ATR period
input double      InpUTSellKey = 1.5;                 // Dual engine: sell floor key
input int         InpUTSellATR = 5;                   // Dual engine: sell floor ATR period
sinput string     InpS2 = "--- Trend and momentum indicators ---"; // Trend and momentum
input int         InpEMATrend = 200;                  // Trend EMA period (200 EMA filter)
input int         InpEMAFast = 21;                    // Fast EMA period
input int         InpEMASlow = 50;                    // Slow EMA period
input int         InpADXPeriod = 14;                  // ADX period
input double      InpADXMin = 25.0;                   // ADX minimum trend strength
input int         InpRSIPeriod = 14;                  // RSI period
input int         InpBBPeriod = 20;                   // Bollinger period
input double      InpBBDev = 2.0;                     // Bollinger deviations
input double      InpKCMult = 1.5;                    // Keltner ATR multiplier (squeeze)
input int         InpChopPeriod = 14;                 // Choppiness index period
input int         InpR2Period = 50;                   // R-squared regression period
input int         InpPivotBars = 3;                   // Pivot / swing bars each side
sinput string     InpS3 = "--- Kalman Supertrend and VWMA zones ---"; // Kalman and VWMA
input double      InpKalmanGain = 0.35;               // Kalman measurement gain
input double      InpKalmanNoise = 0.8;               // Kalman process noise
input int         InpKSTATR = 10;                     // Kalman Supertrend ATR period
input double      InpKSTMult = 2.5;                   // Kalman Supertrend ATR multiplier
input int         InpVWMAPeriod = 20;                 // VWMA zone centre period
input int         InpZoneLookback = 20;               // Zone high/low lookback
input double      InpZoneMult = 1.5;                  // Zone band multiplier
input bool        InpRevNeedTrend = false;            // Zone reversal requires Kalman trend agreement
sinput string     InpS4 = "--- Synapse ratchet band ---"; // Synapse
input int         InpSynATR = 8;                      // Synapse ATR period
input double      InpSynMult = 1.618;                 // Synapse ATR multiplier
input int         InpSynEMA = 8;                      // Synapse trail EMA period
input double      InpSynMinBreakATR = 0.2;            // Synapse minimum breakout distance (ATR)
sinput string     InpS5 = "--- Multi-timeframe ---";  // Multi-timeframe
input ENUM_TIMEFRAMES InpHTF = PERIOD_H1;             // Higher timeframe for 200 EMA bias
input ENUM_TIMEFRAMES InpMTF2 = PERIOD_M30;           // MTF consensus timeframe 2
input ENUM_TIMEFRAMES InpMTF3 = PERIOD_H1;            // MTF consensus timeframe 3
input ENUM_TIMEFRAMES InpMTF4 = PERIOD_H4;            // MTF consensus timeframe 4
input bool        InpMTFExit = true;                  // MTF consensus: exit when 2+ timeframes disagree
sinput string     InpS6 = "--- Smart filters ---";    // Smart filters
input bool        InpUseEMAFilter = false;            // Global 200 EMA trend filter
input bool        InpUseADXFilter = false;            // Global ADX strength filter
input bool        InpUseHTFFilter = false;            // Global higher-timeframe bias filter
input bool        InpUseRegimeFilter = true;          // Skip choppy / spiking regimes for trend strategies
input bool        InpUseSpikeGuard = true;            // ATR spike guard
input double      InpSpikeRatio = 1.3;                // ATR spike ratio vs 50-bar average
input int         InpMaxStreak = 6;                   // Anti-FOMO: max same-colour candle streak (0 = off)
input int         InpMinConfluence = 0;               // Minimum confluence score 0-100 (0 = off)
input double      InpMaxSpreadATR = 0.25;             // Spread guard: max spread as ATR fraction (0 = off)
input int         InpMaxSpreadPoints = 0;             // Spread guard: max spread in points (0 = off)
input bool        InpUseSession = false;              // Session guard enabled
input int         InpSessionStart = 7;                // Session start hour (server)
input int         InpSessionEnd = 20;                 // Session end hour (server)
input int         InpFridayCutoff = 20;               // Friday: no new trades from this hour (24 = off)
input string      InpNewsTimes = "";                  // News pause times, server time (e.g. 13:30;2026.12.05 15:00)
input int         InpNewsBefore = 30;                 // News pause minutes before
input int         InpNewsAfter = 30;                  // News pause minutes after
sinput string     InpS7 = "--- Risk and position sizing ---"; // Risk
input CTLotMode   InpLotMode = LOT_ADAPTIVE;          // Lot sizing mode
input double      InpFixedLot = 0.01;                 // Fixed lot / manual button lot
input double      InpRiskPercent = 0.5;               // Risk per trade (% equity)
input double      InpMinLot = 0.01;                   // Lot floor (user cap)
input double      InpMaxLot = 1.0;                    // Lot ceiling (user cap)
input double      InpSL_ATR = 1.5;                    // Initial stop loss (ATR multiples)
input double      InpTP_RR = 2.0;                     // Take profit (reward:risk, 0 = none)
input double      InpTP1_RR = 0.0;                    // Partial take profit at R (0 = off)
input double      InpTP1_Percent = 50.0;              // Partial take profit volume (%)
input int         InpMaxPositions = 1;                // Maximum open positions
input bool        InpCloseOnOpposite = true;          // Close on opposite signal
input int         InpSlippage = 10;                   // Maximum slippage (points)
sinput string     InpS8 = "--- Positive trailing stop ---"; // Positive trailing stop
input CTTrail     InpTrailMode = TRAIL_CVT_LT_DRIOD;  // Trailing stop mode
input double      InpTrailStartR = 0.5;               // Start locking after profit of R
input double      InpLockBufferATR = 0.10;            // Minimum locked profit (ATR fraction)
input double      InpStepR = 0.5;                     // Step-lock ladder step (R)
input double      InpTrailATRMult = 2.0;              // ATR multiplier for ATR-based locks
input int         InpChandelierBars = 22;             // Chandelier lookback bars
input double      InpChandelierMult = 3.0;            // Chandelier ATR multiplier
input double      InpPercentTrail = 0.5;              // Percent trail distance (% of price)
sinput string     InpS9 = "--- Equity protection ---"; // Equity protection
input double      InpDailyLossPct = 3.0;              // Daily loss limit (% of day-start equity, 0 = off)
input double      InpDailyTargetPct = 0.0;            // Daily profit target (% , 0 = off)
input double      InpMaxDDPct = 10.0;                 // Max drawdown kill switch (% from equity peak, 0 = off)
input int         InpMaxConsecLosses = 0;             // Pause for the day after N consecutive losses (0 = off)
sinput string     InpS10 = "--- Dashboard and chart ---"; // Dashboard
input CTTheme     InpTheme = THEME_LRX_AURORA_ION;           // Colour theme
input CTSize      InpPanelSize = SIZE_M;              // Dashboard size
input bool        InpShowDashboard = true;            // Show main dashboard
input bool        InpShowIndicatorPanel = true;       // Show multi-indicator panel
input bool        InpShowControls = true;             // Show control panel
input bool        InpShowChartRobot = true;           // Show robot logo on chart
input bool        InpCompactStart = false;            // Start with dashboards collapsed to their headers
input bool        InpDrawIndicators = true;           // Draw indicator lines and signal arrows on chart
input int         InpDrawBars = 120;                  // Bars of chart drawings
input bool        InpThemeChart = true;               // Apply theme colours to the chart
input bool        InpAlerts = true;                   // Pop-up alerts on signals
input bool        InpPush = false;                    // Push notifications on signals
input int         InpLookback = 600;                  // Calculation lookback bars

//================================ NAMES ================================
string StrategyName(int s)
  {
   switch(s)
     {
      case STRAT_UT_EMA200:       return "UT Bot ATR Trailing + 200 EMA Filter";
      case STRAT_UT_HTF_EMA_ADX:  return "UT Bot + Higher-Timeframe 200 EMA + ADX Strength";
      case STRAT_UT_MA_VS_TRAIL:  return "UT Bot Moving Average vs ATR Trailing Stop";
      case STRAT_UT_CLASSIC:      return "UT Bot Classic ATR Trailing Stop Flip";
      case STRAT_UT_DUAL_ENGINE:  return "UT Bot Dual-Engine Asymmetric Ceiling and Floor";
      case STRAT_UT_SNIPER:       return "UT Sniper Reversal: Pivot + Bollinger Zone + ATR Spike Guard";
      case STRAT_SYNAPSE:         return "Synapse Adaptive Ratchet Band Scalper";
      case STRAT_MTF_TRAIL:       return "Multi-Timeframe ATR Trailing Stop Consensus";
      case STRAT_BB_TREND_SCALP:  return "Bollinger Band Trend Scalper with ATR Sideways Filter";
      case STRAT_KALMAN_ST:       return "Kalman Supertrend Flip";
      case STRAT_KALMAN_VWMA_REV: return "Kalman Supertrend + VWMA Zone Reversal";
      case STRAT_CONFLUENCE:      return "Smart Multi-Indicator Confluence Score";
      case STRAT_REGIME:          return "Regime Adaptive Switch: Trend Engine or Range Engine";
      case STRAT_EMA_PULLBACK:    return "EMA 21/50 Trend Pullback with RSI Reset";
      case STRAT_NEURAL_TREND: return "Neural Trend Continuation";
      case STRAT_NEURAL_TURN: return "Neural Reversal Timing";
      case STRAT_NEURAL_AGREE: return "Neural Horizon Agreement";
      case STRAT_HA_SAR: return "Opening Session Heikin Ashi Parabolic SAR";
      case STRAT_FRACTAL_EMA: return "Confirmed Fractal with Triple EMA Alignment";
      case STRAT_BIONICK_ELITE: return "UT Momentum with EMA ADX and RSI Confirmation";
      case STRAT_BIONICK_BB: return "Bollinger Reentry with RSI Confirmation";
      case STRAT_VECTOR:          return "ATR Trend Pivot and Overnight Confluence";
      case STRAT_GOLD_STRICT:     return "Gold M15 / H1 EMA / ADX long";
      case STRAT_COMBINED: return "CVT LT DRIOD BOT NO ERRORS Fusion";
      case STRAT_CONTROL: return "UT momentum control";
      case STRAT_ZONE: return "Williams R zone";
      case STRAT_PRIDE: return "Adaptive UT signal selection";
      case STRAT_PANDICH:         return "Pandich asymmetric ATR";
      case STRAT_EXPRESS:         return "New York overnight adaptive trail";
      case STRAT_SQUEEZE:         return "Bollinger-Keltner Squeeze Breakout";
     }
   return "Unknown strategy";
  }

string StrategyShort(int s)
  {
   switch(s)
     {
      case STRAT_UT_EMA200:       return "UT Bot + 200 EMA";
      case STRAT_UT_HTF_EMA_ADX:  return "UT Bot + HTF EMA + ADX";
      case STRAT_UT_MA_VS_TRAIL:  return "UT Bot MA vs Trail";
      case STRAT_UT_CLASSIC:      return "UT Bot Classic Flip";
      case STRAT_UT_DUAL_ENGINE:  return "UT Bot Dual Engine";
      case STRAT_UT_SNIPER:       return "UT Sniper Reversal";
      case STRAT_SYNAPSE:         return "Synapse Ratchet Scalper";
      case STRAT_MTF_TRAIL:       return "MTF Trailing Consensus";
      case STRAT_BB_TREND_SCALP:  return "BB Trend Scalper";
      case STRAT_KALMAN_ST:       return "Kalman Supertrend Flip";
      case STRAT_KALMAN_VWMA_REV: return "Kalman + VWMA Reversal";
      case STRAT_CONFLUENCE:      return "Confluence Score";
      case STRAT_REGIME:          return "Regime Adaptive Switch";
      case STRAT_EMA_PULLBACK:    return "EMA Trend Pullback";
      case STRAT_NEURAL_TREND: return "Neural Trend Continuation";
      case STRAT_NEURAL_TURN: return "Neural Reversal Timing";
      case STRAT_NEURAL_AGREE: return "Neural Horizon Agreement";
      case STRAT_HA_SAR: return "Opening Session Heikin Ashi Parabolic SAR";
      case STRAT_FRACTAL_EMA: return "Confirmed Fractal with Triple EMA Alignment";
      case STRAT_BIONICK_ELITE: return "UT Momentum with EMA ADX and RSI Confirmation";
      case STRAT_BIONICK_BB: return "Bollinger Reentry with RSI Confirmation";
      case STRAT_VECTOR:          return "ATR Trend Pivot and Overnight Confluence";
      case STRAT_GOLD_STRICT:     return "Gold M15 / H1 EMA / ADX long";
      case STRAT_COMBINED: return "CVT LT DRIOD BOT NO ERRORS Fusion";
      case STRAT_CONTROL: return "UT momentum control";
      case STRAT_ZONE: return "Williams R zone";
      case STRAT_PRIDE: return "Adaptive UT signal selection";
      case STRAT_PANDICH:         return "Pandich asymmetric ATR";
      case STRAT_EXPRESS:         return "New York overnight adaptive trail";
      case STRAT_SQUEEZE:         return "Squeeze Breakout";
     }
   return "Unknown";
  }

string TrailName(int t)
  {
   switch(t)
     {
      case TRAIL_PEAK: return "Ultra peak protection";
      case TRAIL_CVT_LT_DRIOD: return "CVT LT DRIOD BOT NO ERRORS Smart Trail";
      case TRAIL_PRIDE: return "Ultra smart positive trailing SL";
      case TRAIL_NEURAL: return "Neural Excursion Profit Lock";
      case TRAIL_STRUCTURE_FLOOR: return "Three-Bar Structure Profit Lock";
      case TRAIL_VECTOR_ULTRA:   return "Ultra positive adaptive lock";
      case TRAIL_OFF:            return "Off (initial stop only)";
      case TRAIL_UT_ATR:         return "UT Bot ATR Trailing Stop Lock";
      case TRAIL_MTF_ATR:        return "Multi-Timeframe ATR Trailing Stop Lock";
      case TRAIL_KALMAN_ST:      return "Kalman Supertrend Line Lock";
      case TRAIL_STEP_LOCK:      return "Step-Lock Profit Ladder";
      case TRAIL_BREAKEVEN_PLUS: return "Breakeven Plus Buffer";
      case TRAIL_CHANDELIER:     return "Chandelier Exit Lock";
      case TRAIL_SWING:          return "Swing-Structure Lock";
      case TRAIL_VOL_ADAPTIVE:   return "Volatility-Adaptive ATR Lock";
      case TRAIL_PERCENT:        return "Percent-of-Price Trailing Lock";
      case TRAIL_SYNAPSE:        return "Synapse EMA Ratchet Band Lock";
      case TRAIL_SMART_HYBRID:   return "Smart Hybrid (tightest valid lock)";
     }
   return "Unknown trail";
  }

string ModeName(int m)
  {
   if(m==MODE_AUTO) return "AUTO";
   if(m==MODE_SEMI) return "SEMI-AUTO";
   return "SIGNALS ONLY";
  }

string LotModeName(int m)
  {
   if(m==LOT_FIXED) return "Fixed lot";
   if(m==LOT_RISK)  return "Risk percent";
   return "Adaptive risk";
  }

//================================ THEMES ================================
struct CTColors
  {
   color bg; color bg2; color hdr; color border; color text; color muted;
   color acc; color acc2; color up; color dn; color warn; color btn; color btnTxt;
   color chartBg; color chartFg; color chartGrid; bool light;
  };
CTColors TC;

color HexC(int hex)
  {
   int r=(hex>>16)&255, g=(hex>>8)&255, b=hex&255;
   return (color)(r | (g<<8) | (b<<16));
  }
int CR(color c) { return ((int)c)&255; }
int CG(color c) { return (((int)c)>>8)&255; }
int CB(color c) { return (((int)c)>>16)&255; }
color MixC(color a,color b,double t)
  {
   if(t<0) t=0;
   if(t>1) t=1;
   int r=(int)MathRound(CR(a)+(CR(b)-CR(a))*t);
   int g=(int)MathRound(CG(a)+(CG(b)-CG(a))*t);
   int bl=(int)MathRound(CB(a)+(CB(b)-CB(a))*t);
   return (color)(r | (g<<8) | (bl<<16));
  }

string ThemeName(int i)
  {
   switch(i)
     {
      case 42: return "Obsidian Jade";
      case 43: return "Midnight Iris";
      case 44: return "Graphite Saffron";
      case 45: return "Ink and Porcelain";
      case 46: return "Black Opal";
      case 47: return "Cocoa Rose";
      case 48: return "Deep Lagoon";
      case 49: return "Copper Night";
      case 50: return "Silver Birch";
      case 51: return "Orchid Ink";
      case 52: return "Droid Electric Cyan";
      case 53: return "Droid Matrix Pulse";
      case 54: return "Droid Cyber Gold";
      case 55: return "Droid Neon Violet";
      case 56: return "Droid Emerald Grid";
      case 57: return "Droid Plasma Red";
      case 58: return "Droid Deep Ocean";
      case 59: return "Droid Titanium Ice";
      case 60: return "Droid Solar Flare";
      case 61: return "Droid Midnight Cobalt";
      case 62: return "Droid Hologram Mint";
      case 63: return "Droid Crimson Forge";
      case 64: return "Droid Sakura Cyber";
      case 65: return "Droid Obsidian Lime";
      case 66: return "Droid Royal Amethyst";
      case 67: return "Droid Daylight Frost";
      case 68: return "CVT LT DRIOD BOT NO ERRORS Aurora Ion";
      case 69: return "CVT LT DRIOD BOT NO ERRORS Plasma Violet";
      case 70: return "CVT LT DRIOD BOT NO ERRORS Quantum Lime";
      case 71: return "CVT LT DRIOD BOT NO ERRORS Obsidian Copper";
      case 72: return "CVT LT DRIOD BOT NO ERRORS Arctic Pulse";
      case 73: return "CVT LT DRIOD BOT NO ERRORS Rose Circuit";
      case 74: return "CVT LT DRIOD BOT NO ERRORS Solar Graphite";
      case 75: return "CVT LT DRIOD BOT NO ERRORS Deep Signal";
      case 0: return "Android Green";      case 1: return "Midnight Neon";      case 2: return "Ocean Blue";
      case 3: return "Carbon Gold";        case 4: return "Light Mint";         case 5: return "Cyber Violet";
      case 6: return "Droid Lime";         case 7: return "Robot Steel";        case 8: return "Arctic Ice";
      case 9: return "Solar Flare";        case 10: return "Crimson Pulse";     case 11: return "Royal Sapphire";
      case 12: return "Emerald Matrix";    case 13: return "Graphite Orange";   case 14: return "Sakura Pink";
      case 15: return "Lavender Dream";    case 16: return "Deep Ocean Teal";   case 17: return "Desert Sand";
      case 18: return "Volcanic Ember";    case 19: return "Aurora Borealis";   case 20: return "Polar Night";
      case 21: return "Golden Hour";       case 22: return "Neon Tokyo";        case 23: return "Forest Moss";
      case 24: return "Cobalt Circuit";    case 25: return "Ruby Night";        case 26: return "Amber Terminal";
      case 27: return "Pastel Candy";      case 28: return "Monochrome Pro";    case 29: return "Paper White";
      case 30: return "Blueprint";         case 31: return "Bubblegum Bot";     case 32: return "Mint Chocolate";
      case 33: return "Copper Patina";     case 34: return "Galaxy Purple";     case 35: return "Sunset Coral";
      case 36: return "Matrix Rain";       case 37: return "Titanium Silver";   case 38: return "Jade Temple";
      case 39: return "Trading Floor Amber"; case 40: return "Nordic Frost";    case 41: return "Vampire Night";
     }
   return "Android Green";
  }

void ThemeBase(int bg,int hdr,int acc,int acc2,int txt,int up,int dn,bool light)
  {
   TC.bg=HexC(bg); TC.hdr=HexC(hdr); TC.acc=HexC(acc); TC.acc2=HexC(acc2);
   TC.text=HexC(txt); TC.up=HexC(up); TC.dn=HexC(dn); TC.light=light;
   TC.bg2=MixC(TC.bg,TC.text,light ? 0.05 : 0.06);
   TC.border=MixC(TC.bg,TC.acc,0.55);
   TC.muted=MixC(TC.text,TC.bg,0.42);
   TC.warn=light ? HexC(0xB7791F) : HexC(0xFFC043);
   TC.btn=MixC(TC.bg,TC.acc,light ? 0.18 : 0.24);
   TC.btnTxt=TC.text;
   TC.chartBg=light ? MixC(TC.bg,HexC(0xFFFFFF),0.5) : MixC(TC.bg,HexC(0x000000),0.35);
   TC.chartFg=MixC(TC.text,TC.chartBg,0.25);
   TC.chartGrid=MixC(TC.chartBg,TC.text,0.10);
  }

void ApplyThemeColors(int i)
  {
   switch(i)
     {
      case 0:  ThemeBase(0x0F1A14,0x13261B,0x3DDC84,0xA4F5C6,0xE8FFF1,0x3DDC84,0xFF5C6C,false); break;
      case 1:  ThemeBase(0x0B0D1A,0x14183A,0x00F0FF,0xFF3CF0,0xE6F7FF,0x00FFA3,0xFF3B6B,false); break;
      case 2:  ThemeBase(0x0A1726,0x0F2742,0x2E9BFF,0x7FD4FF,0xE3F2FF,0x30D5A0,0xFF6B6B,false); break;
      case 3:  ThemeBase(0x121212,0x1E1B14,0xD4AF37,0xFFE08A,0xF5EEDC,0x7BD88F,0xE5534B,false); break;
      case 4:  ThemeBase(0xEFFAF4,0xD4F2E2,0x14A36A,0x0B6E47,0x123B2A,0x10935C,0xD6334A,true);  break;
      case 5:  ThemeBase(0x120B1F,0x221338,0x9D4DFF,0x00E5FF,0xF0E6FF,0x39FF9A,0xFF4D8D,false); break;
      case 6:  ThemeBase(0x111A08,0x1D2B0C,0xA4C639,0xE2F59A,0xF3FFE0,0xA4C639,0xFF6A4D,false); break;
      case 7:  ThemeBase(0x1A1F24,0x262D34,0x8FA3B8,0x3DDC84,0xE6EDF3,0x4CD08A,0xF2665A,false); break;
      case 8:  ThemeBase(0x0E1A22,0x15303D,0x7FE7FF,0xFFFFFF,0xE9FBFF,0x5CF2C2,0xFF7A8A,false); break;
      case 9:  ThemeBase(0x1A0E05,0x2E1806,0xFF8C1A,0xFFD23F,0xFFF1E0,0x8BE05A,0xFF4040,false); break;
      case 10: ThemeBase(0x170709,0x2A0C11,0xFF2E4D,0xFF9AA8,0xFFE8EC,0x41D98B,0xFF2E4D,false); break;
      case 11: ThemeBase(0x0A0F2A,0x121B4A,0x3D6BFF,0xE8C547,0xE8EEFF,0x3BD9A0,0xFF5D6E,false); break;
      case 12: ThemeBase(0x04140D,0x082418,0x00C277,0x7DFFC4,0xD9FFEE,0x00E68A,0xFF5555,false); break;
      case 13: ThemeBase(0x1C1C1E,0x2A2A2D,0xFF7A1A,0xFFB36B,0xF2F2F2,0x52D273,0xFF453A,false); break;
      case 14: ThemeBase(0xFFF4F7,0xFCE1EA,0xE85A8C,0x9B3B66,0x4A1F33,0x2EA36B,0xD7263D,true);  break;
      case 15: ThemeBase(0xF5F1FF,0xE6DDFF,0x7C5CE0,0x4A2FB0,0x2B1F4D,0x1F9E6E,0xD63A5A,true);  break;
      case 16: ThemeBase(0x051A1C,0x0A2E31,0x14B8A6,0x99F6E4,0xE0FFFB,0x2DD4BF,0xFB7185,false); break;
      case 17: ThemeBase(0xF7EFE1,0xEADBC0,0xB07A2C,0x6B4A1B,0x3B2A12,0x3E8E41,0xC0392B,true);  break;
      case 18: ThemeBase(0x140806,0x26100A,0xFF5722,0xFFAB40,0xFFEDE6,0x7CD992,0xFF3D00,false); break;
      case 19: ThemeBase(0x07121F,0x0E2236,0x4DFFB4,0xB26BFF,0xE6FFF6,0x4DFFB4,0xFF6B9E,false); break;
      case 20: ThemeBase(0x0B1020,0x151C33,0x88A0FF,0xD6E0FF,0xE6EBFF,0x6EE7B7,0xF87171,false); break;
      case 21: ThemeBase(0x1F1408,0x33210D,0xFFB238,0xFF7B54,0xFFF3E0,0x9CD66B,0xFF5A5A,false); break;
      case 22: ThemeBase(0x0D0221,0x1B0640,0xFF2A6D,0x05D9E8,0xF4F0FF,0x05D9E8,0xFF2A6D,false); break;
      case 23: ThemeBase(0x0F1A10,0x1A2B1B,0x6FA86B,0xC7E3A1,0xEAF5E4,0x7FC97A,0xE0705C,false); break;
      case 24: ThemeBase(0x061226,0x0B2148,0x2F6BFF,0x00D1FF,0xE5EEFF,0x00D68F,0xFF4F5E,false); break;
      case 25: ThemeBase(0x14060C,0x260B17,0xE0115F,0xFF7AA8,0xFFE6EF,0x3FD68F,0xE0115F,false); break;
      case 26: ThemeBase(0x0D0A00,0x1A1400,0xFFB000,0xFFD666,0xFFE9B3,0xFFC94D,0xFF5E3A,false); break;
      case 27: ThemeBase(0xFDF6FF,0xF1E4FF,0x8FB8FF,0xFF9ECF,0x3D3550,0x3FB984,0xE5577A,true);  break;
      case 28: ThemeBase(0x101010,0x1C1C1C,0xFFFFFF,0xA0A0A0,0xEDEDED,0x9AE6B4,0xFEB2B2,false); break;
      case 29: ThemeBase(0xFFFFFF,0xF0F0F0,0x1F6FEB,0x0B3D91,0x1A1A1A,0x1A7F37,0xCF222E,true);  break;
      case 30: ThemeBase(0x0B2A4A,0x0F3966,0xCFE8FF,0x6FB7FF,0xEAF4FF,0x7CF5C0,0xFF9C9C,false); break;
      case 31: ThemeBase(0x2A0F24,0x3D1535,0xFF77C8,0x7DF9FF,0xFFE8F6,0x7DF9C4,0xFF5577,false); break;
      case 32: ThemeBase(0x2B1D16,0x3A281E,0x98FFCC,0xD9A066,0xF5EDE6,0x98FFCC,0xFF7B6B,false); break;
      case 33: ThemeBase(0x10201E,0x1A302C,0x5FBFA8,0xC87533,0xE8F3EF,0x5FBFA8,0xE0603D,false); break;
      case 34: ThemeBase(0x0C0618,0x1A0F33,0xB57BFF,0xFFD36E,0xEFE6FF,0x6CF0C2,0xFF6B8B,false); break;
      case 35: ThemeBase(0x1E0F14,0x33171F,0xFF7F66,0xFFC46B,0xFFEDE8,0x7EDC9B,0xFF4F5A,false); break;
      case 36: ThemeBase(0x000800,0x001400,0x00FF41,0x008F11,0xC8FFC8,0x00FF41,0xFF3030,false); break;
      case 37: ThemeBase(0xE9ECEF,0xD3D8DD,0x495057,0x2B9A5E,0x212529,0x2B8A3E,0xC92A2A,true);  break;
      case 38: ThemeBase(0x06170F,0x0C2A1C,0x00A86B,0xE3C16F,0xE8FFF4,0x2BD98B,0xFF6464,false); break;
      case 39: ThemeBase(0x000000,0x1A1200,0xFF9F00,0xFFFFFF,0xFFC766,0x00D26A,0xFF3B30,false); break;
      case 40: ThemeBase(0x2E3440,0x3B4252,0x88C0D0,0x81A1C1,0xECEFF4,0xA3BE8C,0xBF616A,false); break;
      case 42: ThemeBase(0x081815,0x102822,0x69E3B4,0xE7C378,0xE9F5EF,0x66DFAD,0xFF868A,false); break;
      case 43: ThemeBase(0x110E22,0x211B36,0xCBA8FF,0x75E0F2,0xF6F1FF,0x7CE6C1,0xFF8DA3,false); break;
      case 44: ThemeBase(0x12130F,0x23251F,0xECC86C,0x81D3BE,0xF5F2E5,0x81D3AE,0xF18F88,false); break;
      case 45: ThemeBase(0xECF1F4,0xDBE4E8,0x145B77,0x874333,0x112B34,0x047254,0xBA424D,true); break;
      case 46: ThemeBase(0x0A0B10,0x171824,0x9BBCF8,0xE7A4D8,0xEFF2FB,0x70E0BE,0xFA8E9F,false); break;
      case 47: ThemeBase(0x1C1014,0x32212A,0xECA8B2,0xEECBA0,0xF9F0EF,0x92D9BA,0xFD8D93,false); break;
      case 48: ThemeBase(0x071921,0x102A36,0x6AD1EF,0xA6E2BB,0xEAF7FB,0x74DAB6,0xFF9793,false); break;
      case 49: ThemeBase(0x17130F,0x2B211A,0xE8AD77,0xA5CBC6,0xF9F2E9,0x92CEAD,0xF18D85,false); break;
      case 50: ThemeBase(0xEFF2ED,0xDFE7DB,0x3E654F,0x7A5437,0x223527,0x216B4B,0xAF3E50,true); break;
      case 51: ThemeBase(0x1A1020,0x2D1B33,0xE3A6EA,0xF0CC88,0xF7EEF8,0x87DAB2,0xF99FA5,false); break;
      case 52: ThemeBase(0x040B16,0x091628,0x00F0FF,0x389CFF,0xE8FAFF,0x22F6B0,0xFF4E70,false); break;
      case 53: ThemeBase(0x030D09,0x081A12,0x2CFF90,0x00E0C4,0xE0FFEE,0x2CFF90,0xFF4C62,false); break;
      case 54: ThemeBase(0x0C0A06,0x18140C,0xFFD02C,0xF4A024,0xFCF6E2,0x4CE894,0xFA4E54,false); break;
      case 55: ThemeBase(0x0D061A,0x1A0C34,0xC862FF,0x2CE4FF,0xF6EAFF,0x46F6C4,0xFF427A,false); break;
      case 56: ThemeBase(0x04100C,0x092018,0x18F29E,0x34D0F6,0xE0FEF0,0x18F29E,0xFF5264,false); break;
      case 57: ThemeBase(0x130508,0x260A10,0xFF3A5C,0xFFA43A,0xFFE8EE,0x4AEC9C,0xFF3A5C,false); break;
      case 58: ThemeBase(0x03101C,0x072036,0x1AD6F6,0x4492FF,0xE2F6FF,0x38EEBC,0xFF5E70,false); break;
      case 59: ThemeBase(0x10161E,0x1C2634,0x92D8FF,0xBAE8FF,0xF0F8FF,0x52EEC4,0xF85E72,false); break;
      case 60: ThemeBase(0x140B04,0x281608,0xFFB018,0xFFDA56,0xFFF4DA,0x74EA76,0xFF4A40,false); break;
      case 61: ThemeBase(0x050B1E,0x0A163C,0x529CFF,0x2EE6F8,0xE6F0FF,0x42EEBA,0xFF5474,false); break;
      case 62: ThemeBase(0x041212,0x0A2424,0x24F8D4,0x4ECEFF,0xE0FEFC,0x24F8D4,0xFF586C,false); break;
      case 63: ThemeBase(0x10060A,0x200C14,0xFF3660,0xFFAE4C,0xFFEAF0,0x4EECA0,0xFF3660,false); break;
      case 64: ThemeBase(0x160814,0x2C1028,0xFF6CC4,0x68D8FF,0xFFEEF8,0x58F0C0,0xFF486C,false); break;
      case 65: ThemeBase(0x080C05,0x121A0A,0xC2FF2E,0x40E8CC,0xF4FFDE,0x84FF54,0xFF4A58,false); break;
      case 66: ThemeBase(0x0C0618,0x180C30,0xB874FF,0x4ACCFF,0xF2E8FF,0x52F0C0,0xFF4E7C,false); break;
      case 67: ThemeBase(0xF2F8FE,0xE0ECF8,0x008ACC,0x0EA28E,0x102032,0x009A70,0xDC3A4C,true); break;
      case 68: ThemeBase(0x050B18,0x0E1930,0x22D3EE,0xA78BFA,0xEAF6FF,0x2BE4A7,0xFF5D7D,false); break;
      case 69: ThemeBase(0x10051F,0x1D0A35,0xB56BFF,0x48E3FF,0xF4EAFF,0x53F0C4,0xFF5A81,false); break;
      case 70: ThemeBase(0x081208,0x13230C,0xB7F34A,0x35DBBA,0xF2FFE0,0x88F058,0xFF526B,false); break;
      case 71: ThemeBase(0x130C0A,0x27150F,0xE89C62,0xF4CC9A,0xFFF2E7,0x75DEAA,0xFF6B67,false); break;
      case 72: ThemeBase(0xF1F8FF,0xDCEBFA,0x2077C8,0x7143AD,0x152B42,0x13835C,0xD63E59,true); break;
      case 73: ThemeBase(0x1B0814,0x2E1024,0xFF6AB8,0x72E9FF,0xFFEAF5,0x56E8A5,0xFF5578,false); break;
      case 74: ThemeBase(0x13120B,0x24210F,0xFFC857,0x9EE37D,0xFFF8E8,0x85E09A,0xF55B4F,false); break;
      case 75: ThemeBase(0x061524,0x0B2940,0x36BFFA,0x4CF2D6,0xE8F8FF,0x4DE5AC,0xFF637C,false); break;
      default: ThemeBase(0x1E1F29,0x282A36,0xBD93F9,0xFF79C6,0xF8F8F2,0x50FA7B,0xFF5555,false); break;
     }
  }

//================================ GLOBAL STATE ================================
int      g_strategy, g_trail, g_theme, g_mode;
bool     g_paused=false, g_killLock=false, g_dayLock=false;
string   g_dayLockWhy="";
double   g_peakEquity=0, g_dayStartEquity=0;
int      g_dayKey=0;
double   g_manualLot=0.01;
datetime g_lastBar=0;
string   g_lastSignalText="Waiting for a closed bar";
string   g_blockReason="";
int      g_lastSignal=0;
datetime g_lastSignalTime=0;
bool     g_closeAllArmed=false;
uint     g_closeAllArmedAt=0;
bool     g_portfolioExit=false;
bool     g_ready=false;
bool     g_isTester=false, g_isVisual=false, g_drawEnabled=true;
string   g_regime="Unknown";
int      g_regimeCode=0;        // 1 trend up, -1 trend down, 0 range, 2 volatile
int      g_scoreLong=0, g_scoreShort=0;
int      g_closedTrades=0, g_closedWins=0, g_consecLosses=0;
double   g_closedNet=0;
string   g_lastAction="Ready";
long     g_chartBgSaved=-1, g_chartFgSaved=-1, g_chartGridSaved=-1, g_chartUpSaved=-1, g_chartDnSaved=-1, g_chartBullSaved=-1, g_chartBearSaved=-1, g_chartLineSaved=-1;
double   g_point=0.00001;
int      g_digits=5;

struct CTPos
  {
   long     ticket;
   int      dir;
   double   lots;
   double   open;
   double   sl;
   double   tp;
   double   profit;
   datetime opened;
  };
CTPos g_pos[];
int   g_npos=0;

//================================ UTILITIES ================================
string vectorStatePrefix="";
string GVName(string key) { return vectorStatePrefix+key; }
double GVGet(string key,double def)
  {
   string n=GVName(key);
   if(GlobalVariableCheck(n)) return GlobalVariableGet(n);
   return def;
  }
void GVPut(string key,double v) { GlobalVariableSet(GVName(key),v); }

double PxBid() { return SymbolInfoDouble(_Symbol,SYMBOL_BID); }
double PxAsk() { return SymbolInfoDouble(_Symbol,SYMBOL_ASK); }
double NormP(double p) { return NormalizeDouble(p,g_digits); }
double Equity() { return AccountInfoDouble(ACCOUNT_EQUITY); }
double Balance() { return AccountInfoDouble(ACCOUNT_BALANCE); }
double SpreadPts() { return (PxAsk()-PxBid())/g_point; }
double StopDist()
  {
   long lvl=SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
   long frz=SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL);
   long m=MathMax(lvl,frz);
   return (double)(m+2)*g_point;
  }

string AssetClass()
  {
   string s=_Symbol; StringToUpper(s);
   if(StringFind(s,"XAU")>=0 || StringFind(s,"XAG")>=0 || StringFind(s,"GOLD")>=0 || StringFind(s,"SILVER")>=0) return "Metal";
   if(StringFind(s,"BTC")>=0 || StringFind(s,"ETH")>=0 || StringFind(s,"XRP")>=0 || StringFind(s,"SOL")>=0 || StringFind(s,"LTC")>=0) return "Crypto";
   string cur[]={"USD","EUR","GBP","JPY","CHF","AUD","NZD","CAD","SEK","NOK","SGD","HKD","ZAR","MXN","TRY","PLN","CNH","DKK","HUF","CZK"};
   int hits=0;
   for(int i=0;i<ArraySize(cur);i++) if(StringFind(s,cur[i])>=0) hits++;
   if(hits>=2) return "Forex";
   if(StringFind(s,"OIL")>=0 || StringFind(s,"WTI")>=0 || StringFind(s,"BRENT")>=0 || StringFind(s,"NGAS")>=0) return "Energy";
   return "Index/CFD";
  }

double PipSize()
  {
   if(g_digits==3 || g_digits==5) return g_point*10.0;
   return g_point;
  }

string Money(double v) { return (v>=0 ? "+" : "")+DoubleToString(v,2); }

string Fit(string s,int n)
  {
   if(StringLen(s)<=n) return s;
   return StringSubstr(s,0,n-2)+"..";
  }

int DayKey(datetime t) { MqlDateTime d; TimeToStruct(t,d); return d.year*1000+d.day_of_year; }

void Note(string s)
  {
   g_lastAction=s;
   if(!g_isTester || g_isVisual) Print(CT_NAME,": ",s);
  }

//================================ TRADE LAYER (MT4 / MT5) ================================
double NormalizeLots(double lots)
  {
   double step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   double vmin=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   double vmax=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
   if(step<=0) step=0.01;
   double lo=MathMax(vmin,InpMinLot), hi=MathMin(vmax,InpMaxLot);
   if(hi<lo) hi=lo;
   if(lots<lo) lots=lo;
   if(lots>hi) lots=hi;
   lots=MathFloor(lots/step+1e-9)*step;
   if(lots<vmin) lots=vmin;
   return NormalizeDouble(lots,8);
  }

int LoadPositions()
  {
   g_npos=0;
   ArrayResize(g_pos,0);
#ifdef __MQL5__
   int total=PositionsTotal();
   for(int i=0;i<total;i++)
     {
      ulong tk=PositionGetTicket(i);
      if(tk==0) continue;
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic || (IsNetting() && !NettingExclusiveFor(InpMagic))) continue;
      ArrayResize(g_pos,g_npos+1);
      g_pos[g_npos].ticket=(long)tk;
      g_pos[g_npos].dir=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY) ? 1 : -1;
      g_pos[g_npos].lots=PositionGetDouble(POSITION_VOLUME);
      g_pos[g_npos].open=PositionGetDouble(POSITION_PRICE_OPEN);
      g_pos[g_npos].sl=PositionGetDouble(POSITION_SL);
      g_pos[g_npos].tp=PositionGetDouble(POSITION_TP);
      g_pos[g_npos].profit=PositionGetDouble(POSITION_PROFIT)+PositionGetDouble(POSITION_SWAP);
      g_pos[g_npos].opened=(datetime)PositionGetInteger(POSITION_TIME);
      g_npos++;
     }
#else
   int total=OrdersTotal();
   for(int i=0;i<total;i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderSymbol()!=_Symbol || OrderMagicNumber()!=InpMagic) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL) continue;
      ArrayResize(g_pos,g_npos+1);
      g_pos[g_npos].ticket=OrderTicket();
      g_pos[g_npos].dir=(OrderType()==OP_BUY) ? 1 : -1;
      g_pos[g_npos].lots=OrderLots();
      g_pos[g_npos].open=OrderOpenPrice();
      g_pos[g_npos].sl=OrderStopLoss();
      g_pos[g_npos].tp=OrderTakeProfit();
      g_pos[g_npos].profit=OrderProfit()+OrderSwap()+OrderCommission();
      g_pos[g_npos].opened=OrderOpenTime();
      g_npos++;
     }
#endif
   return g_npos;
  }

bool PositionStillOpen(long ticket)
  {
#ifdef __MQL5__
   return PositionSelectByTicket((ulong)ticket);
#else
   if(!OrderSelect((int)ticket,SELECT_BY_TICKET)) return false;
   return (OrderCloseTime()==0);
#endif
  }

bool TradeModify(long ticket,double sl,double tp)
  {
   if(g_mode==MODE_SIGNALS) return false;
   double tick=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   MqlTick quote; if(tick<=0 || !SymbolInfoTick(_Symbol,quote) || quote.bid<=0 || quote.ask<quote.bid) return false;
#ifdef __MQL5__
   if(!PositionSelectByTicket((ulong)ticket) || PositionGetInteger(POSITION_MAGIC)!=InpMagic || PositionGetString(POSITION_SYMBOL)!=_Symbol) return false;
   int side=PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ? 1 : -1;
   if(IsNetting() && !NettingExclusiveFor(InpMagic)) return false;
   if(!PositionSelectByTicket((ulong)ticket) || PositionGetInteger(POSITION_MAGIC)!=InpMagic ||
      side!=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ? 1 : -1)) return false;
   double old=PositionGetDouble(POSITION_SL),entry=PositionGetDouble(POSITION_PRICE_OPEN);
   tp=PositionGetDouble(POSITION_TP);
#else
   if(!OrderSelect((int)ticket,SELECT_BY_TICKET) || OrderCloseTime()!=0 || OrderSymbol()!=_Symbol || OrderMagicNumber()!=InpMagic) return false;
   int side=OrderType()==OP_BUY ? 1 : -1;
   double old=OrderStopLoss(),entry=OrderOpenPrice(); tp=OrderTakeProfit();
#endif
   sl=NormP(tick*(side>0 ? MathFloor(sl/tick+1e-9) : MathCeil(sl/tick-1e-9)));
   double market=side>0 ? quote.bid : quote.ask;
   if(g_trail>=TRAIL_VECTOR_ULTRA && side*(sl-entry)+tick*1e-7<quote.ask-quote.bid+(VectorCostTicks+1)*tick) return false;
   if(g_trail>=TRAIL_VECTOR_ULTRA && old>0 && side*(sl-old)<(VectorStepTicks-1e-7)*tick) return false;
   if(sl<=0 || side*(sl-entry)<=tick*1e-7 || (old>0 && side*(sl-old)<tick*0.99999) ||
      side*(market-sl)<StopDist()-tick*1e-7) return false;
#ifdef __MQL5__
   bool sent=g_trade.PositionModify((ulong)ticket,sl,tp);
   if(sent && g_trade.ResultRetcode()==TRADE_RETCODE_DONE) return true;
   Note("SL update unconfirmed #"+IntegerToString(ticket)+" code "+IntegerToString((long)g_trade.ResultRetcode()));
   return false;
#else
   ResetLastError();
   if(!OrderModify((int)ticket,OrderOpenPrice(),sl,tp,0,clrNONE))
     {
      int e=GetLastError();
      if(e!=1) Note("Modify failed #"+IntegerToString(ticket)+" error "+IntegerToString(e));
      return e==1 && OrderSelect((int)ticket,SELECT_BY_TICKET) && OrderCloseTime()==0 &&
             OrderStopLoss()>0 && side*(OrderStopLoss()-sl)>=-tick*1e-7;
     }
   return true;
#endif
  }

// Closing is never blocked by pause, locks or filters. Retries only while the position is still open.
bool TradeClose(long ticket,double lots)
  {
   if(g_mode==MODE_SIGNALS) return false;
   for(int attempt=0;attempt<4;attempt++)
     {
      if(!PositionStillOpen(ticket)) return true;
#ifdef __MQL5__
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol || PositionGetInteger(POSITION_MAGIC)!=InpMagic) return false;
      if(IsNetting() && !NettingExclusiveFor(InpMagic)) return false;
      bool ok;
      if(lots>0 && IsNetting()) {
         double volume=PositionGetDouble(POSITION_VOLUME);
         if(lots>=volume || lots<SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)) return false;
         ENUM_ORDER_TYPE opposite=PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
         MqlTick quote; if(!SymbolInfoTick(_Symbol,quote)) return false;
         double px=opposite==ORDER_TYPE_BUY ? quote.ask : quote.bid;
         ok=g_trade.PositionOpen(_Symbol,opposite,lots,px,0,0,CT_COMMENT);
      }
      else if(lots>0) ok=g_trade.PositionClosePartial((ulong)ticket,lots,(ulong)InpSlippage);
      else       ok=g_trade.PositionClose((ulong)ticket,(ulong)InpSlippage);
      uint rc=g_trade.ResultRetcode();
      if(ok && (rc==TRADE_RETCODE_DONE || rc==TRADE_RETCODE_DONE_PARTIAL || rc==TRADE_RETCODE_PLACED)) return true;
      Note("Close #"+IntegerToString(ticket)+" retcode "+IntegerToString((int)rc));
      if(rc==TRADE_RETCODE_TIMEOUT) return false;
      if(rc!=TRADE_RETCODE_REQUOTE && rc!=TRADE_RETCODE_PRICE_CHANGED && rc!=TRADE_RETCODE_PRICE_OFF && rc!=TRADE_RETCODE_TOO_MANY_REQUESTS && rc!=TRADE_RETCODE_CONNECTION) return false;
      Sleep(300);
#else
      if(!OrderSelect((int)ticket,SELECT_BY_TICKET) || OrderCloseTime()!=0 || OrderSymbol()!=_Symbol || OrderMagicNumber()!=InpMagic) return false;
      double vol=(lots>0) ? lots : OrderLots();
      RefreshRates();
      double px=(OrderType()==OP_BUY) ? MarketInfo(_Symbol,MODE_BID) : MarketInfo(_Symbol,MODE_ASK);
      ResetLastError();
      if(OrderClose((int)ticket,vol,px,InpSlippage,clrNONE)) return true;
      int e=GetLastError();
      Note("Close #"+IntegerToString(ticket)+" error "+IntegerToString(e));
      if(e!=4 && e!=129 && e!=135 && e!=136 && e!=137 && e!=138 && e!=146) return false;
      Sleep(300);
#endif
     }
   return !PositionStillOpen(ticket);
  }

// Opening: no blind retry after a timeout (the order may already be live).
bool TradeOpen(int dir,double lots,double sl,double tp)
  {
   if(g_mode==MODE_SIGNALS) return false;
   lots=NormalizeLots(lots);
   sl=(sl>0) ? NormP(sl) : 0; tp=(tp>0) ? NormP(tp) : 0;
   for(int attempt=0;attempt<3;attempt++)
     {
#ifdef __MQL5__
      bool ok=(dir>0) ? g_trade.Buy(lots,_Symbol,0.0,sl,tp,CT_COMMENT) : g_trade.Sell(lots,_Symbol,0.0,sl,tp,CT_COMMENT);
      uint rc=g_trade.ResultRetcode();
      if(ok && (rc==TRADE_RETCODE_DONE || rc==TRADE_RETCODE_DONE_PARTIAL || rc==TRADE_RETCODE_PLACED)) return true;
      Note("Open failed retcode "+IntegerToString((int)rc));
      if(rc!=TRADE_RETCODE_REQUOTE && rc!=TRADE_RETCODE_PRICE_CHANGED && rc!=TRADE_RETCODE_PRICE_OFF) return false;
      Sleep(300);
#else
      RefreshRates();
      double px=(dir>0) ? MarketInfo(_Symbol,MODE_ASK) : MarketInfo(_Symbol,MODE_BID);
      ResetLastError();
      int tk=OrderSend(_Symbol,(dir>0) ? OP_BUY : OP_SELL,lots,px,InpSlippage,sl,tp,CT_COMMENT,InpMagic,0,(dir>0) ? clrDodgerBlue : clrOrangeRed);
      if(tk>0) return true;
      int e=GetLastError();
      Note("Open failed error "+IntegerToString(e));
      if(e!=129 && e!=135 && e!=136 && e!=138 && e!=146) return false;
      Sleep(300);
#endif
     }
   return false;
  }

void LoadHistoryStats()
  {
   g_closedTrades=0; g_closedWins=0; g_closedNet=0; g_consecLosses=0;
   int dayKeyNow=DayKey(TimeCurrent());
   int streak=0; bool streakOpen=true;
#ifdef __MQL5__
   if(!HistorySelect(0,TimeCurrent()+86400)) return;
   int n=HistoryDealsTotal();
   for(int i=n-1;i>=0;i--)
     {
      ulong d=HistoryDealGetTicket(i);
      if(d==0) continue;
      if(HistoryDealGetString(d,DEAL_SYMBOL)!=_Symbol) continue;
      if(HistoryDealGetInteger(d,DEAL_MAGIC)!=InpMagic) continue;
      long entry=HistoryDealGetInteger(d,DEAL_ENTRY);
      if(entry!=DEAL_ENTRY_OUT && entry!=DEAL_ENTRY_OUT_BY && entry!=DEAL_ENTRY_INOUT) continue;
      double p=HistoryDealGetDouble(d,DEAL_PROFIT)+HistoryDealGetDouble(d,DEAL_SWAP)+HistoryDealGetDouble(d,DEAL_COMMISSION);
      g_closedTrades++; g_closedNet+=p; if(p>0) g_closedWins++;
      if(streakOpen)
        {
         if(p<0 && DayKey((datetime)HistoryDealGetInteger(d,DEAL_TIME))==dayKeyNow) streak++;
         else streakOpen=false;
        }
     }
#else
   int n=OrdersHistoryTotal();
   for(int i=n-1;i>=0;i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
      if(OrderSymbol()!=_Symbol || OrderMagicNumber()!=InpMagic) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL) continue;
      double p=OrderProfit()+OrderSwap()+OrderCommission();
      g_closedTrades++; g_closedNet+=p; if(p>0) g_closedWins++;
      if(streakOpen)
        {
         if(p<0 && DayKey(OrderCloseTime())==dayKeyNow) streak++;
         else streakOpen=false;
        }
     }
#endif
   g_consecLosses=streak;
  }

//================================ DATA AND INDICATORS ================================
// All indicators are computed in-house from raw price series (index = bar shift, 0 = forming bar).
int      N=0;
datetime T[];
double   O[],H[],L[],C[],V[],TR[],SRC[];
double   ATR14[],ATRu[],ATRb[],ATRs[],ATRk[],ATRsyn[],ATRavg[];
double   EMAt[],EMAf[],EMAs[],MAut[],EMAsyn[],EMAm1[],EMAm2[],MACDl[],MACDs[],MACDh[];
double   RSI[],ADX[],PDI[],MDI[];
double   BBm[],BBu[],BBl[],KCu[],KCl[];
double   UTt[],DUt[],KF[],KSTl[],KSTup[],KSTdn[],VW[],ZU[],ZL[],SYNl[],CHOP[],R2[];
int      UTd[],DUd[],KSTd[],SYNd[],HTFb[],MT2d[],MT3d[],MT4d[];
double   MT2l[],MT3l[],MT4l[];

void SizeAll(int n)
  {
   ArrayResize(T,n); ArrayResize(O,n); ArrayResize(H,n); ArrayResize(L,n); ArrayResize(C,n); ArrayResize(V,n);
   ArrayResize(TR,n); ArrayResize(SRC,n);
   ArrayResize(ATR14,n); ArrayResize(ATRu,n); ArrayResize(ATRb,n); ArrayResize(ATRs,n); ArrayResize(ATRk,n);
   ArrayResize(ATRsyn,n); ArrayResize(ATRavg,n);
   ArrayResize(EMAt,n); ArrayResize(EMAf,n); ArrayResize(EMAs,n); ArrayResize(MAut,n); ArrayResize(EMAsyn,n);
   ArrayResize(EMAm1,n); ArrayResize(EMAm2,n); ArrayResize(MACDl,n); ArrayResize(MACDs,n); ArrayResize(MACDh,n);
   ArrayResize(RSI,n); ArrayResize(ADX,n); ArrayResize(PDI,n); ArrayResize(MDI,n);
   ArrayResize(BBm,n); ArrayResize(BBu,n); ArrayResize(BBl,n); ArrayResize(KCu,n); ArrayResize(KCl,n);
   ArrayResize(UTt,n); ArrayResize(DUt,n); ArrayResize(KF,n); ArrayResize(KSTl,n); ArrayResize(KSTup,n); ArrayResize(KSTdn,n);
   ArrayResize(VW,n); ArrayResize(ZU,n); ArrayResize(ZL,n); ArrayResize(SYNl,n); ArrayResize(CHOP,n); ArrayResize(R2,n);
   ArrayResize(UTd,n); ArrayResize(DUd,n); ArrayResize(KSTd,n); ArrayResize(SYNd,n); ArrayResize(HTFb,n);
   ArrayResize(MT2d,n); ArrayResize(MT3d,n); ArrayResize(MT4d,n); ArrayResize(MT2l,n); ArrayResize(MT3l,n); ArrayResize(MT4l,n);
  }

void SeriesEMA(const double &src[],double &out[],int period,int n)
  {
   if(period<1) period=1;
   double k=2.0/(period+1.0);
   out[n-1]=src[n-1];
   for(int i=n-2;i>=0;i--) out[i]=out[i+1]+k*(src[i]-out[i+1]);
  }

void SeriesRMA(const double &src[],double &out[],int period,int n)
  {
   if(period<1) period=1;
   double a=1.0/period;
   out[n-1]=src[n-1];
   for(int i=n-2;i>=0;i--) out[i]=out[i+1]+a*(src[i]-out[i+1]);
  }

void SeriesSMA(const double &src[],double &out[],int period,int n)
  {
   if(period<1) period=1;
   double sum=0;
   for(int i=n-1;i>=0;i--)
     {
      sum+=src[i];
      if(i+period<n) sum-=src[i+period];
      int cnt=MathMin(period,n-i);
      out[i]=sum/cnt;
     }
  }

double Highest(const double &a[],int from,int count)
  {
   double m=-DBL_MAX;
   for(int i=from;i<from+count && i<N;i++) if(a[i]>m) m=a[i];
   return m;
  }
double Lowest(const double &a[],int from,int count)
  {
   double m=DBL_MAX;
   for(int i=from;i<from+count && i<N;i++) if(a[i]<m) m=a[i];
   return m;
  }

// UT Bot style ATR trailing line: ratchets with price, re-anchors on a cross.
void SeriesUT(const double &src[],const double &atr[],double key,double &line[],int &dir[],int n)
  {
   line[n-1]=src[n-1]; dir[n-1]=0;
   for(int i=n-2;i>=0;i--)
     {
      double loss=key*atr[i], prevLine=line[i+1], s=src[i], ps=src[i+1], v;
      if(s>prevLine && ps>prevLine)      v=MathMax(prevLine,s-loss);
      else if(s<prevLine && ps<prevLine) v=MathMin(prevLine,s+loss);
      else if(s>prevLine)                v=s-loss;
      else                               v=s+loss;
      line[i]=v;
      int d=dir[i+1];
      if(ps<=prevLine && s>prevLine) d=1;
      else if(ps>=prevLine && s<prevLine) d=-1;
      else if(d==0) d=(s>v) ? 1 : -1;
      dir[i]=d;
     }
  }

// Asymmetric dual engine: floor engine while long, ceiling engine while short.
void SeriesDualUT(int n)
  {
   DUd[n-1]=1; DUt[n-1]=C[n-1]-InpUTSellKey*ATRs[n-1];
   for(int i=n-2;i>=0;i--)
     {
      int d=DUd[i+1]; double ln=DUt[i+1];
      if(d>0)
        {
         ln=MathMax(ln,SRC[i]-InpUTSellKey*ATRs[i]);
         if(SRC[i]<ln) { d=-1; ln=SRC[i]+InpUTBuyKey*ATRb[i]; }
        }
      else
        {
         ln=MathMin(ln,SRC[i]+InpUTBuyKey*ATRb[i]);
         if(SRC[i]>ln) { d=1; ln=SRC[i]-InpUTSellKey*ATRs[i]; }
        }
      DUd[i]=d; DUt[i]=ln;
     }
  }

void SeriesKalmanST(int n)
  {
   double g=MathMax(0.01,MathMin(0.99,InpKalmanGain));
   double R=1.0/g-1.0, Q=MathMax(0.0001,InpKalmanNoise), P=1.0;
   KF[n-1]=(H[n-1]+L[n-1]+C[n-1])/3.0;
   for(int i=n-2;i>=0;i--)
     {
      double z=(H[i]+L[i]+C[i])/3.0;
      P=P+Q;
      double K=P/(P+R);
      KF[i]=KF[i+1]+K*(z-KF[i+1]);
      P=(1.0-K)*P;
     }
   KSTup[n-1]=KF[n-1]-InpKSTMult*ATRk[n-1];
   KSTdn[n-1]=KF[n-1]+InpKSTMult*ATRk[n-1];
   KSTd[n-1]=1; KSTl[n-1]=KSTup[n-1];
   for(int i=n-2;i>=0;i--)
     {
      double up=KF[i]-InpKSTMult*ATRk[i], dn=KF[i]+InpKSTMult*ATRk[i];
      KSTup[i]=(C[i+1]>KSTup[i+1]) ? MathMax(up,KSTup[i+1]) : up;
      KSTdn[i]=(C[i+1]<KSTdn[i+1]) ? MathMin(dn,KSTdn[i+1]) : dn;
      int d=KSTd[i+1];
      if(d<0 && C[i]>KSTdn[i+1]) d=1;
      else if(d>0 && C[i]<KSTup[i+1]) d=-1;
      KSTd[i]=d;
      KSTl[i]=(d>0) ? KSTup[i] : KSTdn[i];
     }
  }

void SeriesSynapse(int n)
  {
   SYNd[n-1]=1; SYNl[n-1]=EMAsyn[n-1]-InpSynMult*ATRsyn[n-1];
   for(int i=n-2;i>=0;i--)
     {
      double adapt=(ATRavg[i]>0) ? MathMax(0.7,MathMin(1.5,ATR14[i]/ATRavg[i])) : 1.0;
      double m=InpSynMult*adapt;
      double lo=EMAsyn[i]-m*ATRsyn[i], hi=EMAsyn[i]+m*ATRsyn[i];
      int d=SYNd[i+1]; double ln=SYNl[i+1];
      if(d>0)
        {
         ln=MathMax(ln,lo);
         if(C[i]<ln) { d=-1; ln=hi; }
        }
      else
        {
         ln=MathMin(ln,hi);
         if(C[i]>ln) { d=1; ln=lo; }
        }
      SYNd[i]=d; SYNl[i]=ln;
     }
  }

void SeriesADX(int n)
  {
   double pdm[],mdm[],spdm[],smdm[],str[],dx[];
   ArrayResize(pdm,n); ArrayResize(mdm,n); ArrayResize(spdm,n); ArrayResize(smdm,n); ArrayResize(str,n); ArrayResize(dx,n);
   pdm[n-1]=0; mdm[n-1]=0;
   for(int i=n-2;i>=0;i--)
     {
      double up=H[i]-H[i+1], dn=L[i+1]-L[i];
      pdm[i]=(up>dn && up>0) ? up : 0;
      mdm[i]=(dn>up && dn>0) ? dn : 0;
     }
   SeriesRMA(pdm,spdm,InpADXPeriod,n); SeriesRMA(mdm,smdm,InpADXPeriod,n); SeriesRMA(TR,str,InpADXPeriod,n);
   for(int i=n-1;i>=0;i--)
     {
      PDI[i]=(str[i]>0) ? 100.0*spdm[i]/str[i] : 0;
      MDI[i]=(str[i]>0) ? 100.0*smdm[i]/str[i] : 0;
      double s=PDI[i]+MDI[i];
      dx[i]=(s>0) ? 100.0*MathAbs(PDI[i]-MDI[i])/s : 0;
     }
   SeriesRMA(dx,ADX,InpADXPeriod,n);
  }

void SeriesRSI(int n)
  {
   double g[],ls[],ag[],al[];
   ArrayResize(g,n); ArrayResize(ls,n); ArrayResize(ag,n); ArrayResize(al,n);
   g[n-1]=0; ls[n-1]=0;
   for(int i=n-2;i>=0;i--) { double d=C[i]-C[i+1]; g[i]=(d>0) ? d : 0; ls[i]=(d<0) ? -d : 0; }
   SeriesRMA(g,ag,InpRSIPeriod,n); SeriesRMA(ls,al,InpRSIPeriod,n);
   for(int i=0;i<n;i++) RSI[i]=(al[i]<=0) ? ((ag[i]>0) ? 100.0 : 50.0) : 100.0-100.0/(1.0+ag[i]/al[i]);
  }

void SeriesBands(int n)
  {
   int p=MathMax(2,InpBBPeriod);
   SeriesSMA(C,BBm,p,n);
   double kcm[]; ArrayResize(kcm,n); SeriesEMA(C,kcm,p,n);
   for(int i=0;i<n;i++)
     {
      double ss=0; int cnt=0;
      for(int j=i;j<i+p && j<n;j++) { double d=C[j]-BBm[i]; ss+=d*d; cnt++; }
      double sd=(cnt>0) ? MathSqrt(ss/cnt) : 0;
      BBu[i]=BBm[i]+InpBBDev*sd; BBl[i]=BBm[i]-InpBBDev*sd;
      KCu[i]=kcm[i]+InpKCMult*ATR14[i]; KCl[i]=kcm[i]-InpKCMult*ATR14[i];
     }
  }

void SeriesZones(int n)
  {
   int p=MathMax(2,InpVWMAPeriod), lb=MathMax(2,InpZoneLookback);
   for(int i=0;i<n;i++)
     {
      double pv=0,vv=0,cs=0; int cnt=0;
      for(int j=i;j<i+p && j<n;j++) { pv+=C[j]*V[j]; vv+=V[j]; cs+=C[j]; cnt++; }
      VW[i]=(vv>0) ? pv/vv : cs/MathMax(1,cnt);
      double hh=Highest(H,i,lb), ll=Lowest(L,i,lb);
      ZU[i]=VW[i]+MathMax(hh-VW[i],0)*InpZoneMult/2.0;
      ZL[i]=VW[i]-MathMax(VW[i]-ll,0)*InpZoneMult/2.0;
     }
  }

void SeriesRegimeStats(int n)
  {
   int cp=MathMax(2,InpChopPeriod), rp=MathMax(5,InpR2Period);
   for(int i=0;i<n;i++)
     {
      double s=0; for(int j=i;j<i+cp && j<n;j++) s+=TR[j];
      double rng=Highest(H,i,cp)-Lowest(L,i,cp);
      CHOP[i]=(rng>0 && s>0) ? 100.0*MathLog10(s/rng)/MathLog10((double)cp) : 50.0;
      double sx=0,sy=0,sxx=0,syy=0,sxy=0; int m=0;
      for(int j=i;j<i+rp && j<n;j++) { double x=(double)(j-i), y=C[j]; sx+=x; sy+=y; sxx+=x*x; syy+=y*y; sxy+=x*y; m++; }
      double num=m*sxy-sx*sy, den=(m*sxx-sx*sx)*(m*syy-sy*sy);
      R2[i]=(den>0) ? (num*num)/den : 0;
     }
  }

// Higher-timeframe UT direction and 200 EMA bias mapped onto chart bars, using only completed HTF bars.
void MapTimeframe(ENUM_TIMEFRAMES tf,int &dirOut[],double &lineOut[],int &biasOut[],bool wantBias,int mapCount,int explicitEMA=0)
  {
   for(int i=0;i<N;i++) { dirOut[i]=0; lineOut[i]=0; if(wantBias) biasOut[i]=0; }
   int chartSec=PeriodSeconds(PERIOD_CURRENT), tfSec=PeriodSeconds(tf);
   int period=explicitEMA>0 ? explicitEMA : InpEMATrend;
   if(tfSec<chartSec && explicitEMA>0) return;
   if(tfSec<=chartSec && explicitEMA==0)
     {
      for(int i=0;i<N;i++)
        {
         dirOut[i]=UTd[i]; lineOut[i]=UTt[i];
         if(wantBias) biasOut[i]=(C[i]>EMAt[i]) ? 1 : -1;
        }
      return;
     }
   int avail=iBars(_Symbol,tf);
   int m=MathMin(avail,MathMax(period*3,300));
   m=MathMin(m,CT_MAXBARS);
   if(m<InpUTATR+20 || (wantBias && m<period)) return;
   double hc[],hh[],hl[],htr[],hatr[],hline[],hema[];
   int hdir[];
   datetime ht[];
   ArrayResize(hc,m); ArrayResize(hh,m); ArrayResize(hl,m); ArrayResize(htr,m); ArrayResize(hatr,m);
   ArrayResize(hline,m); ArrayResize(hema,m); ArrayResize(hdir,m); ArrayResize(ht,m);
   for(int j=0;j<m;j++)
     {
      hc[j]=iClose(_Symbol,tf,j); hh[j]=iHigh(_Symbol,tf,j); hl[j]=iLow(_Symbol,tf,j); ht[j]=iTime(_Symbol,tf,j);
      if(hc[j]<=0) return;
     }
   for(int j=m-1;j>=0;j--)
     {
      if(j==m-1) htr[j]=hh[j]-hl[j];
      else htr[j]=MathMax(hh[j]-hl[j],MathMax(MathAbs(hh[j]-hc[j+1]),MathAbs(hl[j]-hc[j+1])));
     }
   SeriesRMA(htr,hatr,InpUTATR,m);
   SeriesUT(hc,hatr,InpUTKey,hline,hdir,m);
   if(wantBias) SeriesEMA(hc,hema,period,m);
   int cnt=MathMin(mapCount,N);
   for(int i=0;i<cnt;i++)
     {
      int j=iBarShift(_Symbol,tf,T[i],false);
      if(j<0 || j>=m) continue;
      if(explicitEMA>0 || T[i]+chartSec<ht[j]+tfSec) j++;   // HTF bar not finished when this chart bar closed
      if(j>=m) continue;
      dirOut[i]=hdir[j]; lineOut[i]=hline[j];
      if(wantBias && m-j>=period) biasOut[i]=hc[j]>hema[j] ? 1 : hc[j]<hema[j] ? -1 : 0;
     }
  }

int VectorFastSide[],VectorAsymSide[],VectorHourBias[];
void BuildVectorStudies(int count,int mapped)
{
   double slowATR=0,line=0;
   ArrayResize(VectorFastSide,count); ArrayResize(VectorAsymSide,count); ArrayResize(VectorHourBias,count);
   double fastLine[]; ArrayResize(fastLine,count);
   SeriesUT(SRC,TR,2.0,fastLine,VectorFastSide,count);
   int side=0;
   for(int i=count-1;i>=0;i--) {
      int samples=count-i;
      if(samples<=300) slowATR+=TR[i]/300.0;
      else slowATR+=(TR[i]-slowATR)/300.0;
      if(samples==300) { side=1; line=SRC[i]-1.1*TR[i]; }
      if(samples>300) {
         int previous=side;
         if(side>0 && SRC[i]<line) side=-1;
         else if(side<0 && SRC[i]>line) side=1;
         double next=side>0 ? SRC[i]-1.1*TR[i] : SRC[i]+1.1*slowATR;
         if(previous!=side) line=next;
         else line=side>0 ? MathMax(line,next) : MathMin(line,next);
      }
      VectorAsymSide[i]=side;
   }
   int ignoredDir[]; double ignoredLine[]; ArrayResize(ignoredDir,count); ArrayResize(ignoredLine,count);
   MapTimeframe(PERIOD_H1,ignoredDir,ignoredLine,VectorHourBias,true,mapped,200);
}
int VectorNightFlip(int s)
{
   if(SYNd[s]==SYNd[s+1] || !DroidWindow(T[s],true) ||
      !DroidWindow(T[s]+PeriodSeconds(PERIOD_CURRENT),true)) return 0;
   for(int j=1;j<=3;j++) if(SYNd[s+j]!=SYNd[s+j+1]) return 0;
   return SYNd[s];
}
int VectorGoldFlip(int s)
{
   if(_Period!=PERIOD_M15 || VectorHourBias[s]!=1 || ADX[s]<=25 || !VectorGoldSymbol(_Symbol)) return 0;
   return VectorFastSide[s]>0 && VectorFastSide[s+1]<0 ? 1 : 0;
}
int VectorChartSetup(int s)
{
   if(N-s<=300 || PeriodSeconds(PERIOD_CURRENT)>3600) return 0;
   int flip=UTd[s]!=UTd[s+1] ? UTd[s] : 0;
   int maState=MAut[s]>UTt[s] && C[s]>UTt[s] ? 1 : MAut[s]<UTt[s] && C[s]<UTt[s] ? -1 : 0;
   int bias=C[s]>EMAt[s] ? 1 : C[s]<EMAt[s] ? -1 : 0;
   bool chase=InpMaxStreak>0 && (StreakAt(s,1)>=InpMaxStreak || StreakAt(s,-1)>=InpMaxStreak);
   double ratio=ATRavg[s]>0 ? ATR14[s]/ATRavg[s] : 0;
   return VectorDecision(flip,maState,bias,VectorHourBias[s],VectorAsymSide[s],SniperSignal(s),
                         VectorNightFlip(s),VectorGoldFlip(s),ADX[s],ratio,chase);
}

// Native UT confirmation averages. Short warm-up windows are used only on the oldest samples.
void PrideWMA(const double &src[],double &out[],int period,int n)
{
   double sum=0,weighted=0;
   for(int i=n-1;i>=0;i--) {
      int k=(int)MathMin(period,n-i);
      if(n-i<=period) { weighted+=k*src[i]; sum+=src[i]; }
      else { weighted+=period*src[i]-sum; sum+=src[i]-src[i+period]; }
      out[i]=weighted/(k*(k+1)*0.5);
   }
}
void PrideAverageSeries(const double &src[],double &out[],int period,int n)
{
   if(PrideMA==PRIDE_EMA) { SeriesEMA(src,out,period,n); return; }
   if(PrideMA==PRIDE_SMA) { SeriesSMA(src,out,period,n); return; }
   if(PrideMA==PRIDE_WMA) { PrideWMA(src,out,period,n); return; }
   double fast[],slow[];
   ArrayResize(fast,n); ArrayResize(slow,n);
   PrideWMA(src,fast,(int)MathMax(1,period/2),n); PrideWMA(src,slow,period,n);
   for(int i=0;i<n;i++) fast[i]=2*fast[i]-slow[i];
   PrideWMA(fast,out,(int)MathMax(1,MathRound(MathSqrt(period))),n);
}
int prideClosedRoute=0;
double prideClosedEff=0;
int PrideChartRoute(int s,bool flagConflict=false)
{
   if(s<1 || N-s<=300 || N-s<PridePathBars+1 || PeriodSeconds(PERIOD_CURRENT)>3600 || ATRavg[s]<=0) return 0;
   int flip=UTd[s]!=UTd[s+1] ? UTd[s] : 0;
   int ma=C[s]>UTt[s] && MAut[s]>UTt[s] ? 1 : C[s]<UTt[s] && MAut[s]<UTt[s] ? -1 : 0;
   int bias=C[s]>EMAt[s] ? 1 : C[s]<EMAt[s] ? -1 : 0;
   bool extended=InpMaxStreak>0 && (StreakAt(s,1)>=InpMaxStreak || StreakAt(s,-1)>=InpMaxStreak);
   return PrideRoute(flip,ma,bias,VectorHourBias[s],VectorAsymSide[s],SniperSignal(s),VectorNightFlip(s),
                    VectorGoldFlip(s),RSI[s]>RSI[s+1] ? 1 : RSI[s]<RSI[s+1] ? -1 : 0,
                    PrideEfficiency(C,s,PridePathBars),PrideTrendFloor,ADX[s],ATR14[s]/ATRavg[s],extended,flagConflict);
}
string PrideRouteName(int route)
{
   int k=(int)MathAbs(route);
   string name=k==1 ? "Trend" : k==2 ? "Pivot" : k==3 ? "Overnight" : k==4 ? "Gold M15" : k==5 ? "W%R" : k==6 ? "Control" : "Hold";
   return name+(route>0 ? " BUY" : route<0 ? " SELL" : "");
}

double PrideZoneMA[],PrideST[];
void PrideBuild()
{
   ArrayResize(PrideZoneMA,N);
   PrideAverageSeries(C,PrideZoneMA,20,N);
   if(!PrideUseST) return;
   double a[]; ArrayResize(a,N); SeriesRMA(TR,a,10,N);
   ArrayResize(PrideST,N);
   double upper=0,lower=0;
   int side=-1;
   for(int j=N-1;j>=0;j--) {
      double mid=(H[j]+L[j])*0.5,u=mid+3*a[j],l=mid-3*a[j];
      if(j==N-1) { upper=u;lower=l; }
      else {
         if(u<upper || C[j+1]>upper) upper=u;
         if(l>lower || C[j+1]<lower) lower=l;
         if(side<0 && C[j]>upper) side=1;
         else if(side>0 && C[j]<lower) side=-1;
      }
      PrideST[j]=side;
   }
}
int PrideCross(double prev,double cur)
{
   if(!MathIsValidNumber(prev+cur) || prev>0 || cur>0 || prev < -100 || cur < -100) return 0;
   if(prev<=-80 && cur>-80) return 1;
   if(prev>=-20 && cur<-20) return -1;
   return 0;
}
int PrideControl(int flip,double adx,double rsi)
{
   if(!MathIsValidNumber(adx+rsi) || adx<16 || adx>20 || rsi<0 || rsi>100) return 0;
   if(flip==1 && rsi>55) return 1;
   if(flip==-1 && rsi<45) return -1;
   return 0;
}
int PrideChoose(int base,int zone,int control)
{
   if(base==99 || base*zone<0 || base*control<0 || zone*control<0) return 0;
   if(base!=0) return base;
   return control!=0 ? 6*control : 5*zone;
}
double PrideWilliams(int s)
{
   double hi=Highest(H,s,14),lo=Lowest(L,s,14);
   if(hi<=lo || C[s]<lo || C[s]>hi) return 1.0;
   return -100.0*((hi-C[s])/(hi-lo));
}
int PrideZone(int s)
{
   int d=PrideCross(PrideWilliams(s+1),PrideWilliams(s));
   if(d==0 || (PrideUseMA && d*(C[s]-PrideZoneMA[s])<=0)) return 0;
   if(PrideUseST && PrideST[s]!=d) return 0;
   if(PrideUseChop) {
      double range=Highest(H,s,12)-Lowest(L,s,12),trSum=0;
      for(int i=0;i<12;i++) trSum+=TR[s+i];
      if(range<=0 || trSum<=0 || 100.0*MathLog(trSum/range)/MathLog(12.0)>=PrideCI) return 0;
   }
   if(PrideUseVolume || PrideUseBands) {
      double vol=0,width=0;
      for(int i=s;i<s+50;i++){
         if(PrideUseVolume && V[i]<=0) return 0;
         vol+=V[i];
         if(PrideUseBands) {
            if(BBm[i]<=0 || BBu[i]<=BBl[i]) return 0;
            width+=(BBu[i]-BBl[i])/BBm[i];
         }
      }
      if(PrideUseVolume && V[s]<=vol/50.0) return 0;
      if(PrideUseBands && (BBu[s]-BBl[s])/BBm[s]<=width/50.0) return 0;
   }
   return d;
}
int PrideSelection(int model,int s)
{
   if(s<1 || N-s<100 || ATR14[s]<=0 || PeriodSeconds(PERIOD_CURRENT)>3600) return 0;
   int ctrl=PrideControl(UTd[s]!=UTd[s+1]?UTd[s]:0,ADX[s],RSI[s]);
   if(model==STRAT_CONTROL) return 6*ctrl;
   if(PrideUseBands && N-s<InpBBPeriod+50) return 0;
   int zone=PrideZone(s);
   if(model==STRAT_ZONE) return 5*zone;
   if(N-s<=300 || ATRavg[s]<=0 || ATR14[s]>1.30*ATRavg[s] || VectorHourBias[s]==0) return 0;
   int base=PrideChartRoute(s,true);
   int pick=PrideChoose(base,zone,ctrl);
   if(MathAbs(pick)>=5 && pick*VectorHourBias[s]<0) return 0;
   return pick;
}
bool PrideWeekend(int st,datetime stamp)
{
   if(!PrideFriday || (st!=STRAT_COMBINED && st!=STRAT_CONTROL)) return false;
   MqlDateTime ny;
   if(!TimeToStruct(DroidEastern(stamp),ny)) return false;
   return ny.day_of_week==6 || (ny.day_of_week==5 && ny.hour*60+ny.min>=1005) ||
          (ny.day_of_week==0 && ny.hour<18);
}

bool LoadSeries()
  {
   int want=MathMax(300,MathMin(InpLookback,CT_MAXBARS));
   int avail=iBars(_Symbol,PERIOD_CURRENT);
   if(avail<MathMax(120,InpEMATrend/2)) return false;
   int n=MathMin(want,avail);
   if(n!=N) { N=n; SizeAll(N); }
   for(int i=0;i<N;i++)
     {
      T[i]=iTime(_Symbol,PERIOD_CURRENT,i); O[i]=iOpen(_Symbol,PERIOD_CURRENT,i); H[i]=iHigh(_Symbol,PERIOD_CURRENT,i);
      L[i]=iLow(_Symbol,PERIOD_CURRENT,i); C[i]=iClose(_Symbol,PERIOD_CURRENT,i); V[i]=(double)iVolume(_Symbol,PERIOD_CURRENT,i);
      if(C[i]<=0 || H[i]<=0) return false;
     }
   for(int i=N-1;i>=0;i--)
     {
      if(i==N-1) TR[i]=H[i]-L[i];
      else TR[i]=MathMax(H[i]-L[i],MathMax(MathAbs(H[i]-C[i+1]),MathAbs(L[i]-C[i+1])));
      SRC[i]=InpUTHeikin ? (O[i]+H[i]+L[i]+C[i])/4.0 : C[i];
     }
   SeriesRMA(TR,ATR14,14,N); SeriesRMA(TR,ATRu,InpUTATR,N); SeriesRMA(TR,ATRb,InpUTBuyATR,N); SeriesRMA(TR,ATRs,InpUTSellATR,N);
   SeriesRMA(TR,ATRk,InpKSTATR,N); SeriesRMA(TR,ATRsyn,InpSynATR,N); SeriesSMA(ATR14,ATRavg,50,N);
   SeriesEMA(C,EMAt,InpEMATrend,N); SeriesEMA(C,EMAf,InpEMAFast,N); SeriesEMA(C,EMAs,InpEMASlow,N);
   PrideAverageSeries(SRC,MAut,InpUTMAPeriod,N); SeriesEMA(C,EMAsyn,InpSynEMA,N);
   SeriesEMA(C,EMAm1,12,N); SeriesEMA(C,EMAm2,26,N);
   for(int i=0;i<N;i++) MACDl[i]=EMAm1[i]-EMAm2[i];
   SeriesEMA(MACDl,MACDs,9,N);
   for(int i=0;i<N;i++) MACDh[i]=MACDl[i]-MACDs[i];
   SeriesRSI(N); SeriesADX(N); SeriesBands(N); SeriesZones(N); SeriesRegimeStats(N);
   SeriesUT(SRC,ATRu,InpUTKey,UTt,UTd,N);
   PrideBuild(); SeriesDualUT(N); SeriesKalmanST(N); SeriesSynapse(N);
   int mapCount=g_drawEnabled ? MathMin(N,InpDrawBars+8) : 8;
   BuildVectorStudies(N,mapCount);
   int dummy[]; ArrayResize(dummy,N);
   MapTimeframe(InpHTF,MT2d,MT2l,HTFb,true,mapCount);      // HTF bias (MT2 arrays reused below)
   MapTimeframe(InpMTF2,MT2d,MT2l,dummy,false,mapCount);
   MapTimeframe(InpMTF3,MT3d,MT3l,dummy,false,mapCount);
   MapTimeframe(InpMTF4,MT4d,MT4l,dummy,false,mapCount);
   return true;
  }

//================================ SIGNAL ENGINE ================================
bool FlipTo(const int &d[],int s,int want) { return (s+1<N && d[s]==want && d[s+1]!=want); }

bool IsPivotLow(int k,int p)
  {
   if(k-p<1 || k+p>=N) return false;
   for(int j=1;j<=p;j++) if(L[k]>=L[k-j] || L[k]>=L[k+j]) return false;
   return true;
  }
bool IsPivotHigh(int k,int p)
  {
   if(k-p<1 || k+p>=N) return false;
   for(int j=1;j<=p;j++) if(H[k]<=H[k-j] || H[k]<=H[k+j]) return false;
   return true;
  }

int ConfluenceAt(int s,int dir)
  {
   if(s+1>=N) return 0;
   int sc=0;
   if(dir*(C[s]-EMAt[s])>0) sc+=15;
   if(dir*(EMAf[s]-EMAs[s])>0) sc+=10;
   if(UTd[s]==dir) sc+=15;
   if(KSTd[s]==dir) sc+=10;
   if(SYNd[s]==dir) sc+=10;
   if(dir*MACDh[s]>0) sc+=10;
   if(dir*(RSI[s]-50.0)>0) sc+=10;
   if(ADX[s]>=20 && dir*(PDI[s]-MDI[s])>0) sc+=10;
   if(HTFb[s]==dir) sc+=10;
   return sc;
  }

// 1 trend up, -1 trend down, 0 range, 2 volatile spike, 3 transition
int RegimeAt(int s)
  {
   if(ATRavg[s]>0 && ATR14[s]>InpSpikeRatio*ATRavg[s]) return 2;
   if(ADX[s]>=InpADXMin && CHOP[s]<55.0) return (PDI[s]>=MDI[s]) ? 1 : -1;
   if(CHOP[s]>=61.8 || ADX[s]<18.0) return 0;
   return 3;
  }
string RegimeName(int r)
  {
   if(r==1) return "Trending up";
   if(r==-1) return "Trending down";
   if(r==0) return "Ranging / choppy";
   if(r==2) return "Volatility spike";
   return "Transition";
  }

bool IsReversionStrategy(int st) { return (st==STRAT_UT_SNIPER || st==STRAT_KALMAN_VWMA_REV); }

bool TouchLowerZone(int x) { for(int k=x;k<x+10 && k<N;k++) if(L[k]<=ZL[k]) return true; return false; }
bool TouchUpperZone(int x) { for(int k=x;k<x+10 && k<N;k++) if(H[k]>=ZU[k]) return true; return false; }
bool ZoneRevUp(int x)   { return (x+11<N && TouchLowerZone(x) && C[x]>O[x] && C[x]>ZL[x]); }
bool ZoneRevDown(int x) { return (x+11<N && TouchUpperZone(x) && C[x]<O[x] && C[x]<ZU[x]); }
bool InSqueeze(int k)   { return (BBu[k]<KCu[k] && BBl[k]>KCl[k]); }

int SniperSignal(int s)
  {
   if(s+30>=N || InpPivotBars<1 || InpPivotBars>N/2) return 0;
   for(int dir=1;dir>=-1;dir-=2)
     {
      if(UTd[s]!=dir) continue;
      bool fresh=false;
      for(int k=s;k<s+3;k++) if(UTd[k]==dir && UTd[k+1]!=dir) fresh=true;
      if(!fresh) continue;
      bool zone=false; int a=s;
      for(int k=s;k<s+5;k++)
        {
         if(dir>0 && L[k]<=BBl[k]) { zone=true; if(L[k]<=L[a]) a=k; }
         if(dir<0 && H[k]>=BBu[k]) { zone=true; if(H[k]>=H[a]) a=k; }
        }
      if(!zone) continue;
      int b=s+5;
      for(int k=s+5;k<s+25;k++) { if(dir>0 && L[k]<L[b]) b=k; if(dir<0 && H[k]>H[b]) b=k; }
      bool div=(dir>0) ? (L[a]<=L[b] && RSI[a]>RSI[b]) : (H[a]>=H[b] && RSI[a]<RSI[b]);
      bool piv=false;
      for(int k=s+InpPivotBars;k<s+InpPivotBars+5;k++) if((dir>0 && IsPivotLow(k,InpPivotBars)) || (dir<0 && IsPivotHigh(k,InpPivotBars))) piv=true;
      if(!(div || piv)) continue;
      if(dir*(C[s]-O[s])<=0) continue;
      if(ATRavg[s]>0 && ATR14[s]>InpSpikeRatio*ATRavg[s]) continue;
      return dir;
     }
   return 0;
  }

// Rolling random-feature neural regression. Hidden weights are fixed. The output
// layer fits four exponentially weighted, regularized one-feature regressions.
double ApexSoft(double x) { return x/(1.0+MathAbs(x)); }
double ApexBound(double x) { return MathMax(-1.0,MathMin(1.0,x)); }

void ApexHidden(int s,int horizon,double &h0,double &h1,double &h2,double &h3)
{
   double scale=ATR14[s];
   if(scale<=0) { h0=0; h1=0; h2=0; h3=0; return; }
   double body=(C[s]-O[s])/scale;
   double drift=(C[s]-C[s+4])/(2.0*scale);
   double stretch=(C[s]-C[s+12])/(3.5*scale);
   double wick=(2.0*C[s]-H[s]-L[s])/scale;
   if(horizon==3) {
      h0=ApexSoft(1.6*drift+0.7*stretch);
      h1=ApexSoft(1.2*body+0.6*drift);
      h2=ApexSoft(wick+0.8*stretch);
      h3=ApexSoft(drift-0.5*wick+0.4*body);
   } else {
      h0=ApexSoft(wick-0.9*stretch);
      h1=ApexSoft(body-1.3*drift);
      h2=ApexSoft(1.2*wick-0.5*body);
      h3=ApexSoft(stretch-0.6*body+0.3*wick);
   }
}

double ApexPredict(int s,int horizon)
{
   if(s<1 || s+64+horizon+12>=N || ATR14[s]<=0) return 0;
   double cross[4]={0,0,0,0},energy[4]={0,0,0,0},h[4];
   double weight=ApexRate;
   for(int j=0;j<64;j++) {
      int label=s+j,features=label+horizon;
      if(ATR14[features]<=0) return 0;
      double target=ApexBound((C[label]-C[features])/(ATR14[features]*MathSqrt((double)horizon)));
      ApexHidden(features,horizon,h[0],h[1],h[2],h[3]);
      for(int k=0;k<4;k++) {
         cross[k]+=weight*h[k]*target;
         energy[k]+=weight*h[k]*h[k];
      }
      weight*=1.0-ApexRate;
   }
   ApexHidden(s,horizon,h[0],h[1],h[2],h[3]);
   double score=0;
   for(int k=0;k<4;k++) score+=h[k]*cross[k]/(0.035+energy[k]);
   return ApexBound(score*0.25);
}

double apexTrend=0,apexTurn=0;
int ApexState(int model,int s,double trend,double turn)
{
   if(model==STRAT_NEURAL_TREND)
      return trend>=ApexGate && EMAf[s]>EMAs[s] ? 1 : trend<=-ApexGate && EMAf[s]<EMAs[s] ? -1 : 0;
   if(model==STRAT_NEURAL_TURN)
      return turn>=ApexGate && C[s]<C[s+3] ? 1 : turn<=-ApexGate && C[s]>C[s+3] ? -1 : 0;
   return MathMin(trend,turn)>=ApexGate ? 1 : MathMax(trend,turn)<=-ApexGate ? -1 : 0;
}

int ApexNeuralFlip(int model,int s)
{
   int state=ApexState(model,s,s==1 ? apexTrend : ApexPredict(s,3),s==1 ? apexTurn : ApexPredict(s,1));
   if(state==0) return 0;
   int previous=ApexState(model,s+1,ApexPredict(s+1,3),ApexPredict(s+1,1));
   return state!=previous ? state : 0;
}

// Closed M15 Heikin Ashi SAR. Use the last completed M15 candle at the
// signal bar's open, matching Pine's [1] higher-timeframe request.
int ApexHaSar(int s)
{
   if(PeriodSeconds(PERIOD_CURRENT)>900) return 0;
   int shift=iBarShift(_Symbol,PERIOD_M15,T[s],false);
   if(shift<0) return 0;
   MqlRates rates[];
   int n=CopyRates(_Symbol,PERIOD_M15,shift+1,160,rates);
   if(n<40) return 0;
   double hao=0,hac=0,h1=0,h2=0,l1=0,l2=0,extreme=0,sar=0,af=0.02;
   int side=0;
   for(int i=0;i<n;i++) {
      double oldclose=hac;
      hao=i==0 ? (rates[i].open+rates[i].close)*0.5 : (hao+hac)*0.5;
      hac=(rates[i].open+rates[i].high+rates[i].low+rates[i].close)*0.25;
      double hi=MathMax(rates[i].high,MathMax(hao,hac)),lo=MathMin(rates[i].low,MathMin(hao,hac));
      if(i==1) { side=hac>=oldclose ? 1 : -1; sar=side>0 ? l1 : h1; extreme=side>0 ? hi : lo; }
      if(i>=2) {
         sar+=af*(extreme-sar);
         if((side>0 && lo<sar) || (side<0 && hi>sar)) {
            sar=side>0 ? MathMax(hi,extreme) : MathMin(lo,extreme);
            side=-side; extreme=side>0 ? hi : lo; af=0.02;
         } else if((side>0 && hi>extreme) || (side<0 && lo<extreme)) {
            extreme=side>0 ? hi : lo; af=MathMin(0.20,af+0.02);
         }
         sar=side>0 ? MathMin(sar,MathMin(l1,l2)) : MathMax(sar,MathMax(h1,h2));
      }
      h2=h1; h1=hi; l2=l1; l1=lo;
   }
   return hac>sar ? 1 : hac<sar ? -1 : 0;
}

bool ApexCashOpen(datetime eventTime)
{
   MqlDateTime local; TimeToStruct(DroidEastern(eventTime),local);
   int minute=local.hour*60+local.min;
   return local.day_of_week>=1 && local.day_of_week<=5 && minute>=570 && minute<600;
}

int ApexAddedSignal(int model,int s)
{
   if(model<=STRAT_NEURAL_AGREE) return ApexNeuralFlip(model,s);
   if(model==STRAT_HA_SAR) {
      if(!ApexCashOpen(T[s]) || !ApexCashOpen(T[s]+PeriodSeconds(PERIOD_CURRENT)-1)) return 0;
      int state=ApexHaSar(s);
      return !ApexCashOpen(T[s+1]) || state!=ApexHaSar(s+1) ? state : 0;
   }
   if(model==STRAT_FRACTAL_EMA) {
      if(IsPivotHigh(s+2,2) && EMAf[s]>EMAs[s] && EMAs[s]>EMAt[s]) return 1;
      if(IsPivotLow(s+2,2) && EMAf[s]<EMAs[s] && EMAs[s]<EMAt[s]) return -1;
      return 0;
   }
   int flip=UTd[s]!=UTd[s+1] ? UTd[s] : 0;
   if(model==STRAT_BIONICK_ELITE)
      return flip>0 && C[s]>EMAs[s] && ADX[s]>=20 && RSI[s]>52 ? 1 :
             flip<0 && C[s]<EMAs[s] && ADX[s]>=20 && RSI[s]<48 ? -1 : 0;
   if(model==STRAT_BIONICK_BB)
      return C[s]>BBl[s] && C[s+1]<=BBl[s+1] && RSI[s]<45 ? 1 :
             C[s]<BBu[s] && C[s+1]>=BBu[s+1] && RSI[s]>55 ? -1 : 0;
   return 0;
}

int StrategySignal(int st,int s)
  {
   if(s<1 || s+40>=N) return 0;
   if(st>=STRAT_ZONE) { int pick=PrideSelection(st,s); return pick>0 ? 1 : pick<0 ? -1 : 0; }
   if(st==STRAT_PRIDE) { int route=(s==1 ? prideClosedRoute : PrideChartRoute(s)); return route>0 ? 1 : route<0 ? -1 : 0; }
   if(st>=STRAT_NEURAL_TREND) return ApexAddedSignal(st,s);
   int dir=0;
   switch(st)
     {
      case STRAT_UT_EMA200:
         if(FlipTo(UTd,s,1) && C[s]>EMAt[s]) dir=1;
         if(FlipTo(UTd,s,-1) && C[s]<EMAt[s]) dir=-1;
         break;
      case STRAT_UT_HTF_EMA_ADX:
         if(FlipTo(UTd,s,1) && HTFb[s]==1 && ADX[s]>InpADXMin) dir=1;
         if(FlipTo(UTd,s,-1) && HTFb[s]==-1 && ADX[s]>InpADXMin) dir=-1;
         break;
      case STRAT_UT_MA_VS_TRAIL:
        {
         bool lc=(MAut[s]>UTt[s] && C[s]>UTt[s]), lp=(MAut[s+1]>UTt[s+1] && C[s+1]>UTt[s+1]);
         bool sc=(MAut[s]<UTt[s] && C[s]<UTt[s]), sp=(MAut[s+1]<UTt[s+1] && C[s+1]<UTt[s+1]);
         if(lc && !lp) dir=1;
         if(sc && !sp) dir=-1;
         break;
        }
      case STRAT_UT_CLASSIC:
         if(FlipTo(UTd,s,1)) dir=1;
         if(FlipTo(UTd,s,-1)) dir=-1;
         break;
      case STRAT_UT_DUAL_ENGINE:
         if(FlipTo(DUd,s,1)) dir=1;
         if(FlipTo(DUd,s,-1)) dir=-1;
         break;
      case STRAT_UT_SNIPER:
         dir=SniperSignal(s);
         break;
      case STRAT_SYNAPSE:
         if(FlipTo(SYNd,s,1) && C[s]-SYNl[s+1]>=InpSynMinBreakATR*ATRsyn[s]) dir=1;
         if(FlipTo(SYNd,s,-1) && SYNl[s+1]-C[s]>=InpSynMinBreakATR*ATRsyn[s]) dir=-1;
         break;
      case STRAT_MTF_TRAIL:
        {
         if(MT2d[s]==0 || MT3d[s]==0 || MT4d[s]==0) break;
         bool al=(UTd[s]==1 && MT2d[s]==1 && MT3d[s]==1 && MT4d[s]==1);
         bool alp=(UTd[s+1]==1 && MT2d[s+1]==1 && MT3d[s+1]==1 && MT4d[s+1]==1);
         bool as=(UTd[s]==-1 && MT2d[s]==-1 && MT3d[s]==-1 && MT4d[s]==-1);
         bool asp=(UTd[s+1]==-1 && MT2d[s+1]==-1 && MT3d[s+1]==-1 && MT4d[s+1]==-1);
         if(al && !alp) dir=1;
         if(as && !asp) dir=-1;
         break;
        }
      case STRAT_BB_TREND_SCALP:
        {
         bool sideways=(ATRavg[s]>0 && ATR14[s]<0.85*ATRavg[s]);
         if(sideways) break;
         if(BBm[s]>BBm[s+3] && C[s]>EMAs[s] && C[s]>BBm[s] && C[s+1]<=BBm[s+1]) dir=1;
         if(BBm[s]<BBm[s+3] && C[s]<EMAs[s] && C[s]<BBm[s] && C[s+1]>=BBm[s+1]) dir=-1;
         break;
        }
      case STRAT_KALMAN_ST:
         if(FlipTo(KSTd,s,1)) dir=1;
         if(FlipTo(KSTd,s,-1)) dir=-1;
         break;
      case STRAT_KALMAN_VWMA_REV:
         if(ZoneRevUp(s) && !ZoneRevUp(s+1) && (!InpRevNeedTrend || KSTd[s]==1)) dir=1;
         if(ZoneRevDown(s) && !ZoneRevDown(s+1) && (!InpRevNeedTrend || KSTd[s]==-1)) dir=-1;
         break;
      case STRAT_CONFLUENCE:
        {
         int thr=(InpMinConfluence>0) ? InpMinConfluence : 70;
         int l0=ConfluenceAt(s,1), l1=ConfluenceAt(s+1,1), s0=ConfluenceAt(s,-1), s1=ConfluenceAt(s+1,-1);
         if(l0>=thr && l1<thr && l0>s0) dir=1;
         if(s0>=thr && s1<thr && s0>l0) dir=-1;
         break;
        }
      case STRAT_REGIME:
        {
         int r=RegimeAt(s);
         if(r==1 || r==-1)
           {
            int a=StrategySignal(STRAT_KALMAN_ST,s); if(a==0) a=StrategySignal(STRAT_UT_EMA200,s);
            if(a==r) dir=a;
           }
         else if(r==0) dir=StrategySignal(STRAT_KALMAN_VWMA_REV,s);
         break;
        }
      case STRAT_EMA_PULLBACK:
        {
         double rmin=RSI[s], rmax=RSI[s];
         for(int k=s;k<s+5;k++) { rmin=MathMin(rmin,RSI[k]); rmax=MathMax(rmax,RSI[k]); }
         if(EMAf[s]>EMAs[s] && C[s]>EMAt[s] && L[s]<=EMAf[s] && C[s]>EMAf[s] && C[s]>O[s] && rmin<50 && RSI[s]>RSI[s+1]) dir=1;
         if(EMAf[s]<EMAs[s] && C[s]<EMAt[s] && H[s]>=EMAf[s] && C[s]<EMAf[s] && C[s]<O[s] && rmax>50 && RSI[s]<RSI[s+1]) dir=-1;
         break;
        }
      case STRAT_VECTOR: return VectorChartSetup(s);
      case STRAT_GOLD_STRICT: return VectorGoldFlip(s);
      case STRAT_PANDICH: return VectorAsymSide[s+1]!=0 && VectorAsymSide[s]!=VectorAsymSide[s+1] ? VectorAsymSide[s] : 0;
      case STRAT_EXPRESS: return VectorNightFlip(s);
      case STRAT_SQUEEZE:
        {
         if(InSqueeze(s) || !InSqueeze(s+1)) break;
         int cnt=0; for(int k=s+1;k<s+8;k++) if(InSqueeze(k)) cnt++;
         if(cnt<4) break;
         if(C[s]>BBm[s] && MACDh[s]>0) dir=1;
         if(C[s]<BBm[s] && MACDh[s]<0) dir=-1;
         break;
        }
     }
   return dir;
  }

// Strategy-specific exits for an open position in direction dir (evaluated on closed bar 1).
bool StrategyExit(int st,int dir,string &why)
  {
   int s=1;
   if(s+5>=N) return false;
   if(st==STRAT_EXPRESS && !DroidWindow(TimeCurrent(),true)) { why="Overnight window ended"; return true; }
   if(st==STRAT_MTF_TRAIL && InpMTFExit)
     {
      int dis=0;
      if(UTd[s]==-dir) dis++; if(MT2d[s]==-dir) dis++; if(MT3d[s]==-dir) dis++; if(MT4d[s]==-dir) dis++;
      if(dis>=2) { why="MTF consensus: 2+ timeframes disagree"; return true; }
     }
   if(st==STRAT_BB_TREND_SCALP)
     {
      if(dir>0 && BBl[s]>BBl[s+1] && BBl[s+1]<=BBl[s+2] && C[s]>BBm[s]) { why="BB scalper: lower band stopped expanding"; return true; }
      if(dir<0 && BBu[s]<BBu[s+1] && BBu[s+1]>=BBu[s+2] && C[s]<BBm[s]) { why="BB scalper: upper band stopped expanding"; return true; }
      if(ATRavg[s]>0 && ATR14[s]<0.85*ATRavg[s]) { why="BB scalper: sideways market"; return true; }
     }
   return false;
  }

//================================ SMART FILTERS ================================
bool NewsPause(string &why)
  {
   if(StringLen(InpNewsTimes)<4) return false;
   string parts[];
   int n=StringSplit(InpNewsTimes,';',parts);
   datetime now=TimeCurrent();
   MqlDateTime d; TimeToStruct(now,d);
   for(int i=0;i<n;i++)
     {
      string p=parts[i]; StringTrimLeft(p); StringTrimRight(p);
      if(StringLen(p)<4) continue;
      datetime ev;
      if(StringLen(p)<=5)
        {
         string hm[]; if(StringSplit(p,':',hm)!=2) continue;
         ev=StringToTime(StringFormat("%04d.%02d.%02d %s",d.year,d.mon,d.day,p));
        }
      else ev=StringToTime(p);
      if(ev<=0) continue;
      if(now>=ev-InpNewsBefore*60 && now<=ev+InpNewsAfter*60) { why="News pause around "+p; return true; }
     }
   return false;
  }

bool SessionBlocked(string &why)
  {
   MqlDateTime d; TimeToStruct(TimeCurrent(),d);
   if((d.day_of_week==0 || d.day_of_week==6) && !((g_strategy==STRAT_EXPRESS || g_strategy==STRAT_VECTOR || g_strategy==STRAT_PRIDE || g_strategy==STRAT_COMBINED) && DroidWindow(TimeCurrent(),true))) { why="Weekend"; return true; }
   if(d.day_of_week==5 && InpFridayCutoff<24 && d.hour>=InpFridayCutoff) { why="Friday cutoff"; return true; }
   if(InpUseSession)
     {
      bool inside=(InpSessionStart<=InpSessionEnd) ? (d.hour>=InpSessionStart && d.hour<InpSessionEnd)
                                                  : (d.hour>=InpSessionStart || d.hour<InpSessionEnd);
      if(!inside) { why="Outside session hours"; return true; }
     }
   return false;
  }

bool SpreadBlocked(string &why)
  {
   double sp=SpreadPts();
   if(InpMaxSpreadPoints>0 && sp>InpMaxSpreadPoints) { why="Spread "+DoubleToString(sp,0)+" pts above cap"; return true; }
   if(InpMaxSpreadATR>0 && N>2 && ATR14[1]>0 && sp*g_point>InpMaxSpreadATR*ATR14[1]) { why="Spread too wide vs ATR"; return true; }
   return false;
  }

int StreakAt(int s,int dir)
  {
   int k=0;
   for(int i=s;i<N-1 && i<s+30;i++) { if(dir*(C[i]-O[i])>0) k++; else break; }
   return k;
  }

int CountDir(int dir) { int k=0; for(int i=0;i<g_npos;i++) if(g_pos[i].dir==dir) k++; return k; }

bool EntryAllowed(int dir,bool manual,string &why)
  {
   why="";
   if(g_killLock) { why="Kill switch locked (press RESET LOCK)"; return false; }
   if(g_dayLock)  { why="Day locked: "+g_dayLockWhy; return false; }
   if(g_portfolioExit) { why="Portfolio exit in progress"; return false; }
#ifdef __MQL5__
   if(IsNetting()) {
      if(PositionSelect(_Symbol)) { why="Netting symbol already has a position"; return false; }
      for(int j=OrdersTotal()-1;j>=0;j--) {
         if(OrderGetTicket(j)>0 && OrderGetString(ORDER_SYMBOL)==_Symbol) { why="Working order on netting symbol"; return false; }
      }
   }
#endif
   if(g_mode==MODE_SIGNALS) { why="Signals-only mode"; return false; }
   if(PrideWeekend(g_strategy,TimeCurrent())) { why="Weekend risk limit (New York)"; return false; }
   if(manual) return true;
   if(g_strategy>=STRAT_ZONE && PrideMaxSpreadATR>0) {
      MqlTick q;
      if(N<100 || ATR14[1]<=0 || !SymbolInfoTick(_Symbol,q) || q.bid<=0 || q.ask<q.bid ||
         q.ask-q.bid>ATR14[1]*PrideMaxSpreadATR) { why="Quote or spread / ATR limit"; return false; }
   }
   if(g_strategy>=STRAT_PRIDE && PrideMaxDelaySeconds>0 && N>1 &&
      TimeCurrent()>T[1]+PeriodSeconds(PERIOD_CURRENT)+PrideMaxDelaySeconds) { why="Signal expired"; return false; }
   if(g_paused) { why="Paused"; return false; }
   if(g_mode!=MODE_AUTO) { why="Mode "+ModeName(g_mode)+": no automatic entries"; return false; }
   if(InpDirection==DIR_LONG && dir<0) { why="Long-only setting"; return false; }
   if(InpDirection==DIR_SHORT && dir>0) { why="Short-only setting"; return false; }
   if(g_npos>=InpMaxPositions) { why="Max positions reached"; return false; }
   if(g_strategy==STRAT_EXPRESS && !DroidWindow(TimeCurrent(),true)) { why="Outside overnight window"; return false; }
   if(SessionBlocked(why)) return false;
   if(NewsPause(why)) return false;
   if(SpreadBlocked(why)) return false;
   int s=1;
   if(InpUseEMAFilter && dir*(C[s]-EMAt[s])<=0) { why="200 EMA filter"; return false; }
   if(InpUseADXFilter && ADX[s]<InpADXMin) { why="ADX below "+DoubleToString(InpADXMin,0); return false; }
   if(InpUseHTFFilter && HTFb[s]!=dir) { why="Higher-timeframe bias disagrees"; return false; }
   if(InpUseSpikeGuard && ATRavg[s]>0 && ATR14[s]>InpSpikeRatio*ATRavg[s]) { why="ATR spike guard"; return false; }
   if(InpUseRegimeFilter && g_strategy!=STRAT_REGIME && g_strategy!=STRAT_VECTOR && g_strategy<STRAT_PRIDE)
     {
      int r=RegimeAt(s);
      if(r==2) { why="Volatility spike regime"; return false; }
      if(!IsReversionStrategy(g_strategy) && r==0) { why="Choppy regime (trend strategy)"; return false; }
     }
   if(InpMaxStreak>0 && StreakAt(s,dir)>=InpMaxStreak) { why="Anti-FOMO candle streak"; return false; }
   if(InpMinConfluence>0 && g_strategy!=STRAT_CONFLUENCE && ConfluenceAt(s,dir)<InpMinConfluence) { why="Confluence below minimum"; return false; }
   return true;
  }

//================================ RISK AND LOTS ================================
double DrawdownPct() { double eq=Equity(); return (g_peakEquity>0) ? 100.0*(g_peakEquity-eq)/g_peakEquity : 0; }

double CalcLots(int dir,double slDist,bool manual)
  {
   if(manual) return NormalizeLots(g_manualLot);
   if(InpLotMode==LOT_FIXED || slDist<=0) return NormalizeLots(InpFixedLot);
   double tv=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE), ts=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   if(ts<=0) ts=g_point;
   if(tv<=0 && SymbolInfoString(_Symbol,SYMBOL_CURRENCY_PROFIT)==AccountInfoString(ACCOUNT_CURRENCY))
      tv=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE)*ts;      // fallback when the feed reports no tick value
   if(tv<=0 || ts<=0) return 0;
   double riskMoney=Equity()*InpRiskPercent/100.0;
   if(InpLotMode==LOT_ADAPTIVE)
     {
      double sc=ConfluenceAt(1,dir);
      double scale=MathMax(0.5,MathMin(1.0,0.5+0.5*sc/100.0));
      if(InpMaxDDPct>0) scale*=1.0-0.5*MathMin(1.0,DrawdownPct()/InpMaxDDPct);
      riskMoney*=scale;                  // never above the user's risk percent
     }
   double lossPerLot=slDist/ts*tv;
   if(lossPerLot<=0 || riskMoney<=0) return 0;
   double lots=NormalizeLots(riskMoney/lossPerLot);
   return lots*lossPerLot<=riskMoney+1e-8 ? lots : 0;
  }

void OpenTrade(int dir,bool manual,string reason)
  {
   string why;
   if(!EntryAllowed(dir,manual,why)) { if(manual) Note("Entry blocked: "+why); g_blockReason=why; return; }
   double atr=(N>2) ? ATR14[1] : 0;
   if(atr<=0) { Note("ATR not ready"); return; }
   MqlTick quote;
   double tick=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   if(tick<=0 || !SymbolInfoTick(_Symbol,quote) || quote.bid<=0 || quote.ask<quote.bid) return;
   if(!manual && g_strategy>=STRAT_ZONE && PrideMaxSpreadATR>0 && quote.ask-quote.bid>atr*PrideMaxSpreadATR) {
      Note("Entry quote spread widened"); return;
   }
   double px=dir>0 ? quote.ask : quote.bid;
   double slDist=MathMax(InpSL_ATR*atr,quote.ask-quote.bid+StopDist());
   double sl=(InpSL_ATR>0) ? px-dir*slDist : 0;
   double tp=(InpTP_RR>0 && InpSL_ATR>0) ? px+dir*slDist*InpTP_RR : 0;
   sl=NormP(tick*(dir>0 ? MathFloor(sl/tick+1e-9) : MathCeil(sl/tick-1e-9)));
   slDist=dir*(px-sl);
   if(tp>0) tp=NormP(tick*(dir>0 ? MathCeil(tp/tick-1e-9) : MathFloor(tp/tick+1e-9)));
   double lots=CalcLots(dir,slDist,manual);
   if(lots<=0) { Note("Risk budget below tradable volume or quote unavailable"); return; }
   if(TradeOpen(dir,lots,sl,tp))
     {
      Note((dir>0 ? "BUY " : "SELL ")+DoubleToString(lots,2)+" | "+reason);
      LoadPositions();
     }
  }

int CloseWhere(int which,string reason)   // which: 0 all, 1 profitable, -1 losing, 2 buys, -2 sells
  {
   LoadPositions();
   int closed=0;
   for(int i=g_npos-1;i>=0;i--)
     {
      bool take=(which==0) || (which==1 && g_pos[i].profit>0) || (which==-1 && g_pos[i].profit<0)
                || (which==2 && g_pos[i].dir>0) || (which==-2 && g_pos[i].dir<0);
      if(take && TradeClose(g_pos[i].ticket,0)) closed++;
     }
   if(closed>0) Note("Closed "+IntegerToString(closed)+" | "+reason);
   LoadPositions();
   return closed;
  }

uint g_exitStarted=0;
void StartPortfolioExit(string reason)
  {
   g_portfolioExit=true; g_exitStarted=GetTickCount();
   CloseWhere(0,reason);
   if(g_npos==0) g_portfolioExit=false;
  }

void ServicePortfolioExit()
  {
   if(!g_portfolioExit) return;
   if(g_npos>0) CloseWhere(0,"Portfolio exit retry");
   if(g_npos==0 || GetTickCount()-g_exitStarted>60000) { g_portfolioExit=false; if(g_npos>0) Note("Portfolio exit timed out; lock cleared, positions remain"); }
  }

//================================ POSITIVE TRAILING STOP ================================
string PridePositionID(int i)
{
#ifdef __MQL5__
   if(PositionSelectByTicket((ulong)g_pos[i].ticket))
      return IntegerToString(PositionGetInteger(POSITION_IDENTIFIER));
#endif
   return IntegerToString(g_pos[i].ticket);
}
double RiskOf(int i)
{
   string key="r"+PridePositionID(i);
   double saved=GVGet(key,0);
   if(saved>0) return saved;
   double risk=g_pos[i].dir*(g_pos[i].open-g_pos[i].sl);
   if(g_pos[i].sl<=0 || risk<=0) {
      if(g_trail>=TRAIL_PRIDE) return 0; // No trustworthy initial risk after a missing record.
      risk=InpSL_ATR*ATR14[1];
   }
   if(risk>0) { GVPut(key,risk); GlobalVariablesFlush(); }
   return risk;
}

double RecentSwing(int dir)
  {
   for(int k=InpPivotBars+1;k<MathMin(N-InpPivotBars-1,80);k++)
     {
      if(dir>0 && IsPivotLow(k,InpPivotBars)) return L[k]-0.1*ATR14[1];
      if(dir<0 && IsPivotHigh(k,InpPivotBars)) return H[k]+0.1*ATR14[1];
     }
   return 0;
  }

// Returns the raw lock level for a mode (0 = no level). Validation happens in the caller.
double TrailLevel(int mode,int dir,double open,double R,double px,double pd)
  {
   double atr=ATR14[1], buf=InpLockBufferATR*atr+SpreadPts()*g_point;
   switch(mode)
     {
      case TRAIL_UT_ATR:     return (UTd[1]==dir) ? UTt[1] : 0;
      case TRAIL_MTF_ATR:
        {
         double v[4]={0,0,0,0}; int n=0;
         if(UTd[1]==dir) v[n++]=UTt[1];
         if(MT2d[1]==dir && MT2l[1]>0) v[n++]=MT2l[1];
         if(MT3d[1]==dir && MT3l[1]>0) v[n++]=MT3l[1];
         if(MT4d[1]==dir && MT4l[1]>0) v[n++]=MT4l[1];
         if(n<2) return 0;
         // second-tightest line: the level at least two timeframes agree on
         for(int a=0;a<n-1;a++) for(int b=a+1;b<n;b++) if(dir*(v[b]-v[a])>0) { double t=v[a]; v[a]=v[b]; v[b]=t; }
         return v[1];
        }
      case TRAIL_KALMAN_ST:  return (KSTd[1]==dir) ? KSTl[1] : 0;
      case TRAIL_STEP_LOCK:
        {
         double step=MathMax(0.1,InpStepR)*R;
         int k=(int)MathFloor(pd/step);
         if(k<1) return 0;
         return open+dir*MathMax(buf,(k-1)*step);
        }
      case TRAIL_BREAKEVEN_PLUS: return open+dir*buf;
      case TRAIL_CHANDELIER:
         return (dir>0) ? Highest(H,1,InpChandelierBars)-InpChandelierMult*atr : Lowest(L,1,InpChandelierBars)+InpChandelierMult*atr;
      case TRAIL_SWING:      return RecentSwing(dir);
      case TRAIL_VOL_ADAPTIVE:
        {
         double reg=(atr>0 && ATRavg[1]>0) ? MathMax(0.6,MathMin(1.4,ATRavg[1]/atr)) : 1.0;
         double m=InpTrailATRMult*reg/(1.0+0.25*MathMax(0,pd/R));
         return px-dir*m*atr;
        }
      case TRAIL_PERCENT:    return px*(1.0-dir*InpPercentTrail/100.0);
      case TRAIL_SYNAPSE:    return (SYNd[1]==dir) ? SYNl[1] : 0;
     }
   return 0;
  }

void ManageTrailing()
  {
   if(g_trail==TRAIL_OFF || N<50) return;
   double atr=ATR14[1]; if(atr<=0) return;
   double minStep=MathMax(2*g_point,0.02*atr), sd=StopDist();
   for(int i=0;i<g_npos;i++)
     {
      int dir=g_pos[i].dir; double open=g_pos[i].open, sl=g_pos[i].sl;
      double px=(dir>0) ? PxBid() : PxAsk();
      double pd=dir*(px-open), R=RiskOf(i);
      if(R<=0) continue;
      if(g_trail>=TRAIL_VECTOR_ULTRA) {
         double tick=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
         string peakKey="p"+PridePositionID(i);
         double bestPx=GVGet(peakKey,open);
         if(dir*(px-bestPx)>0) { bestPx=px; GVPut(peakKey,px); }
         double costs=VectorCostTicks*tick+MathMax(0.0,SpreadPts()*g_point);
         double level;
         if(g_trail==TRAIL_CVT_LT_DRIOD) {
            double structure=dir>0 ? Lowest(L,1,3) : Highest(H,1,3);
            level=CVTLTDriodSmartStop(dir,open,sl,px,bestPx,R,atr,prideClosedEff,ADX[1],structure,
                                         costs,sd,tick,VectorArmR,VectorStepTicks);
         } else if(g_trail>=TRAIL_PRIDE)
            level=PrideStagedStop(dir,open,sl,px,bestPx,R,atr,prideClosedEff,costs,sd,tick,VectorArmR,VectorStepTicks,g_trail==TRAIL_PEAK ? PrideRetreat : 0.0,PrideKeep);
         else if(g_trail!=TRAIL_VECTOR_ULTRA) {
            double structure=dir>0 ? Lowest(L,1,3) : Highest(H,1,3);
            level=ApexProfitLock(dir,open,sl,px,bestPx,R,atr,costs,sd,tick,VectorArmR,VectorStepTicks,ApexRetain,
                                 (apexTrend+apexTurn)*0.5,structure,g_trail==TRAIL_STRUCTURE_FLOOR);
         } else level=VectorPositiveStop(dir,open,sl,px,bestPx,R,atr,ADX[1],costs,sd,tick,VectorArmR,VectorStepTicks);
         if(level>0 && TradeModify(g_pos[i].ticket,level,g_pos[i].tp)) g_pos[i].sl=level;
         continue;
      }
      if(pd<InpTrailStartR*R) continue;
      double buf=InpLockBufferATR*atr+SpreadPts()*g_point;
      double best=0;
      if(g_trail==TRAIL_SMART_HYBRID)
        {
         int modes[6]={TRAIL_UT_ATR,TRAIL_KALMAN_ST,TRAIL_CHANDELIER,TRAIL_SWING,TRAIL_STEP_LOCK,TRAIL_BREAKEVEN_PLUS};
         for(int m=0;m<6;m++)
           {
            double v=TrailLevel(modes[m],dir,open,R,px,pd);
            if(v<=0) continue;
            if(dir*(v-(open+dir*buf))<0) continue;        // profit lock only
            if(dir*((px-dir*sd)-v)<0) continue;            // must respect broker distance
            if(best==0 || dir*(v-best)>0) best=v;
           }
        }
      else
        {
         double v=TrailLevel(g_trail,dir,open,R,px,pd);
         if(v>0 && dir*(v-(open+dir*buf))>=0 && dir*((px-dir*sd)-v)>=0) best=v;
        }
      if(best<=0) continue;
      best=NormP(best);
      bool improves=(sl<=0) || (dir*(best-sl)>=minStep);     // never loosen
      if(!improves) continue;
      if(TradeModify(g_pos[i].ticket,best,g_pos[i].tp))
        {
         g_pos[i].sl=best;
         Note("Profit lock "+DoubleToString(best,g_digits)+" ("+TrailName(g_trail)+")");
        }
     }
  }

void ManagePartials()
  {
   if(InpTP1_RR<=0 || InpTP1_Percent<=0 || InpTP1_Percent>=100) return;
   double step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP), vmin=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   if(step<=0 || vmin<=0) return;
   bool changed=false;
   for(int i=0;i<g_npos;i++) {
      int side=g_pos[i].dir;
      double entry=g_pos[i].open, old=g_pos[i].sl;
      string origin=IntegerToString(g_pos[i].opened)+"|"+IntegerToString(side)+"|"+DoubleToString(entry,g_digits);
#ifdef __MQL5__
      if(!PositionSelectByTicket((ulong)g_pos[i].ticket)) continue;
      origin=IntegerToString(PositionGetInteger(POSITION_IDENTIFIER));
#endif
      string marker="partial"+IntegerToString(SymbolHash(origin));
      if(GVGet(marker,0)>0) continue;
      double risk=RiskOf(i),market=side>0 ? PxBid() : PxAsk();
      if(risk<=0 || side*(market-entry)<InpTP1_RR*risk) continue;
      double part=NormalizeDouble(MathFloor(g_pos[i].lots*InpTP1_Percent/100.0/step+1e-9)*step,8);
      if(part<vmin || g_pos[i].lots-part<vmin-1e-9) continue;
      double tick=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
      if(tick<=0) continue;
      double raw=entry+side*(MathMax(InpLockBufferATR*ATR14[1],(VectorCostTicks+1)*tick)+SpreadPts()*g_point);
      double be=NormP(tick*(side>0 ? MathCeil(raw/tick-1e-9) : MathFloor(raw/tick+1e-9)));
      if((old<=0 || side*(be-old)>tick*0.5) && g_trail!=TRAIL_OFF && !TradeModify(g_pos[i].ticket,be,g_pos[i].tp)) continue;
      // Reserve once before transmission. An ambiguous close must not reduce the remainder again.
      GVPut(marker,1); GlobalVariablesFlush();
      if(TradeClose(g_pos[i].ticket,part)) Note("Partial take profit "+DoubleToString(part,2)+" lots");
      else Note("Partial close unconfirmed; inspect account history before further reductions");
      changed=true;
   }
   if(changed) LoadPositions();
  }

//================================ EQUITY PROTECTION ================================
void ManageEquity()
  {
   double eq=Equity();
   int dk=DayKey(TimeCurrent());
   if(dk!=g_dayKey)
     {
      g_dayKey=dk; g_dayStartEquity=eq; g_dayLock=false; g_dayLockWhy="";
      GVPut("dayKey",dk); GVPut("dayEq",eq); GVPut("dayLock",0);
     }
   if(eq>g_peakEquity) { g_peakEquity=eq; GVPut("peak",eq); }
   if(InpMaxDDPct>0 && !g_killLock && DrawdownPct()>=InpMaxDDPct)
     {
      g_killLock=true; GVPut("kill",1);
      Note("Max drawdown kill switch: closing all and locking");
     }
   if(g_killLock && g_npos>0) StartPortfolioExit("Kill switch");      // kill switches always close
   if(g_dayStartEquity>0 && !g_dayLock)
     {
      double dpct=100.0*(eq-g_dayStartEquity)/g_dayStartEquity;
      if(InpDailyLossPct>0 && -dpct>=InpDailyLossPct) { g_dayLock=true; g_dayLockWhy="daily loss limit"; GVPut("dayLock",1); StartPortfolioExit("Daily loss limit"); }
      else if(InpDailyTargetPct>0 && dpct>=InpDailyTargetPct) { g_dayLock=true; g_dayLockWhy="daily profit target"; GVPut("dayLock",1); StartPortfolioExit("Daily profit target"); }
      else if(InpMaxConsecLosses>0 && g_consecLosses>=InpMaxConsecLosses) { g_dayLock=true; g_dayLockWhy="consecutive losses"; GVPut("dayLock",1); }
     }
  }

//================================ BAR PROCESSING ================================
void OnNewBar()
  {
   g_ready=LoadSeries();
   if(!g_ready) { g_lastSignalText="Waiting for history"; return; }
   LoadHistoryStats();
   g_regimeCode=RegimeAt(1); g_regime=RegimeName(g_regimeCode);
   apexTrend=ApexPredict(1,3); apexTurn=ApexPredict(1,1);
   prideClosedRoute=PrideChartRoute(1); prideClosedEff=PrideEfficiency(C,1,PridePathBars);
   g_scoreLong=ConfluenceAt(1,1); g_scoreShort=ConfluenceAt(1,-1);
   LoadPositions();
   // strategy exits and opposite-signal exits are management: never blocked by pause or filters
   for(int i=g_npos-1;i>=0;i--)
     {
      string why;
      bool timeLimit=(g_strategy==STRAT_HA_SAR && TimeCurrent()-g_pos[i].opened>=3*3600);
      if(timeLimit) why="Opening session holding limit";
      if(g_mode!=MODE_SIGNALS && (timeLimit || StrategyExit(g_strategy,g_pos[i].dir,why))) { if(TradeClose(g_pos[i].ticket,0)) Note(why); }
     }
   LoadPositions();
   int sig=PrideWeekend(g_strategy,TimeCurrent()) ? 0 : StrategySignal(g_strategy,1);
   if(g_strategy>=STRAT_PRIDE && PrideMaxDelaySeconds>0 && TimeCurrent()>T[1]+PeriodSeconds(PERIOD_CURRENT)+PrideMaxDelaySeconds) sig=0;
   if(sig!=0 && (datetime)GVGet("lastSignalBar",0)==T[1]) sig=0;
   if(sig!=0)
     {
      GVPut("lastSignalBar",(double)T[1]);
      g_lastSignal=sig; g_lastSignalTime=T[1];
      g_lastSignalText=(sig>0 ? "BUY  " : "SELL ")+TimeToString(T[1],TIME_DATE|TIME_MINUTES);
      if(g_mode!=MODE_SIGNALS && InpCloseOnOpposite) CloseWhere(sig>0 ? -2 : 2,"Opposite signal");
      if(!g_isTester && InpAlerts) Alert(CT_NAME," ",_Symbol," ",(sig>0 ? "BUY" : "SELL")," | ",StrategyName(g_strategy));
      if(!g_isTester && InpPush) SendNotification(CT_NAME+" "+_Symbol+" "+(sig>0 ? "BUY" : "SELL")+" | "+StrategyShort(g_strategy));
      if(g_mode==MODE_AUTO) OpenTrade(sig,false,StrategyShort(g_strategy));
     }
   string w;
   if(!EntryAllowed(1,false,w) && !EntryAllowed(-1,false,w)) g_blockReason=w; else g_blockReason="";
  }

//================================ CUTE ROBOT MASCOT (bitmap) ================================
bool InCircle(double x,double y,double cx,double cy,double r) { double dx=x-cx, dy=y-cy; return (dx*dx+dy*dy<=r*r); }
bool InRRect(double x,double y,double x0,double y0,double x1,double y1,double r)
  {
   double cx=(x0+x1)/2.0, cy=(y0+y1)/2.0, hw=(x1-x0)/2.0, hh=(y1-y0)/2.0;
   if(r>hw) r=hw;
   if(r>hh) r=hh;
   double dx=MathMax(MathAbs(x-cx)-(hw-r),0), dy=MathMax(MathAbs(y-cy)-(hh-r),0);
   return (dx*dx+dy*dy<=r*r);
  }
bool InCapsule(double x,double y,double ax,double ay,double bx,double by,double r)
  {
   double vx=bx-ax, vy=by-ay, l2=vx*vx+vy*vy;
   double t=(l2>0) ? ((x-ax)*vx+(y-ay)*vy)/l2 : 0;
   if(t<0) t=0;
   if(t>1) t=1;
   double px=ax+t*vx-x, py=ay+t*vy-y;
   return (px*px+py*py<=r*r);
  }

// Silhouette of the robot in a 100 x 100 design space, grown by e (used for the outline).
bool RobotSilhouette(double x,double y,double e,bool wave)
  {
   if(InCapsule(x,y,36,20,27,8,2.4+e) || InCapsule(x,y,64,20,73,8,2.4+e)) return true;
   if(InCircle(x,y,26,7,4.8+e) || InCircle(x,y,74,7,4.8+e)) return true;
   if(InRRect(x,y,16-e,14-e,84+e,56+e,19+e)) return true;
   if(InRRect(x,y,43-e,54-e,57+e,60+e,2+e)) return true;
   if(InRRect(x,y,29-e,58-e,71+e,87+e,11+e)) return true;
   if(wave) { if(InCapsule(x,y,27,64,13,50,5.5+e)) return true; }
   else     { if(InCapsule(x,y,27,64,18,79,5.5+e)) return true; }
   if(InCapsule(x,y,73,64,82,79,5.5+e)) return true;
   if(InCapsule(x,y,41,86,41,95,5.2+e) || InCapsule(x,y,59,86,59,95,5.2+e)) return true;
   return false;
  }

// Returns ARGB for one sample point (alpha 0 = transparent).
uint RobotSample(double x,double y,color body,color detail,color face,color outline,bool wave)
  {
   color c=clrNONE; bool hit=false;
   if(RobotSilhouette(x,y,1.9,wave)) { c=outline; hit=true; }
   if(RobotSilhouette(x,y,0,wave))
     {
      c=body; hit=true;
      if(InCircle(x,y,26,7,4.8) || InCircle(x,y,74,7,4.8)) c=detail;
      if(InCircle(x,y,24.5,5.5,1.6) || InCircle(x,y,72.5,5.5,1.6)) c=clrWhite;
      if(InRRect(x,y,43,54,57,60,2)) c=MixC(body,clrBlack,0.30);
      if(InCapsule(x,y,41,86,41,95,5.2) || InCapsule(x,y,59,86,59,95,5.2)) c=MixC(body,clrBlack,0.18);
      if(InRRect(x,y,23,21,77,50,13)) c=face;                                   // face screen
      if(InCircle(x,y,38,34,7.6) || InCircle(x,y,62,34,7.6)) c=MixC(detail,clrWhite,0.55); // eye glow
      if(InCircle(x,y,38,34,6.2) || InCircle(x,y,62,34,6.2)) c=clrWhite;        // eyes
      if(InCircle(x,y,39,35.5,3.6) || InCircle(x,y,63,35.5,3.6)) c=MixC(face,clrBlack,0.4); // pupils
      if(InCircle(x,y,37.3,32.6,1.5) || InCircle(x,y,61.3,32.6,1.5)) c=clrWhite; // sparkle
      if(InCircle(x,y,29.5,43.5,3.4) || InCircle(x,y,70.5,43.5,3.4)) c=HexC(0xFF8FB1); // blush cheeks
      double dx=x-50, dy=y-39.5, d2=dx*dx+dy*dy;
      if(d2>=6.2*6.2 && d2<=8.6*8.6 && y>41.5) c=MixC(detail,clrWhite,0.35);     // smile
      if(InRRect(x,y,35,64,65,81,6)) c=MixC(body,clrWhite,0.22);                 // chest plate
      if(InCircle(x,y,50,72.5,5.6)) c=detail;                                    // power core
      if(InCircle(x,y,50,72.5,2.6)) c=clrWhite;
      if(InCircle(x,y,40,70,1.6) || InCircle(x,y,60,70,1.6)) c=detail;           // chest lights
     }
   if(!hit) return 0;
   return ColorToARGB(c,255);
  }

void BuildRobotResource(string res,int size,color body,color detail,color face,bool wave)
  {
   uint px[];
   ArrayResize(px,size*size);
   color outline=MixC(body,clrBlack,0.55);
   double sc=100.0/size;
   for(int py=0;py<size;py++)
      for(int pxl=0;pxl<size;pxl++)
        {
         double sa=0,sr=0,sg=0,sb=0;
         for(int sy=0;sy<4;sy++)
            for(int sx=0;sx<4;sx++)
              {
               uint v=RobotSample((pxl+(sx+0.5)/4.0)*sc,(py+(sy+0.5)/4.0)*sc,body,detail,face,outline,wave);
               double a=(double)((v>>24)&255);
               if(a<=0) continue;
               sa+=a; sr+=a*((v>>16)&255); sg+=a*((v>>8)&255); sb+=a*(v&255);
              }
         uint outp=0;
         if(sa>0)
           {
            uint A=(uint)MathRound(sa/16.0), R=(uint)MathRound(sr/sa), G=(uint)MathRound(sg/sa), B=(uint)MathRound(sb/sa);
            outp=(A<<24)|(R<<16)|(G<<8)|B;
           }
         px[py*size+pxl]=outp;
        }
   ResourceCreate(res,px,size,size,0,0,size,COLOR_FORMAT_ARGB_NORMALIZE);
  }

string g_resSmall="::Pride_robot_small", g_resBig="::Pride_robot_big", g_resTiny="::Pride_robot_tiny";
int    g_robotBuiltTheme=-1, g_robotBuiltSmall=0, g_robotBuiltBig=0;

void BuildRobots(int smallSize,int bigSize)
  {
   if(g_robotBuiltTheme==g_theme && g_robotBuiltSmall==smallSize && g_robotBuiltBig==bigSize) return;
   color face=TC.light ? MixC(TC.text,clrBlack,0.35) : MixC(TC.bg,clrBlack,0.45);
   BuildRobotResource(g_resSmall,smallSize,TC.acc,TC.acc2,face,false);
   BuildRobotResource(g_resBig,bigSize,TC.acc,TC.acc2,face,true);
   BuildRobotResource(g_resTiny,(int)MathMax(16,MathRound(smallSize*28.0/48.0)),TC.acc,TC.acc2,face,false);
   g_robotBuiltTheme=g_theme; g_robotBuiltSmall=smallSize; g_robotBuiltBig=bigSize;
  }

//================================ DASHBOARD FRAMEWORK ================================
#define P_MAIN  0
#define P_IND   1
#define P_CTRL  2
#define P_ROBOT 3
int    g_px[CT_PANELS], g_py[CT_PANELS], g_pw[CT_PANELS], g_ph[CT_PANELS], g_hdr[CT_PANELS], g_hdrBtnZone[CT_PANELS];
bool   g_pcol[CT_PANELS];
bool   g_pshow[CT_PANELS];
double g_scale=1.0;
bool   g_minimized=false, g_lines=true;
int    g_drag=-1, g_dragOffX=0, g_dragOffY=0;
uint   g_lastUI=0;
int    g_tickCount=0;

int  Sc(double v) { return (int)MathRound(v*g_scale); }
int  TinySize() { return (int)MathMax(16,MathRound(28*g_scale)); }
int  FSz(double v) { return (int)MathMax(6,MathRound(v*g_scale)); }
string PN(int p,string n) { return CT_PFX+"U"+IntegerToString(p)+"_"+n; }

void ObjBase(string n)
  {
   ObjectSetInteger(0,n,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSetInteger(0,n,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,n,OBJPROP_SELECTED,false);
   ObjectSetInteger(0,n,OBJPROP_HIDDEN,true);
   ObjectSetInteger(0,n,OBJPROP_BACK,false);
  }

void URect(string n,int x,int y,int w,int h,color bg,color bd)
  {
   if(ObjectFind(0,n)<0) { ObjectCreate(0,n,OBJ_RECTANGLE_LABEL,0,0,0); ObjBase(n); ObjectSetInteger(0,n,OBJPROP_BORDER_TYPE,BORDER_FLAT); }
   ObjectSetInteger(0,n,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,n,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,n,OBJPROP_XSIZE,MathMax(1,w)); ObjectSetInteger(0,n,OBJPROP_YSIZE,MathMax(1,h));
   ObjectSetInteger(0,n,OBJPROP_BGCOLOR,bg); ObjectSetInteger(0,n,OBJPROP_COLOR,bd);
   ObjectSetInteger(0,n,OBJPROP_ZORDER,10);
  }

void UText(string n,int x,int y,string t,color c,int fs,bool bold,int anchor,string tip)
  {
   if(ObjectFind(0,n)<0) { ObjectCreate(0,n,OBJ_LABEL,0,0,0); ObjBase(n); }
   ObjectSetInteger(0,n,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,n,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,n,OBJPROP_ANCHOR,anchor);
   ObjectSetString(0,n,OBJPROP_TEXT,t); ObjectSetString(0,n,OBJPROP_FONT,bold ? "Segoe UI Semibold" : "Segoe UI");
   ObjectSetInteger(0,n,OBJPROP_FONTSIZE,fs); ObjectSetInteger(0,n,OBJPROP_COLOR,c);
   ObjectSetString(0,n,OBJPROP_TOOLTIP,(tip=="") ? t : tip);
   ObjectSetInteger(0,n,OBJPROP_ZORDER,11);
  }
void UTxt(string n,int x,int y,string t,color c,int fs) { UText(n,x,y,t,c,fs,false,ANCHOR_LEFT_UPPER,""); }

void UBtn(string n,int x,int y,int w,int h,string t,color bg,color fg,int fs,string tip)
  {
   if(ObjectFind(0,n)<0) { ObjectCreate(0,n,OBJ_BUTTON,0,0,0); ObjBase(n); }
   ObjectSetInteger(0,n,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,n,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,n,OBJPROP_XSIZE,w); ObjectSetInteger(0,n,OBJPROP_YSIZE,h);
   ObjectSetString(0,n,OBJPROP_TEXT,t); ObjectSetString(0,n,OBJPROP_FONT,"Segoe UI Semibold");
   ObjectSetInteger(0,n,OBJPROP_FONTSIZE,fs);
   ObjectSetInteger(0,n,OBJPROP_COLOR,fg); ObjectSetInteger(0,n,OBJPROP_BGCOLOR,bg);
   ObjectSetInteger(0,n,OBJPROP_BORDER_COLOR,MixC(bg,TC.acc,0.45));
   ObjectSetInteger(0,n,OBJPROP_STATE,false);
   ObjectSetString(0,n,OBJPROP_TOOLTIP,(tip=="") ? t : tip);
   ObjectSetInteger(0,n,OBJPROP_ZORDER,20);
  }

void UBmp(string n,int x,int y,string res)
  {
   if(ObjectFind(0,n)<0) { ObjectCreate(0,n,OBJ_BITMAP_LABEL,0,0,0); ObjBase(n); }
   ObjectSetInteger(0,n,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,n,OBJPROP_YDISTANCE,y);
   ObjectSetString(0,n,OBJPROP_BMPFILE,0,res);
   ObjectSetInteger(0,n,OBJPROP_ZORDER,12);
  }

void UChip(int p,string key,int x,int y,int w,int h,string t,color c,int fs)
  {
   URect(PN(p,key+"_bg"),x,y,w,h,MixC(TC.bg,c,0.28),MixC(TC.bg,c,0.75));
   UText(PN(p,key+"_tx"),x+w/2,y+h/2,t,TC.light ? MixC(c,clrBlack,0.35) : MixC(c,clrWhite,0.25),fs,true,ANCHOR_CENTER,"");
  }

int ChartW() { return (int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS); }
int ChartH() { return (int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS); }

void SavePanel(int p)
  {
   GVPut("px"+IntegerToString(p),g_px[p]); GVPut("py"+IntegerToString(p),g_py[p]);
   GVPut("pc"+IntegerToString(p),g_pcol[p] ? 1 : 0);
  }

void ClearPanel(int p) { ObjectsDeleteAll(0,CT_PFX+"U"+IntegerToString(p)+"_"); }

void PanelFrame(int p,string title,bool withRobot)
  {
   int x=g_px[p], y=g_py[p], w=g_pw[p], hh=g_hdr[p];
   int h=g_pcol[p] ? hh : g_ph[p];
   URect(PN(p,"shadow"),x+Sc(3),y+Sc(3),w,h,MixC(TC.chartBg,clrBlack,0.5),MixC(TC.chartBg,clrBlack,0.5));
   URect(PN(p,"frame"),x,y,w,h,TC.bg,TC.border);
   URect(PN(p,"hdr"),x+1,y+1,w-2,hh-1,TC.hdr,TC.hdr);
   URect(PN(p,"hdrline"),x+1,y+hh-Sc(2),w-2,Sc(2),TC.acc,TC.acc);
   int tx=x+Sc(10), ts=TinySize();
   if(withRobot) { UBmp(PN(p,"robot"),x+Sc(5),y+(hh-ts)/2,g_resTiny); tx=x+Sc(5)+ts+Sc(8); }
   UText(PN(p,"title"),tx,y+hh/2,title,TC.text,FSz(9),true,ANCHOR_LEFT,"Drag this header to move the panel");
   int bw=Sc(20), bh=Sc(18), by=y+(hh-bh)/2;
   UBtn(PN(p,"b_col"),x+w-Sc(6)-bw,by,bw,bh,g_pcol[p] ? "v" : "^",TC.btn,TC.btnTxt,FSz(8),g_pcol[p] ? "Expand panel" : "Collapse panel");
   UBtn(PN(p,"b_min"),x+w-Sc(8)-2*bw,by,bw,bh,"_",TC.btn,TC.btnTxt,FSz(8),"Minimise all dashboards");
  }

void RowKV(int p,int idx,int x,int y,int w,string k,string v,color vc,string tip)
  {
   UTxt(PN(p,"k"+IntegerToString(idx)),x+Sc(10),y,k,TC.muted,FSz(8));
   UText(PN(p,"v"+IntegerToString(idx)),x+w-Sc(10),y,v,vc,FSz(8),true,ANCHOR_RIGHT_UPPER,tip);
  }

void WrapName(string s,int maxc,string &a,string &b)
  {
   if(StringLen(s)<=maxc) { a=s; b=""; return; }
   int cut=maxc;
   for(int i=maxc;i>maxc/2;i--) if(StringGetCharacter(s,i)==' ') { cut=i; break; }
   a=StringSubstr(s,0,cut); b=StringSubstr(s,cut+1);
   if(StringLen(b)>maxc) b=StringSubstr(b,0,maxc-2)+"..";
  }

color DirColor(int d) { return (d>0) ? TC.up : ((d<0) ? TC.dn : TC.muted); }
string DirWord(int d) { return (d>0) ? "LONG" : ((d<0) ? "SHORT" : "N/A"); }

string TFName(ENUM_TIMEFRAMES tf)
  {
   if(tf==PERIOD_CURRENT) tf=(ENUM_TIMEFRAMES)Period();
   string s=EnumToString(tf);
   StringReplace(s,"PERIOD_","");
   return s;
  }

//================================ MAIN PANEL ================================
void DrawMain()
  {
   int p=P_MAIN;
   g_pw[p]=Sc(340); g_hdr[p]=Sc(58);
   int x=g_px[p], y=g_py[p], w=g_pw[p], hh=g_hdr[p];
   int rh=Sc(17), rows=18;
   g_ph[p]=hh+Sc(8)+Sc(24)+Sc(8)+Sc(48)+rows*rh+Sc(10);
   g_hdrBtnZone[p]=Sc(100);
   int h=g_pcol[p] ? hh : g_ph[p];
   URect(PN(p,"shadow"),x+Sc(3),y+Sc(3),w,h,MixC(TC.chartBg,clrBlack,0.5),MixC(TC.chartBg,clrBlack,0.5));
   URect(PN(p,"frame"),x,y,w,h,TC.bg,TC.border);
   URect(PN(p,"hdr"),x+1,y+1,w-2,hh-1,TC.hdr,TC.hdr);
   URect(PN(p,"hdrline"),x+1,y+hh-Sc(2),w-2,Sc(2),TC.acc,TC.acc);
   int rs=Sc(48);
   UBmp(PN(p,"robot"),x+Sc(6),y+(hh-rs)/2,g_resSmall);
   UText(PN(p,"title"),x+Sc(60),y+Sc(3),"CVT LT DRIOD BOT NO ERRORS",TC.text,FSz(11),true,ANCHOR_LEFT_UPPER,"Drag the header to move the dashboard");
   UText(PN(p,"subtitle"),x+Sc(60),y+Sc(18),"EXPERT ADVISOR",TC.text,FSz(8),true,ANCHOR_LEFT_UPPER,CT_NAME);
   UText(PN(p,"lic"),x+Sc(60),y+Sc(31),CT_LICENSE,TC.acc,FSz(7),true,ANCHOR_LEFT_UPPER,"");
   UText(PN(p,"sym"),x+Sc(60),y+Sc(44),_Symbol+"  "+TFName(PERIOD_CURRENT)+"  |  "+AssetClass()+"  |  #"+IntegerToString(InpMagic),TC.muted,FSz(7),false,ANCHOR_LEFT_UPPER,"");
   int bw=Sc(20), bh=Sc(18), by=y+Sc(6);
   UBtn(PN(p,"b_col"),x+w-Sc(6)-bw,by,bw,bh,g_pcol[p] ? "v" : "^",TC.btn,TC.btnTxt,FSz(8),g_pcol[p] ? "Expand panel" : "Collapse panel");
   UBtn(PN(p,"b_min"),x+w-Sc(8)-2*bw,by,bw,bh,"_",TC.btn,TC.btnTxt,FSz(8),"Minimise all dashboards");
   UBtn(PN(p,"b_ap"),x+w-Sc(10)-3*bw,by,bw,bh,"+",TC.btn,TC.btnTxt,FSz(8),"Larger dashboard");
   UBtn(PN(p,"b_am"),x+w-Sc(12)-4*bw,by,bw,bh,"-",TC.btn,TC.btnTxt,FSz(8),"Smaller dashboard");
   if(g_pcol[p]) return;

   int cy=y+hh+Sc(8);
   string st; color sc;
   if(g_killLock)          { st="KILL SWITCH LOCKED - press RESET LOCK"; sc=TC.dn; }
   else if(g_dayLock)      { st="DAY LOCKED - "+g_dayLockWhy; sc=TC.warn; }
   else if(g_paused)       { st="PAUSED - management still active"; sc=TC.warn; }
   else if(g_portfolioExit){ st="CLOSING ALL POSITIONS"; sc=TC.warn; }
   else if(g_mode==MODE_AUTO) { st="AUTO TRADING ACTIVE"; sc=TC.up; }
   else if(g_mode==MODE_SEMI) { st="SEMI-AUTO: MANUAL ENTRIES"; sc=TC.acc; }
   else                    { st="SIGNALS ONLY - NO AUTO ENTRIES"; sc=TC.acc2; }
   UChip(p,"status",x+Sc(10),cy,w-Sc(20),Sc(24),st,sc,FSz(9));
   cy+=Sc(24)+Sc(8);

   string a,b; WrapName(StrategyName(g_strategy),40,a,b);
   UTxt(PN(p,"stk"),x+Sc(10),cy,"STRATEGY",TC.muted,FSz(7));
   UText(PN(p,"st1"),x+Sc(10),cy+Sc(12),a,TC.acc,FSz(9),true,ANCHOR_LEFT_UPPER,StrategyName(g_strategy));
   UText(PN(p,"st2"),x+Sc(10),cy+Sc(28),(b=="") ? " " : b,TC.acc,FSz(9),true,ANCHOR_LEFT_UPPER,StrategyName(g_strategy));
   cy+=Sc(48);

   double eq=Equity(), bal=Balance();
   double floating=0, lots=0; for(int i=0;i<g_npos;i++) { floating+=g_pos[i].profit; lots+=g_pos[i].lots; }
   double day=(g_dayStartEquity>0) ? eq-g_dayStartEquity : 0;
   double dayPct=(g_dayStartEquity>0) ? 100.0*day/g_dayStartEquity : 0;
   double atr=(g_ready && N>2) ? ATR14[1] : 0;
   int nd=(g_lastSignal!=0) ? g_lastSignal : 1;
   double nextLot=(atr>0) ? CalcLots(nd,MathMax(InpSL_ATR*atr,StopDist()*1.5),false) : NormalizeLots(InpFixedLot);
   string why=""; string sess="Open"; if(SessionBlocked(why)) sess=why; if(NewsPause(why)) sess=why;
   double winp=(g_closedTrades>0) ? 100.0*g_closedWins/g_closedTrades : 0;
   int i0=0;
   RowKV(p,i0++,x,cy,w,"Trailing stop",TrailName(g_trail),TC.text,"Positive-only lock: never loosens");               cy+=rh;
   RowKV(p,i0++,x,cy,w,"Mode | Theme",ModeName(g_mode)+" | "+ThemeName(g_theme),TC.text,"");                             cy+=rh;
   RowKV(p,i0++,x,cy,w,"Market regime",g_regime+(g_ready ? "  ADX "+DoubleToString(ADX[1],0)+"  CHOP "+DoubleToString(CHOP[1],0) : ""),
         (g_regimeCode==1) ? TC.up : ((g_regimeCode==-1) ? TC.dn : ((g_regimeCode==2) ? TC.warn : TC.text)),"");      cy+=rh;
   RowKV(p,i0++,x,cy,w,"Last signal",g_lastSignalText,DirColor(g_lastSignal),"");                                         cy+=rh;
   // confluence bars
   UTxt(PN(p,"k_conf"),x+Sc(10),cy,"Confluence",TC.muted,FSz(8));
   int bx=x+Sc(110), bwid=w-Sc(110)-Sc(64), bhgt=Sc(5);
   URect(PN(p,"cl_bg"),bx,cy+Sc(2),bwid,bhgt,TC.bg2,TC.bg2);
   URect(PN(p,"cl_fg"),bx,cy+Sc(2),MathMax(1,bwid*g_scoreLong/100),bhgt,TC.up,TC.up);
   URect(PN(p,"cs_bg"),bx,cy+Sc(9),bwid,bhgt,TC.bg2,TC.bg2);
   URect(PN(p,"cs_fg"),bx,cy+Sc(9),MathMax(1,bwid*g_scoreShort/100),bhgt,TC.dn,TC.dn);
   UText(PN(p,"v_conf"),x+w-Sc(10),cy,"L"+IntegerToString(g_scoreLong)+" S"+IntegerToString(g_scoreShort),TC.text,FSz(8),true,ANCHOR_RIGHT_UPPER,"Multi-indicator confluence score 0-100");
   cy+=rh;
   RowKV(p,i0++,x,cy,w,"Entry gate",(g_blockReason=="") ? "Clear - waiting for signal" : Fit(g_blockReason,34),(g_blockReason=="") ? TC.up : TC.warn,g_blockReason); cy+=rh;
   RowKV(p,i0++,x,cy,w,"Neural trend / turn",DoubleToString(apexTrend,2)+"  /  "+DoubleToString(apexTurn,2),TC.acc,"Signed forecasts from closed bars"); cy+=rh;
   RowKV(p,i0++,x,cy,w,"Protective stop",g_npos>0 && g_pos[0].sl>0 ? DoubleToString(g_pos[0].sl,g_digits) : "-",TC.warn,"Broker stop on the first owned chart position"); cy+=rh;
   RowKV(p,i0++,x,cy,w,"Balance",DoubleToString(bal,2)+" "+AccountInfoString(ACCOUNT_CURRENCY),TC.text,"");              cy+=rh;
   RowKV(p,i0++,x,cy,w,"Equity",DoubleToString(eq,2),TC.text,"");                                                         cy+=rh;
   RowKV(p,i0++,x,cy,w,"Today P/L",Money(day)+"  ("+DoubleToString(dayPct,2)+"%)",(day>=0) ? TC.up : TC.dn,"");         cy+=rh;
   RowKV(p,i0++,x,cy,w,"Drawdown",DoubleToString(DrawdownPct(),2)+"%  /  kill at "+DoubleToString(InpMaxDDPct,1)+"%",(DrawdownPct()>InpMaxDDPct*0.6) ? TC.warn : TC.text,""); cy+=rh;
   RowKV(p,i0++,x,cy,w,"Open positions",IntegerToString(g_npos)+"  |  "+DoubleToString(lots,2)+" lots  |  "+Money(floating),(floating>=0) ? TC.up : TC.dn,""); cy+=rh;
   RowKV(p,i0++,x,cy,w,"Spread | ATR",DoubleToString(SpreadPts(),0)+" pts  |  "+DoubleToString(atr/g_point,0)+" pts",TC.text,""); cy+=rh;
   RowKV(p,i0++,x,cy,w,"Next lot",DoubleToString(nextLot,2)+"  ("+LotModeName(InpLotMode)+")",TC.text,"");              cy+=rh;
   RowKV(p,i0++,x,cy,w,"Closed trades",IntegerToString(g_closedTrades)+"  |  win "+DoubleToString(winp,0)+"%  |  "+Money(g_closedNet),(g_closedNet>=0) ? TC.up : TC.dn,""); cy+=rh;
   RowKV(p,i0++,x,cy,w,"Session | News",sess,(sess=="Open") ? TC.up : TC.warn,"");                                        cy+=rh;
   RowKV(p,i0++,x,cy,w,"Last action",Fit(g_lastAction,40),TC.muted,g_lastAction);                                          cy+=rh;
  }

//================================ INDICATOR PANEL ================================
void IndRow(int p,int idx,int x,int y,int w,string name,string val,string chip,color cc)
  {
   UTxt(PN(p,"n"+IntegerToString(idx)),x+Sc(10),y+Sc(1),name,TC.muted,FSz(8));
   UText(PN(p,"v"+IntegerToString(idx)),x+Sc(200),y+Sc(1),val,TC.text,FSz(8),true,ANCHOR_RIGHT_UPPER,"");
   UChip(p,"c"+IntegerToString(idx),x+w-Sc(10)-Sc(118),y,Sc(118),Sc(15),chip,cc,FSz(7));
  }

void DrawIndicators()
  {
   int p=P_IND;
   g_pw[p]=Sc(340); g_hdr[p]=Sc(30); g_hdrBtnZone[p]=Sc(54);
   int rh=Sc(18), rows=17;
   g_ph[p]=g_hdr[p]+Sc(8)+rows*rh+Sc(8);
   PanelFrame(p,"MULTI-INDICATOR MATRIX",true);
   if(g_pcol[p]) return;
   int x=g_px[p], y=g_py[p]+g_hdr[p]+Sc(8), w=g_pw[p], k=0, s=1;
   if(!g_ready || N<5)
     {
      UTxt(PN(p,"matrix_wait"),x+Sc(10),y+Sc(8),"WAITING FOR MARKET HISTORY",TC.warn,FSz(8));
      UTxt(PN(p,"matrix_hint"),x+Sc(10),y+Sc(25),"Connect to the symbol and wait for data sync",TC.muted,FSz(7));
      return;
     }
   int dg=g_digits;
   int rt=g_strategy>=STRAT_ZONE ? PrideSelection(g_strategy,1) : prideClosedRoute;
   IndRow(p,k++,x,y,w,"Signal route / ER",DoubleToString(prideClosedEff,2),PrideRouteName(rt),rt==0 ? TC.muted : DirColor(rt>0 ? 1 : -1)); y+=rh;
   double pB=(BBu[s]-BBl[s]>0) ? (C[s]-BBl[s])/(BBu[s]-BBl[s]) : 0.5;
   IndRow(p,k++,x,y,w,"200 EMA trend",DoubleToString(EMAt[s],dg),(C[s]>EMAt[s]) ? "PRICE ABOVE" : "PRICE BELOW",(C[s]>EMAt[s]) ? TC.up : TC.dn); y+=rh;
   IndRow(p,k++,x,y,w,"EMA 21 / 50",(EMAf[s]>EMAs[s]) ? "fast > slow" : "fast < slow",(EMAf[s]>EMAs[s]) ? "BULLISH" : "BEARISH",(EMAf[s]>EMAs[s]) ? TC.up : TC.dn); y+=rh;
   IndRow(p,k++,x,y,w,"ADX / DI",DoubleToString(ADX[s],1)+"  "+DoubleToString(PDI[s],0)+"/"+DoubleToString(MDI[s],0),(ADX[s]>=InpADXMin) ? ((PDI[s]>MDI[s]) ? "STRONG UP" : "STRONG DOWN") : "WEAK TREND",(ADX[s]>=InpADXMin) ? DirColor(PDI[s]>MDI[s] ? 1 : -1) : TC.muted); y+=rh;
   IndRow(p,k++,x,y,w,"RSI",DoubleToString(RSI[s],1),(RSI[s]>70) ? "OVERBOUGHT" : ((RSI[s]<30) ? "OVERSOLD" : ((RSI[s]>50) ? "BULLISH" : "BEARISH")),(RSI[s]>70 || RSI[s]<30) ? TC.warn : DirColor(RSI[s]>50 ? 1 : -1)); y+=rh;
   IndRow(p,k++,x,y,w,"MACD histogram",DoubleToString(MACDh[s]/g_point,1)+" pts",(MACDh[s]>0) ? "BULLISH" : "BEARISH",DirColor(MACDh[s]>0 ? 1 : -1)); y+=rh;
   IndRow(p,k++,x,y,w,"Bollinger %B",DoubleToString(pB,2),InSqueeze(s) ? "SQUEEZE" : ((pB>1) ? "ABOVE UPPER" : ((pB<0) ? "BELOW LOWER" : "INSIDE")),InSqueeze(s) ? TC.warn : TC.acc); y+=rh;
   IndRow(p,k++,x,y,w,"UT Bot ATR trail",DoubleToString(UTt[s],dg),DirWord(UTd[s]),DirColor(UTd[s])); y+=rh;
   IndRow(p,k++,x,y,w,"UT dual engine",DoubleToString(DUt[s],dg),DirWord(DUd[s]),DirColor(DUd[s])); y+=rh;
   IndRow(p,k++,x,y,w,"Kalman Supertrend",DoubleToString(KSTl[s],dg),DirWord(KSTd[s]),DirColor(KSTd[s])); y+=rh;
   IndRow(p,k++,x,y,w,"Synapse band",DoubleToString(SYNl[s],dg),DirWord(SYNd[s]),DirColor(SYNd[s])); y+=rh;
   IndRow(p,k++,x,y,w,"VWMA zone",DoubleToString(VW[s],dg),(C[s]>=ZU[s]) ? "UPPER ZONE" : ((C[s]<=ZL[s]) ? "LOWER ZONE" : "MID ZONE"),(C[s]>=ZU[s]) ? TC.dn : ((C[s]<=ZL[s]) ? TC.up : TC.muted)); y+=rh;
   IndRow(p,k++,x,y,w,"HTF 200 EMA ("+TFName(InpHTF)+")",(HTFb[s]==0) ? "no data" : "bias",(HTFb[s]>0) ? "BULLISH" : ((HTFb[s]<0) ? "BEARISH" : "N/A"),DirColor(HTFb[s])); y+=rh;
   // MTF votes as four mini chips
   UTxt(PN(p,"n_mtf"),x+Sc(10),y+Sc(1),"MTF ATR trail votes",TC.muted,FSz(8));
   int cw=Sc(29), cx=x+w-Sc(10)-4*cw-3*Sc(2);
   UChip(p,"m0",cx,y,cw,Sc(15),TFName(PERIOD_CURRENT),DirColor(UTd[s]),FSz(6));
   UChip(p,"m1",cx+(cw+Sc(2)),y,cw,Sc(15),TFName(InpMTF2),DirColor(MT2d[s]),FSz(6));
   UChip(p,"m2",cx+2*(cw+Sc(2)),y,cw,Sc(15),TFName(InpMTF3),DirColor(MT3d[s]),FSz(6));
   UChip(p,"m3",cx+3*(cw+Sc(2)),y,cw,Sc(15),TFName(InpMTF4),DirColor(MT4d[s]),FSz(6));
   y+=rh;
   IndRow(p,k++,x,y,w,"Choppiness",DoubleToString(CHOP[s],1),(CHOP[s]>=61.8) ? "CHOPPY" : ((CHOP[s]<38.2) ? "STRONG TREND" : "NEUTRAL"),(CHOP[s]>=61.8) ? TC.warn : TC.acc); y+=rh;
   IndRow(p,k++,x,y,w,"R-squared trend fit",DoubleToString(R2[s],2),(R2[s]>=0.6) ? "CLEAN TREND" : "NOISY",(R2[s]>=0.6) ? TC.up : TC.muted); y+=rh;
   double ratio=(ATRavg[s]>0) ? ATR14[s]/ATRavg[s] : 1;
   IndRow(p,k++,x,y,w,"ATR volatility","x"+DoubleToString(ratio,2),(ratio>InpSpikeRatio) ? "SPIKE GUARD" : ((ratio<0.85) ? "QUIET" : "NORMAL"),(ratio>InpSpikeRatio) ? TC.dn : TC.acc); y+=rh;
  }

//================================ CONTROL PANEL ================================
void DrawControls()
  {
   int p=P_CTRL;
   g_pw[p]=Sc(340); g_hdr[p]=Sc(30); g_hdrBtnZone[p]=Sc(54);
   int bh=Sc(24), gap=Sc(5), rows=8;
   g_ph[p]=g_hdr[p]+Sc(8)+rows*(bh+gap)+Sc(6);
   PanelFrame(p,"SMART CONTROLS",true);
   if(g_pcol[p]) return;
   int x=g_px[p]+Sc(8), y=g_py[p]+g_hdr[p]+Sc(8), w=g_pw[p]-Sc(16);
   int bw=(w-2*gap)/3, fs=FSz(8);
   color bb=TC.btn, bt=TC.btnTxt;
   int c0=x, c1=x+bw+gap, c2=x+2*(bw+gap);
   UBtn(PN(p,"b_buy"),c0,y,bw,bh,"BUY "+DoubleToString(g_manualLot,2),MixC(TC.bg,TC.up,0.55),TC.light ? clrWhite : clrBlack,fs,"Market buy with the manual lot");
   UBtn(PN(p,"b_sell"),c1,y,bw,bh,"SELL "+DoubleToString(g_manualLot,2),MixC(TC.bg,TC.dn,0.60),clrWhite,fs,"Market sell with the manual lot");
   UBtn(PN(p,"b_closeall"),c2,y,bw,bh,g_closeAllArmed ? "CONFIRM CLOSE?" : "CLOSE ALL",g_closeAllArmed ? TC.warn : MixC(TC.bg,TC.dn,0.35),g_closeAllArmed ? clrBlack : bt,fs,"Click twice within 5 seconds to close every position");
   y+=bh+gap;
   UBtn(PN(p,"b_cprof"),c0,y,bw,bh,"CLOSE PROFIT",bb,bt,fs,"Close only profitable positions");
   UBtn(PN(p,"b_closs"),c1,y,bw,bh,"CLOSE LOSS",bb,bt,fs,"Close only losing positions");
   UBtn(PN(p,"b_be"),c2,y,bw,bh,"BREAKEVEN+",bb,bt,fs,"Lock breakeven plus buffer on profitable positions");
   y+=bh+gap;
   UBtn(PN(p,"b_pause"),c0,y,bw,bh,g_paused ? "RESUME" : "PAUSE",g_paused ? TC.warn : bb,g_paused ? clrBlack : bt,fs,"Pause or resume new entries (saved)");
   UBtn(PN(p,"b_mode"),c1,y,bw,bh,"MODE: "+((g_mode==MODE_AUTO) ? "AUTO" : ((g_mode==MODE_SEMI) ? "SEMI" : "SIGNAL")),bb,bt,fs,"Cycle trading mode");
   UBtn(PN(p,"b_reset"),c2,y,bw,bh,"RESET LOCK",(g_killLock || g_dayLock) ? TC.warn : bb,(g_killLock || g_dayLock) ? clrBlack : bt,fs,"Reset kill switch / day lock and equity peak");
   y+=bh+gap;
   int sw=Sc(30), mw=w-2*sw-2*gap;
   UBtn(PN(p,"b_sprev"),x,y,sw,bh,"<",bb,bt,fs,"Previous strategy");
   UChip(p,"strat",x+sw+gap,y,mw,bh,Fit(StrategyShort(g_strategy),34),TC.acc,FSz(8));
   UBtn(PN(p,"b_snext"),x+sw+2*gap+mw,y,sw,bh,">",bb,bt,fs,"Next strategy");
   y+=bh+gap;
   UBtn(PN(p,"b_tprev"),x,y,sw,bh,"<",bb,bt,fs,"Previous trailing stop mode");
   UChip(p,"trail",x+sw+gap,y,mw,bh,"TRAIL: "+Fit(TrailName(g_trail),30),TC.acc2,FSz(8));
   UBtn(PN(p,"b_tnext"),x+sw+2*gap+mw,y,sw,bh,">",bb,bt,fs,"Next trailing stop mode");
   y+=bh+gap;
   UBtn(PN(p,"b_thprev"),x,y,sw,bh,"<",bb,bt,fs,"Previous colour theme");
   UChip(p,"theme",x+sw+gap,y,mw,bh,"THEME: "+ThemeName(g_theme)+"  ("+IntegerToString(g_theme+1)+"/"+IntegerToString(CT_THEME_COUNT)+")",TC.acc,FSz(8));
   UBtn(PN(p,"b_thnext"),x+sw+2*gap+mw,y,sw,bh,">",bb,bt,fs,"Next colour theme");
   y+=bh+gap;
   UBtn(PN(p,"b_lotm"),c0,y,bw,bh,"LOT -",bb,bt,fs,"Decrease manual lot");
   UChip(p,"lot",c1,y,bw,bh,"LOT "+DoubleToString(g_manualLot,2),TC.text,FSz(8));
   UBtn(PN(p,"b_lotp"),c2,y,bw,bh,"LOT +",bb,bt,fs,"Increase manual lot");
   y+=bh+gap;
   UBtn(PN(p,"b_lines"),c0,y,bw,bh,g_lines ? "LINES: ON" : "LINES: OFF",bb,bt,fs,"Show or hide indicator lines and arrows on the chart");
   UBtn(PN(p,"b_sizem"),c1,y,bw,bh,"SIZE -",bb,bt,fs,"Shrink all dashboards");
   UBtn(PN(p,"b_sizep"),c2,y,bw,bh,"SIZE +",bb,bt,fs,"Enlarge all dashboards");
  }

//================================ CHART ROBOT PANEL ================================
string RobotMood()
  {
   if(g_killLock) return "Safety lock engaged";
   if(g_paused) return "Taking a break (paused)";
   for(int i=0;i<g_npos;i++) if(g_pos[i].sl>0 && g_pos[i].dir*(g_pos[i].sl-g_pos[i].open)>0) return "Profit locked - trailing";
   if(g_npos>0) return "Managing "+IntegerToString(g_npos)+" position(s)";
   if(g_lastSignal>0 && g_lastSignalTime>0) return "Last call: BUY";
   if(g_lastSignal<0 && g_lastSignalTime>0) return "Last call: SELL";
   return "Scanning the market...";
  }

void DrawRobotPanel()
  {
   int p=P_ROBOT, rs=Sc(116);
   g_pw[p]=MathMax(rs,Sc(150)); g_ph[p]=rs+Sc(36); g_hdr[p]=g_ph[p]; g_hdrBtnZone[p]=0;
   int x=g_px[p], y=g_py[p];
   UBmp(PN(p,"robot"),x+(g_pw[p]-rs)/2,y,g_resBig);
   UText(PN(p,"cap"),x+g_pw[p]/2,y+rs+Sc(4),"CVT LT DRIOD BOT NO ERRORS",TC.acc,FSz(9),true,ANCHOR_UPPER,"Drag the robot to move it");
   UText(PN(p,"mood"),x+g_pw[p]/2,y+rs+Sc(20),RobotMood(),TC.chartFg,FSz(7),false,ANCHOR_UPPER,"");
  }

void ClampPanel(int p)
  {
   int cw=ChartW(), ch=ChartH();
   if(cw<=0 || ch<=0) return;
   if(g_px[p]>cw-Sc(60)) g_px[p]=cw-Sc(60);
   if(g_py[p]>ch-Sc(24)) g_py[p]=ch-Sc(24);
   if(g_px[p]<0) g_px[p]=0;
   if(g_py[p]<0) g_py[p]=0;
  }

void DrawUI()
  {
   if(!g_drawEnabled) return;
   BuildRobots(Sc(48),Sc(116));
   if(g_minimized)
     {
      for(int p=0;p<CT_PANELS;p++) ClearPanel(p);
      string n=CT_PFX+"U9_restore";
      UBtn(n,g_px[P_MAIN],g_py[P_MAIN],Sc(170),Sc(26),"   CVT LT DRIOD BOT NO ERRORS  [+]",TC.hdr,TC.text,FSz(8),"Restore dashboards");
      UBmp(CT_PFX+"U9_robot",g_px[P_MAIN]+Sc(4),g_py[P_MAIN]+Sc(3),g_resTiny);
      ChartRedraw(0);
      return;
     }
   ObjectsDeleteAll(0,CT_PFX+"U9_");
   if(g_pshow[P_MAIN]) DrawMain();
   if(g_pshow[P_IND]) DrawIndicators();
   if(g_pshow[P_CTRL]) DrawControls();
   if(g_pshow[P_ROBOT]) DrawRobotPanel();
   ChartRedraw(0);
  }

void ToggleCollapse(int p)
  {
   g_pcol[p]=!g_pcol[p]; SavePanel(p); ClearPanel(p);
  }

void SetScale(double s)
  {
   g_scale=MathMax(0.6,MathMin(1.7,s)); GVPut("scale",g_scale);
   for(int p=0;p<CT_PANELS;p++) ClearPanel(p);
   g_robotBuiltTheme=-1;
  }

void LayoutDefaults()
  {
   double base[5]={0.75,0.88,1.0,1.15,1.30};
   g_scale=GVGet("scale",base[(int)InpPanelSize]);
   int mx=12, my=28;
   int mainW=(int)MathRound(340*g_scale);
   int indW=(int)MathRound(340*g_scale);
   int indH=Sc(30)+Sc(8)+17*Sc(18)+Sc(8);
   int dx[CT_PANELS], dy[CT_PANELS];
   dx[P_MAIN]=mx; dy[P_MAIN]=my;
   dx[P_IND]=mx+mainW+10; dy[P_IND]=my;
   dx[P_CTRL]=mx+mainW+10; dy[P_CTRL]=my+indH+10;
   int cw=ChartW(); if(cw<=0) cw=1200;
   dx[P_ROBOT]=MathMax(mx+mainW+indW+30,cw-(int)MathRound(190*g_scale)); dy[P_ROBOT]=my+10;
   for(int p=0;p<CT_PANELS;p++)
     {
      g_px[p]=(int)GVGet("px"+IntegerToString(p),dx[p]);
      g_py[p]=(int)GVGet("py"+IntegerToString(p),dy[p]);
      g_pcol[p]=(GVGet("pc"+IntegerToString(p),InpCompactStart ? 1 : 0)>0.5);
     }
   g_pshow[P_MAIN]=InpShowDashboard; g_pshow[P_IND]=InpShowIndicatorPanel; g_pshow[P_CTRL]=InpShowControls; g_pshow[P_ROBOT]=InpShowChartRobot;
   g_minimized=(GVGet("min",0)>0.5);
   g_lines=(GVGet("lines",1)>0.5);
  }

int HitPanel(int mx,int my)
  {
   for(int p=CT_PANELS-1;p>=0;p--)
     {
      if(!g_pshow[p]) continue;
      int x=g_px[p], y=g_py[p], w=g_pw[p], hh=g_hdr[p];
      if(mx>=x && mx<=x+w-g_hdrBtnZone[p] && my>=y && my<=y+hh) return p;
     }
   return -1;
  }

//================================ CHART DRAWINGS ================================
void LSeg(string n,datetime t1,double p1,datetime t2,double p2,color c,int width,int style)
  {
   if(ObjectFind(0,n)<0)
     {
      ObjectCreate(0,n,OBJ_TREND,0,t1,p1,t2,p2);
      ObjectSetInteger(0,n,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,n,OBJPROP_HIDDEN,true);
      ObjectSetInteger(0,n,OBJPROP_RAY_RIGHT,false); ObjectSetInteger(0,n,OBJPROP_BACK,true);
     }
   else { ObjectMove(0,n,0,t1,p1); ObjectMove(0,n,1,t2,p2); }
   ObjectSetInteger(0,n,OBJPROP_COLOR,c); ObjectSetInteger(0,n,OBJPROP_WIDTH,width); ObjectSetInteger(0,n,OBJPROP_STYLE,style);
  }

void LArrow(string n,datetime t,double p,int code,color c)
  {
   if(ObjectFind(0,n)<0)
     {
      ObjectCreate(0,n,OBJ_ARROW,0,t,p);
      ObjectSetInteger(0,n,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,n,OBJPROP_HIDDEN,true); ObjectSetInteger(0,n,OBJPROP_BACK,true);
     }
   else ObjectMove(0,n,0,t,p);
   ObjectSetInteger(0,n,OBJPROP_ARROWCODE,code); ObjectSetInteger(0,n,OBJPROP_COLOR,c); ObjectSetInteger(0,n,OBJPROP_WIDTH,2);
   ObjectSetInteger(0,n,OBJPROP_ANCHOR,(code==233) ? ANCHOR_TOP : ANCHOR_BOTTOM);
  }

void DrawChart()
  {
   if(!g_drawEnabled) return;
   string pre=CT_PFX+"L_";
   if(!g_lines || !InpDrawIndicators || !g_ready) { ObjectsDeleteAll(0,pre); return; }
   ObjectsDeleteAll(0,pre+"a");
   int D=MathMin(InpDrawBars,N-45);
   bool zones=(g_strategy==STRAT_KALMAN_VWMA_REV || g_strategy==STRAT_REGIME);
   bool syn=(g_strategy==STRAT_SYNAPSE || g_trail==TRAIL_SYNAPSE);
   bool dual=(g_strategy==STRAT_UT_DUAL_ENGINE);
   color bbc=MixC(TC.chartBg,TC.chartFg,0.45);
   for(int i=0;i<D;i++)
     {
      string id=IntegerToString(i);
      LSeg(pre+"e"+id,T[i+1],EMAt[i+1],T[i],EMAt[i],TC.acc2,2,STYLE_SOLID);
      if(UTd[i]==UTd[i+1]) LSeg(pre+"u"+id,T[i+1],UTt[i+1],T[i],UTt[i],DirColor(UTd[i]),1,STYLE_DOT);
      else ObjectDelete(0,pre+"u"+id);
      if(KSTd[i]==KSTd[i+1]) LSeg(pre+"k"+id,T[i+1],KSTl[i+1],T[i],KSTl[i],DirColor(KSTd[i]),2,STYLE_SOLID);
      else ObjectDelete(0,pre+"k"+id);
      LSeg(pre+"bu"+id,T[i+1],BBu[i+1],T[i],BBu[i],bbc,1,STYLE_DOT);
      LSeg(pre+"bl"+id,T[i+1],BBl[i+1],T[i],BBl[i],bbc,1,STYLE_DOT);
      if(zones)
        {
         LSeg(pre+"zu"+id,T[i+1],ZU[i+1],T[i],ZU[i],MixC(TC.dn,TC.chartBg,0.35),1,STYLE_DASH);
         LSeg(pre+"zl"+id,T[i+1],ZL[i+1],T[i],ZL[i],MixC(TC.up,TC.chartBg,0.35),1,STYLE_DASH);
        }
      if(syn && SYNd[i]==SYNd[i+1]) LSeg(pre+"s"+id,T[i+1],SYNl[i+1],T[i],SYNl[i],MixC(DirColor(SYNd[i]),TC.acc,0.4),1,STYLE_SOLID);
      if(dual && DUd[i]==DUd[i+1]) LSeg(pre+"d"+id,T[i+1],DUt[i+1],T[i],DUt[i],MixC(DirColor(DUd[i]),TC.acc2,0.3),1,STYLE_SOLID);
      if(i>=1)
        {
         int sg=StrategySignal(g_strategy,i);
         if(sg>0) LArrow(pre+"a"+id,T[i],L[i]-0.25*ATR14[i],233,TC.up);
         if(sg<0) LArrow(pre+"a"+id,T[i],H[i]+0.25*ATR14[i],234,TC.dn);
        }
     }
   // locked stop lines for open positions
   ObjectsDeleteAll(0,pre+"sl");
   for(int i=0;i<g_npos;i++)
     {
      if(g_pos[i].sl<=0) continue;
      string n=pre+"sl"+IntegerToString(g_pos[i].ticket);
      ObjectCreate(0,n,OBJ_HLINE,0,0,g_pos[i].sl);
      bool locked=(g_pos[i].dir*(g_pos[i].sl-g_pos[i].open)>0);
      ObjectSetInteger(0,n,OBJPROP_COLOR,locked ? TC.up : TC.warn);
      ObjectSetInteger(0,n,OBJPROP_STYLE,STYLE_DASHDOT);
      ObjectSetInteger(0,n,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,n,OBJPROP_HIDDEN,true); ObjectSetInteger(0,n,OBJPROP_BACK,true);
      ObjectSetString(0,n,OBJPROP_TEXT,locked ? "CVT LT DRIOD BOT NO ERRORS profit lock" : "CVT LT DRIOD BOT NO ERRORS stop");
     }
  }

void SaveChartColors()
  {
   g_chartBgSaved=ChartGetInteger(0,CHART_COLOR_BACKGROUND); g_chartFgSaved=ChartGetInteger(0,CHART_COLOR_FOREGROUND);
   g_chartGridSaved=ChartGetInteger(0,CHART_COLOR_GRID); g_chartUpSaved=ChartGetInteger(0,CHART_COLOR_CHART_UP);
   g_chartDnSaved=ChartGetInteger(0,CHART_COLOR_CHART_DOWN); g_chartBullSaved=ChartGetInteger(0,CHART_COLOR_CANDLE_BULL);
   g_chartBearSaved=ChartGetInteger(0,CHART_COLOR_CANDLE_BEAR); g_chartLineSaved=ChartGetInteger(0,CHART_COLOR_CHART_LINE);
  }
void RestoreChartColors()
  {
   if(g_chartBgSaved<0) return;
   ChartSetInteger(0,CHART_COLOR_BACKGROUND,g_chartBgSaved); ChartSetInteger(0,CHART_COLOR_FOREGROUND,g_chartFgSaved);
   ChartSetInteger(0,CHART_COLOR_GRID,g_chartGridSaved); ChartSetInteger(0,CHART_COLOR_CHART_UP,g_chartUpSaved);
   ChartSetInteger(0,CHART_COLOR_CHART_DOWN,g_chartDnSaved); ChartSetInteger(0,CHART_COLOR_CANDLE_BULL,g_chartBullSaved);
   ChartSetInteger(0,CHART_COLOR_CANDLE_BEAR,g_chartBearSaved); ChartSetInteger(0,CHART_COLOR_CHART_LINE,g_chartLineSaved);
  }
void ApplyChartTheme()
  {
   if(!InpThemeChart || !g_drawEnabled) return;
   ChartSetInteger(0,CHART_COLOR_BACKGROUND,TC.chartBg); ChartSetInteger(0,CHART_COLOR_FOREGROUND,TC.chartFg);
   ChartSetInteger(0,CHART_COLOR_GRID,TC.chartGrid);
   ChartSetInteger(0,CHART_COLOR_CHART_UP,TC.up); ChartSetInteger(0,CHART_COLOR_CHART_DOWN,TC.dn);
   ChartSetInteger(0,CHART_COLOR_CANDLE_BULL,TC.up); ChartSetInteger(0,CHART_COLOR_CANDLE_BEAR,TC.dn);
   ChartSetInteger(0,CHART_COLOR_CHART_LINE,TC.acc);
  }

void SetTheme(int t)
  {
   g_theme=(t+CT_THEME_COUNT)%CT_THEME_COUNT; GVPut("theme",g_theme);
   ApplyThemeColors(g_theme); ApplyChartTheme();
   g_robotBuiltTheme=-1;
   DrawChart();
  }

//================================ BUTTON ACTIONS ================================
void LockBreakeven()
  {
   LoadPositions();
   int n=0;
   for(int i=0;i<g_npos;i++)
     {
      int dir=g_pos[i].dir; double px=(dir>0) ? PxBid() : PxAsk();
      double be=NormP(g_pos[i].open+dir*(InpLockBufferATR*ATR14[1]+SpreadPts()*g_point));
      if(dir*((px-dir*StopDist())-be)<0) continue;
      if(g_pos[i].sl>0 && dir*(g_pos[i].sl-be)>=0) continue;     // never loosen
      if(TradeModify(g_pos[i].ticket,be,g_pos[i].tp)) n++;
     }
   Note("Breakeven+ locked on "+IntegerToString(n)+" position(s)");
  }

void HandleButton(string key)
  {
   if(key=="b_buy")        { OpenTrade(1,true,"Manual BUY button"); }
   else if(key=="b_sell")  { OpenTrade(-1,true,"Manual SELL button"); }
   else if(key=="b_closeall")
     {
      if(g_closeAllArmed && GetTickCount()-g_closeAllArmedAt<=5000) { g_closeAllArmed=false; StartPortfolioExit("CLOSE ALL button"); }
      else { g_closeAllArmed=true; g_closeAllArmedAt=GetTickCount(); Note("Click CLOSE ALL again within 5 s to confirm"); }
     }
   else if(key=="b_cprof") CloseWhere(1,"CLOSE PROFIT button");
   else if(key=="b_closs") CloseWhere(-1,"CLOSE LOSS button");
   else if(key=="b_be")    LockBreakeven();
   else if(key=="b_pause") { g_paused=!g_paused; GVPut("pause",g_paused ? 1 : 0); Note(g_paused ? "Paused (saved)" : "Resumed"); }
   else if(key=="b_mode")  { g_mode=(g_mode+1)%3; GVPut("mode",g_mode); Note("Mode: "+ModeName(g_mode)); }
   else if(key=="b_reset") { g_killLock=false; g_dayLock=false; g_dayLockWhy=""; g_peakEquity=Equity(); GVPut("kill",0); GVPut("dayLock",0); GVPut("peak",g_peakEquity); Note("Locks reset; equity peak re-based"); }
   else if(key=="b_sprev" || key=="b_snext")
     {
      g_strategy=(g_strategy+((key=="b_snext") ? 1 : CT_STRAT_COUNT-1))%CT_STRAT_COUNT; GVPut("strat",g_strategy);
      Note("Strategy: "+StrategyName(g_strategy)); DrawChart();
     }
   else if(key=="b_tprev" || key=="b_tnext")
     {
      g_trail=(g_trail+((key=="b_tnext") ? 1 : CT_TRAIL_COUNT-1))%CT_TRAIL_COUNT; GVPut("trail",g_trail);
      Note("Trailing stop: "+TrailName(g_trail));
     }
   else if(key=="b_thprev") SetTheme(g_theme-1);
   else if(key=="b_thnext") SetTheme(g_theme+1);
   else if(key=="b_lotm" || key=="b_lotp")
     {
      double step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP); if(step<=0) step=0.01;
      g_manualLot=NormalizeLots(g_manualLot+((key=="b_lotp") ? step : -step)); GVPut("mlot",g_manualLot);
     }
   else if(key=="b_lines") { g_lines=!g_lines; GVPut("lines",g_lines ? 1 : 0); DrawChart(); }
   else if(key=="b_sizem") SetScale(g_scale-0.1);
   else if(key=="b_sizep") SetScale(g_scale+0.1);
   else if(key=="b_am")    SetScale(g_scale-0.05);
   else if(key=="b_ap")    SetScale(g_scale+0.05);
   else if(key=="b_min")   { g_minimized=true; GVPut("min",1); }
  }

//================================ EVENT HANDLERS ================================
int ChartOnInit()
  {
   g_isTester=(MQLInfoInteger(MQL_TESTER)!=0);
   g_isVisual=(MQLInfoInteger(MQL_VISUAL_MODE)!=0);
   g_drawEnabled=(!g_isTester || g_isVisual);
   string scope=AccountInfoString(ACCOUNT_SERVER)+"|"+IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN))+"|"+_Symbol+"|"+IntegerToString(InpMagic);
   vectorStatePrefix="VXRD_"+IntegerToString(SymbolHash(scope))+"_";
   if(g_isTester) vectorStatePrefix+="T"+IntegerToString(ChartID())+"_"+IntegerToString(GetTickCount())+"_";
   g_point=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
   g_digits=(int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
   if(g_point<=0) g_point=0.00001;
   if(InpMinLot<=0 || InpMaxLot<InpMinLot || InpRiskPercent<=0 || InpSL_ATR<=0 || InpPivotBars<1 || InpPivotBars>100 || InpUTATR<1 || InpMaxPositions<1) return INIT_PARAMETERS_INCORRECT;
#ifdef __MQL5__
   g_trade.SetExpertMagicNumber(InpMagic);
   g_trade.SetDeviationInPoints((ulong)InpSlippage);
   g_trade.SetTypeFillingBySymbol(_Symbol);
   g_trade.SetMarginMode();
   g_trade.LogLevel(LOG_LEVEL_ERRORS);
#endif
   // runtime selections persist; a change of the input values re-bases them
   double sig=(double)InpStrategy*1000000.0+(double)InpTrailMode*10000.0+(double)InpTheme*100.0+(double)InpMode;
   if(MathAbs(GVGet("insig",-1)-sig)>0.5)
     {
      g_strategy=InpStrategy; g_trail=InpTrailMode; g_theme=InpTheme; g_mode=InpMode;
      GVPut("insig",sig); GVPut("strat",g_strategy); GVPut("trail",g_trail); GVPut("theme",g_theme); GVPut("mode",g_mode);
     }
   else
     {
      g_strategy=(int)GVGet("strat",InpStrategy); g_trail=(int)GVGet("trail",InpTrailMode);
      g_theme=(int)GVGet("theme",InpTheme); g_mode=(int)GVGet("mode",InpMode);
     }
   g_strategy=MathMax(0,MathMin(CT_STRAT_COUNT-1,g_strategy));
   g_trail=MathMax(0,MathMin(CT_TRAIL_COUNT-1,g_trail));
   g_theme=MathMax(0,MathMin(CT_THEME_COUNT-1,g_theme));
   g_mode=MathMax(0,MathMin(2,g_mode));
   g_paused=(GVGet("pause",0)>0.5);
   g_killLock=(GVGet("kill",0)>0.5);
   g_peakEquity=GVGet("peak",Equity()); if(g_peakEquity<=0) g_peakEquity=Equity();
   g_dayKey=(int)GVGet("dayKey",0); g_dayStartEquity=GVGet("dayEq",Equity());
   g_dayLock=(GVGet("dayLock",0)>0.5); if(g_dayLock) g_dayLockWhy="restored from previous session";
   g_manualLot=NormalizeLots(GVGet("mlot",InpFixedLot));
   ApplyThemeColors(g_theme);
   if(g_drawEnabled)
     {
      SaveChartColors(); ApplyChartTheme();
      ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,true);
      LayoutDefaults();
      EventSetMillisecondTimer(250);
     }
   g_lastBar=0;
   LoadPositions();
   if(g_drawEnabled) DrawUI();
   return INIT_SUCCEEDED;
  }

void ChartOnDeinit(const int reason)
  {
   EventKillTimer();
   if(g_drawEnabled)
     {
      ObjectsDeleteAll(0,CT_PFX);
      RestoreChartColors();
      ChartSetInteger(0,CHART_MOUSE_SCROLL,true);
      ResourceFree(g_resSmall); ResourceFree(g_resBig); ResourceFree(g_resTiny);
      ChartRedraw(0);
     }
   if(g_isTester && vectorStatePrefix!="") GlobalVariablesDeleteAll(vectorStatePrefix);
   if(reason==REASON_REMOVE) Print(CT_NAME,": removed from chart; saved state kept for next attach");
  }

void ChartOnTick()
  {
   datetime bt=iTime(_Symbol,PERIOD_CURRENT,0);
   bool newBar=(bt!=g_lastBar);
   LoadPositions();
   if(g_mode!=MODE_SIGNALS) { ManageEquity(); ServicePortfolioExit(); }
   static datetime weekendAttempt=0;
   if(g_mode!=MODE_SIGNALS && g_npos>0 && PrideWeekend(g_strategy,TimeCurrent()) && TimeCurrent()-weekendAttempt>=5) {
      weekendAttempt=TimeCurrent();
      CloseWhere(0,"Weekend risk limit (New York)");
   }
   if(newBar) { g_lastBar=bt; OnNewBar(); }
   LoadPositions();
   if(g_ready && g_mode!=MODE_SIGNALS)
     {
      ManagePartials();
      ManageTrailing();
     }
   if(g_closeAllArmed && GetTickCount()-g_closeAllArmedAt>5000) g_closeAllArmed=false;
   if(g_drawEnabled)
     {
      if(newBar) DrawChart();
      g_tickCount++;
      if(g_isTester && (newBar || g_tickCount%15==0)) DrawUI();
     }
  }

void ChartOnTimer()
  {
   if(!g_drawEnabled) return;
   if(g_closeAllArmed && GetTickCount()-g_closeAllArmedAt>5000) g_closeAllArmed=false;
   if(g_drag<0) { LoadPositions(); DrawUI(); }
  }

void ChartOnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
   if(!g_drawEnabled) return;
   if(id==CHARTEVENT_OBJECT_CLICK)
     {
      if(StringFind(sparam,CT_PFX+"U")!=0) return;
      ObjectSetInteger(0,sparam,OBJPROP_STATE,false);
      if(sparam==CT_PFX+"U9_restore") { g_minimized=false; GVPut("min",0); ObjectsDeleteAll(0,CT_PFX+"U9_"); DrawUI(); return; }
      int us=StringFind(sparam,"_",StringLen(CT_PFX));
      if(us<0) return;
      int p=(int)StringToInteger(StringSubstr(sparam,StringLen(CT_PFX)+1,us-StringLen(CT_PFX)-1));
      string key=StringSubstr(sparam,us+1);
      if(key=="b_col") ToggleCollapse(p);
      else HandleButton(key);
      DrawUI();
      return;
     }
   if(id==CHARTEVENT_MOUSE_MOVE)
     {
      int mx=(int)lparam, my=(int)dparam;
      bool left=((((int)StringToInteger(sparam))&1)==1);
      if(left)
        {
         if(g_drag<0)
           {
            if(g_minimized) return;
            int p=HitPanel(mx,my);
            if(p<0) return;
            g_drag=p; g_dragOffX=mx-g_px[p]; g_dragOffY=my-g_py[p];
            ChartSetInteger(0,CHART_MOUSE_SCROLL,false);
           }
         else
           {
            g_px[g_drag]=mx-g_dragOffX; g_py[g_drag]=my-g_dragOffY;
            ClampPanel(g_drag);
            DrawUI();
           }
        }
      else if(g_drag>=0)
        {
         SavePanel(g_drag);
         g_drag=-1;
         ChartSetInteger(0,CHART_MOUSE_SCROLL,true);
        }
     }
   if(id==CHARTEVENT_CHART_CHANGE)
     {
      for(int p=0;p<CT_PANELS;p++) ClampPanel(p);
      DrawUI();
     }
  }

//+------------------------------------------------------------------+
//|                                        CVT LT DRIOD BOT NO ERRORS EA       |
//|                                   Copyright 2026, FLOWNEXUSFORGE |
//|   Unified MT4 & MT5 Multi-Engine Intelligent Trading Console     |
//|   Combined Core: BionicPulse + VectorVictor + Vector + BasicoBot|
//|   Cute Android Robot Logo (Dashboard + Chart), 104 Colour Themes, |
//|   12 Robot Logo Palettes, 27 Smart Positive Trailing SL Modes,   |
//|   Movable & Adjustable Dashboards, 16-Indicator Confluence,      |
//|   MTF Alignment (M5-H4), Kronos Positive Basket, Momentum-Fade,  |
//|   Net-Edge Cost Guard, 5-Page Control Deck & Blank Trade Comments|
//+------------------------------------------------------------------+
// CVT LT DRIOD BOT NO ERRORS EA | MetaTrader 4 and MetaTrader 5
// LICENSED BY FLOWNEXUSFORGE
#define SG_ORDER_COMMENT ""              // broker trade comment: always blank
#define SG_BRAND "CVT LT DRIOD BOT NO ERRORS"   // product name shown on dashboards, logs and alerts
#define SG_ENGINE_COUNT 117
#define SG_PALETTE_COUNT 694

enum SXStrategy {
   UT_REVERSAL=0, // UT ATR Trail Reversal
   UT_CONFLUENCE=1, // UT ATR Trail with Confluence Filters
   LEVEL_BREAKOUT=2, // Price Range Breakout
   TREND_PULLBACK=3, // Trend Pullback Continuation
   CONSENSUS=4, // Multi-Signal Directional Consensus
   SUPERTREND_FLIP=5, // Supertrend Direction Change
   UT_VWAP=6, // UT Reversal with VWAP Alignment
   HA_IMPULSE_VWAP=7, // Heikin Ashi Impulse with VWAP
   UT_STC=8, // UT Reversal with Schaff Trend Cycle
   LIQUIDITY_SWEEP=9, // Swing Liquidity Sweep Reversal
   EMA_CROSS=10, // Exponential Moving Average Crossover
   MACD_CROSS=11, // MACD Histogram Zero Crossing
   RANGE_REVERSION=12, // Bollinger Band Mean Reversion
   RSI_REENTRY=13, // RSI Reentry from Overbought or Oversold
   SQUEEZE_BREAKOUT=14, // Volatility Squeeze Release
   PIVOT_RSI=15, // Confirmed Pivot with RSI Extreme
   CYCLE_REVERSAL=16, // Cycle Oscillator Reversal
   LEVEL_BOUNCE=17, // Support and Resistance Bounce
   IMPULSE_ENGULF=18, // Impulse Candle Engulfing
   STC_CROSS=19, // Schaff Trend Cycle Crossover
   VWAP_CROSS=20, // Volume Weighted Average Price Crossing
   ZERO_LAG_FLIP=21, // Zero-Lag Moving Average Direction Change
   TREND_CONTINUATION=22, // Trend Continuation with Momentum
   SUPERTREND_STOP=23, // Supertrend Stop Direction Change
   UT_BOT_ATR_TRAIL=24, // UT Average True Range Trail
   UT_ALERTS_STRATEGY_RR=25, // UT Alert with Risk-Reward Exit
   ENSEMBLE_QUANT_ENSEMBLE=26, // Quantitative Trend Ensemble
   ENSEMBLE_HULL_ICHIMOKU=27, // Hull Moving Average and Ichimoku Cloud
   TREND_CYCLE_HYBRID=28, // Trend and Cycle Hybrid
   INSTANT_MANDATORY_BLITZ=29, // Directional Momentum Pulse
   STONEGEM_QUANTUM_PULSE=30, // Adaptive Momentum Pulse
   STONEGEM_KALMAN_TREND=31, // Kalman Filter Trend Continuation
   STONEGEM_ORDERFLOW_DELTA=32, // Directional Volume Pressure
   STONEGEM_VOLATILITY_BREAKOUT=33, // Volatility Expansion Breakout
   STONEGEM_INSTITUTIONAL_FVG=34, // Fair Value Gap Confirmation
   STONEGEM_SUPREME_BLITZ=35, // Multi-Model Directional Vote
   QUANTUM_SUPERTREND_SHIELD=36, // Adaptive Supertrend Direction
   DRM_MOMENTUM_REGIME=37, // Directional Momentum Regime
   UT_BOT_D1_MA_FILTER=38, // UT Reversal with Daily Moving Average Bias
   SESSION_OPENING_BIAS=39, // Opening Session Directional Bias
   CORAL_UT_RISK_MANAGER=40, // UT Coral Trend Pullback
   FILTERED_UT_STC_HULL=41, // UT Reversal with Schaff Cycle and Hull Trend
   ABSORPTION_DELTA_TRAP=42, // Volume Absorption Reversal
   SCALP_5MIN_PULSE=43, // Moving Average Ribbon Scalp
   STONEGEM_COMPOSITE=44, // Composite Trend Agreement
   RUBY_COMPRESSION=45, // Volatility Compression Release
   DIAMOND_RECLAIM=46, // Price Level Reclaim
   STONEGEM_REGIME=47, // Trend and Range Regime Selection
   DONCHIAN_RETEST=48, // Donchian Channel Breakout Retest
   KELTNER_REENTRY=49, // Keltner Channel Reentry
   AROON_CROSSOVER=50, // Aroon Directional Crossover
   VORTEX_CROSSOVER=51, // Vortex Indicator Crossover
   CHAIKIN_FLOW_CROSS=52, // Chaikin Money Flow Crossing
   DUAL_UT_LINREG=53, // Dual UT Trail with Linear Regression
   UT_EMA200=54, // UT Reversal with Long EMA
   UT_FILTER_MATRIX=55, // UT Reversal with Indicator Filter Matrix
   REGRESSION_PULLBACK=56, // Linear Regression Trend Pullback
   VWAP_MFI_RECLAIM=57, // VWAP and Money Flow Index Reclaim
   GEM_REGIME_ROUTER=58, // Momentum Regime Strategy Selection
   REGIME_CONFLUENCE=59, // Market Regime Confluence
   FAILED_BREAKOUT_RECLAIM=60, // Failed Breakout and Level Reclaim
   MATRIX_CLOCK_VOTE=61, // Session Clock Directional Vote
   MATRIX_UT_FVG=62, // UT Cooldown with Fair Value Gap
   MATRIX_HOVER_FADE=63, // Intraday Range Mean Reversion
   MATRIX_HOVER_BREAK=64, // Intraday Range Breakout
   MATRIX_HOVER_SCALP=65, // Short-Horizon Range Scalp
   UT_CLOSED_FLIP=66, // Confirmed UT Trail Direction Change
   UT_VALUE_TURN=67, // UT Trail with Schaff Cycle Value Turn
   UT_VISUAL_GAP=68, // UT Cooldown with Visible Price Gaps
   PATH_AGREEMENT=69, // Price Path Directional Agreement
   EXPANSION_RETEST=70, // Volatility Expansion Retest
   VWAP_REJECTION=71, // VWAP Wick Rejection
   DUAL_HORIZON=72, // Dual-Horizon Momentum Agreement
   PARABOLIC_ATR=73, // ATR Parabolic Direction Change
   SIMPLE_MA_CROSS=74, // Simple Moving Average Crossover
   RSI_EXTREMES=75, // RSI Extreme Reversal
   BAND_FADE=76, // Bollinger Band Fade
   STOCH_EXTREMES=77, // Stochastic Extreme Reversal
   HISTOGRAM_CROSS=78, // MACD Histogram Crossover
   SESSION_BRACKET=79, // Opening Range Bracket Breakout
   ADAPTIVE_RSI_VOTE=80, // Adaptive Relative Strength Vote
   TREND_CYCLE_VOTE=81, // Trend Cycle Directional Vote
   QUOTE_FLOW=82, // Live Bid and Ask Tick Flow
   STRUCTURE_VOTE=83, // Market Structure Scalp Vote
   FAST_SLOW_UT=84, // Fast and Slow UT Trail Confirmation
   UT_STC_GRADE=85, // Graded UT Trail and Schaff Cycle
   DROID_ADAPTIVE_CONFLUENCE=86, // Adaptive Multi-Indicator Confluence
   GOLD_M15_EMA200_H1_UT_ADX=87, // Gold Fifteen-Minute Two-Hundred EMA Hourly UT Bot ADX
   UT_BOT_UNIFIED_ENGINE=88, // UT Bot Unified ATR Flip Engine
   UT_BOT_ATR_RUNNER=89, // UT Bot ATR Trailing Stop Pure Runner
   UT_BOT_ALERTS_EMA200=90, // UT Bot Alerts Two-Hundred EMA Trend Filter
   UT_BOT_PANDICH_SCALPER=91, // UT Bot Pandich Momentum Scalper
   MIDNIGHT_EXPRESS_SCALPER=92, // Midnight Express Session Scalper
   UT_BOT_ALERTS_ELITE=93, // UT Bot Alerts Elite Confluence
   QUANTNOMAD_TRAIL_SL_ALERT=94, // QuantNomad Trailing Stop Loss Alert Engine
   QUANTNOMAD_MTF_TRAIL_SL=95, // QuantNomad Multi-Timeframe Trailing Stop Strategy
   YUTHAVITHI_BB_SCALPER=96, // Yuthavithi Bollinger Band Scalper
   PRO_KALMAN_SUPERTREND_VWMA=97, // Pro Scalper Kalman Supertrend VWMA Zones
   SCALPER_SMA_RSI_MACD=98, // Scalper SMA RSI MACD Entry Exit Signals
   MPR_SUPERTREND_SCALPER=99, // MPR Supertrend Precision Entry Exit Scalper
   OVERNIGHT_MNQ_SYNAPSE=100, // Overnight Nasdaq Synapse Confluence Scalper
   DR_UT=101, // ATR Trail Reversal
   DR_EMA=102, // EMA Filtered ATR Reversal
   DR_GOLD=103, // Hourly EMA and ADX Gold Long
   DR_ASYM=104, // Asymmetric ATR Reversal
   DR_FOUR=105, // Four Timeframe ATR Agreement
   DR_BAND=106, // Bollinger Expansion Scalp
   DR_KALMAN=107, // Kalman Supertrend and VWMA Zones
   DR_ROUTER=108, // Adaptive Trend and Range Router
   DR_MIDNIGHT=109, // Midnight Opening Range Breakout
   DR_AVERAGE=110, // Moving Average ATR Confirmation
   DR_RIBBON=111, // SMA Ribbon RSI MACD Pullback
   DR_CLOUD=112, // Supertrend Cloud Long
   DR_NIGHT=113, // Overnight Synapse Confluence
   DR_SNIPER=114, // UT Pivot Divergence Reversal
   DR_PANDICH=115, // Stateful Asymmetric ATR Trail
   DR_EXPRESS=116 // Overnight Adaptive Trail Flip
};
enum SXSource { SOURCE_CLOSE=0, SOURCE_HA_CLOSE=1, SOURCE_HL2=2, SOURCE_HLC3=3, SOURCE_OPEN=4 };
enum SXSize {
   PANEL_XS=0,
   PANEL_SMALL=1,
   PANEL_MEDIUM=2,
   PANEL_LARGE=3,
   PANEL_XL=4
};
enum SXTrailMode { TRAIL_STONEGEM_HYBRID=0, TRAIL_UT_BOT_ATR=1, TRAIL_RR_LADDER_RR=2, TRAIL_FIXED_POINTS=3, TRAIL_STEP_BUFFER=4, TRAIL_PURE_ATR=5, TRAIL_ADAPTIVE_ATR_REGIME=6, TRAIL_EXCURSION_40PCT=7, TRAIL_COMPRESSING_EXCURSION=8, TRAIL_SPREAD_3X=9, TRAIL_SPREAD_TIGHT=10, TRAIL_EMA21_DYNAMIC=11, TRAIL_SUPERTREND_LINE=12, TRAIL_WIDE_SWING_ATR=13, TRAIL_CHANDELIER_8BAR=14, TRAIL_PREV_BAR_HL=15, TRAIL_ADX_REGIME_TIGHT=16, TRAIL_RSI_EXTREME_LOCK=17, TRAIL_SPREAD_35X=18, TRAIL_SPREAD_ATR_HYBRID=19, TRAIL_ADX_TREND_RUNNER=20, TRAIL_HIGH_WATER_GIVEBACK=21, TRAIL_STONEGEM_QUANTUM_RATCHET=22, TRAIL_KALMAN_VELOCITY_LOCK=23, TRAIL_ORDERFLOW_IMPULSE_GUARD=24, TRAIL_FIBONACCI_EXCURSION_GRID=25, TRAIL_POSITIVE_PROFIT_RATCHET=26, TRAIL_CHANDELIER_HIGH_WATER=27, TRAIL_SWING_STRUCTURE_LOCK=28, TRAIL_VOLATILITY_ADAPTIVE_LOCK=29, TRAIL_QUANTUM_SUPERTREND_ER=30, TRAIL_DRM_REGIME_LOCK=31, TRAIL_CORAL_RISK_RATCHET=32, TRAIL_ABSORPTION_DELTA_GUARD=33, TRAIL_SCALP_FAST_RATCHET=34, TRAIL_STONEGEM_ULTIMATE_SL=35 };
enum SXTheme {
   THEME_STONEGEM_INK=0,
   THEME_STONEGEM_VELVET=1,
   THEME_STONEGEM_MIDNIGHT=2,
   THEME_STONEGEM_GRAPHITE=3,
   THEME_STONEGEM_DEEP_SEA=4,
   THEME_STONEGEM_SMOKED_BRONZE=5,
   THEME_STONEGEM_AURORA=6,
   THEME_STONEGEM_SLATE=7,
   THEME_STONEGEM_PARCHMENT=8,
   THEME_STONEGEM_PORCELAIN=9,
   THEME_STONEGEM_FROST=10,
   THEME_STONEGEM_BLUSH=11,
   THEME_DIAMOND_INK=12,
   THEME_DIAMOND_VELVET=13,
   THEME_DIAMOND_MIDNIGHT=14,
   THEME_DIAMOND_GRAPHITE=15,
   THEME_DIAMOND_DEEP_SEA=16,
   THEME_DIAMOND_SMOKED_BRONZE=17,
   THEME_DIAMOND_AURORA=18,
   THEME_DIAMOND_SLATE=19,
   THEME_DIAMOND_PARCHMENT=20,
   THEME_DIAMOND_PORCELAIN=21,
   THEME_DIAMOND_FROST=22,
   THEME_DIAMOND_BLUSH=23,
   THEME_RUBY_INK=24,
   THEME_RUBY_VELVET=25,
   THEME_RUBY_MIDNIGHT=26,
   THEME_RUBY_GRAPHITE=27,
   THEME_RUBY_DEEP_SEA=28,
   THEME_RUBY_SMOKED_BRONZE=29,
   THEME_RUBY_AURORA=30,
   THEME_RUBY_SLATE=31,
   THEME_RUBY_PARCHMENT=32,
   THEME_RUBY_PORCELAIN=33,
   THEME_RUBY_FROST=34,
   THEME_RUBY_BLUSH=35,
   THEME_SAPPHIRE_INK=36,
   THEME_SAPPHIRE_VELVET=37,
   THEME_SAPPHIRE_MIDNIGHT=38,
   THEME_SAPPHIRE_GRAPHITE=39,
   THEME_SAPPHIRE_DEEP_SEA=40,
   THEME_SAPPHIRE_SMOKED_BRONZE=41,
   THEME_SAPPHIRE_AURORA=42,
   THEME_SAPPHIRE_SLATE=43,
   THEME_SAPPHIRE_PARCHMENT=44,
   THEME_SAPPHIRE_PORCELAIN=45,
   THEME_SAPPHIRE_FROST=46,
   THEME_SAPPHIRE_BLUSH=47,
   THEME_EMERALD_INK=48,
   THEME_EMERALD_VELVET=49,
   THEME_EMERALD_MIDNIGHT=50,
   THEME_EMERALD_GRAPHITE=51,
   THEME_EMERALD_DEEP_SEA=52,
   THEME_EMERALD_SMOKED_BRONZE=53,
   THEME_EMERALD_AURORA=54,
   THEME_EMERALD_SLATE=55,
   THEME_EMERALD_PARCHMENT=56,
   THEME_EMERALD_PORCELAIN=57,
   THEME_EMERALD_FROST=58,
   THEME_EMERALD_BLUSH=59,
   THEME_AMETHYST_INK=60,
   THEME_AMETHYST_VELVET=61,
   THEME_AMETHYST_MIDNIGHT=62,
   THEME_AMETHYST_GRAPHITE=63,
   THEME_AMETHYST_DEEP_SEA=64,
   THEME_AMETHYST_SMOKED_BRONZE=65,
   THEME_AMETHYST_AURORA=66,
   THEME_AMETHYST_SLATE=67,
   THEME_AMETHYST_PARCHMENT=68,
   THEME_AMETHYST_PORCELAIN=69,
   THEME_AMETHYST_FROST=70,
   THEME_AMETHYST_BLUSH=71,
   THEME_AMBER_INK=72,
   THEME_AMBER_VELVET=73,
   THEME_AMBER_MIDNIGHT=74,
   THEME_AMBER_GRAPHITE=75,
   THEME_AMBER_DEEP_SEA=76,
   THEME_AMBER_SMOKED_BRONZE=77,
   THEME_AMBER_AURORA=78,
   THEME_AMBER_SLATE=79,
   THEME_AMBER_PARCHMENT=80,
   THEME_AMBER_PORCELAIN=81,
   THEME_AMBER_FROST=82,
   THEME_AMBER_BLUSH=83,
   THEME_JADE_INK=84,
   THEME_JADE_VELVET=85,
   THEME_JADE_MIDNIGHT=86,
   THEME_JADE_GRAPHITE=87,
   THEME_JADE_DEEP_SEA=88,
   THEME_JADE_SMOKED_BRONZE=89,
   THEME_JADE_AURORA=90,
   THEME_JADE_SLATE=91,
   THEME_JADE_PARCHMENT=92,
   THEME_JADE_PORCELAIN=93,
   THEME_JADE_FROST=94,
   THEME_JADE_BLUSH=95,
   THEME_GARNET_INK=96,
   THEME_GARNET_VELVET=97,
   THEME_GARNET_MIDNIGHT=98,
   THEME_GARNET_GRAPHITE=99,
   THEME_GARNET_DEEP_SEA=100,
   THEME_GARNET_SMOKED_BRONZE=101,
   THEME_GARNET_AURORA=102,
   THEME_GARNET_SLATE=103,
   THEME_GARNET_PARCHMENT=104,
   THEME_GARNET_PORCELAIN=105,
   THEME_GARNET_FROST=106,
   THEME_GARNET_BLUSH=107,
   THEME_TOPAZ_INK=108,
   THEME_TOPAZ_VELVET=109,
   THEME_TOPAZ_MIDNIGHT=110,
   THEME_TOPAZ_GRAPHITE=111,
   THEME_TOPAZ_DEEP_SEA=112,
   THEME_TOPAZ_SMOKED_BRONZE=113,
   THEME_TOPAZ_AURORA=114,
   THEME_TOPAZ_SLATE=115,
   THEME_TOPAZ_PARCHMENT=116,
   THEME_TOPAZ_PORCELAIN=117,
   THEME_TOPAZ_FROST=118,
   THEME_TOPAZ_BLUSH=119,
   THEME_AQUAMARINE_INK=120,
   THEME_AQUAMARINE_VELVET=121,
   THEME_AQUAMARINE_MIDNIGHT=122,
   THEME_AQUAMARINE_GRAPHITE=123,
   THEME_AQUAMARINE_DEEP_SEA=124,
   THEME_AQUAMARINE_SMOKED_BRONZE=125,
   THEME_AQUAMARINE_AURORA=126,
   THEME_AQUAMARINE_SLATE=127,
   THEME_AQUAMARINE_PARCHMENT=128,
   THEME_AQUAMARINE_PORCELAIN=129,
   THEME_AQUAMARINE_FROST=130,
   THEME_AQUAMARINE_BLUSH=131,
   THEME_TANZANITE_INK=132,
   THEME_TANZANITE_VELVET=133,
   THEME_TANZANITE_MIDNIGHT=134,
   THEME_TANZANITE_GRAPHITE=135,
   THEME_TANZANITE_DEEP_SEA=136,
   THEME_TANZANITE_SMOKED_BRONZE=137,
   THEME_TANZANITE_AURORA=138,
   THEME_TANZANITE_SLATE=139,
   THEME_TANZANITE_PARCHMENT=140,
   THEME_TANZANITE_PORCELAIN=141,
   THEME_TANZANITE_FROST=142,
   THEME_TANZANITE_BLUSH=143,
   THEME_OPAL_INK=144,
   THEME_OPAL_VELVET=145,
   THEME_OPAL_MIDNIGHT=146,
   THEME_OPAL_GRAPHITE=147,
   THEME_OPAL_DEEP_SEA=148,
   THEME_OPAL_SMOKED_BRONZE=149,
   THEME_OPAL_AURORA=150,
   THEME_OPAL_SLATE=151,
   THEME_OPAL_PARCHMENT=152,
   THEME_OPAL_PORCELAIN=153,
   THEME_OPAL_FROST=154,
   THEME_OPAL_BLUSH=155,
   THEME_PLATINUM_INK=156,
   THEME_PLATINUM_VELVET=157,
   THEME_PLATINUM_MIDNIGHT=158,
   THEME_PLATINUM_GRAPHITE=159,
   THEME_PLATINUM_DEEP_SEA=160,
   THEME_PLATINUM_SMOKED_BRONZE=161,
   THEME_PLATINUM_AURORA=162,
   THEME_PLATINUM_SLATE=163,
   THEME_PLATINUM_PARCHMENT=164,
   THEME_PLATINUM_PORCELAIN=165,
   THEME_PLATINUM_FROST=166,
   THEME_PLATINUM_BLUSH=167,
   THEME_COPPER_INK=168,
   THEME_COPPER_VELVET=169,
   THEME_COPPER_MIDNIGHT=170,
   THEME_COPPER_GRAPHITE=171,
   THEME_COPPER_DEEP_SEA=172,
   THEME_COPPER_SMOKED_BRONZE=173,
   THEME_COPPER_AURORA=174,
   THEME_COPPER_SLATE=175,
   THEME_COPPER_PARCHMENT=176,
   THEME_COPPER_PORCELAIN=177,
   THEME_COPPER_FROST=178,
   THEME_COPPER_BLUSH=179,
   THEME_CITRINE_INK=180,
   THEME_CITRINE_VELVET=181,
   THEME_CITRINE_MIDNIGHT=182,
   THEME_CITRINE_GRAPHITE=183,
   THEME_CITRINE_DEEP_SEA=184,
   THEME_CITRINE_SMOKED_BRONZE=185,
   THEME_CITRINE_AURORA=186,
   THEME_CITRINE_SLATE=187,
   THEME_CITRINE_PARCHMENT=188,
   THEME_CITRINE_PORCELAIN=189,
   THEME_CITRINE_FROST=190,
   THEME_CITRINE_BLUSH=191,
   THEME_OBSIDIAN_INK=192,
   THEME_OBSIDIAN_VELVET=193,
   THEME_OBSIDIAN_MIDNIGHT=194,
   THEME_OBSIDIAN_GRAPHITE=195,
   THEME_OBSIDIAN_DEEP_SEA=196,
   THEME_OBSIDIAN_SMOKED_BRONZE=197,
   THEME_OBSIDIAN_AURORA=198,
   THEME_OBSIDIAN_SLATE=199,
   THEME_OBSIDIAN_PARCHMENT=200,
   THEME_OBSIDIAN_PORCELAIN=201,
   THEME_OBSIDIAN_FROST=202,
   THEME_OBSIDIAN_BLUSH=203,
   THEME_TOURMALINE_INK=204,
   THEME_TOURMALINE_VELVET=205,
   THEME_TOURMALINE_MIDNIGHT=206,
   THEME_TOURMALINE_GRAPHITE=207,
   THEME_TOURMALINE_DEEP_SEA=208,
   THEME_TOURMALINE_SMOKED_BRONZE=209,
   THEME_TOURMALINE_AURORA=210,
   THEME_TOURMALINE_SLATE=211,
   THEME_TOURMALINE_PARCHMENT=212,
   THEME_TOURMALINE_PORCELAIN=213,
   THEME_TOURMALINE_FROST=214,
   THEME_TOURMALINE_BLUSH=215,
   THEME_MALACHITE_INK=217,
   THEME_MALACHITE_VELVET=218,
   THEME_MALACHITE_MIDNIGHT=219,
   THEME_MALACHITE_GRAPHITE=220,
   THEME_MALACHITE_DEEP_SEA=221,
   THEME_MALACHITE_SMOKED_BRONZE=222,
   THEME_MALACHITE_AURORA=223,
   THEME_MALACHITE_SLATE=224,
   THEME_MALACHITE_PARCHMENT=225,
   THEME_MALACHITE_PORCELAIN=226,
   THEME_MALACHITE_FROST=227,
   THEME_MALACHITE_BLUSH=228,
   THEME_CINNABAR_INK=229,
   THEME_CINNABAR_VELVET=230,
   THEME_CINNABAR_MIDNIGHT=231,
   THEME_CINNABAR_GRAPHITE=232,
   THEME_CINNABAR_DEEP_SEA=233,
   THEME_CINNABAR_SMOKED_BRONZE=234,
   THEME_CINNABAR_AURORA=235,
   THEME_CINNABAR_SLATE=236,
   THEME_CINNABAR_PARCHMENT=237,
   THEME_CINNABAR_PORCELAIN=238,
   THEME_CINNABAR_FROST=239,
   THEME_CINNABAR_BLUSH=240,
   THEME_LABRADORITE_INK=241,
   THEME_LABRADORITE_VELVET=242,
   THEME_LABRADORITE_MIDNIGHT=243,
   THEME_LABRADORITE_GRAPHITE=244,
   THEME_LABRADORITE_DEEP_SEA=245,
   THEME_LABRADORITE_SMOKED_BRONZE=246,
   THEME_LABRADORITE_AURORA=247,
   THEME_LABRADORITE_SLATE=248,
   THEME_LABRADORITE_PARCHMENT=249,
   THEME_LABRADORITE_PORCELAIN=250,
   THEME_LABRADORITE_FROST=251,
   THEME_LABRADORITE_BLUSH=252,
   THEME_SUNSTONE_INK=253,
   THEME_SUNSTONE_VELVET=254,
   THEME_SUNSTONE_MIDNIGHT=255,
   THEME_SUNSTONE_GRAPHITE=256,
   THEME_SUNSTONE_DEEP_SEA=257,
   THEME_SUNSTONE_SMOKED_BRONZE=258,
   THEME_SUNSTONE_AURORA=259,
   THEME_SUNSTONE_SLATE=260,
   THEME_SUNSTONE_PARCHMENT=261,
   THEME_SUNSTONE_PORCELAIN=262,
   THEME_SUNSTONE_FROST=263,
   THEME_SUNSTONE_BLUSH=264,
   THEME_ARCHIVE_TOP_0=265,
   THEME_ARCHIVE_TOP_1=266,
   THEME_ARCHIVE_TOP_2=267,
   THEME_ARCHIVE_TOP_3=268,
   THEME_ARCHIVE_TOP_4=269,
   THEME_ARCHIVE_TOP_5=270,
   THEME_ARCHIVE_TOP_6=271,
   THEME_ARCHIVE_TOP_7=272,
   THEME_ARCHIVE_TOP_8=273,
   THEME_ARCHIVE_TOP_9=274,
   THEME_ARCHIVE_TOP_10=275,
   THEME_ARCHIVE_TOP_11=276,
   THEME_ARCHIVE_TOP_12=277,
   THEME_ARCHIVE_TOP_13=278,
   THEME_ARCHIVE_TOP_14=279,
   THEME_ARCHIVE_TOP_15=280,
   THEME_ARCHIVE_TOP_16=281,
   THEME_ARCHIVE_TOP_17=282,
   THEME_ARCHIVE_TOP_18=283,
   THEME_ARCHIVE_TOP_19=284,
   THEME_ARCHIVE_TOP_20=285,
   THEME_ARCHIVE_TOP_21=286,
   THEME_ARCHIVE_TOP_22=287,
   THEME_ARCHIVE_TOP_23=288,
   THEME_ARCHIVE_TOP_24=289,
   THEME_ARCHIVE_TOP_25=290,
   THEME_ARCHIVE_TOP_26=291,
   THEME_ARCHIVE_TOP_28=292,
   THEME_ARCHIVE_TOP_29=293,
   THEME_ARCHIVE_TOP_30=294,
   THEME_ARCHIVE_TOP_31=295,
   THEME_ARCHIVE_TOP_32=296,
   THEME_ARCHIVE_TOP_33=297,
   THEME_ARCHIVE_TOP_34=298,
   THEME_ARCHIVE_TOP_35=299,
   THEME_ARCHIVE_TOP_36=300,
   THEME_ARCHIVE_TOP_37=301,
   THEME_ARCHIVE_TOP_38=302,
   THEME_ARCHIVE_TOP_39=303,
   THEME_ARCHIVE_TOP_40=304,
   THEME_ARCHIVE_TOP_41=305,
   THEME_ARCHIVE_TOP_42=306,
   THEME_ARCHIVE_TOP_43=307,
   THEME_ARCHIVE_TOP_44=308,
   THEME_ARCHIVE_TOP_45=309,
   THEME_ARCHIVE_TOP_46=310,
   THEME_ARCHIVE_TOP_47=311,
   THEME_ARCHIVE_TOP_48=312,
   THEME_ARCHIVE_TOP_49=313,
   THEME_ARCHIVE_TOP_50=314,
   THEME_ARCHIVE_TOP_51=315,
   THEME_ARCHIVE_TOP_52=316,
   THEME_ARCHIVE_TOP_53=317,
   THEME_ARCHIVE_TOP_54=318,
   THEME_ARCHIVE_TOP_55=319,
   THEME_ARCHIVE_TOP_56=320,
   THEME_ARCHIVE_TOP_57=321,
   THEME_ARCHIVE_TOP_58=322,
   THEME_ARCHIVE_TOP_59=323,
   THEME_ARCHIVE_TOP_60=324,
   THEME_ARCHIVE_TOP_61=325,
   THEME_ARCHIVE_TOP_62=326,
   THEME_ARCHIVE_TOP_63=327,
   THEME_ARCHIVE_TOP_64=328,
   THEME_ARCHIVE_TOP_65=329,
   THEME_ARCHIVE_TOP_66=330,
   THEME_ARCHIVE_TOP_67=331,
   THEME_ARCHIVE_TOP_68=332,
   THEME_ARCHIVE_TOP_69=333,
   THEME_ARCHIVE_TOP_70=334,
   THEME_ARCHIVE_TOP_71=335,
   THEME_ARCHIVE_HOVER_64=336,
   THEME_ARCHIVE_HOVER_65=337,
   THEME_ARCHIVE_HOVER_66=338,
   THEME_ARCHIVE_HOVER_67=339,
   THEME_ARCHIVE_HOVER_68=340,
   THEME_ARCHIVE_HOVER_69=341,
   THEME_ARCHIVE_HOVER_70=342,
   THEME_ARCHIVE_HOVER_71=343,
   THEME_STUDIO_GEM_DARK=344,
   THEME_STUDIO_BLACK=345,
   THEME_STUDIO_GREY=346,
   THEME_STUDIO_DARK_RED=347,
   THEME_STUDIO_DARK_GREY=348,
   THEME_STUDIO_MAROON=349,
   THEME_STUDIO_ORANGE_RED=350,
   THEME_STUDIO_CRIMSON=351,
   THEME_STUDIO_DARK_SILVER=352,
   THEME_STUDIO_ORANGE=353,
   THEME_STUDIO_METAL_GOLD=354,
   THEME_STUDIO_GREEN=355,
   THEME_STUDIO_FOREST=356,
   THEME_STUDIO_VIOLET=357,
   THEME_STUDIO_RED=358,
   THEME_STUDIO_CARAMEL=359,
   THEME_STUDIO_CORAL=360,
   THEME_STUDIO_SNOW_BLUE=361,
   THEME_STUDIO_GOLD=362,
   THEME_STUDIO_SILVER=363,
   THEME_STUDIO_BLUE=364,
   THEME_STUDIO_CERULEAN=365,
   THEME_STUDIO_WHITE=366,
   THEME_STUDIO_NEON=367,
   THEME_STUDIO_AURORA=368,
   THEME_STUDIO_OCEAN=369,
   THEME_STUDIO_SUNSET=370,
   THEME_STUDIO_GEM_CYBER=371,
   THEME_STUDIO_GEM_PLASMA=372,
   THEME_STUDIO_GEM_OBSIDIAN=373,
   THEME_STUDIO_GEM_EMERALD=374,
   THEME_STUDIO_GEM_SAPPHIRE=375,
   THEME_STUDIO_GEM_RUBY=376,
   THEME_STUDIO_GEM_TITANIUM=377,
   THEME_STUDIO_GEM_SOLAR=378,
   THEME_STUDIO_MIDNIGHT_TEAL=379,
   THEME_STUDIO_DEEP_NAVY=380,
   THEME_STUDIO_ARCTIC_FROST=381,
   THEME_STUDIO_ROSE_GOLD=382,
   THEME_STUDIO_LAVENDER_MIST=383,
   THEME_STUDIO_COPPER_FORGE=384,
   THEME_STUDIO_EMBER_GLOW=385,
   THEME_STUDIO_MOSS_STONE=386,
   THEME_STUDIO_INDIGO_NIGHT=387,
   THEME_STUDIO_PEARL_DAY=388,
   THEME_STUDIO_SLATE_BLUE=389,
   THEME_STUDIO_MINT_CREAM=390,
   THEME_STUDIO_SAND_DUNE=391,
   THEME_STUDIO_CHERRY_BLOSSOM=392,
   THEME_STUDIO_CHAMPAGNE=393,
   THEME_STUDIO_OLIVE_GROVE=394,
   THEME_STUDIO_BERRY_JAM=395,
   THEME_STUDIO_AQUAMARINE=396,
   THEME_STUDIO_COBALT=397,
   THEME_STUDIO_TURQUOISE=398,
   THEME_STUDIO_CITRUS=399,
   THEME_STUDIO_GRAPHITE=400,
   THEME_STUDIO_BURGUNDY=401,
   THEME_STUDIO_ICE_VIOLET=402,
   THEME_STUDIO_TERRACOTTA=403,
   THEME_STUDIO_LIME_NIGHT=404,
   THEME_STUDIO_SEPIA=405,
   THEME_STUDIO_AMBER_NIGHT=406,
   THEME_STUDIO_NORTHERN_LIGHTS=407,
   THEME_STUDIO_VOLCANIC=408,
   THEME_STUDIO_ROYAL_PURPLE=409,
   THEME_STUDIO_SAKURA_NIGHT=410,
   THEME_STUDIO_DEEP_SEA=411,
   THEME_STUDIO_SOLAR_FLARE=412,
   THEME_STUDIO_MATRIX=413,
   THEME_STUDIO_STEEL_BLUE=414,
   THEME_STUDIO_ESPRESSO=415,
   THEME_STUDIO_NEON_PINK=416,
   THEME_STUDIO_GLACIER=417,
   THEME_STUDIO_DAWN_PEACH=418,
   THEME_STUDIO_JADE=419,
   THEME_STUDIO_CARBON_GOLD=420,
   THEME_STUDIO_STORM_GREY=421,
   THEME_STUDIO_GEM_COMPOSITE=422,
   THEME_STUDIO_CYBERPUNK=423,
   THEME_STUDIO_SYNTHWAVE=424,
   THEME_STUDIO_TOKYO_NIGHT=425,
   THEME_STUDIO_NORDIC=426,
   THEME_STUDIO_DESERT_GOLD=427,
   THEME_STUDIO_FOREST_DEW=428,
   THEME_STUDIO_OCEAN_BREEZE=429,
   THEME_STUDIO_BLOOD_MOON=430,
   THEME_STUDIO_ROYAL_GOLD=431,
   THEME_STUDIO_MIDNIGHT_PURPLE=432,
   THEME_STUDIO_COTTON_CANDY=433,
   THEME_STUDIO_SPRING_LEAF=434,
   THEME_STUDIO_BLUEPRINT=435,
   THEME_STUDIO_COAL_EMBER=436,
   THEME_STUDIO_ICE_MINT=437,
   THEME_STUDIO_GEM_COMPOSITE_GOLD=438,
   THEME_STUDIO_GEM_ION_STORM=439,
   THEME_STUDIO_GEM_GRAPHENE=440,
   THEME_STUDIO_GEM_STARFIRE=441,
   THEME_STUDIO_GEM_QUANTUM_CYAN=442,
   THEME_STUDIO_GEM_ULTRAVIOLET=443,
   THEME_STUDIO_GEM_TITANIUM_TEAL=444,
   THEME_STUDIO_GEM_PHOTON_GOLD=445,
   THEME_STUDIO_GEM_POLAR_NIGHT=446,
   THEME_STUDIO_GEM_CRYSTAL_LIME=447,
   THEME_STUDIO_GEM_OBSIDIAN_COPPER=448,
   THEME_STUDIO_GEM_DEEP_MAGENTA=449,
   THEME_STUDIO_GEM_EMERALD_CIRCUIT=450,
   THEME_STUDIO_GEM_SILICON_SILVER=451,
   THEME_STUDIO_GEM_RETROWAVE=452,
   THEME_STUDIO_GEM_BALTIC_SKY=453,
   THEME_STUDIO_GEM_IVORY_GRAPHITE=454,
   THEME_STUDIO_E_DIAMOND_INK=455,
   THEME_STUDIO_E_DIAMOND_VELVET=456,
   THEME_STUDIO_E_DIAMOND_SLATE=457,
   THEME_STUDIO_E_DIAMOND_DUSK=458,
   THEME_STUDIO_E_DIAMOND_FROST=459,
   THEME_STUDIO_E_DIAMOND_MIDNIGHT=460,
   THEME_STUDIO_E_DIAMOND_PORCELAIN=461,
   THEME_STUDIO_E_DIAMOND_MARINE=462,
   THEME_STUDIO_E_DIAMOND_SMOKE=463,
   THEME_STUDIO_E_DIAMOND_AURORA=464,
   THEME_STUDIO_E_RUBY_INK=465,
   THEME_STUDIO_E_RUBY_VELVET=466,
   THEME_STUDIO_E_RUBY_SLATE=467,
   THEME_STUDIO_E_RUBY_DUSK=468,
   THEME_STUDIO_E_RUBY_FROST=469,
   THEME_STUDIO_E_RUBY_MIDNIGHT=470,
   THEME_STUDIO_E_RUBY_PORCELAIN=471,
   THEME_STUDIO_E_RUBY_MARINE=472,
   THEME_STUDIO_E_RUBY_SMOKE=473,
   THEME_STUDIO_E_RUBY_AURORA=474,
   THEME_STUDIO_E_EMERALD_INK=475,
   THEME_STUDIO_E_EMERALD_VELVET=476,
   THEME_STUDIO_E_EMERALD_SLATE=477,
   THEME_STUDIO_E_EMERALD_DUSK=478,
   THEME_STUDIO_E_EMERALD_FROST=479,
   THEME_STUDIO_E_EMERALD_MIDNIGHT=480,
   THEME_STUDIO_E_EMERALD_PORCELAIN=481,
   THEME_STUDIO_E_EMERALD_MARINE=482,
   THEME_STUDIO_E_EMERALD_SMOKE=483,
   THEME_STUDIO_E_EMERALD_AURORA=484,
   THEME_STUDIO_E_SAPPHIRE_INK=485,
   THEME_STUDIO_E_SAPPHIRE_VELVET=486,
   THEME_STUDIO_E_SAPPHIRE_SLATE=487,
   THEME_STUDIO_E_SAPPHIRE_DUSK=488,
   THEME_STUDIO_E_SAPPHIRE_FROST=489,
   THEME_STUDIO_E_SAPPHIRE_MIDNIGHT=490,
   THEME_STUDIO_E_SAPPHIRE_PORCELAIN=491,
   THEME_STUDIO_E_SAPPHIRE_MARINE=492,
   THEME_STUDIO_E_SAPPHIRE_SMOKE=493,
   THEME_STUDIO_E_SAPPHIRE_AURORA=494,
   THEME_STUDIO_E_CRYSTAL_INK=495,
   THEME_STUDIO_E_CRYSTAL_VELVET=496,
   THEME_STUDIO_E_CRYSTAL_SLATE=497,
   THEME_STUDIO_E_CRYSTAL_DUSK=498,
   THEME_STUDIO_E_CRYSTAL_FROST=499,
   THEME_STUDIO_E_CRYSTAL_MIDNIGHT=500,
   THEME_STUDIO_E_CRYSTAL_PORCELAIN=501,
   THEME_STUDIO_E_CRYSTAL_MARINE=502,
   THEME_STUDIO_E_CRYSTAL_SMOKE=503,
   THEME_STUDIO_E_CRYSTAL_AURORA=504,
   THEME_STUDIO_E_AMETHYST_INK=505,
   THEME_STUDIO_E_AMETHYST_VELVET=506,
   THEME_STUDIO_E_AMETHYST_SLATE=507,
   THEME_STUDIO_E_AMETHYST_DUSK=508,
   THEME_STUDIO_E_AMETHYST_FROST=509,
   THEME_STUDIO_E_AMETHYST_MIDNIGHT=510,
   THEME_STUDIO_E_AMETHYST_PORCELAIN=511,
   THEME_STUDIO_E_AMETHYST_MARINE=512,
   THEME_STUDIO_E_AMETHYST_SMOKE=513,
   THEME_STUDIO_E_AMETHYST_AURORA=514,
   THEME_STUDIO_E_TOPAZ_INK=515,
   THEME_STUDIO_E_TOPAZ_VELVET=516,
   THEME_STUDIO_E_TOPAZ_SLATE=517,
   THEME_STUDIO_E_TOPAZ_DUSK=518,
   THEME_STUDIO_E_TOPAZ_FROST=519,
   THEME_STUDIO_E_TOPAZ_MIDNIGHT=520,
   THEME_STUDIO_E_TOPAZ_PORCELAIN=521,
   THEME_STUDIO_E_TOPAZ_MARINE=522,
   THEME_STUDIO_E_TOPAZ_SMOKE=523,
   THEME_STUDIO_E_TOPAZ_AURORA=524,
   THEME_STUDIO_E_AQUAMARINE_INK=525,
   THEME_STUDIO_E_AQUAMARINE_VELVET=526,
   THEME_STUDIO_E_AQUAMARINE_SLATE=527,
   THEME_STUDIO_E_AQUAMARINE_DUSK=528,
   THEME_STUDIO_E_AQUAMARINE_FROST=529,
   THEME_STUDIO_E_AQUAMARINE_MIDNIGHT=530,
   THEME_STUDIO_E_AQUAMARINE_PORCELAIN=531,
   THEME_STUDIO_E_AQUAMARINE_MARINE=532,
   THEME_STUDIO_E_AQUAMARINE_SMOKE=533,
   THEME_STUDIO_E_AQUAMARINE_AURORA=534,
   THEME_STUDIO_E_GARNET_INK=535,
   THEME_STUDIO_E_GARNET_VELVET=536,
   THEME_STUDIO_E_GARNET_SLATE=537,
   THEME_STUDIO_E_GARNET_DUSK=538,
   THEME_STUDIO_E_GARNET_FROST=539,
   THEME_STUDIO_E_GARNET_MIDNIGHT=540,
   THEME_STUDIO_E_GARNET_PORCELAIN=541,
   THEME_STUDIO_E_GARNET_MARINE=542,
   THEME_STUDIO_E_GARNET_SMOKE=543,
   THEME_STUDIO_E_GARNET_AURORA=544,
   THEME_STUDIO_E_OPAL_INK=545,
   THEME_STUDIO_E_OPAL_VELVET=546,
   THEME_STUDIO_E_OPAL_SLATE=547,
   THEME_STUDIO_E_OPAL_DUSK=548,
   THEME_STUDIO_E_OPAL_FROST=549,
   THEME_STUDIO_E_OPAL_MIDNIGHT=550,
   THEME_STUDIO_E_OPAL_PORCELAIN=551,
   THEME_STUDIO_E_OPAL_MARINE=552,
   THEME_STUDIO_E_OPAL_SMOKE=553,
   THEME_STUDIO_E_OPAL_AURORA=554,
   THEME_STUDIO_E_JADE_INK=555,
   THEME_STUDIO_E_JADE_VELVET=556,
   THEME_STUDIO_E_JADE_SLATE=557,
   THEME_STUDIO_E_JADE_DUSK=558,
   THEME_STUDIO_E_JADE_FROST=559,
   THEME_STUDIO_E_JADE_MIDNIGHT=560,
   THEME_STUDIO_E_JADE_PORCELAIN=561,
   THEME_STUDIO_E_JADE_MARINE=562,
   THEME_STUDIO_E_JADE_SMOKE=563,
   THEME_STUDIO_E_JADE_AURORA=564,
   THEME_STUDIO_E_CITRINE_INK=565,
   THEME_STUDIO_E_CITRINE_VELVET=566,
   THEME_STUDIO_E_CITRINE_SLATE=567,
   THEME_STUDIO_E_CITRINE_DUSK=568,
   THEME_STUDIO_E_CITRINE_FROST=569,
   THEME_STUDIO_E_CITRINE_MIDNIGHT=570,
   THEME_STUDIO_E_CITRINE_PORCELAIN=571,
   THEME_STUDIO_E_CITRINE_MARINE=572,
   THEME_STUDIO_E_CITRINE_SMOKE=573,
   THEME_STUDIO_E_CITRINE_AURORA=574,
   THEME_CLOCK_AURORA_GOLD=575,
   THEME_CLOCK_GLACIER_CYAN=576,
   THEME_CLOCK_OBSIDIAN_EMERALD=577,
   THEME_CLOCK_SOLAR_AMBER=578,
   THEME_CLOCK_ROYAL_VIOLET=579,
   THEME_CLOCK_CRIMSON_ALLOY=580,
   THEME_CLOCK_CERULEAN_STEEL=581,
   THEME_CLOCK_TITANIUM_SILVER=582,
   THEME_CLOCK_FOREST_JADE=583,
   THEME_CLOCK_COPPER_ECLIPSE=584,
   THEME_CLOCK_INDIGO_PLASMA=585,
   THEME_CLOCK_ROSE_QUARTZ=586,
   THEME_MALACHITE_CIRCUIT=587,
   THEME_AMBER_CIRCUIT=588,
   THEME_FROSTED_SAPPHIRE=589,
   THEME_WILD_ORCHID=590,
   THEME_EMBER_COPPER=591,
   THEME_MINT_SLATE=592,
   THEME_POLAR_SILVER=593,
   THEME_BLACK_OPAL=594,
   THEME_FOREST_BRASS=595,
   THEME_OCEAN_GLASS=596,
   THEME_ROSE_GARNET=597,
   THEME_INDIGO_GOLD=598,
   THEME_FACET_INK_TIDE=599,
   THEME_FACET_SAWTOOTH_NEON=600,
   THEME_FACET_QUARTZ_TAPE=601,
   THEME_FACET_COPPER_CIRCUIT=602,
   THEME_FACET_ARCTIC_PULSE=603,
   THEME_FACET_MOSS_TERMINAL=604,
   THEME_FACET_EMBER_TAPE=605,
   THEME_FACET_VIOLET_STATIC=606,
   THEME_FACET_CITRINE_LADDER=607,
   THEME_FACET_ROSEWOOD_TICK=608,
   THEME_FACET_COBALT_FLUX=609,
   THEME_FACET_MINT_LEDGER=610,
   THEME_FACET_OBSIDIAN_GOLD=611,
   THEME_FACET_MAGENTA_DRIFT=612,
   THEME_FACET_TEAL_BURST=613,
   THEME_FACET_SOLAR_FLARE=614,
   THEME_FACET_INDIGO_WIRE=615,
   THEME_FACET_LIME_PULSE=616,
   THEME_FACET_SLATE_EMBER=617,
   THEME_FACET_ORCHID_WIRE=618,
   THEME_FACET_SANDSTONE_DAY=619,
   THEME_FACET_LINEN_DAY=620,
   THEME_FACET_PEARL_DAY=621,
   THEME_FACET_GLACIER_DAY=622,
   THEME_FACET_BASALT_PULSE=623,
   THEME_FACET_JADE_LEDGER=624,
   THEME_FACET_GEM_FACET=625,
   THEME_FACET_OPAL_TAPE=626,
   THEME_FACET_GARNET_WIRE=627,
   THEME_FACET_AMBER_GRID=628,
   THEME_FACET_SAPPHIRE_FLOW=629,
   THEME_FACET_EMERALD_TICK=630,
   THEME_FACET_TOPAZ_SIGNAL=631,
   THEME_FACET_ONYX_EMBER=632,
   THEME_FACET_RUBY_STATIC=633,
   THEME_FACET_AQUA_QUARTZ=634,
   THEME_FACET_PERIDOT_BURST=635,
   THEME_FACET_AMETHYST_DRIFT=636,
   THEME_FACET_CINNABAR_NIGHT=637,
   THEME_FACET_LAPIS_TERMINAL=638,
   THEME_FACET_JET_MINT=639,
   THEME_FACET_CITRINE_DUSK=640,
   THEME_FACET_SMOKE_VIOLET=641,
   THEME_FACET_CORAL_REEF=642,
   THEME_FACET_ALABASTER_DAY=643,
   THEME_FACET_JADE_DAY=644,
   THEME_FACET_ROSE_QUARTZ_DAY=645,
   THEME_FACET_SKY_OPAL_DAY=646,
   THEME_FACET_HARBOR_LANTERN=647,
   THEME_FACET_PINE_STATIC=648,
   THEME_FACET_DUNE_LEDGER=649,
   THEME_FACET_NEON_HARBOR=650,
   THEME_FACET_VELVET_ASH=651,
   THEME_FACET_CINDER_MINT=652,
   THEME_FACET_TANGERINE_WIRE=653,
   THEME_FACET_FROST_LEDGER=654,
   THEME_FACET_MULBERRY_TAPE=655,
   THEME_FACET_CEDAR_PULSE=656,
   THEME_FACET_STEEL_ORCHID=657,
   THEME_FACET_OCEAN_EMBER=658,
   THEME_FACET_GRAPHITE_LIME=659,
   THEME_FACET_PLUM_STATIC=660,
   THEME_FACET_BRASS_CIRCUIT=661,
   THEME_FACET_STORM_QUARTZ=662,
   THEME_FACET_MARIGOLD_NIGHT=663,
   THEME_FACET_TURQUOISE_WIRE=664,
   THEME_FACET_MAROON_TERMINAL=665,
   THEME_FACET_LILAC_LEDGER=666,
   THEME_FACET_CLOUD_DAY=667,
   THEME_FACET_PEACH_DAY=668,
   THEME_FACET_MINT_DAY=669,
   THEME_FACET_LAVENDER_DAY=670,
   THEME_FACET_NIMBUS_LEDGER=671,
   THEME_FACET_FERN_STATIC=672,
   THEME_FACET_RUST_TERMINAL=673,
   THEME_FACET_CYAN_EMBER=674,
   THEME_FACET_ASH_ORCHID=675,
   THEME_FACET_MOCHA_WIRE=676,
   THEME_FACET_VIOLET_CITRINE=677,
   THEME_FACET_PEWTER_MINT=678,
   THEME_FACET_SCARLET_TAPE=679,
   THEME_FACET_TEAL_DUSK=680,
   THEME_FACET_GOLD_SLATE=681,
   THEME_FACET_IRIS_PULSE=682,
   THEME_FACET_SPRUCE_QUARTZ=683,
   THEME_FACET_ROSEWATER_NIGHT=684,
   THEME_FACET_LAGOON_EMBER=685,
   THEME_FACET_OLIVE_WIRE=686,
   THEME_FACET_BERRY_STATIC=687,
   THEME_FACET_COBALT_MINT=688,
   THEME_FACET_COPPER_FROST=689,
   THEME_FACET_MAUVE_TERMINAL=690,
   THEME_FACET_DAYLIGHT_LEDGER=691,
   THEME_FACET_APRICOT_DAY=692,
   THEME_FACET_SEAFOAM_DAY=693,
   THEME_FACET_PERIWINKLE_DAY=694,
   THEME_CUSTOM=216
};
enum SXThemeStyle {
   STYLE_SOLID_MATTE=0,
   STYLE_NEON_GLOW=1,
   STYLE_HIGH_CONTRAST=2,
   STYLE_MINIMAL_STEALTH=3,
   STYLE_PASTEL_SOFT=4,
   STYLE_ICE_FROST=5,
   STYLE_CINEMATIC=6,
   STYLE_MONOCHROME=7,
   STYLE_AURORA=8,
   STYLE_TERMINAL=9,
   STYLE_SUNSET_GLOW=10,
   STYLE_DEEP_SPACE=11,
   STYLE_HOLOGRAPHIC=12,
   STYLE_BRUSHED_TITANIUM=13,
   STYLE_CARBON_FIBER=14,
   STYLE_ELECTRIC_CANDY=15
};
enum SXRiskBase { RISKBASE_EQUITY=0, RISKBASE_BALANCE=1, RISKBASE_FREE_MARGIN=2 };

enum LogoMode { LOGO_THEME=0, LOGO_CUSTOM=1, LOGO_GEMSTONES=2 };
input string InpIdentitySection="--- Logo colours and chart ---";
enum RobotBody { ROUNDED_ROBOT=0, WINGED_DRONE=1 };
input RobotBody InpRobotBody=ROUNDED_ROBOT; // Robot shape
input LogoMode InpLogoMode=LOGO_CUSTOM;
input color InpLogoBody=C'73,213,168';
input color InpLogoNodes=C'255,191,117'; // Beacon
// Custom mode accepts an exact colour for every visible logo part. None derives the colour from the base.
input color InpLogoCrownRight=C'182,251,236'; // Shell rim
input color InpLogoUpperRight=C'83,203,187'; // Shell
input color InpLogoLowerRight=C'16,40,58'; // Faceplate
input color InpLogoLowerLeft=C'52,141,160'; // Earpieces
input color InpLogoUpperLeft=C'255,171,149'; // Cheeks
input color InpLogoCrownLeft=C'199,253,246'; // Smile and chest light
input color InpLogoTrace=C'133,238,220'; // Eyes and antenna
input color InpLogoGlint=C'242,255,249'; // Highlights
input color InpLogoWordmark=C'239,252,250'; // Wordmark
input int InpLogoHeaderOpacity=100; // Panel emblem opacity, 0..100
input bool InpStyleCandles=true;
input string InpTickSection="--- Quote flow ---";
input int InpTickWindowSeconds=20;          // Rolling quote window, 3..300 seconds
input int InpTickMinMoves=24;               // Minimum quote changes inside the window (4..400)
input double InpTickMinImbalance=0.62;      // Share of quote moves in one direction (0.50..0.98)
input double InpTickMinDriftPts=6.0;        // Minimum net drift inside the window, broker points
input double InpTickMaxSpreadShare=0.35;    // Spread must be at most this share of the drift
input int InpTickCooldownSeconds=15;        // Minimum seconds between tick-flow entries per symbol
input int InpTickMaxEntriesPerBar=1;        // Tick-flow entries per signal-timeframe bar
input bool InpTickLiveEntry=true;           // Tick engine may enter intrabar, quote by quote
input bool InpTickVeto=false;               // Any engine: refuse entries against strong opposing tick flow
input int InpTickMaxEntriesPerHour=12;      // 0 = off. Tick-flow entries per server hour per symbol
input double InpTickMinRate=0.0;            // 0 = off. Minimum quote changes per second inside the window
input int InpTickConfirmSeconds=2;          // Direction must hold this many seconds before an entry (0 = off)
input double InpTickDriftSpreadMult=3.0;    // Drift must also be at least this many times the current spread (0 = off)
input double InpTickSpreadSpikeMult=3.0;    // Block tick entries while the spread exceeds this multiple of the window average (0 = off)
input int InpRolloverGuardMinutes=10;       // 0 = off. Quiet window around server midnight, no new entries
input bool InpGivebackExit=true;            // Close a position that gives back part of its best profit
input double InpGivebackMinATR=0.5;         // Best profit, in ATR, needed before the give-back exit arms
input double InpGivebackPct=50.0;           // Share of the best profit that may be given back (1..95)
input bool InpTickReverseExit=true;         // Close a position when strong tick flow turns against it
input bool InpTickReverseProfitOnly=true;   // Reverse exit closes only positions that are in profit
input int InpTickReverseMinHoldSec=5;       // Minimum seconds a position is held before a reverse exit
input string InpFlowGuardSection="--- Account protection ---";
input double InpWeeklyLossPercent=5.0;      // 0 = off. Block new entries after this weekly equity loss
input double InpCommissionPerLot=0.0;       // Round-turn commission per lot in account currency, added to sizing risk
input bool InpSizeIncludesSlippage=true;    // Size as if the stop fills slippage points further away
input bool InpUseInstanceLease=true;        // One active instance per account, server and magic number
input bool InpAuthorizeEmergencyReset=false;// Attach once with this ON to clear a saved emergency lock
input string InpVoteSection="--- Structure vote ---";
input int InpVoteMinVotes=3;                // Agreeing reads required (2..6) out of nine
input int InpVoteEmaFast=8;                 // Fast EMA period
input int InpVoteEmaSlow=21;                // Slow EMA period
input int InpVoteEmaMid=55;                 // Ribbon middle EMA period (at least the slow period)
input int InpVoteLongEma=200;               // Long EMA period for the trend-side read
input int InpVoteSweepLookback=12;          // Swing bars for sweep and structure reads (5..40)
input int InpVoteRsiPeriod=7;               // RSI period for the pullback and midline reads
input int InpVoteAdxPeriod=14;              // ADX period
input double InpVoteAdxMin=18.0;            // 0 = off. ADX floor, directional index must agree
input double InpSlipPauseRatio=0.6;         // 0 = off. Pause automatic entries when average fill slippage exceeds this share of InpSlippagePoints
input int InpSlipPauseMinutes=15;           // Length of that pause (1..240)
input bool InpUseTrendFitGate=false;        // Require the closes to line up with the trade direction
input int InpTrendFitBars=20;               // Bars for the trend-fit correlation (5..200)
input double InpMinTrendFit=0.5;            // Required correlation in the trade direction (0..1)
input bool InpVoteVeto=false;               // Let the nine vote reads veto entries from any other engine

input bool InpSignalAlerts=false; // Signal alerts can run with automatic entries paused
input bool InpSlowUTRequire=false;
input bool InpSlowUTUseEMA=false;
input int InpSlowUTEMALength=200;
input bool InpShowSlowUT=true;
input string InpRegimeSection="--- Closed-bar signal controls ---";
input int InpPathBars=18;
input double InpPathEfficiency=0.22;
input int InpRegimeVotes=3;
input double InpRegimeMinRatio=0.55;
input double InpRegimeMaxRatio=2.00;
input double InpRetestToleranceATR=0.15;
input double InpSnapbackDistanceATR=0.75;
input int InpUTQuietBars=30;
input double InpSTCVolumeRatio=1;
input bool InpValueTurnSwing=true;
input int InpRangeWeekday=-1;
input int InpRangeStartUTC=8;
input int InpRangeWindowMinutes=120;
input int InpRangeServerOffsetMinutes=0;
input ENUM_TIMEFRAMES InpRangeTF=PERIOD_M15;
input int InpRangeBars=12;
input double InpRangeBufferATR=0.12;
input string InpStrategySection="--- Signal engine ---";
input SXStrategy ConsoleInpStrategy=DR_ROUTER;
input string InpSmartSection="--- Intelligent Smart Functions ---";
input bool InpSmartRegimeRouter=true;        // Auto-route & shield entries by live market regime
input bool InpSmartAntiChop=false;           // Block fresh entries when ATR ratio is compressed
input double InpSmartMinAtrRatio=0.58;       // Minimum ATR / mean ratio for anti-chop clearance
input bool InpSmartMtfConfirm=false;         // Require higher-timeframe UT Bot directional agreement
input ENUM_TIMEFRAMES InpSmartConfirmTF=PERIOD_H1; // Higher timeframe for smart MTF confirmation
input double InpSmartKalmanGain=0.18;        // 1D recursive Kalman smoothing gain (0.02..0.95)
input int InpSmartVwmaPeriod=21;             // Volume-weighted MA value zone length (5..200)
input bool InpSmartStreakShield=true; // Half daily-loss budget plus opposing velocity blocks entries
//        // Adaptive drawdown and streak defensive state governor
input bool InpSmartVelocityRatchet=true;
input int InpNightOpen=18; // Overnight start in Eastern time
input int InpNightEnd=17; // Overnight end in Eastern time
input int InpClockMinVotes=5; // directional votes out of nine
input int InpClockHoverBars=24;
input int InpClockMaxHoldMinutes=0; // Elapsed-style minute exit; 0 disables it
input double InpClockHoverEdgeATR=0.18;
input bool InpClockRequireUT=false;
input bool InpClockCorrelationGate=false;
input double InpClockMinTrendCorrelation=0.35;
input bool InpClockWideDashboard=false;
input bool InpClockTieredRatchet=true; // Shared Adaptive/Mineral R-multiple profit ratchet
input bool InpClockRejectBadQuotes=true; // Reject invalid prices before entry or modification
input int InpClockTimerSeconds=1; // 1..10 seconds, tick management stays active
input int InpClockRetrySeconds=10; // Minimum spacing between definite entry failures
input ENUM_TIMEFRAMES InpSignalTF=PERIOD_CURRENT;
input SXSource InpSource=SOURCE_CLOSE;
input int InpATRPeriod=10;
input double InpATRMultiplier=1.0;
input int InpCooldownBars=2;
input int InpHistoryBars=1550;
input bool InpAutoEnabled=false;
input bool InpTesterOnlyEntries=true;      // When true, never submit new orders outside Strategy Tester
input bool InpEntryDiagnostics=true;        // Show changed entry reasons in Experts / Strategy Tester Journal
input bool InpTradeOnAttach=true;
input bool InpAllowBuy=true;
input bool InpAllowSell=true;
input bool ConsoleCloseOnOpposite=false;
input int InpMinConfluenceScore=55;
input string InpFilterSection="--- Optional confluence ---";
input int InpFastMA=21;
input int InpSlowMA=200;
input int InpSMAPeriod=50;
input int ConsoleRSIPeriod=14;
input int ConsoleADXPeriod=14;
input bool ConsoleUseEMAFilter=false;
input bool InpUseSMAFilter=false;
input bool InpUseRSIFilter=false;
input double InpRSIBuyMin=50.0;
input double InpRSISellMax=50.0;
input bool ConsoleUseADXFilter=false;
input double InpMinADX=18.0;
input bool InpUseMACDFilter=false;
input bool InpUseZeroLagFilter=false;
input int InpZeroLagPeriod=70;
input double InpZeroLagBandATR=1.2;
input bool InpUseMTFFilter=false;
input ENUM_TIMEFRAMES InpTrendTF1=PERIOD_H1;
input ENUM_TIMEFRAMES InpTrendTF2=PERIOD_H4;
input bool InpUseVolumeFilter=false;
input int InpVolumePeriod=20;
input double InpMinVolumeRatio=0.8;
input int InpBreakoutLookback=20;
input bool InpUseLevelFilter=false;
input double InpLevelRoomATR=0.5;
input bool InpUseFVGFilter=false;
input double InpMinFVGGapPercent=0.01;
input int InpMaxFVGAgeBars=100;
input double ConsoleMaxSpreadATR=0.30;
input int ConsoleMaxSpreadPoints=0;
input int InpMaxQuoteAgeSeconds=30;
input bool ConsoleUseSession=false;
input int InpSessionStartHour=0;
input int InpSessionEndHour=24;
input bool InpUseDateWindow=false;
input datetime InpStartDate=D'2020.01.01 00:00';
input datetime InpEndDate=D'2035.01.01 00:00';
input bool InpCloseAtEndDate=true;
input string InpRiskSection="--- Position sizing and protection ---";
input bool InpUseRiskLot=true;
input double ConsoleRiskPercent=0.25;
input double InpFixedLots=0.01;
input double InpMaxLots=5.0;
input int ConsoleMaxPositions=1;
input int ConsoleMagic=6120572;
input int InpSlippagePoints=30;
input double InpInitialSL_ATR=2.0;
input int InpMinSLPoints=0;
input bool InpBreakEven=true;
input double InpBETriggerATR=1.0;
input double InpBELockATR=0.10;
input bool InpTrailing=true;
input double InpTrailStartATR=1.5;
input double InpTrailDistanceATR=1.0;
input double InpTrailStepATR=0.10;
input bool InpUseUTTrail=true;
input double InpDailyLossPercent=2.0;
input double InpMaxDrawdownPercent=8.0;
input bool InpCloseOnRiskLock=true;
input bool InpPopupAlerts=false;
input bool InpPushAlerts=false;
input string InpDisplaySection="--- Chart dashboard ---";
enum GemDashboardStart { START_OVERVIEW=0, START_INDICATORS=1, START_LOGO_STUDIO=2, START_CLASSIC_DESK=3 };
input GemDashboardStart InpDashboardStart=START_OVERVIEW;
input bool ConsoleShowDashboard=true;
input SXSize ConsolePanelSize=PANEL_LARGE;
input bool InpPanelRight=false;
input int InpPanelX=12;
input int InpPanelY=18;
input bool InpShowFVG=true;
input int InpMaxFVGDraw=15;
input bool InpShowLevels=true;
input bool InpShowTrail=true;
input bool InpShowMA=true;
input bool InpShowZeroLag=false;
input bool InpShowSignals=true;

enum SXAssets { ASSET_CHART=0, ASSET_MARKETWATCH=1, ASSET_CUSTOM=2, ASSET_BROKER=3 };
enum SXEntry { ENTRY_MARKET=0, ENTRY_STOP=1, ENTRY_LIMIT=2 };
enum SXGrid { GRID_OFF=0, GRID_ADVERSE=1, GRID_PYRAMID=2 };
enum SXGridLots { GRID_FIXED=0, GRID_MULTIPLY=1, GRID_ADDITIVE=2 };
input string InpPortfolioSection="--- Portfolio and universe ---";
input SXAssets InpAssets=ASSET_CHART;
input string InpSymbols="";
input int InpMaxSymbols=0;
input int InpScanBatch=4;
input int InpMaxPortfolioPositions=6;
input double InpMaxPortfolioRiskPct=2.0;
input int InpMinEntrySeconds=0;
input string InpModuleSection="--- Consolidated signal modules ---";
input int InpSuperPeriod=120;
input double InpSuperMultiplier=3.0;
input bool InpUseSuperFilter=false;
input int InpVWAPAnchorHour=0;
input int InpVWAPAnchorMinute=0;
input bool InpUseRealVolume=true;
input bool InpUseVWAPFilter=false;
input double InpHAImpulseATR=1.2;
input int InpStcFast=27;
input int InpStcSlow=50;
input int InpStcCycle=80;
input double InpStcSmooth=0.5;
input double InpStcBuyZone=25.0;
input double InpStcSellZone=75.0;
input int InpStcLag=2;
input bool InpUseSTCFilter=false;
input int InpBandPeriod=20;
input double InpBandDeviation=2.0;
input double InpRangeADXMax=25.0;
input int InpATRMeanPeriod=40;
input bool InpUseATRBand=false;
input double InpMinATRRatio=0.50;
input double InpMaxATRRatio=2.50;
input int InpSwingLookback=60;
input int InpPivotLeft=3;
input int InpPivotRight=3;
input double InpPivotRSILow=35.0;
input double InpPivotRSIHigh=65.0;
input string InpExecutionSection="--- Pending orders and basket controls ---";
input SXEntry InpEntryStyle=ENTRY_MARKET;
input double InpPendingOffsetATR=0.25;
input int InpPendingLifeBars=3;
input bool InpPendingOCO=true;
input SXGrid InpGrid=GRID_OFF;
input int InpGridMaxLevels=3;
input double InpGridSpacingATR=1.5;
input SXGridLots InpGridLots=GRID_FIXED;
input double InpGridMultiplier=1.25;
input double InpGridAddLots=0.01;
input bool InpGridRequiresSignal=true;
input bool InpBasketLock=false;
input double InpBasketStartMoney=20.0;
input double InpBasketGivebackPct=35.0;
input double InpBasketMinMoney=2.0;
input double InpBasketLossMoney=0.0;
input bool InpShowVWAP=true;
input bool InpShowSuper=true;
input bool InpShowIndicatorStrip=true;
input string InpStoneGemSection="--- StoneGem Instant Execution, Quantum/Kalman & Themes ---";
input bool InpInstantMandatoryOpen=false;
input bool InpInstantStateEntry=false;
input bool InpMandatoryMinLotFallback=false;
input bool InpAutoWidenStop=true;
input SXTrailMode ConsoleTrailMode=TRAIL_STONEGEM_ULTIMATE_SL;
input double InpPositiveCostLockPerLot=0.0;
input double InpStage2CompressionATR=0.60;
input double InpStage4ExtraLockATR=0.25;
input bool InpUsePositiveProfitRatchet=true;
input double InpProfitRatchetStartATR=0.75;
input double InpProfitRatchetStepATR=0.50;
input double InpProfitRatchetLockPercent=25.0;
input double InpProfitRatchetStepPercent=8.0;
input double InpProfitRatchetMaxPercent=80.0;
input bool InpUseRRPartialTP=true;
input double InpRRPartialRR=3.0;
input double InpRRBETriggerRR=0.75;
input double InpRRKeyValue=3.0;
input int InpRRATRPeriod=1;
input int InpRREMAPeriod=200;
input bool InpRRUseHeikinAshi=false;
input int InpEnsembleMinVotes=2;
input double InpEnsembleMinConfidence=0.55;
input int InpHullPeriod=16;
input double ConsoleKalmanGain=0.28;
input int InpVelocityPeriod=8;
input bool InpSpreadShockShield=true;
input bool InpUseQuantumRatchet=true;
input bool InpDynamicRiskScaling=false;
input double InpDynamicRiskMinMult=0.50;
input double InpDynamicRiskMaxMult=1.50;
input SXTheme ConsoleTheme=THEME_MALACHITE_CIRCUIT;
input SXThemeStyle InpThemeStyle=STYLE_SOLID_MATTE;
input bool InpApplyThemeToChart=true;
input color InpCustomBgColor=C'7,19,29';
input color InpCustomCardColor=C'11,30,42';
input color InpCustomAccentColor=C'30,209,231';
input color InpCustomTextColor=C'230,238,248';
input color InpCustomBorderColor=C'22,69,88';
input color InpCustomBullColor=C'60,228,140';
input color InpCustomBearColor=C'241,82,108';
input color InpCustomMutedColor=C'151,177,192';        // Custom theme: secondary text / labels
input color InpCustomSecondaryColor=C'32,169,228';     // Custom theme: secondary accent (High Contrast style border)
input color InpCustomGridColor=clrNONE;                // Custom theme: chart grid (clrNONE = use border colour)
input color InpCustomZoneBullColor=C'24,65,58';        // Custom theme: bullish FVG zone fill
input color InpCustomZoneBearColor=C'73,35,49';        // Custom theme: bearish FVG zone fill
input color InpCustomVolumeColor=C'78,158,244';        // Custom theme: chart volume colour

input string InpExtraThemeSection="--- Expanded appearance customization ---";
input bool InpEnablePaletteOverrides=false;         // Apply individual colors over ANY of the 343 preset themes
input color InpOverrideBg=clrNONE;                   // clrNONE keeps chosen theme value
input color InpOverrideCard=clrNONE;
input color InpOverrideAccent=clrNONE;
input color InpOverrideSecondary=clrNONE;
input color InpOverrideText=clrNONE;
input color InpOverrideMuted=clrNONE;
input color InpOverrideBorder=clrNONE;
input color InpOverrideBull=clrNONE;
input color InpOverrideBear=clrNONE;
input color InpOverrideZoneBull=clrNONE;
input color InpOverrideZoneBear=clrNONE;
input color InpOverrideGrid=clrNONE;
input color InpOverrideVolume=clrNONE;
input color InpChartUpWickColor=clrNONE;             // Optional chart-only up bar/wick color
input color InpChartDownWickColor=clrNONE;           // Optional chart-only down bar/wick color
input string InpDashboardFont="Segoe UI";          // Installed terminal font face
input int InpDashboardFontSize=0;                   // 0 = automatic panel size, otherwise 7..11

input bool InpUseFormingBar=false;                      // Evaluate live forming candle for instant entry
input int InpQuantumERPeriod=20;                       // SuperTrend Engine [Quantum Algo] Kaufman ER period
input double InpQuantumTrendFactor=2.0;                // SuperTrend Engine tight trend ATR factor
input double InpQuantumRangeFactor=4.0;                // SuperTrend Engine wide range ATR factor
input double InpWhipsawShieldATR=0.25;                 // SuperTrend Engine Whipsaw Shield confirmation ATR
input int InpDrmPeriod=14;                             // DRM Strategy momentum regime period
input bool InpUseD1MAFilter=false;                     // UT Bot with D1 MA Length Filter gate
input int InpD1MAPeriod=50;                            // D1 Moving Average filter period
input int InpCoralCoralPeriod=21;                    // Coral Coral/EMA pullback filter period
input double InpDeltaTrapWickRatio=0.45;               // Absorption Reversal Delta Trap minimum wick ratio

input string InpGuardSection="--- StoneGem Smart Guards (server time, all optional, OFF by default) ---";
input bool InpUseWeekdayFilter=false;                  // Only open new trades on the ticked weekdays below
input bool InpTradeMonday=true;
input bool InpTradeTuesday=true;
input bool InpTradeWednesday=true;
input bool InpTradeThursday=true;
input bool InpTradeFriday=true;
input bool InpTradeSaturday=true;
input bool InpTradeSunday=true;
input bool InpUseFridayCutoff=false;                   // No NEW entries on Friday from the cutoff hour
input int InpFridayCutoffHour=20;                      // 0..23 server hour
input bool InpFridayFlatten=false;                     // Also close owned trades on Friday from the flatten hour
input int InpFridayFlattenHour=22;                     // 0..23 server hour (must be >= cutoff hour)
input bool InpUseBlackout1=false;                      // News blackout window 1: no new entries inside window
input string InpBlackout1Start="12:30";                // HH:MM server time
input string InpBlackout1End="13:30";                  // HH:MM server time (may wrap past midnight)
input bool InpUseBlackout2=false;                      // News blackout window 2
input string InpBlackout2Start="18:00";
input string InpBlackout2End="19:00";
input int InpMaxDailyEntries=12;                        // 0 = off. Max accepted entries/pending orders per server day
input double InpDailyProfitTargetPct=0.0;              // 0 = off. Stop new entries once the day gain reaches this % of day-start equity
input bool InpProfitTargetClosesAll=false;             // Also close owned trades when the daily profit target is hit
input string InpAutoThemeSection="--- StoneGem auto day/night theme ---";
input bool InpAutoThemeSwitch=false;                   // Switch dashboard + chart theme by server hour
input SXTheme InpDayTheme=THEME_DIAMOND_PORCELAIN;
input SXTheme InpNightTheme=THEME_STONEGEM_INK;
input int InpDayStartHour=7;                           // 0..23 server hour when the day theme starts
input int InpNightStartHour=19;                        // 0..23 server hour when the night theme starts

input string InpUnlockSection="--- OPTIONAL No-Locks / No-Restrictions (ALL OFF by default, use at your own risk) ---";
input bool InpUnlockAll=false;                         // MASTER: disables every lock, cap, limit and time restriction below
input bool InpNoDailyLossLock=false;                   // Ignore the daily equity-loss lock
input bool InpNoDrawdownLock=false;                    // Ignore the peak-equity drawdown lock
input bool InpNoProfitTargetLock=false;                // Ignore the daily profit-target lock
input bool InpNoPositionCaps=false;                    // Ignore position, portfolio, stop-risk budget and daily-entry caps
input bool InpNoSpreadQuoteLimits=false;               // Ignore spread caps, stale-quote check and spread-shock shield
input bool InpNoTimeRestrictions=false;                // Ignore session, date window, weekday, Friday and blackout rules
input bool InpNoCooldowns=false;                       // Ignore cooldown bars and minimum entry spacing
input bool InpNoLotCap=false;                          // Ignore the EA max-lots cap (broker limits still apply)
input bool InpNoMarginPrecheck=false;                  // Skip the EA free-margin pre-check (broker still enforces margin)
input string InpAdvancedSection="--- Advanced exits and sizing ---";
input bool InpUseFixedTP=true;                        // Attach a take-profit at R x initial stop distance
input double InpFixedTP_R=2.0;                         // Take-profit in R multiples (0.5..20)
input bool InpUseProfitLadder=false;                   // Close parts of the trade at R targets (3 levels)
input double InpLadder1R=1.0;                          // Level 1 target in R
input double InpLadder1Pct=30.0;                       // Level 1 share of ORIGINAL lots to close (0 = skip)
input double InpLadder2R=2.0;
input double InpLadder2Pct=30.0;
input double InpLadder3R=3.0;
input double InpLadder3Pct=0.0;
input int InpMaxHoldBars=0;                            // 0 = off. Close a trade after this many signal-timeframe bars
input bool InpTimeExitOnlyProfitable=false;            // Time exit only when the trade is not losing
input SXRiskBase InpRiskBase=RISKBASE_EQUITY;          // Capital base used for risk-% lot sizing
input double InpDayLossRiskStepPct=0.0;                // 0 = off. Once day loss reaches this %, risk per trade is scaled down
input double InpDayLossRiskStepMult=0.50;              // Risk multiplier applied after the step-down (0.05..1)


input string InpStoneGemDesk="--- StoneGem console and protection ---";
input bool InpShowPanelEmblem=true;
input bool InpShowChartEmblem=true;
input bool InpShowTradeMarkers=true;  // Mark broker-recorded entries on this chart
input bool InpShowChartGrid=true;     // Show the grid while applying chart colours
input int InpMarkOpacity=12;              // Chart watermark opacity, 0..100 percent
input bool InpNoLocks=false;              // Bypass optional equity loss, drawdown and target locks
input bool InpNoRestrictions=false;       // Bypass optional signal filters, limits and session rules
input bool InpPositiveOnlyUpdates=true;   // Only tighten SL past entry and the configured cost cushion
input int InpBELockTicks=1;               // Minimum positive price lock in tradable ticks
input bool InpExtraSpreadCushion=false;   // Add the current spread to the configured profit cushion
input double InpSpreadShockMultiple=3.0;  // Maximum spread / recent quote spread, 0 = off
input double InpBreakBufferATR=0.05;      // Ruby compression confirmation margin
input int InpFixedStopPoints=0;           // Initial SL in broker points, 0 = use ATR
input int InpFixedTargetPoints=0;         // Target in broker points, 0 = use selected TP mode
input int InpTrailStartPoints=0;          // Fixed-point trailing override, 0 = use ATR mode
input int InpTrailGapPoints=0;
input int InpTrailStepPoints=0;

input string InpAdaptiveSection="--- Optional adaptive signal and volatility intelligence ---";
input bool InpUseAdaptiveConfluence=false;          // Optional directional confirmation; disables no existing strategy by default
input int InpAdaptiveMinVotes=3;                  // 1..5 agreement across Kalman, quantum, zero-lag, MACD, EMA
input double InpAdaptiveMinADX=12.0;              // Minimum trend strength when adaptive confluence is enabled
input bool InpUseVolatilityCircuitBreaker=false;  // Optional ATR regime blocker for new orders; open trades still managed
input double InpVolatilityMinATRRatio=0.35;        // Relative ATR floor (current ATR / smoothed ATR)
input double InpVolatilityMaxATRRatio=3.00;       // Relative ATR ceiling; prevents new orders on extreme expansion
input bool InpUseVolatilityRiskAttenuation=true;  // Optional reduce-only position sizing during volatility expansion
input double InpRiskAttenuationStartRatio=1.30;   // Start reducing risk above this relative ATR
input double InpRiskAttenuationFloor=0.35;        // Never reduce by less than 35% of configured risk


enum GemStone {
   GEM_DIAMOND=0,
   GEM_RUBY=1,
   GEM_EMERALD=2,
   GEM_SAPPHIRE=3,
   GEM_CRYSTAL=4,
   GEM_AMETHYST=5,
   GEM_TOPAZ=6,
   GEM_AQUAMARINE=7,
   GEM_GARNET=8,
   GEM_OPAL=9,
   GEM_JADE=10,
   GEM_CITRINE=11
};
enum GemStopMode {
   STOP_ATR=0,
   STOP_CANDLE=1,
   STOP_SWING=2,
   STOP_PERCENT=3
};
input string InpGemStudySection="--- Gemstone signal studies ---";
input int InpBuyATRLength=10;          // Dual UT long ATR period
input int InpSellATRLength=14;         // Dual UT short ATR period
input double InpBuySensitivity=1.0;   // Long ATR factor, zero disables
input double InpSellSensitivity=1.5;  // Short ATR factor, zero disables
input int InpRegressionLength=14;     // Least-squares candle window
input bool InpMatrixDMI=true;
input bool InpMatrixVwapSlope=true;
input double InpMinVwapSlopeATR=0.0;
input double InpMaxVwapDistanceATR=3.0; // Zero disables
input bool InpMatrixCandle=true;
input double InpMinCandleBodyATR=0.10;
input double InpRouterEfficiency=0.35;
input double InpRouterExpansion=1.20;
input GemStopMode InpInitialStopMode=STOP_ATR;
input double InpStopBufferATR=0.15;
input int InpStopSwingBars=8;
input double InpStopPercent=0.75;
input string InpStudioSection="--- Robot colour studio ---";
input GemStone InpPrimaryGem=GEM_DIAMOND;
input GemStone InpAccentGem=GEM_RUBY;
input int InpWatermarkPixels=258;
input bool InpShowRegressionCandles=false;
input bool InpShowOrderLevels=true;

input string InpContextSection="--- Entry quality and regime confluence ---";
input bool InpUseCostGate=true;        // Automatic entries: compare costs to the target distance
input double InpMaxCostPctOfTarget=18; // Maximum estimated round-trip cost as % of target (or 1R)
input double InpExtraCostPoints=0;     // Estimated commission + slippage beyond the spread, in points
input bool InpUseShockPause=true;     // Pause new entries after an abnormal true-range shock
input int InpShockLookback=30;        // Closed bars used to measure shocks (10-100)
input int InpShockPauseBars=2;        // Bars to pause after a shock (1-10)
input int InpClockAttemptsPerBar=3;   // Maximum entry attempts per candle
input double InpShockMultiple=3.0;     // True range / median of the 21 preceding closed true ranges
input bool InpSharedShockBaseline=false; // Use one baseline ending before the entire recent window

int g_logoMode=0;
color g_logoInk[10],g_logoCache[3][9];
int g_logoSize[3],g_logoAlpha[3],g_logoPart=0;
string g_logoNote="Enter #RRGGBB and press Enter.";
long g_previousForeground=0,g_previousMode=0,g_previousVolumes=0;
double g_slowUT[];
int g_proEvents[];
struct GemSnapshot {
   int primaryUT,secondaryUT,utLastSide,utLastAge,utH1,utH4,utD1;
   double utLastMove,utDistance;
   bool utStrong;
   double fitScore; int scalpUp,scalpDown;
   double pathEfficiency,priorHist,turnLow,turnHigh,targetScale;
   int horizonSide,regimeVotes;
   double plusDI,minusDI,ema200,fast,barLow,barHigh,swingLow,swingHigh;
   double lrOpen,lrClose,lrSlope,vwapSlope,buyTrail,sellTrail,largestShock;
   int positiveVotes,negativeVotes,route,contextMode,contextVotes;
   string buyFilter,sellFilter;
   bool sameSession,shockReady,droidExitLong,droidExitShort;
   string droidState;
   double droidVW,droidStop,droidUpper,droidLower,droidHist,droidHistPrev,droidAdxPrev;
   int droidOldTrend;
};
GemSnapshot g_gem;
int g_primaryGem=0,g_accentGem=1;
bool g_regOverlay=false;

bool g_watermark=true,g_layers=true,g_strip=false,g_noLocks=false,g_noRestrictions=false;
bool g_breakEven=true,g_positiveOnly=true,g_savedColours=false;
int g_lastLayout=-1,g_pageOffset=0;
int g_catalogCursor=0;
datetime g_catalogDone=0;
double g_beTrigger=1.0,g_beLock=0.1,g_trStart=1.5,g_trGap=1.0,g_trStep=0.1;
int g_lockTicks=1;
double g_consoleScale=1.0,g_cachedFast=0,g_cachedSlow=0,g_cachedAtrPrior=0,g_prevLo=0,g_prevHi=0,g_lo8=0,g_hi8=0;
ENUM_CHART_PROPERTY_INTEGER g_chartCols[8];
long g_previousCols[8],g_previousGrid=0;

struct SXPosition {
   datetime opened;
   ulong ticket;
   int direction;
   double lots, open, sl, tp, profit;
};
struct SXZone {
   datetime formed;
   double lower, upper;
   int direction, bar;
   bool filled;
};

MqlRates g_rates[];
double g_atrSeries[],g_utSeries[],g_fastSeries[],g_slowSeries[];
double g_zeroSeries[];
SXZone g_zones[];
SXPosition g_positions[];
ENUM_TIMEFRAMES g_tf;
string g_prefix="",g_key="",g_message="Starting",g_log[8];
int g_n=0,g_zoneCount=0,g_raw=0,g_candidate=0,g_lastSignalDir=0;
int g_scoreBuy=0,g_scoreSell=0,g_mtf[5],g_tf1=0,g_tf2=0,g_tab=0;
int g_zeroTrend=0;
int g_x=12,g_y=24,g_size=1,g_width=380,g_line=22,g_font=10;
bool g_auto=true,g_trailing=true,g_right=false,g_collapsed=false,g_consoleReady=false;
bool g_dailyLock=false,g_peakLock=false,g_uncertain=false,g_tester=false;
bool g_dayAnchored=false;
datetime g_lastClosed=0,g_consoleLastSignalTime=0,g_lastMTF=0,g_lastPaint=0,g_resetArmed=0;
double g_atr=0,g_rsi=50,g_adx=0,g_macd=0,g_sma=0,g_volumeRatio=0;
double g_breakHigh=0,g_breakLow=0,g_pdh=0,g_pdl=0,g_pwh=0,g_pwl=0;
double g_pivot=0,g_r1=0,g_s1=0,g_dayOpen=0;
double g_dayEquity=0,g_consolePeakEquity=0,g_dayLoss=0,g_drawdown=0,g_manualLots=0;
int g_dayCode=0;
color SX_BG=C'16,23,35',SX_CARD=C'25,36,51',SX_EDGE=C'55,71,91';
color SX_TEXT=C'224,232,240',SX_MUTED=C'145,164,184',SX_GOLD=C'235,191,91';
color SX_GREEN=C'52,207,151',SX_RED=C'246,98,113',SX_BLUE=C'78,158,244';
color SX_ZONE_BULL=C'24,65,58',SX_ZONE_BEAR=C'73,35,49',SX_GRID=C'55,71,91',SX_VOLUME=C'78,158,244';

string g_symbol="",g_chartSymbol="",g_guardKey="";
double g_consolePoint=0.00001; int g_consoleDigits=5;
SXStrategy g_consoleStrategy=UT_CONFLUENCE;
SXAssets g_assetMode=ASSET_CHART;
int g_active=0,g_cursor=0,g_scanPage=0,g_enginePage=0;
string g_snapshotSymbol="";
double g_utCurrent=0,g_closeCurrent=0,g_vwap=0,g_superLine=0,g_superUpper=0,g_superLower=0;
double g_stc=0,g_cci=0,g_stoch=50,g_atrRatio=1,g_bandUpper=0,g_bandLower=0,g_basketPeak=0,g_basketLots=0;
int g_superDir=0,g_engineSignals[SG_ENGINE_COUNT];
double g_quantumER=0.5,g_quantumFactor=3.0,g_quantumSuperLine=0,g_drmValue=0,g_d1MA=0,g_coralEMA=0,g_openAnchor=0;
int g_quantumSuperDir=1,g_whipsawsShielded=0,g_deltaTrapSig=0,g_stopPaddingPts=0;
int g_consoleTheme=0,g_themeStyle=1,g_trailMode=0,g_stopStage=1;
bool g_profitLock=false; int g_autoPhase=-1; string g_guardWhy="";
double g_rrTrail=0,g_rrEMA=0,g_hull=0,g_tenkan=0,g_kijun=0,g_spanB=0,g_mfi=50,g_obv=0;
double g_kalman=0,g_kalmanPrev=0,g_velocity=0,g_orderFlowDelta=0;
int g_rrCross=0,g_rrState=0,g_ensembleVotes=0,g_ensembleActive=0,g_ensembleDir=0,g_kalmanDir=0;
double g_ensembleConfidence=0;
double g_vwapSeries[],g_superSeries[],g_stcSeries[],g_rsiSeries[];
int g_utEvents[],g_superDirections[];
datetime g_closePortArmed=0;


//====================================================================
// CVT LT DRIOD BOT NO ERRORS EA INTELLIGENT CONTROL CORE : enums, inputs, state
//====================================================================
enum XeonThemePreset {
   XE_THEME_ANDROID_CURE_EMERALD = 0,  // Android Cure Emerald
   XE_THEME_BIONIC_PULSE_CYAN = 1,     // Bionic Pulse Cyan
   XE_THEME_CARBON_GOLD_PRO = 2,       // Carbon Gold Pro
   XE_THEME_CYBER_VIOLET_NEON = 3,     // Cyber Violet Neon
   XE_THEME_MIDNIGHT_PULSE = 4,        // Midnight Pulse
   XE_THEME_OCEAN_ABYSS = 5,           // Ocean Abyss
   XE_THEME_LIGHT_MINT_CLINICAL = 6,   // Light Mint Clinical
   XE_THEME_SOLAR_AMBER_MATRIX = 7,    // Solar Amber Matrix
   XE_THEME_CRIMSON_OVERDRIVE = 8,     // Crimson Overdrive
   XE_THEME_ARCTIC_TITANIUM = 9,       // Arctic Titanium
   XE_THEME_EMERALD_CIRCUIT = 10,      // Emerald Circuit
   XE_THEME_QUANTUM_OBSIDIAN = 11,     // Quantum Obsidian
   XE_THEME_NEON_SYNTHWAVE = 12,       // Neon Synthwave
   XE_THEME_ROYAL_COBALT = 13,         // Royal Cobalt
   XE_THEME_BIO_HAZARD_LIME = 14,      // Bio-Hazard Lime
   XE_THEME_PLATINUM_STEALTH = 15,     // Platinum Stealth
   XE_THEME_SAKURA_NEON_PINK = 16,     // Sakura Neon Pink
   XE_THEME_AURORA_BOREALIS = 17,      // Aurora Borealis
   XE_THEME_DESERT_SAND_QUARTZ = 18,   // Desert Sand Quartz
   XE_THEME_VOLCANIC_EMBER = 19,       // Volcanic Ember
   XE_THEME_DEEP_SPACE_INDIGO = 20,    // Deep Space Indigo
   XE_THEME_MINT_CHOCOLATE = 21,       // Mint Chocolate
   XE_THEME_SAPPHIRE_ICE = 22,         // Sapphire Ice
   XE_THEME_RETRO_TERMINAL_GREEN = 23, // Retro Terminal Green
   XE_THEME_ROSE_GOLD_LUXE = 24,       // Rose Gold Luxe
   XE_THEME_TOXIC_PURPLE = 25,         // Toxic Purple
   XE_THEME_STEEL_BLUE_CORPORATE = 26, // Steel Blue Corporate
   XE_THEME_SUNSET_HORIZON = 27,       // Sunset Horizon
   XE_THEME_MATRIX_RAIN = 28,          // Matrix Rain
   XE_THEME_CANDY_POP_BUBBLEGUM = 29,  // Candy Pop Bubblegum
   XE_THEME_BLACK_GOLD_ROYALE = 30,    // Black Gold Royale
   XE_THEME_GLACIER_DAY = 31,          // Glacier Day
   XE_THEME_CYBER_RUBY_NOIR = 32,      // Cyber Ruby Noir
   XE_THEME_TIDAL_TEAL = 33,           // Tidal Teal
   XE_THEME_LAVENDER_DREAM = 34,       // Lavender Dream
   XE_THEME_GOLDEN_HOUR = 35,          // Golden Hour
   XE_THEME_FOREST_CANOPY = 36,        // Forest Canopy
   XE_THEME_NEON_TOKYO = 37,           // Neon Tokyo
   XE_THEME_FROST_BITE = 38,           // Frost Bite
   XE_THEME_COPPER_CIRCUIT = 39,       // Copper Circuit
   XE_THEME_MIDNIGHT_ORCHID = 40,      // Midnight Orchid
   XE_THEME_LAVA_LAMP = 41,            // Lava Lamp
   XE_THEME_ICE_MINT_DAY = 42,         // Ice Mint Day
   XE_THEME_OBSIDIAN_EMERALD = 43,     // Obsidian Emerald
   XE_THEME_ELECTRIC_LIME_POP = 44,    // Electric Lime Pop
   XE_THEME_SILVER_MOON = 45,          // Silver Moon
   XE_THEME_CORAL_REEF = 46,           // Coral Reef
   XE_THEME_COSMIC_LATTE = 47,         // Cosmic Latte
   XE_THEME_XEON_PLASMA_CYAN = 48,     // Xeon Plasma Cyan
   XE_THEME_XEON_DROID_NEON = 49,      // Xeon Droid Neon
   XE_THEME_HYPERION_GOLD_BLACK = 50,  // Hyperion Gold Black
   XE_THEME_KRONOS_DARK_OBSIDIAN = 51, // Kronos Dark Obsidian
   XE_THEME_NEURO_MATRIX_EMERALD = 52, // Neuro Matrix Emerald
   XE_THEME_QUANTUM_VIOLET_PULSE = 53, // Quantum Violet Pulse
   XE_THEME_ARCTIC_FROST_GLASS = 54,   // Arctic Frost Glass
   XE_THEME_BRIMSTONE_MAGMA_RED = 55,  // Brimstone Magma Red
   XE_THEME_TITANIUM_CYBER_CHROME = 56,// Titanium Cyber Chrome
   XE_THEME_SOLARIS_AMBER_FORGE = 57,  // Solaris Amber Forge
   XE_THEME_SAPPHIRE_DEEP_SPACE = 58,  // Sapphire Deep Space
   XE_THEME_EMERALD_BIO_PULSE = 59,    // Emerald Bio-Pulse
   XE_THEME_CRIMSON_SAMURAI_NOIR = 60, // Crimson Samurai Noir
   XE_THEME_COBALT_HOLOGRAM = 61,      // Cobalt Hologram
   XE_THEME_ROSE_QUARTZ_CYBER = 62,    // Rose Quartz Cyber
   XE_THEME_DAYLIGHT_CLINICAL_PRO = 63, // Daylight Clinical Pro
   XE_THEME_VECTOR_EMERALD_PRIME = 64, // Emerald Prime
   XE_THEME_VECTOR_ROYAL_SAPPHIRE = 65, // Royal Sapphire Console
   XE_THEME_AETHER_CYBER_TEAL = 66, // Aether Cyber Teal
   XE_THEME_PLASMA_MAGENTA_PULSE = 67, // Plasma Magenta Pulse
   XE_THEME_OBSIDIAN_TITANIUM_GOLD = 68, // Obsidian Titanium Gold
   XE_THEME_NORDIC_FROST_LIGHT = 69, // Nordic Frost Light
   XE_THEME_TOKYO_DRIFT_CRIMSON = 70, // Tokyo Drift Crimson
   XE_THEME_JADE_DRAGON_MATRIX = 71, // Jade Dragon Matrix
   XE_THEME_VELVET_AMETHYST_NIGHT = 72, // Velvet Amethyst Night
   XE_THEME_SOLARIS_COPPER_GLOW = 73, // Solaris Copper Glow
   XE_THEME_ARCTIC_AURORA_MINT = 74, // Arctic Aurora Mint
   XE_THEME_MONOLITH_SLATE_PRO = 75, // Monolith Slate Pro
   XE_THEME_IVORY_EXECUTIVE_DAY = 76, // Ivory Executive Day
   XE_THEME_ULTRAVIOLET_QUANTUM = 77, // Ultraviolet Quantum
   XE_THEME_COBALT_LIGHTNING = 78, // Cobalt Lightning
   XE_THEME_EMERALD_VELVET_NOIR = 79, // Emerald Velvet Noir
   XE_THEME_SUNSET_CORAL_NEON = 80, // Sunset Coral Neon
   XE_THEME_CHAMPAGNE_PEARL_LIGHT = 81, // Champagne Pearl Light
   XE_THEME_CYBERPUNK_ACID_LIME = 82, // Cyberpunk Acid Lime
   XE_THEME_DEEP_OCEAN_BIOLUME = 83, // Deep Ocean Biolume
   XE_THEME_RUBY_OBSIDIAN_LUXE = 84, // Ruby Obsidian Luxe
   XE_THEME_NEON_AQUA_PINK = 85, // Neon Aqua Pink
   XE_THEME_MOCHA_CREAM_DAY = 86, // Mocha Cream Day
   XE_THEME_STARLIGHT_INDIGO_PULSE = 87, // Starlight Indigo Pulse
   XE_APEX_DROID_ELECTRIC_CYAN = 88, // Droid Electric Cyan
   XE_APEX_DROID_MATRIX_PULSE = 89, // Droid Matrix Pulse
   XE_APEX_DROID_CYBER_GOLD = 90, // Droid Cyber Gold
   XE_APEX_DROID_NEON_VIOLET = 91, // Droid Neon Violet
   XE_APEX_DROID_EMERALD_GRID = 92, // Droid Emerald Grid
   XE_APEX_DROID_PLASMA_RED = 93, // Droid Plasma Red
   XE_APEX_DROID_DEEP_OCEAN = 94, // Droid Deep Ocean
   XE_APEX_DROID_TITANIUM_ICE = 95, // Droid Titanium Ice
   XE_APEX_DROID_SOLAR_FLARE = 96, // Droid Solar Flare
   XE_APEX_DROID_MIDNIGHT_COBALT = 97, // Droid Midnight Cobalt
   XE_APEX_DROID_HOLOGRAM_MINT = 98, // Droid Hologram Mint
   XE_APEX_DROID_CRIMSON_FORGE = 99, // Droid Crimson Forge
   XE_APEX_DROID_SAKURA_CYBER = 100, // Droid Sakura Cyber
   XE_APEX_DROID_OBSIDIAN_LIME = 101, // Droid Obsidian Lime
   XE_APEX_DROID_ROYAL_AMETHYST = 102, // Droid Royal Amethyst
   XE_APEX_DROID_DAYLIGHT_FROST = 103 // Droid Daylight Frost
};

enum XeonLogoPalette {
   XE_LOGO_AUTO_THEME = 0,       // Auto (matches active theme)
   XE_LOGO_ANDROID_CURE = 1,     // Android Cure Emerald
   XE_LOGO_XEON_PLASMA = 2,      // Xeon Plasma Cyan
   XE_LOGO_HYPERION_GOLD = 3,    // Hyperion Gold
   XE_LOGO_CYBER_VIOLET = 4,     // Cyber Violet
   XE_LOGO_CRIMSON_PULSE = 5,    // Crimson Pulse
   XE_LOGO_ARCTIC_ICE = 6,       // Arctic Ice
   XE_LOGO_HOLOGRAM_MINT = 7,    // Hologram Mint
   XE_LOGO_SUNSET_CORAL = 8,     // Sunset Coral
   XE_LOGO_ROSE_QUARTZ = 9,      // Rose Quartz
   XE_LOGO_ROYAL_SAPPHIRE = 10,  // Royal Sapphire
   XE_LOGO_BIO_LIME = 11         // Bio-Hazard Lime
};

input string           XE_Sec_Apex          = "=== PORTFOLIO ENTRY AND EXIT FILTERS ===";
input double           XE_GivebackStartR    = 1.0;   // Giveback / Apex trail: start keeping peak profit from this R
input double           XE_GivebackKeepMinPct= 35.0;  // Giveback / Apex trail: share of peak profit kept at the start (%)
input double           XE_GivebackKeepMaxPct= 80.0;  // Giveback / Apex trail: share of peak profit kept at +5R and beyond (%)
input bool             XE_EnableAntiFomo    = false;  // Anti-FOMO guard: no entry after a long run of same-direction candles
input int              XE_FomoMaxStreak     = 5;     // Anti-FOMO: block when this many straight candles already ran (0 = off)
input bool             XE_EnableATRExpansion= false;  // ATR expansion guard: block entries during volatility spikes and stop-hunts
input double           XE_ATRExpansionMult  = 1.30;  // ATR expansion: block when 5-bar range exceeds this multiple of its average (0 = off)
input int              XE_ATRExpansionBars  = 50;    // ATR expansion: bars in the historical average (10-300)
input bool             XE_EnableHTFBias     = false;  // Higher-timeframe 200 EMA bias gate: trade only with the HTF trend
input ENUM_TIMEFRAMES  XE_HTFBiasTF         = PERIOD_H1; // HTF bias timeframe
input int              XE_HTFEmaLen         = 200;   // HTF bias EMA length (20-500)
input double           XE_HTFAdxMin         = 18.0;  // Minimum ADX at entry for the HTF bias gate (0 = off)
input bool             XE_EnableSessionHarvest = false; // Session harvest: attempt to close primary-symbol winners once per day at the hour below
input int              XE_HarvestHour       = 21;    // Session harvest hour (broker server time, 0-23)
datetime g_xeHtfStamp=0;
double g_xeHtfEma=0,g_xeHtfClose=0;
int    g_xeHarvestDay=0;
enum XeonPosTrailMode {
   XE_TRAIL_POSITIVE_PULSE   = 0,  // Smart Positive ATR Ratchet (never widens)
   XE_TRAIL_CURE_TIERED_LOCK = 1,  // Tiered Positive Profit Guard (+1R/+2R/+3R/+4R)
   XE_TRAIL_KALMAN_VELOCITY  = 2,  // Kalman Velocity Positive Lock
   XE_TRAIL_POSITIVE_TP_EXT  = 3,  // Positive Trail + Dynamic TP Runner
   XE_TRAIL_CHANDELIER_POS   = 4,  // Positive Chandelier (8-bar extreme)
   XE_TRAIL_SWING_POS        = 5,  // Positive Swing Structure Lock
   XE_TRAIL_REGIME_ADAPTIVE  = 6,  // Regime-Adaptive Positive Ratchet
   XE_TRAIL_ACCELERATING     = 7,  // Accelerating Positive Ratchet (tightens as R grows)
   XE_TRAIL_FIB_LADDER       = 8,  // Fibonacci Profit Ladder (38 / 50 / 62 / 79%)
   XE_TRAIL_SQUEEZE_AWARE    = 9,  // Squeeze-Aware Positive Guard (volatility adaptive)
   XE_TRAIL_MOMENTUM_FADE    = 10, // Momentum-Fade Positive Lock (confluence adaptive)
   XE_TRAIL_SMART_HYBRID     = 11, // Smart Hybrid Max-Lock (ATR + Fib + Momentum)
   XE_TRAIL_NEURO_STRUCTURE  = 12, // Neuro Structure Positive (IQ-weighted swing floor)
   XE_TRAIL_TIME_DECAY_POS   = 13, // Time-Decay Positive Lock (tightens with bar age)
   XE_TRAIL_REVERSAL_SHIELD  = 14, // Reversal Shield Positive (snaps tight on reversal)
   XE_TRAIL_STEP_LADDER_POS  = 15, // Profit Step-Ladder Positive (+0.5R stair steps)
   XE_TRAIL_KRONOS_BASKET    = 16, // Kronos Positive Basket Lock (portfolio-aware)
   XE_TRAIL_GOLD_TURBO_POS   = 17, // Gold Reaper Turbo Positive (high-beta fast lock)
   XE_TRAIL_ICHIMOKU_TENKAN  = 18, // Ichimoku Tenkan Positive (9-bar mid-range floor)
   XE_TRAIL_XEON_QUANTUM_MAX = 19, // Quantum Max-Lock (strictly highest positive floor)
   XE_TRAIL_BASICO_PEAK_LOCK = 20, // Peak-Excursion Positive Lock (30%-85% peak + momentum-fade bonus)
   XE_TRAIL_VECTOR_VELOCITY  = 21, // Vector Velocity Positive Ratchet (velocity-adaptive ATR + R floor)
   XE_TRAIL_SUPER_VWAP_POS   = 22, // SuperTrend + VWAP Institutional Positive Anchor
   XE_TRAIL_VECTOR_APEX = 23, // Vector Apex Omni
   XE_TRAIL_ADAPTIVE_APEX = 24, // Adaptive Apex Lock
   XE_TRAIL_GIVEBACK = 25, // Giveback Governor
   XE_TRAIL_UT_EXTREME = 26 // UT Positive Chandelier
};

input string           XE_Sec_Core          = "=== CVT LT DRIOD BOT NO ERRORS INTELLIGENT CORE ===";
input bool             XE_ApplyTheme        = true;  // Use Vector 104 colour themes (off = classic theme inputs)
input XeonThemePreset  XE_ColorTheme        = XE_THEME_VECTOR_EMERALD_PRIME; // Vector Colour Theme (104 themes)
input XeonLogoPalette  XE_LogoColor         = XE_LOGO_AUTO_THEME;        // Cute Android Robot Logo Colour Palette
input bool             XE_ShowCureRobotLogo = true;  // Show cute Android robot logo on dashboard
input bool             XE_ChartWatermark    = true;  // Show cute Android robot watermark on chart
input bool             XE_ShowControlDeck   = true;  // Show Vector Control Deck (16 indicators + 42 controls)
input bool             XE_EnableDragMove    = true;  // Enable drag-to-move for ALL dashboards (grab header)
input int              XE_MainScalePct      = 100;   // Main Dashboard scale (65-150 %)
input int              XE_DeckScalePct      = 100;   // Control Deck scale (65-150 %)
input int              XE_DeckX             = -1;    // Control Deck X (-1 = auto dock right)
input int              XE_DeckY             = 34;    // Control Deck Y
input int              XE_WatermarkPixels   = 220;   // Chart robot watermark size (px)
input string           XE_Sec_Trail         = "=== SMART POSITIVE TRAILING SL & TP ===";
input bool             XE_EnablePosTrail    = true;  // Enable Smart Positive Trailing SL
input XeonPosTrailMode XE_PosTrailMode      = XE_TRAIL_VECTOR_APEX; // Smart Positive Trailing Mode (27 modes)
input double           XE_PosBE_TriggerR    = 0.75;  // Positive Breakeven Trigger (R-multiple)
input double           XE_PosBE_LockR       = 0.15;  // Positive Breakeven Lock (+R above entry)
input double           XE_PosATR_Mult       = 1.30;  // Positive ATR Ratchet Multiplier
input double           XE_PosStep_MinPts    = 12.0;  // Minimum Ratchet Step (points, anti-spam)
input bool             XE_EnablePosTP_Trail = true;  // Positive Trailing Take-Profit runner
input double           XE_PosTP_NearR       = 0.35;  // TP runner: extend when TP is within this many R
input double           XE_PosTP_ExtendR     = 0.60;  // TP runner: extension size (R)
input bool             XE_EnableSmartPartial= false; // Smart partial close
input double           XE_PartialR          = 1.0;   // Partial close trigger (R)
input double           XE_PartialPct        = 40.0;  // Partial close size (% of position)
input bool             XE_EnableKronosBasket= true;  // Kronos Positive Basket Lock (locks symbol basket profit)
input double           XE_BasketTriggerUSD  = 80.0;  // Kronos Basket trigger profit (account currency)
input double           XE_BasketKeepPct     = 55.0;  // Kronos Basket trailing keep floor (% of peak profit)
input string           XE_Sec_Intel         = "=== INTELLIGENT FILTERS & GUARDS ===";
input bool             XE_EnableRegimeAI    = true;  // Regime AI (Range / Trend / Breakout / High-Vol)
input bool             XE_BlockHighVol      = true;  // Block new entries in High-Vol regime
input bool             XE_EnableConfluence  = true;  // 16-indicator confluence gate
input double           XE_MinConfluence     = 20.0;  // Minimum confluence score for entries (0-100)
input double           XE_SpikeGuardATR     = 3.0;   // Spike guard: block after bar > N x ATR (0 = off)
input bool             XE_EnableEquityThrot = true;  // Equity-curve throttle (scales lots, floor 25%)
input double           XE_MaxSpreadPts      = 35.0;  // Smart spread guard (points, 0 = off)
input double           XE_DailyDDShieldPct  = 4.0;   // Daily drawdown shield (% of day-start equity, 0 = off)
input bool             XE_ShieldClosesAll   = false; // Shield also closes open positions
input string           XE_Sec_Smart         = "=== CVT LT DRIOD BOT NO ERRORS SMART IQ & NEW INTELLIGENT FUNCTIONS ===";
input bool             XE_EnableIQGate      = true;  // Smart IQ gate: weighted 0-100 directional quality score
input int              XE_MinIQScore        = 45;    // Minimum Smart IQ score for automatic entries (0-100)
input bool             XE_EnableSmartSizing = true;  // Smart sizing: lots follow IQ and regime, never above base risk
input double           XE_MinRiskMult       = 0.20;  // Smart sizing floor (0.05-1.00)
input bool             XE_EnableExhaustGuard= true;  // Exhaustion guard: no chasing stretched RSI + Bollinger extremes
input double           XE_ExhaustRSI        = 78.0;  // Exhaustion RSI threshold
input bool             XE_EnableSpacingGuard= true;  // Entry spacing guard: minimum gap after an owned position opens
input int              XE_SpacingMinutes    = 2;     // Entry spacing in minutes (0 = off)
input bool             XE_EnableProfitLock  = true;  // Daily profit lock: stop new entries once daily target is met
input double           XE_DailyProfitLockPct= 5.0;   // Daily profit target (% of day-start equity, 0 = off)
input bool             XE_EnableTickVeto    = true;  // Tick Quote-Pressure Veto: block opposing microstructure bursts
input bool             XE_EnableMTFAlign    = true;  // MTF Alignment Gate (M5/M15/M30/H1/H4 trend consensus)
input int              XE_MinMTFScore       = 20;    // Minimum MTF alignment score for automatic entries (0-100)
input bool             XE_EnableStreakGuard = true;  // Consecutive-Loss Streak Guard (throttle/pause after tilt)
input int              XE_MaxConsecLosses   = 4;     // Max consecutive losses before Streak Guard engages
input bool             CT_EnableNetEdge     = true;  // Net-Edge Cost Filter: require minimum reward-to-spread edge
input double           CT_MinRewardSpread   = 3.5;   // Minimum TP distance / spread ratio for auto entries
input bool             CT_EnableMomFadeBE   = true;  // Momentum-Fade Early Positive BE (4-vote fade detector)
input bool             CT_EnableSessionIQ   = false; // Session Liquidity Window Filter (server hours)
input int              CT_SessionStartHour  = 7;     // Session start hour (0-23)
input int              CT_SessionEndHour    = 20;    // Session end hour (0-23)

input bool             XE_EnableSessionAI   = true;  // Smart Session AI: restrict auto entries to active liquidity hours
input int              XE_SessionStartHour  = 7;     // Smart Session start hour (broker server time, 0-23)
input int              XE_SessionEndHour    = 21;    // Smart Session end hour (broker server time, 0-23)
input bool             XE_EnableSpreadATR   = true;  // Smart Spread-to-ATR Cost Filter (block costly low-vol chop)
input double           XE_MaxSpreadATRPct   = 18.0;  // Max allowed spread as % of current ATR (0 = off)
input bool             XE_EnableSmartBoost  = true;  // Smart Profit-Curve Confidence Recovery (capped <= 1.0x base risk)
input string           XE_Sec_Guard       = "=== CVT LT DRIOD BOT NO ERRORS PORTFOLIO GUARD ===";
input bool             XE_EnableEqTrailLock = true;  // Trailing equity lock: stop new entries after giving back part of the day's peak gain
input double           XE_EqTrailArmPct     = 2.0;   // Equity lock arms once day gain reaches this % of day-start equity (0 = off)
input double           XE_EqTrailKeepPct    = 60.0;  // Lock when day gain falls below this % of its peak (10-95)
input bool             XE_EqTrailClosesAll  = false; // Equity lock also closes owned exposure (off = only blocks new entries)
input bool             XE_EnableExposureCap = true;  // Currency stack cap: limits correlated same-currency exposure across all symbols (this magic)
input int              XE_MaxCurrencyStack  = 3;     // Max same-direction positions loading one currency, e.g. long USD x3 (0 = off)
input bool             XE_EnableMarginGuard = true;  // Margin-level guard for new entries
input double           XE_MinMarginLevelPct = 300.0; // Block new entries while margin level is below this % (0 = off)
input bool             XE_EnableTimeBE      = true;  // Stale-trade breakeven: lock a small profit on trades that stall in profit
input int              XE_TimeBEBars        = 12;    // Bars (signal timeframe) a trade must be open before the stale-trade BE can act (1-500)
input double           XE_TimeBEMinR        = 0.50;  // Minimum open profit, in R, before the stale-trade BE moves the stop
input double           XE_TimeBELockR       = 0.05;  // Profit locked above entry + costs, in R (0-0.50)
input bool             XE_EnableVolAdaptSL  = false; // Volatility-adaptive initial SL/TP (ATR regime scales the ATR stop; TP follows R)
input double           XE_VolAdaptMinMult   = 0.80;  // Adaptive SL lower clamp (0.50-1.00)
input double           XE_VolAdaptMaxMult   = 1.35;  // Adaptive SL upper clamp (1.00-2.00)
input int              XE_DeckStartPage     = 0;     // Control Deck page at start: 0 Signals,1 Trail,2 Smart,3 Actions,4 Theme,5 Guard

bool   g_xeEqTrailOn=true,g_xeExpoOn=true,g_xeMarginOn=true,g_xeTimeBEOn=true,g_xeVolSLOn=false;
bool   g_xeEqLocked=false,g_xeEqFired=false;
int    g_xeEqDay=0,g_xeOwnedTotal=0,g_xeTimeBECount=0;
double g_xeEqPeakGain=0,g_xeVolMult=1.0;
string g_xeTopCcy="--",g_xeGuardWhy="";
int    g_xeTopStack=0;
bool g_xeBoostOn=true,g_xeSessOn=true,g_xeSpAtrOn=true;
int    g_bpTheme=64,g_bpTrailMode=23,g_bpRegime=0,g_bpLayout=0,g_bpX=0,g_bpY=0,g_bpDay=0,g_xeLogoPal=0;
bool   g_bpTrailOn=true,g_bpTPOn=true,g_bpRegimeOn=true,g_bpThrottleOn=true,g_bpConfOn=true,g_bpPartialOn=false;
bool   g_bpShieldOn=true,g_bpManualTrade=false,g_bpCollapsed=false,g_bpRobotOn=true,g_bpWM=true,g_bpShieldFired=false;
bool   g_xeTickVetoOn=true,g_xeMTFOn=true,g_xeStreakOn=true,g_xeBasketOn=true;
double g_bpScore=0,g_bpER=0,g_bpVolRatio=1,g_bpSpike=0;
int    g_bpVote[16];
string g_bpVal[16];
string g_bpIndName[16]={"EMA","RSI","MACD","ADX","STOCH","CCI","BAND","ER","SUPER","MFI","VWAP","KALMAN","TENKAN","AROON","WILL%R","MTF"};
int    g_xeMTFVote[5];
string g_xeMTFName[5]={"M5","M15","M30","H1","H4"};
double g_xeMTFScore=0;
double g_xeLastBid=0,g_xeTickEMA=0;
int    g_xeTickDir=0,g_xeConsecLoss=0;
double g_xeBasketPeak=0;
bool   g_xeBasketArmed=false;
bool   g_bpIQOn=true,g_bpSizeOn=true,g_bpExhaustOn=true,g_bpSpaceOn=true,g_bpProfitOn=true;
int    g_bpPage=0,g_bpScalePct=100;
double g_bpPB=0.5,g_bpDayGain=0,g_bpSizeMult=1.0;
string g_bpBadgeKey="";
string g_bpRegimeName[4]={"RANGE","TREND","BREAKOUT","HIGH-VOL"};
string g_bpTrailName[27]={
   "Positive ATR Ratchet","Tiered Profit Guard","Kalman Velocity Lock","Trail + TP Runner",
   "Positive Chandelier","Swing Structure Lock","Regime-Adaptive","Accelerating Ratchet",
   "Fibonacci Ladder","Squeeze-Aware Guard","Momentum-Fade Lock","Smart Hybrid Max-Lock",
   "Neuro Structure Pos","Time-Decay Pos Lock","Reversal Shield Pos","Profit Step-Ladder",
   "Kronos Basket Lock","Gold Reaper Turbo","Ichimoku Tenkan Pos","Quantum Max-Lock",
   "Peak-Excursion Pos","Vector Velocity Pos","SuperTrend+VWAP Pos","Vector Apex Omni",
   "Adaptive Apex Lock","Giveback Governor","UT Positive Chandelier"
};
string g_xeLogoName[12]={"Auto Theme","Android Cure","Plasma Cyan","Hyperion Gold","Cyber Violet","Crimson Pulse","Arctic Ice","Hologram Mint","Sunset Coral","Rose Quartz","Royal Sapphire","Bio-Hazard Lime"};
string g_bpRobotKey="",g_bpWMKey="";
datetime g_bpPanicArmed=0;
bool   g_xeMainCustomPos=false,g_xeDeckCustomPos=false,g_xePrevMouseDown=false,g_xeSavedScroll=true;
int    g_xeMainX=12,g_xeMainY=18,g_xeMainScalePct=100,g_xeMainW=390,g_xeMainH=444,g_xeMainHeadH=46;
int    g_xeDeckX=12,g_xeDeckY=34,g_xeDeckW=344,g_xeDeckH=456,g_xeDeckHeadH=76;
int    g_xeDragTarget=0,g_xeDragOffX=0,g_xeDragOffY=0;
void   XEHandleMouseMove(int mx,int my,uint flags);
void   XEResetAllDashboards();
bool   CTMomentumFading(int direction);
bool   CTSessionAllowed();

string BPThemeName(int i);
void   BPLoadTheme(int i);
void   BPInitState();
void   BPRefreshIntel();
bool   BPEntryGate(int direction,string &why);
double BPThrottle();
double RiskLotsCore(int direction,double price,double sl,bool manual);
double BPRiskLots(int direction,double price,double sl,bool manual);
int    BPIQ(int direction);
double BPSizeMult(int direction);
int    BionicRegimeClassifier(double adxVal,double atrFast,double atrSlow,double effRatio);
double BPPositiveSL(int dir,double entry,double market,double curSL,double atr,double risk,double spreadPts,double pt,double tick,double hi8,double lo8,double prevHi,double prevLo,double bestPrice,double utLine);
bool   BPSmartPartial(SXPosition &position,double market,double risk);
void   BPManageTP(SXPosition &position,double market,double risk,double tick,double minDistance);
void   BPTick();
void   BPPaintAll();
void   BPHandleClick(string action);
void   BPCleanup();
void   XEUpdateTickPressure();
void   XEUpdateMTF();
void   XEUpdateStreak();
void XEGuardTick();
void XECheckKronosBasket();
void   XELockProfitHalf();
void   BPClosePositions(int mode);

struct SXAssetState {
   GemSnapshot gem;
   string symbol,key,note;
   int engines[SG_ENGINE_COUNT];
   int spreadCount,stopPadding,deltaTrap,quantumDir;
   double lastBid,lastAsk,spreadRatio,spreadMean,priorAtr,fastEMA,slowEMA,priorLo,priorHi,lo8,hi8;
   double quantumER,quantumLine,drm,coral,dailyMA;
   datetime droidRetry;
   datetime quoteTime,utSeen,utAccepted,lastFormingEvaluation;
   int utRemaining;
   datetime lastClosed,lastSignal,lastMTF;
   int raw,candidate,lastDirection,scoreBuy,scoreSell,tf1,tf2,zero,superDir;
   int mtf0,mtf1,mtf2,mtf3,mtf4;
   double atr,rsi,adx,macd,sma,volume,high,low,pdh,pdl,pwh,pwl,pivot,r1,s1,dayOpen;
   double ut,close,vwap,superLine,superUpper,superLower,stc,cci,stoch,atrRatio,bandUpper,bandLower,basketPeak,basketLots;
   double rrTrail,rrEMA,hull,tenkan,kijun,spanB,mfi,obv,ensembleConfidence,kalman,velocity,orderFlowDelta;
   int rrCross,rrState,ensembleVotes,ensembleActive,ensembleDir,kalmanDir,stopStage;
   bool enabled,uncertain,exiting,ready,fvgBuy,fvgSell;
};
SXAssetState g_assets[];
bool g_exitRequested=false,g_consolePortfolioExit=false;


#define FLOW_PEAK_SLOTS 64
#define FLOW_TICK_BOOKS 24
#define FLOW_TICK_CAP 512
#define FLOW_TICK_TOTAL 12288
#define FLOW_LEASE_SECONDS 30
struct FlowTickInfo {
   int moves,up,down,direction;
   double imbalance,driftPts,halfDriftPts,velocity,spreadPts,rate;
   bool ready;
};
string g_tkSymbol[FLOW_TICK_BOOKS];
int g_tkCount[FLOW_TICK_BOOKS],g_tkHead[FLOW_TICK_BOOKS];
double g_tkMid[FLOW_TICK_TOTAL],g_tkSpr[FLOW_TICK_TOTAL];
long g_tkMs[FLOW_TICK_TOTAL];
int g_tkBooks=0;
bool g_weeklyLock=false,g_emergency=false;
int g_weekCode=0;
double g_weekEquity=0,g_weekLoss=0;
datetime g_emergencyArmed=0;
string g_leaseKey="";
int g_tkConfDir[FLOW_TICK_BOOKS];
datetime g_tkConfSince[FLOW_TICK_BOOKS],g_tkConfSeen[FLOW_TICK_BOOKS];
ulong g_pkTicket[FLOW_PEAK_SLOTS];
string g_pkSymbol[FLOW_PEAK_SLOTS];
double g_pkPeak[FLOW_PEAK_SLOTS];
double g_leaseToken=0;

double g_voteOpen[],g_voteHigh[],g_voteLow[],g_voteClose[];
int g_voteRead[9],g_voteBuyVotes=0,g_voteSellVotes=0;
double g_voteAdx=0,g_votePlusDI=0,g_voteMinusDI=0;
double g_slipAvg=0; int g_slipCount=0; datetime g_slipPausedUntil=0;

// CORE_BEGIN - deterministic scalar functions exercised by the supplied C++ harness.
double SXTrueRange(double high,double low,double previousClose) {
   return MathMax(high-low,MathMax(MathAbs(high-previousClose),MathAbs(low-previousClose)));
}
double SXWilder(double previous,double value,int period) {
   return previous+(value-previous)/period;
}
double SXUTStep(double source,double previousSource,double previousStop,double loss) {
   if(source>previousStop && previousSource>previousStop) return MathMax(previousStop,source-loss);
   if(source<previousStop && previousSource<previousStop) return MathMin(previousStop,source+loss);
   return source>previousStop ? source-loss : source+loss;
}
int SXCross(double source,double previousSource,double stop,double previousStop) {
   if(source>stop && previousSource<=previousStop) return 1;
   if(source<stop && previousSource>=previousStop) return -1;
   return 0;
}
double SXRoundPrice(double price,double tick,int direction) {
   if(tick<=0) return 0;
   if(direction>0) return MathFloor(price/tick+1e-9)*tick;
   return MathCeil(price/tick-1e-9)*tick;
}
double SXFloorVolume(double raw,double minimum,double maximum,double step) {
   if(step<=0 || minimum<=0 || maximum<minimum || raw<minimum-1e-10) return 0;
   double result=MathFloor(MathMin(raw,maximum)/step+1e-9)*step;
   return result<minimum-1e-9 ? 0 : result;
}
bool SXHours(int hour,int start,int end) {
   if(start==end || (start==0 && end==24)) return true;
   if(start<end) return hour>=start && hour<end;
   return hour>=start || hour<end;
}
bool SXCooldown(int barsElapsed,int minimumBars) {
   return barsElapsed>=minimumBars;
}
int SXGap(double highOld,double lowOld,double highNow,double lowNow,double closeNow,double minimumPercent) {
   if(closeNow<=0) return 0;
   if(lowNow>highOld && 100.0*(lowNow-highOld)/closeNow>=minimumPercent) return 1;
   if(highNow<lowOld && 100.0*(lowOld-highNow)/closeNow>=minimumPercent) return -1;
   return 0;
}
double SXProtectStop(int direction,double open,double oldSL,double market,double atr,double initialATR,
                     bool breakEven,double beTrigger,double beLock,bool trailing,double trailStart,
                     double trailDistance,bool useUT,double ut,double minDistance,double tick,bool forceBE) {
   double distance=initialATR>0 ? initialATR : atr;
   if(distance<=0 || tick<=0 || minDistance<0) return oldSL;
   double gain=direction*(market-open),candidate=oldSL;
   if(breakEven && (gain>=beTrigger*distance || forceBE)) {
      double be=open+direction*beLock*distance;
      if(direction>0) candidate=MathMax(candidate,be);
      else if(candidate==0 || be<candidate) candidate=be;
   }
   if(trailing && gain>=trailStart*distance) {
      double trail=market-direction*trailDistance*atr;
      if(direction>0) candidate=MathMax(candidate,trail);
      else if(candidate==0 || trail<candidate) candidate=trail;
      if(useUT && direction*(ut-open)>0 && direction*(market-ut)>=minDistance) {
         if(direction>0) candidate=MathMax(candidate,ut);
         else if(candidate==0 || ut<candidate) candidate=ut;
      }
   }
   if(candidate<=0 || candidate==oldSL) return oldSL;
   candidate=SXRoundPrice(candidate,tick,direction);
   if(direction*(candidate-open)<=0 || direction*(market-candidate)<minDistance-1e-10) return oldSL;
   if(oldSL>0 && direction*(candidate-oldSL)<tick*0.5) return oldSL;
   return candidate;
}
double SXKalmanStep(double prevEst,double price,double gainFactor,double velocity) {
   if(prevEst<=0) return price;
   double k=MathMax(0.01,MathMin(1.0,gainFactor));
   return prevEst + k*(price - prevEst) + 0.12*k*velocity;
}
double SXQuantumVelocity(double closeNow,double closeLag,double atr,int lagBars) {
   if(atr<=0 || lagBars<=0) return 0;
   double raw=(closeNow-closeLag)/(atr*MathSqrt((double)lagBars));
   return MathMax(-5.0,MathMin(5.0,raw));
}
double SXOrderFlowDelta(double open,double high,double low,double close,double volume) {
   double range=high-low;
   if(range<=1e-12 || volume<=0) return 0;
   double clv=((close-low)-(high-close))/range;
   double body=(close-open)/range;
   return volume*(0.65*clv+0.35*body);
}
double SXStoneGemRatchetFloor(int direction,double open,double bestExcursion,double initialRisk,double costBuffer) {
   if(initialRisk<=0) return 0;
   double peak=direction*(bestExcursion-open);
   if(peak<1.5*initialRisk) return 0;
   double lockShare=peak>=6.0*initialRisk ? 0.82 : peak>=4.0*initialRisk ? 0.72 : peak>=2.5*initialRisk ? 0.60 : 0.45;
   return open+direction*(costBuffer+lockShare*peak);
}
bool SXSpreadShockSafe(double currentSpread,double atr,double maxSpreadATR,bool shockShield) {
   if(!shockShield || atr<=0 || maxSpreadATR<=0) return true;
   return currentSpread<=maxSpreadATR*atr*1.85;
}
double SXPositiveProfitRatchetFloor(int direction,double open,double bestExcursion,double initialRisk,
                                   double atr,double costPrice,double startATR,double stepATR,
                                   double baseLockPct,double stepLockPct,double maxLockPct,double tick) {
    if((direction!=1 && direction!=-1) || open<=0 || bestExcursion<=0 || initialRisk<=0 || tick<=0 ||
       startATR<=0 || stepATR<=0 || baseLockPct<=0 || maxLockPct<baseLockPct || maxLockPct>95) return 0;
    double peak=direction*(bestExcursion-open);
    double activation=startATR*initialRisk;
    if(peak<activation || peak<=tick) return 0;
    double stepDistance=MathMax(tick,stepATR*(atr>0 ? atr : initialRisk));
    int steps=(int)MathFloor(MathMax(0.0,peak-activation)/stepDistance+1e-9);
    double lockPct=MathMin(maxLockPct,baseLockPct+steps*MathMax(0.0,stepLockPct));
    double locked=MathMax(0.0,costPrice)+peak*lockPct/100.0;
    locked=MathMin(locked,peak-tick);
    if(locked<=MathMax(0.0,costPrice)) return 0;
    return open+direction*locked;
}
double SXKaufmanER(double netChange,double pathLength) {
   if(pathLength<=1e-12) return 0.5;
   return MathMax(0.0,MathMin(1.0,MathAbs(netChange)/pathLength));
}
double SXQuantumAdaptiveFactor(double er,double trendFactor,double rangeFactor) {
   double lo=MathMin(trendFactor,rangeFactor),hi=MathMax(trendFactor,rangeFactor);
   double cleanER=MathMax(0.0,MathMin(1.0,er));
   return hi-cleanER*(hi-lo);
}
int SXWhipsawShieldFlip(int currentDir,double closePrice,double oppositeBand,double atr,double shieldATR,bool &shielded) {
   shielded=false;
   if(atr<=0) return currentDir;
   double margin=MathMax(0.0,shieldATR)*atr;
   if(currentDir<0 && closePrice>oppositeBand) {
      if(closePrice>=oppositeBand+margin) return 1;
      shielded=true; return currentDir;
   }
   if(currentDir>0 && closePrice<oppositeBand) {
      if(closePrice<=oppositeBand-margin) return -1;
      shielded=true; return currentDir;
   }
   return currentDir;
}
double SXDrmMomentum(double closeNow,double closeLag,double highWindow,double lowWindow,double rsi,double atr) {
   double span=MathMax(atr,highWindow-lowWindow);
   if(span<=1e-12) return 0;
   double normMove=(closeNow-closeLag)/span;
   double rsiBias=(rsi-50.0)/50.0;
   return MathMax(-3.0,MathMin(3.0,0.65*normMove+0.35*rsiBias));
}
int SXDeltaTrapSignal(double open,double high,double low,double close,double prevHigh,double prevLow,double orderFlowDelta,double minWickRatio) {
   double range=high-low;
   if(range<=1e-12) return 0;
   double lowerWick=MathMin(open,close)-low;
   double upperWick=high-MathMax(open,close);
   if(low<prevLow && close>prevLow && lowerWick>=minWickRatio*range && (close>=open || orderFlowDelta>=0)) return 1;
   if(high>prevHigh && close<prevHigh && upperWick>=minWickRatio*range && (close<=open || orderFlowDelta<=0)) return -1;
   return 0;
}
double SXDynamicRiskMultiplier(double baseRiskPct,double confidence,double drawdownPct,bool autoScale,double minMult,double maxMult) {
   if(baseRiskPct<=0) return 0;
   if(!autoScale) return baseRiskPct;
   double confBoost=0.80+0.45*MathMax(0.0,MathMin(1.0,confidence));
   double ddDamp=drawdownPct>2.0 ? MathMax(0.40,1.0-0.06*(drawdownPct-2.0)) : 1.0;
   double mult=MathMax(minMult,MathMin(maxMult,confBoost*ddDamp));
   return baseRiskPct*mult;
}
int SXAdaptiveVoteScore(int direction,int kalman,int quantum,int zeroLag,double macd,double fast,double slow) {
   if(direction!=1 && direction!=-1) return 0;
   int score=0;
   if(direction*kalman>0) score++;
   if(direction*quantum>0) score++;
   if(direction*zeroLag>0) score++;
   if(direction*macd>0) score++;
   if(direction*(fast-slow)>0) score++;
   return score;
}
bool SXVolatilityRegimeAllowed(double atrRatio,bool enabled,double minRatio,double maxRatio) {
   if(!enabled) return true;
   if(atrRatio<=0 || minRatio<=0 || maxRatio<minRatio) return false;
   return atrRatio>=minRatio && atrRatio<=maxRatio;
}
double SXVolatilityRiskAttenuation(double atrRatio,bool enabled,double startRatio,double minMultiplier) {
   if(!enabled || startRatio<=0 || atrRatio<=startRatio) return 1.0;
   return MathMax(minMultiplier,MathMin(1.0,startRatio/atrRatio));
}
double SXAdvancedTrailStop(int mode,int direction,double open,double oldSL,double market,double bestExcursion,
                           double atr,double oldAtr,double initialATR,double ema21,double superLine,
                           double low8,double high8,double prevLow,double prevHigh,double adx,double rsi,
                           double spreadPrice,double costPrice,bool breakEven,double beTrigger,double beLock,
                           double stage2Comp,double stage4Extra,bool trailing,double trailStart,double trailDistance,
                           bool useUT,double ut,double minDistance,double tick,bool forceBE,int &outStage) {
   double distance=initialATR>0 ? initialATR : atr;
   if(distance<=0 || tick<=0 || minDistance<0) { outStage=1; return oldSL; }
   double gain=direction*(market-open);
   double peakMove=MathMax(gain,direction*(bestExcursion-open));
   outStage=1;
   double candidate=oldSL;
   if(breakEven && stage2Comp>0 && gain>=stage2Comp*beTrigger*distance && !forceBE) {
      outStage=2;
      double comp=open-direction*(distance*0.22);
      if(direction>0 && (candidate==0 || comp>candidate) && market-comp>=minDistance) candidate=comp;
      else if(direction<0 && (candidate==0 || comp<candidate) && comp-market>=minDistance) candidate=comp;
   }
   double effBeTrigger=(mode==2 && InpRRBETriggerRR>0) ? InpRRBETriggerRR : beTrigger;
   if(breakEven && (gain>=effBeTrigger*distance || forceBE)) {
      outStage=3;
      double be=open+direction*(costPrice+beLock*distance);
      if(direction>0) candidate=MathMax(candidate,be);
      else if(candidate==0 || be<candidate) candidate=be;
      if(stage4Extra>0 && gain>=1.4*effBeTrigger*distance) {
         outStage=4;
         double be4=open+direction*(costPrice+(beLock+stage4Extra)*distance);
         if(direction>0) candidate=MathMax(candidate,be4);
         else if(candidate==0 || be4<candidate) candidate=be4;
      }
   }
   if(trailing && gain>=trailStart*distance) {
      outStage=5;
      double baseDist=trailDistance*atr;
      double d=baseDist;
      double refPrice=market;
      if(mode==3) d=baseDist;
      else if(mode==4) d=baseDist+0.5*MathMax(tick,InpTrailStepATR*atr);
      else if(mode==5) d=trailDistance*atr;
      else if(mode==6) {
         double ratio=oldAtr>0 ? MathMax(0.5,MathMin(2.0,atr/oldAtr)) : 1.0;
         d=MathMax(baseDist*0.7,atr*(0.9+0.7*ratio));
      } else if(mode==7) { refPrice=bestExcursion>0 ? bestExcursion : market; d=MathMax(baseDist*0.6,peakMove*0.40); }
      else if(mode==8) { refPrice=bestExcursion>0 ? bestExcursion : market; d=MathMax(baseDist*0.45,baseDist-0.18*peakMove); }
      else if(mode==9) d=MathMax(baseDist,spreadPrice*3.0);
      else if(mode==10) d=MathMax(baseDist*0.6,spreadPrice*2.3);
      else if(mode==11) d=ema21>0 ? MathMax(baseDist,MathAbs(market-ema21)) : baseDist;
      else if(mode==12) d=superLine>0 ? MathMax(baseDist*0.6,MathAbs(market-superLine)) : baseDist;
      else if(mode==13) d=MathMax(baseDist*0.6,atr*2.4);
      else if(mode==14) {
         double chan=direction>0 ? low8 : high8;
         d=chan>0 ? MathMax(baseDist*0.6,MathAbs(market-chan)) : baseDist;
      } else if(mode==15) {
         double pb=direction>0 ? prevLow : prevHigh;
         d=pb>0 ? MathMax(baseDist*0.6,MathAbs(market-pb)) : baseDist;
      } else if(mode==16) d=MathMax(baseDist*0.55,atr*(adx>30 ? 1.0 : 1.6));
      else if(mode==17) d=MathMax(baseDist*0.55,atr*((rsi>75 || rsi<25) ? 0.75 : 1.4));
      else if(mode==18) d=MathMax(baseDist,spreadPrice*3.5);
      else if(mode==19) d=MathMax(baseDist,spreadPrice*(3.0+(atr>0 ? spreadPrice/atr : 0)));
      else if(mode==20) d=MathMax(baseDist*0.6,atr*(adx>25 ? 1.8 : 1.0));
      else if(mode==21) { refPrice=bestExcursion>0 ? bestExcursion : market; d=MathMax(baseDist,peakMove*0.30); }
      else if(mode==22) {
         refPrice=bestExcursion>0 ? bestExcursion : market;
         d=MathMax(baseDist*0.50,peakMove*0.28);
         double rFloor=SXStoneGemRatchetFloor(direction,open,refPrice,distance,costPrice);
         if(rFloor>0) {
            if(direction>0) candidate=MathMax(candidate,rFloor);
            else if(candidate==0 || rFloor<candidate) candidate=rFloor;
         }
      } else if(mode==23) {
         double vFactor=MathMax(0.55,MathMin(1.45,1.15-0.12*MathAbs(g_velocity)));
         double kLine=g_kalman>0 ? MathAbs(market-g_kalman) : baseDist;
         d=MathMax(baseDist*0.50,MathMin(baseDist*1.6,kLine*vFactor));
      } else if(mode==24) {
         bool adverseFlow=(direction>0 && g_orderFlowDelta<0) || (direction<0 && g_orderFlowDelta>0);
         d=MathMax(baseDist*0.50,atr*(adverseFlow ? 0.68 : 1.22));
       } else if(mode==25) {
          double fibRet=peakMove>=4.0*distance ? 0.214 : peakMove>=2.5*distance ? 0.382 : 0.500;
          refPrice=bestExcursion>0 ? bestExcursion : market;
          d=MathMax(baseDist*0.50,peakMove*fibRet);
       } else if(mode==26) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          d=MathMax(baseDist*0.35,peakMove*0.18);
       } else if(mode==27) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          d=MathMax(baseDist*0.45,atr*1.10);
       } else if(mode==28) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          double structure=direction>0 ? low8 : high8;
          double structureDistance=structure>0 ? direction*(refPrice-structure) : 0;
          d=structureDistance>0 ? MathMax(baseDist*0.35,structureDistance) : baseDist;
       } else if(mode==29) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          bool alignedFlow=(direction>0 && g_orderFlowDelta>=0) || (direction<0 && g_orderFlowDelta<=0);
          double regimeFactor=adx>=25.0 ? 0.82 : 1.25;
          if(!alignedFlow) regimeFactor*=0.82;
          d=MathMax(baseDist*0.35,atr*regimeFactor);
       } else if(mode==30) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          double qFactor=SXQuantumAdaptiveFactor(g_quantumER,InpQuantumTrendFactor,InpQuantumRangeFactor);
          double qDist=atr*MathMax(0.45,qFactor*0.42);
          if(g_quantumSuperLine>0 && direction*(market-g_quantumSuperLine)>minDistance)
             qDist=MathMin(qDist,MathAbs(market-g_quantumSuperLine));
          d=MathMax(baseDist*0.35,qDist);
       } else if(mode==31) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          double drmTight=MathMax(0.45,1.15-0.22*MathAbs(g_drmValue));
          d=MathMax(baseDist*0.35,atr*drmTight);
       } else if(mode==32) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          double coralDist=g_coralEMA>0 ? MathAbs(market-g_coralEMA) : baseDist;
          d=MathMax(baseDist*0.35,MathMin(baseDist*1.35,coralDist*0.75));
       } else if(mode==33) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          bool trapAgainst=(direction>0 && (g_deltaTrapSig<0 || g_orderFlowDelta<0)) || (direction<0 && (g_deltaTrapSig>0 || g_orderFlowDelta>0));
          d=MathMax(baseDist*0.32,atr*(trapAgainst ? 0.52 : 1.05));
       } else if(mode==34) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          d=MathMax(baseDist*0.30,MathMin(atr*0.72,peakMove*0.22));
       } else if(mode==35) {
          refPrice=bestExcursion>0 ? bestExcursion : market;
          double qFactor=SXQuantumAdaptiveFactor(g_quantumER,InpQuantumTrendFactor,InpQuantumRangeFactor);
          bool trapAgainst=(direction>0 && (g_deltaTrapSig<0 || g_orderFlowDelta<0)) || (direction<0 && (g_deltaTrapSig>0 || g_orderFlowDelta>0));
          double ultDist=MathMin(peakMove*0.20,atr*MathMax(0.42,0.35*qFactor*(trapAgainst ? 0.70 : 1.0)));
          d=MathMax(baseDist*0.30,ultDist);
          double rFloor=SXStoneGemRatchetFloor(direction,open,refPrice,distance,costPrice);
          if(rFloor>0) {
             if(direction>0) candidate=MathMax(candidate,rFloor);
             else if(candidate==0 || rFloor<candidate) candidate=rFloor;
          }
       }
      if(InpUseQuantumRatchet && peakMove>=1.5*distance) {
         double qFloor=SXStoneGemRatchetFloor(direction,open,bestExcursion>0 ? bestExcursion : market,distance,costPrice);
         if(qFloor>0) {
            if(direction>0) candidate=MathMax(candidate,qFloor);
            else if(candidate==0 || qFloor<candidate) candidate=qFloor;
         }
      }
      double trail=refPrice-direction*d;
      if(direction>0) candidate=MathMax(candidate,trail);
      else if(candidate==0 || trail<candidate) candidate=trail;
      if(useUT && direction*(ut-open)>0 && direction*(market-ut)>=minDistance) {
         if(direction>0) candidate=MathMax(candidate,ut);
         else if(candidate==0 || ut<candidate) candidate=ut;
      }
   }
   if(candidate<=0 || candidate==oldSL) return oldSL;
   if(direction>0 && candidate>market-minDistance) candidate=market-minDistance;
   if(direction<0 && candidate<market+minDistance) candidate=market+minDistance;
   candidate=SXRoundPrice(candidate,tick,direction);
   if(outStage>=3 && direction*(candidate-open)<=0) return oldSL;
   if(direction*(market-candidate)<minDistance-1e-10) return oldSL;
   if(oldSL>0 && direction*(candidate-oldSL)<tick*0.5) return oldSL;
   return candidate;
}
// CORE_END

string Side(int direction) { return direction>0 ? "BUY" : direction<0 ? "SELL" : "NEUTRAL"; }
string Yes(bool value) { return value ? "ON" : "OFF"; }
string ConsoleTFName(ENUM_TIMEFRAMES tf) { string s=EnumToString(tf); StringReplace(s,"PERIOD_",""); return s; }
string PriceText(double value) { return DoubleToString(value,g_consoleDigits); }
void Log(string message) {
   for(int i=7;i>0;i--) g_log[i]=g_log[i-1];
   g_log[0]=TimeToString(TimeCurrent(),TIME_MINUTES|TIME_SECONDS)+" "+message;
   g_message=message;
   Print("CVT LT DRIOD BOT NO ERRORS EA | ",g_symbol," | ",message);
}
void Notify(string message) {
   Log(message);
   if(!g_tester && InpPopupAlerts) Alert("CVT LT DRIOD BOT NO ERRORS EA | ",message);
   if(!g_tester && InpPushAlerts) { if(!SendNotification("CVT LT DRIOD BOT NO ERRORS EA | "+message)) Print("Push failed: ",GetLastError()); }
}
double ReadGV(string suffix,double fallback) {
   return GlobalVariableCheck(g_key+suffix) ? GlobalVariableGet(g_key+suffix) : fallback;
}
void WriteGV(string suffix,double value) { GlobalVariableSet(g_key+suffix,value); }
int PaletteSlot(int id) { return id>THEME_CUSTOM ? id-1 : id; }
int PaletteID(int slot) { return slot>=THEME_CUSTOM ? slot+1 : slot; }
string ConsoleThemeName(int t) {
   if(t>=599 && t<=694) {
      string facets[96]={"Ink Tide", "Sawtooth Neon", "Quartz Tape", "Copper Circuit", "Arctic Pulse", "Moss Terminal",
      "Ember Tape", "Violet Static", "Citrine Ladder", "Rosewood Tick", "Cobalt Flux", "Mint Ledger",
      "Obsidian Gold", "Magenta Drift", "Teal Burst", "Solar Flare", "Indigo Wire", "Lime Pulse",
      "Slate Ember", "Orchid Wire", "Sandstone Day", "Linen Day", "Pearl Daylight", "Glacier Day",
      "Basalt Pulse", "Jade Ledger", "Gem Facet", "Opal Tape", "Garnet Wire", "Amber Grid",
      "Sapphire Flow", "Emerald Tick", "Topaz Signal", "Onyx Ember", "Ruby Static", "Aqua Quartz",
      "Peridot Burst", "Amethyst Drift", "Cinnabar Night", "Lapis Terminal", "Jet Mint", "Citrine Dusk",
      "Smoke Violet", "Coral Reef", "Alabaster Day", "Jade Day", "Rose Quartz Day", "Sky Opal Day",
      "Harbor Lantern", "Pine Static", "Dune Ledger", "Neon Harbor", "Velvet Ash", "Cinder Mint",
      "Tangerine Wire", "Frost Ledger", "Mulberry Tape", "Cedar Pulse", "Steel Orchid", "Ocean Ember",
      "Graphite Lime", "Plum Static", "Brass Circuit", "Storm Quartz", "Marigold Night", "Turquoise Wire",
      "Maroon Terminal", "Lilac Ledger", "Cloud Day", "Peach Day", "Mint Day", "Lavender Day",
      "Nimbus Ledger", "Fern Static", "Rust Terminal", "Cyan Ember", "Ash Orchid", "Mocha Wire",
      "Violet Citrine", "Pewter Mint", "Scarlet Tape", "Teal Dusk", "Gold Slate", "Iris Pulse",
      "Spruce Quartz", "Rosewater Night", "Lagoon Ember", "Olive Wire", "Berry Static", "Cobalt Mint",
      "Copper Frost", "Mauve Terminal", "Daylight Ledger", "Apricot Day", "Seafoam Day", "Periwinkle Day"};
      return facets[t-599];
   }
   if(t>=587 && t<=598) { string signature[12]={"Malachite Circuit","Amber Circuit","Frosted Sapphire","Wild Orchid","Ember Copper","Mint Slate","Polar Silver","Black Opal","Forest Brass","Ocean Glass","Rose Garnet","Indigo Gold"}; return signature[t-587]; }
   if(t>=575 && t<=586) { string clockNames[12]={"Aurora Gold","Glacier Cyan","Obsidian Emerald","Solar Amber","Royal Violet","Crimson Alloy","Cerulean Steel","Titanium Silver","Forest Jade","Copper Eclipse","Indigo Plasma","Rose Quartz"}; return clockNames[t-575]; }
   string names[575]={
      "StoneGem / Ink","StoneGem / Velvet","StoneGem / Midnight","StoneGem / Graphite","StoneGem / Deep Sea","StoneGem / Smoked Bronze",
      "StoneGem / Aurora","StoneGem / Slate","StoneGem / Parchment","StoneGem / Porcelain","StoneGem / Frost","StoneGem / Blush",
      "Diamond / Ink","Diamond / Velvet","Diamond / Midnight","Diamond / Graphite","Diamond / Deep Sea","Diamond / Smoked Bronze",
      "Diamond / Aurora","Diamond / Slate","Diamond / Parchment","Diamond / Porcelain","Diamond / Frost","Diamond / Blush",
      "Ruby / Ink","Ruby / Velvet","Ruby / Midnight","Ruby / Graphite","Ruby / Deep Sea","Ruby / Smoked Bronze",
      "Ruby / Aurora","Ruby / Slate","Ruby / Parchment","Ruby / Porcelain","Ruby / Frost","Ruby / Blush",
      "Sapphire / Ink","Sapphire / Velvet","Sapphire / Midnight","Sapphire / Graphite","Sapphire / Deep Sea","Sapphire / Smoked Bronze",
      "Sapphire / Aurora","Sapphire / Slate","Sapphire / Parchment","Sapphire / Porcelain","Sapphire / Frost","Sapphire / Blush",
      "Emerald / Ink","Emerald / Velvet","Emerald / Midnight","Emerald / Graphite","Emerald / Deep Sea","Emerald / Smoked Bronze",
      "Emerald / Aurora","Emerald / Slate","Emerald / Parchment","Emerald / Porcelain","Emerald / Frost","Emerald / Blush",
      "Amethyst / Ink","Amethyst / Velvet","Amethyst / Midnight","Amethyst / Graphite","Amethyst / Deep Sea","Amethyst / Smoked Bronze",
      "Amethyst / Aurora","Amethyst / Slate","Amethyst / Parchment","Amethyst / Porcelain","Amethyst / Frost","Amethyst / Blush",
      "Amber / Ink","Amber / Velvet","Amber / Midnight","Amber / Graphite","Amber / Deep Sea","Amber / Smoked Bronze",
      "Amber / Aurora","Amber / Slate","Amber / Parchment","Amber / Porcelain","Amber / Frost","Amber / Blush",
      "Jade / Ink","Jade / Velvet","Jade / Midnight","Jade / Graphite","Jade / Deep Sea","Jade / Smoked Bronze",
      "Jade / Aurora","Jade / Slate","Jade / Parchment","Jade / Porcelain","Jade / Frost","Jade / Blush",
      "Garnet / Ink","Garnet / Velvet","Garnet / Midnight","Garnet / Graphite","Garnet / Deep Sea","Garnet / Smoked Bronze",
      "Garnet / Aurora","Garnet / Slate","Garnet / Parchment","Garnet / Porcelain","Garnet / Frost","Garnet / Blush",
      "Topaz / Ink","Topaz / Velvet","Topaz / Midnight","Topaz / Graphite","Topaz / Deep Sea","Topaz / Smoked Bronze",
      "Topaz / Aurora","Topaz / Slate","Topaz / Parchment","Topaz / Porcelain","Topaz / Frost","Topaz / Blush",
      "Aquamarine / Ink","Aquamarine / Velvet","Aquamarine / Midnight","Aquamarine / Graphite","Aquamarine / Deep Sea","Aquamarine / Smoked Bronze",
      "Aquamarine / Aurora","Aquamarine / Slate","Aquamarine / Parchment","Aquamarine / Porcelain","Aquamarine / Frost","Aquamarine / Blush",
      "Tanzanite / Ink","Tanzanite / Velvet","Tanzanite / Midnight","Tanzanite / Graphite","Tanzanite / Deep Sea","Tanzanite / Smoked Bronze",
      "Tanzanite / Aurora","Tanzanite / Slate","Tanzanite / Parchment","Tanzanite / Porcelain","Tanzanite / Frost","Tanzanite / Blush",
      "Opal / Ink","Opal / Velvet","Opal / Midnight","Opal / Graphite","Opal / Deep Sea","Opal / Smoked Bronze",
      "Opal / Aurora","Opal / Slate","Opal / Parchment","Opal / Porcelain","Opal / Frost","Opal / Blush",
      "Platinum / Ink","Platinum / Velvet","Platinum / Midnight","Platinum / Graphite","Platinum / Deep Sea","Platinum / Smoked Bronze",
      "Platinum / Aurora","Platinum / Slate","Platinum / Parchment","Platinum / Porcelain","Platinum / Frost","Platinum / Blush",
      "Copper / Ink","Copper / Velvet","Copper / Midnight","Copper / Graphite","Copper / Deep Sea","Copper / Smoked Bronze",
      "Copper / Aurora","Copper / Slate","Copper / Parchment","Copper / Porcelain","Copper / Frost","Copper / Blush",
      "Citrine / Ink","Citrine / Velvet","Citrine / Midnight","Citrine / Graphite","Citrine / Deep Sea","Citrine / Smoked Bronze",
      "Citrine / Aurora","Citrine / Slate","Citrine / Parchment","Citrine / Porcelain","Citrine / Frost","Citrine / Blush",
      "Obsidian / Ink","Obsidian / Velvet","Obsidian / Midnight","Obsidian / Graphite","Obsidian / Deep Sea","Obsidian / Smoked Bronze",
      "Obsidian / Aurora","Obsidian / Slate","Obsidian / Parchment","Obsidian / Porcelain","Obsidian / Frost","Obsidian / Blush",
      "Tourmaline / Ink","Tourmaline / Velvet","Tourmaline / Midnight","Tourmaline / Graphite","Tourmaline / Deep Sea","Tourmaline / Smoked Bronze",
      "Tourmaline / Aurora","Tourmaline / Slate","Tourmaline / Parchment","Tourmaline / Porcelain","Tourmaline / Frost","Tourmaline / Blush",
      "Custom","Malachite / Ink","Malachite / Velvet","Malachite / Midnight","Malachite / Graphite","Malachite / Deep Sea",
      "Malachite / Smoked Bronze","Malachite / Aurora","Malachite / Slate","Malachite / Parchment","Malachite / Porcelain","Malachite / Frost",
      "Malachite / Blush","Cinnabar / Ink","Cinnabar / Velvet","Cinnabar / Midnight","Cinnabar / Graphite","Cinnabar / Deep Sea",
      "Cinnabar / Smoked Bronze","Cinnabar / Aurora","Cinnabar / Slate","Cinnabar / Parchment","Cinnabar / Porcelain","Cinnabar / Frost",
      "Cinnabar / Blush","Labradorite / Ink","Labradorite / Velvet","Labradorite / Midnight","Labradorite / Graphite","Labradorite / Deep Sea",
      "Labradorite / Smoked Bronze","Labradorite / Aurora","Labradorite / Slate","Labradorite / Parchment","Labradorite / Porcelain","Labradorite / Frost",
      "Labradorite / Blush","Sunstone / Ink","Sunstone / Velvet","Sunstone / Midnight","Sunstone / Graphite","Sunstone / Deep Sea",
      "Sunstone / Smoked Bronze","Sunstone / Aurora","Sunstone / Slate","Sunstone / Parchment","Sunstone / Porcelain","Sunstone / Frost",
      "Sunstone / Blush","Mineral Dark","Black","Grey","Dark Red","Dark Grey",
      "Maroon","Orange Red","Crimson","Dark Silver","Orange","Metal Gold",
      "Green","Forest","Violet","Red","Caramel","Coral",
      "Snow Blue","Gold","Silver","Blue","Cerulean","White",
      "Neon","Aurora","Ocean","Sunset","Mineral Cyber","Mineral Plasma",
      "Mineral Obsidian","Mineral Emerald","Mineral Sapphire","Mineral Ruby","Mineral Titanium","Mineral Solar",
      "Midnight Teal","Deep Navy","Arctic Frost","Rose Gold","Lavender Mist","Copper Forge",
      "Ember Glow","Moss Stone","Indigo Night","Pearl Day","Slate Blue","Mint Cream",
      "Sand Dune","Cherry Blossom","Champagne","Olive Grove","Berry Jam","Aquamarine",
      "Cobalt","Turquoise","Citrus","Graphite","Burgundy","Ice Violet",
      "Terracotta","Lime Night","Sepia","Amber Night","Prism Prime","Prism Nebula",
      "Prism Volt","Prism Magma","Prism Glacier","Prism Orchid","Prism Abyss","Prism Solstice",
      "Basalt Smoke","Basalt Nebula","Basalt Volt","Basalt Magma","Basalt Glacier","Basalt Orchid",
      "Basalt Abyss","Basalt Solstice",
      "Studio / Gem Dark", "Studio / Black", "Studio / Grey", "Studio / Dark Red",
      "Studio / Dark Grey", "Studio / Maroon", "Studio / Orange Red", "Studio / Crimson",
      "Studio / Dark Silver", "Studio / Orange", "Studio / Metal Gold", "Studio / Green",
      "Studio / Forest", "Studio / Violet", "Studio / Red", "Studio / Caramel",
      "Studio / Coral", "Studio / Snow Blue", "Studio / Gold", "Studio / Silver",
      "Studio / Blue", "Studio / Cerulean", "Studio / White", "Studio / Neon",
      "Studio / Aurora", "Studio / Ocean", "Studio / Sunset", "Studio / Gem Cyber",
      "Studio / Gem Plasma", "Studio / Gem Obsidian", "Studio / Gem Emerald", "Studio / Gem Sapphire",
      "Studio / Gem Ruby", "Studio / Gem Titanium", "Studio / Gem Solar", "Studio / Midnight Teal",
      "Studio / Deep Navy", "Studio / Arctic Frost", "Studio / Rose Gold", "Studio / Lavender Mist",
      "Studio / Copper Forge", "Studio / Ember Glow", "Studio / Moss Stone", "Studio / Indigo Night",
      "Studio / Pearl Day", "Studio / Slate Blue", "Studio / Mint Cream", "Studio / Sand Dune",
      "Studio / Cherry Blossom", "Studio / Champagne", "Studio / Olive Grove", "Studio / Berry Jam",
      "Studio / Aquamarine", "Studio / Cobalt", "Studio / Turquoise", "Studio / Citrus",
      "Studio / Graphite", "Studio / Burgundy", "Studio / Ice Violet", "Studio / Terracotta",
      "Studio / Lime Night", "Studio / Sepia", "Studio / Amber Night", "Studio / Northern Lights",
      "Studio / Volcanic", "Studio / Royal Purple", "Studio / Sakura Night", "Studio / Deep Sea",
      "Studio / Solar Flare", "Studio / Matrix", "Studio / Steel Blue", "Studio / Espresso",
      "Studio / Neon Pink", "Studio / Glacier", "Studio / Dawn Peach", "Studio / Jade",
      "Studio / Carbon Gold", "Studio / Storm Grey", "Studio / StoneGem", "Studio / Cyberpunk",
      "Studio / Synthwave", "Studio / Tokyo Night", "Studio / Nordic", "Studio / Desert Gold",
      "Studio / Forest Dew", "Studio / Ocean Breeze", "Studio / Blood Moon", "Studio / Royal Gold",
      "Studio / Midnight Purple", "Studio / Cotton Candy", "Studio / Spring Leaf", "Studio / Blueprint",
      "Studio / Coal Ember", "Studio / Ice Mint", "Studio / StoneGem Gold", "Studio / Ion Storm",
      "Studio / Graphene", "Studio / Starfire", "Studio / Quantum Cyan", "Studio / Ultraviolet",
      "Studio / Titanium Teal", "Studio / Photon Gold", "Studio / Polar Night", "Studio / Crystal Lime",
      "Studio / Obsidian Copper", "Studio / Deep Magenta", "Studio / Emerald Circuit", "Studio / Silicon Silver",
      "Studio / Retrowave", "Studio / Baltic Sky", "Studio / Ivory Graphite", "Studio / Diamond Ink",
      "Studio / Diamond Velvet", "Studio / Diamond Slate", "Studio / Diamond Dusk", "Studio / Diamond Frost",
      "Studio / Diamond Midnight", "Studio / Diamond Porcelain", "Studio / Diamond Marine", "Studio / Diamond Smoke",
      "Studio / Diamond Aurora", "Studio / Ruby Ink", "Studio / Ruby Velvet", "Studio / Ruby Slate",
      "Studio / Ruby Dusk", "Studio / Ruby Frost", "Studio / Ruby Midnight", "Studio / Ruby Porcelain",
      "Studio / Ruby Marine", "Studio / Ruby Smoke", "Studio / Ruby Aurora", "Studio / Emerald Ink",
      "Studio / Emerald Velvet", "Studio / Emerald Slate", "Studio / Emerald Dusk", "Studio / Emerald Frost",
      "Studio / Emerald Midnight", "Studio / Emerald Porcelain", "Studio / Emerald Marine", "Studio / Emerald Smoke",
      "Studio / Emerald Aurora", "Studio / Sapphire Ink", "Studio / Sapphire Velvet", "Studio / Sapphire Slate",
      "Studio / Sapphire Dusk", "Studio / Sapphire Frost", "Studio / Sapphire Midnight", "Studio / Sapphire Porcelain",
      "Studio / Sapphire Marine", "Studio / Sapphire Smoke", "Studio / Sapphire Aurora", "Studio / Crystal Ink",
      "Studio / Crystal Velvet", "Studio / Crystal Slate", "Studio / Crystal Dusk", "Studio / Crystal Frost",
      "Studio / Crystal Midnight", "Studio / Crystal Porcelain", "Studio / Crystal Marine", "Studio / Crystal Smoke",
      "Studio / Crystal Aurora", "Studio / Amethyst Ink", "Studio / Amethyst Velvet", "Studio / Amethyst Slate",
      "Studio / Amethyst Dusk", "Studio / Amethyst Frost", "Studio / Amethyst Midnight", "Studio / Amethyst Porcelain",
      "Studio / Amethyst Marine", "Studio / Amethyst Smoke", "Studio / Amethyst Aurora", "Studio / Topaz Ink",
      "Studio / Topaz Velvet", "Studio / Topaz Slate", "Studio / Topaz Dusk", "Studio / Topaz Frost",
      "Studio / Topaz Midnight", "Studio / Topaz Porcelain", "Studio / Topaz Marine", "Studio / Topaz Smoke",
      "Studio / Topaz Aurora", "Studio / Aquamarine Ink", "Studio / Aquamarine Velvet", "Studio / Aquamarine Slate",
      "Studio / Aquamarine Dusk", "Studio / Aquamarine Frost", "Studio / Aquamarine Midnight", "Studio / Aquamarine Porcelain",
      "Studio / Aquamarine Marine", "Studio / Aquamarine Smoke", "Studio / Aquamarine Aurora", "Studio / Garnet Ink",
      "Studio / Garnet Velvet", "Studio / Garnet Slate", "Studio / Garnet Dusk", "Studio / Garnet Frost",
      "Studio / Garnet Midnight", "Studio / Garnet Porcelain", "Studio / Garnet Marine", "Studio / Garnet Smoke",
      "Studio / Garnet Aurora", "Studio / Opal Ink", "Studio / Opal Velvet", "Studio / Opal Slate",
      "Studio / Opal Dusk", "Studio / Opal Frost", "Studio / Opal Midnight", "Studio / Opal Porcelain",
      "Studio / Opal Marine", "Studio / Opal Smoke", "Studio / Opal Aurora", "Studio / Jade Ink",
      "Studio / Jade Velvet", "Studio / Jade Slate", "Studio / Jade Dusk", "Studio / Jade Frost",
      "Studio / Jade Midnight", "Studio / Jade Porcelain", "Studio / Jade Marine", "Studio / Jade Smoke",
      "Studio / Jade Aurora", "Studio / Citrine Ink", "Studio / Citrine Velvet", "Studio / Citrine Slate",
      "Studio / Citrine Dusk", "Studio / Citrine Frost", "Studio / Citrine Midnight", "Studio / Citrine Porcelain",
      "Studio / Citrine Marine", "Studio / Citrine Smoke", "Studio / Citrine Aurora"
   };
   return names[(int)MathMax(0,MathMin(SG_PALETTE_COUNT,t))];
}
int AdjacentFamily(int id,int step) {
   int starts[51]={
      0,12,24,36,48,60,
      72,84,96,108,120,132,
      144,156,168,180,192,204,
      216,228,240,252,264,291,
      327,335,343,370,378,406,422,438,454,464,474,484,494,504,514,524,534,544,554,564,574,586,598,622,646,670,694
   };
   int slot=id==THEME_CUSTOM ? 0 : PaletteSlot(id),family=0,count=ArraySize(starts)-1;
   while(family+1<count && slot>=starts[family+1]) family++;
   int target=(family+step+count)%count;
   return PaletteID(starts[target]+(int)MathMin(slot-starts[family],starts[target+1]-starts[target]-1));
}
string StyleName(int s) {
   string names[16]={"Matte","Accent edge","High contrast","Quiet","Soft","Frost","Cinema","Silver","Aurora","Terminal","Sunset","Deep space","Holographic","Brushed titanium","Carbon fiber","Electric candy"};
   return names[(int)MathMax(0,MathMin(15,s))];
}
color BlendThemeColor(color a,color b,int percent) {
   int k=(int)MathMax(0,MathMin(100,percent));
   int r=(((int)a&255)*(100-k)+((int)b&255)*k)/100;
   int g=((((int)a>>8)&255)*(100-k)+(((int)b>>8)&255)*k)/100;
   int bl=((((int)a>>16)&255)*(100-k)+(((int)b>>16)&255)*k)/100;
   return (color)(r|(g<<8)|(bl<<16));
}
void ApplyStudioPalette(int localID) {
   color B[232]={
      C'14,20,32',C'8,8,12',C'56,58,64',C'40,6,8',C'30,31,34',C'44,8,18',C'36,12,4',C'38,6,14',
      C'38,40,44',C'34,20,6',C'32,26,8',C'6,30,12',C'8,26,16',C'24,10,40',C'36,6,6',C'40,26,14',
      C'40,16,14',C'232,242,252',C'30,24,4',C'226,228,232',C'6,14,40',C'6,26,40',C'248,248,250',C'8,6,16',
      C'6,20,30',C'4,20,34',C'34,10,24',C'14,20,32',C'6,14,26',C'18,6,34',C'10,11,14',C'4,24,18',
      C'6,16,38',C'36,6,16',C'26,28,34',C'28,18,6',C'5,25,31',C'7,14,36',C'226,238,248',C'39,23,32',
      C'244,239,250',C'27,24,25',C'32,13,17',C'17,31,22',C'15,12,36',C'251,251,249',C'28,40,58',C'238,251,244',
      C'247,240,223',C'254,240,245',C'251,245,226',C'27,32,19',C'35,15,33',C'5,37,40',C'9,21,63',C'5,36,42',
      C'31,33,12',C'16,18,21',C'35,9,24',C'18,20,45',C'47,27,20',C'12,28,8',C'40,32,23',C'28,20,9',
      C'6,20,24',C'22,8,6',C'20,8,38',C'24,10,22',C'3,16,30',C'32,16,4',C'2,14,6',C'20,26,36',
      C'26,16,12',C'16,6,20',C'236,246,252',C'255,244,236',C'6,24,20',C'14,14,16',C'30,34,40',C'10,12,26',
      C'12,6,26',C'24,8,40',C'26,27,38',C'46,52,64',C'36,26,12',C'10,26,18',C'8,28,44',C'24,4,8',
      C'18,14,40',C'14,8,30',C'253,243,250',C'244,252,238',C'10,36,84',C'18,16,16',C'238,252,250',C'14,12,8',
      C'9,16,38',C'13,16,19',C'26,7,17',C'3,24,33',C'19,8,43',C'21,29,34',C'26,22,9',C'7,17,36',
      C'12,31,21',C'20,14,14',C'29,6,29',C'2,22,20',C'207,220,229',C'18,10,36',C'8,28,46',C'248,245,237',
      C'12,21,32',C'37,29,43',C'31,43,57',C'35,35,58',C'221,237,242',C'16,25,36',C'238,238,232',C'19,42,53',
      C'46,49,55',C'28,42,51',C'19,24,38',C'40,24,39',C'34,37,52',C'39,28,53',C'226,229,236',C'21,17,30',
      C'243,229,226',C'24,33,46',C'51,39,48',C'34,32,43',C'13,29,40',C'33,29,40',C'27,43,54',C'31,34,55',
      C'217,236,239',C'11,24,32',C'233,237,229',C'14,41,50',C'40,48,51',C'22,42,47',C'13,26,42',C'34,26,43',
      C'27,40,57',C'31,30,58',C'218,232,242',C'12,20,36',C'234,232,233',C'15,36,54',C'41,43,56',C'23,36,52',
      C'18,27,43',C'38,27,44',C'32,41,58',C'37,32,59',C'224,234,243',C'18,22,37',C'240,234,233',C'22,38,54',
      C'49,45,56',C'31,38,52',C'17,26,42',C'38,25,43',C'32,39,57',C'36,30,58',C'223,232,242',C'18,20,36',
      C'240,232,232',C'21,36,53',C'48,43,55',C'30,36,51',C'20,28,37',C'41,27,37',C'35,41,51',C'40,32,51',
      C'227,234,234',C'22,22,28',C'244,235,224',C'25,39,44',C'53,46,45',C'35,39,41',C'14,29,41',C'35,29,42',
      C'28,43,56',C'32,34,57',C'219,236,241',C'13,24,34',C'235,237,231',C'16,41,52',C'42,48,54',C'24,42,50',
      C'18,25,37',C'39,24,37',C'33,38,51',C'38,29,51',C'225,230,234',C'20,18,28',C'242,230,224',C'23,34,44',
      C'50,40,45',C'32,33,41',C'19,27,41',C'40,27,41',C'34,41,56',C'39,32,56',C'226,233,240',C'21,21,34',
      C'243,234,230',C'24,38,51',C'51,45,53',C'33,38,49',C'15,28,39',C'35,28,40',C'29,42,54',C'33,33,54',
      C'220,235,238',C'14,23,31',C'236,236,228',C'17,40,48',C'43,47,50',C'25,40,46',C'19,28,38',C'40,28,38',
      C'34,42,52',C'38,33,52',C'225,235,235',C'20,23,29',C'242,236,225',C'24,40,45',C'51,47,46',C'33,40,42'
   };
   color CARD[232]={
      C'22,32,48',C'18,18,26',C'72,75,82',C'58,12,16',C'44,46,52',C'62,14,28',C'54,20,10',C'56,12,24',
      C'54,56,62',C'50,30,12',C'48,40,14',C'12,46,20',C'14,40,26',C'36,18,58',C'54,12,12',C'58,38,22',
      C'58,26,22',C'214,228,244',C'46,36,10',C'206,210,218',C'12,26,62',C'12,40,60',C'232,234,240',C'16,14,30',
      C'12,34,48',C'10,34,54',C'52,18,38',C'22,32,48',C'12,26,44',C'30,12,54',C'18,20,26',C'10,38,28',
      C'12,28,60',C'54,12,26',C'38,42,50',C'44,28,10',C'10,43,49',C'15,29,57',C'205,223,237',C'61,35,47',
      C'224,216,240',C'48,38,32',C'58,26,25',C'29,48,33',C'30,24,57',C'233,236,238',C'44,61,81',C'215,237,226',
      C'227,213,191',C'244,213,227',C'234,226,203',C'44,52,29',C'61,28,54',C'11,57,61',C'17,37,91',C'11,56,65',
      C'50,54,20',C'29,31,36',C'58,17,37',C'35,38,67',C'72,41,29',C'23,43,17',C'62,49,37',C'49,34,13',
      C'10,38,44',C'48,18,12',C'40,18,70',C'50,22,46',C'8,36,60',C'64,34,8',C'6,32,14',C'36,48,66',
      C'52,34,26',C'38,14,46',C'214,232,244',C'252,226,210',C'12,48,40',C'30,30,34',C'50,56,66',C'20,26,52',
      C'30,12,56',C'48,16,78',C'36,40,59',C'59,66,82',C'66,48,22',C'18,46,32',C'14,52,76',C'52,10,18',
      C'34,28,72',C'30,16,60',C'248,224,240',C'224,242,208',C'18,56,120',C'38,32,30',C'212,240,236',C'34,28,14',
      C'21,33,65',C'28,33,39',C'49,16,34',C'10,44,56',C'38,16,68',C'41,56,60',C'48,41,20',C'13,35,62',
      C'25,53,35',C'38,27,28',C'52,17,50',C'11,42,34',C'231,238,243',C'38,19,59',C'23,49,72',C'228,230,226',
      C'22,36,53',C'52,42,60',C'46,62,78',C'49,48,75',C'205,223,233',C'28,39,52',C'223,220,216',C'28,58,76',
      C'60,65,74',C'41,62,68',C'26,39,57',C'55,37,56',C'49,56,73',C'53,41,70',C'210,216,227',C'32,30,46',
      C'228,211,209',C'34,49,68',C'66,55,66',C'47,51,59',C'21,43,59',C'49,42,58',C'42,62,75',C'45,48,72',
      C'201,223,230',C'23,38,49',C'217,219,213',C'22,58,72',C'54,64,69',C'34,61,63',C'21,40,61',C'49,39,60',
      C'43,59,78',C'46,44,75',C'201,219,234',C'24,33,53',C'218,214,217',C'23,52,76',C'55,58,74',C'35,55,69',
      C'25,41,61',C'54,40,60',C'48,60,79',C'51,45,76',C'207,220,234',C'30,35,53',C'225,216,217',C'31,54,77',
      C'63,61,75',C'44,58,69',C'24,40,61',C'53,39,60',C'47,58,78',C'51,43,75',C'207,218,233',C'29,33,52',
      C'224,214,216',C'30,52,75',C'63,58,74',C'43,55,68',C'27,42,56',C'56,40,54',C'50,60,72',C'54,46,68',
      C'210,221,226',C'33,36,44',C'229,217,207',C'35,55,66',C'68,61,63',C'48,58,57',C'22,43,60',C'50,42,59',
      C'44,62,77',C'47,48,74',C'202,223,232',C'25,38,51',C'219,219,215',C'24,58,74',C'56,64,72',C'36,61,66',
      C'25,39,56',C'54,37,54',C'49,57,72',C'52,42,68',C'209,217,226',C'32,31,44',C'227,212,207',C'33,50,66',
      C'65,56,63',C'46,52,57',C'26,41,60',C'55,40,58',C'49,60,76',C'53,45,73',C'209,220,231',C'32,35,50',
      C'228,216,214',C'34,54,73',C'66,60,71',C'47,57,65',C'22,42,58',C'51,41,57',C'44,61,75',C'48,47,71',
      C'203,222,229',C'26,37,48',C'220,218,211',C'26,56,70',C'58,63,68',C'38,60,62',C'26,42,57',C'55,41,55',
      C'49,61,73',C'53,47,69',C'209,222,227',C'32,37,45',C'227,218,208',C'33,56,67',C'66,63,64',C'46,60,58'
   };
   color A1[232]={
      C'0,230,195',C'0,200,255',C'200,205,214',C'210,34,44',C'150,160,176',C'186,52,100',C'255,69,0',C'220,20,60',
      C'176,178,184',C'255,140,0',C'212,175,55',C'0,200,80',C'60,170,80',C'150,80,255',C'255,40,40',C'205,127,50',
      C'255,111,97',C'30,120,210',C'255,200,0',C'90,100,118',C'40,110,255',C'30,150,200',C'0,102,204',C'57,255,20',
      C'0,255,170',C'0,180,220',C'255,94,77',C'0,230,195',C'0,255,230',C'255,60,240',C'220,185,90',C'0,245,150',
      C'55,165,255',C'255,55,95',C'195,210,230',C'255,190,40',C'20,220,193',C'82,137,255',C'15,118,191',C'234,154,159',
      C'137,90,203',C'218,122,66',C'255,94,47',C'126,187,91',C'118,104,246',C'56,120,163',C'94,172,220',C'22,148,118',
      C'157,108,60',C'195,70,118',C'164,130,46',C'172,186,75',C'209,78,154',C'42,218,200',C'64,115,255',C'22,207,195',
      C'202,236,67',C'174,188,205',C'195,47,104',C'157,152,255',C'224,123,88',C'166,246,75',C'201,166,113',C'246,179,57',
      C'80,255,190',C'255,87,34',C'186,104,255',C'255,143,177',C'0,184,212',C'255,179,0',C'0,255,65',C'100,160,220',
      C'210,160,110',C'255,32,160',C'0,120,190',C'224,98,58',C'0,200,140',C'230,190,70',C'140,170,200',C'255,138,61',
      C'252,238,9',C'255,56,200',C'122,162,247',C'136,192,208',C'232,176,64',C'120,210,140',C'72,202,228',C'230,57,70',
      C'240,196,60',C'160,100,255',C'232,96,168',C'68,150,48',C'200,230,255',C'255,112,40',C'20,150,130',C'255,196,64',
      C'30,240,250',C'192,213,221',C'255,138,55',C'37,234,248',C'208,112,252',C'41,224,190',C'255,221,80',C'124,198,255',
      C'174,248,100',C'228,154,92',C'253,74,210',C'31,228,160',C'36,85,125',C'249,94,192',C'105,203,245',C'77,83,91',
      C'151,225,236',C'158,232,239',C'161,233,240',C'163,233,240',C'75,121,135',C'168,234,241',C'75,121,135',C'173,234,242',
      C'175,234,242',C'178,235,243',C'239,87,125',C'239,91,128',C'240,95,132',C'240,99,135',C'111,59,86',C'241,107,141',
      C'111,59,86',C'241,114,148',C'242,118,151',C'242,122,154',C'70,222,176',C'75,223,178',C'79,223,180',C'84,224,182',
      C'38,117,108',C'93,225,186',C'38,117,108',C'102,226,190',C'107,226,192',C'111,227,194',C'82,141,245',C'86,144,245',
      C'91,146,246',C'95,149,246',C'43,82,138',C'103,154,246',C'43,82,138',C'112,159,247',C'116,162,247',C'120,164,247',
      C'198,172,255',C'199,174,255',C'201,176,255',C'202,177,255',C'93,96,142',C'205,181,255',C'93,96,142',C'208,185,255',
      C'209,186,255',C'210,188,255',C'185,134,235',C'187,137,236',C'188,140,236',C'190,142,236',C'88,79,134',C'194,148,238',
      C'88,79,134',C'197,153,238',C'199,156,239',C'200,159,240',C'255,182,92',C'255,184,96',C'255,185,100',C'255,187,104',
      C'118,100,72',C'255,190,112',C'118,100,72',C'255,193,121',C'255,194,125',C'255,196,129',C'101,221,214',C'105,222,215',
      C'109,222,216',C'112,223,217',C'51,117,125',C'120,224,219',C'51,117,125',C'128,225,221',C'131,226,222',C'135,226,223',
      C'222,102,93',C'223,106,97',C'224,109,101',C'224,113,105',C'103,66,72',C'226,120,113',C'103,66,72',C'227,127,121',
      C'228,130,125',C'229,134,129',C'236,167,201',C'236,169,202',C'237,171,204',C'237,173,205',C'109,93,119',C'238,177,208',
      C'109,93,119',C'239,180,210',C'239,182,212',C'240,184,213',C'120,201,157',C'123,202,159',C'127,203,162',C'130,204,164',
      C'60,108,100',C'137,206,169',C'60,108,100',C'143,209,174',C'147,210,177',C'150,211,179',C'231,201,109',C'232,202,113',
      C'232,203,116',C'233,204,120',C'107,108,79',C'234,206,127',C'107,108,79',C'235,209,135',C'235,210,138',C'236,211,142'
   };
   color A2[232]={
      C'78,158,244',C'255,0,200',C'120,200,255',C'255,150,100',C'255,176,64',C'255,190,120',C'255,200,60',C'255,120,150',
      C'96,200,255',C'255,220,100',C'255,235,150',C'180,255,120',C'170,210,120',C'255,120,220',C'255,170,120',C'255,210,150',
      C'120,220,210',C'0,170,190',C'255,120,40',C'0,120,200',C'0,220,255',C'120,230,255',C'220,60,120',C'255,20,200',
      C'170,100,255',C'80,255,200',C'255,200,60',C'78,158,244',C'55,180,255',C'0,235,255',C'130,180,240',C'120,255,210',
      C'140,220,255',C'255,165,120',C'110,190,255',C'255,125,60',C'111,231,244',C'38,218,233',C'89,181,225',C'237,193,136',
      C'89,145,188',C'241,197,128',C'255,199,72',C'226,211,123',C'227,107,224',C'192,143,80',C'182,211,243',C'70,161,181',
      C'85,140,152',C'158,100,189',C'94,143,139',C'220,182,94',C'158,123,250',C'100,167,242',C'130,203,247',C'131,224,245',
      C'240,168,77',C'104,176,201',C'241,146,138',C'118,227,255',C'241,188,138',C'73,197,133',C'222,207,163',C'254,224,113',
      C'160,120,255',C'255,193,7',C'255,214,102',C'140,200,255',C'255,112,67',C'255,82,82',C'160,255,180',C'220,230,240',
      C'140,190,160',C'0,240,255',C'0,170,160',C'176,90,140',C'230,200,100',C'200,200,205',C'240,160,90',C'64,210,255',
      C'0,240,255',C'84,160,255',C'187,154,247',C'163,190,140',C'196,120,72',C'200,230,120',C'144,224,239',C'255,160,120',
      C'170,140,255',C'255,120,200',C'96,168,232',C'230,160,40',C'255,214,64',C'200,60,40',C'60,110,200',C'255,138,61',
      C'92,125,250',C'100,199,180',C'245,76,146',C'72,141,255',C'81,211,255',C'196,212,217',C'64,209,235',C'182,148,253',
      C'86,221,185',C'191,108,85',C'123,156,249',C'102,203,233',C'108,137,164',C'45,227,250',C'142,239,188',C'131,123,106',
      C'232,111,145',C'237,104,140',C'237,104,140',C'88,223,185',C'48,129,116',C'88,223,185',C'55,87,152',C'98,152,245',
      C'98,152,245',C'201,179,254',C'88,223,185',C'88,223,185',C'88,223,185',C'98,152,245',C'55,87,152',C'98,152,245',
      C'115,103,157',C'201,179,254',C'201,179,254',C'189,146,236',C'98,152,245',C'98,152,245',C'98,152,245',C'201,179,254',
      C'115,103,157',C'201,179,254',C'108,83,147',C'189,146,236',C'189,146,236',C'251,188,111',C'201,179,254',C'201,179,254',
      C'201,179,254',C'189,146,236',C'108,83,147',C'189,146,236',C'145,108,72',C'251,188,111',C'251,188,111',C'115,222,218',
      C'189,146,236',C'189,146,236',C'189,146,236',C'251,188,111',C'145,108,72',C'251,188,111',C'65,128,136',C'115,222,218',
      C'115,222,218',C'222,117,111',C'251,188,111',C'251,188,111',C'251,188,111',C'115,222,218',C'65,128,136',C'115,222,218',
      C'127,66,73',C'222,117,111',C'222,117,111',C'234,175,207',C'115,222,218',C'115,222,218',C'115,222,218',C'222,117,111',
      C'127,66,73',C'222,117,111',C'135,100,129',C'234,175,207',C'234,175,207',C'132,204,168',C'222,117,111',C'222,117,111',
      C'222,117,111',C'234,175,207',C'135,100,129',C'234,175,207',C'74,118,106',C'132,204,168',C'132,204,168',C'230,204,126',
      C'234,175,207',C'234,175,207',C'234,175,207',C'132,204,168',C'74,118,106',C'132,204,168',C'132,118,81',C'230,204,126',
      C'230,204,126',C'164,232,240',C'132,204,168',C'132,204,168',C'132,204,168',C'230,204,126',C'132,118,81',C'230,204,126',
      C'93,134,149',C'164,232,240',C'164,232,240',C'237,104,140',C'230,204,126',C'230,204,126',C'230,204,126',C'164,232,240',
      C'93,134,149',C'164,232,240',C'136,59,89',C'237,104,140',C'237,104,140',C'88,223,185',C'164,232,240',C'164,232,240',
      C'164,232,240',C'237,104,140',C'136,59,89',C'237,104,140',C'48,129,116',C'88,223,185',C'88,223,185',C'98,152,245'
   };
   bool light=(localID==17 || localID==19 || localID==22 || localID==38 || localID==40 || localID==45 || localID==47 || localID==48 || localID==49 || localID==50 || localID==74 || localID==75 || localID==90 || localID==91 || localID==94 || localID==108 || localID==111);
   if(localID>=112) light=((localID-112)%10==4 || (localID-112)%10==6);
   if(localID==27) {
      SX_BG=InpCustomBgColor; SX_CARD=InpCustomCardColor; SX_GOLD=InpCustomAccentColor; SX_TEXT=InpCustomTextColor;
      SX_EDGE=InpCustomBorderColor; SX_MUTED=InpCustomMutedColor; SX_BLUE=InpCustomSecondaryColor; SX_GREEN=InpCustomBullColor; SX_RED=InpCustomBearColor;
      SX_ZONE_BULL=InpCustomZoneBullColor; SX_ZONE_BEAR=InpCustomZoneBearColor; SX_VOLUME=InpCustomVolumeColor;
      SX_GRID=(InpCustomGridColor==clrNONE ? InpCustomBorderColor : InpCustomGridColor);
   } else {
      SX_BG=B[localID]; SX_CARD=CARD[localID]; SX_GOLD=A1[localID]; SX_BLUE=A2[localID];
      SX_EDGE=light ? C'175,188,205' : BlendThemeColor(SX_CARD,SX_GOLD,18);
      SX_TEXT=light ? C'20,26,36' : C'228,236,244';
      SX_MUTED=light ? C'75,88,108' : C'145,164,184';
      SX_GREEN=light ? C'16,158,96' : C'52,207,151';
      SX_RED=light ? C'204,42,60' : C'246,98,113';
      if(g_themeStyle==1) SX_EDGE=SX_GOLD;
      else if(g_themeStyle==2) { SX_TEXT=light ? C'0,0,0' : C'255,255,255'; SX_EDGE=SX_BLUE; }
      else if(g_themeStyle==3) { SX_EDGE=SX_CARD; }
      SX_ZONE_BULL=C'24,65,58'; SX_ZONE_BEAR=C'73,35,49'; SX_GRID=BlendThemeColor(SX_BG,SX_EDGE,43); SX_VOLUME=SX_BLUE;
   }
   // Expanded style filters: styling only, no impact on orders, risk, signals, or trailing.
   if(g_themeStyle==4) { // PASTEL: luminous light cards, softened accents
      SX_BG=C'247,247,251'; SX_CARD=C'232,236,248'; SX_EDGE=C'197,204,221';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'250,250,250',40);
      SX_BLUE=BlendThemeColor(SX_BLUE,C'244,244,250',30);
      SX_TEXT=C'38,42,62'; SX_MUTED=C'96,104,125';
   } else if(g_themeStyle==5) { // FROST: icy blueglass surfaces
      SX_BG=C'13,25,37'; SX_CARD=C'27,48,64'; SX_EDGE=C'105,176,202';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'111,229,255',45);
      SX_BLUE=C'132,209,250'; SX_TEXT=C'233,247,252'; SX_MUTED=C'159,190,205';
   } else if(g_themeStyle==6) { // CINEMATIC: near-black canvas, warm spotlight outline
      SX_BG=BlendThemeColor(SX_BG,C'4,5,9',76);
      SX_CARD=BlendThemeColor(SX_CARD,C'12,14,23',48);
      SX_EDGE=BlendThemeColor(SX_GOLD,C'235,205,153',35);
      SX_TEXT=C'245,241,235'; SX_MUTED=C'168,165,158';
   } else if(g_themeStyle==7) { // MONOCHROME: neutral UI, distinct bullish/bearish markers preserved
      SX_BG=C'18,20,22'; SX_CARD=C'37,40,43'; SX_EDGE=C'131,138,144';
      SX_GOLD=C'227,232,235'; SX_BLUE=C'178,190,198'; SX_TEXT=C'244,247,249'; SX_MUTED=C'167,174,181';
   } else if(g_themeStyle==8) { // AURORA: theme surfaces washed with the primary accent, secondary-accent outline
      SX_BG=BlendThemeColor(SX_BG,SX_GOLD,10);
      SX_CARD=BlendThemeColor(SX_CARD,SX_GOLD,18);
      SX_EDGE=SX_BLUE;
   } else if(g_themeStyle==9) { // TERMINAL: phosphor-green console look
      SX_BG=C'0,8,2'; SX_CARD=C'4,22,8'; SX_EDGE=C'0,160,60';
      SX_GOLD=C'0,255,90'; SX_BLUE=C'120,255,160'; SX_TEXT=C'190,255,200'; SX_MUTED=C'80,160,100';
   } else if(g_themeStyle==10) { // SUNSET GLOW: warm wash and amber outline
      SX_BG=BlendThemeColor(SX_BG,C'255,120,40',8);
      SX_CARD=BlendThemeColor(SX_CARD,C'255,140,60',14);
      SX_EDGE=C'255,160,80'; SX_GOLD=BlendThemeColor(SX_GOLD,C'255,190,110',35);
   } else if(g_themeStyle==11) { // DEEP SPACE: near-black navy with periwinkle outline
      SX_BG=C'3,5,16'; SX_CARD=C'10,14,36'; SX_EDGE=C'70,90,200';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'150,200,255',30); SX_TEXT=C'226,234,255'; SX_MUTED=C'130,145,190';
   } else if(g_themeStyle==12) { // HOLOGRAPHIC: iridescent highlights and high-contrast typography
      SX_BG=BlendThemeColor(SX_BG,C'11,17,40',35);
      SX_CARD=BlendThemeColor(SX_CARD,C'29,28,65',28);
      SX_EDGE=BlendThemeColor(SX_GOLD,C'94,245,255',50);
      SX_BLUE=BlendThemeColor(SX_BLUE,C'243,106,252',32);
   } else if(g_themeStyle==13) { // BRUSHED TITANIUM: neutral materials, distinct signal colors
      SX_BG=C'25,30,36'; SX_CARD=C'42,49,56'; SX_EDGE=C'127,145,156';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'218,225,229',52);
      SX_TEXT=C'237,243,246'; SX_MUTED=C'167,180,191';
   } else if(g_themeStyle==14) { // CARBON FIBER: dark understated panels
      SX_BG=C'9,11,14'; SX_CARD=C'22,25,29'; SX_EDGE=C'49,56,65';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'135,181,205',15);
      SX_TEXT=C'233,239,242'; SX_MUTED=C'132,148,157';
   } else if(g_themeStyle==15) { // ELECTRIC CANDY: magenta / cyan neon
      SX_BG=C'16,8,32'; SX_CARD=C'31,13,51'; SX_EDGE=C'247,71,218';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'251,83,222',55);
      SX_BLUE=BlendThemeColor(SX_BLUE,C'67,246,243',45);
      SX_TEXT=C'248,232,251'; SX_MUTED=C'181,142,208';
   }
}
void ApplyBasicFinish() {
   switch(g_themeStyle) {
         case 1: SX_EDGE=BlendThemeColor(SX_CARD,SX_GOLD,38); break;
         case 2: SX_MUTED=BlendThemeColor(SX_MUTED,SX_TEXT,52); SX_EDGE=BlendThemeColor(SX_EDGE,SX_TEXT,30); break;
         case 3: SX_EDGE=BlendThemeColor(SX_CARD,SX_EDGE,35); break;
         case 4: SX_GOLD=BlendThemeColor(SX_GOLD,SX_TEXT,24); break;
         case 5: SX_GOLD=BlendThemeColor(SX_GOLD,SX_BLUE,55); break;
         case 6: SX_EDGE=BlendThemeColor(SX_CARD,SX_GOLD,18); SX_BLUE=BlendThemeColor(SX_BLUE,SX_MUTED,44); break;
         case 7: SX_GOLD=BlendThemeColor(SX_GOLD,SX_TEXT,80); SX_BLUE=BlendThemeColor(SX_BLUE,SX_MUTED,65); break;
         case 8: SX_EDGE=BlendThemeColor(SX_EDGE,SX_BLUE,48); break;
         case 9: SX_GOLD=BlendThemeColor(SX_GOLD,SX_GREEN,77); break;
         case 10: SX_GOLD=BlendThemeColor(SX_GOLD,SX_RED,42); break;
         case 11: SX_EDGE=BlendThemeColor(SX_EDGE,SX_BLUE,23); SX_GOLD=BlendThemeColor(SX_GOLD,SX_BLUE,33); break;
      }
}
void ApplyStudioFinish() {
   if(g_themeStyle==12) { // HOLOGRAPHIC: iridescent highlights and high-contrast typography
      SX_BG=BlendThemeColor(SX_BG,C'11,17,40',35);
      SX_CARD=BlendThemeColor(SX_CARD,C'29,28,65',28);
      SX_EDGE=BlendThemeColor(SX_GOLD,C'94,245,255',50);
      SX_BLUE=BlendThemeColor(SX_BLUE,C'243,106,252',32);
   } else if(g_themeStyle==13) { // BRUSHED TITANIUM: neutral materials, distinct signal colors
      SX_BG=C'25,30,36'; SX_CARD=C'42,49,56'; SX_EDGE=C'127,145,156';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'218,225,229',52);
      SX_TEXT=C'237,243,246'; SX_MUTED=C'167,180,191';
   } else if(g_themeStyle==14) { // CARBON FIBER: dark understated panels
      SX_BG=C'9,11,14'; SX_CARD=C'22,25,29'; SX_EDGE=C'49,56,65';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'135,181,205',15);
      SX_TEXT=C'233,239,242'; SX_MUTED=C'132,148,157';
   } else if(g_themeStyle==15) { // ELECTRIC CANDY: magenta / cyan neon
      SX_BG=C'16,8,32'; SX_CARD=C'31,13,51'; SX_EDGE=C'247,71,218';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'251,83,222',55);
      SX_BLUE=BlendThemeColor(SX_BLUE,C'67,246,243',45);
      SX_TEXT=C'248,232,251'; SX_MUTED=C'181,142,208';
   }
}
void ApplyTheme(int t,int style=-1) {
   g_consoleTheme=(int)MathMax(0,MathMin(SG_PALETTE_COUNT,t));
   if(style>=0) g_themeStyle=style%16;
   color p_bg[343]={
      C'20,22,30',C'30,22,33',C'16,25,43',C'32,35,42',C'19,34,39',C'38,35,33',
      C'28,29,47',C'41,51,65',C'224,216,202',C'237,237,239',C'219,228,233',C'221,208,213',
      C'20,28,41',C'30,26,41',C'16,28,49',C'32,39,50',C'19,38,46',C'38,38,39',
      C'28,32,54',C'41,54,71',C'224,217,204',C'237,238,239',C'219,229,234',C'221,209,215',
      C'31,19,27',C'38,20,31',C'22,23,41',C'41,33,40',C'26,33,37',C'45,34,31',
      C'36,27,44',C'48,49,63',C'226,216,202',C'238,237,239',C'220,228,233',C'223,208,213',
      C'16,25,42',C'27,24,42',C'13,27,50',C'29,37,51',C'16,36,47',C'36,37,40',
      C'25,31,55',C'39,52,72',C'224,217,204',C'237,238,239',C'218,228,234',C'221,208,215',
      C'15,30,27',C'27,28,32',C'13,30,41',C'29,41,40',C'16,39,38',C'35,40,31',
      C'25,34,45',C'39,55,63',C'224,217,202',C'237,238,239',C'218,229,233',C'221,209,213',
      C'27,21,38',C'35,21,39',C'19,25,47',C'37,34,48',C'23,34,44',C'42,35,38',
      C'32,28,52',C'45,50,69',C'225,216,203',C'238,237,239',C'219,228,234',C'222,208,214',
      C'32,28,22',C'39,26,28',C'22,28,38',C'41,39,36',C'26,38,34',C'45,38,28',
      C'36,32,41',C'48,54,60',C'226,217,201',C'238,238,238',C'220,229,233',C'223,209,212',
      C'18,30,28',C'29,28,32',C'15,30,42',C'31,41,41',C'18,39,38',C'37,40,32',
      C'27,34,45',C'41,55,64',C'224,217,202',C'237,238,239',C'218,229,233',C'221,209,213',
      C'32,22,27',C'39,22,32',C'22,25,41',C'41,35,40',C'26,34,38',C'45,35,31',
      C'36,29,45',C'48,51,63',C'226,216,202',C'238,237,239',C'220,228,233',C'223,208,213',
      C'31,29,22',C'38,27,28',C'22,29,38',C'40,40,36',C'25,39,34',C'44,39,28',
      C'35,33,41',C'47,55,60',C'226,217,201',C'238,238,238',C'219,229,233',C'223,209,212',
      C'15,31,37',C'27,28,38',C'13,30,46',C'29,41,47',C'16,40,43',C'35,40,37',
      C'25,35,51',C'39,56,69',C'224,217,203',C'237,238,239',C'218,229,234',C'221,209,214',
      C'23,23,40',C'32,22,41',C'17,25,48',C'34,35,50',C'21,35,45',C'40,36,39',
      C'30,29,53',C'43,51,70',C'225,216,204',C'237,237,239',C'219,228,234',C'222,208,215',
      C'22,30,36',C'32,27,37',C'17,29,46',C'34,40,46',C'20,39,43',C'39,40,36',
      C'29,34,50',C'42,55,68',C'225,217,203',C'237,238,239',C'219,229,234',C'222,209,214',
      C'23,28,36',C'33,26,38',C'17,28,46',C'35,39,47',C'21,38,43',C'40,39,36',
      C'30,33,51',C'43,54,68',C'225,217,203',C'238,238,239',C'219,229,234',C'222,209,214',
      C'31,26,25',C'38,24,30',C'22,27,40',C'41,37,38',C'26,36,36',C'45,37,30',
      C'36,31,43',C'48,53,62',C'226,217,202',C'238,238,238',C'220,228,233',C'223,208,213',
      C'29,30,24',C'37,27,29',C'20,29,39',C'39,40,38',C'24,39,36',C'43,40,29',
      C'34,34,43',C'46,55,62',C'226,217,202',C'238,238,238',C'219,229,233',C'223,209,212',
      C'21,23,29',C'31,22,33',C'16,25,42',C'33,35,41',C'20,35,38',C'39,36,32',
      C'29,29,46',C'42,51,64',C'225,216,202',C'237,237,239',C'219,228,233',C'222,208,213',
      C'30,23,32',C'37,22,35',C'21,25,44',C'40,35,44',C'25,35,41',C'44,36,34',
      C'35,29,48',C'47,51,66',C'226,216,203',C'238,237,239',C'219,228,233',C'223,208,214',
      C'16,34,29',C'27,31,33',C'13,32,42',C'29,44,42',C'16,42,39',C'36,42,32',
      C'25,37,46',C'39,57,64',C'224,218,202',C'237,238,239',C'218,229,233',C'221,210,213',
      C'38,23,25',C'43,23,30',C'26,26,40',C'45,36,38',C'30,35,36',C'49,36,30',
      C'40,30,43',C'51,52,62',C'227,217,202',C'238,237,238',C'220,228,233',C'224,208,213',
      C'17,32,43',C'28,29,43',C'14,30,50',C'30,42,51',C'17,40,47',C'36,41,40',
      C'26,35,55',C'40,56,72',C'224,217,204',C'237,238,239',C'218,229,234',C'221,209,215',
      C'37,28,27',C'42,26,31',C'25,28,41',C'44,39,40',C'29,38,37',C'48,39,31',
      C'39,33,44',C'51,54,63',C'226,217,202',C'238,238,239',C'220,229,233',C'224,209,213',
      C'14,20,32',C'8,8,12',C'56,58,64',C'40,6,8',C'30,31,34',C'44,8,18',
      C'36,12,4',C'38,6,14',C'38,40,44',C'34,20,6',C'32,26,8',C'6,30,12',
      C'8,26,16',C'24,10,40',C'36,6,6',C'40,26,14',C'40,16,14',C'232,242,252',
      C'30,24,4',C'226,228,232',C'6,14,40',C'6,26,40',C'248,248,250',C'8,6,16',
      C'6,20,30',C'4,20,34',C'34,10,24',C'6,14,26',C'18,6,34',C'10,11,14',
      C'4,24,18',C'6,16,38',C'36,6,16',C'26,28,34',C'28,18,6',C'5,25,31',
      C'7,14,36',C'226,238,248',C'39,23,32',C'244,239,250',C'27,24,25',C'32,13,17',
      C'17,31,22',C'15,12,36',C'251,251,249',C'28,40,58',C'238,251,244',C'247,240,223',
      C'254,240,245',C'251,245,226',C'27,32,19',C'35,15,33',C'5,37,40',C'9,21,63',
      C'5,36,42',C'31,33,12',C'16,18,21',C'35,9,24',C'18,20,45',C'47,27,20',
      C'12,28,8',C'40,32,23',C'28,20,9',C'9,18,34',C'15,10,38',C'8,18,20',
      C'29,12,8',C'235,246,250',C'19,13,36',C'4,22,30',C'250,246,234',C'18,16,28',
      C'24,10,38',C'10,12,8',C'26,10,6',C'236,244,250',C'30,14,30',C'4,16,28',
      C'250,244,232'
   };
   color p_card[343]={
      C'32,34,41',C'43,35,45',C'31,39,56',C'47,50,56',C'31,45,49',C'50,47,45',
      C'42,43,59',C'56,65,77',C'208,201,189',C'220,220,223',C'203,212,217',C'205,193,199',
      C'32,39,51',C'43,39,53',C'31,42,61',C'47,54,63',C'31,49,56',C'50,50,51',
      C'42,46,66',C'56,68,83',C'208,202,192',C'220,222,224',C'203,213,219',C'205,195,202',
      C'42,31,38',C'50,33,43',C'37,37,54',C'56,48,54',C'38,44,48',C'57,46,43',
      C'50,41,57',C'62,63,75',C'211,200,188',C'222,220,222',C'206,211,217',C'208,193,198',
      C'28,37,52',C'40,37,53',C'28,41,62',C'45,52,64',C'28,47,57',C'49,49,52',
      C'40,45,67',C'54,66,84',C'207,202,192',C'219,221,224',C'202,212,219',C'205,194,202',
      C'27,41,38',C'40,41,44',C'28,44,54',C'45,55,54',C'28,50,49',C'48,52,43',
      C'40,48,57',C'54,68,75',C'207,203,188',C'219,222,222',C'202,214,217',C'205,195,198',
      C'39,33,49',C'48,34,51',C'34,39,59',C'52,49,61',C'35,45,54',C'54,47,50',
      C'46,42,64',C'59,64,81',C'210,201,190',C'222,220,224',C'204,212,219',C'207,193,201',
      C'43,39,33',C'51,39,40',C'37,42,51',C'56,54,50',C'38,49,45',C'57,50,40',
      C'50,46,54',C'62,68,73',C'211,202,187',C'222,222,221',C'206,213,216',C'208,195,197',
      C'30,41,39',C'42,41,44',C'30,44,55',C'46,55,55',C'30,50,49',C'49,52,44',
      C'41,48,57',C'56,68,76',C'208,203,188',C'220,222,222',C'202,214,217',C'205,195,198',
      C'43,34,38',C'51,35,44',C'37,39,54',C'56,50,54',C'38,45,49',C'57,47,43',
      C'50,43,57',C'62,65,75',C'211,201,188',C'222,220,222',C'206,212,217',C'208,193,198',
      C'42,40,33',C'50,40,40',C'37,43,51',C'55,54,50',C'37,50,45',C'56,51,40',
      C'49,47,54',C'61,68,73',C'211,202,187',C'222,222,221',C'205,213,216',C'208,195,197',
      C'27,42,48',C'40,41,50',C'28,44,58',C'45,55,61',C'28,51,53',C'48,52,49',
      C'40,49,63',C'54,69,81',C'207,203,190',C'219,222,223',C'202,214,219',C'205,195,200',
      C'35,35,50',C'45,35,53',C'32,39,60',C'49,50,63',C'33,46,55',C'52,48,51',
      C'44,43,65',C'58,65,82',C'209,201,192',C'220,220,224',C'204,212,219',C'206,193,202',
      C'34,41,47',C'45,40,49',C'32,43,58',C'49,54,60',C'32,50,53',C'51,52,48',
      C'43,48,62',C'57,68,80',C'209,203,190',C'220,222,223',C'204,214,219',C'206,195,200',
      C'35,39,47',C'46,39,50',C'32,42,58',C'50,54,61',C'33,49,53',C'52,51,48',
      C'44,47,63',C'58,68,80',C'209,202,190',C'221,222,223',C'204,213,219',C'206,195,200',
      C'42,37,36',C'50,37,42',C'37,41,53',C'56,52,52',C'38,47,47',C'57,49,42',
      C'50,45,56',C'62,67,74',C'211,202,188',C'222,221,221',C'206,212,216',C'208,194,198',
      C'41,41,35',C'49,40,41',C'35,43,52',C'54,54,52',C'36,50,47',C'55,52,41',
      C'48,48,56',C'60,68,74',C'211,203,188',C'222,222,221',C'204,214,216',C'208,195,197',
      C'33,35,40',C'44,35,45',C'31,39,55',C'48,50,55',C'32,46,49',C'51,48,44',
      C'43,43,58',C'57,65,76',C'209,201,188',C'220,220,222',C'203,212,217',C'206,193,199',
      C'42,35,43',C'49,35,47',C'36,39,57',C'55,50,58',C'37,46,51',C'56,48,46',
      C'49,43,60',C'61,65,78',C'211,201,190',C'222,220,223',C'205,212,217',C'208,193,200',
      C'28,45,40',C'40,44,45',C'28,46,55',C'45,58,56',C'28,53,49',C'49,54,44',
      C'40,50,58',C'54,70,76',C'207,204,188',C'219,222,223',C'202,214,217',C'205,197,199',
      C'49,35,36',C'55,36,42',C'40,40,53',C'59,51,52',C'42,46,47',C'61,48,42',
      C'54,44,56',C'65,66,74',C'213,202,188',C'223,220,221',C'206,212,216',C'210,194,198',
      C'29,43,53',C'41,42,54',C'29,44,62',C'46,56,64',C'29,51,57',C'49,53,52',
      C'40,49,67',C'55,69,84',C'208,203,192',C'220,222,224',C'202,214,220',C'205,195,202',
      C'48,39,38',C'54,39,43',C'40,42,54',C'59,54,54',C'41,49,48',C'60,51,43',
      C'53,47,57',C'65,68,75',C'212,202,188',C'223,222,222',C'206,213,217',C'210,195,198',
      C'22,32,48',C'18,18,26',C'72,75,82',C'58,12,16',C'44,46,52',C'62,14,28',
      C'54,20,10',C'56,12,24',C'54,56,62',C'50,30,12',C'48,40,14',C'12,46,20',
      C'14,40,26',C'36,18,58',C'54,12,12',C'58,38,22',C'58,26,22',C'214,228,244',
      C'46,36,10',C'206,210,218',C'12,26,62',C'12,40,60',C'232,234,240',C'16,14,30',
      C'12,34,48',C'10,34,54',C'52,18,38',C'12,26,44',C'30,12,54',C'18,20,26',
      C'10,38,28',C'12,28,60',C'54,12,26',C'38,42,50',C'44,28,10',C'10,43,49',
      C'15,29,57',C'205,223,237',C'61,35,47',C'224,216,240',C'48,38,32',C'58,26,25',
      C'29,48,33',C'30,24,57',C'233,236,238',C'44,61,81',C'215,237,226',C'227,213,191',
      C'244,213,227',C'234,226,203',C'44,52,29',C'61,28,54',C'11,57,61',C'17,37,91',
      C'11,56,65',C'50,54,20',C'29,31,36',C'58,17,37',C'35,38,67',C'72,41,29',
      C'23,43,17',C'62,49,37',C'49,34,13',C'16,32,53',C'29,20,60',C'15,38,37',
      C'48,23,15',C'219,235,243',C'35,26,57',C'10,40,49',C'238,227,205',C'30,26,46',
      C'40,18,60',C'22,26,16',C'44,18,12',C'218,232,244',C'48,24,48',C'10,30,48',
      C'236,226,206'
   };
   color p_accent[343]={
      C'215,173,121',C'218,168,126',C'221,162,131',C'216,171,123',C'222,158,134',C'219,165,128',
      C'225,153,139',C'217,170,124',C'93,76,63',C'107,88,70',C'101,77,70',C'88,66,64',
      C'142,213,245',C'148,208,245',C'154,202,244',C'144,211,245',C'158,199,244',C'151,205,245',
      C'164,194,244',C'146,210,245',C'57,80,97',C'62,93,111',C'62,83,103',C'61,76,97',
      C'243,128,164',C'243,135,160',C'243,143,155',C'243,130,163',C'243,148,152',C'243,139,158',
      C'243,155,148',C'244,151,175',C'111,67,81',C'130,73,95',C'111,71,79',C'95,64,70',
      C'129,171,255',C'129,177,252',C'130,184,249',C'129,173,254',C'130,188,248',C'130,181,251',
      C'130,194,245',C'139,181,253',C'57,80,114',C'66,89,132',C'61,87,121',C'53,79,105',
      C'96,213,172',C'110,211,167',C'126,208,161',C'101,212,170',C'135,206,157',C'118,209,164',
      C'149,204,152',C'105,211,169',C'47,87,74',C'48,100,86',C'57,92,77',C'54,78,67',
      C'194,154,246',C'199,154,238',C'206,153,228',C'196,154,243',C'209,153,223',C'203,153,233',
      C'215,152,214',C'206,169,242',C'86,70,108',C'95,80,126',C'95,75,111',C'89,69,101',
      C'231,172,88',C'233,169,93',C'235,164,98',C'232,171,90',C'236,162,102',C'234,166,96',
      C'238,159,106',C'233,176,104',C'99,76,51',C'113,87,53',C'107,79,56',C'94,67,51',
      C'159,217,162',C'155,216,168',C'150,216,174',C'158,217,164',C'148,215,178',C'153,216,171',
      C'144,215,183',C'156,217,166',C'58,81,71',C'68,94,79',C'61,87,79',C'55,81,75',
      C'234,139,145',C'229,141,155',C'224,143,166',C'232,140,148',C'220,145,172',C'226,142,160',
      C'216,147,182',C'235,165,173',C'103,70,80',C'124,78,86',C'111,76,90',C'93,66,84',
      C'240,201,111',C'228,199,125',C'213,198,141',C'236,200,116',C'205,197,150',C'220,199,133',
      C'192,195,163',C'232,200,120',C'82,76,58',C'101,88,59',C'88,87,70',C'72,76,67',
      C'105,216,223',C'113,212,226',C'121,208,231',C'108,215,224',C'126,205,233',C'117,210,229',
      C'134,202,236',C'110,214,225',C'44,81,91',C'48,93,101',C'50,86,99',C'49,78,95',
      C'155,160,252',C'164,159,246',C'173,157,239',C'158,160,250',C'179,156,235',C'168,158,243',
      C'188,154,229',C'175,173,248',C'76,76,119',C'79,83,131',C'82,76,116',C'78,71,107',
      C'186,235,229',C'191,229,228',C'198,221,226',C'188,233,229',C'201,217,226',C'195,225,227',
      C'207,211,224',C'190,231,228',C'66,81,86',C'75,93,98',C'73,84,91',C'70,76,85',
      C'196,206,217',C'190,203,216',C'183,200,215',C'194,205,217',C'179,198,215',C'187,202,216',
      C'173,195,214',C'192,204,216',C'71,77,88',C'82,90,100',C'78,87,100',C'66,76,87',
      C'235,170,130',C'221,173,137',C'205,178,145',C'230,171,132',C'196,180,150',C'213,176,141',
      C'183,183,157',C'226,172,135',C'93,77,69',C'106,81,70',C'87,80,72',C'76,76,70',
      C'213,211,111',C'203,211,120',C'192,212,131',C'210,211,114',C'185,212,137',C'198,211,126',
      C'176,212,146',C'207,211,117',C'74,81,56',C'88,93,59',C'76,87,62',C'67,81,62',
      C'172,184,217',C'176,181,207',C'180,177,195',C'173,183,214',C'183,175,188',C'178,179,201',
      C'187,172,178',C'175,182,210',C'71,76,89',C'81,87,106',C'83,85,95',C'73,72,81',
      C'238,149,200',C'226,156,197',C'212,165,193',C'234,151,199',C'204,170,191',C'219,161,195',
      C'192,177,188',C'232,162,202',C'95,71,91',C'116,78,106',C'95,80,95',C'78,72,84',
      C'85,219,150',C'103,217,146',C'123,215,142',C'91,218,149',C'135,214,139',C'113,216,144',
      C'153,212,135',C'97,218,147',C'45,88,67',C'44,103,77',C'56,93,70',C'54,81,61',
      C'255,130,105',C'253,139,111',C'252,150,118',C'254,133,107',C'251,156,122',C'253,144,115',
      C'249,164,128',C'254,161,141',C'115,69,62',C'135,75,66',C'114,73,63',C'97,67,60',
      C'114,197,233',C'120,200,222',C'128,203,210',C'116,198,229',C'132,205,202',C'124,201,216',
      C'139,208,192',C'118,199,226',C'50,81,95',C'55,93,112',C'57,89,95',C'52,79,81',
      C'234,176,114',C'232,173,125',C'230,170,138',C'233,175,118',C'228,168,146',C'231,171,132',
      C'226,165,157',C'233,174,121',C'97,77,64',C'107,84,63',C'103,81,74',C'88,70,70',
      C'0,230,195',C'0,200,255',C'200,205,214',C'210,34,44',C'150,160,176',C'186,52,100',
      C'255,69,0',C'220,20,60',C'176,178,184',C'255,140,0',C'212,175,55',C'0,200,80',
      C'60,170,80',C'150,80,255',C'255,40,40',C'205,127,50',C'255,111,97',C'30,120,210',
      C'255,200,0',C'90,100,118',C'40,110,255',C'30,150,200',C'0,102,204',C'57,255,20',
      C'0,255,170',C'0,180,220',C'255,94,77',C'0,255,230',C'255,60,240',C'220,185,90',
      C'0,245,150',C'55,165,255',C'255,55,95',C'195,210,230',C'255,190,40',C'20,220,193',
      C'82,137,255',C'15,118,191',C'234,154,159',C'137,90,203',C'218,122,66',C'255,94,47',
      C'126,187,91',C'118,104,246',C'56,120,163',C'94,172,220',C'22,148,118',C'157,108,60',
      C'195,70,118',C'164,130,46',C'172,186,75',C'209,78,154',C'42,218,200',C'64,115,255',
      C'22,207,195',C'202,236,67',C'174,188,205',C'195,47,104',C'157,152,255',C'224,123,88',
      C'166,246,75',C'201,166,113',C'246,179,57',C'0,214,190',C'116,100,255',C'196,255,70',
      C'255,126,55',C'27,126,195',C'224,130,255',C'0,213,202',C'186,115,46',C'168,120,255',
      C'255,80,220',C'200,255,60',C'255,120,40',C'30,120,220',C'235,120,255',C'0,210,200',
      C'200,120,20'
   };
   color p_secondary[343]={
      C'237,130,160',C'236,131,159',C'236,133,158',C'235,134,156',C'234,135,155',C'234,136,154',
      C'233,138,153',C'235,164,174',C'106,68,78',C'122,80,87',C'112,75,81',C'96,66,72',
      C'190,172,243',C'189,173,243',C'187,174,243',C'186,176,243',C'184,177,243',C'183,178,243',
      C'181,179,243',C'180,181,243',C'71,76,102',C'82,87,118',C'76,81,110',C'65,72,97',
      C'243,186,130',C'243,184,131',C'243,183,132',C'243,181,133',C'243,179,134',C'243,177,135',
      C'243,176,136',C'243,174,137',C'95,72,64',C'111,81,73',C'103,76,70',C'95,71,66',
      C'132,222,233',C'132,220,234',C'132,219,234',C'132,217,235',C'132,216,236',C'132,214,236',
      C'131,213,237',C'131,211,238',C'50,81,95',C'58,92,108',C'54,86,101',C'50,78,95',
      C'212,193,129',C'209,194,130',C'205,194,132',C'202,195,133',C'198,195,134',C'195,196,135',
      C'191,197,137',C'188,197,138',C'73,81,65',C'83,93,74',C'76,87,70',C'65,76,62',
      C'239,150,177',C'238,150,179',C'236,150,181',C'235,150,183',C'234,150,185',C'232,151,187',
      C'231,151,189',C'232,159,196',C'95,68,90',C'111,78,104',C'103,73,98',C'88,64,88',
      C'246,143,128',C'246,144,127',C'245,145,126',C'245,146,124',C'244,146,123',C'244,147,122',
      C'243,148,121',C'244,165,141',C'103,68,60',C'120,78,67',C'111,74,62',C'102,70,59',
      C'126,212,208',C'127,212,207',C'128,212,205',C'129,212,204',C'130,213,202',C'131,213,201',
      C'132,213,200',C'133,213,198',C'51,81,81',C'59,93,91',C'56,87,85',C'53,81,79',
      C'194,156,225',C'195,155,223',C'196,155,220',C'198,154,218',C'199,154,215',C'200,153,213',
      C'201,153,211',C'210,167,215',C'87,69,95',C'102,78,108',C'95,73,100',C'88,68,93',
      C'136,188,225',C'139,188,222',C'142,189,218',C'145,189,215',C'148,190,211',C'152,190,208',
      C'155,190,204',C'158,191,201',C'65,79,86',C'76,92,96',C'72,86,89',C'63,75,78',
      C'168,185,252',C'166,186,251',C'164,187,250',C'162,188,249',C'160,189,249',C'159,190,248',
      C'157,191,247',C'155,192,246',C'61,80,104',C'71,92,118',C'65,87,109',C'56,76,95',
      C'226,148,203',C'224,148,204',C'222,149,206',C'220,149,207',C'217,149,209',C'215,150,210',
      C'213,150,212',C'217,166,219',C'88,68,100',C'103,78,114',C'95,74,108',C'87,69,101',
      C'231,183,219',C'230,185,219',C'228,186,220',C'227,188,220',C'226,189,220',C'224,191,220',
      C'223,192,221',C'222,194,221',C'81,76,89',C'94,87,101',C'86,81,95',C'73,71,84',
      C'147,183,210',C'148,184,210',C'150,184,210',C'151,185,211',C'153,186,211',C'154,186,211',
      C'156,187,211',C'157,188,211',C'64,78,92',C'75,90,105',C'71,84,98',C'61,74,86',
      C'121,199,189',C'124,198,187',C'128,197,185',C'131,196,184',C'135,196,182',C'138,195,180',
      C'142,194,178',C'145,193,177',C'61,80,79',C'71,91,88',C'67,84,81',C'64,78,76',
      C'132,213,188',C'134,213,186',C'137,213,183',C'139,213,181',C'142,213,179',C'144,213,176',
      C'147,213,174',C'149,213,172',C'57,81,72',C'67,93,80',C'62,87,74',C'60,81,70',
      C'204,158,133',C'203,159,136',C'202,160,138',C'201,160,141',C'200,161,143',C'199,162,146',
      C'198,163,148',C'205,176,166',C'83,74,74',C'95,86,85',C'88,80,81',C'76,71,74',
      C'139,210,173',C'142,208,174',C'145,206,175',C'148,205,175',C'151,203,176',C'154,201,177',
      C'157,199,178',C'160,197,179',C'66,81,79',C'76,93,90',C'72,86,85',C'69,78,80',
      C'232,204,118',C'228,204,119',C'223,205,120',C'219,205,121',C'214,206,122',C'210,206,123',
      C'206,207,124',C'201,207,125',C'72,80,57',C'82,92,63',C'75,86,61',C'67,80,58',
      C'242,205,156',C'242,203,154',C'243,200,153',C'243,198,151',C'244,196,150',C'244,194,148',
      C'244,192,147',C'245,189,145',C'95,77,67',C'111,87,74',C'103,81,70',C'88,71,62',
      C'168,220,143',C'166,219,146',C'165,219,148',C'163,218,151',C'162,217,154',C'160,217,156',
      C'158,216,159',C'157,215,162',C'58,81,70',C'66,93,80',C'61,87,76',C'57,81,74',
      C'217,152,207',C'218,153,204',C'218,153,201',C'219,154,199',C'219,155,196',C'220,156,193',
      C'220,156,190',C'225,172,197',C'94,71,87',C'110,81,97',C'102,77,89',C'88,67,79',
      C'78,158,244',C'255,0,200',C'120,200,255',C'255,150,100',C'255,176,64',C'255,190,120',
      C'255,200,60',C'255,120,150',C'96,200,255',C'255,220,100',C'255,235,150',C'180,255,120',
      C'170,210,120',C'255,120,220',C'255,170,120',C'255,210,150',C'120,220,210',C'0,170,190',
      C'255,120,40',C'0,120,200',C'0,220,255',C'120,230,255',C'220,60,120',C'255,20,200',
      C'170,100,255',C'80,255,200',C'255,200,60',C'55,180,255',C'0,235,255',C'130,180,240',
      C'120,255,210',C'140,220,255',C'255,165,120',C'110,190,255',C'255,125,60',C'111,231,244',
      C'38,218,233',C'89,181,225',C'237,193,136',C'89,145,188',C'241,197,128',C'255,199,72',
      C'226,211,123',C'227,107,224',C'192,143,80',C'182,211,243',C'70,161,181',C'85,140,152',
      C'158,100,189',C'94,143,139',C'220,182,94',C'158,123,250',C'100,167,242',C'130,203,247',
      C'131,224,245',C'240,168,77',C'104,176,201',C'241,146,138',C'118,227,255',C'241,188,138',
      C'73,197,133',C'222,207,163',C'254,224,113',C'255,190,82',C'255,112,198',C'80,220,170',
      C'255,66,95',C'0,166,179',C'255,180,210',C'80,158,255',C'160,74,52',C'0,229,255',
      C'130,90,255',C'60,220,160',C'255,60,90',C'0,170,190',C'255,170,210',C'70,150,255',
      C'180,80,60'
   };
   color p_ink[343]={
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',C'244,241,235',
      C'244,241,235',C'244,241,235',C'27,31,43',C'27,31,43',C'27,31,43',C'27,31,43',
      C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',
      C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',
      C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'20,26,36',
      C'228,236,244',C'20,26,36',C'228,236,244',C'228,236,244',C'20,26,36',C'228,236,244',
      C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',
      C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',
      C'228,236,244',C'20,26,36',C'228,236,244',C'20,26,36',C'228,236,244',C'228,236,244',
      C'228,236,244',C'228,236,244',C'20,26,36',C'228,236,244',C'20,26,36',C'20,26,36',
      C'20,26,36',C'20,26,36',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',
      C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',
      C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',C'228,236,244',
      C'228,236,244',C'20,26,36',C'228,236,244',C'228,236,244',C'20,26,36',C'228,236,244',
      C'228,236,244',C'228,236,244',C'228,236,244',C'20,26,36',C'228,236,244',C'228,236,244',
      C'20,26,36'
   };
   color p_muted[343]={
      C'176,175,173',C'180,175,174',C'176,176,178',C'181,180,178',C'176,178,175',C'182,179,174',
      C'179,178,179',C'184,185,184',C'79,79,85',C'89,91,101',C'77,83,93',C'72,72,82',
      C'176,176,176',C'180,176,177',C'176,177,179',C'181,181,180',C'176,180,178',C'182,180,176',
      C'179,179,181',C'184,186,186',C'79,80,85',C'89,92,101',C'77,83,93',C'72,72,83',
      C'179,174,172',C'182,174,174',C'178,176,177',C'184,179,177',C'178,178,175',C'184,179,174',
      C'182,177,178',C'186,184,184',C'80,79,84',C'89,91,100',C'78,83,93',C'73,72,82',
      C'175,176,176',C'179,176,177',C'175,177,180',C'180,181,180',C'175,179,178',C'182,180,176',
      C'179,178,181',C'183,185,187',C'79,80,85',C'88,92,101',C'77,83,93',C'72,72,83',
      C'175,177,172',C'179,177,174',C'175,178,177',C'180,181,177',C'175,180,175',C'181,181,174',
      C'179,179,178',C'183,186,184',C'79,80,84',C'88,92,100',C'77,84,93',C'72,72,82',
      C'178,174,175',C'181,175,176',C'177,176,179',C'183,180,179',C'177,178,177',C'183,179,176',
      C'181,177,180',C'185,184,186',C'80,79,85',C'89,91,101',C'78,83,93',C'73,72,83',
      C'180,176,170',C'182,176,173',C'178,177,176',C'184,181,176',C'178,180,174',C'184,180,173',
      C'182,179,177',C'186,186,183',C'80,80,84',C'89,92,100',C'78,83,92',C'73,72,81',
      C'176,177,172',C'179,177,174',C'176,178,177',C'181,181,177',C'176,180,175',C'182,181,174',
      C'179,179,178',C'184,186,184',C'79,80,84',C'89,92,100',C'77,84,93',C'72,72,82',
      C'180,175,172',C'182,175,174',C'178,176,177',C'184,180,177',C'178,178,175',C'184,179,174',
      C'182,178,178',C'186,185,184',C'80,79,84',C'89,91,100',C'78,83,93',C'73,72,82',
      C'179,177,170',C'182,177,173',C'178,178,176',C'184,181,176',C'178,180,174',C'184,180,173',
      C'182,179,177',C'185,186,183',C'80,80,84',C'89,92,100',C'78,83,92',C'73,72,81',
      C'175,177,175',C'179,177,176',C'175,178,178',C'180,181,179',C'175,180,177',C'181,181,175',
      C'179,180,180',C'183,186,186',C'79,80,85',C'88,92,101',C'77,84,93',C'72,72,82',
      C'177,175,176',C'180,175,177',C'176,176,179',C'182,180,180',C'176,179,177',C'183,179,176',
      C'180,178,181',C'184,185,186',C'79,79,85',C'89,91,101',C'78,83,93',C'72,72,83',
      C'177,177,175',C'180,177,175',C'176,178,178',C'182,181,179',C'176,180,177',C'182,181,175',
      C'180,179,180',C'184,186,185',C'79,80,85',C'89,92,101',C'78,84,93',C'72,72,82',
      C'177,176,175',C'181,176,176',C'176,177,178',C'182,181,179',C'176,180,177',C'183,180,175',
      C'180,179,180',C'184,186,185',C'79,80,85',C'89,92,101',C'78,83,93',C'72,72,82',
      C'179,176,171',C'182,176,173',C'178,177,177',C'184,181,176',C'178,179,175',C'184,180,173',
      C'182,178,178',C'186,185,183',C'80,80,84',C'89,92,100',C'78,83,92',C'73,72,82',
      C'179,177,171',C'182,177,173',C'177,178,176',C'183,181,176',C'177,180,175',C'184,181,173',
      C'181,179,178',C'185,186,183',C'80,80,84',C'89,92,100',C'78,84,92',C'73,72,81',
      C'176,175,173',C'180,175,174',C'176,176,177',C'181,180,177',C'176,179,175',C'182,179,174',
      C'180,178,178',C'184,185,184',C'79,79,84',C'89,91,100',C'77,83,93',C'72,72,82',
      C'179,175,174',C'182,175,175',C'177,176,178',C'184,180,178',C'178,179,176',C'184,179,175',
      C'182,178,179',C'185,185,185',C'80,79,85',C'89,91,101',C'78,83,93',C'73,72,82',
      C'175,178,173',C'179,178,174',C'175,179,177',C'180,182,178',C'175,181,175',C'182,181,174',
      C'179,180,178',C'183,186,184',C'79,80,84',C'88,92,101',C'77,84,93',C'72,73,82',
      C'182,175,171',C'184,175,173',C'179,177,177',C'185,180,176',C'179,179,175',C'185,179,173',
      C'183,178,178',C'187,185,183',C'81,80,84',C'90,91,100',C'78,83,92',C'74,72,82',
      C'175,178,177',C'179,177,177',C'175,178,180',C'181,182,180',C'175,180,178',C'182,181,176',
      C'179,180,181',C'184,186,187',C'79,80,85',C'89,92,101',C'77,84,94',C'72,72,83',
      C'181,176,172',C'183,176,174',C'179,177,177',C'185,181,177',C'179,180,175',C'185,180,174',
      C'183,179,178',C'187,186,184',C'80,80,84',C'90,92,100',C'78,83,93',C'74,72,82',
      C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',
      C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',
      C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'75,88,108',
      C'145,164,184',C'75,88,108',C'145,164,184',C'145,164,184',C'75,88,108',C'145,164,184',
      C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',
      C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',
      C'145,164,184',C'75,88,108',C'145,164,184',C'75,88,108',C'145,164,184',C'145,164,184',
      C'145,164,184',C'145,164,184',C'75,88,108',C'145,164,184',C'75,88,108',C'75,88,108',
      C'75,88,108',C'75,88,108',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',
      C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',
      C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',C'145,164,184',
      C'145,164,184',C'75,88,108',C'145,164,184',C'145,164,184',C'75,88,108',C'145,164,184',
      C'145,164,184',C'145,164,184',C'145,164,184',C'75,88,108',C'145,164,184',C'145,164,184',
      C'75,88,108'
   };
   color p_edge[343]={
      C'60,61,66',C'69,62,70',C'59,65,79',C'73,75,79',C'59,70,73',C'75,72,70',
      C'68,69,82',C'80,88,98',C'177,172,164',C'187,188,192',C'173,181,187',C'175,165,172',
      C'60,65,75',C'69,65,77',C'59,68,84',C'73,78,85',C'59,74,79',C'75,75,75',
      C'68,71,88',C'80,90,103',C'177,173,167',C'187,190,193',C'173,182,189',C'175,167,175',
      C'68,58,64',C'75,60,68',C'64,64,78',C'80,73,78',C'65,70,72',C'81,71,68',
      C'75,67,80',C'86,86,96',C'180,171,163',C'189,188,192',C'176,180,187',C'177,165,172',
      C'56,64,76',C'67,64,77',C'56,67,84',C'71,77,86',C'56,72,80',C'74,74,76',
      C'67,70,89',C'79,89,104',C'176,173,167',C'186,189,193',C'172,181,189',C'175,166,175',
      C'55,67,64',C'67,67,69',C'56,70,78',C'71,79,78',C'56,75,73',C'73,77,68',
      C'67,73,80',C'79,90,96',C'176,174,163',C'186,190,192',C'172,183,187',C'175,167,172',
      C'66,60,73',C'73,61,75',C'61,65,82',C'77,74,84',C'62,70,78',C'79,72,74',
      C'72,68,86',C'83,87,101',C'179,172,165',C'189,188,193',C'174,181,189',C'176,165,174',
      C'69,65,59',C'76,65,65',C'64,68,75',C'80,78,74',C'65,74,70',C'81,75,65',
      C'75,71,78',C'86,90,94',C'180,173,163',C'189,190,191',C'176,182,187',C'177,167,171',
      C'58,67,64',C'68,67,69',C'58,70,78',C'72,79,78',C'58,75,73',C'74,77,69',
      C'67,73,80',C'80,90,97',C'177,174,163',C'187,190,192',C'172,183,187',C'175,167,172',
      C'69,61,64',C'76,62,69',C'64,65,78',C'80,75,78',C'65,70,73',C'81,72,68',
      C'75,69,80',C'86,88,96',C'180,172,163',C'189,188,192',C'176,181,187',C'177,165,172',
      C'68,66,59',C'75,66,65',C'64,69,75',C'80,78,74',C'64,75,70',C'80,76,65',
      C'74,72,78',C'85,90,94',C'180,173,163',C'189,190,191',C'175,182,187',C'177,167,171',
      C'55,68,72',C'67,67,74',C'56,70,81',C'71,79,84',C'56,76,77',C'73,77,73',
      C'67,74,85',C'79,91,101',C'176,174,165',C'186,190,192',C'172,183,189',C'175,167,173',
      C'62,62,74',C'71,62,77',C'60,65,83',C'74,75,85',C'60,71,78',C'77,73,75',
      C'70,69,87',C'82,88,102',C'178,172,167',C'187,188,193',C'174,181,189',C'176,165,175',
      C'61,67,71',C'71,66,73',C'60,69,81',C'74,78,83',C'60,75,77',C'76,77,72',
      C'69,73,84',C'81,90,100',C'178,174,165',C'187,190,192',C'174,183,189',C'176,167,173',
      C'62,65,71',C'72,65,74',C'60,68,81',C'75,78,84',C'60,74,77',C'77,76,72',
      C'70,72,85',C'82,90,100',C'178,173,165',C'188,190,192',C'174,182,189',C'176,167,173',
      C'68,64,62',C'75,64,67',C'64,67,77',C'80,77,76',C'65,72,71',C'81,74,67',
      C'75,70,79',C'86,90,95',C'180,173,163',C'189,189,191',C'176,181,187',C'177,166,172',
      C'67,67,61',C'74,66,66',C'62,69,76',C'79,78,76',C'63,75,71',C'80,77,66',
      C'73,73,79',C'84,90,95',C'180,174,163',C'189,190,191',C'174,183,187',C'177,167,171',
      C'60,62,65',C'70,62,70',C'59,65,78',C'73,75,78',C'60,71,73',C'76,73,69',
      C'69,69,81',C'81,88,97',C'178,172,163',C'187,188,192',C'173,181,187',C'176,165,172',
      C'68,62,68',C'74,62,71',C'63,65,80',C'80,75,81',C'64,71,75',C'80,73,71',
      C'74,69,83',C'85,88,98',C'180,172,165',C'189,188,192',C'175,181,187',C'177,165,173',
      C'56,70,65',C'67,70,70',C'56,71,78',C'71,82,79',C'56,77,73',C'74,78,69',
      C'67,75,81',C'79,92,97',C'176,175,163',C'186,190,192',C'172,183,187',C'175,169,172',
      C'74,62,62',C'80,63,67',C'67,66,77',C'83,76,76',C'68,71,71',C'85,73,67',
      C'79,70,79',C'88,89,95',C'181,173,163',C'190,188,191',C'176,181,187',C'179,166,172',
      C'57,69,77',C'67,68,78',C'57,70,84',C'72,80,86',C'57,76,80',C'74,77,76',
      C'67,74,89',C'80,91,104',C'177,174,167',C'187,190,193',C'172,183,190',C'175,167,175',
      C'73,65,64',C'79,65,68',C'67,68,78',C'83,78,78',C'67,74,72',C'84,76,68',
      C'78,72,80',C'88,90,96',C'181,173,163',C'190,190,192',C'176,182,187',C'179,167,172',
      C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',
      C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',
      C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'175,188,205',
      C'55,71,91',C'175,188,205',C'55,71,91',C'55,71,91',C'175,188,205',C'55,71,91',
      C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',
      C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',
      C'55,71,91',C'175,188,205',C'55,71,91',C'175,188,205',C'55,71,91',C'55,71,91',
      C'55,71,91',C'55,71,91',C'175,188,205',C'55,71,91',C'175,188,205',C'175,188,205',
      C'175,188,205',C'175,188,205',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',
      C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',
      C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',C'55,71,91',
      C'55,71,91',C'175,188,205',C'55,71,91',C'55,71,91',C'175,188,205',C'55,71,91',
      C'55,71,91',C'55,71,91',C'55,71,91',C'175,188,205',C'55,71,91',C'55,71,91',
      C'175,188,205'
   };
   color p_bull[343]={
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'19,92,71',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'19,92,71',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'19,92,71',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'19,92,71',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'19,92,71',C'20,99,75',C'19,92,71',C'18,86,67',
      C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',C'104,203,176',
      C'104,203,176',C'104,203,176',C'18,86,67',C'20,99,75',C'19,92,71',C'18,86,67',
      C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',
      C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',
      C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'16,158,96',
      C'52,207,151',C'16,158,96',C'52,207,151',C'52,207,151',C'16,158,96',C'52,207,151',
      C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',
      C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',
      C'52,207,151',C'16,158,96',C'52,207,151',C'16,158,96',C'52,207,151',C'52,207,151',
      C'52,207,151',C'52,207,151',C'16,158,96',C'52,207,151',C'16,158,96',C'16,158,96',
      C'16,158,96',C'16,158,96',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',
      C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',
      C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',C'52,207,151',
      C'52,207,151',C'16,158,96',C'52,207,151',C'52,207,151',C'16,158,96',C'52,207,151',
      C'52,207,151',C'52,207,151',C'52,207,151',C'16,158,96',C'52,207,151',C'52,207,151',
      C'16,158,96'
   };
   color p_bear[343]={
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'119,47,66',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'119,47,66',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'119,47,66',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'119,47,66',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'119,47,66',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'119,47,66',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'241,162,173',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',C'239,146,159',
      C'239,146,159',C'242,169,179',C'129,50,70',C'150,56,79',C'139,53,74',C'129,50,70',
      C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',
      C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',
      C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'204,42,60',
      C'246,98,113',C'204,42,60',C'246,98,113',C'246,98,113',C'204,42,60',C'246,98,113',
      C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',
      C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',
      C'246,98,113',C'204,42,60',C'246,98,113',C'204,42,60',C'246,98,113',C'246,98,113',
      C'246,98,113',C'246,98,113',C'204,42,60',C'246,98,113',C'204,42,60',C'204,42,60',
      C'204,42,60',C'204,42,60',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',
      C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',
      C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',C'246,98,113',
      C'246,98,113',C'204,42,60',C'246,98,113',C'246,98,113',C'204,42,60',C'246,98,113',
      C'246,98,113',C'246,98,113',C'246,98,113',C'204,42,60',C'246,98,113',C'246,98,113',
      C'204,42,60'
   };
   if(g_consoleTheme>=599) {
      int k=g_consoleTheme-599;
      color bgT[96]={C'16,22,30', C'26,15,31', C'18,25,28', C'29,20,17', C'16,27,30', C'16,30,18',
      C'31,17,15', C'21,15,31', C'30,28,16', C'30,16,20', C'14,18,32', C'17,29,26',
      C'27,24,19', C'31,15,28', C'14,32,31', C'30,23,16', C'14,14,32', C'24,30,16',
      C'20,23,26', C'28,16,30', C'239,234,225', C'237,235,227', C'227,231,237', C'225,235,239',
      C'21,22,25', C'15,31,23', C'23,17,29', C'19,26,27', C'32,14,17', C'31,25,15',
      C'12,20,34', C'15,31,20', C'29,26,17', C'26,22,20', C'31,15,16', C'17,28,29',
      C'28,30,16', C'24,14,32', C'28,20,18', C'13,16,33', C'20,26,24', C'28,28,17',
      C'21,19,27', C'30,19,16', C'235,233,229', C'227,237,232', C'238,227,228', C'226,233,238',
      C'15,24,31', C'18,28,22', C'28,24,18', C'16,18,30', C'25,21,25', C'27,22,19',
      C'29,22,17', C'20,24,26', C'30,16,23', C'30,22,16', C'21,20,26', C'14,22,32',
      C'22,25,21', C'26,17,29', C'29,27,17', C'18,21,28', C'31,27,15', C'16,30,28',
      C'31,15,15', C'23,18,28', C'230,232,234', C'239,230,225', C'227,237,233', C'232,226,238',
      C'17,23,28', C'17,29,19', C'30,19,16', C'15,28,31', C'24,21,25', C'27,22,19',
      C'22,16,30', C'21,24,25', C'31,15,15', C'17,29,29', C'26,25,20', C'18,15,31',
      C'17,28,25', C'28,17,21', C'16,26,30', C'27,28,18', C'31,15,26', C'15,20,31',
      C'19,24,27', C'28,18,28', C'237,235,227', C'240,232,224', C'227,238,235', C'226,227,238'};
      SX_BG=bgT[k];
      color cardT[96]={C'26,34,45', C'39,24,47', C'29,38,43', C'45,32,27', C'25,41,46', C'26,45,29',
      C'47,28,25', C'33,25,47', C'45,43,26', C'45,26,31', C'23,29,49', C'27,45,40',
      C'41,37,31', C'47,25,43', C'23,48,47', C'46,36,25', C'23,23,48', C'37,45,26',
      C'31,36,40', C'42,26,45', C'227,220,206', C'224,221,209', C'210,214,224', C'206,222,227',
      C'32,34,39', C'25,47,36', C'36,27,45', C'30,40,41', C'48,23,28', C'47,38,24',
      C'21,32,50', C'24,47,32', C'44,40,27', C'40,34,32', C'47,25,27', C'27,43,44',
      C'42,45,26', C'38,23,48', C'43,31,29', C'22,25,50', C'31,40,37', C'43,43,28',
      C'33,31,41', C'45,30,26', C'221,218,213', C'209,224,217', C'225,208,211', C'208,218,226',
      C'25,38,47', C'29,43,35', C'42,37,29', C'26,29,45', C'39,32,39', C'41,34,31',
      C'44,34,27', C'31,37,40', C'45,26,36', C'45,35,26', C'33,32,40', C'23,34,49',
      C'35,38,33', C'40,27,44', C'45,42,27', C'29,33,43', C'47,41,25', C'26,45,43',
      C'47,24,25', C'36,29,43', C'213,217,220', C'227,214,206', C'209,224,219', C'216,208,226',
      C'28,36,43', C'27,44,30', C'45,31,26', C'24,43,47', C'38,33,38', C'41,35,30',
      C'34,26,45', C'33,37,38', C'47,24,24', C'27,43,44', C'40,38,31', C'29,24,47',
      C'28,43,39', C'43,28,33', C'25,40,46', C'41,43,29', C'47,25,39', C'25,31,47',
      C'31,37,41', C'42,29,42', C'224,221,210', C'228,217,205', C'208,225,222', C'208,209,226'};
      SX_CARD=cardT[k];
      color accentT[96]={C'73,206,233', C'140,233,73', C'233,166,73', C'233,148,73', C'73,233,233', C'73,233,73',
      C'233,137,73', C'196,83,234', C'233,206,73', C'234,83,120', C'73,140,233', C'73,233,180',
      C'233,185,73', C'233,73,193', C'73,233,211', C'233,164,73', C'101,123,236', C'174,233,73',
      C'233,126,73', C'233,73,233', C'140,78,23', C'149,62,24', C'24,76,149', C'23,101,140',
      C'73,233,206', C'73,233,153', C'233,73,180', C'73,233,153', C'233,105,73', C'233,180,73',
      C'73,180,233', C'73,233,113', C'73,206,233', C'233,132,73', C'234,83,108', C'73,233,227',
      C'201,233,73', C'168,101,236', C'233,111,73', C'92,127,235', C'73,233,169', C'233,222,73',
      C'187,92,235', C'73,233,219', C'149,74,24', C'17,105,76', C'149,24,66', C'24,87,149',
      C'233,193,73', C'73,233,126', C'233,174,73', C'73,233,201', C'233,73,206', C'73,233,174',
      C'233,148,73', C'73,193,233', C'233,73,140', C'73,233,73', C'206,73,233', C'233,126,73',
      C'158,233,73', C'211,73,233', C'233,195,73', C'73,166,233', C'233,201,73', C'73,233,201',
      C'233,95,73', C'180,101,236', C'24,76,149', C'149,53,24', C'17,105,83', C'70,24,149',
      C'233,180,73', C'79,233,73', C'233,153,73', C'233,121,73', C'233,73,233', C'233,153,73',
      C'233,211,73', C'73,233,174', C'234,83,88', C'73,233,222', C'233,190,73', C'156,110,237',
      C'73,233,153', C'234,83,113', C'233,142,73', C'227,233,73', C'233,73,164', C'73,233,174',
      C'233,132,73', C'222,73,233', C'24,87,149', C'149,66,24', C'17,105,98', C'24,24,149'};
      SX_GOLD=accentT[k];
      color secondaryT[96]={C'159,115,222', C'115,222,213', C'115,168,222', C'115,195,222', C'115,141,222', C'222,204,115',
      C'222,201,115', C'115,204,222', C'115,186,222', C'115,204,222', C'222,195,115', C'195,115,222',
      C'115,186,222', C'115,222,222', C'222,177,115', C'115,186,222', C'115,222,186', C'150,115,222',
      C'115,186,222', C'222,222,115', C'39,92,145', C'39,83,145', C'110,39,145', C'56,39,145',
      C'222,168,115', C'222,115,186', C'115,222,168', C'222,115,222', C'115,204,222', C'115,150,222',
      C'222,186,115', C'222,150,115', C'222,201,115', C'115,222,222', C'115,222,186', C'222,115,168',
      C'186,115,222', C'168,222,115', C'115,177,222', C'222,183,115', C'222,115,222', C'132,115,222',
      C'115,222,132', C'222,136,115', C'39,83,145', C'110,39,145', C'39,110,145', C'145,74,39',
      C'115,204,222', C'222,168,115', C'115,177,222', C'222,115,168', C'115,222,168', C'222,150,115',
      C'115,186,222', C'150,115,222', C'115,222,186', C'222,165,115', C'115,222,168', C'115,204,222',
      C'115,186,222', C'195,222,115', C'115,159,222', C'222,150,115', C'132,115,222', C'222,115,168',
      C'115,222,204', C'115,222,150', C'145,74,39', C'39,101,145', C'145,39,92', C'137,103,36',
      C'115,204,222', C'222,115,222', C'115,204,222', C'115,222,222', C'186,222,115', C'115,186,222',
      C'115,204,222', C'222,150,115', C'115,204,222', C'222,115,168', C'115,159,222', C'115,222,168',
      C'222,150,115', C'115,222,213', C'115,193,222', C'168,115,222', C'168,222,115', C'222,168,115',
      C'115,186,222', C'115,222,132', C'145,74,39', C'39,101,145', C'145,39,110', C'145,92,39'};
      SX_BLUE=secondaryT[k];
      color inkT[96]={C'233,236,242', C'239,233,242', C'233,239,242', C'242,235,233', C'233,239,242', C'233,242,234',
      C'242,234,233', C'236,233,242', C'242,240,233', C'242,233,235', C'233,235,242', C'233,242,239',
      C'242,239,233', C'242,233,240', C'233,242,241', C'242,237,233', C'233,233,242', C'238,242,233',
      C'233,237,242', C'240,233,242', C'20,26,36', C'20,26,36', C'20,26,36', C'20,26,36',
      C'233,235,242', C'233,242,237', C'237,233,242', C'233,240,242', C'242,233,234', C'242,238,233',
      C'233,236,242', C'233,242,236', C'242,240,233', C'242,235,233', C'242,233,233', C'233,241,242',
      C'240,242,233', C'238,233,242', C'242,234,233', C'233,234,242', C'233,242,239', C'242,241,233',
      C'235,233,242', C'242,234,233', C'20,26,36', C'20,26,36', C'20,26,36', C'20,26,36',
      C'233,238,242', C'233,242,236', C'242,238,233', C'233,234,242', C'242,233,242', C'242,236,233',
      C'242,236,233', C'233,239,242', C'242,233,237', C'242,237,233', C'234,233,242', C'233,237,242',
      C'236,242,233', C'239,233,242', C'242,240,233', C'233,235,242', C'242,239,233', C'233,242,240',
      C'242,233,233', C'237,233,242', C'20,26,36', C'20,26,36', C'20,26,36', C'20,26,36',
      C'233,237,242', C'233,242,234', C'242,235,233', C'233,240,242', C'241,233,242', C'242,237,233',
      C'237,233,242', C'233,239,242', C'242,233,233', C'233,241,242', C'242,240,233', C'234,233,242',
      C'233,242,239', C'242,233,236', C'233,239,242', C'241,242,233', C'242,233,239', C'233,235,242',
      C'233,239,242', C'242,233,242', C'20,26,36', C'20,26,36', C'20,26,36', C'20,26,36'};
      SX_TEXT=inkT[k];
      color mutedT[96]={C'138,150,168', C'158,138,168', C'138,158,168', C'168,147,138', C'138,161,168', C'138,168,143',
      C'168,142,138', C'149,138,168', C'168,164,138', C'168,138,145', C'138,145,168', C'138,168,161',
      C'168,158,138', C'168,138,163', C'138,168,167', C'168,153,138', C'138,138,168', C'156,168,138',
      C'138,153,168', C'163,138,168', C'108,96,75', C'102,96,71', C'84,96,120', C'75,100,108',
      C'138,145,168', C'138,168,154', C'153,138,168', C'138,164,168', C'168,138,143', C'168,156,138',
      C'138,149,168', C'138,168,148', C'168,161,138', C'168,145,138', C'168,138,140', C'138,166,168',
      C'163,168,138', C'156,138,168', C'168,143,138', C'138,142,168', C'138,168,158', C'168,167,138',
      C'145,138,168', C'168,144,138', C'102,93,71', C'71,102,87', C'120,84,90', C'79,100,114',
      C'138,156,168', C'138,168,150', C'168,155,138', C'138,142,168', C'168,138,168', C'168,148,138',
      C'168,150,138', C'138,159,168', C'168,138,153', C'168,152,138', C'143,138,168', C'138,151,168',
      C'148,168,138', C'161,138,168', C'168,163,138', C'138,147,168', C'168,160,138', C'138,168,164',
      C'168,138,139', C'153,138,168', C'79,96,114', C'114,92,79', C'71,102,91', C'101,84,120',
      C'138,154,168', C'138,168,142', C'168,145,138', C'138,163,168', C'166,138,168', C'168,151,138',
      C'151,138,168', C'138,158,168', C'168,138,138', C'138,167,168', C'168,162,138', C'144,138,168',
      C'138,168,159', C'168,138,148', C'138,160,168', C'165,168,138', C'168,138,158', C'138,147,168',
      C'138,158,168', C'168,138,168', C'102,97,71', C'108,92,75', C'71,102,96', C'84,86,120'};
      SX_MUTED=mutedT[k];
      color edgeT[96]={C'52,66,85', C'75,50,88', C'57,73,81', C'84,63,53', C'51,78,86', C'52,85,58',
      C'88,55,50', C'64,50,88', C'85,81,52', C'85,52,61', C'47,58,91', C'53,84,77',
      C'78,72,60', C'88,50,81', C'48,90,88', C'86,69,51', C'48,48,90', C'72,85,52',
      C'61,69,77', C'80,52,85', C'191,178,156', C'186,181,161', C'162,170,185', C'156,182,191',
      C'63,66,74', C'50,88,70', C'69,53,84', C'59,76,79', C'90,48,55', C'89,73,49',
      C'44,62,94', C'49,89,62', C'83,76,55', C'75,66,62', C'88,50,53', C'55,81,83',
      C'80,85,52', C'72,48,90', C'81,61,57', C'45,51,93', C'61,77,71', C'82,81,56',
      C'64,60,78', C'85,59,52', C'180,176,167', C'161,186,173', C'187,160,164', C'159,176,188',
      C'50,72,88', C'57,81,67', C'80,70,58', C'52,57,85', C'74,63,74', C'78,66,60',
      C'83,66,55', C'61,72,77', C'85,52,69', C'85,68,52', C'64,62,75', C'47,66,91',
      C'67,73,64', C'76,55,83', C'84,79,53', C'57,64,81', C'88,78,50', C'52,85,81',
      C'89,49,50', C'69,57,81', C'168,173,179', C'191,169,156', C'161,186,177', C'172,159,188',
      C'56,70,82', C'55,83,58', C'85,60,52', C'49,82,89', C'73,64,73', C'79,68,59',
      C'67,52,85', C'64,70,73', C'89,49,49', C'55,82,83', C'77,73,61', C'57,49,89',
      C'56,82,74', C'82,56,64', C'51,77,86', C'79,81,57', C'88,50,75', C'50,61,88',
      C'60,72,78', C'80,58,80', C'185,181,162', C'193,173,154', C'160,187,182', C'159,161,188'};
      SX_EDGE=edgeT[k];
      color bullT[96]={C'57,208,133', C'57,208,107', C'57,208,158', C'57,208,133', C'57,208,171', C'57,208,82',
      C'57,208,133', C'57,208,133', C'57,208,120', C'57,208,145', C'57,145,208', C'57,208,133',
      C'57,208,120', C'57,208,133', C'57,208,133', C'57,133,208', C'57,208,133', C'57,208,107',
      C'57,208,133', C'57,208,133', C'29,124,77', C'29,124,77', C'27,116,71', C'29,124,77',
      C'57,208,133', C'57,208,133', C'57,208,133', C'57,208,158', C'57,208,133', C'57,208,133',
      C'57,145,208', C'57,208,95', C'57,208,133', C'57,208,133', C'57,208,133', C'57,208,133',
      C'57,208,107', C'57,208,133', C'57,208,133', C'57,145,208', C'57,208,133', C'57,208,120',
      C'57,208,133', C'57,208,158', C'29,124,77', C'29,124,77', C'27,116,71', C'29,124,77',
      C'57,208,133', C'57,208,120', C'57,208,133', C'57,208,133', C'57,208,133', C'57,208,133',
      C'57,133,208', C'57,208,158', C'57,208,133', C'57,208,120', C'57,208,133', C'57,208,133',
      C'57,208,107', C'57,208,133', C'57,208,120', C'57,145,208', C'57,208,133', C'57,208,133',
      C'57,208,133', C'57,208,133', C'29,124,77', C'29,124,77', C'29,124,77', C'27,116,71',
      C'57,208,133', C'57,208,107', C'57,208,133', C'57,208,133', C'57,208,133', C'57,208,133',
      C'57,208,133', C'57,208,133', C'57,208,133', C'57,208,133', C'57,208,133', C'57,208,133',
      C'57,208,133', C'57,208,133', C'57,145,208', C'57,208,120', C'57,208,133', C'57,208,133',
      C'57,208,133', C'57,208,133', C'29,124,77', C'29,124,77', C'29,124,77', C'27,116,71'};
      SX_GREEN=bullT[k];
      color bearT[96]={C'225,71,84', C'225,71,122', C'225,84,71', C'225,76,71', C'225,71,96', C'225,71,84',
      C'225,71,84', C'225,71,96', C'225,71,71', C'225,71,84', C'225,135,71', C'225,71,84',
      C'225,76,71', C'225,71,84', C'225,71,84', C'225,135,71', C'225,71,84', C'225,71,84',
      C'225,71,84', C'225,71,84', C'167,27,39', C'167,27,39', C'167,27,39', C'167,27,39',
      C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84',
      C'225,127,71', C'225,71,84', C'225,71,84', C'225,71,84', C'225,84,71', C'225,71,84',
      C'225,71,84', C'225,71,84', C'225,71,84', C'225,127,71', C'225,71,84', C'225,71,71',
      C'225,71,84', C'225,71,84', C'167,27,39', C'167,27,39', C'167,27,39', C'167,27,39',
      C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84',
      C'225,127,71', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84',
      C'225,71,84', C'225,71,84', C'225,71,71', C'225,127,71', C'225,71,84', C'225,71,84',
      C'225,71,84', C'225,71,84', C'167,27,39', C'167,27,39', C'167,27,39', C'167,27,39',
      C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84', C'225,71,84',
      C'225,71,84', C'225,71,84', C'225,102,71', C'225,71,84', C'225,71,84', C'225,71,84',
      C'225,71,84', C'225,71,84', C'225,127,71', C'225,71,84', C'225,71,84', C'225,71,84',
      C'225,71,84', C'225,71,84', C'167,27,39', C'167,27,39', C'167,27,39', C'167,27,39'};
      SX_RED=bearT[k];
      SX_GRID=BlendThemeColor(SX_BG,SX_TEXT,10); SX_VOLUME=SX_BLUE;
      SX_ZONE_BULL=BlendThemeColor(SX_BG,SX_GREEN,16); SX_ZONE_BEAR=BlendThemeColor(SX_BG,SX_RED,16);
      ApplyStudioFinish();
   } else if(g_consoleTheme>=587) {
      color ground[12]={C'10,25,25',C'29,23,17',C'16,26,43',C'33,22,39',C'38,24,18',C'17,31,39',C'25,32,39',C'23,21,37',C'17,30,22',C'11,32,42',C'36,20,30',C'21,26,51'};
      color primary[12]={C'100,229,180',C'255,191,102',C'129,183,255',C'222,159,255',C'255,164,125',C'133,224,210',C'217,230,241',C'185,167,255',C'164,220,153',C'113,229,245',C'255,155,183',C'167,184,255'};
      color highlight[12]={C'224,189,119',C'118,232,217',C'159,240,229',C'255,203,130',C'241,212,143',C'202,209,255',C'145,213,250',C'121,239,215',C'242,205,123',C'144,171,255',C'225,202,144',C'240,200,121'};
      int k=g_consoleTheme-587;
      SX_BG=ground[k]; SX_GOLD=primary[k]; SX_BLUE=highlight[k];
      SX_TEXT=C'236,246,244'; SX_MUTED=C'161,186,186';
      SX_CARD=BlendThemeColor(SX_BG,SX_TEXT,7); SX_EDGE=BlendThemeColor(SX_CARD,SX_GOLD,31);
      SX_GREEN=C'101,225,168'; SX_RED=C'245,132,148';
      SX_GRID=BlendThemeColor(SX_BG,SX_TEXT,8); SX_VOLUME=SX_BLUE;
      SX_ZONE_BULL=BlendThemeColor(SX_BG,SX_GREEN,16); SX_ZONE_BEAR=BlendThemeColor(SX_BG,SX_RED,16);
      ApplyBasicFinish(); ApplyStudioFinish();
   } else if(g_consoleTheme>=575) {
      color bg[12]={C'15,22,28',C'8,25,42',C'9,24,20',C'32,21,12',C'22,15,38',C'35,15,24',C'13,27,42',C'24,28,34',C'18,32,25',C'34,23,19',C'19,20,43',C'37,24,35'};
      color accent[12]={C'245,193,77',C'94,225,255',C'60,224,151',C'255,158,59',C'194,150,255',C'255,114,137',C'104,176,255',C'207,221,236',C'136,224,166',C'239,163,114',C'160,169,255',C'250,168,213'};
      int k=g_consoleTheme-575;
      SX_BG=bg[k]; SX_GOLD=accent[k]; SX_CARD=BlendThemeColor(SX_BG,C'218,232,245',7);
      SX_BLUE=BlendThemeColor(SX_GOLD,C'103,194,255',45);
      SX_TEXT=C'240,246,252'; SX_MUTED=C'166,185,202';
      SX_GREEN=C'64,225,151'; SX_RED=C'249,103,132';
      SX_EDGE=BlendThemeColor(SX_CARD,SX_GOLD,38);
      if(g_themeStyle==2) SX_EDGE=SX_GOLD;
      if(g_themeStyle==3) SX_EDGE=SX_CARD;
      SX_GRID=BlendThemeColor(SX_BG,SX_TEXT,10); SX_VOLUME=SX_BLUE;
      SX_ZONE_BULL=BlendThemeColor(SX_BG,SX_GREEN,18); SX_ZONE_BEAR=BlendThemeColor(SX_BG,SX_RED,18);
   } else if(g_consoleTheme>=344) {
      int localID=g_consoleTheme-344;
      if(localID>=27) localID++;
      ApplyStudioPalette(localID);
   } else {
   if(g_consoleTheme==216) {
      SX_BG=InpCustomBgColor; SX_CARD=InpCustomCardColor; SX_GOLD=InpCustomAccentColor;
      SX_BLUE=InpCustomSecondaryColor; SX_TEXT=InpCustomTextColor; SX_MUTED=InpCustomMutedColor;
      SX_EDGE=InpCustomBorderColor; SX_GREEN=InpCustomBullColor; SX_RED=InpCustomBearColor;
   } else {
      int slot=PaletteSlot(g_consoleTheme);
      SX_BG=p_bg[slot]; SX_CARD=p_card[slot]; SX_GOLD=p_accent[slot]; SX_BLUE=p_secondary[slot];
      SX_TEXT=p_ink[slot]; SX_MUTED=p_muted[slot]; SX_EDGE=p_edge[slot]; SX_GREEN=p_bull[slot]; SX_RED=p_bear[slot];
      if(slot<264 || g_themeStyle>=8) ApplyBasicFinish();
   }
   SX_ZONE_BULL=g_consoleTheme==216 ? InpCustomZoneBullColor : BlendThemeColor(SX_BG,SX_GREEN,13);
   SX_ZONE_BEAR=g_consoleTheme==216 ? InpCustomZoneBearColor : BlendThemeColor(SX_BG,SX_RED,13);
   SX_GRID=(g_consoleTheme==216 && InpCustomGridColor!=clrNONE) ? InpCustomGridColor : BlendThemeColor(SX_BG,SX_TEXT,8);
   SX_VOLUME=g_consoleTheme==216 ? InpCustomVolumeColor : SX_BLUE;
   if(g_consoleTheme>=265 && g_themeStyle<8) {
      bool light=SX_TEXT==C'20,26,36';
      if(g_themeStyle==1) SX_EDGE=SX_GOLD;
      else if(g_themeStyle==2) { SX_TEXT=light ? C'0,0,0' : C'255,255,255'; SX_EDGE=SX_BLUE; }
      else if(g_themeStyle==3) { SX_EDGE=SX_CARD; }
      SX_ZONE_BULL=C'24,65,58'; SX_ZONE_BEAR=C'73,35,49'; SX_GRID=SX_EDGE; SX_VOLUME=SX_BLUE;
   // Style filters from the source palettes.
   if(g_themeStyle==4) { // PASTEL: luminous light cards, softened accents
      SX_BG=C'247,247,251'; SX_CARD=C'232,236,248'; SX_EDGE=C'197,204,221';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'250,250,250',40);
      SX_BLUE=BlendThemeColor(SX_BLUE,C'244,244,250',30);
      SX_TEXT=C'38,42,62'; SX_MUTED=C'96,104,125';
   } else if(g_themeStyle==5) { // FROST: icy blueglass surfaces
      SX_BG=C'13,25,37'; SX_CARD=C'27,48,64'; SX_EDGE=C'105,176,202';
      SX_GOLD=BlendThemeColor(SX_GOLD,C'111,229,255',45);
      SX_BLUE=C'132,209,250'; SX_TEXT=C'233,247,252'; SX_MUTED=C'159,190,205';
   } else if(g_themeStyle==6) { // CINEMATIC: near-black canvas, warm spotlight outline
      SX_BG=BlendThemeColor(SX_BG,C'4,5,9',76);
      SX_CARD=BlendThemeColor(SX_CARD,C'12,14,23',48);
      SX_EDGE=BlendThemeColor(SX_GOLD,C'235,205,153',35);
      SX_TEXT=C'245,241,235'; SX_MUTED=C'168,165,158';
   } else if(g_themeStyle==7) { // MONOCHROME: neutral UI, distinct bullish/bearish markers preserved
      SX_BG=C'18,20,22'; SX_CARD=C'37,40,43'; SX_EDGE=C'131,138,144';
      SX_GOLD=C'227,232,235'; SX_BLUE=C'178,190,198'; SX_TEXT=C'244,247,249'; SX_MUTED=C'167,174,181';
   }
   }
   if(g_themeStyle>=12) ApplyStudioFinish();
   }
   if(g_bpTheme>=0) BPLoadTheme(g_bpTheme);
   if(InpEnablePaletteOverrides) {
      if(InpOverrideBg!=clrNONE) SX_BG=InpOverrideBg;
      if(InpOverrideCard!=clrNONE) SX_CARD=InpOverrideCard;
      if(InpOverrideAccent!=clrNONE) SX_GOLD=InpOverrideAccent;
      if(InpOverrideSecondary!=clrNONE) SX_BLUE=InpOverrideSecondary;
      if(InpOverrideText!=clrNONE) SX_TEXT=InpOverrideText;
      if(InpOverrideMuted!=clrNONE) SX_MUTED=InpOverrideMuted;
      if(InpOverrideBorder!=clrNONE) SX_EDGE=InpOverrideBorder;
      if(InpOverrideBull!=clrNONE) SX_GREEN=InpOverrideBull;
      if(InpOverrideBear!=clrNONE) SX_RED=InpOverrideBear;
      if(InpOverrideZoneBull!=clrNONE) SX_ZONE_BULL=InpOverrideZoneBull;
      if(InpOverrideZoneBear!=clrNONE) SX_ZONE_BEAR=InpOverrideZoneBear;
      if(InpOverrideGrid!=clrNONE) SX_GRID=InpOverrideGrid;
      if(InpOverrideVolume!=clrNONE) SX_VOLUME=InpOverrideVolume;
   }
   if(InpApplyThemeToChart) {
      RememberChart();
      ChartSetInteger(0,CHART_FOREGROUND,false);
      if(InpStyleCandles) { ChartSetInteger(0,CHART_MODE,CHART_CANDLES); ChartSetInteger(0,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK); }
      ChartSetInteger(0,CHART_SHOW_GRID,InpShowChartGrid);
      ChartSetInteger(0,CHART_COLOR_BACKGROUND,SX_BG);
      ChartSetInteger(0,CHART_COLOR_FOREGROUND,SX_TEXT);
      ChartSetInteger(0,CHART_COLOR_GRID,SX_GRID);
      ChartSetInteger(0,CHART_COLOR_CANDLE_BULL,g_consoleTheme==THEME_CUSTOM ? SX_GOLD : SX_GREEN);
      ChartSetInteger(0,CHART_COLOR_CANDLE_BEAR,SX_RED);
      ChartSetInteger(0,CHART_COLOR_CHART_UP,InpChartUpWickColor==clrNONE ? (g_consoleTheme==THEME_CUSTOM ? SX_GOLD : SX_GREEN) : InpChartUpWickColor);
      ChartSetInteger(0,CHART_COLOR_CHART_DOWN,InpChartDownWickColor==clrNONE ? SX_RED : InpChartDownWickColor);
      ChartSetInteger(0,CHART_COLOR_VOLUME,SX_VOLUME);
   }
}
string PositionATRKey(ulong ticket) {
   if(g_tester) return g_key+"A"+StringFormat("%I64u",ticket);
   return g_guardKey+"A"+StringFormat("%I64u",ticket);
}
double PositionATR(ulong ticket,double fallback) {
   string key=PositionATRKey(ticket);
   return GlobalVariableCheck(key) ? GlobalVariableGet(key) : fallback;
}
string PositionExcursionKey(ulong ticket) {
   return PositionATRKey(ticket)+"_EX";
}
string PositionPartialKey(ulong ticket) {
   return PositionATRKey(ticket)+"_PT";
}
double UpdatePositionExcursion(ulong ticket,int direction,double market) {
   string key=PositionExcursionKey(ticket);
   if(!GlobalVariableCheck(key)) { GlobalVariableSet(key,market); return market; }
   double old=GlobalVariableGet(key);
   if((direction>0 && market>old) || (direction<0 && market<old)) { GlobalVariableSet(key,market); return market; }
   return old;
}
double PositionCostPrice(double lots) {
   if(InpPositiveCostLockPerLot<=0 || lots<=0) return 0;
   double tick=TickSize(),val=SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_VALUE);
   if(tick<=0 || val<=0) return 0;
   return InpPositiveCostLockPerLot*tick/val;
}
double ConsoleEquity() { return AccountInfoDouble(ACCOUNT_EQUITY); }
double ConsoleBalance() { return AccountInfoDouble(ACCOUNT_BALANCE); }
double TickSize() {
   double value=SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_SIZE);
   return value>0 ? value : g_consolePoint;
}
double MinStopDistance(bool modifying) {
   double stops=(double)SymbolInfoInteger(g_symbol,SYMBOL_TRADE_STOPS_LEVEL);
   if(modifying) stops=MathMax(stops,(double)SymbolInfoInteger(g_symbol,SYMBOL_TRADE_FREEZE_LEVEL));
   return (stops+2+(InpAutoWidenStop ? g_stopPaddingPts : 0))*g_consolePoint+TickSize();
}
bool Tick(MqlTick &quote) {
   if(!SymbolInfoTick(g_symbol,quote) || quote.bid<=0 || quote.ask<=0 || quote.ask<quote.bid) return false;
   if(InpClockRejectBadQuotes && (!MathIsValidNumber(quote.bid) || !MathIsValidNumber(quote.ask) || quote.time<=0)) return false;
   return true;
}
double Source(MqlRates &bar) {
   if(InpSource==SOURCE_HA_CLOSE) return (bar.open+bar.high+bar.low+bar.close)/4.0;
   if(InpSource==SOURCE_HL2) return (bar.high+bar.low)/2.0;
   if(InpSource==SOURCE_HLC3) return (bar.high+bar.low+bar.close)/3.0;
   if(InpSource==SOURCE_OPEN) return bar.open;
   return bar.close;
}
double EMAValue(MqlRates &bars[],int count,int period) {
   if(count<period || period<1) return 0;
   double value=bars[0].close;
   double alpha=2.0/(period+1.0);
   for(int i=1;i<count;i++) value+=alpha*(bars[i].close-value);
   return value;
}
int Trend(ENUM_TIMEFRAMES tf) {
   MqlRates bars[];
   ArraySetAsSeries(bars,false);
   int count=CopyRates(g_symbol,tf,1,(int)MathMax(InpSlowMA*3,InpSlowMA+50),bars);
   if(count<InpSlowMA*3) return 0;
   double fast=EMAValue(bars,count,InpFastMA),slow=EMAValue(bars,count,InpSlowMA);
   if(fast<=0 || slow<=0) return 0;
   return fast>slow ? 1 : fast<slow ? -1 : 0;
}
void UpdateMTF(bool force=false) {
   if(!force && TimeCurrent()-g_lastMTF<10) return;
   ENUM_TIMEFRAMES frames[5]={PERIOD_M5,PERIOD_M15,PERIOD_M30,PERIOD_H1,PERIOD_H4};
   for(int i=0;i<5;i++) g_mtf[i]=Trend(frames[i]);
   bool first=false,second=false;
   for(int i=0;i<5;i++) {
      if(InpTrendTF1==frames[i]) { g_tf1=g_mtf[i]; first=true; }
      if(InpTrendTF2==frames[i]) { g_tf2=g_mtf[i]; second=true; }
   }
   if(!first) g_tf1=Trend(InpTrendTF1);
   if(!second) g_tf2=Trend(InpTrendTF2);
   g_lastMTF=TimeCurrent();
}
void UpdateLevels() {
   MqlRates bars[]; ArraySetAsSeries(bars,false);
   if(CopyRates(g_symbol,PERIOD_D1,1,1,bars)==1) {
      g_pdh=bars[0].high; g_pdl=bars[0].low;
      g_pivot=(bars[0].high+bars[0].low+bars[0].close)/3.0;
      g_r1=2*g_pivot-g_pdl; g_s1=2*g_pivot-g_pdh;
   } else { g_pdh=0; g_pdl=0; g_pivot=0; g_r1=0; g_s1=0; }
   if(CopyRates(g_symbol,PERIOD_W1,1,1,bars)==1) { g_pwh=bars[0].high; g_pwl=bars[0].low; }
   else { g_pwh=0; g_pwl=0; }
   g_dayOpen=iOpen(g_symbol,PERIOD_D1,0);
}

double RegressionEnd(int end,int length,int field) {
   int start=end-length+1;
   if(start<0 || length<2) return 0;
   double middle=(length-1)*0.5,sum=0,covariance=0;
   for(int j=0;j<length;j++) {
      MqlRates b=g_rates[start+j];
      double value=field==0 ? b.open : field==1 ? b.high : field==2 ? b.low : b.close;
      sum+=value; covariance+=(j-middle)*value;
   }
   double variance=length*(length*length-1.0)/12.0;
   return sum/length+middle*covariance/variance;
}
int Direction(double delta) { return delta>0 ? 1 : delta<0 ? -1 : 0; }

// Each trail has its own Wilder ATR and crossover. A zero factor disables that leg.
int DualTrailCross(int length,double factor,double &lastStop) {
   lastStop=0;
   if(factor<=0 || g_n<=length) return 0;
   double atr=0,stop=0,previous=0; int eventSide=0;
   for(int i=0;i<g_n;i++) {
      double c=g_rates[i].close;
      double tr=SXTrueRange(g_rates[i].high,g_rates[i].low,i>0 ? g_rates[i-1].close : c);
      if(i<length) atr+=tr/length;
      else atr=SXWilder(atr,tr,length);
      if(i==length-1) stop=c-factor*atr;
      else if(i>=length) {
         double old=stop;
         stop=SXUTStep(c,previous,old,factor*atr);
         if(i==g_n-1) eventSide=SXCross(c,previous,stop,old);
      }
      previous=c;
   }
   lastStop=stop;
   return eventSide;
}
int MatrixPass(int direction) {
   bool slopeReady=(g_n>=12);
   if(direction==0 || g_n<2 || g_atr<=0) return 0;
   int n=g_n-1;
   if(InpMatrixDMI && (g_adx<InpMinADX || direction*(g_gem.plusDI-g_gem.minusDI)<=0)) return 0;
   if(InpMatrixVwapSlope && (!slopeReady || direction*g_gem.vwapSlope<InpMinVwapSlopeATR)) return 0;
   if(InpMatrixCandle && direction*(g_rates[n].close-g_rates[n].open)<=0) return 0;
   if(MathAbs(g_rates[n].close-g_rates[n].open)<InpMinCandleBodyATR*g_atr) return 0;
   return direction;
}
void BuildGemSignals() {
   int n=g_n-1;
   if(n<2) return;
   g_gem.ema200=EMAValue(g_rates,g_n,200);
   g_gem.fast=g_fastSeries[n];
   g_gem.barLow=g_rates[n].low; g_gem.barHigh=g_rates[n].high;
   g_gem.swingLow=g_gem.barLow; g_gem.swingHigh=g_gem.barHigh;
   for(int i=(int)MathMax(0,g_n-(int)InpStopSwingBars);i<g_n;i++) {
      if(i>=g_n-InpStopSwingBars) {
         g_gem.swingLow=MathMin(g_gem.swingLow,g_rates[i].low);
         g_gem.swingHigh=MathMax(g_gem.swingHigh,g_rates[i].high);
      }
   }
   int anchorOffset=60*(InpVWAPAnchorHour*60+InpVWAPAnchorMinute);
   g_gem.sameSession=(g_rates[n].time-anchorOffset)/86400==(g_rates[n-1].time-anchorOffset)/86400;
   g_gem.vwapSlope=g_atr>0 && g_gem.sameSession ? (g_vwapSeries[n]-g_vwapSeries[n-1])/g_atr : 0;
   g_gem.lrOpen=RegressionEnd(n,InpRegressionLength,0);
   g_gem.lrClose=RegressionEnd(n,InpRegressionLength,3);
   double prevLR=RegressionEnd(n-1,InpRegressionLength,3);
   g_gem.lrSlope=g_atr>0 ? (g_gem.lrClose-prevLR)/g_atr : 0;
   int up=DualTrailCross(InpBuyATRLength,InpBuySensitivity,g_gem.buyTrail);
   int down=DualTrailCross(InpSellATRLength,InpSellSensitivity,g_gem.sellTrail);
   int reg=Direction(g_gem.lrClose-g_gem.lrOpen);
   g_engineSignals[DUAL_UT_LINREG]=up>0 && reg>0 ? 1 : down<0 && reg<0 ? -1 : 0;
   g_engineSignals[UT_EMA200]=g_gem.ema200>0 && g_raw*(g_closeCurrent-g_gem.ema200)>0 ? g_raw : 0;
   g_engineSignals[UT_FILTER_MATRIX]=MatrixPass(g_raw);
   int reclaim=SXCross(g_closeCurrent,g_rates[n-1].close,g_gem.fast,g_fastSeries[n-1]);
   g_engineSignals[REGRESSION_PULLBACK]=reclaim!=0 && reclaim*g_gem.lrSlope>0 && reclaim==reg ? reclaim : 0;
   int vCross=SXCross(g_closeCurrent,g_rates[n-1].close,g_vwap,g_vwap);
   g_engineSignals[VWAP_MFI_RECLAIM]=vCross*(g_mfi-50)>0 && vCross*g_gem.vwapSlope>=0 ? vCross : 0;
   if(g_quantumER>=InpRouterEfficiency && g_adx>=InpMinADX) { g_gem.route=REGRESSION_PULLBACK; }
   else if(g_atrRatio>=InpRouterExpansion) { g_gem.route=LEVEL_BREAKOUT; }
   else { g_gem.route=VWAP_MFI_RECLAIM; }
   g_engineSignals[GEM_REGIME_ROUTER]=g_engineSignals[g_gem.route];
}
double InitialStop(int direction,double entry,double minimum) {
   if(g_consoleStrategy==UT_VALUE_TURN && InpValueTurnSwing && InpFixedStopPoints<=0) {
      double anchor=direction>0 ? g_gem.turnLow : g_gem.turnHigh;
      if(anchor>0) return entry-direction*MathMax(direction*(entry-anchor),MathMax(minimum,InpMinSLPoints*g_consolePoint));
   }
   if(InpFixedStopPoints>0) return entry-direction*MathMax(InpFixedStopPoints*g_consolePoint,MathMax(minimum,InpMinSLPoints*g_consolePoint));
   double distance=InpInitialSL_ATR*g_atr*XEVolSLMult();
   if(InpInitialStopMode==STOP_CANDLE || InpInitialStopMode==STOP_SWING) {
      double anchor=direction>0 ? g_gem.barLow : g_gem.barHigh;
      if(InpInitialStopMode==STOP_SWING) anchor=direction>0 ? g_gem.swingLow : g_gem.swingHigh;
      if(anchor<=0) return 0;
      distance=MathMax(direction*(entry-anchor)+InpStopBufferATR*g_atr,minimum);
   } else if(InpInitialStopMode==STOP_PERCENT) distance=entry*InpStopPercent/100.0;
   return entry-direction*MathMax(distance,MathMax(InpMinSLPoints*g_consolePoint,minimum));
}


// Votes are signed directions. A conflict inside an event family produces a neutral event.
int FamilyEvent(int first,int second,int third) {
   int high=(int)MathMax(first,MathMax(second,third));
   int low=(int)MathMin(first,MathMin(second,third));
   if(high>0 && low<0) return 0;
   return high>0 ? 1 : low<0 ? -1 : 0;
}
int ConfirmEvent(int eventSide,int bias,int pressure) {
   if(eventSide==0 || eventSide*bias<0 || eventSide*pressure<0) return 0;
   return eventSide*bias>0 || eventSide*pressure>0 ? eventSide : 0;
}

// Compare the breakout bar and the reclaim bar against a channel that predates both.
int FailedBreakout(int last) {
   int first=last-1-InpBreakoutLookback;
   if(first<0) return 0;
   double ceiling=g_rates[first].high,floorPrice=g_rates[first].low;
   for(int i=first+1;i<=last-2;i++) {
      ceiling=MathMax(ceiling,g_rates[i].high);
      floorPrice=MathMin(floorPrice,g_rates[i].low);
   }
   MqlRates prior=g_rates[last-1],bar=g_rates[last];
   if(bar.close<=floorPrice || bar.close>=ceiling) return 0;
   if(prior.close>ceiling && bar.close<bar.open) return -1;
   if(prior.close<floorPrice && bar.close>bar.open) return 1;
   return 0;
}

int RegimeConfluence() {
   int eventSide=0,bias=0,pressure=0;
   if(g_atrRatio>=InpRouterExpansion) {
      g_gem.contextMode=2;
      eventSide=FamilyEvent(g_engineSignals[LEVEL_BREAKOUT],g_engineSignals[DONCHIAN_RETEST],g_engineSignals[RUBY_COMPRESSION]);
      bias=Direction(g_gem.plusDI-g_gem.minusDI);
      pressure=Direction(g_orderFlowDelta);
   } else if(g_quantumER>=InpRouterEfficiency && g_adx>=InpMinADX) {
      g_gem.contextMode=1;
      eventSide=FamilyEvent(g_engineSignals[DUAL_UT_LINREG],g_engineSignals[REGRESSION_PULLBACK],g_engineSignals[EMA_CROSS]);
      bias=Direction(g_cachedFast-g_cachedSlow);
      pressure=Direction(g_macd);
   } else {
      g_gem.contextMode=0;
      eventSide=FamilyEvent(g_engineSignals[FAILED_BREAKOUT_RECLAIM],g_engineSignals[KELTNER_REENTRY],g_engineSignals[VWAP_MFI_RECLAIM]);
      bias=Direction(g_rates[g_n-1].close-g_rates[g_n-1].open);
      pressure=Direction(g_rsiSeries[g_n-1]-g_rsiSeries[g_n-2]);
   }
   g_gem.contextVotes=eventSide+bias+pressure;
   return ConfirmEvent(eventSide,bias,pressure);
}

void UpdateShock(int lastClosed) {
   g_gem.shockReady=false;
   g_gem.largestShock=0;
   int first=lastClosed-InpShockPauseBars+1;
   int look=InpShockLookback;
   if(first<=look) return;
   double median=0;
   for(int bar=first;bar<=lastClosed;bar++) {
      if(!InpSharedShockBaseline || bar==first) {
         for(int j=0;j<look;j++) {
            int at=bar-look+j;
         }
         if(median<=0) return;
      }
      double ratio=SXTrueRange(g_rates[bar].high,g_rates[bar].low,g_rates[bar-1].close)/median;
      g_gem.largestShock=MathMax(g_gem.largestShock,ratio);
   }
   g_gem.shockReady=true;
}

bool AutoEntryQuality(double spread,double entry,double sl,double tp,string &reason) {
   if(BroadRestrictions()) return true;
   if(InpUseShockPause && g_gem.largestShock>=InpShockMultiple) {
      reason="Shock pause: recent true range "+DoubleToString(g_gem.largestShock,2)+"x median"; return false;
   }
   if(!InpUseCostGate) return true;
   double distance=tp>0 ? MathAbs(tp-entry) : MathAbs(entry-sl);
   double cost=spread+InpExtraCostPoints*g_consolePoint;
   if(distance<=0 || spread<0 || !MathIsValidNumber(cost)) { reason="Cost estimate unavailable"; return false; }
   double percentage=100*cost/distance;
   if(percentage>InpMaxCostPctOfTarget) {
      reason="Entry cost "+DoubleToString(percentage,1)+"% exceeds "+DoubleToString(InpMaxCostPctOfTarget,1)+"%";
      return false;
   }
   return true;
}

bool UsesFormingBar() {
   return InpUseFormingBar && (int)g_consoleStrategy<DUAL_UT_LINREG;
}
int RequiredHistoryBars() {
   int minimum=(int)MathMax(600,3*MathMax(InpBuyATRLength,InpSellATRLength));
   minimum=(int)MathMax(minimum,MathMax(InpSlowMA*3,MathMax(InpATRPeriod*3,ConsoleADXPeriod*3)));
   minimum=(int)MathMax(minimum,MathMax(ConsoleRSIPeriod+30,InpZeroLagPeriod*3));
   minimum=(int)MathMax(minimum,MathMax(InpSuperPeriod*3,InpStcSlow+2*InpStcCycle+10));
   minimum=(int)MathMax(minimum,MathMax(InpATRMeanPeriod+InpATRPeriod+10,InpSwingLookback+InpPivotRight+10));
   return (int)MathMax(minimum,MathMax(InpBandPeriod+5,MathMax(InpSMAPeriod+10,MathMax(InpVolumePeriod+5,InpBreakoutLookback+5))));
}
bool BuildSnapshot() {
   bool wasReady=g_consoleReady;
   g_snapshotSymbol="";
   g_consoleReady=false;
   ArraySetAsSeries(g_rates,false);
   int startShift=UsesFormingBar() ? 0 : 1;
   int required=RequiredHistoryBars();
   int n=CopyRates(g_symbol,g_tf,startShift,InpHistoryBars,g_rates);
   if(n<required) { g_message="History: "+IntegerToString((int)MathMax(0,n))+" / "+IntegerToString(required)+" bars required"; return false; }
   datetime expected=iTime(g_symbol,g_tf,startShift);
   if(expected<=0 || g_rates[n-1].time!=expected) { g_message="History: latest broker bar is not synchronized"; return false; }
   g_n=n; ArrayResize(g_atrSeries,n); ArrayResize(g_utSeries,n);
   ArrayResize(g_fastSeries,n); ArrayResize(g_slowSeries,n);
   ArrayResize(g_zeroSeries,n); g_zeroTrend=0;
   ArrayResize(g_zones,(int)MathMin(n,500)); g_zoneCount=0;
   double atr=0,trSum=0,ut=0,previousSource=0;
   double fast=0,slow=0,macd12=0,macd26=0,macdSignal=0,zero=0;
   double gain=0,loss=0,atrDX=0,plus=0,minus=0,adx=0,dxSum=0;
   g_gem.plusDI=0; g_gem.minusDI=0;
   int dxCount=0; g_raw=0;
   for(int i=0;i<n;i++) {
      if(i==n-1) g_gem.droidAdxPrev=adx;
      double c=g_rates[i].close,prev=i>0 ? g_rates[i-1].close : c;
      double tr=SXTrueRange(g_rates[i].high,g_rates[i].low,prev);
      trSum+=tr;
      if(i==InpATRPeriod-1) atr=trSum/InpATRPeriod;
      else if(i>=InpATRPeriod) atr=SXWilder(atr,tr,InpATRPeriod);
      g_atrSeries[i]=atr;
      double src=Source(g_rates[i]);
      if(i<InpATRPeriod-1) { g_utSeries[i]=0; previousSource=src; }
      else if(i==InpATRPeriod-1) { ut=src-InpATRMultiplier*atr; g_utSeries[i]=ut; previousSource=src; }
      else {
         double old=ut; ut=SXUTStep(src,previousSource,ut,InpATRMultiplier*atr);
         if(i==n-1) g_raw=SXCross(src,previousSource,ut,old);
         g_utSeries[i]=ut; previousSource=src;
      }
      // EMA seeds use the first close. A long warmup reduces seed dependence.
      if(i==0) { fast=c; slow=c; macd12=c; macd26=c; }
      else { fast+=2.0/(InpFastMA+1)*(c-fast); slow+=2.0/(InpSlowMA+1)*(c-slow);
             macd12+=2.0/13*(c-macd12); macd26+=2.0/27*(c-macd26); }
      double macd=macd12-macd26; macdSignal+=2.0/10*(macd-macdSignal);
      g_fastSeries[i]=fast; g_slowSeries[i]=slow;
      int lag=(InpZeroLagPeriod-1)/2;
      double adjusted=c+(i>=lag ? c-g_rates[i-lag].close : 0);
      if(i==0) zero=adjusted; else zero+=2.0/(InpZeroLagPeriod+1)*(adjusted-zero);
      g_zeroSeries[i]=zero;
      if(atr>0 && c>zero+InpZeroLagBandATR*atr) g_zeroTrend=1;
      else if(atr>0 && c<zero-InpZeroLagBandATR*atr) g_zeroTrend=-1;
      if(i==n-2) g_gem.priorHist=macd-macdSignal;
      if(i==n-1) g_macd=macd-macdSignal;
      if(i>0) {
         double change=c-prev,up=MathMax(0,change),down=MathMax(0,-change);
         if(i<=ConsoleRSIPeriod) { gain+=up/ConsoleRSIPeriod; loss+=down/ConsoleRSIPeriod; }
         else { gain=SXWilder(gain,up,ConsoleRSIPeriod); loss=SXWilder(loss,down,ConsoleRSIPeriod); }
         double dmUp=g_rates[i].high-g_rates[i-1].high,dmDown=g_rates[i-1].low-g_rates[i].low;
         double pdm=dmUp>dmDown && dmUp>0 ? dmUp : 0,mdm=dmDown>dmUp && dmDown>0 ? dmDown : 0;
         if(i<=ConsoleADXPeriod) { atrDX+=tr/ConsoleADXPeriod; plus+=pdm/ConsoleADXPeriod; minus+=mdm/ConsoleADXPeriod; }
         else { atrDX=SXWilder(atrDX,tr,ConsoleADXPeriod); plus=SXWilder(plus,pdm,ConsoleADXPeriod); minus=SXWilder(minus,mdm,ConsoleADXPeriod); }
         if(i>=ConsoleADXPeriod) {
            double pdi=atrDX>0 ? 100*plus/atrDX : 0,mdi=atrDX>0 ? 100*minus/atrDX : 0;
            if(i==n-1) { g_gem.plusDI=pdi; g_gem.minusDI=mdi; }
            double dx=(pdi+mdi)>0 ? 100*MathAbs(pdi-mdi)/(pdi+mdi) : 0;
            if(dxCount<ConsoleADXPeriod) { dxSum+=dx; dxCount++; adx=dxSum/dxCount; }
            else adx=SXWilder(adx,dx,ConsoleADXPeriod);
         }
      }
      for(int j=0;j<g_zoneCount;j++) if(!g_zones[j].filled && i>g_zones[j].bar) {
         if((g_zones[j].direction>0 && g_rates[i].low<=g_zones[j].lower) ||
            (g_zones[j].direction<0 && g_rates[i].high>=g_zones[j].upper)) g_zones[j].filled=true;
      }
      if(i>=2 && i>=n-InpMaxFVGAgeBars-2) {
         int gap=SXGap(g_rates[i-2].high,g_rates[i-2].low,g_rates[i].high,g_rates[i].low,c,InpMinFVGGapPercent);
         if(gap!=0) {
            if(g_zoneCount>=ArraySize(g_zones)) { for(int z=1;z<g_zoneCount;z++) g_zones[z-1]=g_zones[z]; g_zoneCount--; }
            SXZone zone; zone.formed=g_rates[i].time; zone.direction=gap; zone.filled=false; zone.bar=i;
            zone.lower=gap>0 ? g_rates[i-2].high : g_rates[i].high;
            zone.upper=gap>0 ? g_rates[i].low : g_rates[i-2].low;
            g_zones[g_zoneCount++]=zone;
         }
      }
   }
   g_atr=atr; g_adx=adx;
   g_rsi=(gain+loss)<1e-12 ? 50 : loss<1e-12 ? 100 : 100-100/(1+gain/loss);
   int smaP=(int)MathMin(n,MathMax(1,InpSMAPeriod)); g_sma=0; for(int i=n-smaP;i<n;i++) g_sma+=g_rates[i].close/smaP;
   int volP=(int)MathMin(n-1,MathMax(1,InpVolumePeriod)); double volume=0; for(int i=n-1-volP;i<n-1;i++) volume+=(double)g_rates[i].tick_volume/volP;
   g_volumeRatio=volume>0 ? (double)g_rates[n-1].tick_volume/volume : 1.0;
   int brkP=(int)MathMin(n-1,MathMax(1,InpBreakoutLookback)); g_breakHigh=g_rates[n-2].high; g_breakLow=g_rates[n-2].low;
   for(int i=n-1-brkP;i<n-1;i++) {
      g_breakHigh=MathMax(g_breakHigh,g_rates[i].high); g_breakLow=MathMin(g_breakLow,g_rates[i].low);
   }
   UpdateMTF(true); UpdateLevels();
   g_scoreBuy=Score(1); g_scoreSell=Score(-1);
   int breakout=g_rates[n-1].close>g_breakHigh ? 1 : g_rates[n-1].close<g_breakLow ? -1 : 0;
   int pullback=0;
   if(fast>slow && g_rates[n-2].close<=g_fastSeries[n-2] && g_rates[n-1].close>fast) pullback=1;
   if(fast<slow && g_rates[n-2].close>=g_fastSeries[n-2] && g_rates[n-1].close<fast) pullback=-1;
   g_candidate=g_raw;
   if(g_consoleStrategy==LEVEL_BREAKOUT) g_candidate=breakout;
   if(g_consoleStrategy==TREND_PULLBACK) g_candidate=pullback;
   if(g_consoleStrategy==CONSENSUS) {
      int votes=g_raw+breakout+pullback;
      g_candidate=votes>0 ? 1 : votes<0 ? -1 : 0;
   }
   g_cachedFast=fast; g_cachedSlow=slow; g_cachedAtrPrior=g_atrSeries[n-2];
   g_prevLo=g_rates[n-1].low; g_prevHi=g_rates[n-1].high; g_lo8=g_prevLo; g_hi8=g_prevHi;
   for(int b=(int)MathMax(0,n-8);b<n;b++) { g_lo8=MathMin(g_lo8,g_rates[b].low); g_hi8=MathMax(g_hi8,g_rates[b].high); }
   BuildExtendedSignals();
   g_consoleReady=g_atr>0 && MathIsValidNumber(g_atr);
   if(g_consoleReady) {
      if(SignalFilters(1,g_gem.buyFilter)) g_gem.buyFilter="Clear";
      if(SignalFilters(-1,g_gem.sellFilter)) g_gem.sellFilter="Clear";
   }
   if(g_consoleReady && !wasReady) g_message="History ready; awaiting signal";
   else if(!g_consoleReady) g_message="History: ATR unavailable or zero";
   return g_consoleReady;
}

int Score(int direction) {
   if(g_n<2) return 0;
   int score=0;
   if(direction*(g_fastSeries[g_n-1]-g_slowSeries[g_n-1])>0) score+=20;
   if(direction*(g_rsi-50)>0) score+=15;
   if(direction*g_macd>0) score+=15;
   if(g_adx>=InpMinADX) score+=10;
   if(g_tf1==direction) score+=15;
   if(g_tf2==direction) score+=10;
   if(g_volumeRatio>=InpMinVolumeRatio) score+=5;
   if(g_zeroTrend==direction) score+=10;
   return score;
}

bool g_foreignNetting=false;
bool IsNetting() {
#ifdef __MQL5__
   return AccountInfoInteger(ACCOUNT_MARGIN_MODE)!=ACCOUNT_MARGIN_MODE_RETAIL_HEDGING;
#else
   return false;
#endif
}
#ifdef __MQL5__
bool NettingExclusiveFor(long magic) {
   ulong identifier=(ulong)PositionGetInteger(POSITION_IDENTIFIER);
   if(!HistorySelectByPosition(identifier) || HistoryDealsTotal()<1) return false;
   bool observed=false;
   for(int j=0;j<HistoryDealsTotal();j++) {
      ulong deal=HistoryDealGetTicket(j);
      long kind=HistoryDealGetInteger(deal,DEAL_TYPE);
      if(kind==DEAL_TYPE_BUY || kind==DEAL_TYPE_SELL) {
         if(HistoryDealGetInteger(deal,DEAL_MAGIC)!=magic) return false;
         observed=true;
      }
   }
   return observed;
}
bool NettingExclusive() { return NettingExclusiveFor(ConsoleMagic); }
#endif
void ConsoleLoadPositions() {
   ArrayResize(g_positions,0); g_foreignNetting=false;
#ifdef __MQL5__
   bool netting=IsNetting();
   for(int i=PositionsTotal()-1;i>=0;i--) {
      ulong ticket=PositionGetTicket(i); if(ticket==0 || PositionGetString(POSITION_SYMBOL)!=g_symbol) continue;
      bool mine=PositionGetInteger(POSITION_MAGIC)==ConsoleMagic;
      if(netting && mine) mine=NettingExclusive();
      if(!mine) { if(netting) g_foreignNetting=true; continue; }
      if(!PositionSelectByTicket(ticket)) continue;
      SXPosition p; p.ticket=ticket;
      p.direction=PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ? 1 : -1;
      p.opened=(datetime)PositionGetInteger(POSITION_TIME);
      p.lots=PositionGetDouble(POSITION_VOLUME); p.open=PositionGetDouble(POSITION_PRICE_OPEN);
      p.sl=PositionGetDouble(POSITION_SL); p.tp=PositionGetDouble(POSITION_TP);
      p.profit=PositionGetDouble(POSITION_PROFIT)+PositionGetDouble(POSITION_SWAP);
      int count=ArraySize(g_positions); ArrayResize(g_positions,count+1); g_positions[count]=p;
   }
#else
   for(int i=OrdersTotal()-1;i>=0;i--) {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderSymbol()!=g_symbol || OrderMagicNumber()!=ConsoleMagic || OrderType()>OP_SELL) continue;
      SXPosition p; p.ticket=(ulong)OrderTicket(); p.direction=OrderType()==OP_BUY ? 1 : -1;
      p.opened=OrderOpenTime();
      p.lots=OrderLots(); p.open=OrderOpenPrice(); p.sl=OrderStopLoss(); p.tp=OrderTakeProfit();
      p.profit=OrderProfit()+OrderSwap()+OrderCommission();
      int count=ArraySize(g_positions); ArrayResize(g_positions,count+1); g_positions[count]=p;
   }
#endif
}
int WorkingOrders() {
   int count=0;
#ifdef __MQL5__
   for(int i=OrdersTotal()-1;i>=0;i--) {
      if(OrderGetTicket(i)==0) continue;
      if(OrderGetString(ORDER_SYMBOL)==g_symbol && OrderGetInteger(ORDER_MAGIC)==ConsoleMagic) count++;
   }
#else
   for(int i=OrdersTotal()-1;i>=0;i--) {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderSymbol()==g_symbol && OrderMagicNumber()==ConsoleMagic && OrderType()>OP_SELL) count++;
   }
#endif
   return count;
}
double Floating() {
   double value=0; for(int i=0;i<ArraySize(g_positions);i++) value+=g_positions[i].profit; return value;
}
string TradePermissionIssue() {
   if(!g_tester && !(bool)TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)) return "Terminal AutoTrading / Algo Trading is off";
   if(!(bool)MQLInfoInteger(MQL_TRADE_ALLOWED)) return "EA trading permission is off";
   if(!(bool)AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)) return "Account trading is not allowed";
   if(!g_tester && !(bool)AccountInfoInteger(ACCOUNT_TRADE_EXPERT)) return "Broker or account does not allow EA orders";
   return "";
}
bool CanTrade() { return TradePermissionIssue()==""; }
void SetUncertain(string reason) {
   g_uncertain=true; WriteGV("uncertain",1); Notify(reason+"; inspect broker orders, then RECONCILE");
}
#ifdef __MQL5__
ENUM_ORDER_TYPE_FILLING Filling() {
   long flags=SymbolInfoInteger(g_symbol,SYMBOL_FILLING_MODE);
   if((flags&SYMBOL_FILLING_FOK)==SYMBOL_FILLING_FOK) return ORDER_FILLING_FOK;
   if((flags&SYMBOL_FILLING_IOC)==SYMBOL_FILLING_IOC) return ORDER_FILLING_IOC;
   return ORDER_FILLING_RETURN;
}
bool SendRequest(MqlTradeRequest &request,string action) {
   bool unchanged=false;
   return SendRequestStatus(request,action,unchanged);
}
bool SendRequestStatus(MqlTradeRequest &request,string action,bool &unchanged) {
   unchanged=false;
   MqlTradeCheckResult check={}; MqlTradeResult result={};
   ENUM_ORDER_TYPE_FILLING fillings[3];
   fillings[0]=request.type_filling;
   fillings[1]=ORDER_FILLING_IOC;
   fillings[2]=ORDER_FILLING_RETURN;
   if(fillings[0]==ORDER_FILLING_IOC) { fillings[1]=ORDER_FILLING_FOK; fillings[2]=ORDER_FILLING_RETURN; }
   else if(fillings[0]==ORDER_FILLING_RETURN) { fillings[1]=ORDER_FILLING_IOC; fillings[2]=ORDER_FILLING_FOK; }
   bool checked=false; int chosen=0;
   for(int f=0;f<3;f++) {
      if(request.action==TRADE_ACTION_DEAL) request.type_filling=fillings[f];
      ZeroMemory(check); ResetLastError();
      if(OrderCheck(request,check)) { checked=true; chosen=f; break; }
      if(request.action!=TRADE_ACTION_DEAL || check.retcode!=10030) break;
   }
   if(!checked) {
      if(InpAutoWidenStop && check.retcode==10016) g_stopPaddingPts=(int)MathMin(1000,g_stopPaddingPts==0 ? 20 : g_stopPaddingPts*2);
      Log(action+" check failed "+IntegerToString((int)check.retcode)+" "+check.comment); return false;
   }
   bool sent=false; int error=0;
   for(int attempt=0;attempt<3;attempt++) {
      ZeroMemory(result); ResetLastError();
      sent=OrderSend(request,result); error=GetLastError();
      if(sent && (result.retcode==TRADE_RETCODE_DONE || result.retcode==TRADE_RETCODE_DONE_PARTIAL)) break;
      if(request.action==TRADE_ACTION_DEAL && result.retcode==10030 && attempt<2 && chosen<2) {
         chosen++; request.type_filling=fillings[chosen]; continue;
      }
      if(request.action==TRADE_ACTION_DEAL && request.position>0 && (result.retcode==10004 || result.retcode==10021) && attempt<2) {
         MqlTick q; if(Tick(q)) request.price=(request.type==ORDER_TYPE_BUY) ? q.ask : q.bid;
         continue;
      }
      break;
   }
   if(!sent && (result.retcode==0 || result.retcode==10031)) { SetUncertain(action+" transport status unknown "+IntegerToString(error)); return false; }
   if(result.retcode==TRADE_RETCODE_DONE || result.retcode==TRADE_RETCODE_DONE_PARTIAL) {
      if(request.action==TRADE_ACTION_DEAL && request.position==0 && !IsNetting() && result.price>0)
         FlowSlipRecord(request.price,result.price,request.type==ORDER_TYPE_BUY ? 1 : -1);
      Log(action+" executed: "+result.comment); return true;
   }
   if(result.retcode==TRADE_RETCODE_PLACED || result.retcode==TRADE_RETCODE_TIMEOUT) {
      SetUncertain(action+" awaiting execution confirmation "+IntegerToString((int)result.retcode)); return false;
   }
   if(result.retcode==TRADE_RETCODE_NO_CHANGES && request.action==TRADE_ACTION_SLTP) { unchanged=true; return true; }
   if(InpAutoWidenStop && (result.retcode==10016 || error==130)) g_stopPaddingPts=(int)MathMin(1000,g_stopPaddingPts==0 ? 20 : g_stopPaddingPts*2);
   Log(action+" rejected "+IntegerToString((int)result.retcode)+" / "+IntegerToString(error)+" "+result.comment);
   return false;
}
#endif
double ConsoleNormalizeLots(double raw) {
   return NormalizeDouble(SXFloorVolume(raw,SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN),
      NoLotCap() ? SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MAX) : MathMin(InpMaxLots,SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MAX)),SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_STEP)),8);
}
double RiskLots(int direction,double price,double sl,bool manual) { return BPRiskLots(direction,price,sl,manual); }
double RiskLotsCore(int direction,double price,double sl,bool manual) {
   if(manual || !InpUseRiskLot) return ConsoleNormalizeLots(manual ? g_manualLots : InpFixedLots);
   double sizingStop=sl-(InpSizeIncludesSlippage ? direction*InpSlippagePoints*g_consolePoint : 0);
   double loss=0;
#ifdef __MQL5__
   double reference=SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN),estimate=0;
   if(reference<=0 || !OrderCalcProfit(direction>0 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL,g_symbol,reference,price,sizingStop,estimate)) return 0;
   loss=MathAbs(estimate)/reference;
#else
   double tick=TickSize(),value=SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_VALUE);
   if(tick<=0 || value<=0) return 0;
   loss=MathAbs(price-sizingStop)/tick*value;
#endif
   loss+=InpCommissionPerLot;
   if(loss<=0 || !MathIsValidNumber(loss)) return 0;
   double effRiskPct=SXDynamicRiskMultiplier(ConsoleRiskPercent,g_ensembleConfidence,g_drawdown,InpDynamicRiskScaling,InpDynamicRiskMinMult,InpDynamicRiskMaxMult);
   if(InpDayLossRiskStepPct>0 && g_dayLoss>=InpDayLossRiskStepPct) effRiskPct*=InpDayLossRiskStepMult;
   effRiskPct*=SXVolatilityRiskAttenuation(g_atrRatio,InpUseVolatilityRiskAttenuation,InpRiskAttenuationStartRatio,InpRiskAttenuationFloor);
   double raw=RiskBaseAmount()*effRiskPct/100.0/loss;
   double normed=ConsoleNormalizeLots(raw);
   if(normed<=0 && InpMandatoryMinLotFallback && !InpUseVolatilityRiskAttenuation && (int)g_consoleStrategy<DUAL_UT_LINREG && (g_consoleStrategy==INSTANT_MANDATORY_BLITZ || (int)g_consoleStrategy>=30)) {
      double minLot=SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN);
      if(TradeRisk(g_symbol,direction,minLot,price,sl)<=ConsoleEquity()*InpMaxPortfolioRiskPct/100.0)
         return ConsoleNormalizeLots(minLot);
   }
   return normed;
}
bool SessionOpen() {
   MqlDateTime now; TimeToStruct(TimeCurrent(),now);
   return !ConsoleUseSession || SXHours(now.hour,InpSessionStartHour,InpSessionEndHour);
}
bool LevelRoom(int direction) {
   if(!InpUseLevelFilter) return true;
   if(g_pdh<=0 || g_pdl<=0 || g_pwh<=0 || g_pwl<=0) return false;
   // MQL4 array initializers require constants; level prices change at runtime.
   double levels[6];
   levels[0]=g_pdh;
   levels[1]=g_pdl;
   levels[2]=g_pwh;
   levels[3]=g_pwl;
   levels[4]=g_r1;
   levels[5]=g_s1;
   double c=g_closeCurrent,room=1e100;
   for(int i=0;i<6;i++) if(levels[i]>0 && direction*(levels[i]-c)>0) room=MathMin(room,direction*(levels[i]-c));
   return room>=InpLevelRoomATR*g_atr;
}
bool FVGMatch(int direction) {
   if(!InpUseFVGFilter) return true;
   if(g_snapshotSymbol==g_symbol) return FVGExists(direction);
   if(g_active<0 || g_active>=ArraySize(g_assets)) return false;
   return direction>0 ? g_assets[g_active].fvgBuy : g_assets[g_active].fvgSell;
}
bool SignalFilters(int direction,string &why) {
   if(BroadRestrictions()) return true;
   if(FlowSlipPaused()) { why="Fill slippage pause"; return false; }
   if(g_consoleStrategy>=DROID_ADAPTIVE_CONFLUENCE && g_consoleStrategy<DR_UT && InpSmartStreakShield && InpDailyLossPercent>0 && g_dayLoss>=0.5*InpDailyLossPercent && g_candidate!=0 && Direction(g_velocity)!=direction) {
      why="Daily loss and opposing price velocity"; return false;
   }
   if(!NoTimeRestrictions() && FlowRolloverQuiet()) { why="Rollover quiet window"; return false; }
   if(!FlowTickAgrees(direction,why)) return false;
   if(InpUseTrendFitGate && direction*g_gem.fitScore<InpMinTrendFit) { why="Directional trend fit below threshold"; return false; }
   int votesAgainst=direction>0 ? g_gem.scalpDown : g_gem.scalpUp;
   int votesFor=direction>0 ? g_gem.scalpUp : g_gem.scalpDown;
   if(InpVoteVeto && votesAgainst>=InpVoteMinVotes && votesAgainst>votesFor) { why="Structure vote veto"; return false; }
   if(g_consoleStrategy==UT_CONFLUENCE || g_consoleStrategy==CONSENSUS) {
      int score=direction>0 ? g_scoreBuy : g_scoreSell;
      if(score<InpMinConfluenceScore) { why="Confluence score below threshold"; return false; }
   }
   if(InpUseAdaptiveConfluence) {
      int votes=SXAdaptiveVoteScore(direction,g_kalmanDir,g_quantumSuperDir,g_zeroTrend,g_macd,g_cachedFast,g_cachedSlow);
      if(votes<InpAdaptiveMinVotes || g_adx<InpAdaptiveMinADX) { why="Adaptive confluence confirmation"; return false; }
   }
   if(ConsoleUseEMAFilter && direction*(g_cachedFast-g_cachedSlow)<=0) { why="EMA trend disagreement"; return false; }
   if(InpUseSMAFilter && direction*(g_closeCurrent-g_sma)<=0) { why="SMA trend disagreement"; return false; }
   if(InpUseRSIFilter && ((direction>0 && g_rsi<InpRSIBuyMin) || (direction<0 && g_rsi>InpRSISellMax))) { why="RSI filter"; return false; }
   if(ConsoleUseADXFilter && g_adx<InpMinADX) { why="ADX trend too weak"; return false; }
   if(InpUseMACDFilter && direction*g_macd<=0) { why="MACD disagreement"; return false; }
   if(InpUseZeroLagFilter && g_zeroTrend!=direction) { why="Zero-lag ATR band disagreement"; return false; }
   if(InpUseMTFFilter && (g_tf1!=direction || g_tf2!=direction)) { why="MTF disagreement / history loading"; return false; }
   if(InpUseVolumeFilter && g_volumeRatio<InpMinVolumeRatio) { why="Tick volume too low"; return false; }
   if(!LevelRoom(direction)) { why="Insufficient room to a level / history loading"; return false; }
   if(InpUseSuperFilter && g_superDir!=direction) { why="SuperTrend disagreement"; return false; }
   if(InpUseSTCFilter && ((direction>0 && g_stc<50) || (direction<0 && g_stc>50))) { why="STC disagreement"; return false; }
   if(InpUseATRBand && (g_atrRatio<InpMinATRRatio || g_atrRatio>InpMaxATRRatio)) { why="ATR volatility-band filter"; return false; }
   if(InpUseD1MAFilter && g_d1MA>0 && direction*(g_closeCurrent-g_d1MA)<=0) { why="D1 MA length filter disagreement"; return false; }
   if(!FVGMatch(direction)) { why="No recent unfilled matching FVG"; return false; }
   if(InpSmartAntiChop && g_atrRatio<InpSmartMinAtrRatio) { why="ATR compression filter"; return false; }
   if(InpSmartMtfConfirm && ClosedTrailBias(InpSmartConfirmTF)!=direction) { why="Confirming ATR bias missing or opposite"; return false; }
   if(g_consoleStrategy>=DROID_ADAPTIVE_CONFLUENCE && g_consoleStrategy<=OVERNIGHT_MNQ_SYNAPSE && InpSmartRegimeRouter && g_adx<25 && g_atrRatio<InpSmartMinAtrRatio) {why="Confluence regime filter";return false;}
   return true;
}
bool EntryGate(int direction,string &why,bool bracketSibling=false) {
   if(!g_consoleReady) { why="Signal history not ready"; return false; }
   if(InpTesterOnlyEntries && !g_tester) { why="Tester-only preset: new entries blocked outside Strategy Tester"; return false; }
   if(g_exitRequested || g_consolePortfolioExit) { why="Owned exit still in progress"; return false; }
   if(!NoPositionCaps() && PortfolioExposureCount()>=InpMaxPortfolioPositions) { why="Portfolio exposure cap"; return false; }
   if(!bracketSibling && !NoCooldowns() && InpMinEntrySeconds>0 && TimeCurrent()-(datetime)ReadGV("submit",0)<InpMinEntrySeconds) { why="Entry time spacing"; return false; }
   why=TradePermissionIssue(); if(why!="") return false;
   if(g_emergency) { why="Emergency stop"; return false; }
   if(g_dailyLock || g_peakLock || g_weeklyLock) { why="Equity protection lock"; return false; }
   if(!BroadRestrictions() && !SXVolatilityRegimeAllowed(g_atrRatio,InpUseVolatilityCircuitBreaker,InpVolatilityMinATRRatio,InpVolatilityMaxATRRatio)) {
      why="ATR outside volatility circuit limits"; return false;
   }
   if(g_uncertain) { why="Outstanding order / reconcile required"; return false; }
#ifdef __MQL5__
   if(IsNetting()) {
      for(int k=OrdersTotal()-1;k>=0;k--) {
         if(OrderGetTicket(k)>0 && OrderGetString(ORDER_SYMBOL)==g_symbol && OrderGetInteger(ORDER_MAGIC)!=ConsoleMagic) {
            why="Foreign pending order on netting symbol"; return false;
         }
      }
   }
#endif
   if(g_foreignNetting) { why="Netting ownership is mixed or unverified"; return false; }
   if((direction>0 && !InpAllowBuy) || (direction<0 && !InpAllowSell)) { why="Direction disabled"; return false; }
   int limit=IsNetting() ? 1 : (NoPositionCaps() ? 100000 : ConsoleMaxPositions);
   if(ArraySize(g_positions)+WorkingOrders()>=limit) { why="Maximum positions reached"; return false; }
   if(!NoTimeRestrictions() && !SessionOpen()) { why="Outside server-time session"; return false; }
   if(GuardBlocksEntry(why)) return false;
   if(!NoTimeRestrictions() && InpUseDateWindow && (TimeCurrent()<InpStartDate || TimeCurrent()>=InpEndDate)) { why="Outside date window"; return false; }
   MqlTick quote; if(!Tick(quote)) { why="No valid quote"; return false; }
   if(!NoSpreadQuoteLimits() && InpMaxQuoteAgeSeconds>0 && TimeCurrent()-quote.time>InpMaxQuoteAgeSeconds) { why="Stale quote"; return false; }
   double spread=quote.ask-quote.bid;
   if(!NoSpreadQuoteLimits() && InpSpreadShockMultiple>0 && g_assets[g_active].spreadCount>=8 &&
      g_assets[g_active].spreadRatio>InpSpreadShockMultiple) { why="Spread spike versus recent quotes"; return false; }
   if(!NoSpreadQuoteLimits() && ConsoleMaxSpreadPoints>0 && spread/g_consolePoint>ConsoleMaxSpreadPoints) { why="Spread exceeds points cap"; return false; }
   if(!NoSpreadQuoteLimits() && ConsoleMaxSpreadATR>0 && spread>ConsoleMaxSpreadATR*g_atr) { why="Spread exceeds ATR cap"; return false; }
   if(!BPEntryGate(direction,why)) return false;
   int tradeMode=AllowedTradeMode(g_symbol);
   if(tradeMode==SYMBOL_TRADE_MODE_DISABLED || tradeMode==SYMBOL_TRADE_MODE_CLOSEONLY ||
      (direction>0 && tradeMode==SYMBOL_TRADE_MODE_SHORTONLY) || (direction<0 && tradeMode==SYMBOL_TRADE_MODE_LONGONLY)) {
      why="Broker symbol direction unavailable"; return false;
   }
   return true;
}

bool SupportsRequest(SXEntry mode,string &reason) {
#ifdef __MQL5__
   long flags=SymbolInfoInteger(g_symbol,SYMBOL_ORDER_MODE);
   long needed=mode==ENTRY_STOP ? SYMBOL_ORDER_STOP : mode==ENTRY_LIMIT ? SYMBOL_ORDER_LIMIT : SYMBOL_ORDER_MARKET;
   if((flags&needed)==0) { reason="Broker disables this order type"; return false; }
   if((flags&SYMBOL_ORDER_SL)==0) { reason="Symbol does not accept attached protective stops"; return false; }
   if((InpUseFixedTP || InpFixedTargetPoints>0) && (flags&SYMBOL_ORDER_TP)==0) {
      reason="Symbol does not accept the selected take profit"; return false;
   }
#endif
   return true;
}
bool EntryPrices(int direction,SXEntry style,double trigger,MqlTick &quote,double &price,double &sl,double &tp,string &why) {
   double distance=MinStopDistance(false);
   price=direction>0 ? quote.ask : quote.bid;
   if(style!=ENTRY_MARKET) {
      bool stop=style==ENTRY_STOP;
      double offset=(stop ? 1.0 : -1.0)*InpPendingOffsetATR*g_atr;
      price=trigger>0 ? trigger : price+direction*offset;
      if(direction>0) price=stop ? MathMax(price,quote.ask+distance) : MathMin(price,quote.ask-distance);
      else price=stop ? MathMin(price,quote.bid-distance) : MathMax(price,quote.bid+distance);
      price=NormalizeDouble(SXRoundPrice(price,TickSize(),stop ? -direction : direction),g_consoleDigits);
   }
   sl=InitialStop(direction,price,distance);
   if(sl<=0) { why="Initial stop reference unavailable"; return false; }
   if(style==ENTRY_MARKET) sl=direction>0 ? MathMin(sl,quote.bid-distance) : MathMax(sl,quote.ask+distance);
   sl=NormalizeDouble(SXRoundPrice(sl,TickSize(),direction),g_consoleDigits);
   if(price<=0 || sl<=0 || direction*(price-sl)<=0) { why="Invalid entry or protective stop"; return false; }
   tp=TargetFor(direction,price,sl,distance);
   if((InpUseFixedTP || InpFixedTargetPoints>0) && tp<=0) { why="Target outside symbol price range"; return false; }
   return true;
}
SXEntry AutomaticEntryStyle() {
   if(g_consoleStrategy==SUPERTREND_STOP) return ENTRY_STOP;
#ifdef __MQL5__
   if(InpEntryStyle==ENTRY_MARKET) {
      long types=SymbolInfoInteger(g_symbol,SYMBOL_ORDER_MODE);
      if((types&SYMBOL_ORDER_MARKET)==0 && (types&SYMBOL_ORDER_LIMIT)!=0) return ENTRY_LIMIT;
   }
#endif
   return InpEntryStyle;
}
bool OpenPosition(int direction,bool manual=false,double overrideLots=0) {
   ConsoleLoadPositions(); string why="";
   if(!EntryGate(direction,why) || !SupportsRequest(ENTRY_MARKET,why)) { Log("Entry blocked: "+why); return false; }
   MqlTick quote; if(!Tick(quote)) { Log("Entry blocked: no valid broker quote"); return false; }
   double price=0,sl=0,tp=0;
   if(!EntryPrices(direction,ENTRY_MARKET,0,quote,price,sl,tp,why)) { Log(why); return false; }
   if(!manual && !AutoEntryQuality(quote.ask-quote.bid,price,sl,tp,why)) { Log(why); return false; }
   double lots=overrideLots>0 ? ConsoleNormalizeLots(overrideLots) : RiskLots(direction,price,sl,manual);
   if(lots<=0) { Log("Entry blocked: size below broker minimum / valuation unavailable"); return false; }
   if(!PortfolioRiskAllows(direction,lots,price,sl)) { Log("Entry blocked: aggregate stop-risk budget"); return false; }
   WriteGV("submit",(double)TimeCurrent());
#ifdef __MQL5__
   double margin=0;
   if(!NoMarginPrecheck() && (!OrderCalcMargin(direction>0 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL,g_symbol,lots,price,margin) ||
      margin>AccountInfoDouble(ACCOUNT_MARGIN_FREE)*0.95)) { Log("Entry blocked: insufficient margin / margin quote unavailable"); return false; }
   MqlTradeRequest request={}; request.action=TRADE_ACTION_DEAL; request.symbol=g_symbol;
   request.magic=(ulong)ConsoleMagic; request.type=direction>0 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   request.volume=lots; request.price=price; request.sl=sl; request.tp=tp;
   request.deviation=(ulong)InpSlippagePoints; request.type_filling=Filling();
   request.comment=SG_ORDER_COMMENT;
   bool success=SendRequest(request,Side(direction)+" "+DoubleToString(lots,4));
#else
   ResetLastError();
   double free=AccountFreeMarginCheck(g_symbol,direction>0 ? OP_BUY : OP_SELL,lots);
   if(!NoMarginPrecheck() && (free<=AccountInfoDouble(ACCOUNT_MARGIN_FREE)*0.05 || GetLastError()==134)) { Log("Entry blocked: insufficient margin"); return false; }
   ResetLastError(); int ticket=OrderSend(g_symbol,direction>0 ? OP_BUY : OP_SELL,lots,price,InpSlippagePoints,sl,tp,
      SG_ORDER_COMMENT,ConsoleMagic,0,direction>0 ? SX_GREEN : SX_RED);
   bool success=ticket>0;
   if(!success) { int error=GetLastError(); if(error==130 && InpAutoWidenStop) g_stopPaddingPts=(int)MathMin(1000,g_stopPaddingPts==0 ? 20 : g_stopPaddingPts*2); if(error==128) SetUncertain("Order timeout"); else Log("Entry rejected: MT4 error "+IntegerToString(error)); }
   else Log(Side(direction)+" executed #"+IntegerToString(ticket));
#endif
   ConsoleLoadPositions();
#ifndef __MQL5__
   if(success && OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) FlowSlipRecord(price,OrderOpenPrice(),direction);
#endif
   if(success) {
      for(int i=0;i<ArraySize(g_positions);i++) {
         string atrKey=PositionATRKey(g_positions[i].ticket);
         if(!GlobalVariableCheck(atrKey)) GlobalVariableSet(atrKey,g_atr);
      }
      WriteGV("tradebar",(double)iTime(g_symbol,g_tf,1)); CountEntry();
      GlobalVariablesFlush();
   }
   return success;
}
double ApexConsoleSwing(int side) {
   MqlRates bars[];
   if(CopyRates(g_symbol,g_tf,1,3,bars)!=3) return 0;
   return side>0 ? MathMin(bars[0].low,MathMin(bars[1].low,bars[2].low)) :
                   MathMax(bars[0].high,MathMax(bars[1].high,bars[2].high));
}
bool ModifyStop(SXPosition &position,double sl,bool &already) {
   already=false;
   if(!CanTrade()) return false;
   if(VectorConsoleLock && g_trailing) {
      MqlTick live;
      if(!Tick(live)) return false;
      double tick=TickSize(),fee=PositionCostPrice(position.lots);
      if(tick<=0 || (InpPositiveCostLockPerLot>0 && fee<=0)) return false;
      double market=position.direction>0 ? live.bid : live.ask;
      sl=NormalizeDouble(SXRoundPrice(sl,tick,position.direction),g_consoleDigits);
      double floorGain=fee+(live.ask-live.bid)+(VectorCostTicks+1)*tick;
      if(position.direction*(sl-position.open)<floorGain-tick*1e-7 ||
         position.direction*(market-sl)<MinStopDistance(true)-tick*1e-7) return false;
   }
#ifdef __MQL5__
   if(!PositionSelectByTicket(position.ticket) || PositionGetString(POSITION_SYMBOL)!=g_symbol || PositionGetInteger(POSITION_MAGIC)!=ConsoleMagic) return false;
   if(IsNetting() && (!NettingExclusive() || !PositionSelectByTicket(position.ticket))) return false;
   double liveSL=PositionGetDouble(POSITION_SL);
   if(liveSL>0 && position.direction*(sl-liveSL)<=0) { already=true; return true; }
   MqlTradeRequest request={}; request.action=TRADE_ACTION_SLTP; request.position=position.ticket;
   request.symbol=g_symbol; request.magic=(ulong)ConsoleMagic; request.sl=sl; request.tp=PositionGetDouble(POSITION_TP);
   return SendRequestStatus(request,"Protect #"+StringFormat("%I64u",position.ticket),already);
#else
   if(!OrderSelect((int)position.ticket,SELECT_BY_TICKET,MODE_TRADES) || OrderCloseTime()!=0 || OrderSymbol()!=g_symbol || OrderMagicNumber()!=ConsoleMagic) return false;
   double liveSL=OrderStopLoss();
   if(liveSL>0 && position.direction*(sl-liveSL)<=0) { already=true; return true; }
   ResetLastError();
   bool success=OrderModify((int)position.ticket,OrderOpenPrice(),sl,OrderTakeProfit(),0,clrNONE);
   if(!success) {
      int error=GetLastError();
      if(error==1 && OrderSelect((int)position.ticket,SELECT_BY_TICKET,MODE_TRADES) && OrderCloseTime()==0 &&
         OrderStopLoss()>0 && position.direction*(OrderStopLoss()-sl)>=-TickSize()*0.000001) { already=true; return true; }
      Log("SL modify failed: "+IntegerToString(error));
   }
   return success;
#endif
}
bool ClosePosition(SXPosition &position,double volume) {
   if(!CanTrade()) { Log("Close blocked: algorithmic trading disabled"); return false; }
   MqlTick quote; if(!Tick(quote)) return false;
   volume=NormalizeDouble(volume,8);
#ifdef __MQL5__
   if(!PositionSelectByTicket(position.ticket) || PositionGetString(POSITION_SYMBOL)!=g_symbol || PositionGetInteger(POSITION_MAGIC)!=ConsoleMagic) return false;
   if(IsNetting() && (!NettingExclusive() || !PositionSelectByTicket(position.ticket))) return false;
   volume=MathMin(volume,PositionGetDouble(POSITION_VOLUME)); if(volume<=0) return false;
   MqlTradeRequest request={}; request.action=TRADE_ACTION_DEAL; request.position=position.ticket;
   request.symbol=g_symbol; request.magic=(ulong)ConsoleMagic;
   request.type=position.direction>0 ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
   request.volume=volume; request.price=position.direction>0 ? quote.bid : quote.ask;
   request.deviation=(ulong)InpSlippagePoints; request.type_filling=Filling(); request.comment=SG_ORDER_COMMENT;
   double before=PositionGetDouble(POSITION_VOLUME);
   if(!SendRequest(request,"Close #"+StringFormat("%I64u",position.ticket))) return false;
   double after=PositionSelectByTicket(position.ticket) ? PositionGetDouble(POSITION_VOLUME) : 0.0;
   double tolerance=SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_STEP)*0.1;
   return true;
#else
   ResetLastError();
   if(!OrderSelect((int)position.ticket,SELECT_BY_TICKET,MODE_TRADES) || OrderCloseTime()!=0 || OrderSymbol()!=g_symbol || OrderMagicNumber()!=ConsoleMagic) return false;
   volume=MathMin(volume,OrderLots()); if(volume<=0) return false;
   bool success=OrderClose((int)position.ticket,volume,position.direction>0 ? quote.bid : quote.ask,InpSlippagePoints,clrNONE);
   if(!success) { int error=GetLastError(); if(error==128) SetUncertain("Close timeout"); else Log("Close failed: MT4 error "+IntegerToString(error)); }
   else Log("Closed #"+StringFormat("%I64u",position.ticket));
   return success;
#endif
}
bool CancelWorkingOrders() {
   bool ok=true;
   if(!CanTrade()) return WorkingOrders()==0;
   for(int i=OrdersTotal()-1;i>=0;i--) {
#ifdef __MQL5__
      ulong ticket=OrderGetTicket(i); if(ticket==0) continue;
      if(OrderGetString(ORDER_SYMBOL)!=g_symbol || OrderGetInteger(ORDER_MAGIC)!=ConsoleMagic) continue;
      MqlTradeRequest request={}; request.action=TRADE_ACTION_REMOVE; request.order=ticket;
      request.symbol=g_symbol; request.magic=(ulong)ConsoleMagic;
      if(!SendRequest(request,"Cancel working order")) ok=false;
#else
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderSymbol()!=g_symbol || OrderMagicNumber()!=ConsoleMagic || OrderType()<=OP_SELL) continue;
      if(!OrderDelete(OrderTicket(),clrNONE)) { ok=false; Log("Pending cancellation failed: "+IntegerToString(GetLastError())); }
#endif
   }
   return ok;
}
bool CloseOwned(int direction=0,bool partial=false) {
   if(g_uncertain) return false;
   ConsoleLoadPositions(); bool ok=true;
   if(!partial && direction==0) ok=CancelWorkingOrders();
   for(int i=ArraySize(g_positions)-1;i>=0;i--) {
      if(direction!=0 && g_positions[i].direction!=direction) continue;
      double volume=g_positions[i].lots;
      if(partial) {
         double minimum=SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN);
         volume=ConsoleNormalizeLots(volume*0.5);
         if(volume<minimum || g_positions[i].lots-volume<minimum-1e-9) { Log("50% close skipped: minimum volume / remainder"); continue; }
      }
      if(!ClosePosition(g_positions[i],volume)) ok=false;
   }
   ConsoleLoadPositions(); return ok;
}
bool NoDailyLossLock() { return BroadLocks() || InpNoDailyLossLock; }
bool NoDrawdownLock() { return BroadLocks() || InpNoDrawdownLock; }
bool NoProfitLock() { return BroadLocks() || InpNoProfitTargetLock; }
bool NoPositionCaps() { return BroadRestrictions() || InpNoPositionCaps; }
bool NoSpreadQuoteLimits() { return BroadRestrictions() || InpNoSpreadQuoteLimits; }
bool NoTimeRestrictions() { return BroadRestrictions() || InpNoTimeRestrictions; }
bool NoCooldowns() { return BroadRestrictions() || InpNoCooldowns; }
bool NoLotCap() { return BroadRestrictions() || InpNoLotCap; }
bool NoMarginPrecheck() { return BroadRestrictions() || InpNoMarginPrecheck; }
bool AnyUnlock() {
   if(BroadLocks() || BroadRestrictions()) return true;
   return InpUnlockAll || InpNoDailyLossLock || InpNoDrawdownLock || InpNoProfitTargetLock || InpNoPositionCaps || InpNoSpreadQuoteLimits ||
      InpNoTimeRestrictions || InpNoCooldowns || InpNoLotCap || InpNoMarginPrecheck;
}
double RiskBaseAmount() {
   double value=ConsoleEquity();
   if(InpRiskBase==RISKBASE_BALANCE) value=AccountInfoDouble(ACCOUNT_BALANCE);
   else if(InpRiskBase==RISKBASE_FREE_MARGIN) value=AccountInfoDouble(ACCOUNT_MARGIN_FREE);
   return value>0 ? value : ConsoleEquity();
}
string LadderKey(SXPosition &position,string tag) {
   return g_key+"LAD"+IntegerToString((int)position.opened)+(position.direction>0 ? "B" : "S")+tag;
}
// Profit ladder: closes a share of the ORIGINAL lots at each R target. Keys use open time, so MT4 partial-close ticket changes do not repeat a level.
double InitialRiskPrice(SXPosition &p,double atr) {
   string key=PositionATRKey(p.ticket)+"R";
   if(GlobalVariableCheck(key)) return GlobalVariableGet(key);
   double distance=p.direction*(p.open-p.sl);
   if(p.sl<=0 || distance<=0) distance=InpFixedStopPoints>0 ? InpFixedStopPoints*g_consolePoint : MathMax(atr*InpInitialSL_ATR,InpMinSLPoints*g_consolePoint);
   if(distance>0) GlobalVariableSet(key,distance);
   return distance;
}
bool LadderStep(SXPosition &position,double market,double reference) {
   double initRisk=InitialRiskPrice(position,reference);
   if(initRisk<=0) return false;
   string originKey=LadderKey(position,"O");
   if(!GlobalVariableCheck(originKey)) GlobalVariableSet(originKey,position.lots);
   double origin=GlobalVariableGet(originKey),minVol=SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN);
   double target[3],share[3];
   target[0]=InpLadder1R; share[0]=InpLadder1Pct;
   target[1]=InpLadder2R; share[1]=InpLadder2Pct;
   target[2]=InpLadder3R; share[2]=InpLadder3Pct;
   for(int i=0;i<3;i++) {
      if(target[i]<=0 || share[i]<=0) continue;
      string key=LadderKey(position,IntegerToString(i));
      if(GlobalVariableCheck(key)) continue;
      if(position.direction*(market-position.open)<target[i]*initRisk) continue;
      double volume=ConsoleNormalizeLots(origin*share[i]/100.0);
      if(volume>position.lots-minVol) volume=ConsoleNormalizeLots(position.lots-minVol);
      if(volume<minVol-1e-9) { GlobalVariableSet(key,2.0); continue; }
      if(ClosePosition(position,volume)) {
         GlobalVariableSet(key,1.0); GlobalVariablesFlush();
         Log("Profit ladder L"+IntegerToString(i+1)+" "+DoubleToString(target[i],2)+"R closed "+DoubleToString(volume,3)+" lots");
         return true;
      }
      return false;
   }
   return false;
}
double PositiveBEPrice(SXPosition &position,double tick,double reference,double cost,double cushion) {
   double lock=MathMax(cushion,cost+g_beLock*reference);
   return NormalizeDouble(SXRoundPrice(position.open+position.direction*lock,tick,-position.direction),g_consoleDigits);
}
void ApplyPositiveBE() {
   ConsoleLoadPositions();
   if(ArraySize(g_positions)==0) { Log("BE: no EA positions on "+g_symbol); return; }
   if(!CanTrade()) { Log("BE: enable algorithmic trading"); return; }
   if(g_uncertain) { Log("BE: reconcile this symbol first"); return; }
   MqlTick q;
   double tick=TickSize();
   if(tick<=0 || !Tick(q)) { Log("BE: waiting for a valid quote"); return; }
   if(!g_consoleReady) BuildSnapshot();
   double distance=MinStopDistance(true),spread=q.ask-q.bid,tolerance=tick*0.000001;
   int changed=0,protectedAlready=0,waiting=0,failed=0;
   for(int i=0;i<ArraySize(g_positions);i++) {
      SXPosition p=g_positions[i];
      double reference=PositionATR(p.ticket,g_consoleReady ? g_atr : 0);
      double cost=PositionCostPrice(p.lots);
      if((g_beLock>0 && reference<=0) || (InpPositiveCostLockPerLot>0 && cost<=0)) { waiting++; continue; }
      double cushion=cost+MathMax(1,g_lockTicks)*tick+(InpExtraSpreadCushion ? spread : 0);
      double target=PositiveBEPrice(p,tick,reference,cost,cushion);
      double market=p.direction>0 ? q.bid : q.ask;
      if(target<=0 || p.direction*(target-p.open)<=0) { waiting++; continue; }
      if(p.sl>0 && p.direction*(target-p.sl)<=tolerance) { protectedAlready++; continue; }
      if(p.direction*(market-target)<distance-tolerance) { waiting++; continue; }
      bool already=false;
      if(ModifyStop(p,target,already)) {
         if(already) protectedAlready++;
         else { changed++; g_stopStage=3; }
      }
      else { failed++; if(g_uncertain) { Log("BE: broker status unknown; reconcile symbol"); return; } }
   }
   if(failed>0) Log("BE: "+IntegerToString(changed)+" moved, "+IntegerToString(failed)+" unconfirmed; see Journal");
   else Log("BE: "+IntegerToString(changed)+" moved, "+IntegerToString(protectedAlready)+" protected, "+IntegerToString(waiting)+" waiting");
}
void ManageStops() {
   if(!g_consoleReady || !CanTrade() || ArraySize(g_positions)==0) return;
   MqlTick quote; if(!Tick(quote)) return;
   double minDistance=MinStopDistance(true),tick=TickSize();
   double spreadPrice=MathMax(0.0,quote.ask-quote.bid);
   bool trailQuoteSafe=SXSpreadShockSafe(spreadPrice,g_atr,ConsoleMaxSpreadATR,InpSpreadShockShield && !NoSpreadQuoteLimits());
   double oldAtr=g_cachedAtrPrior,ema21=g_cachedFast,prevLow=g_prevLo,prevHigh=g_prevHi;
   double low8=g_lo8,high8=g_hi8;
   double prideCloses[],prideEff=0;
   bool prideAvailable=false;
   if(VectorConsoleLock && PridePortfolioLock && g_trailing) {
      ArraySetAsSeries(prideCloses,true);
      prideAvailable=CopyClose(g_symbol,g_tf,1,PridePathBars+1,prideCloses)==PridePathBars+1;
      if(prideAvailable) prideEff=PrideEfficiency(prideCloses,0,PridePathBars);
   }
   for(int i=0;i<ArraySize(g_positions);i++) {
      SXPosition position=g_positions[i];
      if(g_consoleStrategy>=DR_UT && ((position.direction>0 && g_gem.droidExitLong) || (position.direction<0 && g_gem.droidExitShort))) {
         if(!g_uncertain && TimeCurrent()>=g_assets[g_active].droidRetry) {
            if(!ClosePosition(position,position.lots)) g_assets[g_active].droidRetry=TimeCurrent()+InpClockRetrySeconds;
         }
         continue;
      }
      string referenceKey=PositionATRKey(position.ticket);
      if(!GlobalVariableCheck(referenceKey)) GlobalVariableSet(referenceKey,g_atr);
      double reference=PositionATR(position.ticket,g_atr);
      double tradeRiskDistance=InitialRiskPrice(position,reference);
      double market=position.direction>0 ? quote.bid : quote.ask;
      double bestEx=UpdatePositionExcursion(position.ticket,position.direction,market);
      if(((InpMaxHoldBars>0 && TimeCurrent()-position.opened>=(datetime)(InpMaxHoldBars*PeriodSeconds(g_tf))) || (InpClockMaxHoldMinutes>0 && TimeCurrent()-position.opened>=(datetime)(InpClockMaxHoldMinutes*60))) && (!InpTimeExitOnlyProfitable || position.profit>=0)) {
         if(ClosePosition(position,position.lots)) Log("Max-hold time exit #"+StringFormat("%I64u",position.ticket));
         continue;
      }
      if(!trailQuoteSafe) continue;
      if(g_consoleStrategy>=DROID_ADAPTIVE_CONFLUENCE && g_consoleStrategy<DR_UT && InpSmartVelocityRatchet && g_trailing && position.direction*g_velocity<0 && position.direction*(market-position.open)>=2*reference) {
         double level=position.open+position.direction*reference;
         if(position.direction*(market-level)>minDistance && (position.sl==0 || position.direction*(level-position.sl)>tick)) {
            bool same=false;
            if(ModifyStop(position,level,same)) continue;
         }
      }
      if(BPSmartPartial(position,market,tradeRiskDistance)) continue;
      BPManageTP(position,market,tradeRiskDistance,tick,minDistance);
      if(InpUseRRPartialTP && (g_consoleStrategy==UT_ALERTS_STRATEGY_RR || g_trailMode==(int)TRAIL_RR_LADDER_RR) && InpRRPartialRR>0) {
         string pKey=PositionPartialKey(position.ticket);
         if(!GlobalVariableCheck(pKey)) {
            double initRisk=tradeRiskDistance;
            if(initRisk>0 && position.direction*(market-position.open)>=InpRRPartialRR*initRisk) {
               double minVol=SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN);
               double halfVol=ConsoleNormalizeLots(position.lots*0.5);
               if(halfVol>=minVol && position.lots-halfVol>=minVol-1e-9 && ClosePosition(position,halfVol)) {
                  GlobalVariableSet(pKey,1.0);
                  Log("RR 3:1 R:R 50% partial close #" + StringFormat("%I64u",position.ticket));
                  continue; // Do not modify the pre-close ticket/volume snapshot
               }
            }
         }
      }
      if(InpUseProfitLadder && LadderStep(position,market,reference)) continue;
      double proposed=position.sl;
      int stage=1;
      if(InpTrailStartPoints>0) {
         if(g_trailing) proposed=FixedTrail(position.direction,position.open,position.sl,market,minDistance,tick);
         stage=proposed!=position.sl ? 5 : 1;
      } else if(g_trailMode<=1 && InpPositiveCostLockPerLot<=0) {
         proposed=SXProtectStop(position.direction,position.open,position.sl,market,g_atr,reference,
            g_breakEven,g_beTrigger,g_beLock,g_trailing,g_trStart,g_trGap,
            InpUseUTTrail,g_utCurrent,minDistance,tick,false);
         stage=proposed!=position.sl ? (g_trailing && position.direction*(market-position.open)>=g_trStart*reference ? 5 : 3) : 1;
      } else {
         double activeUT=(g_consoleStrategy==UT_ALERTS_STRATEGY_RR && g_rrTrail>0) ? g_rrTrail : g_utCurrent;
         proposed=SXAdvancedTrailStop(g_trailMode,position.direction,position.open,position.sl,market,bestEx,
            g_atr,oldAtr,reference,ema21,g_superLine,low8,high8,prevLow,prevHigh,g_adx,g_rsi,
            spreadPrice,PositionCostPrice(position.lots),g_breakEven,g_beTrigger,g_beLock,
            InpStage2CompressionATR,InpStage4ExtraLockATR,g_trailing,g_trStart,g_trGap,
            InpUseUTTrail,activeUT,minDistance,tick,false,stage);
       }
       if(InpTrailStartPoints==0 && g_trailing && InpUsePositiveProfitRatchet) {
          double initialRisk=MathMax(tick,tradeRiskDistance);
          double costBuffer=PositionCostPrice(position.lots);
          double floor=SXPositiveProfitRatchetFloor(position.direction,position.open,bestEx,initialRisk,g_atr,
             costBuffer,InpProfitRatchetStartATR,InpProfitRatchetStepATR,InpProfitRatchetLockPercent,
             InpProfitRatchetStepPercent,InpProfitRatchetMaxPercent,tick);
          if(floor>0) {
             double safeFloor=position.direction>0 ? MathMin(floor,market-minDistance) : MathMax(floor,market+minDistance);
             safeFloor=SXRoundPrice(safeFloor,tick,position.direction);
             bool safe=safeFloor>0 && position.direction*(safeFloor-position.open)>0 &&
                       position.direction*(market-safeFloor)>=minDistance-1e-10;
             if(safe) {
                if(position.direction>0 && safeFloor>proposed) { proposed=safeFloor; stage=6; }
                else if(position.direction<0 && (proposed==0 || safeFloor<proposed)) { proposed=safeFloor; stage=6; }
             }
          }
      }
      if(g_bpTrailOn) {
         double curRef=position.sl;
         if(proposed>0 && (curRef==0 || position.direction*(proposed-curRef)>0)) curRef=proposed;
         double bpSL=BPPositiveSL(position.direction,position.open,market,curRef,g_atr,tradeRiskDistance,spreadPrice/g_consolePoint,g_consolePoint,tick,high8,low8,prevHigh,prevLow,bestEx,g_utCurrent);
         if(bpSL>0) { // keep every positive-trail stop at least the broker stop distance from price, ratchet-only
            bpSL=position.direction>0 ? MathMin(bpSL,market-minDistance) : MathMax(bpSL,market+minDistance);
            bpSL=SXRoundPrice(bpSL,tick,position.direction);
            if(curRef>0 && position.direction*(bpSL-curRef)<=0) bpSL=0;
         }
         if(bpSL>0 && position.direction*(bpSL-position.open)>0 && (proposed==0 || position.direction*(bpSL-proposed)>0)) { proposed=bpSL; stage=6; }
      }
      double cost=PositionCostPrice(position.lots);
      if(InpClockTieredRatchet && g_trailing && tradeRiskDistance>0) {
         double rawFloor=SXStoneGemRatchetFloor(position.direction,position.open,bestEx,tradeRiskDistance,cost);
         if(rawFloor>0) {
            double safe=position.direction>0 ? MathMin(rawFloor,market-minDistance) : MathMax(rawFloor,market+minDistance);
            safe=SXRoundPrice(safe,tick,position.direction);
            if(safe>0 && position.direction*(safe-position.open)>0 && position.direction*(market-safe)>=minDistance-tick*1e-6 && (proposed==0 || position.direction*(safe-proposed)>0)) { proposed=safe; stage=6; }
         }
      }
      double stale=g_trailing ? XETimeBEStop(position,market,tradeRiskDistance,cost,minDistance,tick) : 0;
      if(stale>0 && (proposed<=0 || position.direction*(stale-proposed)>0)) { proposed=stale; stage=6; }
      if(VectorConsoleLock && g_trailing && (InpPositiveCostLockPerLot<=0 || cost>0)) {
         double buffer=cost+spreadPrice+VectorCostTicks*tick;
         double ultra=VectorPositiveStop(position.direction,position.open,position.sl,market,bestEx,
                        tradeRiskDistance,g_atr,g_adx,buffer,minDistance,tick,VectorArmR,VectorStepTicks);
         if(prideAvailable) {
            double staged=PrideStagedStop(position.direction,position.open,position.sl,market,bestEx,tradeRiskDistance,
                          g_atr,prideEff,buffer,minDistance,tick,VectorArmR,VectorStepTicks,PrideConsolePeak ? PrideRetreat : 0.0,PrideKeep);
            if(staged>0 && (ultra<=0 || position.direction*(staged-ultra)>0)) ultra=staged;
         }
         if(ApexPortfolioStructure) {
            double level=ApexProfitLock(position.direction,position.open,position.sl,market,bestEx,tradeRiskDistance,
                        g_atr,buffer,minDistance,tick,VectorArmR,VectorStepTicks,ApexRetain,0,
                        ApexConsoleSwing(position.direction),true);
            if(level>0 && (ultra<=0 || position.direction*(level-ultra)>0)) ultra=level;
         }
         if(ultra>0 && (proposed<=0 || position.direction*(ultra-proposed)>0)) { proposed=ultra; stage=6; }
      }
      if(InpPositiveCostLockPerLot>0 && cost<=0 && (g_positiveOnly)) continue;
      double cushion=cost+g_lockTicks*tick+(InpExtraSpreadCushion ? spreadPrice : 0.0);
      double floorSL=SXRoundPrice(position.open+position.direction*cushion,tick,-position.direction);
      if((g_breakEven && position.direction*(market-position.open)>=g_beTrigger*reference)) {
         double be=PositiveBEPrice(position,tick,reference,cost,cushion);
         if(position.direction*(market-be)>=minDistance && (proposed==0 || position.direction*(be-proposed)>0)) { proposed=be; stage=3; }
      }
      if((g_positiveOnly) && position.direction*(proposed-floorSL)<-tick*0.000001) continue;
      if(proposed<=0 || position.direction*(market-proposed)<minDistance-tick*0.000001) continue;
      g_stopStage=stage;
      double minimumStep=MathMax(tick,InpTrailStartPoints>0 ? InpTrailStepPoints*g_consolePoint : g_trStep*g_atr);
      if(proposed>0 && proposed!=position.sl && (position.sl==0 || position.direction*(proposed-position.sl)>=minimumStep)) {
         bool already=false; if(ModifyStop(position,NormalizeDouble(proposed,g_consoleDigits),already) && !already && stale>0 && proposed==stale) g_xeTimeBECount++;
      }
   }
}
int DayCode() { MqlDateTime d; TimeToStruct(TimeCurrent(),d); return d.year*10000+d.mon*100+d.day; }
void RiskGuard() {
   double equity=ConsoleEquity(); if(equity<=0) return;
   int day=DayCode();
   if(day!=g_dayCode) {
      g_dayCode=day; g_dayEquity=equity; g_dailyLock=false; g_profitLock=false;
      WriteGuard("day",day); WriteGuard("dayeq",equity); WriteGuard("daylock",0); WriteGuard("profitlock",0);
   }
   int week=FlowWeekCode();
   if(week!=g_weekCode) {
      g_weekCode=week; g_weekEquity=equity; g_weeklyLock=false;
      WriteGuard("week",week); WriteGuard("weekeq",equity); WriteGuard("weeklock",0);
   }
   g_weekLoss=g_weekEquity>0 ? MathMax(0,100*(g_weekEquity-equity)/g_weekEquity) : 0;
   if(NoDailyLossLock() && g_weeklyLock) { g_weeklyLock=false; WriteGuard("weeklock",0); }
   if(!NoDailyLossLock() && !g_weeklyLock && InpWeeklyLossPercent>0 && g_weekLoss>=InpWeeklyLossPercent) {
      g_weeklyLock=true; WriteGuard("weeklock",1); Notify("Weekly equity-loss limit reached"); GlobalVariablesFlush();
   }
   if(g_consolePeakEquity<equity) { g_consolePeakEquity=equity; WriteGuard("peak",equity); }
   g_dayLoss=g_dayEquity>0 ? MathMax(0,100*(g_dayEquity-equity)/g_dayEquity) : 0;
   g_drawdown=g_consolePeakEquity>0 ? MathMax(0,100*(g_consolePeakEquity-equity)/g_consolePeakEquity) : 0;
   g_bpDayGain=g_dayEquity>0 ? MathMax(0,100*(equity-g_dayEquity)/g_dayEquity) : 0;
   if(NoDailyLossLock() && g_dailyLock) { g_dailyLock=false; WriteGuard("daylock",0); }
   if(NoDrawdownLock() && g_peakLock) { g_peakLock=false; WriteGuard("peaklock",0); }
   if(NoProfitLock() && g_profitLock) { g_profitLock=false; WriteGuard("profitlock",0); }
   if(!NoDailyLossLock() && !g_dailyLock && InpDailyLossPercent>0 && g_dayLoss>=InpDailyLossPercent) {
      g_dailyLock=true; WriteGuard("daylock",1); Notify("Daily equity-loss limit reached"); GlobalVariablesFlush();
   }
   if(!NoDrawdownLock() && !g_peakLock && InpMaxDrawdownPercent>0 && g_drawdown>=InpMaxDrawdownPercent) {
      g_peakLock=true; WriteGuard("peaklock",1); Notify("Peak equity drawdown limit reached"); GlobalVariablesFlush();
   }
   if(!NoProfitLock() && !g_profitLock && InpDailyProfitTargetPct>0 && g_dayEquity>0 && 100*(equity-g_dayEquity)/g_dayEquity>=InpDailyProfitTargetPct) {
      g_profitLock=true; WriteGuard("profitlock",1); Notify("Daily profit target reached; new entries paused until next server day"); GlobalVariablesFlush();
   }
   static datetime lastAttempt=0;
   if(g_profitLock && InpProfitTargetClosesAll && PortfolioExposureCount()>0 && TimeCurrent()-lastAttempt>=3) {
      lastAttempt=TimeCurrent(); RequestPortfolioExit("Daily profit target");
   }
   if(!NoTimeRestrictions() && InpUseFridayCutoff && InpFridayFlatten && PortfolioExposureCount()>0 && TimeCurrent()-lastAttempt>=3) {
      MqlDateTime fr; TimeToStruct(TimeCurrent(),fr);
      if(fr.day_of_week==5 && fr.hour>=InpFridayFlattenHour) { lastAttempt=TimeCurrent(); RequestPortfolioExit("Friday flatten"); }
   }
   if((g_dailyLock || g_peakLock || g_weeklyLock) && InpCloseOnRiskLock && TimeCurrent()-lastAttempt>=3) {
      lastAttempt=TimeCurrent(); RequestPortfolioExit("Account equity guard");
   }
   if(g_emergency && PortfolioExposureCount()>0 && TimeCurrent()-lastAttempt>=3) {
      lastAttempt=TimeCurrent(); RequestPortfolioExit("Emergency stop");
   }
}
bool ProcessSignal() {
   if(!g_auto || !g_consoleReady || g_candidate==0 || g_exitRequested || g_consolePortfolioExit) return false;
   datetime closed=iTime(g_symbol,g_tf,1);
   g_consoleLastSignalTime=(datetime)ReadGV("signal",(double)g_consoleLastSignalTime);
   int elapsed=100000000;
   if(g_consoleLastSignalTime>0) {
      int shift=iBarShift(g_symbol,g_tf,g_consoleLastSignalTime,false); elapsed=shift>=1 ? shift-1 : 0;
   }
   if(!NoCooldowns() && !SXCooldown(elapsed,InpCooldownBars)) { g_message="Cooldown: "+IntegerToString((int)MathMax(0,InpCooldownBars-elapsed))+" bars"; return false; }
   SXEntry entry=AutomaticEntryStyle();
   double trigger=g_consoleStrategy==SUPERTREND_STOP ? (g_candidate>0 ? g_superUpper : g_superLower) : 0;
   string why="";
   if(!SignalFilters(g_candidate,why)) { Log("Signal filtered: "+why); return false; }
   if(!BroadRestrictions() && (InpUseShockPause || InpUseCostGate)) {
      MqlTick quote;
      double price=0,sl=0,tp=0;
      if(!Tick(quote)) { Log("Entry quote unavailable"); return false; }
      if(!EntryPrices(g_candidate,entry,trigger,quote,price,sl,tp,why) ||
         !AutoEntryQuality(quote.ask-quote.bid,price,sl,tp,why)) { Log(why); return false; }
   }
   if(g_consoleStrategy==SUPERTREND_STOP) {
      if(ArraySize(g_positions)>0) { g_message="Position already open"; return false; }
      if(WorkingOrders()>0 && !CancelWorkingOrders()) return false;
   } else if(WorkingOrders()>0) { g_message="Waiting for owned pending order"; return false; }
   DrawSignal(closed,g_candidate);
   bool accepted=entry==ENTRY_MARKET ? OpenPosition(g_candidate,false) : PlacePending(g_candidate,entry,false,trigger);
   if(accepted || g_uncertain) {
      g_consoleLastSignalTime=closed; g_lastSignalDir=g_candidate;
      WriteGV("signal",(double)closed); WriteGV("sigdir",g_candidate); GlobalVariablesFlush();
      if(accepted) Notify(Side(g_candidate)+" accepted | "+EnumToString(g_consoleStrategy)+" | "+g_symbol);
   }
   return accepted || g_uncertain;
}

// Reserve the bar atomically before submission. Release only after a definite failure.
// The legacy bar key is deliberately not reused: it may represent a rejected order.
void TryClockEntry(datetime closed) {
   if(!g_auto) { g_message="AUTO OFF: enable automatic entries"; return; }
   if(!g_consoleReady) return;
   if(ReadGV("uncertain",0)>0 || ReadGV("inflight",0)>0) g_uncertain=true;
   if(g_uncertain) { g_message="RECONCILE: inspect broker orders first"; return; }
   string permission=TradePermissionIssue(); if(permission!="") { g_message="ALGO OFF: "+permission; return; }
   if(g_dailyLock || g_peakLock || g_profitLock || g_weeklyLock || g_emergency) { g_message="RISK LOCK: check equity protection"; return; }
   if(g_exitRequested || g_consolePortfolioExit) { g_message="Owned exit in progress"; return; }
   if(g_candidate==0) { g_message=SignalWaitReason(); return; }
   ConsoleLoadPositions();
   if(!NoPositionCaps() && ArraySize(g_positions)+WorkingOrders()>=ConsoleMaxPositions && !ConsoleCloseOnOpposite) {
      g_message="Position / pending cap reached"; return;
   }
   if(ReadGV("tradebar",0)>=(double)closed || ReadGV("signal",0)>=(double)closed) {
      g_message="Entry already accepted this bar"; return;
   }
   datetime lastSignal=(datetime)ReadGV("signal",0);
   if(!NoCooldowns() && lastSignal>0) {
      int shift=iBarShift(g_symbol,g_tf,lastSignal,false);
      int elapsed=shift>=1 ? shift-1 : 0;
      if(elapsed<InpCooldownBars) { g_message="Cooldown: "+IntegerToString(InpCooldownBars-elapsed)+" bars"; return; }
   }
   string why="";
   if(!SignalFilters(g_candidate,why)) { g_message="Signal: "+why; return; }
   SXEntry style=AutomaticEntryStyle();
   if(!SupportsRequest(style,why)) { g_message="Broker: "+why; return; }
   if(g_consoleStrategy!=SUPERTREND_STOP && !ConsoleCloseOnOpposite && !EntryGate(g_candidate,why)) { g_message="Blocked: "+why; return; }
   MqlTick q;
   if(!Tick(q)) { g_message="Waiting for valid broker quote"; return; }
   double px=0,sl=0,tp=0, trigger=g_consoleStrategy==SUPERTREND_STOP ? (g_candidate>0 ? g_superUpper : g_superLower) : 0;
   if(!EntryPrices(g_candidate,style,trigger,q,px,sl,tp,why) || !AutoEntryQuality(q.ask-q.bid,px,sl,tp,why)) { g_message=why; return; }
   double lots=RiskLots(g_candidate,px,sl,false);
   if(lots<=0) { g_message="Risk size below minimum "+DoubleToString(SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN),3)+" lots / valuation unavailable"; return; }
   if(!ConsoleCloseOnOpposite && g_consoleStrategy!=SUPERTREND_STOP && !PortfolioRiskAllows(g_candidate,lots,px,sl)) { g_message="Aggregate stop-risk cap"; return; }
   string key=g_key+"entrybar";
   if(!GlobalVariableCheck(key) && !GlobalVariableTemp(key)) { g_message="Entry reservation unavailable"; return; }
   double previous=GlobalVariableGet(key);
   if(previous>=(double)closed) { g_message="Entry already reserved this candle"; return; }
   datetime now=TimeCurrent();
   if(ReadGV("trybar",0)==(double)closed) {
      if(ReadGV("trycount",0)>=InpClockAttemptsPerBar) { g_message="Retry limit reached for this candle"; return; }
      if(now-(datetime)ReadGV("trytime",0)<InpClockRetrySeconds) return;
   }
   if(!GlobalVariableSetOnCondition(key,(double)closed,previous)) { g_message="Entry reservation held by another instance"; return; }
   if(ReadGV("trybar",0)!=(double)closed) { WriteGV("trybar",(double)closed); WriteGV("trycount",0); }
   WriteGV("trycount",ReadGV("trycount",0)+1); WriteGV("trytime",(double)now);
   // Persist a restart-safe marker before the broker path. A crash requires reconciliation.
   WriteGV("inflight",(double)closed);
   GlobalVariablesFlush();
   bool accepted=ProcessSignal();
   WriteGV("inflight",0);
   if(!accepted && !g_uncertain && ReadGV("uncertain",0)<=0) {
      GlobalVariableSetOnCondition(key,previous,(double)closed);
      if(ReadGV("trycount",0)>=InpClockAttemptsPerBar) Log("Retry limit: "+g_message);
   }
   GlobalVariablesFlush();
}

// The same robot is rasterized for the console and the chart at their actual
// pixel sizes. The untouched pixels are transparent, including the area around the crest.



string StoneName(int stone) {
   string names[12]={"Sky","Rose","Mint","Blue","Lilac","Violet","Orange","Teal","Red","Pink","Green","Gold"};
   return names[stone];
}
color StoneColor(int stone) {
   color colours[12]={C'141,214,239',C'217,49,92',C'22,184,119',C'54,103,224',C'180,163,240',C'153,100,214',
                      C'232,152,55',C'59,184,181',C'178,54,59',C'218,154,190',C'71,169,123',C'218,180,61'};
   return colours[stone];
}
double EdgeValue(double ax,double ay,double bx,double by,double px,double py) {
   return (bx-ax)*(py-ay)-(by-ay)*(px-ax);
}
void Facet(uint &pixels[],int side,double ax,double ay,double bx,double by,double cx,double cy,color fill,int opacity) {
   int left=(int)MathMax(0,MathFloor(MathMin(ax,MathMin(bx,cx))));
   int right=(int)MathMin(side-1,MathCeil(MathMax(ax,MathMax(bx,cx))));
   int top=(int)MathMax(0,MathFloor(MathMin(ay,MathMin(by,cy))));
   int bottom=(int)MathMin(side-1,MathCeil(MathMax(ay,MathMax(by,cy))));
   uint rgb=(((uint)fill&255)<<16)|((uint)fill&65280)|(((uint)fill>>16)&255);
   uint packed=((uint)opacity<<24)|rgb;
   for(int y=top;y<=bottom;y++) for(int x=left;x<=right;x++) {
      double e0=EdgeValue(ax,ay,bx,by,x+0.5,y+0.5);
      double e1=EdgeValue(bx,by,cx,cy,x+0.5,y+0.5);
      double e2=EdgeValue(cx,cy,ax,ay,x+0.5,y+0.5);
      if((e0>=0 && e1>=0 && e2>=0) || (e0<=0 && e1<=0 && e2<=0)) pixels[y*side+x]=packed;
   }
}

string LogoPartName(int part) {
   string wings[10]={"Chassis crown","Chassis shell","Visor glass","LED eyes","Eye glints","Antenna beacon","Drone wings","LED smile","Core halo","Wordmark"};
   if(InpRobotBody==WINGED_DRONE) return wings[part];
   string names[10]={"Shell rim","Shell","Faceplate","Earpieces","Cheeks","Smile","Eyes","Beacon","Eye glint","Wordmark"};
   return names[part];
}
void LoadLogoInputs() {
   g_logoInk[0]=InpLogoCrownRight; g_logoInk[1]=InpLogoUpperRight; g_logoInk[2]=InpLogoLowerRight;
   g_logoInk[3]=InpLogoLowerLeft; g_logoInk[4]=InpLogoUpperLeft; g_logoInk[5]=InpLogoCrownLeft;
   g_logoInk[6]=InpLogoTrace; g_logoInk[7]=InpLogoNodes; g_logoInk[8]=InpLogoGlint; g_logoInk[9]=InpLogoWordmark;
}
color LogoInk(int part) {
   if(g_logoMode==LOGO_CUSTOM && g_logoInk[part]!=clrNONE) return g_logoInk[part];
   color body=g_logoMode==LOGO_CUSTOM ? InpLogoBody : g_logoMode==LOGO_GEMSTONES ? StoneColor(g_primaryGem) : SX_GOLD;
   color node=g_logoMode==LOGO_CUSTOM ? InpLogoNodes : g_logoMode==LOGO_GEMSTONES ? StoneColor(g_accentGem) : SX_BLUE;
   if(part==9) return SX_TEXT;
   if(part==8) return BlendThemeColor(node,clrWhite,48);
   if(part>=6) return node;
   int shade[6]={68,8,-39,-55,-20,40};
   return BlendThemeColor(body,shade[part]>=0 ? clrWhite : C'2,9,19',(int)MathAbs(shade[part]));
}
string LogoHex(color ink) {
   string digits="0123456789ABCDEF",value="#";
   for(int i=0;i<3;i++) {
      int channel=((int)ink>>(8*i))&255;
      value+=StringSubstr(digits,channel/16,1)+StringSubstr(digits,channel%16,1);
   }
   return value;
}
bool ParseLogoHex(string value,color &ink) {
   int start=StringLen(value)==7 && StringGetCharacter(value,0)==35 ? 1 : 0;
   if(StringLen(value)-start!=6) return false;
   int packed=0,channel=0;
   for(int i=0;i<6;i++) {
      int c=(int)StringGetCharacter(value,start+i);
      int digit=c>=48 && c<=57 ? c-48 : c>=65 && c<=70 ? c-55 : c>=97 && c<=102 ? c-87 : -1;
      if(digit<0) return false;
      channel=channel*16+digit;
      if(i%2==1) { packed|=channel<<(8*(i/2)); channel=0; }
   }
   ink=(color)packed; return true;
}
// Start a live edit from the palette actually on screen, including theme/gemstone colours.
void EditLogoColor(int part,color ink) {
   if(g_logoMode!=LOGO_CUSTOM) {
      for(int i=0;i<10;i++) g_logoInk[i]=LogoInk(i);
      g_logoMode=LOGO_CUSTOM;
   }
   g_logoInk[part]=ink;
}
string LogoModeName() {
   return g_logoMode==LOGO_CUSTOM ? "Custom RGB" : g_logoMode==LOGO_GEMSTONES ? "Accent palette" : "Follow theme";
}

void GemObject(string suffix,string tag,int x,int y,int size,int opacity,bool back) {
   string object=g_prefix+suffix,resource=g_prefix+tag;
   if(size<8 || opacity<=0) { ObjectDelete(0,object); return; }
   int slot=tag=="GemHeader" ? 0 : tag=="GemWater" ? 1 : 2;
   bool changed=(g_logoSize[slot]!=size || g_logoAlpha[slot]!=opacity);
   color palette[9]; ArrayInitialize(palette,0);
   for(int i=0;i<9;i++) { palette[i]=LogoInk(i); if(palette[i]!=g_logoCache[slot][i]) changed=true; }
   if(changed) {
      uint pixels[];
      LogoArt(pixels,size,opacity);
      if(ArraySize(pixels)!=size*size || !ResourceCreate("::"+resource,pixels,(uint)size,(uint)size,0,0,(uint)size,COLOR_FORMAT_ARGB_NORMALIZE)) {
         Print(SG_BRAND," | emblem ",GetLastError()); return;
      }
      g_logoSize[slot]=size; g_logoAlpha[slot]=opacity;
      for(int i=0;i<9;i++) g_logoCache[slot][i]=palette[i];
   }
   if(ObjectFind(0,object)<0) {
      if(!ObjectCreate(0,object,OBJ_BITMAP_LABEL,0,0,0)) return;
      ObjectSetString(0,object,OBJPROP_BMPFILE,0,"::"+resource);
      ObjectSetString(0,object,OBJPROP_BMPFILE,1,"::"+resource);
      ObjectSetInteger(0,object,OBJPROP_CORNER,CORNER_LEFT_UPPER);
      ObjectSetInteger(0,object,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
      ObjectSetInteger(0,object,OBJPROP_BACK,back);
      ObjectSetInteger(0,object,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(0,object,OBJPROP_HIDDEN,true);
      ObjectSetInteger(0,object,OBJPROP_ZORDER,0);
      ObjectSetString(0,object,OBJPROP_TOOLTIP,"\n");
   }
   ObjectSetInteger(0,object,OBJPROP_XSIZE,size); ObjectSetInteger(0,object,OBJPROP_YSIZE,size);
   ObjectSetInteger(0,object,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,object,OBJPROP_YDISTANCE,y);
}
void ChartEmblem(int cw,int ch,int panelWidth,bool folded) {
   if(!g_watermark || cw<140 || ch<125) { ObjectDelete(0,g_prefix+"art_watermark"); return; }
   int left=0,right=cw-52;
   if(ConsoleShowDashboard && !folded) { if(g_right) right=g_x-12; else left=g_x+panelWidth+12; }
   int freeWidth=right-left;
   int size=(int)MathMin(InpWatermarkPixels,MathMin(freeWidth*.46,ch*.43));
   if(size<52) { ObjectDelete(0,g_prefix+"art_watermark"); return; }
   GemObject("art_watermark","GemWater",left+(freeWidth-size)/2,(ch-size)/2,size,(int)(2.55*InpMarkOpacity+0.5),true);
}
int Px(int n) { return (int)MathFloor(n*g_consoleScale+0.5); }
string SizeName(int index) {
   string names[5]={"XS","S","M","L","XL"};
   return names[index];
}
string Cut(string value,int limit) {
   if(limit<3) return "";
   if(StringLen(value)<=limit) return value;
   return StringSubstr(value,0,limit-2)+"..";
}
string TrailDisplay() {
   string name=EnumToString((SXTrailMode)g_trailMode);
   StringReplace(name,"TRAIL_","");StringReplace(name,"STONEGEM_","");StringReplace(name,"_"," ");
   return name;
}
string EngineTitle(int idx) {
   string names[SG_ENGINE_COUNT]={
      "UT ATR Trail Reversal",
      "UT ATR Trail with Confluence Filters",
      "Price Range Breakout",
      "Trend Pullback Continuation",
      "Multi-Signal Directional Consensus",
      "Supertrend Direction Change",
      "UT Reversal with VWAP Alignment",
      "Heikin Ashi Impulse with VWAP",
      "UT Reversal with Schaff Trend Cycle",
      "Swing Liquidity Sweep Reversal",
      "Exponential Moving Average Crossover",
      "MACD Histogram Zero Crossing",
      "Bollinger Band Mean Reversion",
      "RSI Reentry from Overbought or Oversold",
      "Volatility Squeeze Release",
      "Confirmed Pivot with RSI Extreme",
      "Cycle Oscillator Reversal",
      "Support and Resistance Bounce",
      "Impulse Candle Engulfing",
      "Schaff Trend Cycle Crossover",
      "Volume Weighted Average Price Crossing",
      "Zero-Lag Moving Average Direction Change",
      "Trend Continuation with Momentum",
      "Supertrend Stop Direction Change",
      "UT Average True Range Trail",
      "UT Alert with Risk-Reward Exit",
      "Quantitative Trend Ensemble",
      "Hull Moving Average and Ichimoku Cloud",
      "Trend and Cycle Hybrid",
      "Directional Momentum Pulse",
      "Adaptive Momentum Pulse",
      "Kalman Filter Trend Continuation",
      "Directional Volume Pressure",
      "Volatility Expansion Breakout",
      "Fair Value Gap Confirmation",
      "Multi-Model Directional Vote",
      "Adaptive Supertrend Direction",
      "Directional Momentum Regime",
      "UT Reversal with Daily Moving Average Bias",
      "Opening Session Directional Bias",
      "UT Coral Trend Pullback",
      "UT Reversal with Schaff Cycle and Hull Trend",
      "Volume Absorption Reversal",
      "Moving Average Ribbon Scalp",
      "Composite Trend Agreement",
      "Volatility Compression Release",
      "Price Level Reclaim",
      "Trend and Range Regime Selection",
      "Donchian Channel Breakout Retest",
      "Keltner Channel Reentry",
      "Aroon Directional Crossover",
      "Vortex Indicator Crossover",
      "Chaikin Money Flow Crossing",
      "Dual UT Trail with Linear Regression",
      "UT Reversal with Long EMA",
      "UT Reversal with Indicator Filter Matrix",
      "Linear Regression Trend Pullback",
      "VWAP and Money Flow Index Reclaim",
      "Momentum Regime Strategy Selection",
      "Market Regime Confluence",
      "Failed Breakout and Level Reclaim",
      "Session Clock Directional Vote",
      "UT Cooldown with Fair Value Gap",
      "Intraday Range Mean Reversion",
      "Intraday Range Breakout",
      "Short-Horizon Range Scalp",
      "Confirmed UT Trail Direction Change",
      "UT Trail with Schaff Cycle Value Turn",
      "UT Cooldown with Visible Price Gaps",
      "Price Path Directional Agreement",
      "Volatility Expansion Retest",
      "VWAP Wick Rejection",
      "Dual-Horizon Momentum Agreement",
      "ATR Parabolic Direction Change",
      "Simple Moving Average Crossover",
      "RSI Extreme Reversal",
      "Bollinger Band Fade",
      "Stochastic Extreme Reversal",
      "MACD Histogram Crossover",
      "Opening Range Bracket Breakout",
      "Adaptive Relative Strength Vote",
      "Trend Cycle Directional Vote",
      "Live Bid and Ask Tick Flow",
      "Market Structure Scalp Vote",
      "Fast and Slow UT Trail Confirmation",
      "Graded UT Trail and Schaff Cycle",
      "Adaptive Multi-Indicator Confluence",
      "Gold Fifteen-Minute Two-Hundred EMA Hourly UT Bot ADX",
      "UT Bot Unified ATR Flip Engine",
      "UT Bot ATR Trailing Stop Pure Runner",
      "UT Bot Alerts Two-Hundred EMA Trend Filter",
      "UT Bot Pandich Momentum Scalper",
      "Midnight Express Session Scalper",
      "UT Bot Alerts Elite Confluence",
      "QuantNomad Trailing Stop Loss Alert Engine",
      "QuantNomad Multi-Timeframe Trailing Stop Strategy",
      "Yuthavithi Bollinger Band Scalper",
      "Pro Scalper Kalman Supertrend VWMA Zones",
      "Scalper SMA RSI MACD Entry Exit Signals",
      "MPR Supertrend Precision Entry Exit Scalper",
      "Overnight Nasdaq Synapse Confluence Scalper",
      "ATR Trail Reversal",
      "EMA Filtered ATR Reversal",
      "Hourly EMA and ADX Gold Long",
      "Asymmetric ATR Reversal",
      "Four Timeframe ATR Agreement",
      "Bollinger Expansion Scalp",
      "Kalman Supertrend and VWMA Zones",
      "Adaptive Trend and Range Router",
      "Midnight Opening Range Breakout",
      "Moving Average ATR Confirmation",
      "SMA Ribbon RSI MACD Pullback",
      "Supertrend Cloud Long",
      "Overnight Synapse Confluence",
      "UT Pivot Divergence Reversal",
      "Stateful Asymmetric ATR Trail",
      "Overnight Adaptive Trail Flip"};
   return idx>=0 && idx<SG_ENGINE_COUNT ? names[idx] : "Unknown";
}
string Value(double v,int places=2) { return DoubleToString(v,places); }
string MarketPrice(double n) { return g_consoleReady && n!=0 ? PriceText(n) : "--"; }
string Signed(double v,int n=2) { return (v>0 ? "+" : "")+DoubleToString(v,n); }
string Bias(int d) { return d>0 ? "Bullish" : d<0 ? "Bearish" : "Neutral"; }
color BiasColor(int d) { return d>0 ? SX_GREEN : d<0 ? SX_RED : SX_MUTED; }
string UiState() {
   if(g_uncertain) return "RECONCILE";
   if(g_emergency) return "EMERGENCY";
   if(g_dailyLock || g_peakLock || g_profitLock || g_weeklyLock) return "RISK LOCK";
   if(g_exitRequested || g_consolePortfolioExit) return "EXITING";
   if(!g_auto) return "PAUSED";
   if(!CanTrade()) return "ALGO OFF";
   if(!g_consoleReady) return "WARMING UP";
   return "AUTO ON";
}
void Control(string id,ENUM_OBJECT kind,int x,int y,int w,int h,string value,color fg,color bg,int font,bool strong=false,string hint="") {
   string obj=g_prefix+"ui_"+id;
   bool newObj=ObjectFind(0,obj)<0;
   if(newObj && !ObjectCreate(0,obj,kind,0,0,0)) return;
   ObjectSetInteger(0,obj,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSetInteger(0,obj,OBJPROP_XDISTANCE,g_x+Px(x)); ObjectSetInteger(0,obj,OBJPROP_YDISTANCE,g_y+Px(y+g_pageOffset));
   ObjectSetInteger(0,obj,OBJPROP_BACK,false); ObjectSetInteger(0,obj,OBJPROP_HIDDEN,true);
   ObjectSetInteger(0,obj,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,obj,OBJPROP_ZORDER,kind==OBJ_BUTTON || kind==OBJ_EDIT ? 30 : 0);
   if(kind!=OBJ_LABEL) {
      ObjectSetInteger(0,obj,OBJPROP_XSIZE,(int)MathMax(1,Px(w))); ObjectSetInteger(0,obj,OBJPROP_YSIZE,(int)MathMax(1,Px(h)));
      ObjectSetInteger(0,obj,OBJPROP_BGCOLOR,bg);
      ObjectSetInteger(0,obj,OBJPROP_BORDER_COLOR,kind==OBJ_RECTANGLE_LABEL ? bg : BlendThemeColor(bg,SX_MUTED,23));
   }
   if(kind==OBJ_RECTANGLE_LABEL) {
      ObjectSetInteger(0,obj,OBJPROP_BORDER_TYPE,BORDER_FLAT); ObjectSetInteger(0,obj,OBJPROP_COLOR,bg);
      ObjectSetString(0,obj,OBJPROP_TOOLTIP,"\n"); return;
   }
   ObjectSetInteger(0,obj,OBJPROP_COLOR,fg);
   int adjust=InpDashboardFontSize==0 ? 0 : (int)MathMax(-2,MathMin(2,InpDashboardFontSize-9));
   ObjectSetInteger(0,obj,OBJPROP_FONTSIZE,(int)MathMax(6,Px(font+adjust)));
   ObjectSetString(0,obj,OBJPROP_FONT,strong && InpDashboardFont=="Segoe UI" ? "Segoe UI Semibold" : InpDashboardFont);
   if(kind!=OBJ_EDIT || newObj) ObjectSetString(0,obj,OBJPROP_TEXT,value);
   ObjectSetString(0,obj,OBJPROP_TOOLTIP,hint=="" ? value : hint);
   if(kind==OBJ_LABEL) ObjectSetInteger(0,obj,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
   if(kind==OBJ_BUTTON) ObjectSetInteger(0,obj,OBJPROP_STATE,false);
   if(kind==OBJ_EDIT) { ObjectSetInteger(0,obj,OBJPROP_READONLY,false); ObjectSetInteger(0,obj,OBJPROP_ALIGN,ALIGN_CENTER); }
}
void Box(string id,int x,int y,int w,int h,color bg) { Control(id,OBJ_RECTANGLE_LABEL,x,y,w,h,"",bg,bg,8); }
void TextAt(string id,int x,int y,string msg,color c,int size=9,bool strong=false,string tip="") { Control(id,OBJ_LABEL,x,y,0,0,msg,c,SX_CARD,size,strong,tip); }
void Key(string id,int x,int y,int w,string msg,color fg,color bg,string tip="") { Control(id,OBJ_BUTTON,x,y,w,23,msg,fg,bg,8,false,tip); }
void Field(int index,int y,string title,string value,color c) {
   string k=IntegerToString(index);
   TextAt("rk"+k,17,y,title,SX_MUTED,9);
   TextAt("rv"+k,171,y,Cut(value,26),c,9,true,value);
   Box("rl"+k,17,y+21,320,1,SX_EDGE);
}
void Meter(string id,int x,int y,int w,double fraction,color tint) {
   Box(id+"Track",x,y,w,3,BlendThemeColor(SX_CARD,SX_MUTED,17));
   int fill=(int)MathFloor(w*MathMax(0,MathMin(1,fraction)));
   if(fill>0) Box(id+"Fill",x,y,fill,3,tint); else ObjectDelete(0,g_prefix+"ui_"+id+"Fill");
}
void ScoreTile(string id,int x,string label,int value,color tint) {
   Box(id+"Block",x,201,155,64,SX_CARD);
   TextAt(id+"Key",x+10,206,label,SX_MUTED,8);
   TextAt(id+"Value",x+10,220,g_consoleReady ? IntegerToString(value) : "--",tint,17,true);
   TextAt(id+"Unit",x+70,229,"/ 100",SX_MUTED,8);
   Meter(id,x+10,255,135,g_consoleReady ? value/100.0 : 0,tint);
}
void PageTitle(string title,string context) {
   TextAt("heading",16,146,title,SX_TEXT,15,true);
   TextAt("context",226,153,Cut(context,18),SX_GOLD,8,false,context);
}
void ClearUI() { ObjectsDeleteAll(0,g_prefix+"ui_"); }
void Pages(int y,int page,int count) {
   Key("prev",17,y,78,"Previous",SX_MUTED,SX_CARD);
   TextAt("page",122,y+3,"Page "+IntegerToString(page+1)+" of "+IntegerToString((int)MathMax(1,count)),SX_MUTED,8);
   Key("next",258,y,79,"Next",SX_TEXT,SX_CARD);
}
void DrawTradeTicket() {
   TextAt("ticketTitle",17,73,"Quick orders",SX_TEXT,13,true);
   TextAt("ticketSymbol",17,94,Cut(g_chartSymbol,25),SX_BLUE,8,true,g_chartSymbol);
   TextAt("lotLabel",220,82,"LOTS",SX_MUTED,8,true);
   Control("lots",OBJ_EDIT,259,76,78,26,LotText(g_manualLots),SX_TEXT,SX_CARD,10,false,"Manual order volume on "+g_chartSymbol);
   color buyTint=BlendThemeColor(SX_CARD,SX_GREEN,10),sellTint=BlendThemeColor(SX_CARD,SX_RED,10);
   Control("buy",OBJ_BUTTON,17,111,101,27,"BUY",SX_BG,SX_GREEN,10,true,"Buy at market on "+g_chartSymbol);
   Control("buylimit",OBJ_BUTTON,125,111,101,27,"BUY LIMIT",SX_GREEN,buyTint,9,true,"Place a buy limit below the current ask");
   Control("buystop",OBJ_BUTTON,233,111,104,27,"BUY STOP",SX_GREEN,buyTint,9,true,"Place a buy stop above the current ask");
   Control("sell",OBJ_BUTTON,17,144,101,27,"SELL",SX_BG,SX_RED,10,true,"Sell at market on "+g_chartSymbol);
   Control("selllimit",OBJ_BUTTON,125,144,101,27,"SELL LIMIT",SX_RED,sellTint,9,true,"Place a sell limit above the current bid");
   Control("sellstop",OBJ_BUTTON,233,144,104,27,"SELL STOP",SX_RED,sellTint,9,true,"Place a sell stop below the current bid");
   Control("be",OBJ_BUTTON,17,180,209,28,"POSITIVE BE NOW",SX_BG,SX_GOLD,10,true,"Apply a positive stop to eligible EA positions on "+g_chartSymbol);
   Control("beAuto",OBJ_BUTTON,233,180,104,28,"Auto BE  "+Yes(g_breakEven),g_breakEven ? SX_BLUE : SX_MUTED,SX_CARD,8,true,"Toggle automatic breakeven");
   Box("ticketRule",16,218,322,1,SX_EDGE);
}
void LegacyPaintPanel() {
   int cw=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0),ch=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
   if(cw<1 || ch<1) return;
   bool tiny=cw<170 || ch<140 || (g_tab>=10 && (cw<268 || ch<248));
   bool folded=g_collapsed || tiny;
   bool compact=!folded && (cw<262 || ch<475);
   int layout=folded ? 0 : compact ? 1 : 2;
   int height=folded ? 68 : compact ? 264 : 660;
   double sizeScales[5]={0.74,0.88,1.0,1.15,1.3};
   double wanted=sizeScales[g_size]*(g_xeMainScalePct/100.0);
   g_consoleScale=MathMax(0.10,MathMin(wanted,MathMin((cw-6)/354.0,(ch-6)/(double)height)));
   g_pageOffset=0;
   g_width=Px(354); g_xeMainW=g_width; g_xeMainH=Px(height); g_xeMainHeadH=Px(64);
   if(g_xeMainCustomPos) { g_x=(int)MathMax(4,MathMin(g_xeMainX,MathMax(4,cw-g_width-4))); g_y=(int)MathMax(4,MathMin(g_xeMainY,MathMax(4,ch-Px(height)-4))); }
   else { g_x=g_right ? (int)MathMax(0,cw-g_width-InpPanelX) : (int)MathMin(InpPanelX,MathMax(0,cw-g_width)); g_y=(int)MathMax(0,MathMin(InpPanelY,ch-Px(height)-2)); }
   ChartEmblem(cw,ch,g_width,folded);
   if(!ConsoleShowDashboard) { PaintIndicatorStrip(); return; }
   if(layout!=g_lastLayout) {ClearUI(); g_lastLayout=layout;}
   Box("frame",0,0,354,height,SX_EDGE);
   Box("back",1,1,352,height-2,SX_BG);
   Box("mast",1,1,352,64,SX_CARD);
   Box("mastRule",2,64,350,1,BlendThemeColor(SX_CARD,SX_GOLD,40));
   if(InpShowPanelEmblem) GemObject("ui_emblem","GemHeader",g_x+Px(12),g_y+Px(8),Px(50),(int)MathRound(2.55*InpLogoHeaderOpacity),false);
   int titleX=InpShowPanelEmblem ? 70 : 16;
   TextAt("maker",titleX,8,"FLOWNEXUSFORGE",SX_GOLD,8,true);
   TextAt("brand",titleX,23,SG_BRAND,LogoInk(9),12,true);
   if(!folded) Key("tab10",235,38,72,"Dashboard",SX_GOLD,SX_CARD);
   Key("msdec",260,17,18,"-",SX_TEXT,SX_BG,"Shrink Main Dashboard (-5%)"); Key("msinc",280,17,18,"+",SX_TEXT,SX_BG,"Enlarge Main Dashboard (+5%)"); Key("mrst",300,17,18,"R",SX_GOLD,SX_BG,"Reset all dashboard positions & sizes");
   Key("collapse",320,17,22,folded ? "+" : "_",SX_MUTED,SX_CARD,tiny ? "Enlarge chart to display all controls" : "Collapse or expand dashboard");
   if(folded) { PaintIndicatorStrip(); ChartRedraw(); return; }
   DrawTradeTicket();
   if(compact) {
      TextAt("statusTitle",17,225,"LATEST EVENT",SX_GOLD,8,true);
      TextAt("notice",17,242,Cut(g_message,46),SX_MUTED,8,false,g_message);
      PaintIndicatorStrip(); ChartRedraw(); return;
   }
   g_pageOffset=150;
   string nav[10]={"Market","Signals","Scanner","Orders","Risk","Protect","Engines","Journal","Theme","Context"};
   for(int i=0;i<10;i++) {
      bool first=i<5; int col=first ? i : i-5,step=65;
      int x=16+col*step, y=first ? 76 : 105;
      Key("tab"+IntegerToString(i),x,y,step-3,nav[i],i==g_tab ? SX_TEXT : SX_MUTED,i==g_tab ? BlendThemeColor(SX_CARD,SX_GOLD,15) : SX_CARD);
      if(i==g_tab) Box("navLine",x+3,y+20,step-9,2,SX_GOLD);
   }
   MqlTick q; bool quoted=Tick(q); string ccy=AccountInfoString(ACCOUNT_CURRENCY);
   string symbol=Cut(g_chartSymbol,17),tf=ConsoleTFName(g_tf);
   int owned=ArraySize(g_positions),working=WorkingOrders();
   if(g_tab==0) {
      PageTitle("Market overview",tf+"  /  "+symbol);
      TextAt("regime",17,179,g_consoleReady ? EngineTitle((int)g_consoleStrategy)+"   /   "+Bias(g_candidate) : "Loading broker history",SX_MUTED,9);
      ScoreTile("bull",16,"BUY CONFLUENCE",g_scoreBuy,SX_GREEN); ScoreTile("bear",182,"SELL CONFLUENCE",g_scoreSell,SX_RED);
      Field(0,278,"Bid / ask",quoted ? PriceText(q.bid)+" / "+PriceText(q.ask) : "--",SX_TEXT);
      Field(1,305,"Spread / ATR",quoted && g_atr>0 ? Value((q.ask-q.bid)/g_consolePoint,1)+" pts / "+Value(100*(q.ask-q.bid)/g_atr,1)+"%" : "--",SX_BLUE);
      Field(2,332,"Account equity",Value(ConsoleEquity())+" "+ccy,SX_TEXT);
      Field(3,359,"Chart floating P/L",Signed(Floating())+" "+ccy,Floating()<0 ? SX_RED : SX_GREEN);
      Field(4,386,"Tick flow",FlowTickText(),FlowTickColor());
   } else if(g_tab==1 && g_consoleStrategy==FAST_SLOW_UT) {
      PageTitle("ATR confirmation",tf+" / "+symbol);
      Field(0,183,"Main / slow ATR",Bias(g_gem.primaryUT)+" / "+Bias(g_gem.secondaryUT),SX_TEXT);
      Field(1,210,"Last reversal",g_gem.utLastSide==0 ? "--" : Side(g_gem.utLastSide)+(g_gem.utStrong ? " strong" : " regular"),SX_GOLD);
      Field(3,264,"Move since reversal",g_gem.utLastAge>=0 ? Signed(g_gem.utLastMove)+"%" : "--",SX_TEXT);
      Field(4,291,"Distance to ATR trail",Value(g_gem.utDistance)+"%",SX_BLUE);
      Field(5,318,"H1 closed trend",Bias(g_gem.utH1),BiasColor(g_gem.utH1));
      Field(6,345,"H4 closed trend",Bias(g_gem.utH4),BiasColor(g_gem.utH4));
      Field(7,372,"D1 closed trend",Bias(g_gem.utD1),BiasColor(g_gem.utD1));
   } else if(g_tab==1) {
      PageTitle("Signal matrix",tf+"  /  "+symbol);
      Field(0,183,"EMA fast / slow",MarketPrice(g_cachedFast)+" / "+MarketPrice(g_cachedSlow),SX_TEXT);
      Field(1,210,"RSI / ADX",g_consoleReady ? Value(g_rsi,1)+" / "+Value(g_adx,1) : "--",SX_TEXT);
      Field(2,237,"MACD histogram",MarketPrice(g_macd),BiasColor(g_macd>0 ? 1 : g_macd<0 ? -1 : 0));
      Field(3,264,"ATR / MFI",MarketPrice(g_atr)+" / "+(g_consoleReady ? Value(g_mfi,1) : "--"),SX_BLUE);
      Field(5,318,"SuperTrend / STC",g_consoleReady ? Bias(g_superDir)+" / "+Value(g_stc,1) : "--",BiasColor(g_superDir));
      Field(6,345,"Stochastic / CCI",g_consoleReady ? Value(g_stoch,1)+" / "+Value(g_cci,1) : "--",SX_TEXT);
      Field(7,372,"H1 / H4 trend",Bias(g_mtf[3])+" / "+Bias(g_mtf[4]),SX_GOLD);
   } else if(g_tab==2) {
      int total=ArraySize(g_assets),count=(total+5)/6;
      if(g_scanPage>=count) g_scanPage=0;
      PageTitle("Asset scanner",IntegerToString(total)+" symbols");
      Key("assets",17,180,154,ScopeName(),SX_GOLD,SX_CARD,"Change entry universe and pause automatic entries");
      TextAt("scanHead",181,184,"SIGNAL / STATUS",SX_MUTED,8);
      for(int j=0;j<6;j++) {
         int i=g_scanPage*6+j;
         string left="--",right=""; color t=SX_MUTED;
         if(i<total) {
            SXAssetState a=g_assets[i]; left=a.symbol; right=!a.enabled ? "Manage only" : a.uncertain ? "Reconcile" : !a.ready ? "Loading history" : Bias(a.candidate);
            if(a.ready && a.enabled && !a.uncertain) right+="  "+IntegerToString(a.scoreBuy)+"/"+IntegerToString(a.scoreSell);
            t=a.uncertain ? SX_RED : a.ready ? BiasColor(a.candidate) : SX_MUTED;
            TextAt("scanTip"+IntegerToString(j),17,212+27*j,Cut(left,20),SX_TEXT,9,true,a.note);
            TextAt("scanVal"+IntegerToString(j),171,212+27*j,Cut(right,22),t,9,false,a.note);
         } else {
            TextAt("scanTip"+IntegerToString(j),17,212+27*j,"--",SX_MUTED,9);
            TextAt("scanVal"+IntegerToString(j),171,212+27*j," ",SX_MUTED,9);
         }
         Box("scanRule"+IntegerToString(j),17,233+27*j,320,1,SX_EDGE);
      }
      Pages(385,g_scanPage,count);
   } else if(g_tab==3) {
      PageTitle("Order desk",symbol);
      Field(0,183,"Open / pending",IntegerToString(owned)+" / "+IntegerToString(working),SX_BLUE);
      Field(1,211,"Lot minimum / step",Value(SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN),3)+" / "+Value(SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_STEP),3),SX_TEXT);
      Field(2,239,"Pending offset",Value(InpPendingOffsetATR)+" ATR",SX_TEXT);
      Field(3,267,"Owned chart P/L",Signed(Floating())+" "+ccy,SX_TEXT);
      TextAt("management",17,315,"POSITION CONTROLS",SX_GOLD,8,true);
      Key("partial",17,346,101,"Close 50%",SX_BLUE,SX_CARD); Key("cancel",125,346,104,"Cancel pending",SX_GOLD,SX_CARD);
      Key("close",236,346,101,"Close symbol",SX_RED,SX_CARD);
      Key("portfolio",17,381,154,"Exit portfolio",SX_RED,SX_CARD); Key("reconcile",182,381,155,"Reconcile symbol",SX_GOLD,SX_CARD);
   } else if(g_tab==4) {
      PageTitle("Risk controls",ccy);
      Field(0,180,"Automatic sizing",InpUseRiskLot ? Value(ConsoleRiskPercent,2)+"% of risk base" : Value(InpFixedLots,3)+" lots",SX_TEXT);
      Field(1,207,"Daily loss / limit",Value(g_dayLoss)+"% / "+Value(InpDailyLossPercent)+"%",g_dailyLock ? SX_RED : SX_TEXT);
      Field(2,234,"Peak DD / limit",Value(g_drawdown)+"% / "+Value(InpMaxDrawdownPercent)+"%",g_peakLock ? SX_RED : SX_TEXT);
      Field(3,261,"Owned stop risk",Value(PortfolioRiskMoney())+" "+ccy,SX_BLUE);
      Field(4,288,"Week loss / limit",Value(g_weekLoss)+"% / "+Value(InpWeeklyLossPercent)+"%",g_weeklyLock ? SX_RED : SX_TEXT);
      Key("nolocks",17,327,154,"No locks  "+Yes(BroadLocks()),BroadLocks() ? SX_RED : SX_MUTED,SX_CARD,"Bypass daily loss, peak drawdown and profit-target locks");
      Key("norestrict",182,327,155,"No restrictions  "+Yes(BroadRestrictions()),BroadRestrictions() ? SX_RED : SX_MUTED,SX_CARD,"Bypass optional entry filters, caps, sessions and cooldowns");
      Key("guard",17,361,154,"Rebase equity",SX_GOLD,SX_CARD);
      TextAt("guardText",17,393,g_emergency ? "EMERGENCY LOCK - reattach with reset to clear" : AnyUnlock() ? "Override active" : "Day / week / DD  "+FlowGuardText(),g_emergency || AnyUnlock() ? SX_RED : SX_GREEN,9,true);
   } else if(g_tab==5) {
      PageTitle("Stop protection","BREAK-EVEN / SL");
      Field(0,180,"Initial stop",InpFixedStopPoints>0 ? IntegerToString(InpFixedStopPoints)+" points" : Value(InpInitialSL_ATR)+" ATR",SX_TEXT);
      Field(1,207,"Take profit",InpFixedTargetPoints>0 ? IntegerToString(InpFixedTargetPoints)+" points" : InpUseFixedTP ? Value(InpFixedTP_R)+" R" : "Trail exits",SX_TEXT);
      TextAt("bet",17,235,"BE trigger / lock (ATR)",SX_MUTED,9);
      Control("beTrigger",OBJ_EDIT,173,231,76,23,Value(g_beTrigger),SX_TEXT,SX_CARD,9,false,"Breakeven trigger in entry ATR");
      Control("beLock",OBJ_EDIT,260,231,77,23,Value(g_beLock),SX_TEXT,SX_CARD,9,false,"Profit locked in entry ATR");
      TextAt("minLock",17,262,"Minimum lock (ticks)",SX_MUTED,9);
      Control("lockTicks",OBJ_EDIT,173,258,76,23,IntegerToString(g_lockTicks),SX_GOLD,SX_CARD,9,false,"Minimum tradable ticks beyond entry plus costs");
      TextAt("plusCost",260,262,"+ costs",SX_MUTED,9);
      if(InpTrailStartPoints>0) Field(4,288,"Trail start / gap",IntegerToString(InpTrailStartPoints)+" / "+IntegerToString(InpTrailGapPoints)+" pts",SX_TEXT);
      else {
         TextAt("trt",17,289,"Trail start / gap (ATR)",SX_MUTED,9);
         Control("trStart",OBJ_EDIT,173,285,76,23,Value(g_trStart),SX_TEXT,SX_CARD,9,false,"Start trailing after this many entry ATR");
         Control("trGap",OBJ_EDIT,260,285,77,23,Value(g_trGap),SX_TEXT,SX_CARD,9,false,"Base trailing distance in current ATR");
      }
      Key("strict",17,322,154,"Positive only  "+Yes(g_positiveOnly),g_positiveOnly ? SX_GREEN : SX_MUTED,SX_CARD);
      Key("tmode",182,322,155,TrailDisplay(),SX_GOLD,SX_CARD,EnumToString((SXTrailMode)g_trailMode));
      Field(5,355,"Spread cushion",InpExtraSpreadCushion ? "Included" : "Off",SX_TEXT);
      TextAt("trailStep",17,391,InpTrailStartPoints>0 ? "Trailing step (points)" : "Trailing step (ATR)",SX_MUTED,9);
      if(InpTrailStartPoints>0) TextAt("ptStep",173,391,IntegerToString(InpTrailStepPoints),SX_TEXT,9);
      else Control("trStep",OBJ_EDIT,173,387,76,23,Value(g_trStep),SX_TEXT,SX_CARD,9,false,"Minimum incremental improvement in ATR");
   } else if(g_tab==6) {
      PageTitle("Signal engines",IntegerToString(SG_ENGINE_COUNT)+" ENGINES");
      for(int j=0;j<6;j++) {
         int e=g_enginePage*6+j; if(e>=SG_ENGINE_COUNT) break;
         string key=IntegerToString(e);
         bool selected=e==(int)g_consoleStrategy;
         Key("engine"+key,17,184+j*31,207,EngineTitle(e),selected ? SX_GOLD : SX_TEXT,selected ? BlendThemeColor(SX_CARD,SX_GOLD,9) : SX_CARD);
         TextAt("vote"+key,241,188+j*31,e>=DROID_ADAPTIVE_CONFLUENCE && !selected ? "Select to load" : g_consoleReady ? Bias(g_engineSignals[e]) : "--",BiasColor(g_engineSignals[e]),9);
      }
      Pages(383,g_enginePage,(SG_ENGINE_COUNT+5)/6);
   } else if(g_tab==7) {
      PageTitle("Event journal","BROKER TIME");
      int y=185;
      for(int j=0;j<8;j++) {
         string line=g_log[j]; TextAt("log"+IntegerToString(j),17,y,Cut(line=="" ? "--" : line,48),j==0 ? SX_GOLD : SX_MUTED,8,false,line);
         Box("logRule"+IntegerToString(j),17,y+20,320,1,SX_EDGE); y+=27;
      }
   } else if(g_tab==8) {
      PageTitle("Appearance",g_consoleTheme==THEME_CUSTOM ? "CUSTOM" : IntegerToString(PaletteSlot(g_consoleTheme)+1)+" / "+IntegerToString(SG_PALETTE_COUNT));
      Box("swatch",16,183,322,53,SX_CARD);
      TextAt("themeName",27,189,ConsoleThemeName(g_consoleTheme),SX_GOLD,12,true);
      TextAt("styleName",27,213,StyleName(g_themeStyle),SX_MUTED,8);
      Box("chip1",268,200,15,15,SX_GOLD); Box("chip2",289,200,15,15,SX_BLUE); Box("chip3",310,200,15,15,SX_GREEN);
      Key("familyPrev",17,251,74,"< Family",SX_TEXT,SX_CARD); Key("familyNext",95,251,76,"Family >",SX_TEXT,SX_CARD);
      Key("themePrev",182,251,74,"< Tone",SX_TEXT,SX_CARD); Key("theme",260,251,77,"Tone >",SX_TEXT,SX_CARD);
      Key("tstyle",17,287,154,"Style  "+StyleName(g_themeStyle),SX_BLUE,SX_CARD);
      Key("water",182,287,155,"Chart emblem  "+Yes(g_watermark),SX_BLUE,SX_CARD);
      Key("anchor",17,323,154,g_right ? "Dock left" : "Dock right",SX_MUTED,SX_CARD);
      Key("size",182,323,155,"Size  "+SizeName(g_size),SX_MUTED,SX_CARD);
      Key("overlays",17,360,154,"Chart layers  "+Yes(g_layers),SX_GOLD,SX_CARD);
      Key("strip",182,360,155,"Indicator strip  "+Yes(g_strip),SX_GOLD,SX_CARD);
      Key("logoMode",136,218,201,g_logoMode==LOGO_THEME ? "Logo: follow theme" : g_logoMode==LOGO_CUSTOM ? "Logo: custom RGB" : "Logo: accent palette",SX_TEXT,SX_CARD);
      Key("mainGem",17,391,154,"Primary  "+StoneName(g_primaryGem),SX_BLUE,SX_CARD);
      Key("accentGem",182,391,155,"Accent  "+StoneName(g_accentGem),SX_GOLD,SX_CARD);
   } else {
      PageTitle("Entry context",tf+" / "+symbol);
      string regime=g_gem.contextMode==0 ? "Range" : g_gem.contextMode==1 ? "Trend" : "Expansion";
      Field(0,183,"Market regime",g_consoleReady ? regime : "--",SX_GOLD);
      Field(1,210,"Family votes (net)",g_consoleReady ? Signed(g_gem.contextVotes,0)+" / 3" : "--",SX_TEXT);
      Field(2,237,"Recent TR / median",g_gem.shockReady ? Value(g_gem.largestShock)+"x" : "Warming up",SX_BLUE);
      Field(3,264,"Auto shock gate",!InpUseShockPause ? "Off" : BroadRestrictions() ? "Bypassed" : !g_gem.shockReady ? "Warming up" : g_gem.largestShock>=InpShockMultiple ? "Paused" : "Clear",SX_TEXT);
      Field(4,291,"Buy signal filters",g_consoleReady ? g_gem.buyFilter : "--",SX_TEXT);
      Field(5,318,"Sell signal filters",g_consoleReady ? g_gem.sellFilter : "--",SX_TEXT);
      Field(6,345,"Entry cost limit",!InpUseCostGate ? "Off" : BroadRestrictions() ? "Bypassed" : Value(InpMaxCostPctOfTarget,1)+"% of target / 1R",SX_TEXT);
      Key("regOverlay",17,383,154,"Regression  "+Yes(g_regOverlay),SX_BLUE,SX_CARD);
      TextAt("matrixVotes",181,388,g_consoleReady ? "Engines "+IntegerToString(g_gem.positiveVotes)+" up / "+IntegerToString(g_gem.negativeVotes)+" down" : "--",SX_MUTED,8);
   }
   Box("deskRule",16,418,322,1,SX_EDGE);
   Key("auto",17,432,100,UiState(),g_auto && CanTrade() && !g_dailyLock && !g_peakLock && !g_uncertain ? SX_GREEN : SX_GOLD,SX_CARD,"Toggle automated new entries");
   Key("trail",125,432,102,"Trail  "+Yes(g_trailing),g_trailing ? SX_BLUE : SX_MUTED,SX_CARD);
   Key("jump",235,432,102,g_tab==3 ? "Overview" : "Order desk",SX_TEXT,SX_CARD);
   TextAt("statusTitle",17,468,AnyUnlock() ? "OVERRIDE ACTIVE" : "LATEST EVENT",AnyUnlock() ? SX_RED : SX_GOLD,8,true);
   TextAt("notice",17,485,Cut(g_message,46),SX_MUTED,8,false,g_message);
   g_pageOffset=0;
   PaintIndicatorStrip(); ChartRedraw();
}
string ClockLabel(int i) {
   string labels[9]={"Trend matrix","RSI momentum","MACD momentum","SuperTrend","Candle flow proxy","Session VWAP","Schaff cycle","Kalman trend","UT ATR bias"};
   return labels[i];
}
void ClockCard(string id,int x,int y,int w,string label,string val,color tint) {
   Box(id+"edge",x,y,w,54,SX_EDGE); Box(id+"bg",x+1,y+1,w-2,52,SX_CARD);
   TextAt(id+"label",x+9,y+6,label,SX_MUTED,9,true); TextAt(id+"value",x+9,y+23,val,tint,16,true);
}
string StudyName(int i) {
   string labels[8]={"EMA spread","RSI","MACD histogram","Money Flow Index","Session VWAP","SuperTrend","Schaff Trend Cycle","UT ATR trail"};
   return labels[i];
}
string StudyRule(int i) {
   string rules[8]={"Fast minus slow","Midline 50","Zero line","Midline 50","Close vs. VWAP","Trend direction","Midline 50","Close vs. trail"};
   return rules[i];
}
bool StudyAvailable(int i) {
   if(!g_consoleReady) return false;
   if(i==5) return g_superLine>0 && g_superDir!=0;
   if(i==7) return g_utCurrent>0;
   return true;
}
int StudySide(int i) {
   if(!StudyAvailable(i)) return 0;
   if(i==3) return Direction(g_mfi-50);
   int clock[8]={0,1,2,0,5,3,6,8};
   return ClockVote(clock[i]);
}
string StudyReading(int i) {
   if(!StudyAvailable(i)) return "--";
   switch(i) {
      case 0: return Signed(g_cachedFast-g_cachedSlow,g_consoleDigits);
      case 1: return Value(g_rsi,1);
      case 2: return Signed(g_macd,g_consoleDigits);
      case 3: return Value(g_mfi,1);
      case 4: return PriceText(g_vwap);
      case 5: return PriceText(g_superLine);
      case 6: return Value(g_stc,1);
   }
   return PriceText(g_utCurrent);
}
void StudyTally(int &up,int &down,int &flat,int &ready) {
   up=0; down=0; flat=0; ready=0;
   for(int i=0;i<8;i++) {
      if(!StudyAvailable(i)) continue;
      ready++;
      int d=StudySide(i);
      if(d>0) up++; else if(d<0) down++; else flat++;
   }
}
void DashboardMetric(string key,int x,int y,int w,string label,string reading,color tint) {
   Box(key+"bg",x,y,w,68,SX_CARD);
   TextAt(key+"label",x+9,y+8,label,SX_MUTED,8,true);
   TextAt(key+"read",x+9,y+28,reading,tint,15,true);
}
void PaintOverview(int w,bool narrow) {
   int up,down,flat,ready; StudyTally(up,down,flat,ready);
   int textX=20,heroY=134,inner=w-40;
   TextAt("view",textX,94,"Market overview",SX_TEXT,20,true);
   Box("hero",textX,heroY,inner,107,SX_CARD);
   TextAt("mixTitle",textX+12,heroY+9,"INDICATOR AGREEMENT",SX_MUTED,8,true);
   string tilt=ready==0 ? "Awaiting data" : up>down ? "Bullish tilt" : down>up ? "Bearish tilt" : "Balanced";
   color tint=ready>0 ? BiasColor(Direction(up-down)) : SX_MUTED;
   TextAt("tilt",textX+12,heroY+27,tilt,tint,19,true);
   TextAt("coverage",w-(narrow ? 98 : 115),heroY+12,IntegerToString(ready)+" / 8 ready",SX_TEXT,9,true);
   int track=inner-24,xx=textX+12,used=0;
   int counts[4]; counts[0]=up; counts[1]=down; counts[2]=flat; counts[3]=8-ready;
   color inks[4]; inks[0]=SX_GREEN; inks[1]=SX_RED; inks[2]=SX_MUTED; inks[3]=SX_EDGE;
   for(int k=0;k<4;k++) {
      int end=(used+counts[k])*track/8;
      if(counts[k]>0) Box("mix"+IntegerToString(k),xx+used*track/8,heroY+65,end-used*track/8,6,inks[k]);
      else ObjectDelete(0,g_prefix+"ui_mix"+IntegerToString(k));
      used+=counts[k];
   }
   TextAt("counts",textX+12,heroY+80,IntegerToString(up)+" bullish     "+IntegerToString(down)+" bearish     "+IntegerToString(flat)+" neutral",SX_TEXT,9);
   int tile=(inner-12)/3;
   DashboardMetric("rsi",20,254,tile,"RSI",StudyReading(1),BiasColor(StudySide(1)));
   DashboardMetric("adx",26+tile,254,tile,"ADX",g_consoleReady ? Value(g_adx,1) : "--",SX_TEXT);
   DashboardMetric("atr",32+2*tile,254,inner-2*tile-12,"ATR / MEAN",g_consoleReady && g_atrRatio>0 ? Value(g_atrRatio,2)+"x" : "--",SX_BLUE);
   TextAt("engineLabel",20,341,"ENTRY ENGINE",SX_MUTED,8,true);
   TextAt("engineName",20,361,EngineTitle((int)g_consoleStrategy),SX_TEXT,narrow ? 8 : 11,true);
   if(g_consoleStrategy>=DROID_ADAPTIVE_CONFLUENCE && g_consoleStrategy<DR_UT) TextAt("droidContext",20,389,DroidSmartRegimeLabel(),SX_BLUE,8);
   else if(g_consoleStrategy>=DR_UT) TextAt("droidContext",20,389,g_gem.droidState,SX_BLUE,8);
   else ObjectDelete(0,g_prefix+"ui_droidContext");
   int statusX=narrow ? 235 : 385;
   TextAt("stateLabel",statusX,341,"EA STATE",SX_MUTED,8,true);
   TextAt("stateValue",statusX,361,UiState(),SX_GOLD,12,true);
}
void PaintStudyBoard(int w,bool narrow) {
   TextAt("view",20,94,"Indicator board",SX_TEXT,20,true);
   int readX=narrow ? 163 : 220,sideX=narrow ? 276 : 481;
   Box("thead",20,135,w-40,24,SX_CARD);
   TextAt("thStudy",28,139,"INDICATOR",SX_MUTED,8,true);
   TextAt("thReading",readX,139,"READING",SX_MUTED,8,true);
   if(!narrow) TextAt("thRule",351,139,"BASIS",SX_MUTED,8,true);
   TextAt("thSide",sideX,139,"BIAS",SX_MUTED,8,true);
   for(int i=0;i<8;i++) {
      string k=IntegerToString(i); int y=165+28*i;
      bool ok=StudyAvailable(i); int side=StudySide(i);
      TextAt("name"+k,28,y,StudyName(i),SX_TEXT,9,true,StudyRule(i));
      TextAt("read"+k,readX,y,StudyReading(i),SX_TEXT,10,true);
      if(!narrow) TextAt("basis"+k,351,y,StudyRule(i),SX_MUTED,9);
      TextAt("vote"+k,sideX,y,ok ? Bias(side) : "Pending",ok ? BiasColor(side) : SX_MUTED,9,true);
      Box("rule"+k,20,y+21,w-40,1,SX_EDGE);
   }
}
void PaintLogoStudio(int w,bool narrow) {
   TextAt("view",20,94,"Logo studio",SX_TEXT,20,true);
   int left=20,swatches=narrow ? 151 : 251,cell=(w-20-swatches-6)/2,sz=narrow ? 84 : 122;
   for(int i=0;i<10;i++) {
      int x=swatches+(i%2)*(cell+6),y=138+(i/2)*37;
      string k=IntegerToString(i);
      Control("part"+k,OBJ_BUTTON,x,y,cell,30,LogoPartName(i),i==g_logoPart ? SX_GOLD : SX_TEXT,SX_CARD,8,i==g_logoPart);
      Box("chip"+k,x+2,y+2,4,26,LogoInk(i));
   }
   TextAt("hexLabel",20,331,LogoPartName(g_logoPart)+"   /   RGB HEX",SX_MUTED,8,true);
   Control("logoHex",OBJ_EDIT,20,350,narrow ? 105 : 126,26,LogoHex(LogoInk(g_logoPart)),SX_TEXT,SX_CARD,10,true,"Type #RRGGBB and press Enter");
   Key("logoMode",narrow ? 134 : 160,351,narrow ? 106 : 138,LogoModeName(),SX_BLUE,SX_CARD,"Cycle theme, custom RGB and accent palette");
   Key("logoReset",w-(narrow ? 129 : 158),351,narrow ? 109 : 138,"Reload inputs",SX_MUTED,SX_CARD);
   TextAt("studioNote",20,386,g_logoNote,SX_MUTED,8);
}
void PaintGemDashboard(int cw,int ch) {
   bool narrow=cw<770;
   int w=narrow ? 390 : 620,h=444;
   double sizes[5]={0.74,0.88,1.0,1.15,1.30};
   g_consoleScale=MathMax(0.45,MathMin(sizes[g_size]*(g_xeMainScalePct/100.0),MathMin((cw-6.0)/w,(ch-6.0)/h)));
   g_width=Px(w); g_pageOffset=0; g_xeMainW=g_width; g_xeMainH=Px(h); g_xeMainHeadH=Px(46);
   if(g_xeMainCustomPos) { g_x=(int)MathMax(4,MathMin(g_xeMainX,MathMax(4,cw-g_width-4))); g_y=(int)MathMax(4,MathMin(g_xeMainY,MathMax(4,ch-Px(h)-4))); }
   else { g_x=g_right ? (int)MathMax(0,cw-g_width-InpPanelX) : (int)MathMin(InpPanelX,MathMax(0,cw-g_width)); g_y=(int)MathMax(0,MathMin(InpPanelY,ch-Px(h)-2)); }
   int layout=20+2*(g_tab-10)+(narrow ? 1 : 0);
   if(g_lastLayout!=layout) { ClearUI(); g_lastLayout=layout; }
   Box("frame",0,0,w,h,SX_EDGE); Box("surface",1,1,w-2,h-2,SX_BG);
   Box("mast",1,1,w-2,46,SX_CARD);
   if(InpShowPanelEmblem) GemObject("ui_emblem","GemHeader",g_x+Px(12),g_y+Px(4),Px(39),(int)MathRound(2.55*InpLogoHeaderOpacity),false);
   TextAt("brand",InpShowPanelEmblem ? 58 : 16,13,SG_BRAND,LogoInk(9),narrow ? 11 : 13,true);
   TextAt("instrument",w-(narrow ? 124 : 175),16,Cut(g_chartSymbol,narrow ? 8 : 14)+" / "+ConsoleTFName(g_tf),SX_MUTED,8,true);
   Key("msdec",w-95,11,20,"-",SX_TEXT,SX_BG,"Shrink Main Dashboard (-5%)"); Key("msinc",w-73,11,20,"+",SX_TEXT,SX_BG,"Enlarge Main Dashboard (+5%)"); Key("mrst",w-51,11,20,"R",SX_GOLD,SX_BG,"Reset all dashboard positions & sizes"); Key("collapse",w-29,11,20,"_",SX_MUTED,SX_CARD);
   string labels[4]={"Overview","Indicators","Logo studio","Order desk"};
   int tabs[4]={10,11,12,3},step=(w-36)/4;
   for(int i=0;i<4;i++) {
      int x=18+step*i;
      Key("tab"+IntegerToString(tabs[i]),x,57,step-4,labels[i],g_tab==tabs[i] ? SX_GOLD : SX_MUTED,SX_CARD);
      if(g_tab==tabs[i]) Box("active",x,80,step-4,2,SX_GOLD);
   }
   if(g_tab==10) PaintOverview(w,narrow);
   else if(g_tab==11) PaintStudyBoard(w,narrow);
   else PaintLogoStudio(w,narrow);
   Box("footRule",20,408,w-40,1,SX_EDGE);
   string footer="CVT LT DRIOD BOT NO ERRORS | LICENSED BY FLOWNEXUSFORGE";
   TextAt("footer",20,419,footer,SX_MUTED,8);
   if(g_tab!=12) TextAt("context",w-(narrow ? 134 : 151),419,"Chart symbol only",SX_MUTED,8);
   ChartEmblem(cw,ch,g_width,false); PaintIndicatorStrip(); ChartRedraw();
}

void PaintPanel() {
   int cw=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0),ch=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
   if(ConsoleShowDashboard && g_tab>=10 && !g_collapsed && cw>=268 && ch>=248) { PaintGemDashboard(cw,ch); return; }
   if(!InpClockWideDashboard || g_tab>1 || g_collapsed || cw<730 || ch<400 || !ConsoleShowDashboard) { LegacyPaintPanel(); return; }
   int w=700,h=570;
   double sizes[5]={0.70,0.85,1.0,1.15,1.30};
   g_consoleScale=MathMax(0.45,MathMin(sizes[g_size]*(g_xeMainScalePct/100.0),MathMin((cw*0.75)/w,(ch-12.0)/h)));
   g_pageOffset=0; g_width=Px(w); g_xeMainW=g_width; g_xeMainH=Px(h); g_xeMainHeadH=Px(28);
   if(g_xeMainCustomPos) { g_x=(int)MathMax(4,MathMin(g_xeMainX,MathMax(4,cw-g_width-4))); g_y=(int)MathMax(4,MathMin(g_xeMainY,MathMax(4,ch-Px(h)-4))); }
   else { g_x=g_right ? (int)MathMax(0,cw-g_width-InpPanelX) : (int)MathMin(InpPanelX,MathMax(0,cw-g_width)); g_y=(int)MathMax(0,MathMin(InpPanelY,ch-Px(h)-2)); }
   if(g_lastLayout!=3+g_tab) { ClearUI(); g_lastLayout=3+g_tab; }
   Box("frame",0,0,w,h,SX_GOLD); Box("back",1,1,w-2,h-2,SX_BG);
   Box("mast",2,2,w-4,26,SX_CARD);
#ifdef __MQL5__
   TextAt("maker",13,6,"METATRADER 5 / EXPERT ADVISOR",SX_GOLD,9,true);
#else
   TextAt("maker",13,6,"METATRADER 4 / EXPERT ADVISOR",SX_GOLD,9,true);
#endif
   Key("tab0",370,3,80,"Overview",g_tab==0 ? SX_GOLD : SX_MUTED,SX_CARD);
   Key("tab1",454,3,91,"Signal matrix",g_tab==1 ? SX_GOLD : SX_MUTED,SX_CARD);
   Key("tab2",549,3,64,"Markets",SX_MUTED,SX_CARD); Key("tab3",617,3,55,"Tools",SX_MUTED,SX_CARD);
   Key("collapse",675,3,19,"-",SX_MUTED,SX_CARD);
   if(InpShowPanelEmblem) GemObject("ui_emblem","GemHeader",g_x+Px(14),g_y+Px(33),Px(47),(int)MathRound(2.55*InpLogoHeaderOpacity),false);
   TextAt("brand",InpShowPanelEmblem ? 70 : 14,35,SG_BRAND,LogoInk(9),24,true);
   Key("tab10",250,3,103,"Dashboard",SX_GOLD,SX_CARD);
   TextAt("symbol",544,70,g_chartSymbol+" / "+ConsoleTFName(g_tf),SX_MUTED,10);
   Box("rule",14,89,672,1,SX_EDGE);
   int cb=g_consoleReady ? ClockBias() : 0, votes=cb==0 ? 0 : ClockVotes(cb);
   Box("statusCard",14,99,672,40,SX_CARD);
   TextAt("statusLabel",25,110,"STATUS",SX_MUTED,10,true); TextAt("status",103,105,UiState(),UiState()=="AUTO ON" ? SX_GREEN : SX_MUTED,16,true);
   TextAt("votes",342,108,g_consoleReady ? "ALIGNED  "+IntegerToString(votes)+" / 9  ("+IntegerToString((int)MathRound(votes*100.0/9))+"%)" : "WARMING UP",BiasColor(cb),14,true);
   TextAt("threshold",575,111,"MIN "+IntegerToString(InpClockMinVotes)+" VOTES",SX_MUTED,9,true);
   MqlTick q; bool quoted=Tick(q); double dp=g_dayEquity>0 ? 100*(ConsoleEquity()/g_dayEquity-1) : 0;
   ClockCard("p",14,147,120,"POSITIONS",IntegerToString(ArraySize(g_positions)),SX_TEXT);
   ClockCard("e",140,147,184,"EQUITY / "+AccountInfoString(ACCOUNT_CURRENCY),Value(ConsoleEquity()),SX_TEXT);
   ClockCard("d",330,147,170,"DAILY EQUITY",Signed(dp)+"%",dp<0 ? SX_RED : SX_GREEN);
   ClockCard("s",506,147,180,"SPREAD",quoted ? Value((q.ask-q.bid)/g_consolePoint,1)+" pts" : "--",SX_TEXT);
   TextAt("matrixTitle",14,210,"MULTI-SIGNAL ENGINE",SX_GOLD,15,true);
   TextAt("engine",337,214,Cut(EngineTitle((int)g_consoleStrategy),30),SX_MUTED,10,true);
   TextAt("bias",564,214,g_consoleReady ? Bias(cb)+" bias" : "Waiting",BiasColor(cb),10,true);
   if(g_tab==1) {
      Box("table",14,237,672,195,SX_CARD);
      TextAt("colA",24,240,"SIGNAL SOURCE",SX_MUTED,9,true); TextAt("colB",294,240,"READING",SX_MUTED,9,true); TextAt("colC",503,240,"DIRECTIONAL VOTE",SX_MUTED,9,true);
      for(int i=0;i<9;i++) {
         string k=IntegerToString(i); int yy=259+19*i,d=g_consoleReady ? ClockVote(i) : 0;
         Box("line"+k,14,yy-2,672,1,SX_EDGE);
         TextAt("signal"+k,24,yy,ClockLabel(i),SX_TEXT,10);
         TextAt("reading"+k,294,yy,g_consoleReady ? Bias(d) : "--",BiasColor(d),10,true);
         Meter("vote"+k,503,yy+6,96,d==0 ? 0 : 1,BiasColor(d));
         TextAt("count"+k,624,yy,d==0 ? "0" : d>0 ? "+1" : "-1",BiasColor(d),10,true);
      }
   } else {
      for(int i=0;i<9;i++) {
         string k=IntegerToString(i); int xx=14+(i%3)*226,yy=237+(i/3)*65,d=g_consoleReady ? ClockVote(i) : 0;
         Box("tileedge"+k,xx,yy,220,59,SX_EDGE); Box("tile"+k,xx+1,yy+1,218,57,SX_CARD);
         TextAt("sig"+k,xx+11,yy+7,ClockLabel(i),SX_MUTED,10,true);
         TextAt("val"+k,xx+11,yy+29,g_consoleReady ? Bias(d) : "--",BiasColor(d),13,true);
      }
   }
   Box("rule2",14,438,672,1,SX_EDGE);
   TextAt("ticket",14,447,"ORDER TICKET",SX_TEXT,15,true);
   TextAt("risk",180,451,"Risk "+Value(ConsoleRiskPercent)+"% / manual lots",SX_MUTED,9);
   Control("lots",OBJ_EDIT,415,444,75,23,LotText(g_manualLots),SX_TEXT,SX_CARD,10,false);
   Key("auto",566,444,120,UiState(),g_auto ? SX_GREEN : SX_MUTED,SX_CARD);
   string ids[7]={"buy","sell","buylimit","selllimit","buystop","sellstop","be"};
   string names[7]={"BUY","SELL","BUY LIMIT","SELL LIMIT","BUY STOP","SELL STOP","BREAKEVEN"};
   for(int i=0;i<7;i++) {
      color tint=i==0 ? SX_GREEN : i==1 ? SX_RED : i==6 ? C'238,192,66' : i<4 ? C'242,157,70' : SX_BLUE;
      Control(ids[i],OBJ_BUTTON,14+96*i,478,92,53,names[i],tint,BlendThemeColor(SX_CARD,tint,22),10,true);
   }
   TextAt("notice",14,546,Cut("Entry  "+g_message,57),SX_MUTED,9,false,g_message);
   Key("tab8",421,539,104,g_consoleTheme==THEME_CUSTOM ? "Custom colours" : Cut(ConsoleThemeName(g_consoleTheme),16),SX_GOLD,SX_CARD);
   Key("size",531,539,68,SizeName(g_size),SX_TEXT,SX_CARD); Key("anchor",605,539,81,g_right ? "Top right" : "Top left",SX_TEXT,SX_CARD);
   ChartEmblem(cw,ch,g_width,false); PaintIndicatorStrip(); ChartRedraw();
}

bool FVGExists(int direction) {
   for(int i=g_zoneCount-1;i>=0;i--)
      if(g_zones[i].direction==direction && !g_zones[i].filled && g_n-1-g_zones[i].bar<=InpMaxFVGAgeBars) return true;
   return false;
}
void Horizontal(string id,double value,color c,ENUM_LINE_STYLE style=STYLE_DOT) {
   if(value<=0) return;
   string name=g_prefix+"chart_"+id;
   if(ObjectFind(0,name)<0) ObjectCreate(0,name,OBJ_HLINE,0,0,value);
   ObjectSetDouble(0,name,OBJPROP_PRICE,0,value); ObjectSetInteger(0,name,OBJPROP_COLOR,c);
   ObjectSetInteger(0,name,OBJPROP_STYLE,style); ObjectSetInteger(0,name,OBJPROP_BACK,true);
   ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
   ObjectSetString(0,name,OBJPROP_TEXT,id);
}
void Segment(string id,datetime left,double y1,datetime right,double y2,color c,int width) {
   string name=g_prefix+"chart_"+id;
   if(ObjectFind(0,name)<0) ObjectCreate(0,name,OBJ_TREND,0,left,y1,right,y2);
   ObjectMove(0,name,0,left,y1); ObjectMove(0,name,1,right,y2);
   ObjectSetInteger(0,name,OBJPROP_COLOR,c); ObjectSetInteger(0,name,OBJPROP_WIDTH,width);
   ObjectSetInteger(0,name,OBJPROP_RAY_RIGHT,false); ObjectSetInteger(0,name,OBJPROP_BACK,true);
   ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
}
void DrawSignal(datetime time,int direction) {
   if(!g_layers || !InpShowSignals || !g_consoleReady || g_symbol!=g_chartSymbol) return;
   string name=g_prefix+"signal_"+IntegerToString((long)time);
   double price=direction>0 ? g_rates[g_n-1].low-0.25*g_atr : g_rates[g_n-1].high+0.25*g_atr;
   if(ObjectFind(0,name)<0) ObjectCreate(0,name,OBJ_ARROW,0,time,price);
   ObjectSetInteger(0,name,OBJPROP_ARROWCODE,direction>0 ? 233 : 234);
   ObjectSetInteger(0,name,OBJPROP_COLOR,direction>0 ? SX_GREEN : SX_RED);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,2); ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,name,OBJPROP_HIDDEN,true); ObjectSetInteger(0,name,OBJPROP_BACK,true); // never paint over the dashboards
   int count=0;
   for(int i=ObjectsTotal(0,0,-1)-1;i>=0;i--) {
      string object=ObjectName(0,i,0,-1);
      if(StringFind(object,g_prefix+"signal_")==0) {
         count++; if(count>100) ObjectDelete(0,object);
      }
   }
}
void ChartArrow(string id,datetime at,double price,int code,color ink,int width,string tip) {
   string name=g_prefix+"chart_"+id;
   if(ObjectFind(0,name)<0 && !ObjectCreate(0,name,OBJ_ARROW,0,at,price)) return;
   ObjectMove(0,name,0,at,price);
   ObjectSetInteger(0,name,OBJPROP_ARROWCODE,code); ObjectSetInteger(0,name,OBJPROP_COLOR,ink);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,width); ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,name,OBJPROP_HIDDEN,true); ObjectSetInteger(0,name,OBJPROP_BACK,true); ObjectSetString(0,name,OBJPROP_TOOLTIP,tip);
}
void HistorySignal(string key,int bar,int direction,bool superTrend) {
   if(direction==0) return;
   double base=direction>0 ? g_rates[bar].low : g_rates[bar].high;
   double price=base-direction*g_atrSeries[bar]*(superTrend ? 0.52 : 0.23);
   datetime at=g_rates[bar].time;
   int code=superTrend ? (direction>0 ? 217 : 218) : (direction>0 ? 233 : 234);
   string label=superTrend ? "SuperTrend flip" : "UT ATR reversal";
   ChartArrow(key+IntegerToString((long)at),at,price,code,
              superTrend ? SX_GOLD : (direction>0 ? SX_GREEN : SX_RED),superTrend ? 1 : 2,
              label+" / "+Side(direction));
}
void TradeEntryMarker(ulong ticket,datetime at,double price,int direction) {
   string id=StringFormat("%I64u",ticket);
   ChartArrow("fill"+id,at,price,direction>0 ? 241 : 242,direction>0 ? SX_BLUE : SX_RED,2,
              "Broker entry #"+id+" / "+Side(direction)+" / "+PriceText(price));
}
void PaintTradeEntries(datetime from) {
   int drawn=0;
#ifdef __MQL5__
   if(!HistorySelect(from,TimeCurrent())) return;
   for(int i=HistoryDealsTotal()-1;i>=0 && drawn<80;i--) {
      ulong ticket=HistoryDealGetTicket(i);
      if(ticket==0 || HistoryDealGetString(ticket,DEAL_SYMBOL)!=g_chartSymbol || HistoryDealGetInteger(ticket,DEAL_MAGIC)!=ConsoleMagic) continue;
      long entry=HistoryDealGetInteger(ticket,DEAL_ENTRY),side=HistoryDealGetInteger(ticket,DEAL_TYPE);
      if((entry!=DEAL_ENTRY_IN && entry!=DEAL_ENTRY_INOUT) || (side!=DEAL_TYPE_BUY && side!=DEAL_TYPE_SELL)) continue;
      TradeEntryMarker(ticket,(datetime)HistoryDealGetInteger(ticket,DEAL_TIME),HistoryDealGetDouble(ticket,DEAL_PRICE),side==DEAL_TYPE_BUY ? 1 : -1);
      drawn++;
   }
#else
   for(int pool=0;pool<2;pool++) {
      int count=pool==0 ? OrdersTotal() : OrdersHistoryTotal();
      for(int i=count-1;i>=0 && drawn<80;i--) {
         if(!OrderSelect(i,SELECT_BY_POS,pool==0 ? (int)MODE_TRADES : (int)MODE_HISTORY)) continue;
         if(OrderSymbol()!=g_chartSymbol || OrderMagicNumber()!=ConsoleMagic || OrderOpenTime()<from) continue;
         int side=OrderType(); if(side!=OP_BUY && side!=OP_SELL) continue;
         TradeEntryMarker((ulong)OrderTicket(),OrderOpenTime(),OrderOpenPrice(),side==OP_BUY ? 1 : -1); drawn++;
      }
   }
#endif
}

void PaintChart() {
   if(!g_layers || !g_consoleReady) return;
   if(g_symbol!=g_chartSymbol || g_snapshotSymbol!=g_symbol) return;
   ObjectsDeleteAll(0,g_prefix+"chart_");
   if(InpShowLevels) {
      Horizontal("PDH",g_pdh,SX_BLUE); Horizontal("PDL",g_pdl,SX_BLUE);
      Horizontal("PWH",g_pwh,SX_MUTED); Horizontal("PWL",g_pwl,SX_MUTED);
      Horizontal("PIVOT",g_pivot,SX_GOLD); Horizontal("R1",g_r1,SX_RED);
      Horizontal("S1",g_s1,SX_GREEN); Horizontal("DAY OPEN",g_dayOpen,SX_MUTED);
      Horizontal("RANGE HIGH",g_breakHigh,SX_BLUE,STYLE_DASH); Horizontal("RANGE LOW",g_breakLow,SX_BLUE,STYLE_DASH);
   }
   if((g_consoleStrategy==DR_PANDICH || g_consoleStrategy==DR_NIGHT || g_consoleStrategy==DR_EXPRESS) && g_gem.droidStop>0) Horizontal("ACTIVE MODEL TRAIL",g_gem.droidStop,SX_GOLD);
   if(g_consoleStrategy==DR_KALMAN && g_gem.droidVW>0) {
      Horizontal("VWMA MID",g_gem.droidVW,SX_BLUE);
      Horizontal("VWMA UPPER",g_gem.droidUpper,SX_MUTED);
      Horizontal("VWMA LOWER",g_gem.droidLower,SX_MUTED);
      Horizontal("KALMAN SUPERTREND",g_gem.droidStop,SX_GOLD);
   }
   if(InpShowSuper) Horizontal("SUPERTREND",g_superLine,g_superDir>0 ? SX_GREEN : SX_RED,STYLE_DASH);
   datetime forming=iTime(g_symbol,g_tf,0);
   int begin=(int)MathMax(InpATRPeriod+1,g_n-101);
   if(begin>=g_n) return;
   for(int i=begin;i<g_n;i++) {
      string suffix=IntegerToString(i-begin);
      if((g_consoleStrategy==FAST_SLOW_UT || g_consoleStrategy==UT_STC_GRADE) && InpShowSlowUT && ArraySize(g_slowUT)==g_n && g_slowUT[i-1]>0) {
         Segment("slowUT"+suffix,g_rates[i-1].time,g_slowUT[i-1],g_rates[i].time,g_slowUT[i],SX_BLUE,1);
         ObjectSetInteger(0,g_prefix+"chart_slowUT"+suffix,OBJPROP_STYLE,STYLE_DOT);
      }
      if(g_consoleStrategy==FAST_SLOW_UT && InpShowSignals && ArraySize(g_proEvents)==g_n && MathAbs(g_proEvents[i])==2)
         ChartArrow("strongUT"+suffix,g_rates[i].time,g_proEvents[i]>0 ? g_rates[i].low-0.60*g_atrSeries[i] : g_rates[i].high+0.60*g_atrSeries[i],171,SX_GOLD,1,"Strong ATR reversal");
      if(InpShowSuper && g_atrSeries[i-1]>0 && g_superDirections[i-1]==g_superDirections[i])
         Segment("super"+suffix,g_rates[i-1].time,g_superSeries[i-1],g_rates[i].time,g_superSeries[i],g_superDirections[i]>0 ? SX_GREEN : SX_RED,1);
      if(InpShowSignals && g_atrSeries[i]>0 && g_rates[i].time<forming) {
         if(g_utEvents[i]!=0) HistorySignal("utSignal",i,g_utEvents[i],false);
         if(g_superDirections[i-1]!=g_superDirections[i]) HistorySignal("stSignal",i,g_superDirections[i],true);
      }
      if(InpShowTrail && g_utSeries[i-1]>0) Segment("ut"+suffix,g_rates[i-1].time,g_utSeries[i-1],g_rates[i].time,g_utSeries[i],Source(g_rates[i])>=g_utSeries[i] ? SX_GREEN : SX_RED,2);
      if(InpShowMA) {
         Segment("fast"+suffix,g_rates[i-1].time,g_fastSeries[i-1],g_rates[i].time,g_fastSeries[i],SX_BLUE,1);
         Segment("slow"+suffix,g_rates[i-1].time,g_slowSeries[i-1],g_rates[i].time,g_slowSeries[i],SX_GOLD,1);
      }
      if(InpShowZeroLag) Segment("zero"+suffix,g_rates[i-1].time,g_zeroSeries[i-1],g_rates[i].time,g_zeroSeries[i],SX_MUTED,1);
   }
   if(g_regOverlay) {
      for(int j=(int)MathMax(InpRegressionLength,g_n-48);j<g_n;j++) {
         double o=RegressionEnd(j,InpRegressionLength,0),c=RegressionEnd(j,InpRegressionLength,3);
         double h=MathMax(MathMax(o,c),RegressionEnd(j,InpRegressionLength,1));
         double l=MathMin(MathMin(o,c),RegressionEnd(j,InpRegressionLength,2));
         datetime t=g_rates[j].time;
         Segment("regwick"+IntegerToString(j),t,l,t,h,c>=o ? SX_GOLD : SX_BLUE,1);
         Segment("regbody"+IntegerToString(j),t,o,t,c,c>=o ? SX_GOLD : SX_BLUE,3);
      }
   }
   if(InpShowTradeMarkers) PaintTradeEntries(g_rates[begin].time);
   if(InpShowFVG) {
      int drawn=0;
      datetime right=iTime(g_symbol,g_tf,0)+(datetime)(PeriodSeconds(g_tf)*8);
      for(int i=g_zoneCount-1;i>=0 && drawn<InpMaxFVGDraw;i--) {
         if(g_zones[i].filled || g_n-1-g_zones[i].bar>InpMaxFVGAgeBars) continue;
         string name=g_prefix+"chart_fvg"+IntegerToString(drawn++);
         ObjectCreate(0,name,OBJ_RECTANGLE,0,g_zones[i].formed,g_zones[i].lower,right,g_zones[i].upper);
         ObjectSetInteger(0,name,OBJPROP_COLOR,g_zones[i].direction>0 ? SX_ZONE_BULL : SX_ZONE_BEAR);
         ObjectSetInteger(0,name,OBJPROP_FILL,true); ObjectSetInteger(0,name,OBJPROP_BACK,true);
         ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
         ObjectSetString(0,name,OBJPROP_TOOLTIP,"CVT LT DRIOD BOT NO ERRORS EA | unfilled "+Side(g_zones[i].direction)+" FVG");
      }
   }
}

int SXParseHHMM(string text) {
   int colon=StringFind(text,":");
   if(colon<1 || colon>2 || StringLen(text)!=colon+3) return -1;
   int h=(int)StringToInteger(StringSubstr(text,0,colon)),m=(int)StringToInteger(StringSubstr(text,colon+1,2));
   if(h<0 || h>23 || m<0 || m>59) return -1;
   return h*60+m;
}
bool SXInWindow(int nowMinute,int startMinute,int endMinute) {
   if(startMinute<0 || endMinute<0 || startMinute==endMinute) return false;
   return startMinute<endMinute ? (nowMinute>=startMinute && nowMinute<endMinute) : (nowMinute>=startMinute || nowMinute<endMinute);
}
bool WeekdayAllowed(int dow) {
   if(!InpUseWeekdayFilter) return true;
   switch(dow) {
      case 1: return InpTradeMonday;
      case 2: return InpTradeTuesday;
      case 3: return InpTradeWednesday;
      case 4: return InpTradeThursday;
      case 5: return InpTradeFriday;
      case 6: return InpTradeSaturday;
      default: return InpTradeSunday;
   }
}
// Smart Guards: returns true when a NEW entry must be refused. Never touches exits, stops or trailing.
bool GuardBlocksEntry(string &why) {
   MqlDateTime now; TimeToStruct(TimeCurrent(),now);
   if(!NoTimeRestrictions()) {
      if(!WeekdayAllowed(now.day_of_week)) { why="Weekday filter"; return true; }
      if(InpUseFridayCutoff && now.day_of_week==5 && now.hour>=InpFridayCutoffHour) { why="Friday entry cutoff"; return true; }
      int minute=now.hour*60+now.min;
      if(InpUseBlackout1 && SXInWindow(minute,SXParseHHMM(InpBlackout1Start),SXParseHHMM(InpBlackout1End))) { why="News blackout 1"; return true; }
      if(InpUseBlackout2 && SXInWindow(minute,SXParseHHMM(InpBlackout2Start),SXParseHHMM(InpBlackout2End))) { why="News blackout 2"; return true; }
   }
   if(g_profitLock && !NoProfitLock()) { why="Daily profit target reached"; return true; }
   if(!NoPositionCaps() && InpMaxDailyEntries>0 && (int)ReadGuard("entries",0)>=InpMaxDailyEntries && (int)ReadGuard("entriesday",0)==DayCode()) { why="Daily entry cap"; return true; }
   return false;
}
string GuardStatus() {
   string why=""; return GuardBlocksEntry(why) ? why : "CLEAR";
}
void CountEntry() {
   int day=DayCode();
   if((int)ReadGuard("entriesday",0)!=day) { WriteGuard("entriesday",day); WriteGuard("entries",0); }
   WriteGuard("entries",ReadGuard("entries",0)+1);
}
void AutoThemeTick() {
   if(!InpAutoThemeSwitch) return;
   MqlDateTime now; TimeToStruct(TimeCurrent(),now);
   bool day=SXHours(now.hour,InpDayStartHour,InpNightStartHour);
   int phase=day ? 1 : 0;
   if(phase==g_autoPhase) return;
   g_autoPhase=phase;
   ApplyTheme(day ? (int)InpDayTheme : (int)InpNightTheme,g_themeStyle);
   ClearUI(); Log((day ? "Day theme " : "Night theme ")+ConsoleThemeName(g_consoleTheme));
}
bool ValidInputs() {
   if(XE_GivebackStartR<0.2 || XE_GivebackStartR>4.0 || XE_GivebackKeepMinPct<5 || XE_GivebackKeepMinPct>90 || XE_GivebackKeepMaxPct<XE_GivebackKeepMinPct || XE_GivebackKeepMaxPct>95) return false;
   if(XE_FomoMaxStreak<0 || XE_FomoMaxStreak>30 || XE_ATRExpansionMult<0 || XE_ATRExpansionMult>10 || XE_ATRExpansionBars<10 || XE_ATRExpansionBars>300) return false;
   if(XE_HTFEmaLen<20 || XE_HTFEmaLen>500 || XE_HTFAdxMin<0 || XE_HTFAdxMin>60 || XE_HarvestHour<0 || XE_HarvestHour>23) return false;
   if((int)XE_PosTrailMode<0 || (int)XE_PosTrailMode>=27) return false;

   if(XE_MinIQScore<0 || XE_MinIQScore>100 || XE_MinRiskMult<0.05 || XE_MinRiskMult>1.0 || XE_ExhaustRSI<60 || XE_ExhaustRSI>99 ||
      XE_SpacingMinutes<0 || XE_SpacingMinutes>1440 || XE_DailyProfitLockPct<0 || XE_DailyProfitLockPct>100 ||
      XE_DeckScalePct<65 || XE_DeckScalePct>150 || XE_MainScalePct<65 || XE_MainScalePct>150) return false;
   if(InpSmartMinAtrRatio<0.1 || InpSmartMinAtrRatio>5 || InpSmartKalmanGain<0.02 || InpSmartKalmanGain>0.95 || InpSmartVwmaPeriod<5 || InpSmartVwmaPeriod>200) return false;
   if(VectorServerUTCMinutes < -840 || VectorServerUTCMinutes>840 || InpNightEnd<0 || InpNightOpen>23 || InpNightOpen<=InpNightEnd) return false;
   if(InpSlowUTEMALength<2 || InpSlowUTEMALength>800 || ((ConsoleInpStrategy==FAST_SLOW_UT || ConsoleInpStrategy==UT_STC_GRADE) && InpSlowUTUseEMA && InpHistoryBars<InpSlowUTEMALength)) return false;
   if(InpTickWindowSeconds<3 || InpTickWindowSeconds>300 || InpTickMinMoves<4 || InpTickMinMoves>400) return false;
   if(InpTickMinImbalance<0.5 || InpTickMinImbalance>0.98 || InpTickMinDriftPts<0 || InpTickMaxSpreadShare<=0 || InpTickMaxSpreadShare>5) return false;
   if(InpTickCooldownSeconds<0 || InpTickMaxEntriesPerBar<1 || InpTickMaxEntriesPerBar>50) return false;
   if(InpWeeklyLossPercent<0 || InpWeeklyLossPercent>100 || InpCommissionPerLot<0) return false;
   if(InpTickMaxEntriesPerHour<0 || InpTickMaxEntriesPerHour>500 || InpTickMinRate<0 || InpTickMinRate>50 || InpTickReverseMinHoldSec<0 || InpTickReverseMinHoldSec>3600) return false;
   if(InpTickConfirmSeconds<0 || InpTickConfirmSeconds>30 || InpTickDriftSpreadMult<0 || InpTickDriftSpreadMult>50) return false;
   if(InpRolloverGuardMinutes<0 || InpRolloverGuardMinutes>120 || InpGivebackMinATR<0 || InpGivebackMinATR>20 || InpGivebackPct<1 || InpGivebackPct>95) return false;
   if(InpTickSpreadSpikeMult<0 || InpTickSpreadSpikeMult>50) return false;
   if(InpSlipPauseRatio<0 || InpSlipPauseRatio>5 || InpSlipPauseMinutes<1 || InpSlipPauseMinutes>240) return false;
   if(InpVoteMinVotes<2 || InpVoteMinVotes>6 || InpVoteEmaFast<2 || InpVoteEmaSlow<=InpVoteEmaFast || InpVoteEmaMid<InpVoteEmaSlow || InpVoteLongEma<InpVoteEmaMid) return false;
   if(InpVoteSweepLookback<5 || InpVoteSweepLookback>40 || InpVoteRsiPeriod<2 || InpVoteRsiPeriod>50 || InpVoteAdxPeriod<2 || InpVoteAdxPeriod>50 || InpVoteAdxMin<0 || InpVoteAdxMin>60) return false;
   if(InpTrendFitBars<5 || InpTrendFitBars>200 || InpMinTrendFit<0 || InpMinTrendFit>1) return false;
   if((int)InpDashboardStart<0 || (int)InpDashboardStart>3 || InpLogoHeaderOpacity<0 || InpLogoHeaderOpacity>100) return false;
   if((int)InpLogoMode<0 || (int)InpLogoMode>2 || InpLogoBody==clrNONE || InpLogoNodes==clrNONE) return false;
   if(InpPathBars<6 || InpPathBars>120 || InpPathEfficiency<=0 || InpPathEfficiency>1 || InpRegimeVotes<2 || InpRegimeVotes>4) return false;
   if(InpRegimeMinRatio<=0 || InpRegimeMaxRatio<=InpRegimeMinRatio || InpRegimeMaxRatio>10 || InpRetestToleranceATR<=0 || InpRetestToleranceATR>1.5 || InpSnapbackDistanceATR<=0 || InpSnapbackDistanceATR>5) return false;
   if(InpUTQuietBars<0 || InpUTQuietBars>500 || InpSTCVolumeRatio<=0 || InpSTCVolumeRatio>10) return false;
   if(InpRangeWeekday< -1 || InpRangeWeekday>6 || InpRangeStartUTC<0 || InpRangeStartUTC>23 || InpRangeWindowMinutes<1 || InpRangeWindowMinutes>1440 || InpRangeBars<2 || InpRangeBars>200 || InpRangeServerOffsetMinutes< -840 || InpRangeServerOffsetMinutes>840 || InpRangeBufferATR<=0 || InpRangeBufferATR>5) return false;
   if(ConsoleInpStrategy==SESSION_BRACKET && InpAllowBuy && InpAllowSell && (ConsoleMaxPositions<2 || InpMaxPortfolioPositions<2)) return false;
   if(InpClockTimerSeconds<1 || InpClockTimerSeconds>10 || InpClockRetrySeconds<5 || InpClockRetrySeconds>300 || InpClockAttemptsPerBar<1 || InpClockAttemptsPerBar>60) return false;
   if(InpClockMaxHoldMinutes<0 || InpClockMaxHoldMinutes>100000 || InpClockMinVotes<5 || InpClockMinVotes>9 || InpClockHoverBars<8 || InpClockHoverBars>200 || InpClockHoverEdgeATR<=0 || InpClockHoverEdgeATR>1 || InpClockMinTrendCorrelation<0 || InpClockMinTrendCorrelation>1) return false;
   if(InpShockLookback<10 || InpShockLookback>100 || InpMaxCostPctOfTarget<=0 || InpMaxCostPctOfTarget>100 || InpExtraCostPoints<0 || InpShockMultiple<=1 || InpShockPauseBars<1 || InpShockPauseBars>10) return false;
   if(InpBuyATRLength<1 || InpBuyATRLength>500 || InpSellATRLength<1 || InpSellATRLength>500 ||
      InpBuySensitivity<0 || InpSellSensitivity<0 || InpBuySensitivity>30 || InpSellSensitivity>30) return false;
   if(InpRegressionLength<3 || InpRegressionLength>200 || InpRouterEfficiency<0 || InpRouterEfficiency>1 || InpRouterExpansion<=0) return false;
   if(InpMinVwapSlopeATR<0 || InpMaxVwapDistanceATR<0 || InpMinCandleBodyATR<0) return false;
   if((int)InpInitialStopMode<0 || (int)InpInitialStopMode>3 || InpStopBufferATR<0 || InpStopSwingBars<2 || InpStopSwingBars>200 || InpStopPercent<=0 || InpStopPercent>50) return false;
   if(InpHistoryBars<RequiredHistoryBars()) return false;
   if((int)InpPrimaryGem<0 || (int)InpPrimaryGem>11 || (int)InpAccentGem<0 || (int)InpAccentGem>11 ||
      InpWatermarkPixels<32 || InpWatermarkPixels>640) return false;
   if(InpAdaptiveMinVotes<1 || InpAdaptiveMinVotes>5 || InpAdaptiveMinADX<0 || InpAdaptiveMinADX>100) return false;
   if(InpVolatilityMinATRRatio<=0 || InpVolatilityMaxATRRatio<InpVolatilityMinATRRatio || InpVolatilityMaxATRRatio>20) return false;
   if(InpRiskAttenuationStartRatio<=0 || InpRiskAttenuationFloor<=0 || InpRiskAttenuationFloor>1.0) return false;
   if(InpMarkOpacity<0 || InpMarkOpacity>100 || InpBELockTicks<1 || InpSpreadShockMultiple<0 || InpBreakBufferATR<0) return false;
   if(InpFixedStopPoints<0 || InpFixedTargetPoints<0 || InpTrailStartPoints<0 || InpTrailGapPoints<0 || InpTrailStepPoints<0) return false;
   if(InpTrailStartPoints>0 && (InpTrailGapPoints<1 || InpTrailStepPoints<1)) return false;
   if(InpATRPeriod<2 || InpATRPeriod>200 || InpATRMultiplier<=0 || InpATRMultiplier>20 || InpCooldownBars<0) return false;
   if(InpFastMA<2 || InpSlowMA<=InpFastMA || InpSlowMA>1000 || InpSMAPeriod<2 || InpSMAPeriod>1000) return false;
   if(InpHistoryBars<MathMax(InpSlowMA*3,MathMax(InpSMAPeriod+30,InpBreakoutLookback+30)) || InpHistoryBars>20000 || InpHistoryBars<InpATRPeriod*3 || InpHistoryBars<ConsoleADXPeriod*3) return false;
   if(ConsoleRSIPeriod<2 || ConsoleRSIPeriod>200 || ConsoleADXPeriod<2 || ConsoleADXPeriod>200 || InpHistoryBars<MathMax(ConsoleRSIPeriod+30,2*ConsoleADXPeriod+30)) return false;
   if(InpVolumePeriod<2 || InpVolumePeriod>500 || InpHistoryBars<InpVolumePeriod+30 || InpMinVolumeRatio<0) return false;
   if(InpBreakoutLookback<2 || InpBreakoutLookback>1000 || InpMinConfluenceScore<0 || InpMinConfluenceScore>100) return false;
   if(InpZeroLagPeriod<2 || InpZeroLagPeriod>1000 || InpZeroLagBandATR<=0 || InpHistoryBars<InpZeroLagPeriod*3) return false;
   if(InpRSIBuyMin<0 || InpRSIBuyMin>100 || InpRSISellMax<0 || InpRSISellMax>100 || InpMinADX<0 || InpMinADX>100) return false;
   if(ConsoleRiskPercent<=0 || ConsoleRiskPercent>10 || InpFixedLots<=0 || InpMaxLots<=0 || ConsoleMaxPositions<1 || ConsoleMaxPositions>20 || ConsoleMagic<=0) return false;
   if(InpInitialSL_ATR<=0 || InpMinSLPoints<0 || InpSlippagePoints<0 || InpBETriggerATR<=0 || InpBELockATR<=0 || InpBELockATR>=InpBETriggerATR) return false;
   if(InpTrailStartATR<=0 || InpTrailDistanceATR<=0 || InpTrailDistanceATR>=InpTrailStartATR || InpTrailStepATR<0) return false;
   if(InpDailyLossPercent<0 || InpDailyLossPercent>100 || InpMaxDrawdownPercent<0 || InpMaxDrawdownPercent>100) return false;
   if(ConsoleMaxSpreadATR<0 || ConsoleMaxSpreadPoints<0 || InpMaxQuoteAgeSeconds<0 || InpMinFVGGapPercent<0 || InpMaxFVGAgeBars<1) return false;
   if(InpLevelRoomATR<0 || InpMaxFVGDraw<0 || InpMaxFVGDraw>50 || InpSessionStartHour<0 || InpSessionStartHour>23 || InpSessionEndHour<0 || InpSessionEndHour>24) return false;
   if(InpUseDateWindow && InpStartDate>=InpEndDate) return false;
   if(InpPanelX<0 || InpPanelY<0) return false;
   if(InpMaxPortfolioPositions<1 || InpMaxPortfolioPositions>200 || InpScanBatch<1 || InpScanBatch>100 || InpMaxSymbols<0) return false;
   if((int)ConsoleInpStrategy<0 || (int)ConsoleInpStrategy>=SG_ENGINE_COUNT || (int)InpSource<0 || (int)InpSource>4 || (int)ConsolePanelSize<0 || (int)ConsolePanelSize>4) return false;
   if((int)ConsoleTrailMode<0 || (int)ConsoleTrailMode>=36 || (int)ConsoleTheme<0 || (int)ConsoleTheme>SG_PALETTE_COUNT || (int)InpThemeStyle<0 || (int)InpThemeStyle>=16) return false;
   if(InpFridayCutoffHour<0 || InpFridayCutoffHour>23 || InpFridayFlattenHour<0 || InpFridayFlattenHour>23 || (InpFridayFlatten && InpFridayFlattenHour<InpFridayCutoffHour)) return false;
   if((InpUseBlackout1 && (SXParseHHMM(InpBlackout1Start)<0 || SXParseHHMM(InpBlackout1End)<0 || SXParseHHMM(InpBlackout1Start)==SXParseHHMM(InpBlackout1End))) ||
      (InpUseBlackout2 && (SXParseHHMM(InpBlackout2Start)<0 || SXParseHHMM(InpBlackout2End)<0 || SXParseHHMM(InpBlackout2Start)==SXParseHHMM(InpBlackout2End)))) return false;
   if(InpFixedTP_R<0.5 || InpFixedTP_R>20 || InpLadder1R<0 || InpLadder2R<0 || InpLadder3R<0 || InpLadder1R>50 || InpLadder2R>50 || InpLadder3R>50) return false;
   if(InpLadder1Pct<0 || InpLadder2Pct<0 || InpLadder3Pct<0 || InpLadder1Pct+InpLadder2Pct+InpLadder3Pct>95) return false;
   if(InpMaxHoldBars<0 || InpMaxHoldBars>100000 || (int)InpRiskBase<0 || (int)InpRiskBase>2) return false;
   if(InpDayLossRiskStepPct<0 || InpDayLossRiskStepPct>100 || InpDayLossRiskStepMult<0.05 || InpDayLossRiskStepMult>1.0) return false;
   if(InpMaxDailyEntries<0 || InpMaxDailyEntries>1000 || InpDailyProfitTargetPct<0 || InpDailyProfitTargetPct>1000) return false;
   if((int)InpDayTheme<0 || (int)InpDayTheme>SG_PALETTE_COUNT || (int)InpNightTheme<0 || (int)InpNightTheme>SG_PALETTE_COUNT || InpDayStartHour<0 || InpDayStartHour>23 || InpNightStartHour<0 || InpNightStartHour>23 || (InpAutoThemeSwitch && InpDayStartHour==InpNightStartHour)) return false;
   if(InpDashboardFontSize!=0 && (InpDashboardFontSize<7 || InpDashboardFontSize>11)) return false;
   if(InpQuantumERPeriod<2 || InpQuantumERPeriod>200 || InpQuantumTrendFactor<=0 || InpQuantumRangeFactor<InpQuantumTrendFactor || InpQuantumRangeFactor>20.0 || InpWhipsawShieldATR<0 || InpWhipsawShieldATR>5.0) return false;
   if(InpDrmPeriod<2 || InpDrmPeriod>200 || InpD1MAPeriod<2 || InpD1MAPeriod>1000 || InpCoralCoralPeriod<2 || InpCoralCoralPeriod>500 || InpDeltaTrapWickRatio<=0 || InpDeltaTrapWickRatio>0.95) return false;
   if(InpPositiveCostLockPerLot<0 || InpStage2CompressionATR<0 || InpStage2CompressionATR>1.0 || InpStage4ExtraLockATR<0 || InpStage4ExtraLockATR>5.0) return false;
    if(InpProfitRatchetStartATR<=0 || InpProfitRatchetStepATR<=0 || InpProfitRatchetLockPercent<=0 || InpProfitRatchetLockPercent>90 || InpProfitRatchetStepPercent<0 || InpProfitRatchetStepPercent>25 || InpProfitRatchetMaxPercent<InpProfitRatchetLockPercent || InpProfitRatchetMaxPercent>95) return false;
   if(InpRRPartialRR<=0 || InpRRBETriggerRR<0 || InpRRKeyValue<=0 || InpRRATRPeriod<1 || InpRRATRPeriod>200 || InpRREMAPeriod<2 || InpRREMAPeriod>1000) return false;
   if(InpEnsembleMinVotes<1 || InpEnsembleMinVotes>30 || InpEnsembleMinConfidence<=0 || InpEnsembleMinConfidence>1.0 || InpHullPeriod<4 || InpHullPeriod>200) return false;
   if(ConsoleKalmanGain<=0 || ConsoleKalmanGain>1.0 || InpVelocityPeriod<2 || InpVelocityPeriod>100 || InpDynamicRiskMinMult<=0 || InpDynamicRiskMinMult>1.0 || InpDynamicRiskMaxMult<1.0 || InpDynamicRiskMaxMult>5.0) return false;
   if((int)InpAssets<0 || (int)InpAssets>3 || (int)InpEntryStyle<0 || (int)InpEntryStyle>2 || (int)InpGrid<0 || (int)InpGrid>2 || (int)InpGridLots<0 || (int)InpGridLots>2) return false;
   if(InpMaxPortfolioRiskPct<=0 || InpMaxPortfolioRiskPct>50 || InpMinEntrySeconds<0) return false;
   if(InpSuperPeriod<2 || InpSuperPeriod>500 || InpSuperMultiplier<=0 || InpHistoryBars<InpSuperPeriod*3) return false;
   if(InpStcFast<2 || InpStcSlow<=InpStcFast || InpStcCycle<2 || InpStcCycle>200 || InpStcSlow>500 || InpStcSmooth<=0 || InpStcSmooth>1) return false;
   if(InpStcBuyZone<=0 || InpStcBuyZone>=50 || InpStcSellZone<=50 || InpStcSellZone>=100 || InpStcLag<0 || InpStcLag>5) return false;
   if(InpHistoryBars<InpStcSlow+2*InpStcCycle+10 || InpVWAPAnchorHour<0 || InpVWAPAnchorHour>23 || InpVWAPAnchorMinute<0 || InpVWAPAnchorMinute>59) return false;
   if(InpHAImpulseATR<=0 || InpBandPeriod<5 || InpBandPeriod>300 || InpBandDeviation<=0 || InpRangeADXMax<=0 || InpATRMeanPeriod<5 || InpATRMeanPeriod>500) return false;
   if(InpMinATRRatio<=0 || InpMaxATRRatio<InpMinATRRatio || InpSwingLookback<10 || InpSwingLookback>500 || InpPivotLeft<1 || InpPivotRight<1 || InpPivotLeft>20 || InpPivotRight>20) return false;
   if(InpPivotRSILow<=0 || InpPivotRSILow>=50 || InpPivotRSIHigh<=50 || InpPivotRSIHigh>=100) return false;
   if(InpPendingOffsetATR<=0 || InpPendingLifeBars<1 || InpPendingLifeBars>500) return false;
   if(InpHistoryBars<InpBandPeriod+5 || InpHistoryBars<InpATRMeanPeriod+InpATRPeriod+10 || InpHistoryBars<InpSwingLookback+InpPivotRight+10) return false;
   if(InpGridMaxLevels<2 || InpGridMaxLevels>20 || InpGridSpacingATR<=0 || InpGridMultiplier<1 || InpGridMultiplier>3 || InpGridAddLots<0) return false;
   if(InpBasketStartMoney<=0 || InpBasketGivebackPct<=0 || InpBasketGivebackPct>=100 || InpBasketMinMoney<0 || InpBasketLossMoney<0) return false;
   return true;
}
int ConsoleOnInit() {
   g_beTrigger=InpBETriggerATR; g_beLock=InpBELockATR; g_trStart=InpTrailStartATR; g_trGap=InpTrailDistanceATR; g_trStep=InpTrailStepATR; g_lockTicks=InpBELockTicks;
   g_noLocks=InpNoLocks; g_noRestrictions=InpNoRestrictions; g_positiveOnly=InpPositiveOnlyUpdates; g_breakEven=InpBreakEven;
   g_logoMode=(int)InpLogoMode; LoadLogoInputs(); g_logoPart=0;
   g_logoNote="Enter #RRGGBB and press Enter.";
   for(int i=0;i<3;i++) g_logoSize[i]=0;
   g_primaryGem=(int)InpPrimaryGem; g_accentGem=(int)InpAccentGem;
   g_regOverlay=InpShowRegressionCandles; g_watermark=InpShowChartEmblem; g_strip=InpShowIndicatorStrip; g_layers=true;
   if(InpHistoryBars<RequiredHistoryBars()) {
      Print(SG_BRAND," | InpHistoryBars must be at least ",RequiredHistoryBars()," for these inputs");
      return INIT_PARAMETERS_INCORRECT;
   }
   if(!ValidInputs()) { Print("CVT LT DRIOD BOT NO ERRORS EA | Invalid input combination"); return INIT_PARAMETERS_INCORRECT; }
   g_chartSymbol=Symbol(); g_symbol=g_chartSymbol;
   g_consolePoint=SymbolInfoDouble(g_symbol,SYMBOL_POINT); g_consoleDigits=(int)SymbolInfoInteger(g_symbol,SYMBOL_DIGITS);
   if(g_consolePoint<=0) return INIT_FAILED;
   g_tf=InpSignalTF==PERIOD_CURRENT ? (ENUM_TIMEFRAMES)_Period : InpSignalTF;
#ifdef __MQL5__
   g_tester=(bool)MQLInfoInteger(MQL_TESTER);
#else
   g_tester=IsTesting();
#endif
   g_guardKey="NSGGuard_"+IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN))+"_"+IntegerToString(SymbolHash(AccountInfoString(ACCOUNT_SERVER)+IntegerToString(ConsoleMagic)))+"_";
   if(g_tester) g_guardKey="NSGTest_"+IntegerToString((long)GetTickCount())+"_";
   g_prefix="LRP_"+IntegerToString(ChartID())+"_";
   g_x=InpPanelX; g_y=InpPanelY; g_size=(int)ConsolePanelSize; g_right=InpPanelRight;
   g_auto=InpAutoEnabled; g_trailing=InpTrailing; g_manualLots=InpFixedLots;
   g_consoleStrategy=ConsoleInpStrategy; g_assetMode=InpAssets;
   g_tab=InpDashboardStart==START_CLASSIC_DESK ? 0 : 10+(int)InpDashboardStart;
#ifndef __MQL5__
   if(g_tester) g_assetMode=ASSET_CHART;
#endif
   g_trailMode=(int)ConsoleTrailMode; g_themeStyle=(int)InpThemeStyle; BPInitState(); ApplyTheme((int)ConsoleTheme,g_themeStyle);
   g_profitLock=ReadGuard("profitlock",0)>0;
   BuildUniverse(); if(ArraySize(g_assets)<1) return INIT_FAILED;
   if(AnyUnlock()) Print("CVT LT DRIOD BOT NO ERRORS EA | UNLOCK MODE ACTIVE: one or more safety locks, caps or restrictions are disabled by your inputs");
   ActivateAsset(0);
   g_dayCode=(int)ReadGuard("day",0); g_dayEquity=ReadGuard("dayeq",ConsoleEquity());
   g_consolePeakEquity=ReadGuard("peak",ConsoleEquity()); g_peakLock=ReadGuard("peaklock",0)>0; g_dailyLock=ReadGuard("daylock",0)>0;
   g_weekCode=(int)ReadGuard("week",0); g_weekEquity=ReadGuard("weekeq",ConsoleEquity()); g_weeklyLock=ReadGuard("weeklock",0)>0;
   g_emergency=ReadGuard("emergency",0)>0;
   if(g_emergency && InpAuthorizeEmergencyReset) {
      g_emergency=false; WriteGuard("emergency",0); g_auto=false;
      Print("CVT LT DRIOD BOT NO ERRORS EA | Emergency lock cleared; automatic entries stay off until you enable AUTO");
   }
   if(g_emergency) g_auto=false;
   RiskGuard();
   bool built=BuildSnapshot();
   if(!InpTradeOnAttach && iTime(g_symbol,g_tf,1)>0) WriteGV("skipbar",(double)iTime(g_symbol,g_tf,1));
   else if(InpTradeOnAttach && ReadGV("skipbar",0)>0) WriteGV("skipbar",0);
   if(!FlowLeaseAcquire()) { Print("CVT LT DRIOD BOT NO ERRORS EA | An instance is active for this symbol and magic"); return INIT_FAILED; }
   bool useTimer=true;
#ifndef __MQL5__
   useTimer=!g_tester;
#endif
   if(useTimer && !EventSetTimer(InpClockTimerSeconds)) {
      Print(SG_BRAND," | Could not start terminal timer; error ",GetLastError());
      FlowLeaseRelease(); return INIT_FAILED;
   }
   Log(IntegerToString(SG_ENGINE_COUNT)+" engines | "+IntegerToString(SG_PALETTE_COUNT)+" palettes | "+IntegerToString(ArraySize(g_assets))+" symbols");
   ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,true); SaveAsset(); PaintChart(); PaintPanel(); BPRefreshIntel(); BPPaintAll(); return INIT_SUCCEEDED;
}
void ConsoleOnDeinit(const int reason) {
   EventKillTimer(); FlowLeaseRelease(); SaveAsset(); RestoreChart(); BPCleanup();
   if(g_prefix!="") {
      ObjectsDeleteAll(0,g_prefix);
      if(g_logoSize[0]>0) ResourceFree("::"+g_prefix+"GemHeader");
      if(g_logoSize[1]>0) ResourceFree("::"+g_prefix+"GemWater");
      if(g_logoSize[2]>0) ResourceFree("::"+g_prefix+"GemStudio");
   }
   GlobalVariablesFlush();
   if(g_tester && g_guardKey!="") {
      GlobalVariablesDeleteAll(g_guardKey);
      for(int i=0;i<ArraySize(g_assets);i++) GlobalVariablesDeleteAll(g_assets[i].key);
   }
}
void ConsoleOnTick() {
   if(ArraySize(g_assets)<1) return;
   ActivateAsset(0); RiskGuard(); XEGuardTick(); ProcessAsset(0,true);
   if(g_consolePortfolioExit && PortfolioExposureCount()==0) g_consolePortfolioExit=false;
#ifndef __MQL5__
   if(g_tester && IsVisualMode()) { ActivateAsset(0); PaintTradeLevels(); PaintPanel(); }
#endif
}
void PaintTradeLevels() {
   string ids[3]={"Owned entry","Owned SL","Owned TP"};
   double values[3]; values[0]=0; values[1]=0; values[2]=0;
   if(InpShowOrderLevels && g_layers && g_symbol==g_chartSymbol && ArraySize(g_positions)>0) {
      values[0]=g_positions[0].open; values[1]=g_positions[0].sl; values[2]=g_positions[0].tp;
   }
   for(int i=0;i<3;i++) {
      if(values[i]>0) Horizontal(ids[i],values[i],i==0 ? SX_GOLD : i==1 ? SX_RED : SX_GREEN,STYLE_DASH);
      else ObjectDelete(0,g_prefix+"chart_"+ids[i]);
   }
}
void ConsoleOnTimer() {
   FlowLeaseBeat();
   DiscoverBroker(InpScanBatch);
   int count=ArraySize(g_assets); if(count<1) return;
   ActivateAsset(0); RiskGuard(); AutoThemeTick();
   // Manage open exposure before round-robin entry scans.
   bool hasOrders=PortfolioExposureCount()>0;
   bool processed[]; ArrayResize(processed,count);
   for(int i=0;i<count;i++) { processed[i]=false; if(g_assets[i].exiting || (hasOrders && HasExposure(g_assets[i].symbol))) { ProcessAsset(i,true); processed[i]=true; } }
   int batch=(int)MathMin(count,InpScanBatch);
   for(int i=0;i<batch;i++) { if(!processed[g_cursor]) ProcessAsset(g_cursor,true); g_cursor=(g_cursor+1)%count; }
   if(g_consolePortfolioExit && PortfolioExposureCount()==0) g_consolePortfolioExit=false;
   ActivateAsset(0); PaintTradeLevels(); PaintPanel(); BPTick(); BPPaintAll();
}
void RefreshLayers() {
   ObjectsDeleteAll(0,g_prefix+"chart_");
   if(!g_layers) ObjectsDeleteAll(0,g_prefix+"signal_");
   if(g_layers && g_symbol==g_chartSymbol) {
      if(g_snapshotSymbol!=g_chartSymbol && !BuildSnapshot()) return;
      PaintChart();
   }
}
string LotText(double lots) {
   string s=DoubleToString(lots,8);
   while(StringLen(s)>0 && StringSubstr(s,StringLen(s)-1)=="0" && StringLen(s)-StringFind(s,".")>3)
      s=StringSubstr(s,0,StringLen(s)-1);
   return s;
}
bool ReadTicketLots(bool announce) {
   string obj=g_prefix+"ui_lots",typed=ObjectGetString(0,obj,OBJPROP_TEXT);
   bool valid=StringLen(typed)>0; int separators=0;
   for(int i=0;i<StringLen(typed);i++) {
      int ch=(int)StringGetCharacter(typed,i);
      if(ch==46) separators++;
      else if(ch<48 || ch>57) valid=false;
   }
   double lots=StringToDouble(typed);
   if(!valid || separators>1 || !MathIsValidNumber(lots) || lots<=0) {
      Log("Enter a positive number in Lots"); return false;
   }
   g_manualLots=lots; ObjectSetString(0,obj,OBJPROP_TEXT,LotText(lots));
   if(announce) Log("Manual size "+LotText(lots)+" lots");
   return true;
}
void ConsoleOnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam) {
   if(ArraySize(g_assets)<1) return;
   ActivateAsset(0);
   if(id==CHARTEVENT_MOUSE_MOVE) { XEHandleMouseMove((int)lparam,(int)dparam,(uint)StringToInteger(sparam)); return; }
   if(id==CHARTEVENT_OBJECT_CLICK && StringFind(sparam,g_prefix+"bp_d_b_")==0) { BPHandleClick(StringSubstr(sparam,StringLen(g_prefix+"bp_d_b_"))); return; }
   if(id==CHARTEVENT_KEYDOWN) { FlowKey((int)lparam); return; }
   if(id==CHARTEVENT_CHART_CHANGE) { PaintPanel(); BPPaintAll(); return; }
   if(id==CHARTEVENT_OBJECT_ENDEDIT && g_tab==12 && sparam==g_prefix+"ui_logoHex") {
      color ink=clrNONE;
      if(ParseLogoHex(ObjectGetString(0,sparam,OBJPROP_TEXT),ink)) {
         EditLogoColor(g_logoPart,ink); g_logoNote=LogoPartName(g_logoPart)+" set to "+LogoHex(ink)+".";
      } else g_logoNote="Enter a six-digit hex colour, for example 3DDC84.";
      ObjectDelete(0,sparam); PaintPanel(); return;
   }
   if(id==CHARTEVENT_OBJECT_ENDEDIT && sparam==g_prefix+"ui_lots") {
      ReadTicketLots(true); SaveAsset(); PaintPanel(); return;
   }
   if(id==CHARTEVENT_OBJECT_ENDEDIT && StringFind(sparam,g_prefix+"ui_")==0) {
      string field=StringSubstr(sparam,StringLen(g_prefix+"ui_"));
      string typed=ObjectGetString(0,sparam,OBJPROP_TEXT);
      double v=StringToDouble(typed);
      bool ok=MathIsValidNumber(v) && v>0 && v<=1000;
      int dots=0;
      for(int i=0;i<StringLen(typed);i++) {
         int c=(int)StringGetCharacter(typed,i);
         if(c==46) dots++;
         if(((c<48 || c>57) && c!=46) || dots>1) ok=false;
      }
      if(ok && field=="beTrigger" && v>g_beLock) g_beTrigger=v;
      else if(ok && field=="beLock" && v<g_beTrigger) g_beLock=v;
      else if(ok && field=="lockTicks" && v==MathFloor(v)) g_lockTicks=(int)v;
      else if(ok && field=="trStart" && v>g_trGap) g_trStart=v;
      else if(ok && field=="trGap" && v<g_trStart) g_trGap=v;
      else if(ok && field=="trStep") g_trStep=v;
      else ok=false;
      Log(ok ? "Stop setting updated: "+field : "Check the value and trigger / gap ordering");
      ObjectDelete(0,sparam); SaveAsset(); PaintPanel(); return;
   }
   if(id!=CHARTEVENT_OBJECT_CLICK || StringFind(sparam,g_prefix+"ui_")!=0) return;
   string action=StringSubstr(sparam,StringLen(g_prefix+"ui_"));
   ObjectSetInteger(0,sparam,OBJPROP_STATE,false);
   if(action=="auto") { g_auto=!g_auto; Log("Automatic entries "+Yes(g_auto)); }
   else if(action=="trail") { g_trailing=!g_trailing; Log("Trailing "+Yes(g_trailing)); }
   else if(action=="beAuto") { g_breakEven=!g_breakEven; Log("Auto breakeven "+Yes(g_breakEven)); }
   else if(action=="strict") { g_positiveOnly=!g_positiveOnly; Log("Positive-only stop updates "+Yes(g_positiveOnly)); }
   else if(action=="nolocks" || action=="norestrict") {
      if(InpUnlockAll) Log("Both overrides are enabled by the master input");
      else if(action=="nolocks") { g_noLocks=!g_noLocks; RiskGuard(); Log("No Locks "+Yes(g_noLocks)); }
      else { g_noRestrictions=!g_noRestrictions; Log("No Restrictions "+Yes(g_noRestrictions)); }
   }
   else if(action=="assets") {
#ifndef __MQL5__
      if(g_tester) { Log("MT4 tester uses the tested chart symbol"); SaveAsset(); PaintPanel(); return; }
#endif
      SaveAsset(); g_auto=false; g_assetMode=(SXAssets)(((int)g_assetMode+1)%4);
      BuildUniverse(); ActivateAsset(0); if(BuildSnapshot()) SaveAsset();
      Log("Scope: "+ScopeName()+"; automatic entries paused"); ClearUI();
   }
   else if(action=="anchor") { g_right=!g_right; ClearUI(); }
   else if(action=="size") { g_size=(g_size+1)%5; ClearUI(); }
   else if(action=="msdec") { g_xeMainScalePct=(int)MathMax(65,g_xeMainScalePct-5); GlobalVariableSet(g_prefix+"xe_ms",g_xeMainScalePct); ClearUI(); Log("Main Dashboard scale "+IntegerToString(g_xeMainScalePct)+"%"); }
   else if(action=="msinc") { g_xeMainScalePct=(int)MathMin(150,g_xeMainScalePct+5); GlobalVariableSet(g_prefix+"xe_ms",g_xeMainScalePct); ClearUI(); Log("Main Dashboard scale "+IntegerToString(g_xeMainScalePct)+"%"); }
   else if(action=="mrst") { XEResetAllDashboards(); }
   else if(action=="collapse") { g_collapsed=!g_collapsed; ClearUI(); }
   else if(StringFind(action,"tab")==0 || action=="jump") {
      g_tab=action=="jump" ? (g_tab==3 ? 0 : 3) : (int)StringToInteger(StringSubstr(action,3));
      ClearUI();
   }
   else if(action=="prev" || action=="next") {
      int delta=action=="next" ? 1 : -1;
      if(g_tab==6) { int pages=(SG_ENGINE_COUNT+5)/6; g_enginePage=(g_enginePage+delta+pages)%pages; }
      if(g_tab==2) { int pages=(ArraySize(g_assets)+5)/6; if(pages>0) g_scanPage=(g_scanPage+delta+pages)%pages; }
      ClearUI();
   }
   else if(g_tab==6 && StringFind(action,"engine")==0) {
      int idx=(int)StringToInteger(StringSubstr(action,6));
      if(idx>=0 && idx<SG_ENGINE_COUNT) {
         g_consoleStrategy=(SXStrategy)idx;
         for(int i=0;i<ArraySize(g_assets);i++) { g_assets[i].candidate=0; g_assets[i].ready=false; }
         g_candidate=0; g_consoleReady=false;
         if(BuildSnapshot()) PaintChart();
         Log("Engine selected: "+EngineTitle(idx));
      }
   }
   else if(action=="theme" || action=="themePrev" || action=="familyPrev" || action=="familyNext" || action=="tstyle") {
      g_bpTheme=-1;
      int change=action=="theme" ? 1 : action=="themePrev" ? -1 : action=="familyNext" ? 12 : action=="familyPrev" ? -12 : 0;
      if(action=="tstyle") ApplyTheme(g_consoleTheme,(g_themeStyle+1)%16);
      else if(action=="familyPrev" || action=="familyNext") ApplyTheme(AdjacentFamily(g_consoleTheme,action=="familyNext" ? 1 : -1),g_themeStyle);
      else ApplyTheme(PaletteID(((g_consoleTheme==THEME_CUSTOM ? 0 : PaletteSlot(g_consoleTheme))+change+SG_PALETTE_COUNT)%SG_PALETTE_COUNT),g_themeStyle);
      RefreshLayers(); ClearUI(); Log(ConsoleThemeName(g_consoleTheme)+" / "+StyleName(g_themeStyle));
   }
   else if(g_tab==12 && StringFind(action,"part")==0) {
      int part=(int)StringToInteger(StringSubstr(action,4));
      if(part>=0 && part<10) { g_logoPart=part; g_logoNote="Enter #RRGGBB and press Enter."; ObjectDelete(0,g_prefix+"ui_logoHex"); }
   }
   else if(action=="logoReset" && g_tab==12) {
      LoadLogoInputs(); g_logoMode=(int)InpLogoMode;
      g_primaryGem=(int)InpPrimaryGem; g_accentGem=(int)InpAccentGem;
      g_logoNote="Input colours restored."; ObjectDelete(0,g_prefix+"ui_logoHex");
   }
   else if(action=="logoMode") {
      g_logoMode=(g_logoMode+1)%3; g_logoNote="Using "+LogoModeName()+".";
      ObjectDelete(0,g_prefix+"ui_logoHex");
   }
   else if(action=="mainGem" || action=="accentGem") {
      g_logoMode=LOGO_GEMSTONES;
      if(action=="mainGem") g_primaryGem=(g_primaryGem+1)%12; else g_accentGem=(g_accentGem+1)%12;
   }
   else if(action=="regOverlay") { g_regOverlay=!g_regOverlay; RefreshLayers(); }
   else if(action=="water") { g_watermark=!g_watermark; Log("Chart emblem "+Yes(g_watermark)); }
   else if(action=="strip") { g_strip=!g_strip; Log("Indicator strip "+Yes(g_strip)); }
   else if(action=="overlays") { g_layers=!g_layers; RefreshLayers(); Log("Chart layers "+Yes(g_layers)); }
   else if(action=="tmode") { g_trailMode=(g_trailMode+1)%36; Log(EnumToString((SXTrailMode)g_trailMode)); }
   else if(action=="buy" || action=="sell" || action=="buystop" || action=="sellstop" || action=="buylimit" || action=="selllimit") {
      if(ReadTicketLots(false)) {
         if(!g_consoleReady) BuildSnapshot();
         int d=(action=="buy" || action=="buystop" || action=="buylimit") ? 1 : -1;
         g_bpManualTrade=true;
         if(action=="buy" || action=="sell") OpenPosition(d,true);
         else PlacePending(d,(action=="buystop" || action=="sellstop") ? ENTRY_STOP : ENTRY_LIMIT,true,0);
         g_bpManualTrade=false;
      }
   }
   else if(action=="cancel") { if(CancelWorkingOrders()) Log("Pending orders cleared for "+g_symbol); }
   else if(action=="close") { g_auto=false; BeginSymbolExit("Manual symbol exit"); }
   else if(action=="partial") CloseOwned(0,true);
   else if(action=="be") ApplyPositiveBE();
   else if(action=="portfolio") {
      if(g_closePortArmed==0 || TimeCurrent()>g_closePortArmed) { g_closePortArmed=TimeCurrent()+5; Log("Press Exit portfolio again within five seconds"); }
      else { g_auto=false; RequestPortfolioExit("Manual portfolio exit"); g_closePortArmed=0; }
   }
   else if(action=="reconcile") {
      if(WorkingOrders()>0) Log("Review and clear working orders before reconciliation");
      else { g_uncertain=false; WriteGV("uncertain",0); WriteGV("inflight",0); Log("Chart symbol reconciled after broker review"); }
   }
   else if(action=="guard") {
      if(g_resetArmed==0 || TimeCurrent()>g_resetArmed) { g_resetArmed=TimeCurrent()+5; Log("Press Rebase equity again within five seconds"); }
      else if(PortfolioExposureCount()>0 || AnyUncertain()) Log("Close and reconcile owned exposure before rebasing");
      else {
         g_auto=false; g_consolePeakEquity=ConsoleEquity(); g_dayEquity=ConsoleEquity(); g_dailyLock=false; g_peakLock=false; g_profitLock=false;
         WriteGuard("peak",g_consolePeakEquity); WriteGuard("dayeq",g_dayEquity); WriteGuard("peaklock",0); WriteGuard("daylock",0); WriteGuard("profitlock",0);
         g_resetArmed=0; Log("Equity anchors rebased; auto paused");
      }
   }
   SaveAsset(); GlobalVariablesFlush(); PaintPanel(); BPPaintAll();
}
long SymbolHash(string text) {
   long value=2166136261;
   for(int i=0;i<StringLen(text);i++) value=((value^(long)StringGetCharacter(text,i))*16777619)&(long)4294967295;
   return value;
}
string StateKey(string symbol) {
   if(g_tester) return g_guardKey+"S"+IntegerToString(SymbolHash(symbol+"|"+IntegerToString((int)g_tf)))+"_";
   string context=AccountInfoString(ACCOUNT_SERVER)+"|"+IntegerToString(ConsoleMagic)+"|"+symbol+"|"+IntegerToString((int)g_tf);
   return "LRP_"+IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN))+"_"+IntegerToString(SymbolHash(context))+"_";
}
double ReadGuard(string suffix,double fallback) {
   return GlobalVariableCheck(g_guardKey+suffix) ? GlobalVariableGet(g_guardKey+suffix) : fallback;
}
void WriteGuard(string suffix,double value) { GlobalVariableSet(g_guardKey+suffix,value); }
string PendingKey(ulong ticket) {
   return g_guardKey+"P"+StringFormat("%I64u",ticket);
}
void SaveAsset() {
   if(g_active<0 || g_active>=ArraySize(g_assets)) return;
   SXAssetState a=g_assets[g_active];
   a.lastClosed=g_lastClosed; a.lastSignal=g_consoleLastSignalTime; a.lastMTF=g_lastMTF;
   a.raw=g_raw; a.candidate=g_candidate; a.lastDirection=g_lastSignalDir;
   a.scoreBuy=g_scoreBuy; a.scoreSell=g_scoreSell; a.tf1=g_tf1; a.tf2=g_tf2; a.zero=g_zeroTrend; a.superDir=g_superDir;
   a.mtf0=g_mtf[0]; a.mtf1=g_mtf[1]; a.mtf2=g_mtf[2]; a.mtf3=g_mtf[3]; a.mtf4=g_mtf[4];
   a.atr=g_atr; a.rsi=g_rsi; a.adx=g_adx; a.macd=g_macd; a.sma=g_sma; a.volume=g_volumeRatio;
   a.high=g_breakHigh; a.low=g_breakLow; a.pdh=g_pdh; a.pdl=g_pdl; a.pwh=g_pwh; a.pwl=g_pwl;
   a.pivot=g_pivot; a.r1=g_r1; a.s1=g_s1; a.dayOpen=g_dayOpen;
   a.ut=g_utCurrent; a.close=g_closeCurrent; a.vwap=g_vwap; a.superLine=g_superLine; a.superUpper=g_superUpper; a.superLower=g_superLower;
   a.stc=g_stc; a.cci=g_cci; a.stoch=g_stoch; a.atrRatio=g_atrRatio; a.bandUpper=g_bandUpper; a.bandLower=g_bandLower;
   a.basketPeak=g_basketPeak; a.basketLots=g_basketLots; a.note=g_message;
   a.stopPadding=g_stopPaddingPts;
   a.exiting=g_exitRequested; a.uncertain=g_uncertain; a.ready=g_consoleReady;
   if(g_snapshotSymbol==g_symbol) {
      a.priorAtr=g_cachedAtrPrior; a.fastEMA=g_cachedFast; a.slowEMA=g_cachedSlow;
      a.priorLo=g_prevLo; a.priorHi=g_prevHi; a.lo8=g_lo8; a.hi8=g_hi8;
      a.quantumER=g_quantumER; a.quantumLine=g_quantumSuperLine; a.drm=g_drmValue; a.coral=g_coralEMA;
      a.dailyMA=g_d1MA; a.deltaTrap=g_deltaTrapSig; a.quantumDir=g_quantumSuperDir;
      a.fvgBuy=FVGExists(1); a.fvgSell=FVGExists(-1);
      a.gem=g_gem;
      for(int i=0;i<SG_ENGINE_COUNT;i++) a.engines[i]=g_engineSignals[i];
      a.rrTrail=g_rrTrail; a.rrEMA=g_rrEMA; a.hull=g_hull; a.tenkan=g_tenkan; a.kijun=g_kijun; a.spanB=g_spanB;
      a.mfi=g_mfi; a.obv=g_obv; a.ensembleConfidence=g_ensembleConfidence; a.kalman=g_kalman; a.velocity=g_velocity; a.orderFlowDelta=g_orderFlowDelta;
      a.rrCross=g_rrCross; a.rrState=g_rrState; a.ensembleVotes=g_ensembleVotes; a.ensembleActive=g_ensembleActive; a.ensembleDir=g_ensembleDir; a.kalmanDir=g_kalmanDir; a.stopStage=g_stopStage;
   }
   g_assets[g_active]=a;
}
void ActivateAsset(int index) {
   g_active=index; SXAssetState a=g_assets[index];
   g_symbol=a.symbol; g_key=a.key; g_gem=a.gem;
   g_cachedAtrPrior=a.priorAtr; g_cachedFast=a.fastEMA; g_cachedSlow=a.slowEMA;
   g_prevLo=a.priorLo; g_prevHi=a.priorHi; g_lo8=a.lo8; g_hi8=a.hi8;
   g_quantumER=a.quantumER; g_quantumSuperLine=a.quantumLine; g_drmValue=a.drm; g_coralEMA=a.coral;
   g_d1MA=a.dailyMA; g_deltaTrapSig=a.deltaTrap; g_quantumSuperDir=a.quantumDir; g_stopPaddingPts=a.stopPadding;
   g_exitRequested=a.exiting; g_uncertain=a.uncertain; g_consoleReady=a.ready;
   g_consolePoint=SymbolInfoDouble(g_symbol,SYMBOL_POINT); g_consoleDigits=(int)SymbolInfoInteger(g_symbol,SYMBOL_DIGITS);
   g_lastClosed=a.lastClosed; g_consoleLastSignalTime=a.lastSignal; g_lastMTF=a.lastMTF;
   g_raw=a.raw; g_candidate=a.candidate; g_lastSignalDir=a.lastDirection;
   g_scoreBuy=a.scoreBuy; g_scoreSell=a.scoreSell; g_tf1=a.tf1; g_tf2=a.tf2; g_zeroTrend=a.zero; g_superDir=a.superDir;
   g_mtf[0]=a.mtf0; g_mtf[1]=a.mtf1; g_mtf[2]=a.mtf2; g_mtf[3]=a.mtf3; g_mtf[4]=a.mtf4;
   g_atr=a.atr; g_rsi=a.rsi; g_adx=a.adx; g_macd=a.macd; g_sma=a.sma; g_volumeRatio=a.volume;
   g_breakHigh=a.high; g_breakLow=a.low; g_pdh=a.pdh; g_pdl=a.pdl; g_pwh=a.pwh; g_pwl=a.pwl;
   g_pivot=a.pivot; g_r1=a.r1; g_s1=a.s1; g_dayOpen=a.dayOpen;
   g_utCurrent=a.ut; g_closeCurrent=a.close; g_vwap=a.vwap; g_superLine=a.superLine; g_superUpper=a.superUpper; g_superLower=a.superLower;
   g_stc=a.stc; g_cci=a.cci; g_stoch=a.stoch; g_atrRatio=a.atrRatio; g_bandUpper=a.bandUpper; g_bandLower=a.bandLower;
   g_basketPeak=a.basketPeak; g_basketLots=a.basketLots; g_message=a.note;
   for(int i=0;i<SG_ENGINE_COUNT;i++) g_engineSignals[i]=a.engines[i];
   g_rrTrail=a.rrTrail; g_rrEMA=a.rrEMA; g_hull=a.hull; g_tenkan=a.tenkan; g_kijun=a.kijun; g_spanB=a.spanB;
   g_mfi=a.mfi; g_obv=a.obv; g_ensembleConfidence=a.ensembleConfidence; g_kalman=a.kalman; g_velocity=a.velocity; g_orderFlowDelta=a.orderFlowDelta;
   g_rrCross=a.rrCross; g_rrState=a.rrState; g_ensembleVotes=a.ensembleVotes; g_ensembleActive=a.ensembleActive; g_ensembleDir=a.ensembleDir; g_kalmanDir=a.kalmanDir; g_stopStage=a.stopStage;
   ConsoleLoadPositions();
}
void AddAsset(string symbol,bool enabled) {
   StringTrimLeft(symbol); StringTrimRight(symbol); if(symbol=="") return;
   for(int i=0;i<ArraySize(g_assets);i++) if(g_assets[i].symbol==symbol) { if(enabled) g_assets[i].enabled=true; return; }
   if(!SymbolSelect(symbol,true) && symbol!=g_chartSymbol) { Log("Symbol unavailable: "+symbol); return; }
   if(enabled && InpMaxSymbols>0) {
      int trading=0; for(int i=0;i<ArraySize(g_assets);i++) if(g_assets[i].enabled) trading++;
      if(trading>=InpMaxSymbols) return;
   }
   SXAssetState a; ZeroMemory(a); a.symbol=symbol; a.enabled=enabled; a.key=StateKey(symbol); a.note="Waiting for history";
   a.lastClosed=InpTradeOnAttach ? 0 : iTime(symbol,g_tf,1);
   if(!InpTradeOnAttach && a.lastClosed>0) GlobalVariableSet(a.key+"skipbar",(double)a.lastClosed);
   if(InpTradeOnAttach && GlobalVariableCheck(a.key+"skipbar")) GlobalVariableSet(a.key+"skipbar",0);
   a.lastSignal=(datetime)(GlobalVariableCheck(a.key+"signal") ? GlobalVariableGet(a.key+"signal") : 0);
   a.uncertain=(GlobalVariableCheck(a.key+"uncertain") && GlobalVariableGet(a.key+"uncertain")>0) ||
      (GlobalVariableCheck(a.key+"inflight") && GlobalVariableGet(a.key+"inflight")>0);
   if(a.uncertain) GlobalVariableSet(a.key+"uncertain",1);
   a.exiting=GlobalVariableCheck(a.key+"exit") && GlobalVariableGet(a.key+"exit")>0;
   a.basketPeak=GlobalVariableCheck(a.key+"basket") ? GlobalVariableGet(a.key+"basket") : 0;
   a.basketLots=GlobalVariableCheck(a.key+"basketlots") ? GlobalVariableGet(a.key+"basketlots") : 0;
   int n=ArraySize(g_assets); ArrayResize(g_assets,n+1); g_assets[n]=a;
}
void BuildUniverse() {
   ArrayResize(g_assets,0); g_cursor=0; g_scanPage=0; g_catalogCursor=0; g_catalogDone=0;
   AddAsset(g_chartSymbol,g_assetMode==ASSET_CHART || g_assetMode==ASSET_BROKER);
   if(g_assetMode==ASSET_BROKER) DiscoverBroker(InpScanBatch);
   if(g_assetMode==ASSET_MARKETWATCH) {
      int total=SymbolsTotal(true);
      for(int i=0;i<total;i++) {
         string name=SymbolName(i,true);
         int mode=AllowedTradeMode(name);
         if(mode!=SYMBOL_TRADE_MODE_DISABLED && mode!=SYMBOL_TRADE_MODE_CLOSEONLY) AddAsset(name,true);
      }
   } else if(g_assetMode==ASSET_CUSTOM) {
      string parts[]; int n=StringSplit(InpSymbols,StringGetCharacter(",",0),parts);
      for(int i=0;i<n;i++) AddAsset(parts[i],true);
   }
   // Retain management contexts for owned positions outside a changed entry universe.
#ifdef __MQL5__
   for(int i=0;i<PositionsTotal();i++) if(PositionGetTicket(i)>0 && PositionGetInteger(POSITION_MAGIC)==ConsoleMagic) AddAsset(PositionGetString(POSITION_SYMBOL),false);
   for(int i=0;i<OrdersTotal();i++) if(OrderGetTicket(i)>0 && OrderGetInteger(ORDER_MAGIC)==ConsoleMagic) AddAsset(OrderGetString(ORDER_SYMBOL),false);
#else
   for(int i=0;i<OrdersTotal();i++) if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber()==ConsoleMagic) AddAsset(OrderSymbol(),false);
#endif
}
double ConsoleSeriesEMA(double &src[],int end,int period) {
   double result=src[0],alpha=2.0/(period+1);
   for(int i=1;i<=end;i++) result+=alpha*(src[i]-result);
   return result;
}
void BandValues(int end,double &mid,double &upper,double &lower) {
   mid=0; upper=0; lower=0; if(end<InpBandPeriod-1) return;
   for(int i=end-InpBandPeriod+1;i<=end;i++) mid+=g_rates[i].close/InpBandPeriod;
   double variance=0; for(int i=end-InpBandPeriod+1;i<=end;i++) variance+=MathPow(g_rates[i].close-mid,2)/InpBandPeriod;
   double deviation=MathSqrt(variance)*InpBandDeviation; upper=mid+deviation; lower=mid-deviation;
}
bool ConfirmedPivot(int index,bool low,int end) {
   if(index<InpPivotLeft || index+InpPivotRight>end) return false;
   double value=low ? g_rates[index].low : g_rates[index].high;
   for(int i=index-InpPivotLeft;i<=index+InpPivotRight;i++) if(i!=index) {
      if(low && g_rates[i].low<=value) return false;
      if(!low && g_rates[i].high>=value) return false;
   }
   return true;
}
int SweepSignal() {
   int n=g_n-1; bool buy=false,sell=false;
   for(int i=n-1-InpPivotRight;i>=(int)MathMax(InpPivotLeft,n-InpSwingLookback);i--) if(ConfirmedPivot(i,true,n-1)) {
      buy=g_rates[n].low<g_rates[i].low && g_rates[n].close>g_rates[i].low; break;
   }
   for(int i=n-1-InpPivotRight;i>=(int)MathMax(InpPivotLeft,n-InpSwingLookback);i--) if(ConfirmedPivot(i,false,n-1)) {
      sell=g_rates[n].high>g_rates[i].high && g_rates[n].close<g_rates[i].high; break;
   }
   return buy==sell ? 0 : buy ? 1 : -1;
}
int ClockVote(int k) {
   // During BuildExtendedSignals(), g_consoleReady is set only after this matrix is built.
   // Permit that first pass when ATR is initialized, but reject invalid indices/unready data.
   if(k<0 || k>=9 || (!g_consoleReady && g_atr<=0)) return 0;
   if(k==0) return Direction(g_cachedFast-g_cachedSlow);
   if(k==1) return Direction(g_rsi-50.0);
   if(k==2) return Direction(g_macd);
   if(k==3) return g_superDir;
   if(k==4) return Direction(g_orderFlowDelta);
   if(k==5) return (g_vwap>0 && g_closeCurrent>0) ? Direction(g_closeCurrent-g_vwap) : 0;
   if(k==6) return Direction(g_stc-50.0);
   if(k==7) return g_kalmanDir;
   if(k==8) return (g_utCurrent>0 && g_closeCurrent>0) ? Direction(g_closeCurrent-g_utCurrent) : 0;
   return 0;
}
int ClockVotes(int side) {
   int count=0;
   for(int i=0;i<9;i++) if(ClockVote(i)==side) count++;
   return count;
}
int ClockBias() {
   int buys=ClockVotes(1),sells=ClockVotes(-1);
   return buys>sells ? 1 : sells>buys ? -1 : 0;
}

void BuildExtendedSignals() {
   int n=g_n,last=n-1;
   ArrayResize(g_vwapSeries,n); ArrayResize(g_superSeries,n); ArrayResize(g_stcSeries,n); ArrayResize(g_rsiSeries,n); ArrayResize(g_utEvents,n); ArrayResize(g_superDirections,n);
   double macd[],first[],smoothed[],second[],stATR[];
   ArrayResize(macd,n); ArrayResize(first,n); ArrayResize(smoothed,n); ArrayResize(second,n); ArrayResize(stATR,n);
   double fast=0,slow=0,gain=0,loss=0,stAtr=0,trSum=0,up=0,down=0,pv=0,vol=0;
   double haOpen=0,haClose=0,lastHAOpen=0,lastHAClose=0,previousUp=0,previousDown=0;
   int direction=1,previousDirection=1,zeroPrevious=0,zeroDirection=0;
   datetime anchor=0; int offset=InpVWAPAnchorHour*3600+InpVWAPAnchorMinute*60;
   for(int i=0;i<n;i++) {
      double c=g_rates[i].close,prev=i>0 ? g_rates[i-1].close : c,src=Source(g_rates[i]);
      datetime barAnchor=(datetime)(((long)g_rates[i].time-offset)/86400*86400+offset);
      if(i==0 || barAnchor!=anchor) { anchor=barAnchor; pv=0; vol=0; }
      double volume=InpUseRealVolume && g_rates[i].real_volume>0 ? (double)g_rates[i].real_volume : (double)g_rates[i].tick_volume;
      pv+=(g_rates[i].high+g_rates[i].low+c)/3.0*volume; vol+=volume;
      g_vwapSeries[i]=vol>0 ? pv/vol : 0;
      lastHAOpen=haOpen; lastHAClose=haClose;
      haClose=(g_rates[i].open+g_rates[i].high+g_rates[i].low+c)/4.0;
      haOpen=i==0 ? (g_rates[i].open+c)/2.0 : (lastHAOpen+lastHAClose)/2.0;
      if(i==0) { fast=src; slow=src; } else { fast+=2.0/(InpStcFast+1)*(src-fast); slow+=2.0/(InpStcSlow+1)*(src-slow); }
      macd[i]=fast-slow;
      double lo=macd[i],hi=macd[i]; int begin=(int)MathMax(0,i-InpStcCycle+1);
      for(int j=begin;j<i;j++) { lo=MathMin(lo,macd[j]); hi=MathMax(hi,macd[j]); }
      first[i]=hi>lo ? 100*(macd[i]-lo)/(hi-lo) : i>0 ? first[i-1] : 0;
      smoothed[i]=i>0 ? smoothed[i-1]+InpStcSmooth*(first[i]-smoothed[i-1]) : first[i];
      lo=smoothed[i]; hi=smoothed[i];
      for(int j=begin;j<i;j++) { lo=MathMin(lo,smoothed[j]); hi=MathMax(hi,smoothed[j]); }
      second[i]=hi>lo ? 100*(smoothed[i]-lo)/(hi-lo) : i>0 ? second[i-1] : 0;
      g_stcSeries[i]=i>0 ? g_stcSeries[i-1]+InpStcSmooth*(second[i]-g_stcSeries[i-1]) : second[i];
      g_stcSeries[i]=MathMax(0,MathMin(100,g_stcSeries[i]));
      double tr=SXTrueRange(g_rates[i].high,g_rates[i].low,prev); trSum+=tr;
      if(i==InpSuperPeriod-1) stAtr=trSum/InpSuperPeriod;
      else if(i>=InpSuperPeriod) stAtr=SXWilder(stAtr,tr,InpSuperPeriod);
      stATR[i]=stAtr; previousDirection=direction; previousUp=up; previousDown=down;
      if(i>=InpSuperPeriod-1) {
         double mid=(g_rates[i].high+g_rates[i].low)/2.0;
         double lower=mid-InpSuperMultiplier*stAtr,upper=mid+InpSuperMultiplier*stAtr;
         up=i==InpSuperPeriod-1 ? lower : prev>previousUp ? MathMax(lower,previousUp) : lower;
         down=i==InpSuperPeriod-1 ? upper : prev<previousDown ? MathMin(upper,previousDown) : upper;
         if(i>InpSuperPeriod-1) direction=c>previousDown ? 1 : c<previousUp ? -1 : direction;
      }
      g_superDirections[i]=direction; g_superSeries[i]=direction>0 ? up : down;
      if(i>0) {
         double delta=c-prev;
         if(i<=ConsoleRSIPeriod) { gain+=MathMax(0,delta)/ConsoleRSIPeriod; loss+=MathMax(0,-delta)/ConsoleRSIPeriod; }
         else { gain=SXWilder(gain,MathMax(0,delta),ConsoleRSIPeriod); loss=SXWilder(loss,MathMax(0,-delta),ConsoleRSIPeriod); }
      }
      g_rsiSeries[i]=(gain+loss)<1e-12 ? 50 : loss<1e-12 ? 100 : 100-100/(1+gain/loss);
      g_utEvents[i]=i>InpATRPeriod-1 ? SXCross(src,Source(g_rates[i-1]),g_utSeries[i],g_utSeries[i-1]) : 0;
      if(i==n-2) zeroPrevious=zeroDirection;
      if(g_atrSeries[i]>0 && c>g_zeroSeries[i]+InpZeroLagBandATR*g_atrSeries[i]) zeroDirection=1;
      if(g_atrSeries[i]>0 && c<g_zeroSeries[i]-InpZeroLagBandATR*g_atrSeries[i]) zeroDirection=-1;
      if(i==n-2) zeroPrevious=zeroDirection;
   }
   g_utCurrent=g_utSeries[last]; g_closeCurrent=g_rates[last].close;
   g_vwap=g_vwapSeries[last];
   bool vwapComplete=(g_vwap>0 && g_rates[0].time<=anchor);
   g_superDir=direction; g_superLine=g_superSeries[last]; g_superUpper=down; g_superLower=up; g_stc=g_stcSeries[last];
   int bp=(int)MathMin(n,MathMax(1,InpBandPeriod)); double typicalMean=0; for(int i=n-bp;i<n;i++) typicalMean+=(g_rates[i].high+g_rates[i].low+g_rates[i].close)/3.0/bp;
   double deviation=0; for(int i=n-bp;i<n;i++) deviation+=MathAbs((g_rates[i].high+g_rates[i].low+g_rates[i].close)/3.0-typicalMean)/bp;
   g_cci=deviation>0 ? ((g_rates[last].high+g_rates[last].low+g_closeCurrent)/3.0-typicalMean)/(0.015*deviation) : 0;
   double high=g_rates[last].high,low=g_rates[last].low;
   for(int i=(int)MathMax(0,n-14);i<n;i++) { high=MathMax(high,g_rates[i].high); low=MathMin(low,g_rates[i].low); }
   g_stoch=high>low ? 100*(g_closeCurrent-low)/(high-low) : 50;
   int amp=(int)MathMin(n,MathMax(1,InpATRMeanPeriod)); double meanATR=0; for(int i=n-amp;i<n;i++) meanATR+=g_atrSeries[i]/amp;
   g_atrRatio=meanATR>0 ? g_atr/meanATR : 0;
   double mid=0,prevMid=0,prevUpper=0,prevLower=0; BandValues(last,mid,g_bandUpper,g_bandLower); BandValues(last-1,prevMid,prevUpper,prevLower);
   int ut=g_raw,br=g_closeCurrent>g_breakHigh ? 1 : g_closeCurrent<g_breakLow ? -1 : 0;
   int pull=g_candidate; if(g_consoleStrategy!=TREND_PULLBACK) {
      pull=0;
      if(g_fastSeries[last]>g_slowSeries[last] && g_rates[last-1].close<=g_fastSeries[last-1] && g_closeCurrent>g_fastSeries[last]) pull=1;
      if(g_fastSeries[last]<g_slowSeries[last] && g_rates[last-1].close>=g_fastSeries[last-1] && g_closeCurrent<g_fastSeries[last]) pull=-1;
   }
   for(int i=0;i<SG_ENGINE_COUNT;i++) g_engineSignals[i]=0;
   g_engineSignals[UT_REVERSAL]=ut; g_engineSignals[UT_CONFLUENCE]=ut; g_engineSignals[LEVEL_BREAKOUT]=br; g_engineSignals[TREND_PULLBACK]=pull;
   g_engineSignals[UT_VWAP]=vwapComplete && ut*(g_closeCurrent-g_vwap)>0 ? ut : 0;
   g_engineSignals[HA_IMPULSE_VWAP]=vwapComplete && MathAbs(haClose-haOpen)>=InpHAImpulseATR*g_atr ? (haClose>haOpen && g_closeCurrent>g_vwap ? 1 : haClose<haOpen && g_closeCurrent<g_vwap ? -1 : 0) : 0;
   g_engineSignals[SUPERTREND_FLIP]=direction!=previousDirection ? direction : 0;
   int stcNow=g_stcSeries[last]>InpStcBuyZone && g_stcSeries[last-1]<=InpStcBuyZone ? 1 : g_stcSeries[last]<InpStcSellZone && g_stcSeries[last-1]>=InpStcSellZone ? -1 : 0;
   int stcRecent=stcNow,utRecent=ut;
   for(int i=last-1;i>=(int)MathMax(1,last-InpStcLag);i--) {
      if(stcRecent==0) stcRecent=g_stcSeries[i]>InpStcBuyZone && g_stcSeries[i-1]<=InpStcBuyZone ? 1 : g_stcSeries[i]<InpStcSellZone && g_stcSeries[i-1]>=InpStcSellZone ? -1 : 0;
      if(utRecent==0) utRecent=g_utEvents[i];
   }
   g_engineSignals[UT_STC]=ut!=0 && ut==stcRecent ? ut : stcNow!=0 && stcNow==utRecent ? stcNow : 0;
   g_engineSignals[LIQUIDITY_SWEEP]=SweepSignal();
   int emaCross=SXCross(g_fastSeries[last],g_fastSeries[last-1],g_slowSeries[last],g_slowSeries[last-1]);
   g_engineSignals[EMA_CROSS]=g_adx>=InpMinADX && g_atrRatio>=InpMinATRRatio && g_atrRatio<=InpMaxATRRatio ? emaCross : 0;
   double ema12=0,ema26=0,signal=0,previousHist=0;
   for(int i=0;i<n;i++) {
      if(i==0) { ema12=g_rates[i].close; ema26=ema12; }
      else { ema12+=2.0/13*(g_rates[i].close-ema12); ema26+=2.0/27*(g_rates[i].close-ema26); }
      signal+=2.0/10*(ema12-ema26-signal); if(i==n-2) previousHist=ema12-ema26-signal;
   }
   g_engineSignals[MACD_CROSS]=g_macd>0 && previousHist<=0 && g_rsi>50 ? 1 : g_macd<0 && previousHist>=0 && g_rsi<50 ? -1 : 0;
   if(g_adx<=InpRangeADXMax) {
      if(g_rates[last].low<g_bandLower && g_closeCurrent>g_bandLower && g_rsi<45 && g_cci<-50) g_engineSignals[RANGE_REVERSION]=1;
      if(g_rates[last].high>g_bandUpper && g_closeCurrent<g_bandUpper && g_rsi>55 && g_cci>50) g_engineSignals[RANGE_REVERSION]=-1;
   }
   g_engineSignals[RSI_REENTRY]=g_rsiSeries[last]>30 && g_rsiSeries[last-1]<=30 ? 1 : g_rsiSeries[last]<70 && g_rsiSeries[last-1]>=70 ? -1 : 0;
   g_engineSignals[SQUEEZE_BREAKOUT]=prevUpper-prevLower<2.5*g_atr && g_bandUpper-g_bandLower>prevUpper-prevLower ? br : 0;
   int pivotIndex=last-InpPivotRight;
   bool pivotLow=ConfirmedPivot(pivotIndex,true,last),pivotHigh=ConfirmedPivot(pivotIndex,false,last);
   g_engineSignals[PIVOT_RSI]=pivotLow && g_rsiSeries[pivotIndex]<=InpPivotRSILow ? 1 : pivotHigh && g_rsiSeries[pivotIndex]>=InpPivotRSIHigh ? -1 : 0;
   if(g_adx<=InpRangeADXMax) {
      if(g_rates[last].low<=g_breakLow+0.2*g_atr && g_closeCurrent>g_breakLow && g_closeCurrent>g_rates[last].open && g_rsiSeries[last-1]<=InpPivotRSILow && g_rsi>g_rsiSeries[last-1]) g_engineSignals[CYCLE_REVERSAL]=1;
      if(g_rates[last].high>=g_breakHigh-0.2*g_atr && g_closeCurrent<g_breakHigh && g_closeCurrent<g_rates[last].open && g_rsiSeries[last-1]>=InpPivotRSIHigh && g_rsi<g_rsiSeries[last-1]) g_engineSignals[CYCLE_REVERSAL]=-1;
   }
   bool bounceBuy=false,bounceSell=false; double levels[7];
   levels[0]=g_pdh; levels[1]=g_pdl; levels[2]=g_pwh; levels[3]=g_pwl; levels[4]=g_pivot; levels[5]=g_r1; levels[6]=g_s1;
   for(int i=0;i<7;i++) if(levels[i]>0) {
      if(g_rates[last].low<levels[i] && g_closeCurrent>levels[i] && g_closeCurrent>g_rates[last].open) bounceBuy=true;
      if(g_rates[last].high>levels[i] && g_closeCurrent<levels[i] && g_closeCurrent<g_rates[last].open) bounceSell=true;
   }
   g_engineSignals[LEVEL_BOUNCE]=bounceBuy==bounceSell ? 0 : bounceBuy ? 1 : -1;
   double body=g_closeCurrent-g_rates[last].open;
   bool engulfBuy=body>0 && g_rates[last-1].close<g_rates[last-1].open && g_rates[last].open<=g_rates[last-1].close && g_closeCurrent>=g_rates[last-1].open;
   bool engulfSell=body<0 && g_rates[last-1].close>g_rates[last-1].open && g_rates[last].open>=g_rates[last-1].close && g_closeCurrent<=g_rates[last-1].open;
   g_engineSignals[IMPULSE_ENGULF]=MathAbs(body)>=0.6*g_atr ? (engulfBuy ? 1 : engulfSell ? -1 : 0) : 0;
   g_engineSignals[STC_CROSS]=stcNow;
   g_engineSignals[VWAP_CROSS]=vwapComplete ? SXCross(g_closeCurrent,g_rates[last-1].close,g_vwap,g_vwapSeries[last-1]) : 0;
   g_engineSignals[ZERO_LAG_FLIP]=zeroDirection!=zeroPrevious ? zeroDirection : 0;
   g_engineSignals[TREND_CONTINUATION]=g_adx>=InpMinADX ? (g_fastSeries[last]>g_slowSeries[last] && g_rsi>=45 && g_rsi<=68 && g_macd>=0 ? 1 : g_fastSeries[last]<g_slowSeries[last] && g_rsi>=32 && g_rsi<=55 && g_macd<=0 ? -1 : 0) : 0;
   g_engineSignals[SUPERTREND_STOP]=-direction;
   int votes=ut+br+pull+g_engineSignals[SUPERTREND_FLIP]+g_engineSignals[LIQUIDITY_SWEEP];
   g_engineSignals[CONSENSUS]=votes>=2 ? 1 : votes<=-2 ? -1 : 0;

   // Engine 24: UT Bot - ATR Trailing Stop (lDGmh7ou by QuantNomad)
   int utState=Source(g_rates[last])>g_utCurrent ? 1 : Source(g_rates[last])<g_utCurrent ? -1 : 0;
   g_engineSignals[UT_BOT_ATR_TRAIL]=ut!=0 ? ut : (InpInstantStateEntry ? utState : 0);

   // Engine 25: Strategy for UT Bot Alerts indicator (RRnsvSZR by StrategiesForEveryone)
   double rrAtr=0,rrTrSum=0,rrStop=0,rrPrevStop=0,rrPrevSrc=0,rrEma=0;
   int rrP=(int)MathMax(1,InpRRATRPeriod),rrEmaP=(int)MathMax(2,InpRREMAPeriod);
   for(int i=0;i<n;i++) {
      double c=g_rates[i].close,prev=i>0 ? g_rates[i-1].close : c;
      double tr=SXTrueRange(g_rates[i].high,g_rates[i].low,prev);
      rrTrSum+=tr;
      if(i==rrP-1) rrAtr=rrTrSum/rrP;
      else if(i>=rrP) rrAtr=SXWilder(rrAtr,tr,rrP);
      double rrSrc=InpRRUseHeikinAshi ? (g_rates[i].open+g_rates[i].high+g_rates[i].low+c)/4.0 : Source(g_rates[i]);
      if(i<rrP-1) { rrStop=rrSrc; rrPrevSrc=rrSrc; }
      else if(i==rrP-1) { rrStop=rrSrc-InpRRKeyValue*rrAtr; rrPrevStop=rrStop; rrPrevSrc=rrSrc; }
      else {
         rrPrevStop=rrStop;
         rrStop=SXUTStep(rrSrc,rrPrevSrc,rrStop,InpRRKeyValue*rrAtr);
         if(i==last) g_rrCross=SXCross(rrSrc,rrPrevSrc,rrStop,rrPrevStop);
         rrPrevSrc=rrSrc;
      }
      if(i==0) rrEma=c; else rrEma+=2.0/(rrEmaP+1.0)*(c-rrEma);
   }
   g_rrTrail=rrStop; g_rrEMA=rrEma;
   double rrLastSrc=InpRRUseHeikinAshi ? (g_rates[last].open+g_rates[last].high+g_rates[last].low+g_closeCurrent)/4.0 : Source(g_rates[last]);
   g_rrState=(rrLastSrc>g_rrTrail && g_closeCurrent>g_rrEMA) ? 1 : (rrLastSrc<g_rrTrail && g_closeCurrent<g_rrEMA) ? -1 : 0;
   if(g_rrCross>0 && g_closeCurrent>g_rrEMA) g_engineSignals[UT_ALERTS_STRATEGY_RR]=1;
   else if(g_rrCross<0 && g_closeCurrent<g_rrEMA) g_engineSignals[UT_ALERTS_STRATEGY_RR]=-1;
   else if(InpInstantStateEntry) g_engineSignals[UT_ALERTS_STRATEGY_RR]=g_rrState;

   // Engine 26 & 27: DIRECTIONAL ENSEMBLE 30-Strategy Quant Ensemble + Hull MA + Ichimoku + MFI + OBV
   int hullP=(int)MathMax(4,InpHullPeriod),halfP=hullP/2,rootP=(int)MathMax(2,MathSqrt(hullP));
   double hullNow=0,hullPrev=0,wSumRoot=0;
   for(int r=0;r<rootP;r++) {
      int idxNow=last-r,idxPrev=last-1-r;
      if(idxPrev<hullP) break;
      double wmaHalfNow=0,wmaFullNow=0,wmaHalfPrev=0,wmaFullPrev=0,dHalf=0,dFull=0;
      for(int k=0;k<halfP;k++) { double w=halfP-k; wmaHalfNow+=g_rates[idxNow-k].close*w; wmaHalfPrev+=g_rates[idxPrev-k].close*w; dHalf+=w; }
      for(int k=0;k<hullP;k++) { double w=hullP-k; wmaFullNow+=g_rates[idxNow-k].close*w; wmaFullPrev+=g_rates[idxPrev-k].close*w; dFull+=w; }
      double rw=rootP-r;
      hullNow+=rw*(2.0*(wmaHalfNow/dHalf)-(wmaFullNow/dFull));
      hullPrev+=rw*(2.0*(wmaHalfPrev/dHalf)-(wmaFullPrev/dFull));
      wSumRoot+=rw;
   }
   g_hull=wSumRoot>0 ? hullNow/wSumRoot : g_closeCurrent;
   double hullOld=wSumRoot>0 ? hullPrev/wSumRoot : g_rates[last-1].close;
   double hi9=g_rates[last].high,lo9=g_rates[last].low,hi26=g_rates[last].high,lo26=g_rates[last].low,hi52=g_rates[last].high,lo52=g_rates[last].low;
   for(int i=(int)MathMax(0,n-9);i<n;i++) { hi9=MathMax(hi9,g_rates[i].high); lo9=MathMin(lo9,g_rates[i].low); }
   for(int i=(int)MathMax(0,n-26);i<n;i++) { hi26=MathMax(hi26,g_rates[i].high); lo26=MathMin(lo26,g_rates[i].low); }
   for(int i=(int)MathMax(0,n-52);i<n;i++) { hi52=MathMax(hi52,g_rates[i].high); lo52=MathMin(lo52,g_rates[i].low); }
   g_tenkan=(hi9+lo9)/2.0; g_kijun=(hi26+lo26)/2.0; g_spanB=(hi52+lo52)/2.0;
   double posFlow=0,negFlow=0,obvSum=0;
   for(int i=(int)MathMax(1,n-14);i<n;i++) {
      double tpNow=(g_rates[i].high+g_rates[i].low+g_rates[i].close)/3.0;
      double tpOld=(g_rates[i-1].high+g_rates[i-1].low+g_rates[i-1].close)/3.0;
      double fl=tpNow*(double)g_rates[i].tick_volume;
      if(tpNow>tpOld) posFlow+=fl; else if(tpNow<tpOld) negFlow+=fl;
   }
   g_mfi=(posFlow+negFlow)<1e-12 ? 50.0 : negFlow<1e-12 ? 100.0 : 100.0-100.0/(1.0+posFlow/negFlow);
   for(int i=(int)MathMax(1,n-20);i<n;i++) {
      if(g_rates[i].close>g_rates[i-1].close) obvSum+=(double)g_rates[i].tick_volume;
      else if(g_rates[i].close<g_rates[i-1].close) obvSum-=(double)g_rates[i].tick_volume;
   }
   g_obv=obvSum;
   int hullIchi=0;
   if(g_closeCurrent>g_hull && g_hull>hullOld && g_tenkan>=g_kijun && g_mfi>=48) hullIchi=1;
   else if(g_closeCurrent<g_hull && g_hull<hullOld && g_tenkan<=g_kijun && g_mfi<=52) hullIchi=-1;
   g_engineSignals[ENSEMBLE_HULL_ICHIMOKU]=hullIchi;

   // Evaluate 30-sub-strategy Ensemble Quant Ensemble votes
   int tBuys=0,tSells=0;
   for(int k=0;k<24;k++) { if(g_engineSignals[k]>0) tBuys++; else if(g_engineSignals[k]<0) tSells++; }
   if(utState>0) tBuys++; else if(utState<0) tSells++;
   if(g_rrState>0) tBuys++; else if(g_rrState<0) tSells++;
   if(hullIchi>0) tBuys++; else if(hullIchi<0) tSells++;
   if(g_obv>0 && g_closeCurrent>g_fastSeries[last]) tBuys++; else if(g_obv<0 && g_closeCurrent<g_fastSeries[last]) tSells++;
   if(g_superDir>0) tBuys++; else if(g_superDir<0) tSells++;
   if(g_fastSeries[last]>g_slowSeries[last]) tBuys++; else if(g_fastSeries[last]<g_slowSeries[last]) tSells++;
   g_ensembleActive=tBuys+tSells;
   g_ensembleVotes=tBuys>tSells ? tBuys : (tSells>tBuys ? -tSells : 0);
   double tTrend=MathMin(1.0,g_adx/45.0),tMom=MathMin(1.0,MathAbs(g_rsi-50.0)/35.0),tVol=MathMin(1.0,g_volumeRatio/2.0);
   g_ensembleConfidence=g_ensembleActive>0 ? MathMin(0.99,0.48+0.18*tTrend+0.16*tMom+0.12*tVol+0.05*(MathAbs(g_ensembleVotes)/(double)MathMax(1,g_ensembleActive))) : 0;
   g_ensembleDir=(MathAbs(g_ensembleVotes)>=InpEnsembleMinVotes && g_ensembleConfidence>=InpEnsembleMinConfidence) ? (g_ensembleVotes>0 ? 1 : -1) : 0;
   g_engineSignals[ENSEMBLE_QUANT_ENSEMBLE]=g_ensembleDir;

   // Engine 28: TREND_CYCLE_HYBRID (trend grid + Dark Cycle Plus + Multi-filter)
   int vk=0;
   if((g_engineSignals[LIQUIDITY_SWEEP]>0 || g_engineSignals[CYCLE_REVERSAL]>0 || g_zeroTrend>0) && g_fastSeries[last]>=g_slowSeries[last] && g_rsi>=48) vk=1;
   else if((g_engineSignals[LIQUIDITY_SWEEP]<0 || g_engineSignals[CYCLE_REVERSAL]<0 || g_zeroTrend<0) && g_fastSeries[last]<=g_slowSeries[last] && g_rsi<=52) vk=-1;
   g_engineSignals[TREND_CYCLE_HYBRID]=vk;

   // Engine 29: INSTANT_MANDATORY_BLITZ (Pure mandatory opens trades instantly - never 0 when history ready)
   int blitzVote=utState + (g_fastSeries[last]>=g_slowSeries[last] ? 1 : -1) + g_superDir + (g_rrState!=0 ? g_rrState : utState) + (g_ensembleVotes>=0 ? 1 : -1);
   g_engineSignals[INSTANT_MANDATORY_BLITZ]=blitzVote>=0 ? 1 : -1;

   // StoneGem Quantum Velocity, Kalman Filter & Synthetic Order-Flow Delta (Engines 30..35)
   int velLag=(int)MathMax(2,MathMin(100,InpVelocityPeriod));
   int lagIdx=(int)MathMax(0,last-velLag);
   g_velocity=SXQuantumVelocity(g_closeCurrent,g_rates[lagIdx].close,g_atr,velLag);
   double kal=g_rates[0].close,kalPrev=kal;
   for(int i=1;i<n;i++) {
      kalPrev=kal;
      double stepVel=g_rates[i].close-g_rates[i-1].close;
      kal=SXKalmanStep(kal,g_rates[i].close,ConsoleKalmanGain,stepVel);
   }
   g_kalman=kal; g_kalmanPrev=kalPrev;
   g_kalmanDir=(g_closeCurrent>=g_kalman && g_kalman>=g_kalmanPrev) ? 1 : (g_closeCurrent<=g_kalman && g_kalman<=g_kalmanPrev) ? -1 : (g_closeCurrent>=g_kalman ? 1 : -1);
   double deltaSum=0;
   for(int i=(int)MathMax(0,n-6);i<n;i++) {
      double volBar=InpUseRealVolume && g_rates[i].real_volume>0 ? (double)g_rates[i].real_volume : (double)g_rates[i].tick_volume;
      deltaSum+=SXOrderFlowDelta(g_rates[i].open,g_rates[i].high,g_rates[i].low,g_rates[i].close,volBar);
   }
   g_orderFlowDelta=deltaSum;

   // Engine 30: STONEGEM_QUANTUM_PULSE (Quantum Velocity + Kalman + UT State)
   g_engineSignals[STONEGEM_QUANTUM_PULSE]=(g_velocity>=0.20 && g_kalmanDir>0 && utState>=0) ? 1 : (g_velocity<=-0.20 && g_kalmanDir<0 && utState<=0) ? -1 : (InpInstantStateEntry ? g_kalmanDir : 0);

   // Engine 31: STONEGEM_KALMAN_TREND (Kalman Filter + ADX + Session VWAP)

   // Engine 32: STONEGEM_ORDERFLOW_DELTA (Order-Flow Delta + MFI + OBV)
   g_engineSignals[STONEGEM_KALMAN_TREND]=(g_kalmanDir>0 && (!vwapComplete || g_closeCurrent>=g_vwap) && g_rsi>=48) ? 1 : (g_kalmanDir<0 && (!vwapComplete || g_closeCurrent<=g_vwap) && g_rsi<=52) ? -1 : 0;
   g_engineSignals[STONEGEM_ORDERFLOW_DELTA]=(g_orderFlowDelta>0 && g_mfi>=50 && g_obv>=0) ? 1 : (g_orderFlowDelta<0 && g_mfi<=50 && g_obv<=0) ? -1 : (InpInstantStateEntry ? (g_orderFlowDelta>=0 ? 1 : -1) : 0);

   // Engine 33: STONEGEM_VOLATILITY_BREAKOUT (ATR Regime Expansion + Squeeze/Breakout + Velocity)
   g_engineSignals[STONEGEM_VOLATILITY_BREAKOUT]=(br>0 || (g_atrRatio>=0.95 && g_velocity>0.35 && g_closeCurrent>g_fastSeries[last])) ? 1 : (br<0 || (g_atrRatio>=0.95 && g_velocity<-0.35 && g_closeCurrent<g_fastSeries[last])) ? -1 : 0;

   // Engine 34: STONEGEM_INSTITUTIONAL_FVG (Unfilled FVG + Sweep/Level Bounce + UT/Kalman Bias)
   bool fvgUp=FVGExists(1),fvgDn=FVGExists(-1);
   g_engineSignals[STONEGEM_INSTITUTIONAL_FVG]=(fvgUp && (g_engineSignals[LIQUIDITY_SWEEP]>=0 || g_kalmanDir>0)) ? 1 : (fvgDn && (g_engineSignals[LIQUIDITY_SWEEP]<=0 || g_kalmanDir<0)) ? -1 : (InpInstantStateEntry ? utState : 0);

   // Engine 35: STONEGEM_SUPREME_BLITZ (Adaptive Quantum/Kalman Blitz Engine)
   int supremeVote=g_engineSignals[INSTANT_MANDATORY_BLITZ] + g_kalmanDir + (g_velocity>=0 ? 1 : -1) + (g_orderFlowDelta>=0 ? 1 : -1) + utState;
   g_engineSignals[STONEGEM_SUPREME_BLITZ]=supremeVote>=0 ? 1 : -1;

   // Engine 36: QUANTUM_SUPERTREND_SHIELD (SuperTrend Engine [Quantum Algo] sUpeCIiJ with Kaufman ER & Whipsaw Shield)
   int erP=(int)MathMin(last,MathMax(2,InpQuantumERPeriod));
   double pathLen=0;
   for(int i=last-erP+1;i<=last;i++) pathLen+=MathAbs(g_rates[i].close-g_rates[i-1].close);
   g_quantumER=SXKaufmanER(g_closeCurrent-g_rates[last-erP].close,pathLen);
   g_quantumFactor=SXQuantumAdaptiveFactor(g_quantumER,InpQuantumTrendFactor,InpQuantumRangeFactor);
   double qUp=0,qDn=0; int qDir=1,qPrevDir=1; g_whipsawsShielded=0;
   for(int i=0;i<n;i++) {
      double qMid=(g_rates[i].high+g_rates[i].low)/2.0;
      double curAtr=g_atrSeries[i]>0 ? g_atrSeries[i] : g_atr;
      double lower=qMid-g_quantumFactor*curAtr,upper=qMid+g_quantumFactor*curAtr;
      double prevClose=i>0 ? g_rates[i-1].close : g_rates[i].close;
      qUp=(i==0 || prevClose<=qUp) ? lower : MathMax(lower,qUp);
      qDn=(i==0 || prevClose>=qDn) ? upper : MathMin(upper,qDn);
      qPrevDir=qDir;
      bool shielded=false;
      double oppBand=qDir<0 ? qDn : qUp;
      qDir=SXWhipsawShieldFlip(qDir,g_rates[i].close,oppBand,curAtr,InpWhipsawShieldATR,shielded);
      if(shielded) g_whipsawsShielded++;
   }
   g_quantumSuperDir=qDir;
   g_quantumSuperLine=qDir>0 ? qUp : qDn;
   g_engineSignals[QUANTUM_SUPERTREND_SHIELD]=(qDir!=qPrevDir) ? qDir : (InpInstantStateEntry ? qDir : 0);

   // Engine 37: DRM_MOMENTUM_REGIME (Causal Non-Repainting DRM Strategy 08eSyDlq)
   int drmP=(int)MathMin(last,MathMax(2,InpDrmPeriod));
   double hiDrm=g_rates[last].high,loDrm=g_rates[last].low;
   for(int i=last-drmP;i<=last;i++) { hiDrm=MathMax(hiDrm,g_rates[i].high); loDrm=MathMin(loDrm,g_rates[i].low); }
   g_drmValue=SXDrmMomentum(g_closeCurrent,g_rates[last-drmP].close,hiDrm,loDrm,g_rsi,g_atr);
   g_engineSignals[DRM_MOMENTUM_REGIME]=g_drmValue>=0.18 ? 1 : g_drmValue<=-0.18 ? -1 : (InpInstantStateEntry ? (g_drmValue>=0 ? 1 : -1) : 0);

   // Engine 38: UT_BOT_D1_MA_FILTER (UT Bot with D1 MA Length Filter SCxZW6YQ)
   MqlRates d1Bars[]; ArraySetAsSeries(d1Bars,false);
   int d1P=(int)MathMax(2,InpD1MAPeriod);
   int d1Count=CopyRates(g_symbol,PERIOD_D1,0,d1P+5,d1Bars);
   if(d1Count>=d1P) {
      double sumD1=0; for(int i=d1Count-d1P;i<d1Count;i++) sumD1+=d1Bars[i].close;
      g_d1MA=sumD1/d1P;
   } else g_d1MA=g_slowSeries[last];
   int d1Bias=g_closeCurrent>=g_d1MA ? 1 : -1;
   g_engineSignals[UT_BOT_D1_MA_FILTER]=(ut!=0 && ut==d1Bias) ? ut : (InpInstantStateEntry && utState==d1Bias ? utState : (InpInstantMandatoryOpen ? d1Bias : 0));

   // Engine 39: SESSION_OPENING_BIAS (Session opening gXMNQQqA â Candle/Session Open ATR Breakout & Trail)
   g_openAnchor=g_dayOpen>0 ? g_dayOpen : g_rates[last].open;
   double openDisp=g_closeCurrent-g_openAnchor;
   g_engineSignals[SESSION_OPENING_BIAS]=(openDisp>=0.15*g_atr && g_closeCurrent>=g_rates[last].open && utState>=0) ? 1 :
                       (openDisp<=-0.15*g_atr && g_closeCurrent<=g_rates[last].open && utState<=0) ? -1 :
                       (InpInstantStateEntry ? (openDisp>=0 ? 1 : -1) : 0);

   // Engine 40: CORAL_UT_RISK_MANAGER (UT Bot Strategy with Risk Management Coral pWT8wmAC)
   int coralP=(int)MathMax(2,InpCoralCoralPeriod);
   double coral=g_rates[0].close,cAlpha=2.0/(coralP+1.0);
   for(int i=1;i<n;i++) coral+=cAlpha*(g_rates[i].close-coral);
   g_coralEMA=coral;
   int coralDir=(g_closeCurrent>g_coralEMA && g_fastSeries[last]>=g_coralEMA) ? 1 : (g_closeCurrent<g_coralEMA && g_fastSeries[last]<=g_coralEMA) ? -1 : 0;
   g_engineSignals[CORAL_UT_RISK_MANAGER]=(ut!=0 && (coralDir==ut || coralDir==0)) ? ut : (InpInstantStateEntry ? (coralDir!=0 ? coralDir : utState) : 0);

   // Engine 41: FILTERED_UT_STC_HULL (Filtered3ENh UT Bot + STC + Hull MA Multi-Confirmation Engine)
   int hullDir=g_hull>=hullOld ? 1 : -1;
   int stcBias=g_stc>=50.0 ? 1 : -1;
   g_engineSignals[FILTERED_UT_STC_HULL]=(utState>0 && hullDir>0 && (stcNow>0 || stcBias>0)) ? 1 :
                       (utState<0 && hullDir<0 && (stcNow<0 || stcBias<0)) ? -1 :
                       (InpInstantStateEntry ? ((utState+hullDir+stcBias)>=0 ? 1 : -1) : 0);

   // Engine 42: ABSORPTION_DELTA_TRAP (Absorption Reversal Delta Trap wMcOiPoG)
   double prevHi4=g_rates[last>0 ? last-1 : 0].high,prevLo4=g_rates[last>0 ? last-1 : 0].low;
   for(int i=(int)MathMax(0,last-5);i<last;i++) { prevHi4=MathMax(prevHi4,g_rates[i].high); prevLo4=MathMin(prevLo4,g_rates[i].low); }
   g_deltaTrapSig=SXDeltaTrapSignal(g_rates[last].open,g_rates[last].high,g_rates[last].low,g_closeCurrent,prevHi4,prevLo4,g_orderFlowDelta,InpDeltaTrapWickRatio);
   g_engineSignals[ABSORPTION_DELTA_TRAP]=g_deltaTrapSig!=0 ? g_deltaTrapSig : (InpInstantStateEntry ? (g_orderFlowDelta>=0 ? 1 : -1) : 0);

   // Engine 43: SCALP_5MIN_PULSE (Scalp Signal Bot 5 min 1BmQAGQi â Fast Ribbon + UT + Stoch/RSI Scalp)
   int scalpRibbon=(g_closeCurrent>=g_fastSeries[last] && g_rsi>=48 && g_stoch>=45) ? 1 :
                   (g_closeCurrent<=g_fastSeries[last] && g_rsi<=52 && g_stoch<=55) ? -1 : 0;
   g_engineSignals[SCALP_5MIN_PULSE]=(scalpRibbon!=0 && scalpRibbon==utState) ? scalpRibbon : (InpInstantStateEntry ? (scalpRibbon!=0 ? scalpRibbon : utState) : 0);

   // Engine 44: STONEGEM_COMPOSITE (Combined Master Engine across all 6 EAs & 9 TradingView Scripts â Mandatory Instant Non-Fragile)
   int roverVote=g_engineSignals[STONEGEM_SUPREME_BLITZ] + g_quantumSuperDir + (g_drmValue>=0 ? 1 : -1) + d1Bias +
                   (g_closeCurrent>=g_coralEMA ? 1 : -1) + hullDir + (g_deltaTrapSig!=0 ? g_deltaTrapSig : (g_orderFlowDelta>=0 ? 1 : -1)) +
                   (scalpRibbon!=0 ? scalpRibbon : utState) + utState;
   g_engineSignals[STONEGEM_COMPOSITE]=roverVote>=0 ? 1 : -1;

   g_engineSignals[RUBY_COMPRESSION]=RubyCompression(last);
   g_engineSignals[DIAMOND_RECLAIM]=DiamondReclaim(last);
   g_engineSignals[STONEGEM_REGIME]=StoneGemRegime(last,g_engineSignals[RUBY_COMPRESSION],g_engineSignals[DIAMOND_RECLAIM]);
   g_engineSignals[DONCHIAN_RETEST]=DonchianRetest(last);
   g_engineSignals[KELTNER_REENTRY]=KeltnerReentry(last);
   g_engineSignals[AROON_CROSSOVER]=AroonCross(last);
   g_engineSignals[VORTEX_CROSSOVER]=VortexCross(last);
   g_engineSignals[CHAIKIN_FLOW_CROSS]=ChaikinFlowCross(last);
   BuildGemSignals();
   g_engineSignals[FAILED_BREAKOUT_RECLAIM]=FailedBreakout(last);
   g_engineSignals[REGIME_CONFLUENCE]=RegimeConfluence();
   // New closed-bar engines, sharing the inherited cooldown, risk and execution gates.
   int cb=ClockBias();
   g_engineSignals[MATRIX_CLOCK_VOTE]=(cb!=0 && ClockVotes(cb)>=InpClockMinVotes && (!InpClockRequireUT || cb==utState)) ? cb : 0;
   g_engineSignals[MATRIX_UT_FVG]=utRecent>0 && fvgUp && utState>0 && stcBias>0 ? 1 : utRecent<0 && fvgDn && utState<0 && stcBias<0 ? -1 : 0;
   if(InpClockCorrelationGate && last>=20) {
      double sx=0,sy=0,sxx=0,syy=0,sxy=0;
      for(int j=0;j<20;j++) { double x=j,y=g_rates[last-19+j].close-g_rates[last-19].close; sx+=x; sy+=y; sxx+=x*x; syy+=y*y; sxy+=x*y; }
      double den=MathSqrt(MathMax(0,(20*sxx-sx*sx)*(20*syy-sy*sy)));
      double corr=den>0 ? (20*sxy-sx*sy)/den : 0;
      if(corr*cb<InpClockMinTrendCorrelation) g_engineSignals[MATRIX_CLOCK_VOTE]=0;
   }
   if(last>InpClockHoverBars && g_atr>0) {
      double hh=g_rates[last-1].high,ll=g_rates[last-1].low;
      for(int j=last-InpClockHoverBars;j<last;j++) { hh=MathMax(hh,g_rates[j].high); ll=MathMin(ll,g_rates[j].low); }
      double edge=InpClockHoverEdgeATR*g_atr, c0=g_rates[last].close, p0=g_rates[last-1].close;
      if(hh-ll>=0.8*g_atr && hh-ll<=12*g_atr) {
         g_engineSignals[MATRIX_HOVER_FADE]=g_adx<=InpRangeADXMax ? (c0<=ll+edge && c0>=ll-edge && g_rsi<48 ? 1 : c0>=hh-edge && c0<=hh+edge && g_rsi>52 ? -1 : 0) : 0;
         g_engineSignals[MATRIX_HOVER_BREAK]=c0>hh+edge && p0<=hh ? 1 : c0<ll-edge && p0>=ll ? -1 : 0;
         double hMid=(g_rates[last].high+g_rates[last].low)*0.5;
         g_engineSignals[MATRIX_HOVER_SCALP]=g_adx<=InpRangeADXMax ? (c0<hMid-edge && c0>ll && g_rsi<45 ? 1 : c0>hMid+edge && c0<hh && g_rsi>55 ? -1 : 0) : 0;
      }
   }
   BuildAdditionalSignals(last);
   g_engineSignals[QUOTE_FLOW]=FlowTickSignalNow(g_symbol);
   g_engineSignals[STRUCTURE_VOTE]=FlowVoteSignal(last);
   g_gem.scalpUp=g_voteBuyVotes; g_gem.scalpDown=g_voteSellVotes;
   g_gem.fitScore=FlowTrendFit(n,InpTrendFitBars);
   BuildFastSlowStudy(last);
   int gradeNow=g_engineSignals[FAST_SLOW_UT],gradeRecent=gradeNow;
   for(int i=last-1;i>=(int)MathMax(0,last-InpStcLag) && gradeRecent==0;i--)
      gradeRecent=Direction(g_proEvents[i]);
   g_engineSignals[UT_STC_GRADE]=GradeUTSTC(gradeNow,gradeRecent,stcNow,stcRecent,g_gem.primaryUT,g_gem.secondaryUT);
   if(g_consoleStrategy>=DROID_ADAPTIVE_CONFLUENCE && g_consoleStrategy<=OVERNIGHT_MNQ_SYNAPSE) BuildDroidCombinedSignals(last);
   BuildDroidSignals(last,g_bandUpper,g_bandLower,prevUpper,prevLower);
   UpdateShock(InpUseFormingBar && (int)g_consoleStrategy<DUAL_UT_LINREG ? last-1 : last);
   g_gem.positiveVotes=0; g_gem.negativeVotes=0;
   for(int i=0;i<SG_ENGINE_COUNT;i++) {
      if(g_engineSignals[i]>0) g_gem.positiveVotes++;
      if(g_engineSignals[i]<0) g_gem.negativeVotes++;
   }
   g_candidate=g_engineSignals[(int)g_consoleStrategy];
   if(g_candidate==0 && (int)g_consoleStrategy<DUAL_UT_LINREG && InpInstantMandatoryOpen && InpInstantStateEntry) {
      g_candidate=g_engineSignals[STONEGEM_COMPOSITE]!=0 ? g_engineSignals[STONEGEM_COMPOSITE] : (g_engineSignals[STONEGEM_SUPREME_BLITZ]!=0 ? g_engineSignals[STONEGEM_SUPREME_BLITZ] : utState);
   }
   g_snapshotSymbol=g_symbol;
}

double TradeRisk(string symbol,int direction,double volume,double entry,double sl) {
   if(sl<=0) return ConsoleEquity();
   if(direction*(entry-sl)<=0) return 0;
#ifdef __MQL5__
   double estimate=0;
   if(!OrderCalcProfit(direction>0 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL,symbol,volume,entry,sl,estimate)) return ConsoleEquity();
   return MathAbs(estimate);
#else
   double tick=SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE),value=SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_VALUE);
   if(tick<=0 || value<=0) return ConsoleEquity();
   return MathAbs(entry-sl)/tick*value*volume;
#endif
}
int PortfolioExposureCount() {
   int count=0;
#ifdef __MQL5__
   for(int i=0;i<PositionsTotal();i++) if(PositionGetTicket(i)>0 && PositionGetInteger(POSITION_MAGIC)==ConsoleMagic) count++;
   for(int i=0;i<OrdersTotal();i++) if(OrderGetTicket(i)>0 && OrderGetInteger(ORDER_MAGIC)==ConsoleMagic) count++;
#else
   for(int i=0;i<OrdersTotal();i++) if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber()==ConsoleMagic) count++;
#endif
   return count;
}
double PortfolioRiskMoney() {
   double risk=0;
#ifdef __MQL5__
   for(int i=0;i<PositionsTotal();i++) if(PositionGetTicket(i)>0 && PositionGetInteger(POSITION_MAGIC)==ConsoleMagic) {
      risk+=TradeRisk(PositionGetString(POSITION_SYMBOL),PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ? 1 : -1,PositionGetDouble(POSITION_VOLUME),PositionGetDouble(POSITION_PRICE_OPEN),PositionGetDouble(POSITION_SL));
   }
   for(int i=0;i<OrdersTotal();i++) if(OrderGetTicket(i)>0 && OrderGetInteger(ORDER_MAGIC)==ConsoleMagic) {
      long kind=OrderGetInteger(ORDER_TYPE);
      int direction=(kind==ORDER_TYPE_BUY || kind==ORDER_TYPE_BUY_LIMIT || kind==ORDER_TYPE_BUY_STOP || kind==ORDER_TYPE_BUY_STOP_LIMIT) ? 1 : -1;
      risk+=TradeRisk(OrderGetString(ORDER_SYMBOL),direction,OrderGetDouble(ORDER_VOLUME_CURRENT),OrderGetDouble(ORDER_PRICE_OPEN),OrderGetDouble(ORDER_SL));
   }
#else
   for(int i=0;i<OrdersTotal();i++) if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber()==ConsoleMagic) {
      int kind=OrderType(); int direction=kind==OP_BUY || kind==OP_BUYLIMIT || kind==OP_BUYSTOP ? 1 : -1;
      risk+=TradeRisk(OrderSymbol(),direction,OrderLots(),OrderOpenPrice(),OrderStopLoss());
   }
#endif
   return risk;
}
bool PortfolioRiskAllows(int direction,double volume,double entry,double sl) {
   double equity=ConsoleEquity(); if(equity<=0) return false;
   if(NoPositionCaps()) return true;
   return PortfolioRiskMoney()+TradeRisk(g_symbol,direction,volume,entry,sl)<=equity*InpMaxPortfolioRiskPct/100.0+0.00001;
}
bool HasExposure(string symbol) {
#ifdef __MQL5__
   for(int i=0;i<PositionsTotal();i++) if(PositionGetTicket(i)>0 && PositionGetString(POSITION_SYMBOL)==symbol && PositionGetInteger(POSITION_MAGIC)==ConsoleMagic) return true;
   for(int i=0;i<OrdersTotal();i++) if(OrderGetTicket(i)>0 && OrderGetString(ORDER_SYMBOL)==symbol && OrderGetInteger(ORDER_MAGIC)==ConsoleMagic) return true;
#else
   for(int i=0;i<OrdersTotal();i++) if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==symbol && OrderMagicNumber()==ConsoleMagic) return true;
#endif
   return false;
}
bool CancelTicket(ulong ticket) {
   if(!CanTrade()) return false;
#ifdef __MQL5__
   MqlTradeRequest request={}; request.action=TRADE_ACTION_REMOVE; request.symbol=g_symbol; request.magic=(ulong)ConsoleMagic; request.order=ticket;
   return SendRequest(request,"Cancel pending #"+StringFormat("%I64u",ticket));
#else
   ResetLastError(); if(OrderDelete((int)ticket,clrNONE)) return true;
   Log("Pending cancellation failed "+IntegerToString(GetLastError())); return false;
#endif
}
void ManagePending() {
   if(g_uncertain) return;
   bool cancel=(InpPendingOCO || g_consoleStrategy==SESSION_BRACKET) && ArraySize(g_positions)>0;
   for(int i=OrdersTotal()-1;i>=0;i--) {
      ulong ticket=0;
#ifdef __MQL5__
      ticket=OrderGetTicket(i); if(ticket==0 || OrderGetString(ORDER_SYMBOL)!=g_symbol || OrderGetInteger(ORDER_MAGIC)!=ConsoleMagic) continue;
#else
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES) || OrderSymbol()!=g_symbol || OrderMagicNumber()!=ConsoleMagic || OrderType()<=OP_SELL) continue;
      ticket=(ulong)OrderTicket();
#endif
      datetime expires=GlobalVariableCheck(PendingKey(ticket)) ? (datetime)GlobalVariableGet(PendingKey(ticket)) : 0;
      if(cancel || (expires>0 && TimeCurrent()>=expires)) if(CancelTicket(ticket)) GlobalVariableDel(PendingKey(ticket));
   }
}
bool PlacePending(int direction,SXEntry style,bool manual=false,double trigger=0,bool bracketSibling=false) {
   ConsoleLoadPositions(); string why="";
   if(style==ENTRY_MARKET) return OpenPosition(direction,manual);
   if(!EntryGate(direction,why,bracketSibling) || !SupportsRequest(style,why)) { Log("Pending blocked: "+why); return false; }
   MqlTick quote; if(!Tick(quote)) return false;
   bool stop=style==ENTRY_STOP;
   double price=0,sl=0,tp=0;
   if(!EntryPrices(direction,style,trigger,quote,price,sl,tp,why)) { Log(why); return false; }
   if(!manual && !AutoEntryQuality(quote.ask-quote.bid,price,sl,tp,why)) { Log(why); return false; }
   double lots=RiskLots(direction,price,sl,manual);
   if(price<=0 || sl<=0 || lots<=0 || !PortfolioRiskAllows(direction,lots,price,sl)) { Log("Pending blocked: price, volume or aggregate stop risk"); return false; }
   WriteGV("submit",(double)TimeCurrent()); ulong ticket=0; bool success=false;
#ifdef __MQL5__
   MqlTradeRequest request={}; MqlTradeCheckResult check={}; MqlTradeResult result={};
   request.action=TRADE_ACTION_PENDING; request.symbol=g_symbol; request.magic=(ulong)ConsoleMagic;
   request.type=direction>0 ? (stop ? ORDER_TYPE_BUY_STOP : ORDER_TYPE_BUY_LIMIT) : (stop ? ORDER_TYPE_SELL_STOP : ORDER_TYPE_SELL_LIMIT);
   request.volume=lots; request.price=price; request.sl=sl; request.tp=tp; request.type_time=ORDER_TIME_GTC;
   long expiryFlags=SymbolInfoInteger(g_symbol,SYMBOL_EXPIRATION_MODE);
   if((expiryFlags&SYMBOL_EXPIRATION_GTC)==0) {
      if((expiryFlags&SYMBOL_EXPIRATION_SPECIFIED)!=0) {
         request.type_time=ORDER_TIME_SPECIFIED;
         request.expiration=(datetime)(TimeCurrent()+InpPendingLifeBars*PeriodSeconds(g_tf));
      } else if((expiryFlags&SYMBOL_EXPIRATION_DAY)!=0) request.type_time=ORDER_TIME_DAY;
      else if((expiryFlags&SYMBOL_EXPIRATION_SPECIFIED_DAY)!=0) {
         request.type_time=ORDER_TIME_SPECIFIED_DAY;
         request.expiration=(datetime)(TimeCurrent()+InpPendingLifeBars*PeriodSeconds(g_tf));
      } else { Log("Broker has no supported pending-order expiry"); return false; }
   }
   request.type_filling=ORDER_FILLING_RETURN; request.comment=SG_ORDER_COMMENT;
   ResetLastError();
   if(!OrderCheck(request,check)) { if(InpAutoWidenStop && check.retcode==10016) g_stopPaddingPts=(int)MathMin(1000,g_stopPaddingPts==0 ? 20 : g_stopPaddingPts*2); Log("Pending precheck "+IntegerToString((int)check.retcode)+" "+check.comment); return false; }
   bool sent=OrderSend(request,result); int error=GetLastError();
   success=sent && (result.retcode==TRADE_RETCODE_PLACED || result.retcode==TRADE_RETCODE_DONE) && result.order>0;
   ticket=result.order;
   if(result.retcode==TRADE_RETCODE_TIMEOUT || (!sent && (result.retcode==0 || result.retcode==10031)) ||
      (sent && (result.retcode==TRADE_RETCODE_PLACED || result.retcode==TRADE_RETCODE_DONE) && ticket==0))
      SetUncertain("Pending request lacks confirmation");
   else if(!success) Log("Pending rejected "+IntegerToString((int)result.retcode)+" / "+IntegerToString(error));
#else
   int kind=direction>0 ? (stop ? OP_BUYSTOP : OP_BUYLIMIT) : (stop ? OP_SELLSTOP : OP_SELLLIMIT);
   ResetLastError(); int answer=OrderSend(g_symbol,kind,lots,price,InpSlippagePoints,sl,tp,SG_ORDER_COMMENT,ConsoleMagic,0,clrNONE);
   success=answer>0; ticket=answer>0 ? (ulong)answer : 0;
   if(!success) { int error=GetLastError(); if(error==128) SetUncertain("Pending timeout"); else Log("Pending rejected "+IntegerToString(error)); }
#endif
   if(success) {
      GlobalVariableSet(PendingKey(ticket),(double)(TimeCurrent()+InpPendingLifeBars*PeriodSeconds(g_tf)));
      WriteGV("tradebar",(double)iTime(g_symbol,g_tf,1)); CountEntry();
      Log(Side(direction)+(stop ? " STOP #" : " LIMIT #")+StringFormat("%I64u",ticket)); GlobalVariablesFlush();
   }
   return success;
}
void BeginSymbolExit(string reason) {
   if(!g_exitRequested) Log(reason+"; requesting owned exits");
   g_exitRequested=true; WriteGV("exit",1); CloseOwned();
}
void RequestPortfolioExit(string reason) {
   if(!g_consolePortfolioExit) Log(reason+"; requesting portfolio exits");
   g_consolePortfolioExit=true;
   for(int i=0;i<ArraySize(g_assets);i++) {
      g_assets[i].exiting=true; GlobalVariableSet(g_assets[i].key+"exit",1);
   }
   g_exitRequested=true;
}
void ManageBasket() {
   if(ArraySize(g_positions)==0) {
      if(g_basketPeak!=0 || g_basketLots!=0) { g_basketPeak=0; g_basketLots=0; WriteGV("basket",0); WriteGV("basketlots",0); }
      if(g_exitRequested && WorkingOrders()==0) { g_exitRequested=false; WriteGV("exit",0); }
      return;
   }
   double lots=0; for(int i=0;i<ArraySize(g_positions);i++) lots+=g_positions[i].lots;
   if(g_basketLots>0 && lots<g_basketLots-0.0000001) {
      g_basketPeak*=lots/g_basketLots; WriteGV("basket",g_basketPeak);
   }
   g_basketLots=lots; WriteGV("basketlots",lots);
   double profit=Floating();
   if(profit>g_basketPeak) { g_basketPeak=profit; WriteGV("basket",profit); }
   if(InpBasketLossMoney>0 && profit<=-InpBasketLossMoney) BeginSymbolExit("Basket loss threshold");
   if(InpBasketLock && g_basketPeak>=InpBasketStartMoney) {
      double floor=MathMax(InpBasketMinMoney,g_basketPeak*(1-InpBasketGivebackPct/100));
      if(profit<=floor) BeginSymbolExit("Basket profit giveback");
   }
}
void ManageGrid() {
   if(!g_auto || InpGrid==GRID_OFF || IsNetting() || !g_consoleReady || g_exitRequested || g_consolePortfolioExit || g_uncertain || WorkingOrders()>0) return;
   int count=ArraySize(g_positions);
   if(count<1 || count>=InpGridMaxLevels || (!NoPositionCaps() && count>=ConsoleMaxPositions)) return;
   int direction=g_positions[0].direction,latest=0,first=0;
   for(int i=0;i<count;i++) {
      if(g_positions[i].direction!=direction) return;
      if(g_positions[i].opened>g_positions[latest].opened) latest=i;
      if(g_positions[i].opened<g_positions[first].opened) first=i;
   }
   if((datetime)ReadGV("tradebar",0)==iTime(g_symbol,g_tf,1)) return;
   if(InpGridRequiresSignal && g_candidate!=direction) return;
   MqlTick quote; if(!Tick(quote)) return;
   double delta=direction*((direction>0 ? quote.ask : quote.bid)-g_positions[latest].open);
   double gap=InpGridSpacingATR*g_atr;
   if((InpGrid==GRID_ADVERSE && delta>-gap) || (InpGrid==GRID_PYRAMID && delta<gap)) return;
   if(!BuildSnapshot()) return;
   string why=""; if(!SignalFilters(direction,why)) return;
   double lots=g_positions[first].lots;
   if(InpGridLots==GRID_MULTIPLY) lots*=MathPow(InpGridMultiplier,count);
   if(InpGridLots==GRID_ADDITIVE) lots+=InpGridAddLots*count;
   OpenPosition(direction,false,lots);
}
void ProcessAsset(int index,bool permitEntry=true) {
   ActivateAsset(index);
   UpdateSpreadStats();
   FlowRecordQuote();
   bool hadExit=g_exitRequested;
   if(g_exitRequested) { CloseOwned(); ConsoleLoadPositions(); }
   if(!NoTimeRestrictions() && InpUseDateWindow && InpCloseAtEndDate && TimeCurrent()>=InpEndDate) BeginSymbolExit("Entry date range ended");
   datetime closed=iTime(g_symbol,g_tf,1);
   datetime now=TimeCurrent();
   bool formingDue=UsesFormingBar() && now!=g_assets[index].lastFormingEvaluation;
   if(closed>0 && (closed!=g_lastClosed || !g_consoleReady || formingDue)) {
      bool freshClosed=(closed!=g_lastClosed);
      if(UsesFormingBar()) g_assets[index].lastFormingEvaluation=now;
      if(BuildSnapshot()) {
         if(g_lastClosed==0 && !InpTradeOnAttach) WriteGV("skipbar",(double)closed);
         g_lastClosed=closed;
         if(InpSignalAlerts && g_candidate!=0 && g_consoleStrategy!=QUOTE_FLOW && g_assets[index].enabled) {
            string key=g_key+"al"+IntegerToString((int)g_consoleStrategy);
            if(!GlobalVariableCheck(key)) GlobalVariableTemp(key);
            double prior=GlobalVariableGet(key);
            if(prior<(double)closed && GlobalVariableSetOnCondition(key,(double)closed,prior))
               Notify(Side(g_candidate)+" signal | "+g_symbol+" | "+EngineTitle((int)g_consoleStrategy)+(g_consoleStrategy==FAST_SLOW_UT && g_gem.utStrong ? " | strong" : ""));
         }
         if(g_candidate==0) g_message=SignalWaitReason();
         if(g_symbol==g_chartSymbol && freshClosed) PaintChart();
      }
   }
   if(permitEntry && g_assets[index].enabled) {
      if(hadExit) g_message="Owned exit still in progress";
      else if(!g_auto) g_message="AUTO OFF: enable automatic entries";
      else if(InpTesterOnlyEntries && !g_tester) g_message="Tester-only preset: new entries blocked outside Strategy Tester";
      else if(!g_consoleReady) { /* preserve the warm-up or synchronization status */ }
      else if(ReadGV("skipbar",0)==(double)closed) g_message="Trade on attach off: waiting for the next candle";
      else if(g_consoleStrategy==SESSION_BRACKET) ProcessSessionBracket();
      else if(FlowLiveOnly()) FlowTickEntry();
      else TryClockEntry(closed);
   }
   if(!hadExit) FlowTickExits();
   ManageStops();
   if(permitEntry && g_assets[index].enabled && !hadExit && g_consoleStrategy!=SESSION_BRACKET) ManageGrid();
   if(g_symbol==g_chartSymbol && InpEntryDiagnostics) {
      static string lastDiagnostic=""; static datetime lastDiagnosticAt=0;
      if(g_message!="" && (lastDiagnosticAt==0 || (g_message!=lastDiagnostic && TimeCurrent()-lastDiagnosticAt>=10))) {
         Print("CVT LT DRIOD BOT NO ERRORS EA | ",g_symbol," | ENTRY STATUS: ",g_message);
         lastDiagnostic=g_message; lastDiagnosticAt=TimeCurrent();
      }
   }
   SaveAsset();
}
int RubyCompression(int last) {
   if(last<9 || g_atrSeries[last-1]<=0) return 0;
   double hi=g_rates[last-1].high,lo=g_rates[last-1].low;
   for(int j=last-6;j<last-1;j++) { hi=MathMax(hi,g_rates[j].high); lo=MathMin(lo,g_rates[j].low); }
   if(hi-lo>2.35*g_atrSeries[last-1] || g_volumeRatio<0.90) return 0;
   double margin=InpBreakBufferATR*g_atrSeries[last-1];
   if(g_rates[last].close>hi+margin && g_macd>0) return 1;
   if(g_rates[last].close<lo-margin && g_macd<0) return -1;
   return 0;
}
int DiamondReclaim(int last) {
   if(last<2 || g_atr<=0) return 0;
   double fast=g_fastSeries[last],previous=g_fastSeries[last-1],slow=g_slowSeries[last];
   double padding=0.12*g_atr;
   bool bull=fast>slow && g_tf1>0 && g_rates[last-1].low<=previous+padding && g_rates[last].close>fast && g_rates[last].close>g_rates[last-1].high && g_rsi>51;
   bool bear=fast<slow && g_tf1<0 && g_rates[last-1].high>=previous-padding && g_rates[last].close<fast && g_rates[last].close<g_rates[last-1].low && g_rsi<49;
   return bull ? 1 : bear ? -1 : 0;
}
int StoneGemRegime(int last,int expansion,int reclaim) {
   if(last<2 || g_atr<=0 || g_atrRatio>2.8) return 0;
   if(expansion!=0) return expansion;
   if(g_adx>=InpMinADX && g_quantumER>=0.24) {
      if(reclaim!=0) return reclaim;
      bool up=g_fastSeries[last]>g_slowSeries[last] && g_superDir>0 && g_macd>0 && g_rsi>=53 && g_rsi<=77;
      bool down=g_fastSeries[last]<g_slowSeries[last] && g_superDir<0 && g_macd<0 && g_rsi<=47 && g_rsi>=23;
      return up ? 1 : down ? -1 : 0;
   }
   if(g_adx<=InpRangeADXMax && g_bandUpper>g_bandLower) {
      if(g_rates[last].low<g_bandLower && g_closeCurrent>g_bandLower && g_mfi<44 && g_stoch<34) return 1;
      if(g_rates[last].high>g_bandUpper && g_closeCurrent<g_bandUpper && g_mfi>56 && g_stoch>66) return -1;
   }
   return 0;
}
int DonchianRetest(int last) {
   if(last<21 || g_atrSeries[last-1]<=0) return 0;
   double high=g_rates[last-2].high,low=g_rates[last-2].low;
   for(int i=last-21;i<last-2;i++) { high=MathMax(high,g_rates[i].high); low=MathMin(low,g_rates[i].low); }
   double tolerance=0.12*g_atrSeries[last-1];
   if(high<=low) return 0;
   if(g_rates[last-1].close>high && MathAbs(g_rates[last].low-high)<=tolerance && g_rates[last].close>high) return 1;
   if(g_rates[last-1].close<low && MathAbs(g_rates[last].high-low)<=tolerance && g_rates[last].close<low) return -1;
   return 0;
}
int KeltnerReentry(int last) {
   if(last<1 || g_atrSeries[last]<=0 || g_atrSeries[last-1]<=0) return 0;
   double previous=g_rates[last-1].close-g_fastSeries[last-1],current=g_rates[last].close-g_fastSeries[last];
   if(MathAbs(current)>=2*g_atrSeries[last]) return 0;
   if(previous < -2*g_atrSeries[last-1]) return 1;
   if(previous >  2*g_atrSeries[last-1]) return -1;
   return 0;
}
int CrossDirection(double previous,double current) {
   if(previous<=1e-9 && current>1e-9) return 1;
   if(previous>=-1e-9 && current< -1e-9) return -1;
   return 0;
}
double AroonBalance(int last) {
   int high=last-25,low=last-25;
   for(int i=last-24;i<=last;i++) {
      if(g_rates[i].high>=g_rates[high].high) high=i;
      if(g_rates[i].low<=g_rates[low].low) low=i;
   }
   return (high-low)*4.0;
}
int AroonCross(int last) {
   if(last<26) return 0;
   return CrossDirection(AroonBalance(last-1),AroonBalance(last));
}
bool VortexBalance(int last,double &value) {
   if(last<14) return false;
   double plus=0,minus=0,totalRange=0;
   for(int i=last-13;i<=last;i++) {
      plus+=MathAbs(g_rates[i].high-g_rates[i-1].low);
      minus+=MathAbs(g_rates[i].low-g_rates[i-1].high);
      double prior=g_rates[i-1].close;
      totalRange+=MathMax(g_rates[i].high,prior)-MathMin(g_rates[i].low,prior);
   }
   if(totalRange<=0) return false;
   value=(plus-minus)/totalRange; return true;
}
int VortexCross(int last) {
   double previous=0,current=0;
   if(!VortexBalance(last-1,previous) || !VortexBalance(last,current)) return 0;
   return CrossDirection(previous,current);
}
bool ChaikinFlow(int last,double &flow) {
   if(last<19) return false;
   double weighted=0,volume=0;
   for(int i=last-19;i<=last;i++) {
      MqlRates r=g_rates[i]; double v=(double)r.tick_volume;
      if(v<=0) continue;
      volume+=v;
      if(r.high>r.low) weighted+=v*((r.close-r.low)-(r.high-r.close))/(r.high-r.low);
   }
   if(volume<=0) return false;
   flow=weighted/volume; return true;
}
int ChaikinFlowCross(int last) {
   double previous=0,current=0;
   if(!ChaikinFlow(last-1,previous) || !ChaikinFlow(last,current)) return 0;
   return CrossDirection(previous,current);
}
bool BroadLocks() { return InpUnlockAll || g_noLocks; }
bool BroadRestrictions() { return InpUnlockAll || g_noRestrictions; }
string ScopeName() {
   if(g_assetMode==ASSET_BROKER) return "Broker catalog";
   if(g_assetMode==ASSET_MARKETWATCH) return "Market Watch";
   if(g_assetMode==ASSET_CUSTOM) return "Custom list";
   return "Chart only";
}
int AllowedTradeMode(string symbol) {
#ifdef __MQL5__
   return (int)SymbolInfoInteger(symbol,SYMBOL_TRADE_MODE);
#else
   if(MarketInfo(symbol,MODE_TRADEALLOWED)<=0) return SYMBOL_TRADE_MODE_DISABLED;
   return (int)SymbolInfoInteger(symbol,SYMBOL_TRADE_MODE);
#endif
}
void DiscoverBroker(int budget) {
   if(g_assetMode!=ASSET_BROKER) return;
   int total=SymbolsTotal(false);
   if(total<=0) return;
   if(g_catalogCursor>=total) {
      if(TimeCurrent()-g_catalogDone<60) return;
      g_catalogCursor=0;
   }
   for(int j=0;j<budget && g_catalogCursor<total;j++) {
      string candidate=SymbolName(g_catalogCursor++,false);
      if(candidate=="" || !SymbolSelect(candidate,true)) continue;
      int mode=AllowedTradeMode(candidate);
      if(mode==SYMBOL_TRADE_MODE_DISABLED || mode==SYMBOL_TRADE_MODE_CLOSEONLY) continue;
      AddAsset(candidate,true);
   }
   if(g_catalogCursor>=total) g_catalogDone=TimeCurrent();
}
void UpdateSpreadStats() {
   if(g_active<0 || g_active>=ArraySize(g_assets)) return;
   MqlTick q;
   if(!Tick(q)) return;
   if(g_assets[g_active].quoteTime==q.time && g_assets[g_active].lastBid==q.bid && g_assets[g_active].lastAsk==q.ask) return;
   double spread=q.ask-q.bid;
   double previous=g_assets[g_active].spreadMean;
   g_assets[g_active].spreadRatio=(previous>0 ? spread/previous : 1.0);
   g_assets[g_active].spreadMean=previous>0 ? previous+0.085*(spread-previous) : spread;
   g_assets[g_active].spreadCount++;
   g_assets[g_active].quoteTime=q.time; g_assets[g_active].lastBid=q.bid; g_assets[g_active].lastAsk=q.ask;
}
double TargetFor(int d,double entry,double stop,double gap) {
   double dist=0;
   if(InpFixedTargetPoints>0) dist=InpFixedTargetPoints*g_consolePoint;
   else if(InpUseFixedTP) dist=(InpFixedTP_R*(g_consoleStrategy==UT_VALUE_TURN && InpValueTurnSwing && g_gem.targetScale>0 ? g_gem.targetScale : 1.0))*MathAbs(entry-stop);
   if(dist<=0) return 0;
   return NormalizeDouble(SXRoundPrice(entry+d*MathMax(gap,dist),TickSize(),-d),g_consoleDigits);
}
double FixedTrail(int direction,double open,double oldSL,double market,double minDistance,double tick) {
   double gain=direction*(market-open);
   if(InpTrailStartPoints<=0 || gain<InpTrailStartPoints*g_consolePoint) return oldSL;
   double proposed=SXRoundPrice(market-direction*MathMax(minDistance,InpTrailGapPoints*g_consolePoint),tick,direction);
   if(direction*(proposed-open)<=0 || (oldSL>0 && direction*(proposed-oldSL)<MathMax(tick,InpTrailStepPoints*g_consolePoint)-tick*1e-7)) return oldSL;
   return proposed;
}
void RememberChart() {
   if(g_savedColours || !InpApplyThemeToChart) return;
   g_chartCols[0]=CHART_COLOR_BACKGROUND; g_chartCols[1]=CHART_COLOR_FOREGROUND; g_chartCols[2]=CHART_COLOR_GRID;
   g_chartCols[3]=CHART_COLOR_CANDLE_BULL; g_chartCols[4]=CHART_COLOR_CANDLE_BEAR; g_chartCols[5]=CHART_COLOR_CHART_UP;
   g_chartCols[6]=CHART_COLOR_CHART_DOWN; g_chartCols[7]=CHART_COLOR_VOLUME;
   for(int i=0;i<8;i++) g_previousCols[i]=ChartGetInteger(0,g_chartCols[i],0);
   g_previousForeground=ChartGetInteger(0,CHART_FOREGROUND,0);
   g_previousMode=ChartGetInteger(0,CHART_MODE,0);
   g_previousVolumes=ChartGetInteger(0,CHART_SHOW_VOLUMES,0);
   g_previousGrid=ChartGetInteger(0,CHART_SHOW_GRID,0);
   g_savedColours=true;
}
void RestoreChart() {
   if(!g_savedColours) return;
   for(int i=0;i<8;i++) ChartSetInteger(0,g_chartCols[i],g_previousCols[i]);
   ChartSetInteger(0,CHART_SHOW_GRID,g_previousGrid);
   ChartSetInteger(0,CHART_FOREGROUND,g_previousForeground);
   ChartSetInteger(0,CHART_MODE,g_previousMode);
   ChartSetInteger(0,CHART_SHOW_VOLUMES,g_previousVolumes);
   g_savedColours=false;
}


string SignalWaitReason() {
   if(g_consoleStrategy>=DR_UT) return EngineTitle((int)g_consoleStrategy)+" / "+g_gem.droidState;
   if(g_consoleStrategy==QUOTE_FLOW) return "Tick flow: "+FlowTickText();
   if(g_consoleStrategy==PATH_AGREEMENT) {
      if(g_atrRatio<InpRegimeMinRatio || g_atrRatio>InpRegimeMaxRatio) return "Waiting for ATR regime";
      if(g_gem.pathEfficiency<InpPathEfficiency) return "Path efficiency below "+Value(InpPathEfficiency,2);
      if(g_gem.horizonSide==0) return "Waiting for agreeing price horizons";
      return "Directional agreement "+IntegerToString(g_gem.regimeVotes)+"/4";
   }
   if(g_consoleStrategy==UT_STC_GRADE) return "Waiting for fast/slow UT and a matching STC turn";
   if(g_consoleStrategy==UT_VISUAL_GAP && g_active>=0 && g_assets[g_active].utRemaining>0)
      return "UT quiet period: "+IntegerToString(g_assets[g_active].utRemaining)+" bars";
   if(g_consoleStrategy==MATRIX_CLOCK_VOTE) {
      int side=ClockBias(), votes=side==0 ? 0 : ClockVotes(side);
      return "No entry: "+IntegerToString(votes)+"/9 votes; need "+IntegerToString(InpClockMinVotes)+(InpClockRequireUT ? " + UT" : "");
   }
   if(g_consoleStrategy!=STONEGEM_REGIME) return "Waiting for "+EngineTitle((int)g_consoleStrategy)+" signal";
   if(g_atrRatio>2.8) return "ATR expansion exceeds the regime limit";
   if(g_adx>=InpMinADX && g_quantumER>=0.24) {
      if(g_rsi<23) return "Short setup waits for RSI to recover to 23";
      if(g_rsi>77) return "Long setup waits for RSI to cool to 77";
      return "Waiting for EMA, momentum and trend alignment";
   }
   return "Waiting for a band reclaim or a range break";
}

void ManualHedge() {
   if(IsNetting()) { Log("Hedge requires an MT4 or MT5 hedging account"); return; }
   ConsoleLoadPositions(); double net=0;
   for(int i=0;i<ArraySize(g_positions);i++) net+=g_positions[i].direction*g_positions[i].lots;
   if(MathAbs(net)<SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN)) { Log("No net owned exposure to hedge"); return; }
   OpenPosition(net>0 ? -1 : 1,true,MathAbs(net));
}
bool AnyUncertain() {
   for(int i=0;i<ArraySize(g_assets);i++) if(g_assets[i].uncertain) return true;
   return g_uncertain;
}

void ChartCaption(string id,int x,int y,string label,color ink,int size,bool strong=false) {
   string name=g_prefix+"strip_"+id;
   if(ObjectFind(0,name)<0 && !ObjectCreate(0,name,OBJ_LABEL,0,0,0)) return;
   ObjectSetInteger(0,name,OBJPROP_CORNER,CORNER_LEFT_UPPER); ObjectSetInteger(0,name,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,name,OBJPROP_COLOR,ink); ObjectSetInteger(0,name,OBJPROP_FONTSIZE,size);
   ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,name,OBJPROP_HIDDEN,true); ObjectSetInteger(0,name,OBJPROP_ZORDER,0);
   ObjectSetString(0,name,OBJPROP_FONT,strong && InpDashboardFont=="Segoe UI" ? "Segoe UI Semibold" : InpDashboardFont);
   ObjectSetString(0,name,OBJPROP_TEXT,label); ObjectSetString(0,name,OBJPROP_TOOLTIP,"\n");
}
void PaintIndicatorStrip() {
   int cw=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
   bool docked=ConsoleShowDashboard && !g_collapsed && g_lastLayout!=0;
   int left=docked && !g_right ? g_x+g_width+22 : 12,right=docked && g_right ? g_x-12 : cw-72;
   if(right-left<173) { ObjectsDeleteAll(0,g_prefix+"strip_"); return; }
   ChartCaption("symbol",left,19,g_chartSymbol+"   /   "+ConsoleTFName(g_tf),SX_TEXT,13,true);
   if(g_layers && InpShowMA) {
      ChartCaption("fast",left,48,"EMA "+IntegerToString(InpFastMA),SX_BLUE,8,true);
      ChartCaption("slow",left+72,48,"EMA "+IntegerToString(InpSlowMA),SX_GOLD,8,true);
   } else { ObjectDelete(0,g_prefix+"strip_fast"); ObjectDelete(0,g_prefix+"strip_slow"); }
   if(g_layers && InpShowVWAP) ChartCaption("vwap",left+144,48,"VWAP",SX_TEXT,8,true);
   else ObjectDelete(0,g_prefix+"strip_vwap");
   string stem=g_prefix+"strip_read";
   if(!g_strip) { ObjectsDeleteAll(0,stem); return; }
   int x=right-160,y=right-left>=435 ? 16 : 75;
   string card=stem+"Card";
   if(ObjectFind(0,card)<0) ObjectCreate(0,card,OBJ_RECTANGLE_LABEL,0,0,0);
   ObjectSetInteger(0,card,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSetInteger(0,card,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,card,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,card,OBJPROP_XSIZE,160); ObjectSetInteger(0,card,OBJPROP_YSIZE,138);
   ObjectSetInteger(0,card,OBJPROP_BGCOLOR,SX_CARD); ObjectSetInteger(0,card,OBJPROP_BORDER_TYPE,BORDER_FLAT);
   ObjectSetInteger(0,card,OBJPROP_COLOR,SX_EDGE); ObjectSetInteger(0,card,OBJPROP_BACK,false);
   ObjectSetInteger(0,card,OBJPROP_SELECTABLE,false); ObjectSetInteger(0,card,OBJPROP_HIDDEN,true);
   ObjectSetString(0,card,OBJPROP_TOOLTIP,"\n");
   ChartCaption("readTitle",x+10,y+8,"CHART INDICATORS",SX_GOLD,8,true);
   ChartCaption("readATR",x+10,y+28,"ATR   "+(g_consoleReady ? PriceText(g_atr) : "--"),SX_TEXT,9);
   ChartCaption("readST",x+10,y+46,"ST     "+(g_consoleReady ? Side(g_superDir) : "--"),g_consoleReady ? BiasColor(g_superDir) : SX_MUTED,9,true);
   ChartCaption("readSTC",x+10,y+64,"STC   "+(g_consoleReady ? Value(g_stc,1) : "--"),SX_TEXT,9);
   ChartCaption("readRSI",x+10,y+100,"RSI "+(g_consoleReady ? Value(g_rsi,1) : "--")+"   ADX "+(g_consoleReady ? Value(g_adx,1) : "--"),SX_TEXT,9);
   ChartCaption("readVOL",x+10,y+118,"VOL   "+(g_consoleReady ? Value(g_volumeRatio,2)+"x" : "--"),SX_TEXT,9);
}


int SignOf(double value,double deadband=0.0) {
   return value>deadband ? 1 : value < -deadband ? -1 : 0;
}

double SMAAt(int end,int period) {
   if(period<1 || end<period-1) return 0;
   double total=0;
   for(int i=end-period+1;i<=end;i++) total+=g_rates[i].close;
   return total/period;
}

double StochasticK(int end,int period) {
   if(end<period-1) return 50;
   double hi=g_rates[end].high,lo=g_rates[end].low;
   for(int i=end-period+1;i<end;i++) {
      hi=MathMax(hi,g_rates[i].high); lo=MathMin(lo,g_rates[i].low);
   }
   return hi>lo ? 100*(g_rates[end].close-lo)/(hi-lo) : 50;
}

int ParabolicATR(int last,double &line) {
   line=0;
   if(last<3) return 0;
   int first=(int)MathMax(1,last-160),side=g_rates[first].close>=g_rates[first-1].close ? 1 : -1;
   line=side>0 ? g_rates[first-1].low : g_rates[first-1].high;
   double extreme=side>0 ? g_rates[first].high : g_rates[first].low;
   double accel=0.04; int event=0;
   for(int i=first+1;i<=last;i++) {
      event=0;
      double next=line+side*accel*g_atrSeries[i-1];
      if(side>0) {
         next=MathMin(next,MathMin(g_rates[i-1].low,g_rates[i-2].low));
         if(g_rates[i].low<=next) { line=extreme; extreme=g_rates[i].low; side=-1; accel=0.04; event=-1; continue; }
         if(g_rates[i].high>extreme) { extreme=g_rates[i].high; accel=MathMin(0.32,accel+0.02); }
      } else {
         next=MathMax(next,MathMax(g_rates[i-1].high,g_rates[i-2].high));
         if(g_rates[i].high>=next) { line=extreme; extreme=g_rates[i].high; side=1; accel=0.04; event=1; continue; }
         if(g_rates[i].low<extreme) { extreme=g_rates[i].low; accel=MathMin(0.32,accel+0.02); }
      }
      line=next;
   }
   return event;
}

double CorrelationRSI(int last) {
   if(last<32) return 50;
   double avgPrice=0,avgMomentum=0;
   for(int i=last-19;i<=last;i++) {
      avgPrice+=g_rates[i].close/20; avgMomentum+=(g_rates[i].close-g_rates[i-3].close)/20;
   }
   double a=0,b=0,c=0;
   for(int i=last-19;i<=last;i++) {
      double px=g_rates[i].close-avgPrice,mom=g_rates[i].close-g_rates[i-3].close-avgMomentum;
      a+=px*mom; b+=px*px; c+=mom*mom;
   }
   double corr=b*c>0 ? MathMax(-1.0,MathMin(1.0,a/MathSqrt(b*c))) : 0;
   int length=(int)MathFloor(7+(1-corr)*10.5+0.5);
   double gain=0,loss=0;
   for(int i=last-length+1;i<=last;i++) {
      double delta=g_rates[i].close-g_rates[i-1].close;
      gain+=MathMax(0,delta); loss+=MathMax(0,-delta);
   }
   return gain+loss>0 ? 100*gain/(gain+loss) : 50;
}

bool AcceptUT(int side,int bar,int lastAccepted,int spacing) {
   return side!=0 && (lastAccepted<0 || bar-lastAccepted>=spacing);
}

int CooldownFlip(int k) {
   datetime endTime=g_rates[k].time;
   datetime seen=g_assets[g_active].utSeen, accepted=g_assets[g_active].utAccepted;
   bool save=g_consoleStrategy==UT_VISUAL_GAP;
   string suffix="";
   if(save) {
      suffix="uf"+IntegerToString(SymbolHash(IntegerToString(InpATRPeriod)+"|"+DoubleToString(InpATRMultiplier,8)+"|"+IntegerToString((int)InpSource)+"|"+IntegerToString(InpUTQuietBars)));
      if(seen==0) accepted=(datetime)ReadGV(suffix,0);
   }
   if(seen>endTime || accepted>endTime) { seen=0; accepted=0; }
   datetime original=accepted;
   int last=-1,begin=0;
   for(int i=k;i>=0;i--) {
      if(last<0 && accepted>0 && g_rates[i].time==accepted) last=i;
      if(begin==0 && g_rates[i].time<=MathMax((double)seen,(double)accepted)) begin=i+1;
      if(begin>0 && (last>=0 || accepted<g_rates[0].time)) break;
   }
   for(int i=begin;i<=k;i++) {
      if(AcceptUT(g_utEvents[i],i,last,InpUTQuietBars)) { last=i; accepted=g_rates[i].time; }
   }
   g_assets[g_active].utSeen=endTime;
   g_assets[g_active].utAccepted=accepted;
   g_assets[g_active].utRemaining=last>=0 ? (int)MathMax(0,InpUTQuietBars-(k-last)) : 0;
   if(save && accepted!=original) WriteGV(suffix,(double)accepted);
   return accepted==endTime ? g_utEvents[k] : 0;
}

bool ValueTurnGuards(int side,double rangeATR,double volumeRatio,double counterWick,double emaSlope,double location) {
   if(side==0 || rangeATR<0.45 || rangeATR>2.4 || volumeRatio<InpSTCVolumeRatio || counterWick>0.48) return false;
   if(side*emaSlope< -0.18) return false;
   return side>0 ? location<=0.50 : location>=0.50;
}

int STCValueTurn(int k,int flip) {
   int span=g_atrRatio>=1.25 ? 8 : g_atrRatio<=0.80 ? 20 : 14;
   if(k<51 || k<span) return 0;
   double lo=g_rates[k].low,hi=g_rates[k].high;
   for(int j=k-span+1;j<k;j++) { lo=MathMin(lo,g_rates[j].low); hi=MathMax(hi,g_rates[j].high); }
   g_gem.turnLow=lo-0.10*g_atr;
   g_gem.turnHigh=hi+0.10*g_atr;
   g_gem.targetScale=g_atrRatio>=1.25 ? 1.25 : g_atrRatio<=0.80 ? 0.80 : 1.0;
   if(flip==0 || hi<=lo || g_atr<=0) return 0;
   bool extreme=false;
   for(int j=k-InpStcLag;j<=k;j++) {
      if(flip>0 ? g_stcSeries[j]<=InpStcBuyZone : g_stcSeries[j]>=InpStcSellZone) extreme=true;
   }
   if(!extreme) return 0;
   MqlRates b=g_rates[k];
   double range=b.high-b.low;
   if(range<=0) return 0;
   double priorATR=0,shortVol=0,longVol=0;
   for(int j=0;j<k;j++) {
      double tr=SXTrueRange(g_rates[j].high,g_rates[j].low,j>0 ? g_rates[j-1].close : g_rates[j].close);
      if(j<50) priorATR+=tr/50.0;
      else priorATR=SXWilder(priorATR,tr,50);
   }
   for(int j=k-19;j<=k;j++) {
      double v=(double)g_rates[j].tick_volume;
      longVol+=v/20.0;
      if(j>=k-4) shortVol+=v/5.0;
   }
   if(priorATR<=0 || longVol<=0) return 0;
   double wick=flip>0 ? b.high-MathMax(b.open,b.close) : MathMin(b.open,b.close)-b.low;
   double slope=(g_fastSeries[k]-g_fastSeries[k-3])/(3*g_atr);
   return ValueTurnGuards(flip,range/priorATR,shortVol/longVol,wick/range,slope,(b.close-lo)/(hi-lo)) ? flip : 0;
}

datetime RangeWindow(datetime utc) {
   if(utc<=0) return 0;
   datetime start=(datetime)((long)utc/86400*86400+InpRangeStartUTC*3600);
   if(start>utc) start-=86400;
   if(InpRangeWeekday>=0) {
      MqlDateTime d; TimeToStruct(start,d);
      start-=(datetime)(((d.day_of_week-InpRangeWeekday+7)%7)*86400);
   }
   return utc-start<InpRangeWindowMinutes*60 ? start : 0;
}

// Use separate evidence for path direction, volatility and momentum.
int RegimeVote(int up,int down,double efficiency,double ratio,double trendFloor,double minRatio,double maxRatio,int need) {
   if(ratio<minRatio || ratio>maxRatio || efficiency<trendFloor) return 0;
   if(up>=need && up>down) return 1;
   if(down>=need && down>up) return -1;
   return 0;
}
int ExpansionRetest(int k) {
   if(k<22 || g_atrSeries[k-2]<=0) return 0;
   double high=g_rates[k-2].high,low=g_rates[k-2].low;
   for(int j=k-21;j<k-2;j++) {
      high=MathMax(high,g_rates[j].high);
      low=MathMin(low,g_rates[j].low);
   }
   double cushion=InpRetestToleranceATR*g_atrSeries[k-2];
   MqlRates breakout=g_rates[k-1],test=g_rates[k];
   if(breakout.close>high+cushion && test.low<=high+cushion && test.low>=high-cushion && test.close>high && test.close>test.open) return 1;
   if(breakout.close<low-cushion && test.high>=low-cushion && test.high<=low+cushion && test.close<low && test.close<test.open) return -1;
   return 0;
}
int VWAPRejection(int k) {
   MqlRates now=g_rates[k],prior=g_rates[k-1];
   double span=now.high-now.low;
   if(span<=0) return 0;
   double center=g_vwapSeries[k],base=g_vwapSeries[k-1],band=InpSnapbackDistanceATR*g_atrSeries[k-1];
   if(prior.close<base-band && now.close>now.open && now.close>prior.close && now.close<center &&
      (MathMin(now.close,now.open)-now.low)/span>=0.30) return 1;
   if(prior.close>base+band && now.close<now.open && now.close<prior.close && now.close>center &&
      (now.high-MathMax(now.close,now.open))/span>=0.30) return -1;
   return 0;
}
// Both horizons must agree; direction is taken from closed prices.
int HorizonDirection(int k,int fast,int slow,double atr) {
   if(fast<2 || slow<=fast || k<slow || atr<=0) return 0;
   double fastMove=g_rates[k].close-g_rates[k-fast].close;
   double slowMove=g_rates[k].close-g_rates[k-slow].close;
   double path=0;
   for(int i=k-slow+1;i<=k;i++) path+=MathAbs(g_rates[i].close-g_rates[i-1].close);
   if(path<=0 || MathAbs(slowMove)/path<InpPathEfficiency || MathAbs(fastMove)<0.20*atr) return 0;
   return Direction(fastMove)==Direction(slowMove) ? Direction(slowMove) : 0;
}
void BuildAdditionalSignals(int k) {
   if(k<2 || g_active<0 || g_active>=ArraySize(g_assets)) return;
   int flip=g_utEvents[k];
   g_engineSignals[UT_CLOSED_FLIP]=flip;
   g_engineSignals[UT_VALUE_TURN]=STCValueTurn(k,flip);
   if(!InpUseFormingBar || (int)g_consoleStrategy>=DUAL_UT_LINREG)
      g_engineSignals[UT_VISUAL_GAP]=CooldownFlip(k);
   int slow=InpPathBars, fast=(int)MathMax(2,slow/3);
   int horizon=HorizonDirection(k,fast,slow,g_atr);
   int votes[4];
   votes[0]=horizon;
   votes[1]=Direction(Source(g_rates[k])-g_utCurrent);
   votes[2]=g_kalmanDir;
   votes[3]=Direction(g_fastSeries[k]-g_fastSeries[k-1]);
   int up=0,down=0;
   for(int i=0;i<4;i++) { if(votes[i]>0) up++; else if(votes[i]<0) down++; }
   double path=0,eff=0;
   if(k>=slow) {
      for(int i=k-slow+1;i<=k;i++) path+=MathAbs(g_rates[i].close-g_rates[i-1].close);
      if(path>0) eff=MathAbs(g_rates[k].close-g_rates[k-slow].close)/path;
   }
   int agreement=RegimeVote(up,down,eff,g_atrRatio,InpPathEfficiency,InpRegimeMinRatio,InpRegimeMaxRatio,InpRegimeVotes);
   g_engineSignals[PATH_AGREEMENT]=agreement==horizon ? agreement : 0;
   g_engineSignals[EXPANSION_RETEST]=ExpansionRetest(k);
   g_engineSignals[VWAP_REJECTION]=VWAPRejection(k);
   g_engineSignals[DUAL_HORIZON]=horizon;
   double stop=0;
   g_engineSignals[PARABOLIC_ATR]=ParabolicATR(k,stop);
   if(k>=InpSlowMA) g_engineSignals[SIMPLE_MA_CROSS]=CrossDirection(SMAAt(k-1,InpFastMA)-SMAAt(k-1,InpSlowMA),SMAAt(k,InpFastMA)-SMAAt(k,InpSlowMA));
   g_engineSignals[RSI_EXTREMES]=g_rsi<30 ? 1 : g_rsi>70 ? -1 : 0;
   g_engineSignals[BAND_FADE]=g_closeCurrent<g_bandLower ? 1 : g_closeCurrent>g_bandUpper ? -1 : 0;
   double stoch=StochasticK(k,5);
   g_engineSignals[STOCH_EXTREMES]=stoch<20 ? 1 : stoch>80 ? -1 : 0;
   g_engineSignals[HISTOGRAM_CROSS]=CrossDirection(g_gem.priorHist,g_macd);
   int adaptive=SignOf(CorrelationRSI(k)-50,2);
   int core=ClockBias();
   g_engineSignals[ADAPTIVE_RSI_VOTE]=core!=0 && adaptive==core && ClockVotes(core)>=InpClockMinVotes ? core : 0;
   int tally=votes[1]+g_quantumSuperDir+adaptive+g_kalmanDir;
   g_engineSignals[TREND_CYCLE_VOTE]=tally>=3 ? 1 : tally<=-3 ? -1 : 0;
   g_gem.pathEfficiency=eff;
   g_gem.horizonSide=horizon;
   g_gem.regimeVotes=(up>down ? up : down);
}

void ProcessSessionBracket() {
   if(!g_auto || !g_consoleReady || g_uncertain || g_exitRequested || g_consolePortfolioExit || ArraySize(g_positions)>0 || WorkingOrders()>0) return;
   datetime utc=TimeCurrent()-InpRangeServerOffsetMinutes*60;
   datetime start=RangeWindow(utc);
   if(start<=0) { g_message="Waiting for range window (UTC)"; return; }
   string key=g_guardKey+"R"+IntegerToString(SymbolHash(g_symbol));
   if(!GlobalVariableCheck(key)) GlobalVariableSet(key,0);
   double previous=GlobalVariableGet(key);
   if(previous>=(double)start) return;
   MqlRates closed[];
   ArraySetAsSeries(closed,false);
   // Anchor the range to bars that had already closed when the session began.
   datetime anchor=(datetime)(start+InpRangeServerOffsetMinutes*60);
   int shift=iBarShift(g_symbol,InpRangeTF,anchor,false);
   if(shift<0 || CopyRates(g_symbol,InpRangeTF,shift+1,InpRangeBars,closed)!=InpRangeBars) { g_message="Range history unavailable"; return; }
   double high=closed[0].high,low=closed[0].low;
   for(int i=1;i<InpRangeBars;i++) { high=MathMax(high,closed[i].high); low=MathMin(low,closed[i].low); }
   if(high<=low) return;
   string why="";
   bool buy=InpAllowBuy,sell=InpAllowSell;
   if(!buy && !sell) return;
   if((buy && !EntryGate(1,why)) || (sell && !EntryGate(-1,why))) { g_message=why; return; }
   if(buy && sell && (IsNetting() || (!NoPositionCaps() && (ConsoleMaxPositions<2 || PortfolioExposureCount()+2>InpMaxPortfolioPositions)))) {
      g_message="Two-sided bracket needs hedging and two available slots"; return;
   }
   if(!GlobalVariableSetOnCondition(key,(double)start,previous)) return;
   GlobalVariablesFlush();
   double buffer=MathMax(TickSize(),InpRangeBufferATR*g_atr);
   MqlTick quote;
   if(!Tick(quote)) { GlobalVariableSetOnCondition(key,previous,(double)start); return; }
   if((buy && high+buffer<=quote.ask) || (sell && low-buffer>=quote.bid)) { g_message="Opening range already crossed"; return; }
   bool first=buy ? PlacePending(1,ENTRY_STOP,false,high+buffer) : PlacePending(-1,ENTRY_STOP,false,low-buffer);
   if(!first) { if(!g_uncertain) GlobalVariableSetOnCondition(key,previous,(double)start); return; }
   if(buy && sell && !PlacePending(-1,ENTRY_STOP,false,low-buffer,true) && !g_uncertain) {
   }
}

// Normalized rounded rectangles form one robot at every supported chart size.
void RobotPart(uint &pixels[],int size,double x,double y,double w,double h,double radius,color ink,int alpha) {
   int x0=(int)MathMax(0,MathFloor(x*size)),y0=(int)MathMax(0,MathFloor(y*size));
   int x1=(int)MathMin(size,MathCeil((x+w)*size)),y1=(int)MathMin(size,MathCeil((y+h)*size));
   uint packed=((uint)alpha<<24)|(((uint)ink&255)<<16)|((uint)ink&65280)|(((uint)ink>>16)&255);
   for(int j=y0;j<y1;j++) for(int i=x0;i<x1;i++) {
      double px=(i+.5)/size,py=(j+.5)/size;
      double dx=px-MathMax(x+radius,MathMin(px,x+w-radius));
      double dy=py-MathMax(y+radius,MathMin(py,y+h-radius));
      if(dx*dx+dy*dy<=radius*radius) pixels[j*size+i]=packed;
   }
}
void LogoArt(uint &pixels[],int size,int alpha) {
   if(InpRobotBody==WINGED_DRONE) { WingedArt(pixels,size,alpha); return; }
   if(ArrayResize(pixels,size*size)!=size*size) return;
   ArrayInitialize(pixels,0);
   RobotPart(pixels,size,.48,.09,.04,.17,.018,LogoInk(6),alpha);
   RobotPart(pixels,size,.442,.025,.116,.116,.058,LogoInk(7),alpha);
   RobotPart(pixels,size,.466,.043,.035,.035,.017,LogoInk(8),alpha);
   RobotPart(pixels,size,.052,.39,.16,.29,.073,LogoInk(3),alpha);
   RobotPart(pixels,size,.788,.39,.16,.29,.073,LogoInk(3),alpha);
   RobotPart(pixels,size,.13,.205,.74,.56,.17,LogoInk(0),alpha);
   RobotPart(pixels,size,.149,.232,.702,.51,.148,LogoInk(1),alpha);
   RobotPart(pixels,size,.197,.322,.606,.325,.118,LogoInk(2),alpha);
   for(int eye=0;eye<2;eye++) {
      double x=eye==0 ? .312 : .602;
      RobotPart(pixels,size,x,.39,.086,.126,.041,LogoInk(6),alpha);
      RobotPart(pixels,size,x+.011,.397,.026,.034,.012,LogoInk(8),alpha);
      RobotPart(pixels,size,x-.051,.531,.083,.031,.015,LogoInk(4),alpha);
   }
   RobotPart(pixels,size,.463,.522,.074,.029,.014,LogoInk(5),alpha);
   RobotPart(pixels,size,.335,.768,.33,.103,.047,LogoInk(3),alpha);
   RobotPart(pixels,size,.286,.807,.428,.128,.061,LogoInk(1),alpha);
   RobotPart(pixels,size,.40,.839,.20,.035,.017,LogoInk(5),alpha);
   RobotPart(pixels,size,.315,.906,.122,.068,.032,LogoInk(0),alpha);
   RobotPart(pixels,size,.563,.906,.122,.068,.032,LogoInk(0),alpha);
}

void FlowClearInfo(FlowTickInfo &info) {
   info.moves=0; info.up=0; info.down=0; info.direction=0;
   info.imbalance=0.5; info.driftPts=0; info.halfDriftPts=0; info.velocity=0; info.spreadPts=0; info.rate=0;
   info.ready=false;
}
long FlowQuoteMs(MqlTick &q) {
#ifdef __MQL5__
   if(q.time_msc>0) return (long)q.time_msc;
#endif
   return (long)q.time*1000;
}
int FlowBook(string symbol,bool create) {
   for(int i=0;i<g_tkBooks;i++) if(g_tkSymbol[i]==symbol) return i;
   if(!create || g_tkBooks>=FLOW_TICK_BOOKS) return -1;
   int b=g_tkBooks; g_tkBooks++;
   g_tkSymbol[b]=symbol; g_tkCount[b]=0; g_tkHead[b]=0; g_tkConfDir[b]=0; g_tkConfSince[b]=0; g_tkConfSeen[b]=0;
   return b;
}
// Records one quote change for the active symbol. The chart symbol always keeps a book; other
// symbols are tracked only when the tick engine or the tick veto needs them.
void FlowRecordQuote() {
   bool chartSymbol=(g_symbol==g_chartSymbol);
   if(!chartSymbol && g_consoleStrategy!=QUOTE_FLOW && !InpTickVeto) return;
   MqlTick q; if(!Tick(q)) return;
   int b=FlowBook(g_symbol,true); if(b<0) return;
   long ms=FlowQuoteMs(q);
   double mid=(q.bid+q.ask)*0.5;
   int base=b*FLOW_TICK_CAP;
   if(g_tkCount[b]>0) {
      int last=(g_tkHead[b]+FLOW_TICK_CAP-1)%FLOW_TICK_CAP;
      if(ms<g_tkMs[base+last]) { g_tkCount[b]=0; g_tkHead[b]=0; }
      else if(g_tkMid[base+last]==mid) { g_tkSpr[base+last]=q.ask-q.bid; return; }
   }
   int h=g_tkHead[b];
   g_tkMid[base+h]=mid; g_tkMs[base+h]=ms; g_tkSpr[base+h]=q.ask-q.bid;
   g_tkHead[b]=(h+1)%FLOW_TICK_CAP;
   if(g_tkCount[b]<FLOW_TICK_CAP) g_tkCount[b]++;
}
bool FlowTickStats(string symbol,FlowTickInfo &info) {
   FlowClearInfo(info);
   int b=FlowBook(symbol,false); if(b<0) return false;
   int count=g_tkCount[b]; if(count<3) return false;
   int base=b*FLOW_TICK_CAP;
   int newest=(g_tkHead[b]+FLOW_TICK_CAP-1)%FLOW_TICK_CAP;
   long newestMs=g_tkMs[base+newest];
   long windowMs=(long)InpTickWindowSeconds*1000;
   long nowMs=(long)TimeCurrent()*1000;
   if(nowMs-newestMs>windowMs) return false;
   long endMs=nowMs>newestMs ? nowMs : newestMs;
   long cutoff=endMs-windowMs,halfCut=endMs-windowMs/2;
   int taken=0,oldest=newest;
   for(int k=0;k<count;k++) {
      int idx=(newest-k+FLOW_TICK_CAP)%FLOW_TICK_CAP;
      if(g_tkMs[base+idx]<cutoff) break;
      taken++; oldest=idx;
   }
   if(taken<3) return false;
   double point=SymbolInfoDouble(symbol,SYMBOL_POINT); if(point<=0) return false;
   double previous=g_tkMid[base+oldest],first=previous,halfMid=previous;
   bool halfSet=false;
   int up=0,down=0;
   for(int j=1;j<taken;j++) {
      int idx=(oldest+j)%FLOW_TICK_CAP;
      double mid=g_tkMid[base+idx];
      if(mid>previous) up++; else if(mid<previous) down++;
      if(!halfSet && g_tkMs[base+idx]>=halfCut) { halfMid=previous; halfSet=true; }
      previous=mid;
   }
   int moves=up+down; if(moves<1) return false;
   info.up=up; info.down=down; info.moves=moves;
   info.imbalance=(double)MathMax(up,down)/(double)moves;
   info.direction=up>down ? 1 : (down>up ? -1 : 0);
   info.driftPts=(previous-first)/point;
   info.halfDriftPts=halfSet ? (previous-halfMid)/point : 0;
   double spanSec=MathMax(1.0,(double)(endMs-g_tkMs[base+oldest])/1000.0);
   info.velocity=info.driftPts/spanSec;
   info.rate=(double)moves/spanSec;
   info.spreadPts=g_tkSpr[base+newest]/point;
   info.ready=moves>=InpTickMinMoves;
   return info.ready;
}
// +1 / -1 when quote flow is one-sided, still moving in its second half, and wide enough to clear the spread.
int FlowTickDecisionReason(string symbol,FlowTickInfo &info,string &reason) {
   if(!FlowTickStats(symbol,info)) {
      reason="Tick flow warming up: "+IntegerToString(info.moves)+"/"+IntegerToString(InpTickMinMoves)+" quote moves";
      return 0;
   }
   int dir=info.direction;
   if(dir==0) { reason="Tick flow has no directional majority"; return 0; }
   if(info.imbalance<InpTickMinImbalance) { reason="Tick imbalance below threshold"; return 0; }
   if(InpTickMinRate>0 && info.rate<InpTickMinRate) { reason="Tick move rate below threshold"; return 0; }
   if(dir*info.driftPts<MathMax(InpTickMinDriftPts,InpTickDriftSpreadMult*info.spreadPts)) {
      reason="Tick drift below points / spread threshold"; return 0;
   }
   if(dir*info.halfDriftPts<=0) { reason="No continuing drift in the second half of the tick window"; return 0; }
   if(info.spreadPts>InpTickMaxSpreadShare*MathAbs(info.driftPts)) {
      reason="Spread is too large relative to tick drift"; return 0;
   }
   reason="";
   return dir;
}
int FlowTickDecision(string symbol,FlowTickInfo &info) {
   string reason="";
   return FlowTickDecisionReason(symbol,info,reason);
}
int FlowTickSignalNow(string symbol) {
   FlowTickInfo info;
   return FlowTickDecision(symbol,info);
}
// Veto only when strong tick flow runs AGAINST the candidate. Missing or thin tick data never blocks.
bool FlowTickAgrees(int direction,string &why) {
   if(!InpTickVeto) return true;
   FlowTickInfo info;
   if(!FlowTickStats(g_symbol,info)) return true;
   if(info.direction!=0 && info.direction!=direction && info.imbalance>=InpTickMinImbalance &&
      info.direction*info.driftPts>=InpTickMinDriftPts) { why="Opposing tick flow"; return false; }
   return true;
}
// True inside the quiet window around server midnight, when spreads and swaps distort quotes.
bool FlowRolloverQuiet() {
   if(InpRolloverGuardMinutes<=0) return false;
   MqlDateTime t; TimeToStruct(TimeCurrent(),t);
   int minute=t.hour*60+t.min,half=(InpRolloverGuardMinutes+1)/2;
   return minute>=1440-half || minute<half;
}
string FlowTickRegime(FlowTickInfo &info) {
   if(info.moves<InpTickMinMoves) return "Thin";
   if(info.imbalance<0.55) return "Choppy";
   if(info.imbalance>=InpTickMinImbalance && MathAbs(info.driftPts)>=MathMax(InpTickMinDriftPts,InpTickDriftSpreadMult*info.spreadPts)) return "Burst";
   return "Drifting";
}
// Direction must hold continuously for InpTickConfirmSeconds before an entry is allowed.
bool FlowTickConfirmed(string symbol,int direction) {
   int b=FlowBook(symbol,false); if(b<0) return false;
   datetime now=TimeCurrent();
   if(direction==0) { g_tkConfDir[b]=0; return false; }
   if(g_tkConfDir[b]!=direction || now-g_tkConfSeen[b]>3) { g_tkConfDir[b]=direction; g_tkConfSince[b]=now; }
   g_tkConfSeen[b]=now;
   return now-g_tkConfSince[b]>=InpTickConfirmSeconds;
}
// True when the newest spread is far above the average spread of the same window (news, thin liquidity).
bool FlowSpreadSpike(string symbol) {
   if(InpTickSpreadSpikeMult<=0) return false;
   int b=FlowBook(symbol,false); if(b<0) return false;
   int count=g_tkCount[b]; if(count<8) return false;
   int base=b*FLOW_TICK_CAP,newest=(g_tkHead[b]+FLOW_TICK_CAP-1)%FLOW_TICK_CAP;
   long cutoff=g_tkMs[base+newest]-(long)InpTickWindowSeconds*1000;
   double sum=0; int n=0;
   for(int k=1;k<count;k++) {
      int idx=(newest-k+FLOW_TICK_CAP)%FLOW_TICK_CAP;
      if(g_tkMs[base+idx]<cutoff) break;
      sum+=g_tkSpr[base+idx]; n++;
   }
   if(n<5) return false;
   double avg=sum/n; if(avg<=0) return false;
   return g_tkSpr[base+newest]>InpTickSpreadSpikeMult*avg;
}
bool FlowLiveOnly() { return InpTickLiveEntry && g_consoleStrategy==QUOTE_FLOW; }
void FlowTickEntry() {
   if(!FlowLiveOnly() || !g_auto || !g_consoleReady) return;
   if(ReadGV("uncertain",0)>0 || ReadGV("inflight",0)>0) g_uncertain=true;
   if(g_uncertain) { g_message="RECONCILE: inspect broker orders first"; return; }
   string why=TradePermissionIssue();
   if(why!="") { g_message="ALGO OFF: "+why; return; }
   if(g_dailyLock || g_peakLock || g_profitLock || g_weeklyLock || g_emergency) { g_message="RISK LOCK: check equity protection"; return; }
   if(g_exitRequested || g_consolePortfolioExit) { g_message="Owned exit still in progress"; return; }
   FlowTickInfo info;
   int direction=FlowTickDecisionReason(g_symbol,info,why);
   g_candidate=direction;
   bool confirmed=FlowTickConfirmed(g_symbol,direction);
   if(direction==0) { g_message=why; return; }
   if(!confirmed) { g_message="Tick direction confirmation in progress"; return; }
   if(!NoTimeRestrictions() && FlowRolloverQuiet()) { g_message="Rollover quiet window"; return; }
   if(!NoSpreadQuoteLimits() && FlowSpreadSpike(g_symbol)) { g_message="Tick spread spike"; return; }
   int limit=IsNetting() ? 1 : ConsoleMaxPositions;
   if(WorkingOrders()>0) { g_message="Waiting for owned pending order"; return; }
   if((IsNetting() || !NoPositionCaps()) && ArraySize(g_positions)>=limit) { g_message="Tick position cap"; return; }
   datetime now=TimeCurrent();
   if(!NoCooldowns() && now-(datetime)ReadGV("tickfire",0)<InpTickCooldownSeconds) { g_message="Tick entry cooldown"; return; }
   datetime bar=iTime(g_symbol,g_tf,0);
   if(bar<=0) { g_message="Waiting for current broker bar"; return; }
   double sameBar=((datetime)ReadGV("tickbar",0)==bar) ? ReadGV("tickbarn",0) : 0;
   if(!NoCooldowns() && sameBar>=InpTickMaxEntriesPerBar) { g_message="Tick entries per bar cap"; return; }
   long hourCode=(long)now/3600;
   double hourCount=((long)ReadGV("tickhr",0)==hourCode) ? ReadGV("tickhrn",0) : 0;
   if(!NoCooldowns() && InpTickMaxEntriesPerHour>0 && hourCount>=InpTickMaxEntriesPerHour) { g_message="Tick entries per hour cap"; return; }
   datetime lastTry=(datetime)ReadGV("ticktry",0);
   if(lastTry>0 && now>=lastTry && now-lastTry<InpClockRetrySeconds) return;
   // ActivateAsset restores the symbol's snapshot scalars. Only refresh on a new bar (ProcessAsset).
   g_lastSignalDir=direction;
   if(!SignalFilters(direction,why)) { g_message="Tick signal filtered: "+why; return; }
   if(!EntryGate(direction,why)) { g_message="Blocked: "+why; return; }
   SXEntry style=AutomaticEntryStyle();
   if(!SupportsRequest(style,why)) { g_message="Broker: "+why; return; }
   MqlTick q; double px=0,sl=0,tp=0;
   if(!Tick(q)) { g_message="Waiting for valid broker quote"; return; }
   if(!EntryPrices(direction,style,0,q,px,sl,tp,why) || !AutoEntryQuality(q.ask-q.bid,px,sl,tp,why)) { g_message=why; return; }
   double volume=RiskLots(direction,px,sl,false);
   if(volume<=0) { g_message="Risk size below broker minimum or symbol valuation unavailable"; return; }
   if(!PortfolioRiskAllows(direction,volume,px,sl)) { g_message="Aggregate stop-risk cap"; return; }
   WriteGV("ticktry",(double)now);
   WriteGV("inflight",(double)bar); GlobalVariablesFlush();
   bool accepted=false;
   accepted=style==ENTRY_MARKET ? OpenPosition(direction,false) : PlacePending(direction,style,false,0);
   WriteGV("inflight",0);
   if(accepted || g_uncertain) {
      WriteGV("tickfire",(double)now); WriteGV("tickbar",(double)bar); WriteGV("tickbarn",sameBar+1);
      WriteGV("tickhr",(double)hourCode); WriteGV("tickhrn",hourCount+1);
   }
   GlobalVariablesFlush();
   if(accepted) { DrawSignal(bar,direction); Notify(Side(direction)+" tick flow accepted"); }
}
int FlowPeakSlot(ulong ticket,bool create) {
   int freeAt=-1;
   for(int i=0;i<FLOW_PEAK_SLOTS;i++) {
      if(g_pkTicket[i]==ticket) return i;
      if(g_pkTicket[i]==0 && freeAt<0) freeAt=i;
   }
   if(!create || freeAt<0) return -1;
   g_pkTicket[freeAt]=ticket; g_pkSymbol[freeAt]=g_symbol; g_pkPeak[freeAt]=0;
   return freeAt;
}
void FlowPeakPurge() {
   for(int i=0;i<FLOW_PEAK_SLOTS;i++) {
      if(g_pkTicket[i]==0 || g_pkSymbol[i]!=g_symbol) continue;
      bool alive=false;
      for(int j=0;j<ArraySize(g_positions);j++) if(g_positions[j].ticket==g_pkTicket[i]) { alive=true; break; }
      if(!alive) { g_pkTicket[i]=0; g_pkPeak[i]=0; g_pkSymbol[i]=""; }
   }
}
// Closes a position that has given back InpGivebackPct of its best open profit, once that best profit
// reached InpGivebackMinATR x ATR. Peak values live in memory; after a restart tracking begins again.
void FlowGivebackExit() {
   if(!InpGivebackExit || g_atr<=0) return;
   FlowPeakPurge();
   MqlTick q; if(!Tick(q)) return;
   double bid=q.bid,ask=q.ask;
   if(bid<=0 || ask<=0) return;
   bool closedAny=false;
   for(int i=ArraySize(g_positions)-1;i>=0;i--) {
      double gain=g_positions[i].direction>0 ? bid-g_positions[i].open : g_positions[i].open-ask;
      int slot=FlowPeakSlot(g_positions[i].ticket,true); if(slot<0) continue;
      if(gain>g_pkPeak[slot]) g_pkPeak[slot]=gain;
      double peak=g_pkPeak[slot];
      if(peak<InpGivebackMinATR*g_atr) continue;
      if(gain>peak*(1.0-InpGivebackPct/100.0)) continue;
      if(ClosePosition(g_positions[i],g_positions[i].lots)) {
         Log("Give-back exit on "+g_symbol+" after "+DoubleToString(100.0*(peak-gain)/peak,0)+"% of the peak profit returned");
         g_pkTicket[slot]=0; g_pkPeak[slot]=0; g_pkSymbol[slot]=""; closedAny=true;
      }
   }
   if(closedAny) ConsoleLoadPositions();
}
// Closes a position when strong tick flow turns against it (profit-only by default).
void FlowTickReverseExit() {
   if(!InpTickReverseExit || g_uncertain) return;
   datetime now=TimeCurrent();
   if(now-(datetime)ReadGV("tickexit",0)<2) return;
   FlowTickInfo info;
   int flow=FlowTickDecision(g_symbol,info);
   if(flow==0) return;
   ConsoleLoadPositions();
   int closed=0; bool tried=false;
   for(int i=ArraySize(g_positions)-1;i>=0;i--) {
      if(g_positions[i].direction==flow) continue;
      if(InpTickReverseProfitOnly && g_positions[i].profit<=0) continue;
      if(now-g_positions[i].opened<InpTickReverseMinHoldSec) continue;
      tried=true;
      if(ClosePosition(g_positions[i],g_positions[i].lots)) closed++;
   }
   if(tried) WriteGV("tickexit",(double)now);
   if(closed>0) { Log("Tick reversal exit closed "+IntegerToString(closed)+" position(s) on "+g_symbol); ConsoleLoadPositions(); }
}
void FlowTickExits() {
   if(!g_consoleReady || g_uncertain) return;
   FlowGivebackExit();
   FlowTickReverseExit();
}
string FlowTickText() {
   FlowTickInfo info;
   if(!FlowTickStats(g_chartSymbol,info)) return "Collecting quotes";
   int d=FlowTickDecision(g_chartSymbol,info);
   return (d!=0 ? Side(d) : FlowTickRegime(info))+"  "+DoubleToString(100.0*info.imbalance,0)+"%  "+DoubleToString(info.driftPts,1)+" pts  "+DoubleToString(info.rate,1)+"/s";
}
color FlowTickColor() {
   FlowTickInfo info;
   if(!FlowTickStats(g_chartSymbol,info)) return SX_MUTED;
   return BiasColor(FlowTickDecision(g_chartSymbol,info));
}
string FlowGuardText() {
   return Value(g_dayLoss,1)+"% / "+Value(g_weekLoss,1)+"% / "+Value(g_drawdown,1)+"%";
}
int FlowWeekCode() { return (int)(((long)TimeCurrent()/86400-4)/7); }
void FlowEmergencyTrigger() {
   g_auto=false; g_emergency=true; WriteGuard("emergency",1); GlobalVariablesFlush();
   RequestPortfolioExit("Emergency stop");
}
// Press X twice within five seconds on the chart: flatten owned exposure and lock new entries.
void FlowKey(int key) {
   if(key!=88) return;
   datetime now=TimeLocal();
   if(g_emergencyArmed==0 || now>g_emergencyArmed) {
      g_emergencyArmed=now+5;
      Log("Press X again within five seconds for EMERGENCY stop");
      return;
   }
   g_emergencyArmed=0; FlowEmergencyTrigger(); PaintPanel();
}
double LeaseStamp() {
   long chart=ChartID();
   int tag=(int)(chart%900000)+1;
   return (double)((long)TimeLocal()*1000000+(long)tag);
}
bool FlowLeaseAcquire() {
   if(g_tester || !InpUseInstanceLease) return true;
   string scope=AccountInfoString(ACCOUNT_SERVER)+"|"+IntegerToString(ConsoleMagic);
   if(InpAssets==ASSET_CHART) scope+="|"+g_chartSymbol;
   g_leaseKey="NSGLease_"+IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN))+"_"+IntegerToString(SymbolHash(scope));
   if(!GlobalVariableCheck(g_leaseKey)) GlobalVariableTemp(g_leaseKey);
   double prior=GlobalVariableGet(g_leaseKey);
   if(prior>0 && MathAbs((double)TimeLocal()-MathFloor(prior/1000000.0))<FLOW_LEASE_SECONDS) return false;
   double next=LeaseStamp();
   if(!GlobalVariableSetOnCondition(g_leaseKey,next,prior)) return false;
   g_leaseToken=next; return true;
}
void FlowLeaseBeat() {
   if(g_tester || !InpUseInstanceLease || g_leaseToken<=0) return;
   double next=LeaseStamp();
   if(GlobalVariableSetOnCondition(g_leaseKey,next,g_leaseToken)) { g_leaseToken=next; return; }
   g_leaseToken=0; g_auto=false;
   Log("Another chart owns this instance. Expert removed.");
   ExpertRemove();
}
void FlowLeaseRelease() {
   if(g_leaseToken>0 && g_leaseKey!="") GlobalVariableSetOnCondition(g_leaseKey,0,g_leaseToken);
   g_leaseToken=0;
}

int FlowVoteCore(int n,int last) {
   for(int k=0;k<9;k++) g_voteRead[k]=0;
   g_voteBuyVotes=0; g_voteSellVotes=0; g_voteAdx=0; g_votePlusDI=0; g_voteMinusDI=0;
   int look=InpVoteSweepLookback;
   if(last<2 || last>=n || last<look+2) return 0;
   int fp=InpVoteEmaFast,sp=InpVoteEmaSlow,mp=InpVoteEmaMid,lp=InpVoteLongEma,rp=InpVoteRsiPeriod,ap=InpVoteAdxPeriod;
   double ef=g_voteClose[0],es=ef,em=ef,el=ef,efPrev=ef,esPrev=ef;
   double gain=0,loss=0,rsi=50,rsiPrev=50;
   double trS=0,pS=0,mS=0,adx=0,dxSum=0; int dxN=0;
   for(int i=0;i<=last;i++) {
      double c=g_voteClose[i];
      if(i>0) {
         efPrev=ef; esPrev=es;
         ef+=2.0/(fp+1.0)*(c-ef); es+=2.0/(sp+1.0)*(c-es); em+=2.0/(mp+1.0)*(c-em); el+=2.0/(lp+1.0)*(c-el);
         double d=c-g_voteClose[i-1];
         if(i<=rp) { gain+=MathMax(0,d)/rp; loss+=MathMax(0,-d)/rp; }
         else { gain=(gain*(rp-1)+MathMax(0,d))/rp; loss=(loss*(rp-1)+MathMax(0,-d))/rp; }
         rsiPrev=rsi;
         if(i>=rp) rsi=loss<=0 ? 100.0 : 100.0-100.0/(1.0+gain/loss);
         double tr=MathMax(g_voteHigh[i]-g_voteLow[i],MathMax(MathAbs(g_voteHigh[i]-g_voteClose[i-1]),MathAbs(g_voteLow[i]-g_voteClose[i-1])));
         double up=g_voteHigh[i]-g_voteHigh[i-1],dn=g_voteLow[i-1]-g_voteLow[i];
         double pdm=(up>dn && up>0) ? up : 0.0,mdm=(dn>up && dn>0) ? dn : 0.0;
         if(i<=ap) { trS+=tr; pS+=pdm; mS+=mdm; }
         else { trS=trS-trS/ap+tr; pS=pS-pS/ap+pdm; mS=mS-mS/ap+mdm; }
         if(i>=ap && trS>0) {
            double pdi=100.0*pS/trS,mdi=100.0*mS/trS,dx=(pdi+mdi)>0 ? 100.0*MathAbs(pdi-mdi)/(pdi+mdi) : 0.0;
            if(dxN<ap) { dxSum+=dx; dxN++; if(dxN==ap) adx=dxSum/ap; }
            else adx=(adx*(ap-1)+dx)/ap;
            if(i==last) { g_votePlusDI=pdi; g_voteMinusDI=mdi; }
         }
      }
   }
   g_voteAdx=adx;
   double close=g_voteClose[last],open=g_voteOpen[last],high=g_voteHigh[last],low=g_voteLow[last];
   // 0 fast/slow EMA direction
   g_voteRead[0]=ef>es ? 1 : ef<es ? -1 : 0;
   // 1 long EMA side (needs enough history to settle)
   g_voteRead[1]=last>=lp ? (close>el ? 1 : close<el ? -1 : 0) : 0;
   // 2 three-EMA ribbon order
   g_voteRead[2]=(ef>es && es>em) ? 1 : (ef<es && es<em) ? -1 : 0;
   // 3 EMA cross on the closed bar
   g_voteRead[3]=(efPrev<=esPrev && ef>es) ? 1 : (efPrev>=esPrev && ef<es) ? -1 : 0;
   // 4 liquidity-sweep rejection: wick through the prior swing, close back inside
   double priorLow=g_voteLow[last-1],priorHigh=g_voteHigh[last-1];
   for(int j=2;j<=look;j++) { priorLow=MathMin(priorLow,g_voteLow[last-j]); priorHigh=MathMax(priorHigh,g_voteHigh[last-j]); }
   g_voteRead[4]=(low<priorLow && close>priorLow && close>open) ? 1 : (high>priorHigh && close<priorHigh && close<open) ? -1 : 0;
   // 5 fair-value-gap retrace: recent three-bar gap, price dips into it and closes back out
   for(int k=last-2;k>=last-10 && k>=0 && g_voteRead[5]==0;k--) {
      double gapLowUp=g_voteHigh[k],gapHighUp=g_voteLow[k+2];
      double gapHighDn=g_voteLow[k],gapLowDn=g_voteHigh[k+2];
      if(gapHighUp>gapLowUp && k+2<last && low<=gapHighUp && close>gapHighUp && close>open) g_voteRead[5]=1;
      else if(gapHighDn>gapLowDn && k+2<last && high>=gapLowDn && close<gapLowDn && close<open) g_voteRead[5]=-1;
   }
   // 6 RSI zone pullback inside the EMA trend
   g_voteRead[6]=(ef>es && rsiPrev<=45.0 && rsi>45.0) ? 1 : (ef<es && rsiPrev>=55.0 && rsi<55.0) ? -1 : 0;
   // 7 RSI midline cross
   g_voteRead[7]=(rsiPrev<=50.0 && rsi>50.0) ? 1 : (rsiPrev>=50.0 && rsi<50.0) ? -1 : 0;
   // 8 structure break: close beyond the prior swing extreme
   g_voteRead[8]=close>priorHigh ? 1 : close<priorLow ? -1 : 0;
   for(int r=0;r<9;r++) { if(g_voteRead[r]>0) g_voteBuyVotes++; else if(g_voteRead[r]<0) g_voteSellVotes++; }
   if(InpVoteAdxMin>0 && adx<InpVoteAdxMin) return 0;
   if(g_voteBuyVotes>=InpVoteMinVotes && g_voteBuyVotes>g_voteSellVotes && (InpVoteAdxMin<=0 || g_votePlusDI>g_voteMinusDI)) return 1;
   if(g_voteSellVotes>=InpVoteMinVotes && g_voteSellVotes>g_voteBuyVotes && (InpVoteAdxMin<=0 || g_voteMinusDI>g_votePlusDI)) return -1;
   return 0;
}
int FlowVoteSignal(int last) {
   int n=last+1;
   ArrayResize(g_voteOpen,n); ArrayResize(g_voteHigh,n); ArrayResize(g_voteLow,n); ArrayResize(g_voteClose,n);
   for(int i=0;i<n;i++) { g_voteOpen[i]=g_rates[i].open; g_voteHigh[i]=g_rates[i].high; g_voteLow[i]=g_rates[i].low; g_voteClose[i]=g_rates[i].close; }
   return FlowVoteCore(n,last);
}
void FlowSlipRecord(double requested,double filled,int direction) {
   if(InpSlipPauseRatio<=0 || InpSlippagePoints<=0 || g_consolePoint<=0 || requested<=0 || filled<=0) return;
   double slip=direction*(filled-requested)/g_consolePoint;
   g_slipCount++;
   g_slipAvg=g_slipCount==1 ? slip : g_slipAvg+0.3*(slip-g_slipAvg);
   if(g_slipCount>=3 && g_slipAvg>InpSlipPauseRatio*InpSlippagePoints) {
      g_slipPausedUntil=TimeCurrent()+InpSlipPauseMinutes*60;
      Log("Entries paused "+IntegerToString(InpSlipPauseMinutes)+" min: average fill slippage "+DoubleToString(g_slipAvg,1)+" points");
      g_slipCount=0; g_slipAvg=0;
   }
}
bool FlowSlipPaused() { return g_slipPausedUntil>TimeCurrent(); }
double FlowTrendFit(int n,int len) {
   if(len<5 || n<len) return 0;
   double sx=0,sy=0,sxx=0,syy=0,sxy=0;
   for(int k=0;k<len;k++) { double x=k,y=g_rates[n-len+k].close; sx+=x; sy+=y; sxx+=x*x; syy+=y*y; sxy+=x*y; }
   double den=MathSqrt((len*sxx-sx*sx)*(len*syy-sy*sy));
   return den>0 ? (len*sxy-sx*sy)/den : 0;
}

// Confirm a fast ATR reversal with the bias of a second, slower trail.
int MakeTrail(MqlRates &bars[],int count,int period,double factor,double &series[]) {
   if(ArrayResize(series,count)!=count || count<=period) return 0;
   ArrayInitialize(series,0);
   double total=0,atr=0,stop=0,previous=0;
   for(int i=0;i<count;i++) {
      double value=Source(bars[i]);
      double tr=SXTrueRange(bars[i].high,bars[i].low,i>0 ? bars[i-1].close : bars[i].close);
      if(i<period) { total+=tr; if(i==period-1) { atr=total/period; stop=value-factor*atr; } }
      else { atr=SXWilder(atr,tr,period); stop=SXUTStep(value,previous,stop,factor*atr); }
      if(i>=period-1) series[i]=stop;
      previous=value;
   }
   return Direction(previous-stop);
}
int ClosedTrailBias(ENUM_TIMEFRAMES tf) {
   MqlRates bars[]; ArraySetAsSeries(bars,false);
   int n=CopyRates(g_symbol,tf,1,(int)MathMax(180,8*InpATRPeriod),bars);
   if(n<3*InpATRPeriod) return 0;
   double trail[];
   return MakeTrail(bars,n,InpATRPeriod,InpATRMultiplier,trail);
}
int GradeUTSTC(int utNow,int utRecent,int stcNow,int stcRecent,int fastBias,int slowBias) {
   int side=(utNow!=0 && utNow==stcRecent) ? utNow :
            (stcNow!=0 && stcNow==utRecent) ? stcNow : 0;
   return side!=0 && side==fastBias && side==slowBias ? side : 0;
}
void BuildFastSlowStudy(int k) {
   int slow=MakeTrail(g_rates,k+1,2*InpATRPeriod,2*InpATRMultiplier,g_slowUT);
   g_gem.secondaryUT=slow;
   g_gem.primaryUT=Direction(Source(g_rates[k])-g_utSeries[k]);
   bool useEMA=InpSlowUTUseEMA;
   double ema=0,weight=2.0/(InpSlowUTEMALength+1);
   g_gem.utLastSide=0; g_gem.utLastAge=-1; g_gem.utLastMove=0; g_gem.utStrong=false;
   ArrayResize(g_proEvents,k+1); ArrayInitialize(g_proEvents,0);
   for(int i=0;i<=k;i++) {
      ema=i>0 ? ema+weight*(g_rates[i].close-ema) : g_rates[i].close;
      int flip=g_utEvents[i];
      if(flip==0 || i<2*InpATRPeriod) continue;
      bool strong=flip* (Source(g_rates[i])-g_slowUT[i])>0;
      if((InpSlowUTRequire && !strong) || (useEMA && (i+1<InpSlowUTEMALength || flip*(g_rates[i].close-ema)<=0))) continue;
      if((flip>0 && !InpAllowBuy) || (flip<0 && !InpAllowSell)) continue;
      g_proEvents[i]=flip*(strong ? 2 : 1);
      g_gem.utLastSide=flip; g_gem.utLastAge=k-i; g_gem.utStrong=strong;
      g_gem.utLastMove=g_rates[i].close>0 ? flip*100*(g_rates[k].close/g_rates[i].close-1) : 0;
   }
   g_engineSignals[FAST_SLOW_UT]=Direction(g_proEvents[k]);
   g_gem.utDistance=Source(g_rates[k])>0 ? 100*MathAbs(Source(g_rates[k])-g_utSeries[k])/Source(g_rates[k]) : 0;
   if(g_consoleStrategy!=FAST_SLOW_UT && g_consoleStrategy!=UT_STC_GRADE) return;
   g_gem.utH1=ClosedTrailBias(PERIOD_H1); g_gem.utH4=ClosedTrailBias(PERIOD_H4); g_gem.utD1=ClosedTrailBias(PERIOD_D1);
}

// before the chart bar opens, matching Pine's prior-bar security requests.
int DroidHigher(ENUM_TIMEFRAMES tf,datetime asOf,bool useEMA) {
   if(PeriodSeconds(g_tf)>=PeriodSeconds(tf)) return 0;
   int current=iBarShift(g_symbol,tf,asOf,false);
   if(current<0 || iTime(g_symbol,tf,current)>asOf) return 0;
   MqlRates bars[];
   int required=useEMA ? 650 : (int)MathMax(180,8*InpATRPeriod);
   int count=CopyRates(g_symbol,tf,current+1,required,bars);
   if(count!=required || bars[count-1].time!=iTime(g_symbol,tf,current+1)) return 0;
   if(useEMA) return Direction(bars[count-1].close-EMAValue(bars,count,200));
   double line[];
   return MakeTrail(bars,count,InpATRPeriod,InpATRMultiplier,line);
}
int DroidAgreement(int local,int h1,int h4,int day,int &up,int &down) {
   up=0;down=0;
   if(local==0 || h1==0 || h4==0 || day==0) return 0;
   if(local>0) up++; if(h1>0) up++; if(h4>0) up++; if(day>0) up++;
   down=4-up;
   return up==4 ? 1 : down==4 ? -1 : 0;
}
double DroidMean(int k,int length) {
   double sum=0;
   for(int i=k-length+1;i<=k;i++) sum+=g_rates[i].close;
   return sum/length;
}
double DroidVWMA(int k) {
   double mass=0,total=0;
   for(int i=k-19;i<=k;i++) {
      double volume=(double)g_rates[i].tick_volume;
      if(InpUseRealVolume && g_rates[i].real_volume>0) volume=(double)g_rates[i].real_volume;
      total+=volume*g_rates[i].close;mass+=volume;
   }
   return mass>0 ? total/mass : 0;
}
int DroidMidnight(int k) {
   int sec=PeriodSeconds(g_tf);
   if(sec<=0 || sec>1800 || 1800%sec!=0) return 0;
   datetime start=(datetime)((long)g_rates[k].time/86400*86400);
   if(g_rates[k].time<start+1800 || g_rates[k].time>=start+14400) return 0;
   int count=0; double hi=0,lo=0;
   for(int i=k-1;i>=0 && g_rates[i].time>=start;i--) {
      if(g_rates[i].time>=start+1800) continue;
      if(count==0) { hi=g_rates[i].high;lo=g_rates[i].low; }
      hi=MathMax(hi,g_rates[i].high);lo=MathMin(lo,g_rates[i].low);count++;
   }
   if(count*sec!=1800) return 0;
   double c=g_rates[k].close,p=g_rates[k-1].close;
   return c>hi && p<=hi ? 1 : c<lo && p>=lo ? -1 : 0;
}
void BuildDroidSignals(int k,double upper,double lower,double priorUpper,double priorLower) {
   g_gem.droidExitLong=false;g_gem.droidExitShort=false;g_gem.droidState="Ready";
   if(g_consoleStrategy<DR_UT || k<40) return;
   double c=g_rates[k].close,p=g_rates[k-1].close;
   int ut=g_raw;
   g_engineSignals[DR_UT]=ut;
   g_engineSignals[DR_EMA]=ut*(c-g_gem.ema200)>0 ? ut : 0;
   if(g_consoleStrategy==DR_GOLD) {
      double tight=0; int flip=DualTrailCross(1,2.0,tight);
      int hour=DroidHigher(PERIOD_H1,g_rates[k].time,true);
      g_gem.droidState=g_tf!=PERIOD_M15 ? "Use M15 for Gold Long" : hour==0 ? "Waiting for H1 EMA history" : hour<0 ? "Below hourly EMA" : "Above hourly EMA";
      g_engineSignals[DR_GOLD]=g_tf==PERIOD_M15 && VectorGoldSymbol(g_symbol) && hour>0 && g_adx>25 && flip>0 ? 1 : 0;
   }
   double buy=0,sell=0;
   int buyFlip=DualTrailCross(InpBuyATRLength,InpBuySensitivity,buy);
   int sellFlip=DualTrailCross(InpSellATRLength,InpSellSensitivity,sell);
   g_engineSignals[DR_ASYM]=buyFlip>0 ? 1 : sellFlip<0 ? -1 : 0;
   if(g_consoleStrategy==DR_FOUR) {
      int up=0,down=0,oldUp=0,oldDown=0;
      int side=Direction(Source(g_rates[k])-g_utSeries[k]);
      int priorSide=Direction(Source(g_rates[k-1])-g_utSeries[k-1]);
      datetime now=g_rates[k].time,prior=g_rates[k-1].time;
      int vote=DroidAgreement(side,DroidHigher(PERIOD_H1,now,false),DroidHigher(PERIOD_H4,now,false),DroidHigher(PERIOD_D1,now,false),up,down);
      int previous=DroidAgreement(priorSide,DroidHigher(PERIOD_H1,prior,false),DroidHigher(PERIOD_H4,prior,false),DroidHigher(PERIOD_D1,prior,false),oldUp,oldDown);
      g_gem.droidState=up+down==0 ? "Needs subhour chart and H1/H4/D1" : IntegerToString(up)+" up / "+IntegerToString(down)+" down";
      g_engineSignals[DR_FOUR]=up+down==4 && oldUp+oldDown==4 && vote!=previous ? vote : 0;
      g_gem.droidExitLong=down>=2;g_gem.droidExitShort=up>=2;
   }
   double vw=DroidVWMA(k);
   double estimate=(g_rates[0].high+g_rates[0].low+g_rates[0].close)/3,error=1,upperStop=0,lowerStop=0;
   double ema9=g_rates[0].close,ema12=ema9,ema26=ema9,signal=0,oldHist=0,oldAvg=estimate;
   double gain=0,loss=0;
   int lastLow=-10,lastHigh=-10,lastUp=-10,lastDown=-10,stSide=1;
   for(int i=1;i<=k;i++) {
      double price=g_rates[i].close,prev=g_rates[i-1].close;
      oldAvg=ema9; ema9+=.2*(price-ema9);
      ema12+=(2.0/13)*(price-ema12);ema26+=(2.0/27)*(price-ema26);
      signal+=.2*(ema12-ema26-signal); double hist=ema12-ema26-signal;
      if(hist>0 && oldHist<=0) lastUp=i;
      if(hist<0 && oldHist>=0) lastDown=i;
      if(i==k-1) g_gem.droidHistPrev=hist;
      oldHist=hist;
      double delta=price-prev;
      if(i<=4) { gain+=MathMax(0,delta)/4;loss+=MathMax(0,-delta)/4; }
      else { gain=SXWilder(gain,MathMax(0,delta),4);loss=SXWilder(loss,MathMax(0,-delta),4); }
      if(i>=4) {
         double r=gain+loss>0 ? 100*gain/(gain+loss) : 50;
         if(r<=30) lastLow=i; if(r>=70) lastHigh=i;
      }
      error+=.8; double kg=error/(error+.65);estimate+=kg*((g_rates[i].high+g_rates[i].low+price)/3-estimate);error=(1-kg)*error;
      if(g_atrSeries[i]<=0) continue;
      double hi=estimate+2.5*g_atrSeries[i],lo=estimate-2.5*g_atrSeries[i];
      if(upperStop>0 && prev<=upperStop) hi=MathMin(hi,upperStop);
      if(lowerStop>0 && prev>=lowerStop) lo=MathMax(lo,lowerStop);
      if(i==k) g_gem.droidOldTrend=stSide;
      if(upperStop>0 && stSide<0 && price>upperStop) stSide=1; else if(lowerStop>0 && stSide>0 && price<lowerStop) stSide=-1;
      upperStop=hi; lowerStop=lo;
   }
   int maState=c>g_utSeries[k] && ema9>g_utSeries[k] ? 1 : c<g_utSeries[k] && ema9<g_utSeries[k] ? -1 : 0;
   int oldMAState=p>g_utSeries[k-1] && oldAvg>g_utSeries[k-1] ? 1 : p<g_utSeries[k-1] && oldAvg<g_utSeries[k-1] ? -1 : 0;
   g_engineSignals[DR_AVERAGE]=maState!=oldMAState ? maState : 0;
   int band=g_atrRatio>=1 && upper-lower>priorUpper-priorLower ? (c>upper && p<=priorUpper ? 1 : c<lower && p>=priorLower ? -1 : 0) : 0;
   g_engineSignals[DR_BAND]=band;
   if(g_consoleStrategy==DR_BAND) {g_gem.droidExitLong=lower>priorLower || g_atrRatio<1;g_gem.droidExitShort=upper<priorUpper || g_atrRatio<1;}
   g_gem.droidHist=oldHist;
   if(vw<=0) vw=DroidMean(k,20);
   double highest=g_rates[k].high,lowest=g_rates[k].low;
   for(int i=k-19;i<k;i++){highest=MathMax(highest,g_rates[i].high);lowest=MathMin(lowest,g_rates[i].low);}
   g_gem.droidUpper=vw+.75*MathMax(0,highest-vw);g_gem.droidLower=vw-.75*MathMax(0,vw-lowest);
   g_engineSignals[DR_KALMAN]=stSide!=g_gem.droidOldTrend ? stSide : 0;
   g_gem.droidVW=vw;g_gem.droidStop=stSide>0 ? lowerStop : upperStop;
   double travel=0;for(int i=k-19;i<=k;i++) travel+=MathAbs(g_rates[i].close-g_rates[i-1].close);
   double efficiency=travel>0 ? MathAbs(c-g_rates[k-20].close)/travel : 0;
   bool trend=g_adx>=22 && efficiency>=.30;
   int fade=p<priorLower && c>=lower && c<(upper+lower)*.5 ? 1 : p>priorUpper && c<=upper && c>(upper+lower)*.5 ? -1 : 0;
   g_engineSignals[DR_ROUTER]=g_atrRatio>2.2 || g_atrRatio<.55 ? 0 : trend ? g_engineSignals[DR_EMA] : fade;
   if(g_consoleStrategy==DR_ROUTER) g_gem.droidState=g_atrRatio>2.2 || g_atrRatio<.55 ? "Volatility hold" : trend ? "Trend / EMA and ATR" : "Range / band re-entry";
   g_engineSignals[DR_MIDNIGHT]=DroidMidnight(k);
   double a=DroidMean(k,5),b=DroidMean(k,8),d=DroidMean(k,13);
   bool bull=a>b && b>d && c>g_gem.ema200,bear=a<b && b<d && c<g_gem.ema200;
   bool turnUp=k-lastUp<=2 && k-lastLow<=2 && (lastUp==k || lastLow==k) && oldHist>0;
   bool turnDown=k-lastDown<=2 && k-lastHigh<=2 && (lastDown==k || lastHigh==k) && oldHist<0;
   g_engineSignals[DR_RIBBON]=bull && turnUp ? 1 : bear && turnDown ? -1 : 0;
   bool cloud=stSide>0 && ema9>g_cachedFast && c>MathMax(ema9,g_cachedFast);
   g_engineSignals[DR_CLOUD]=cloud && (p<=MathMax(oldAvg,g_fastSeries[k-1]) || oldAvg<=g_fastSeries[k-1]) ? 1 : 0;
   if(g_consoleStrategy==DR_CLOUD) g_gem.droidExitLong=stSide<0 || ema9<g_cachedFast;
   if(g_consoleStrategy==DR_NIGHT || g_consoleStrategy==DR_EXPRESS) DroidOvernight(k,g_consoleStrategy==DR_EXPRESS);
   if(g_consoleStrategy==DR_SNIPER) g_engineSignals[DR_SNIPER]=DroidPivotReversal(k);
   if(g_consoleStrategy==DR_PANDICH) g_engineSignals[DR_PANDICH]=DroidStateful(k);
}
// Convert broker timestamps to Eastern time, including US DST since 2007.
datetime DroidEastern(datetime server) {
   datetime utc=server-VectorServerUTCMinutes*60;
   MqlDateTime date;TimeToStruct(utc,date);
   date.mon=3;date.day=1;date.hour=7;date.min=0;date.sec=0;
   datetime march=StructToTime(date);TimeToStruct(march,date);
   datetime start=march+(7+(7-date.day_of_week)%7)*86400;
   date.mon=11;date.day=1;date.hour=6;date.min=0;date.sec=0;
   datetime nov=StructToTime(date);TimeToStruct(nov,date);
   datetime finish=nov+((7-date.day_of_week)%7)*86400;
   return utc+(utc>=start && utc<finish ? -4 : -5)*3600;
}
bool DroidWindow(datetime server,bool express) {
   MqlDateTime dt;TimeToStruct(DroidEastern(server),dt);
   int m=dt.hour*60+dt.min,opens=express ? 1081 : 60*InpNightOpen,ends=express ? 960 : 60*InpNightEnd;
   if(m<opens && m>=ends) return false;
   int sessionDay=(dt.day_of_week+(m<ends ? 6 : 0))%7;
   return sessionDay>=(express ? 0 : 1) && sessionDay<=4;
}
void DroidOvernight(int k,bool express) {
   double mid=g_rates[0].close,ema8=mid,ema25=mid,fourAgo=mid,trail=0,atr=0,baseATR=0,up=0,down=0;
   double fastHistory[4]={0,0,0,0};for(int j=0;j<4;j++) fastHistory[j]=mid;
   int lastTrend=1,lastVote=0,signal=0,points=0;
   int length=express ? 8 : 23;
   for(int i=1;i<=k;i++) {
      double c=g_rates[i].close,p=g_rates[i-1].close,delta=c-p;
      double tr=SXTrueRange(g_rates[i].high,g_rates[i].low,p);
      if(i<=length) atr+=tr/length; else atr=SXWilder(atr,tr,length);
      if(i<=18) {up+=MathMax(0,delta)/18;down+=MathMax(0,-delta)/18;}
      else {up=SXWilder(up,MathMax(0,delta),18);down=SXWilder(down,MathMax(0,-delta),18);}
      mid+=(2.0/(express ? 9.0 : 11.0))*(c-mid);
      ema8+=(2.0/9)*(c-ema8);ema25+=(2.0/26)*(c-ema25);
      fourAgo=fastHistory[(i+1)%4];fastHistory[i%4]=ema8;
      if(i<length) continue;
      baseATR=baseATR>0 ? baseATR+(2.0/21)*(atr-baseATR) : atr;
      double adjust=express && baseATR>0 ? MathMax(.75,MathMin(1.5,atr/baseATR)) : 1.0;
      double span=1.618*atr*adjust;
      int old=lastTrend;
      if(i==length) trail=mid-span;
      else {
         if(lastTrend>0 && c<trail) lastTrend=-1;
         else if(lastTrend<0 && c>trail) lastTrend=1;
         double next=mid-lastTrend*span;
         trail=old!=lastTrend ? next : lastTrend>0 ? MathMax(trail,next) : MathMin(trail,next);
      }
      if(express) signal=old!=lastTrend ? lastTrend : 0;
      else if(i>=k-1) {
         double r=up+down>0 ? 100*up/(up+down) : 50;
         int d=lastTrend;points=0;
         if(d*(ema8-ema25)>0) points++;
         if((d==1 && r>=58) || (d==-1 && r<=48)) points++;
         if(d*(i==k ? g_gem.droidHist : g_gem.droidHistPrev)>0) points++;
         if((i==k ? g_adx : g_gem.droidAdxPrev)>=18) points++;
         if(d*(c-g_rates[i].open)>=g_atrSeries[i]) points++;
         if(d*(ema8-fourAgo)>0) points++;
         int vote=points>=3 ? d : 0;signal=vote!=lastVote ? vote : 0;lastVote=vote;
      }
   }
   datetime closeTime=g_rates[k].time+PeriodSeconds(g_tf);
   bool live=DroidWindow(g_rates[k].time,express) && DroidWindow(closeTime,express);
   g_engineSignals[express ? DR_EXPRESS : DR_NIGHT]=live ? signal : 0;
   g_gem.droidStop=trail;
   g_gem.droidExitLong=!live || lastTrend<0;g_gem.droidExitShort=!live || lastTrend>0;
   g_gem.droidState=!live ? "Outside Eastern window" : express ? "Adaptive ATR trail" : IntegerToString(points)+" / 6 confirmations";
}
int DroidPivotReversal(int k) {
   int i=k-3;
   if(g_atrRatio>1.3) return 0;
   bool low=ConfirmedPivot(i,true,k),high=ConfirmedPivot(i,false,k);
   if(!low && !high) return 0;
   double mid,upper,lower;BandValues(i,mid,upper,lower);
   int candle=Direction(g_rates[k].close-g_rates[k].open);
   int streak=candle==Direction(g_rates[k-1].close-g_rates[k-1].open) && candle==Direction(g_rates[k-2].close-g_rates[k-2].open) ? candle : 0;
   for(int side=-1;side<=1;side+=2) {
      if((side>0 && (!low || g_rates[i].low>lower)) || (side<0 && (!high || g_rates[i].high<upper)) || side==streak || side*(g_rates[k].close-g_utSeries[k])<=0) continue;
      for(int j=i-1;j>=(int)MathMax(20,i-60);j--) if(ConfirmedPivot(j,side>0,k)) {
         bool extreme=side>0 ? g_rates[i].low<g_rates[j].low : g_rates[i].high>g_rates[j].high;
         if(extreme && side*(g_rsiSeries[i]-g_rsiSeries[j])>0) return side;
         break;
      }
   }
   return 0;
}
int DroidStateful(int k) {
   double slow=0,line=0;int side=1,eventSide=0;
   for(int i=0;i<=k;i++){
      double c=g_rates[i].close,tr=SXTrueRange(g_rates[i].high,g_rates[i].low,i>0 ? g_rates[i-1].close : c);
      if(i<300) slow+=tr/300;else slow=SXWilder(slow,tr,300);
      if(i==299){line=c-1.1*tr;continue;}
      if(i<300) continue;
      int before=side;
      if(side>0 && c<line) side=-1;else if(side<0 && c>line) side=1;
      double next=side>0 ? c-1.1*tr : c+1.1*slow;
      line=before!=side ? next : side>0 ? MathMax(line,next) : MathMin(line,next);
      eventSide=side!=before ? side : 0;
   }
   g_gem.droidStop=line;g_gem.droidExitLong=side<0;g_gem.droidExitShort=side>0;
   return eventSide;
}

double DroidKalmanAt(int end,double gain) {
   int start=(int)MathMax(0,end-120);
   double est=g_rates[start].close;
   for(int i=start+1;i<=end;i++) est=est+gain*(g_rates[i].close-est);
   return est;
}
double DroidVWMAAt(int end,int period) {
   int start=(int)MathMax(0,end-period+1);
   double num=0.0,den=0.0;
   for(int i=start;i<=end;i++) {
      double vol=(double)MathMax((long)1,g_rates[i].tick_volume);
      num+=g_rates[i].close*vol;
      den+=vol;
   }
   return den>0.0 ? num/den : g_rates[end].close;
}
string DroidSmartRegimeLabel() {
   if(!g_consoleReady) return "WARMING UP";
   if(g_atrRatio>0 && g_atrRatio<InpSmartMinAtrRatio) return "CHOP SHIELD";
   if(g_adx>=25.0) return "STRONG TREND";
   if(g_atrRatio>=1.35) return "EXPANSION";
   if(g_adx<18.0) return "RANGE MODE";
   return "BALANCED";
}
void BuildDroidCombinedSignals(int k) {
   if(k<3 || g_atr<=0) return;
   double c0=g_rates[k].close, o0=g_rates[k].open, h0=g_rates[k].high, l0=g_rates[k].low;
   double c1=g_rates[k-1].close, h1=g_rates[k-1].high, l1=g_rates[k-1].low;
   int utFlip=g_utEvents[k];
   int utBias=Direction(Source(g_rates[k])-g_utCurrent);
   int htfBias=ClosedTrailBias(InpSmartConfirmTF);
   double ema200=g_gem.ema200>0 ? g_gem.ema200 : g_cachedSlow;
   double kalNow=DroidKalmanAt(k,InpSmartKalmanGain);
   double kalPrev=DroidKalmanAt(k-1,InpSmartKalmanGain);
   double vwma=DroidVWMAAt(k,InpSmartVwmaPeriod);
   double smaF=SMAAt(k,InpFastMA), smaS=SMAAt(k,InpSMAPeriod);
   int stFlip=(k>0 && g_superDirections[k]!=g_superDirections[k-1]) ? g_superDirections[k] : 0;
   MqlDateTime dt; TimeToStruct(g_rates[k].time,dt);
   bool inMidnight=(dt.hour>=23 || dt.hour<3);
   bool inOvernight=(dt.hour>=22 || dt.hour<13);
   bool bodyExp=MathAbs(c0-o0)>g_atr*0.35;
   int diBias=(g_gem.plusDI>g_gem.minusDI) ? 1 : (g_gem.minusDI>g_gem.plusDI ? -1 : 0);
   int macdCross=CrossDirection(g_gem.priorHist,g_macd);

   // Adaptive Multi-Indicator Confluence
   g_engineSignals[DROID_ADAPTIVE_CONFLUENCE]=(utFlip>0 && c0>ema200 && kalNow>vwma && g_rsi>50) ? 1 :
                                              (utFlip<0 && c0<ema200 && kalNow<vwma && g_rsi<50) ? -1 : 0;
   // Gold Fifteen-Minute Two-Hundred EMA Hourly UT Bot ADX
   int emaCross=CrossDirection(c1-g_fastSeries[k-1],c0-g_fastSeries[k]);
   int goldTrig=utFlip!=0 ? utFlip : emaCross;
   g_engineSignals[GOLD_M15_EMA200_H1_UT_ADX]=(goldTrig>0 && c0>ema200 && htfBias>0 && g_adx>=InpMinADX && diBias>0) ? 1 :
                                              (goldTrig<0 && c0<ema200 && htfBias<0 && g_adx>=InpMinADX && diBias<0) ? -1 : 0;
   // UT Bot Unified ATR Flip Engine
   g_engineSignals[UT_BOT_UNIFIED_ENGINE]=utFlip;
   // UT Bot ATR Trailing Stop Pure Runner
   g_engineSignals[UT_BOT_ATR_RUNNER]=utFlip;
   // UT Bot Alerts Two-Hundred EMA Trend Filter
   g_engineSignals[UT_BOT_ALERTS_EMA200]=(utFlip>0 && c0>ema200) ? 1 : (utFlip<0 && c0<ema200) ? -1 : 0;
   // UT Bot Pandich Momentum Scalper
   g_engineSignals[UT_BOT_PANDICH_SCALPER]=(utFlip>0 && g_rsi>52 && bodyExp) ? 1 :
                                           (utFlip<0 && g_rsi<48 && bodyExp) ? -1 : 0;
   // Midnight Express Session Scalper
   g_engineSignals[MIDNIGHT_EXPRESS_SCALPER]=(inMidnight && c0>ema200 && emaCross>0 && g_rsi>50) ? 1 :
                                             (inMidnight && c0<ema200 && emaCross<0 && g_rsi<50) ? -1 : 0;
   // UT Bot Alerts Elite Confluence
   g_engineSignals[UT_BOT_ALERTS_ELITE]=(utFlip>0 && c0>ema200 && g_adx>=InpMinADX && g_rsi>50 && g_macd>0) ? 1 :
                                        (utFlip<0 && c0<ema200 && g_adx>=InpMinADX && g_rsi<50 && g_macd<0) ? -1 : 0;
   // QuantNomad Trailing Stop Loss Alert Engine
   g_engineSignals[QUANTNOMAD_TRAIL_SL_ALERT]=CrossDirection(c1-g_utSeries[k-1],c0-g_utSeries[k]);
   // QuantNomad Multi-Timeframe Trailing Stop Strategy
   g_engineSignals[QUANTNOMAD_MTF_TRAIL_SL]=(utFlip>0 && htfBias>0) ? 1 : (utFlip<0 && htfBias<0) ? -1 : 0;
   // Yuthavithi Bollinger Band Scalper
   g_engineSignals[YUTHAVITHI_BB_SCALPER]=(l1<g_bandLower && c0>g_bandLower && c0>o0 && g_rsi<46) ? 1 :
                                          (h1>g_bandUpper && c0<g_bandUpper && c0<o0 && g_rsi>54) ? -1 : 0;
   // Pro Scalper Kalman Supertrend VWMA Zones
   int kalStCross=CrossDirection(kalPrev-g_superSeries[k-1],kalNow-g_superSeries[k]);
   int kalTrig=stFlip!=0 ? stFlip : kalStCross;
   bool bullZone=(c0>=vwma-0.5*g_atr && c0<=vwma+1.4*g_atr && kalNow>vwma);
   bool bearZone=(c0<=vwma+0.5*g_atr && c0>=vwma-1.4*g_atr && kalNow<vwma);
   g_engineSignals[PRO_KALMAN_SUPERTREND_VWMA]=(kalTrig>0 && bullZone) ? 1 : (kalTrig<0 && bearZone) ? -1 : 0;
   // Scalper SMA RSI MACD Entry Exit Signals
   g_engineSignals[SCALPER_SMA_RSI_MACD]=(smaF>smaS && g_rsi>50 && macdCross>0) ? 1 :
                                         (smaF<smaS && g_rsi<50 && macdCross<0) ? -1 : 0;
   // MPR Supertrend Precision Entry Exit Scalper
   g_engineSignals[MPR_SUPERTREND_SCALPER]=(stFlip>0 && c0>ema200) ? 1 : (stFlip<0 && c0<ema200) ? -1 : 0;
   // Overnight Nasdaq Synapse Confluence Scalper
   bool vwapBull=(g_vwap>0 && c0>g_vwap), vwapBear=(g_vwap>0 && c0<g_vwap);
   g_engineSignals[OVERNIGHT_MNQ_SYNAPSE]=(inOvernight && vwapBull && c0>g_cachedFast && g_rsi>52 && utBias>0) ? 1 :
                                          (inOvernight && vwapBear && c0<g_cachedFast && g_rsi<48 && utBias<0) ? -1 : 0;
}


void LogoTrace(uint &pixels[],int side,double ax,double ay,double bx,double by,double weight,color ink,int alpha) {
   double dx=bx-ax,dy=by-ay,dist=MathSqrt(dx*dx+dy*dy);
   if(dist<=0) return;
   double nx=-dy*weight/dist,ny=dx*weight/dist;
   Facet(pixels,side,(ax+nx)*side,(ay+ny)*side,(ax-nx)*side,(ay-ny)*side,(bx+nx)*side,(by+ny)*side,ink,alpha);
   Facet(pixels,side,(ax-nx)*side,(ay-ny)*side,(bx-nx)*side,(by-ny)*side,(bx+nx)*side,(by+ny)*side,ink,alpha);
}
uint DroidPackARGB(color fill,int opacity) {
   uint rgb=(((uint)fill&255)<<16)|((uint)fill&65280)|(((uint)fill>>16)&255);
   return ((uint)opacity<<24)|rgb;
}
void DroidCircle(uint &pixels[],int side,double cx,double cy,double r,color fill,int opacity) {
   int left=(int)MathMax(0,MathFloor(cx-r));
   int right=(int)MathMin(side-1,MathCeil(cx+r));
   int top=(int)MathMax(0,MathFloor(cy-r));
   int bottom=(int)MathMin(side-1,MathCeil(cy+r));
   double r2=r*r;
   uint packed=DroidPackARGB(fill,opacity);
   for(int y=top;y<=bottom;y++) {
      double dy=(y+0.5)-cy;
      for(int x=left;x<=right;x++) {
         double dx=(x+0.5)-cx;
         if(dx*dx+dy*dy<=r2) pixels[y*side+x]=packed;
      }
   }
}
void DroidRoundRect(uint &pixels[],int side,double x0,double y0,double w,double h,double rad,color fill,int opacity) {
   int left=(int)MathMax(0,MathFloor(x0));
   int right=(int)MathMin(side-1,MathCeil(x0+w));
   int top=(int)MathMax(0,MathFloor(y0));
   int bottom=(int)MathMin(side-1,MathCeil(y0+h));
   double ix0=x0+rad,ix1=x0+w-rad,iy0=y0+rad,iy1=y0+h-rad,r2=rad*rad;
   uint packed=DroidPackARGB(fill,opacity);
   for(int y=top;y<=bottom;y++) {
      double py=y+0.5;
      for(int x=left;x<=right;x++) {
         double px=x+0.5;
         double dx=(px<ix0) ? (ix0-px) : (px>ix1 ? (px-ix1) : 0.0);
         double dy=(py<iy0) ? (iy0-py) : (py>iy1 ? (py-iy1) : 0.0);
         if(dx*dx+dy*dy<=r2) pixels[y*side+x]=packed;
      }
   }
}
void WingedArt(uint &pixels[],int size,int alpha) {
   if(ArrayResize(pixels,size*size)!=size*size) return;
   ArrayInitialize(pixels,0);
   double s=(double)size;
   // Core hover ring behind cute droid
   DroidCircle(pixels,size,0.50*s,0.55*s,0.44*s,LogoInk(8),alpha);
   DroidCircle(pixels,size,0.50*s,0.55*s,0.38*s,LogoInk(2),alpha);
   // Twin drone wings & side ear pods
   Facet(pixels,size,0.03*s,0.42*s,0.21*s,0.37*s,0.19*s,0.58*s,LogoInk(6),alpha);
   Facet(pixels,size,0.97*s,0.42*s,0.79*s,0.37*s,0.81*s,0.58*s,LogoInk(6),alpha);
   DroidRoundRect(pixels,size,0.12*s,0.43*s,0.09*s,0.22*s,0.04*s,LogoInk(6),alpha);
   DroidRoundRect(pixels,size,0.79*s,0.43*s,0.09*s,0.22*s,0.04*s,LogoInk(6),alpha);
   // Antenna stem & glowing beacon orb
   DroidRoundRect(pixels,size,0.475*s,0.12*s,0.05*s,0.16*s,0.02*s,LogoInk(5),alpha);
   DroidCircle(pixels,size,0.50*s,0.11*s,0.072*s,LogoInk(5),alpha);
   DroidCircle(pixels,size,0.48*s,0.09*s,0.026*s,LogoInk(4),alpha);
   // Rounded cute robot head shell + top crown highlight
   DroidRoundRect(pixels,size,0.19*s,0.25*s,0.62*s,0.53*s,0.18*s,LogoInk(1),alpha);
   DroidRoundRect(pixels,size,0.24*s,0.27*s,0.52*s,0.12*s,0.06*s,LogoInk(0),alpha);
   // Glossy dark visor screen
   DroidRoundRect(pixels,size,0.25*s,0.38*s,0.50*s,0.31*s,0.10*s,LogoInk(2),alpha);
   // Big cute glowing LED eyes + specular glints
   DroidCircle(pixels,size,0.39*s,0.51*s,0.074*s,LogoInk(3),alpha);
   DroidCircle(pixels,size,0.61*s,0.51*s,0.074*s,LogoInk(3),alpha);
   DroidCircle(pixels,size,0.368*s,0.485*s,0.025*s,LogoInk(4),alpha);
   DroidCircle(pixels,size,0.588*s,0.485*s,0.025*s,LogoInk(4),alpha);
   // Cute rosy hover cheeks + LED smile arc
   DroidCircle(pixels,size,0.305*s,0.585*s,0.024*s,LogoInk(7),alpha);
   DroidCircle(pixels,size,0.695*s,0.585*s,0.024*s,LogoInk(7),alpha);
   LogoTrace(pixels,size,0.43,0.605,0.50,0.638,0.015,LogoInk(7),alpha);
   LogoTrace(pixels,size,0.50,0.638,0.57,0.605,0.015,LogoInk(7),alpha);
   // Mini hover thruster base under chin
   DroidRoundRect(pixels,size,0.37*s,0.80*s,0.26*s,0.075*s,0.036*s,LogoInk(0),alpha);
   DroidRoundRect(pixels,size,0.43*s,0.865*s,0.14*s,0.045*s,0.02*s,LogoInk(3),alpha);
}



//====================================================================
// CVT LT DRIOD BOT NO ERRORS EA : INTELLIGENT CONTROL CORE (104 themes, 27 positive
// trailing modes, 12 smart filters, 16 indicators, cute robot, deck)
//====================================================================
string BPThemeName(int i) {
   string n[104]={
      "Android Cure Emerald","Bionic Pulse Cyan","Carbon Gold Pro","Cyber Violet Neon",
      "Midnight Pulse","Ocean Abyss","Light Mint Clinical","Solar Amber Matrix",
      "Crimson Overdrive","Arctic Titanium","Emerald Circuit","Quantum Obsidian",
      "Neon Synthwave","Royal Cobalt","Bio-Hazard Lime","Platinum Stealth",
      "Sakura Neon Pink","Aurora Borealis","Desert Sand Quartz","Volcanic Ember",
      "Deep Space Indigo","Mint Chocolate","Sapphire Ice","Retro Terminal Green",
      "Rose Gold Luxe","Toxic Purple","Steel Blue Corporate","Sunset Horizon",
      "Matrix Rain","Candy Pop Bubblegum","Black Gold Royale","Glacier Day",
      "Cyber Ruby Noir","Tidal Teal","Lavender Dream","Golden Hour",
      "Forest Canopy","Neon Tokyo","Frost Bite","Copper Circuit",
      "Midnight Orchid","Lava Lamp","Ice Mint Day","Obsidian Emerald",
      "Electric Lime Pop","Silver Moon","Coral Reef","Cosmic Latte",
      "Xeon Plasma Cyan","Xeon Droid Neon","Hyperion Gold Black","Kronos Dark Obsidian",
      "Neuro Matrix Emerald","Quantum Violet Pulse","Arctic Frost Glass","Brimstone Magma Red",
      "Titanium Cyber Chrome","Solaris Amber Forge","Sapphire Deep Space","Emerald Bio-Pulse",
      "Crimson Samurai Noir","Cobalt Hologram","Rose Quartz Cyber","Daylight Clinical Pro",
      "Emerald Prime","Royal Sapphire Console","Aether Cyber Teal","Plasma Magenta Pulse",
      "Obsidian Titanium Gold","Nordic Frost Light","Tokyo Drift Crimson","Jade Dragon Matrix",
      "Velvet Amethyst Night","Solaris Copper Glow","Arctic Aurora Mint","Monolith Slate Pro",
      "Ivory Executive Day","Ultraviolet Quantum","Cobalt Lightning","Emerald Velvet Noir",
      "Sunset Coral Neon","Champagne Pearl Light","Cyberpunk Acid Lime","Deep Ocean Biolume",
      "Ruby Obsidian Luxe","Neon Aqua Pink","Mocha Cream Day","Starlight Indigo Pulse",
      "Droid Electric Cyan", "Droid Matrix Pulse", "Droid Cyber Gold", "Droid Neon Violet", "Droid Emerald Grid", "Droid Plasma Red", "Droid Deep Ocean", "Droid Titanium Ice", "Droid Solar Flare", "Droid Midnight Cobalt", "Droid Hologram Mint", "Droid Crimson Forge", "Droid Sakura Cyber", "Droid Obsidian Lime", "Droid Royal Amethyst", "Droid Daylight Frost"
   };
   if(i<0 || i>=104) return "Classic theme";
   return n[i];
}
void BPLoadTheme(int i) {
   if(i<0 || i>=104) return;
   color t[104][9]={
      {C'8,17,15',C'14,30,26',C'30,74,62',C'226,246,238',C'120,160,148',C'61,220,132',C'0,200,180',C'61,220,132',C'255,92,108'},
      {C'6,15,26',C'12,28,44',C'26,76,104',C'226,244,252',C'120,160,184',C'0,229,255',C'80,140,255',C'0,229,190',C'255,82,110'},
      {C'14,14,16',C'26,26,30',C'78,66,30',C'240,236,224',C'150,144,128',C'255,196,46',C'214,160,40',C'74,214,130',C'245,80,80'},
      {C'14,8,28',C'28,16,54',C'84,50,150',C'240,232,255',C'156,140,196',C'187,99,255',C'255,80,220',C'80,240,200',C'255,70,120'},
      {C'6,10,22',C'14,22,44',C'36,56,110',C'224,232,250',C'124,140,176',C'96,150,255',C'150,110,255',C'60,220,170',C'255,96,110'},
      {C'4,20,30',C'8,38,54',C'20,92,120',C'220,244,250',C'110,160,176',C'30,200,220',C'40,140,200',C'60,230,180',C'255,110,100'},
      {C'242,250,247',C'224,240,234',C'160,200,186',C'20,40,34',C'90,120,110',C'0,150,110',C'20,110,170',C'0,150,100',C'220,60,70'},
      {C'20,12,4',C'40,26,8',C'110,70,16',C'255,240,214',C'180,150,100',C'255,160,20',C'255,200,70',C'130,220,90',C'255,80,60'},
      {C'20,6,10',C'40,12,20',C'120,28,44',C'255,232,236',C'184,130,140',C'255,50,80',C'255,130,60',C'70,220,140',C'255,50,80'},
      {C'22,28,34',C'36,46,56',C'90,110,128',C'236,244,250',C'150,166,180',C'160,210,240',C'200,214,226',C'90,220,190',C'240,100,110'},
      {C'4,18,12',C'8,34,22',C'20,100,60',C'214,255,232',C'110,170,136',C'40,255,140',C'0,200,120',C'40,255,140',C'255,90,90'},
      {C'5,5,8',C'14,14,20',C'44,44,64',C'230,232,244',C'130,134,156',C'140,150,255',C'90,200,255',C'70,230,170',C'255,90,120'},
      {C'20,6,36',C'40,12,64',C'150,30,150',C'255,226,250',C'190,130,196',C'255,60,200',C'40,220,255',C'40,255,200',C'255,70,110'},
      {C'6,14,40',C'12,28,76',C'30,70,170',C'228,236,255',C'130,150,200',C'70,130,255',C'255,200,60',C'70,220,170',C'255,90,100'},
      {C'10,14,4',C'22,30,8',C'80,110,16',C'240,255,214',C'150,170,110',C'190,255,0',C'255,230,0',C'150,255,60',C'255,80,60'},
      {C'16,17,19',C'30,32,35',C'78,82,88',C'236,238,240',C'144,148,154',C'214,220,228',C'160,170,186',C'120,220,190',C'236,100,110'},
      {C'24,8,20',C'46,16,38',C'140,40,100',C'255,236,246',C'200,140,174',C'255,105,180',C'255,160,210',C'90,240,190',C'255,70,100'},
      {C'6,16,28',C'12,32,48',C'40,110,120',C'226,250,244',C'124,170,170',C'70,255,190',C'140,120,255',C'70,255,190',C'255,100,140'},
      {C'248,242,230',C'236,226,206',C'200,180,140',C'52,40,24',C'120,104,80',C'190,120,20',C'30,120,150',C'20,140,90',C'200,60,50'},
      {C'16,8,6',C'36,16,10',C'120,40,16',C'255,232,220',C'180,130,110',C'255,100,30',C'255,180,40',C'120,220,100',C'255,60,50'},
      {C'8,6,30',C'18,14,60',C'56,44,150',C'232,230,255',C'140,136,196',C'120,110,255',C'80,190,255',C'80,230,190',C'255,90,140'},
      {C'22,14,10',C'40,28,20',C'100,70,50',C'240,255,246',C'170,150,136',C'80,240,190',C'190,130,80',C'80,240,190',C'240,100,90'},
      {C'8,20,40',C'16,40,72',C'50,110,190',C'230,244,255',C'130,160,196',C'100,190,255',C'190,230,255',C'90,230,220',C'255,110,120'},
      {C'0,10,0',C'2,24,4',C'0,110,30',C'160,255,170',C'60,160,76',C'0,255,70',C'140,255,0',C'0,255,70',C'255,70,50'},
      {C'24,16,18',C'44,30,34',C'140,96,100',C'255,238,232',C'190,156,150',C'232,160,140',C'255,205,170',C'130,220,170',C'245,100,110'},
      {C'14,6,22',C'30,12,44',C'100,40,130',C'244,230,255',C'170,140,190',C'200,80,255',C'150,255,60',C'150,255,60',C'255,60,150'},
      {C'232,238,246',C'214,224,238',C'150,170,200',C'22,34,54',C'90,106,132',C'30,90,180',C'0,130,160',C'0,140,100',C'210,60,70'},
      {C'24,10,24',C'48,20,40',C'150,60,70',C'255,236,224',C'200,150,150',C'255,120,70',C'255,190,80',C'120,230,160',C'255,70,110'},
      {C'0,6,2',C'4,20,10',C'0,90,40',C'190,255,206',C'70,140,90',C'30,255,110',C'0,200,160',C'30,255,110',C'255,60,60'},
      {C'255,244,250',C'255,226,240',C'240,170,210',C'60,24,50',C'150,100,130',C'230,60,160',C'60,170,230',C'20,170,130',C'230,60,80'},
      {C'8,6,4',C'22,18,10',C'110,84,20',C'250,240,210',C'170,156,120',C'240,190,40',C'255,225,120',C'100,220,120',C'240,70,60'},
      {C'240,248,255',C'220,236,250',C'150,190,230',C'16,36,60',C'90,118,150',C'20,130,220',C'0,170,190',C'0,160,120',C'220,60,80'},
      {C'12,4,8',C'28,10,18',C'110,24,52',C'255,230,238',C'176,124,140',C'255,40,90',C'255,120,150',C'70,230,150',C'255,60,80'},
      {C'4,18,20',C'8,36,40',C'20,110,112',C'220,252,250',C'110,170,170',C'20,230,210',C'60,170,230',C'40,235,170',C'255,100,100'},
      {C'246,242,255',C'232,224,252',C'184,166,230',C'38,28,70',C'106,92,150',C'120,80,230',C'80,130,230',C'20,150,110',C'220,60,90'},
      {C'24,14,4',C'44,28,8',C'140,96,20',C'255,244,214',C'190,160,100',C'255,176,32',C'255,120,60',C'130,220,90',C'255,80,70'},
      {C'6,16,8',C'12,32,16',C'40,100,48',C'226,250,224',C'120,164,116',C'110,220,90',C'190,210,70',C'90,230,110',C'255,100,80'},
      {C'8,4,20',C'18,10,44',C'70,40,160',C'240,236,255',C'150,140,200',C'0,240,255',C'255,50,170',C'40,255,170',C'255,60,120'},
      {C'6,16,26',C'12,30,46',C'60,120,160',C'236,248,255',C'140,176,200',C'150,230,255',C'90,160,255',C'100,240,210',C'255,110,130'},
      {C'18,10,6',C'36,20,12',C'130,72,36',C'255,236,222',C'184,146,120',C'232,128,60',C'80,200,190',C'110,220,130',C'255,80,60'},
      {C'12,6,22',C'26,12,46',C'110,50,160',C'246,230,255',C'176,140,200',C'218,112,255',C'120,150,255',C'100,240,190',C'255,90,150'},
      {C'20,4,4',C'40,10,10',C'150,36,24',C'255,236,224',C'190,130,116',C'255,90,40',C'255,200,60',C'120,220,110',C'255,50,50'},
      {C'238,252,250',C'218,244,240',C'140,200,192',C'14,44,40',C'80,120,114',C'0,160,140',C'40,130,200',C'0,160,110',C'220,70,80'},
      {C'3,6,5',C'10,18,15',C'30,70,56',C'222,250,238',C'120,160,146',C'0,255,160',C'80,230,255',C'0,255,160',C'255,80,100'},
      {C'8,10,6',C'20,26,12',C'90,120,20',C'246,255,220',C'160,176,120',C'200,255,40',C'255,80,200',C'120,255,80',C'255,70,90'},
      {C'236,238,242',C'220,224,232',C'160,168,184',C'24,28,40',C'96,104,120',C'80,96,200',C'0,140,180',C'0,150,110',C'210,60,70'},
      {C'4,16,24',C'8,34,48',C'20,110,130',C'232,250,250',C'124,170,176',C'255,127,102',C'40,210,220',C'60,230,170',C'255,90,110'},
      {C'252,246,236',C'244,232,214',C'208,184,150',C'54,40,28',C'128,108,88',C'200,110,30',C'60,130,160',C'40,140,90',C'200,60,50'},
      // --- 16 NEW VECTOR SIGNATURE THEMES (48..63) ---
      {C'5,12,20',C'10,24,38',C'24,84,118',C'230,248,255',C'118,166,192',C'0,245,255',C'60,165,255',C'38,242,174',C'255,84,114'},
      {C'6,16,12',C'12,30,22',C'28,96,66',C'228,255,240',C'116,172,144',C'56,255,146',C'0,224,210',C'56,255,146',C'255,78,104'},
      {C'10,9,7',C'22,20,15',C'96,76,28',C'250,244,226',C'168,154,120',C'255,204,54',C'238,164,42',C'82,226,144',C'246,82,86'},
      {C'7,6,12',C'16,14,26',C'58,48,104',C'236,232,252',C'140,132,178',C'152,126,255',C'64,212,255',C'68,238,180',C'255,82,126'},
      {C'3,14,10',C'7,28,18',C'18,98,62',C'218,255,234',C'104,168,136',C'32,240,136',C'120,255,190',C'32,240,136',C'255,74,94'},
      {C'14,6,26',C'28,12,52',C'104,42,168',C'244,232,255',C'170,136,204',C'204,102,255',C'46,226,255',C'74,244,196',C'255,68,124'},
      {C'12,20,30',C'22,36,52',C'68,112,150',C'238,248,255',C'146,178,204',C'128,216,255',C'178,234,255',C'78,236,196',C'255,98,118'},
      {C'18,6,6',C'36,12,12',C'132,36,28',C'255,234,228',C'188,132,124',C'255,88,48',C'255,184,48',C'96,228,128',C'255,58,64'},
      {C'14,16,20',C'26,30,36',C'82,92,108',C'238,242,248',C'148,158,174',C'198,216,238',C'94,186,255',C'84,232,178',C'244,88,104'},
      {C'18,11,4',C'36,22,8',C'124,76,20',C'255,242,216',C'188,154,106',C'255,172,28',C'255,216,84',C'112,232,116',C'255,76,68'},
      {C'5,10,28',C'10,22,56',C'34,68,156',C'228,238,255',C'126,148,200',C'78,152,255',C'42,226,246',C'64,236,184',C'255,86,118'},
      {C'4,18,14',C'10,36,28',C'26,114,88',C'222,254,242',C'112,176,154',C'0,248,172',C'74,212,255',C'0,248,172',C'255,86,104'},
      {C'14,5,9',C'30,10,18',C'116,26,48',C'255,232,238',C'182,126,142',C'255,48,88',C'255,168,72',C'76,234,158',C'255,48,88'},
      {C'6,16,32',C'12,32,60',C'36,104,168',C'228,246,255',C'126,168,204',C'48,210,255',C'132,148,255',C'64,242,196',C'255,88,120'},
      {C'20,10,18',C'38,18,34',C'132,58,108',C'255,236,248',C'194,144,178',C'255,112,196',C'120,214,255',C'86,238,188',C'255,74,108'},
      {C'244,248,252',C'228,236,246',C'164,184,210',C'18,32,48',C'86,108,134',C'0,136,196',C'16,158,136',C'0,152,108',C'218,56,74'},
      {C'6,16,14',C'12,28,24',C'28,84,68',C'232,252,244',C'118,166,150',C'0,232,162',C'46,204,255',C'32,238,148',C'255,86,108'},
      {C'6,12,28',C'12,24,52',C'36,78,164',C'234,242,255',C'126,154,202',C'76,172,255',C'134,118,255',C'52,232,182',C'255,88,112'},
      {C'4,18,24',C'10,34,44',C'24,104,124',C'226,252,255',C'112,172,186',C'0,238,224',C'68,164,255',C'44,242,186',C'255,94,114'},
      {C'18,6,26',C'34,12,50',C'122,36,152',C'252,234,255',C'182,132,202',C'246,74,218',C'64,218,255',C'64,244,192',C'255,74,118'},
      {C'10,10,12',C'22,22,26',C'96,80,34',C'246,242,230',C'156,148,132',C'255,204,64',C'184,196,214',C'72,224,146',C'248,84,92'},
      {C'240,246,252',C'224,235,246',C'154,182,212',C'18,34,54',C'88,112,140',C'22,120,214',C'0,152,172',C'14,154,108',C'218,64,78'},
      {C'16,6,12',C'32,12,24',C'128,30,58',C'255,236,242',C'186,128,146',C'255,54,96',C'0,218,242',C'62,234,158',C'255,54,96'},
      {C'4,14,10',C'10,28,20',C'26,96,62',C'222,255,236',C'106,166,134',C'32,244,142',C'244,196,56',C'32,244,142',C'255,88,88'},
      {C'12,8,24',C'24,16,46',C'86,56,148',C'242,236,255',C'158,140,196',C'184,122,255',C'96,188,255',C'74,234,188',C'255,86,134'},
      {C'20,12,6',C'38,24,12',C'132,76,30',C'255,242,226',C'188,148,112',C'255,148,48',C'255,204,88',C'108,224,126',C'255,78,66'},
      {C'6,18,24',C'12,34,46',C'38,112,124',C'230,252,250',C'126,174,182',C'82,252,206',C'108,158,255',C'82,252,206',C'255,98,128'},
      {C'18,22,28',C'30,36,46',C'74,88,110',C'236,242,250',C'142,156,176',C'112,192,255',C'168,148,255',C'76,222,168',C'244,96,108'},
      {C'250,248,242',C'238,234,222',C'192,182,158',C'34,30,24',C'112,104,92',C'176,122,24',C'32,108,162',C'20,144,96',C'206,62,68'},
      {C'8,4,22',C'18,10,44',C'76,42,164',C'238,232,255',C'148,136,198',C'148,92,255',C'0,228,255',C'68,242,196',C'255,72,128'},
      {C'4,12,32',C'10,24,62',C'32,82,188',C'230,240,255',C'126,154,206',C'56,162,255',C'255,212,62',C'56,232,178',C'255,86,102'},
      {C'4,12,10',C'10,24,20',C'30,86,64',C'226,248,238',C'116,158,140',C'48,218,148',C'218,184,84',C'48,218,148',C'246,86,98'},
      {C'22,10,18',C'42,20,34',C'142,58,76',C'255,238,234',C'194,146,152',C'255,112,92',C'255,188,76',C'88,232,168',C'255,72,104'},
      {C'252,247,240',C'242,233,220',C'202,182,156',C'44,34,26',C'126,110,94',C'188,126,44',C'46,124,158',C'26,146,102',C'210,68,74'},
      {C'10,12,6',C'20,24,12',C'88,118,20',C'244,255,220',C'152,172,114',C'186,255,32',C'0,224,255',C'136,255,64',C'255,68,96'},
      {C'2,14,26',C'6,28,50',C'18,86,126',C'220,248,255',C'106,162,188',C'24,224,242',C'84,132,255',C'36,240,188',C'255,96,112'},
      {C'14,6,8',C'28,12,18',C'112,28,48',C'255,236,240',C'178,128,138',C'238,56,96',C'244,186,88',C'76,226,154',C'238,56,96'},
      {C'10,8,24',C'20,16,46',C'64,142,196',C'238,246,255',C'142,162,202',C'0,236,224',C'255,78,196',C'38,242,188',C'255,72,126'},
      {C'248,242,234',C'236,226,212',C'188,166,142',C'46,34,26',C'124,104,88',C'168,108,52',C'48,126,156',C'28,144,98',C'208,68,72'},
      {C'8,8,26',C'16,18,52',C'52,62,154',C'234,238,255',C'136,144,198',C'118,142,255',C'72,218,255',C'68,236,186',C'255,86,124'},
      {C'4,11,22',C'9,22,40',C'20,92,136',C'232,250,255',C'116,172,202',C'0,240,255',C'56,156,255',C'34,246,176',C'255,78,112'},
      {C'3,13,9',C'8,26,18',C'20,104,68',C'224,255,238',C'108,176,144',C'44,255,144',C'0,224,196',C'44,255,144',C'255,76,98'},
      {C'12,10,6',C'24,20,12',C'106,82,26',C'252,246,226',C'174,158,120',C'255,208,44',C'244,160,36',C'76,232,148',C'250,78,84'},
      {C'13,6,26',C'26,12,52',C'108,44,174',C'246,234,255',C'172,138,208',C'200,98,255',C'44,228,255',C'70,246,196',C'255,66,122'},
      {C'4,16,12',C'9,32,24',C'24,110,80',C'224,254,240',C'114,178,152',C'24,242,158',C'52,208,246',C'24,242,158',C'255,82,100'},
      {C'19,5,8',C'38,10,16',C'138,30,48',C'255,232,238',C'190,128,142',C'255,58,92',C'255,164,58',C'74,236,156',C'255,58,92'},
      {C'3,16,28',C'7,32,54',C'20,96,142',C'226,246,255',C'112,166,196',C'26,214,246',C'68,146,255',C'56,238,188',C'255,94,112'},
      {C'16,22,30',C'28,38,52',C'76,112,148',C'240,248,255',C'150,178,204',C'146,216,255',C'186,232,255',C'82,238,196',C'248,94,114'},
      {C'20,11,4',C'40,22,8',C'132,78,20',C'255,244,218',C'192,156,108',C'255,176,24',C'255,218,86',C'116,234,118',C'255,74,64'},
      {C'5,11,30',C'10,22,60',C'36,74,168',C'230,240,255',C'128,152,204',C'82,156,255',C'46,230,248',C'66,238,186',C'255,84,116'},
      {C'4,18,18',C'10,36,36',C'24,118,114',C'224,254,252',C'114,178,176',C'36,248,212',C'78,206,255',C'36,248,212',C'255,88,108'},
      {C'16,6,10',C'32,12,20',C'122,28,50',C'255,234,240',C'184,128,144',C'255,54,96',C'255,174,76',C'78,236,160',C'255,54,96'},
      {C'22,8,20',C'44,16,40',C'144,48,112',C'255,238,248',C'198,144,182',C'255,108,196',C'104,216,255',C'88,240,192',C'255,72,108'},
      {C'8,12,5',C'18,26,10',C'84,118,24',C'244,255,222',C'158,178,120',C'194,255,46',C'64,232,204',C'132,255,84',C'255,74,88'},
      {C'12,6,24',C'24,12,48',C'96,46,162',C'242,232,255',C'168,140,204',C'184,116,255',C'74,204,255',C'82,240,192',C'255,78,124'},
      {C'242,248,254',C'224,236,248',C'158,184,214',C'16,32,50',C'84,108,136',C'0,138,204',C'14,162,142',C'0,154,112',C'220,58,76'}
   };
   SX_BG=t[i][0]; SX_CARD=t[i][1]; SX_EDGE=t[i][2]; SX_TEXT=t[i][3]; SX_MUTED=t[i][4];
   SX_GOLD=t[i][5]; SX_BLUE=t[i][6]; SX_GREEN=t[i][7]; SX_RED=t[i][8];
   SX_ZONE_BULL=BlendThemeColor(SX_BG,SX_GREEN,14); SX_ZONE_BEAR=BlendThemeColor(SX_BG,SX_RED,14);
   SX_GRID=BlendThemeColor(SX_BG,SX_TEXT,8); SX_VOLUME=SX_BLUE;
}
void BPInitState() {
   g_bpTheme=(XE_ApplyTheme && !InpAutoThemeSwitch) ? (int)XE_ColorTheme : -1;
   g_xeSessOn=XE_EnableSessionAI; g_xeSpAtrOn=XE_EnableSpreadATR; g_xeBoostOn=XE_EnableSmartBoost;
   g_xeEqTrailOn=XE_EnableEqTrailLock; g_xeExpoOn=XE_EnableExposureCap; g_xeMarginOn=XE_EnableMarginGuard;
   g_xeTimeBEOn=XE_EnableTimeBE; g_xeVolSLOn=XE_EnableVolAdaptSL; g_xeTimeBECount=0; g_xeVolMult=1.0; g_xeEqFired=false;
   XEGuardRestore();
   g_xeLogoPal=(int)XE_LogoColor;
   g_bpTrailOn=XE_EnablePosTrail; g_bpTrailMode=(int)XE_PosTrailMode; g_bpTPOn=XE_EnablePosTP_Trail;
   g_bpRegimeOn=XE_EnableRegimeAI; g_bpThrottleOn=XE_EnableEquityThrot; g_bpConfOn=XE_EnableConfluence;
   g_bpPartialOn=XE_EnableSmartPartial; g_bpShieldOn=(XE_DailyDDShieldPct>0);
   g_bpRobotOn=XE_ShowCureRobotLogo; g_bpWM=XE_ChartWatermark;
   if(g_bpWM && g_bpRobotOn) g_watermark=false;
   g_bpIQOn=XE_EnableIQGate; g_bpSizeOn=XE_EnableSmartSizing; g_bpExhaustOn=XE_EnableExhaustGuard;
   g_bpSpaceOn=XE_EnableSpacingGuard; g_bpProfitOn=XE_EnableProfitLock;
   g_xeTickVetoOn=XE_EnableTickVeto; g_xeMTFOn=XE_EnableMTFAlign;
   g_xeStreakOn=XE_EnableStreakGuard; g_xeBasketOn=XE_EnableKronosBasket;
   g_bpScalePct=(int)MathMax(65,MathMin(150,XE_DeckScalePct)); g_bpPage=(int)MathMax(0,MathMin(5,XE_DeckStartPage)); g_bpBadgeKey="";
   g_xeMainScalePct=(int)MathMax(65,MathMin(150,XE_MainScalePct));
   g_xeMainX=InpPanelX; g_xeMainY=InpPanelY; g_xeMainCustomPos=false;
   g_xeDeckX=XE_DeckX; g_xeDeckY=XE_DeckY; g_xeDeckCustomPos=(XE_DeckX>=0);
   g_xeDragTarget=0; g_xePrevMouseDown=false;
   if(GlobalVariableCheck(g_prefix+"xe_mx")) { g_xeMainX=(int)GlobalVariableGet(g_prefix+"xe_mx"); g_xeMainY=(int)GlobalVariableGet(g_prefix+"xe_my"); g_xeMainCustomPos=true; }
   if(GlobalVariableCheck(g_prefix+"xe_ms")) g_xeMainScalePct=(int)MathMax(65,MathMin(150,GlobalVariableGet(g_prefix+"xe_ms")));
   if(GlobalVariableCheck(g_prefix+"xe_dx")) { g_xeDeckX=(int)GlobalVariableGet(g_prefix+"xe_dx"); g_xeDeckY=(int)GlobalVariableGet(g_prefix+"xe_dy"); g_xeDeckCustomPos=true; }
   if(GlobalVariableCheck(g_prefix+"xe_ds")) g_bpScalePct=(int)MathMax(65,MathMin(150,GlobalVariableGet(g_prefix+"xe_ds")));
   g_bpCollapsed=false; g_bpLayout=0; g_bpRobotKey=""; g_bpWMKey=""; g_bpShieldFired=false;
   g_xeLastBid=0; g_xeTickEMA=0; g_xeTickDir=0; g_xeConsecLoss=0;
   g_xeBasketPeak=0; g_xeBasketArmed=false; g_xeMTFScore=0;
   for(int i=0;i<5;i++) g_xeMTFVote[i]=0;
   for(int i=0;i<16;i++) { g_bpVote[i]=0; g_bpVal[i]="--"; }
}
void BPCleanup() {
   ObjectsDeleteAll(0,g_prefix+"bp_");
   ResourceFree("::"+g_prefix+"BPRobot");
   ResourceFree("::"+g_prefix+"BPRobotW");
   ResourceFree("::"+g_prefix+"BPRobotB");
}

//--------------------------------------------------------------------
// Intelligent classifiers, microstructure, MTF, streak & basket guards
//--------------------------------------------------------------------
int BionicRegimeClassifier(double adxVal,double atrFast,double atrSlow,double effRatio) {
   if(atrSlow<=0.0) return 0;
   double volRatio=atrFast/atrSlow;
   if(volRatio>1.65) return 3;
   if(adxVal>=25.0 && effRatio>=0.45) return 1;
   if(volRatio>=1.25 && effRatio>=0.35) return 2;
   return 0;
}
void XEUpdateTickPressure() {
   double bid=SymbolInfoDouble(g_symbol,SYMBOL_BID);
   if(bid<=0 || g_consolePoint<=0) return;
   if(g_xeLastBid>0) {
      double d=(bid-g_xeLastBid)/g_consolePoint;
      g_xeTickEMA=0.72*g_xeTickEMA+0.28*d;
      g_xeTickDir=(g_xeTickEMA>1.8) ? 1 : ((g_xeTickEMA<-1.8) ? -1 : 0);
   }
   g_xeLastBid=bid;
}
int XETFTrendVote(ENUM_TIMEFRAMES tf) {
   MqlRates rr[];
   int got=CopyRates(g_symbol,tf,0,60,rr);
   if(got<35) return 0;
   ArraySetAsSeries(rr,false);
   double k9=2.0/10.0,k21=2.0/22.0,e9=rr[0].close,e21=rr[0].close;
   for(int i=1;i<got;i++) { e9+=k9*(rr[i].close-e9); e21+=k21*(rr[i].close-e21); }
   double c=rr[got-1].close;
   if(c>e9 && e9>e21) return 1;
   if(c<e9 && e9<e21) return -1;
   return 0;
}
void XEUpdateMTF() {
   ENUM_TIMEFRAMES tfs[5]={PERIOD_M5,PERIOD_M15,PERIOD_M30,PERIOD_H1,PERIOD_H4};
   double w[5]={0.12,0.18,0.20,0.25,0.25},sum=0;
   for(int i=0;i<5;i++) {
      g_xeMTFVote[i]=XETFTrendVote(tfs[i]);
      sum+=w[i]*g_xeMTFVote[i];
   }
   g_xeMTFScore=100.0*sum;
}
void XEUpdateStreak() {
   int losses=0;
#ifdef __MQL5__
   if(HistorySelect(TimeCurrent()-86400*5,TimeCurrent())) {
      int total=HistoryDealsTotal();
      for(int i=total-1;i>=0 && losses<20;i--) {
         ulong tk=HistoryDealGetTicket(i);
         if(tk==0) continue;
         if(HistoryDealGetInteger(tk,DEAL_MAGIC)!=ConsoleMagic || HistoryDealGetString(tk,DEAL_SYMBOL)!=g_symbol) continue;
         if(HistoryDealGetInteger(tk,DEAL_ENTRY)!=DEAL_ENTRY_OUT) continue;
         double pr=HistoryDealGetDouble(tk,DEAL_PROFIT)+HistoryDealGetDouble(tk,DEAL_SWAP)+HistoryDealGetDouble(tk,DEAL_COMMISSION);
         if(pr<0) losses++; else break;
      }
   }
#else
   int total=OrdersHistoryTotal();
   for(int i=total-1;i>=0 && losses<20;i--) {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
      if(OrderMagicNumber()!=ConsoleMagic || OrderSymbol()!=g_symbol) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL) continue;
      double pr=OrderProfit()+OrderSwap()+OrderCommission();
      if(pr<0) losses++; else break;
   }
#endif
   g_xeConsecLoss=losses;
}
void XECheckKronosBasket() {
   if(!g_xeBasketOn || XE_BasketTriggerUSD<=0) return;
   int np=ArraySize(g_positions);
   if(np<1) { g_xeBasketPeak=0; g_xeBasketArmed=false; return; }
   double netPL=0;
   for(int i=0;i<np;i++) netPL+=g_positions[i].profit;
   if(netPL>=XE_BasketTriggerUSD) {
      g_xeBasketArmed=true;
      if(netPL>g_xeBasketPeak) g_xeBasketPeak=netPL;
   }
   if(g_xeBasketArmed && g_xeBasketPeak>0) {
      double floorUSD=g_xeBasketPeak*MathMax(0.10,MathMin(0.95,XE_BasketKeepPct/100.0));
      if(netPL<=floorUSD && netPL>0) {
         BPClosePositions(0);
         Log("Kronos Positive Basket locked +"+StringFormat("%.2f",netPL)+" (peak "+StringFormat("%.2f",g_xeBasketPeak)+")");
         g_xeBasketPeak=0; g_xeBasketArmed=false;
      }
   }
}
void XELockProfitHalf() {
   ConsoleLoadPositions();
   int np=ArraySize(g_positions); if(np<1) { Log("No owned positions to lock"); return; }
   double tick=SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_SIZE);
   double minD=MinStopDistance(true);
   int locked=0;
   for(int i=0;i<np;i++) {
      double mkt=(g_positions[i].direction>0) ? SymbolInfoDouble(g_symbol,SYMBOL_BID) : SymbolInfoDouble(g_symbol,SYMBOL_ASK);
      double prof=g_positions[i].direction*(mkt-g_positions[i].open);
      if(prof<=minD*1.5) continue;
      double targetSL=g_positions[i].open+g_positions[i].direction*(prof*0.50);
      targetSL=SXRoundPrice(targetSL,tick,g_positions[i].direction);
      if(g_positions[i].sl>0 && g_positions[i].direction*(targetSL-g_positions[i].sl)<=tick) continue;
      bool already=false; if(ModifyStop(g_positions[i],targetSL,already)) locked++;
   }
   Log("Locked +50% open profit on "+IntegerToString(locked)+" position(s)");
}
double BPThrottle() {
   if(!g_bpThrottleOn || !XE_EnableEquityThrot) return 1.0;
   double dd=g_drawdown,lim=MathMax(XE_DailyDDShieldPct,1.0);
   if(dd>=lim*0.65) return 0.25;
   if(dd>=lim*0.45) return 0.50;
   if(dd>=lim*0.25) return 0.75;
   return 1.0;
}
bool BPShieldHit() { return g_bpShieldOn && XE_DailyDDShieldPct>0 && g_dayLoss>=XE_DailyDDShieldPct; }
int BPIQ(int direction) {
   if((direction!=1 && direction!=-1) || !g_consoleReady) return 0;
   int score=0;
   if(direction*(g_cachedFast-g_cachedSlow)>0) score+=18;
   if(direction*(g_closeCurrent-g_cachedFast)>0) score+=14;
   if(g_adx>=25.0) score+=14; else if(g_adx>=18.0) score+=9; else score+=3;
   if(g_quantumER>=0.45) score+=14; else if(g_quantumER>=0.25) score+=9; else score+=3;
   double rsiBias=direction*(g_rsi-50.0);
   if(rsiBias>=6.0) score+=12; else if(rsiBias>=0.0) score+=6;
   if(g_volumeRatio>=1.10) score+=8; else if(g_volumeRatio>=0.80) score+=5;
   if(direction*g_superDir>0) score+=8;
   if(direction*g_quantumSuperDir>0) score+=4;
   if(direction*g_xeMTFScore>=20.0) score+=8; else if(direction*g_xeMTFScore>0) score+=4;
   return (int)MathMax(0,MathMin(100,score));
}
double BPSmartSizeMult(int direction) {
   if(!g_bpSizeOn) return 1.0;
   double m=0.50+0.50*(double)BPIQ(direction)/100.0;
   if(g_bpRegimeOn) {
      if(g_bpRegime==0) m*=0.80; else if(g_bpRegime==2) m*=0.90; else if(g_bpRegime==3) m*=0.35;
   }
   if(g_xeStreakOn && g_xeConsecLoss>=2) m*=0.65;
   if(g_xeBoostOn && BPIQ(direction)>=75 && g_bpRegime==1 && g_bpDayGain>0.25 && g_xeConsecLoss==0) m=MathMin(1.0,m*1.15);
   return MathMax(XE_MinRiskMult,MathMin(1.0,m));
}
double BPSizeMult(int direction) {
   double thr=g_bpThrottleOn ? BPThrottle() : 1.0;
   double m=thr*BPSmartSizeMult(direction);
   return MathMax(MathMin(thr,XE_MinRiskMult),MathMin(1.0,m));
}
double BPRiskLots(int direction,double price,double sl,bool manual) {
   double lots=RiskLotsCore(direction,price,sl,manual);
   if(manual || lots<=0) return lots;
   double m=BPSizeMult(direction);
   g_bpSizeMult=m;
   if(m>=0.999) return lots;
   double scaled=ConsoleNormalizeLots(lots*m);
   return scaled>0 ? scaled : lots;
}
double BPEMA(int period,int offset) {
   int last=g_n-1-offset; if(last<1) return 0;
   int start=(int)MathMax(0,last-(int)MathMax(300,period*4));
   double k=2.0/(period+1),e=g_rates[start].close;
   for(int i=start+1;i<=last;i++) e+=k*(g_rates[i].close-e);
   return e;
}
double BPAvgTR(int bars) {
   int n=g_n; double s=0; int c=0;
   for(int i=n-1;i>=1 && c<bars;i--,c++) s+=SXTrueRange(g_rates[i].high,g_rates[i].low,g_rates[i-1].close);
   return c>0 ? s/c : 0;
}
void BPRefreshIntel() {
   int n=g_n;
   if(!g_consoleReady || n<60 || ArraySize(g_rates)<n || g_atr<=0) { g_bpScore=0; g_bpRegime=0; return; }
   double c=g_rates[n-1].close;
   double e20=BPEMA(20,0),e50=BPEMA(50,0),e200=BPEMA(200,0);
   int s=(c>e20 ? 1 : -1)+(e20>e50 ? 1 : -1)+(e50>e200 ? 1 : -1);
   g_bpVote[0]=s>=2 ? 1 : (s<=-2 ? -1 : 0);
   g_bpVal[0]=StringFormat("%+.1fA",(c-e50)/g_atr);
   g_bpVote[1]=g_rsi>55 ? 1 : (g_rsi<45 ? -1 : 0);
   g_bpVal[1]=StringFormat("%.0f",g_rsi);
   g_bpVote[2]=g_macd>0 ? 1 : (g_macd<0 ? -1 : 0);
   g_bpVal[2]=g_macd>0 ? "BULL" : (g_macd<0 ? "BEAR" : "FLAT");
   double di=g_gem.plusDI-g_gem.minusDI;
   g_bpVote[3]=g_adx>=20 ? (di>0 ? 1 : -1) : 0;
   g_bpVal[3]=StringFormat("%.0f",g_adx);
   // Stochastic 14,3
   double kv[3]={0,0,0};
   for(int b=0;b<3;b++) {
      int last=n-1-b; double hh=-DBL_MAX,ll=DBL_MAX;
      for(int j=last;j>last-14 && j>=0;j--) { if(g_rates[j].high>hh) hh=g_rates[j].high; if(g_rates[j].low<ll) ll=g_rates[j].low; }
      kv[b]=hh>ll ? 100.0*(g_rates[last].close-ll)/(hh-ll) : 50.0;
   }
   double kNow=kv[0],dNow=(kv[0]+kv[1]+kv[2])/3.0;
   g_bpVote[4]=(kNow>dNow && kNow<85) ? 1 : ((kNow<dNow && kNow>15) ? -1 : 0);
   g_bpVal[4]=StringFormat("%.0f",kNow);
   // CCI 20
   double tp[20],tpMean=0; int cnt=0; ArrayInitialize(tp,0);
   for(int j=n-1;j>=n-20 && j>=0;j--) { tp[cnt]=(g_rates[j].high+g_rates[j].low+g_rates[j].close)/3.0; tpMean+=tp[cnt]; cnt++; }
   double cci=0;
   if(cnt>=20) {
      tpMean/=cnt; double md=0; for(int j=0;j<cnt;j++) md+=MathAbs(tp[j]-tpMean); md/=cnt;
      cci=md>0 ? (tp[0]-tpMean)/(0.015*md) : 0;
   }
   g_bpVote[5]=cci>50 ? 1 : (cci<-50 ? -1 : 0);
   g_bpVal[5]=StringFormat("%+.0f",cci);
   // Bollinger %B 20,2
   double mean=0,sq=0;
   for(int j=n-1;j>=n-20;j--) mean+=g_rates[j].close; mean/=20.0;
   for(int j=n-1;j>=n-20;j--) sq+=(g_rates[j].close-mean)*(g_rates[j].close-mean);
   double sd=MathSqrt(sq/20.0),pb=sd>0 ? (c-(mean-2*sd))/(4*sd) : 0.5;
   g_bpVote[6]=pb>0.60 ? 1 : (pb<0.40 ? -1 : 0);
   g_bpVal[6]=StringFormat("%.2f",pb);
   // Efficiency ratio 10
   double net=MathAbs(c-g_rates[n-11].close),path=0;
   for(int j=n-1;j>=n-10;j--) path+=MathAbs(g_rates[j].close-g_rates[j-1].close);
   g_bpER=path>0 ? net/path : 0;
   g_bpVote[7]=g_bpER>=0.40 ? (c>g_rates[n-11].close ? 1 : -1) : 0;
   g_bpVal[7]=StringFormat("%.2f",g_bpER);
   g_bpPB=pb;
   g_bpVote[8]=g_superDir>0 ? 1 : (g_superDir<0 ? -1 : 0);
   g_bpVal[8]=g_superDir>0 ? "UP" : (g_superDir<0 ? "DOWN" : "FLAT");
   g_bpVote[9]=g_mfi>=58 ? 1 : (g_mfi<=42 ? -1 : 0);
   g_bpVal[9]=StringFormat("%.0f",g_mfi);
   g_bpVote[10]=(g_vwap>0 && c>g_vwap) ? 1 : ((g_vwap>0 && c<g_vwap) ? -1 : 0);
   g_bpVal[10]=g_vwap>0 ? StringFormat("%+.1fA",(c-g_vwap)/g_atr) : "n/a";
   g_bpVote[11]=g_kalmanDir>0 ? 1 : (g_kalmanDir<0 ? -1 : 0);
   g_bpVal[11]=g_kalmanDir>0 ? "UP" : (g_kalmanDir<0 ? "DOWN" : "FLAT");
   // 12: Ichimoku Tenkan-sen (9)
   double thh=-DBL_MAX,tll=DBL_MAX;
   for(int j=n-1;j>=n-9 && j>=0;j--) { if(g_rates[j].high>thh) thh=g_rates[j].high; if(g_rates[j].low<tll) tll=g_rates[j].low; }
   double tenkan=0.5*(thh+tll);
   g_bpVote[12]=(c>tenkan) ? 1 : ((c<tenkan) ? -1 : 0);
   g_bpVal[12]=StringFormat("%+.1fA",(c-tenkan)/g_atr);
   // 13: Aroon Oscillator (14)
   int hiIdx=0,loIdx=0; double ahh=-DBL_MAX,all=DBL_MAX;
   for(int j=0;j<14 && n-1-j>=0;j++) {
      if(g_rates[n-1-j].high>ahh) { ahh=g_rates[n-1-j].high; hiIdx=j; }
      if(g_rates[n-1-j].low<all) { all=g_rates[n-1-j].low; loIdx=j; }
   }
   double aroonOsc=100.0*(double)(loIdx-hiIdx)/14.0;
   g_bpVote[13]=aroonOsc>=25.0 ? 1 : (aroonOsc<=-25.0 ? -1 : 0);
   g_bpVal[13]=StringFormat("%+.0f",aroonOsc);
   // 14: Williams %R (14)
   double wpr=(ahh>all) ? -100.0*(ahh-c)/(ahh-all) : -50.0;
   g_bpVote[14]=(wpr>-35.0) ? 1 : ((wpr<-65.0) ? -1 : 0);
   g_bpVal[14]=StringFormat("%.0f",wpr);
   // 15: Multi-Timeframe Alignment (M5..H4)
   XEUpdateMTF();
   g_bpVote[15]=g_xeMTFScore>=20.0 ? 1 : (g_xeMTFScore<=-20.0 ? -1 : 0);
   g_bpVal[15]=StringFormat("%+.0f",g_xeMTFScore);

   double w[16]={1.5,1.0,1.0,1.25,0.9,0.75,0.75,0.75,1.0,0.5,0.6,0.75,0.8,0.75,0.65,1.35},sum=0,wsum=0;
   for(int i=0;i<16;i++) { sum+=w[i]*g_bpVote[i]; wsum+=w[i]; }
   g_bpScore=100.0*sum/wsum;
   double fast=BPAvgTR(5),slow=BPAvgTR(50);
   g_bpVolRatio=slow>0 ? fast/slow : 1.0;
   g_bpRegime=BionicRegimeClassifier(g_adx,fast,slow,g_bpER);
   g_bpSpike=(g_rates[n-1].high-g_rates[n-1].low)/g_atr;
}
double XEVolSLMult() {
   if(!g_xeVolSLOn) { g_xeVolMult=1.0; return 1.0; }
   double lo=MathMax(0.50,MathMin(1.00,XE_VolAdaptMinMult)),hi=MathMax(1.00,MathMin(2.00,XE_VolAdaptMaxMult));
   double v=g_bpVolRatio>0 ? g_bpVolRatio : 1.0;
   // Hot tape (fast ATR above slow ATR) widens the stop to sit outside noise; quiet tape tightens it.
   double m=1.0+0.60*(v-1.0);
   if(g_bpRegime==3) m=MathMax(m,1.15);
   g_xeVolMult=MathMax(lo,MathMin(hi,m));
   return g_xeVolMult;
}
string XECcyBase(string sym) { return SymbolInfoString(sym,SYMBOL_CURRENCY_BASE); }
string XECcyQuote(string sym) { return SymbolInfoString(sym,SYMBOL_CURRENCY_PROFIT); }
void XECcyAdd(string &names[],int &stacks[],string ccy,int delta) {
   if(ccy=="") return;
   int n=ArraySize(names);
   for(int i=0;i<n;i++) if(names[i]==ccy) { stacks[i]+=delta; return; }
   ArrayResize(names,n+1); ArrayResize(stacks,n+1); names[n]=ccy; stacks[n]=delta;
}
void XEAddSymbolExposure(string &names[],int &stacks[],string sym,int dir) {
   string b=XECcyBase(sym),q=XECcyQuote(sym);
   if(b=="" || q=="" || b==q) return;   // CFDs / indices: counted in the total cap only
   XECcyAdd(names,stacks,b,dir); XECcyAdd(names,stacks,q,-dir);
}
// Owned (this magic) open positions across the whole account, with per-currency stacks.
int XEOwnedExposure(string &names[],int &stacks[]) {
   ArrayResize(names,0); ArrayResize(stacks,0);
   int total=0;
#ifdef __MQL5__
   for(int i=PositionsTotal()-1;i>=0;i--) {
      ulong t=PositionGetTicket(i); if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=ConsoleMagic) continue;
      int dir=PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ? 1 : -1;
      total++; XEAddSymbolExposure(names,stacks,PositionGetString(POSITION_SYMBOL),dir);
   }
#else
   for(int i=OrdersTotal()-1;i>=0;i--) {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=ConsoleMagic || OrderType()>OP_SELL) continue;
      int dir=OrderType()==OP_BUY ? 1 : -1;
      total++; XEAddSymbolExposure(names,stacks,OrderSymbol(),dir);
   }
#endif
   return total;
}
void XERefreshExposure() {
   string names[]; int stacks[];
   g_xeOwnedTotal=XEOwnedExposure(names,stacks);
   g_xeTopCcy="--"; g_xeTopStack=0;
   for(int i=0;i<ArraySize(names);i++) if(MathAbs(stacks[i])>MathAbs(g_xeTopStack)) { g_xeTopStack=stacks[i]; g_xeTopCcy=names[i]; }
}
bool XEExposureAllows(int direction,string &why) {
   if(!g_xeExpoOn || NoPositionCaps()) return true;
   string names[]; int stacks[];
   XEOwnedExposure(names,stacks);   // the plain position-count cap stays with InpMaxPortfolioPositions
   if(XE_MaxCurrencyStack>0 && direction!=0) {
      string b=XECcyBase(g_symbol),q=XECcyQuote(g_symbol);
      if(b!="" && q!="" && b!=q) {
         XECcyAdd(names,stacks,b,direction); XECcyAdd(names,stacks,q,-direction);
         for(int i=0;i<ArraySize(names);i++) {
            if(names[i]!=b && names[i]!=q) continue;
            int add=names[i]==b ? direction : -direction;
            if(stacks[i]*add>0 && MathAbs(stacks[i])>XE_MaxCurrencyStack) {
               why="Currency stack cap: "+names[i]+" "+(stacks[i]>0 ? "long x" : "short x")+IntegerToString((int)MathAbs(stacks[i]))+" > "+IntegerToString(XE_MaxCurrencyStack);
               return false;
            }
         }
      }
   }
   return true;
}
bool XEMarginAllows(string &why) {
   if(!g_xeMarginOn || XE_MinMarginLevelPct<=0 || NoMarginPrecheck()) return true;
   double margin=AccountInfoDouble(ACCOUNT_MARGIN);
   if(margin<=0) return true;
   double level=AccountInfoDouble(ACCOUNT_MARGIN_LEVEL);
   if(level>0 && level<XE_MinMarginLevelPct) { why="Margin guard: level "+StringFormat("%.0f",level)+"% < "+StringFormat("%.0f",XE_MinMarginLevelPct)+"%"; return false; }
   return true;
}
// Stale-trade breakeven candidate: 0 when it does not apply. Positive-only and ratchet-only by construction.
double XETimeBEStop(SXPosition &position,double market,double risk,double cost,double minDistance,double tick) {
   if(!g_xeTimeBEOn || risk<=0 || tick<=0 || position.opened<=0) return 0.0;
   int bars=iBarShift(g_symbol,g_tf,position.opened,false);
   if(bars<(int)MathMax(1,MathMin(500,XE_TimeBEBars))) return 0.0;
   double profit=position.direction*(market-position.open);
   if(profit<MathMax(0.05,XE_TimeBEMinR)*risk) return 0.0;
   double lock=position.open+position.direction*(cost+MathMax(0.0,MathMin(0.50,XE_TimeBELockR))*risk);
   lock=position.direction>0 ? MathMin(lock,market-minDistance) : MathMax(lock,market+minDistance);
   lock=SXRoundPrice(lock,tick,position.direction);
   if(lock<=0 || position.direction*(lock-position.open)<=0) return 0.0;
   if(position.sl>0 && position.direction*(lock-position.sl)<=0) return 0.0;
   return lock;
}
void XEGuardTick() {
   int day=DayCode();
   if(day!=g_xeEqDay) {
      g_xeEqDay=day; g_xeEqPeakGain=0; g_xeEqLocked=false; g_xeEqFired=false;
      WriteGuard("xeeqday",day); WriteGuard("xeeqpk",0); WriteGuard("xeeqlk",0);
   }
   double gain=g_dayEquity>0 ? 100.0*(ConsoleEquity()-g_dayEquity)/g_dayEquity : 0.0;
   if(gain>g_xeEqPeakGain) { g_xeEqPeakGain=gain; WriteGuard("xeeqpk",gain); }
   double keep=MathMax(10.0,MathMin(95.0,XE_EqTrailKeepPct));
   if(g_xeEqTrailOn && !NoProfitLock() && XE_EqTrailArmPct>0 && !g_xeEqLocked &&
      g_xeEqPeakGain>=XE_EqTrailArmPct && gain<g_xeEqPeakGain*keep/100.0) {
      g_xeEqLocked=true; WriteGuard("xeeqlk",1); GlobalVariablesFlush();
      Notify("Trailing equity lock: day gain "+StringFormat("%+.2f",gain)+"% fell below "+StringFormat("%.0f",keep)+"% of peak "+StringFormat("%+.2f",g_xeEqPeakGain)+"%");
   }
   if(g_xeEqLocked && g_xeEqTrailOn && XE_EqTrailClosesAll && !g_xeEqFired && PortfolioExposureCount()>0) {
      g_xeEqFired=true; RequestPortfolioExit("CVT LT DRIOD BOT NO ERRORS trailing equity lock");
   }
   XERefreshExposure();
   XEVolSLMult();
}
void XEGuardRestore() {
   int day=DayCode();
   if(GlobalVariableCheck(g_guardKey+"xeeqday") && (int)GlobalVariableGet(g_guardKey+"xeeqday")==day) {
      g_xeEqDay=day;
      g_xeEqPeakGain=GlobalVariableCheck(g_guardKey+"xeeqpk") ? GlobalVariableGet(g_guardKey+"xeeqpk") : 0.0;
      g_xeEqLocked=GlobalVariableCheck(g_guardKey+"xeeqlk") && GlobalVariableGet(g_guardKey+"xeeqlk")>0;
   } else { g_xeEqDay=0; g_xeEqPeakGain=0; g_xeEqLocked=false; }
}
string XEGuardStatus() {
   string why="";
   if(g_xeEqTrailOn && g_xeEqLocked && !NoProfitLock()) return "EQ LOCK";
   if(!XEMarginAllows(why)) return "MARGIN";
   if(!XEExposureAllows(g_bpScore>=0 ? 1 : -1,why)) return "EXPOSURE";
   return "CLEAR";
}
void XEHtfRefresh() {
   static string cachedSymbol="";
   if(cachedSymbol!=g_symbol) {cachedSymbol=g_symbol;g_xeHtfStamp=0;g_xeHtfEma=0;}
   datetime now=iTime(g_symbol,XE_HTFBiasTF,0);
   if(now<=0) {g_xeHtfEma=0;return;}
   if(g_xeHtfStamp>0 && now==g_xeHtfStamp && g_xeHtfEma>0) return;
   int len=(int)MathMax(20,MathMin(500,XE_HTFEmaLen));
   MqlRates rr[];
   int got=CopyRates(g_symbol,XE_HTFBiasTF,0,len*3+5,rr);
   if(got<len+5) { g_xeHtfEma=0; return; }
   ArraySetAsSeries(rr,false);
   double k=2.0/(len+1),e=rr[0].close;
   int last=got-2;
   if(rr[last+1].time!=now) {g_xeHtfEma=0;return;}
   for(int i=1;i<=last;i++) e+=k*(rr[i].close-e);
   g_xeHtfEma=e; g_xeHtfClose=rr[last].close; g_xeHtfStamp=now;
}
bool XEPrideGate(int direction,string &why) {
   if(direction!=1 && direction!=-1) return true;
   if(BroadRestrictions()) return true;
   if(XE_EnableAntiFomo && XE_FomoMaxStreak>0 && g_n>XE_FomoMaxStreak+2) {
      int streak=0;
      for(int i=g_n-1;i>=0 && streak<XE_FomoMaxStreak;i--) {
         if(direction*(g_rates[i].close-g_rates[i].open)>0) streak++; else break;
      }
      if(streak>=XE_FomoMaxStreak) { why="Anti-FOMO guard: "+IntegerToString(streak)+" straight candles already ran"; return false; }
   }
   if(XE_EnableATRExpansion && XE_ATRExpansionMult>0) {
      double slow=BPAvgTR((int)MathMax(10,MathMin(300,XE_ATRExpansionBars))),fast=BPAvgTR(5);
      if(g_n<=XE_ATRExpansionBars || slow<=0) {why="Waiting for ATR history";return false;}
      if(slow>0 && fast>XE_ATRExpansionMult*slow) { why="ATR expansion guard: volatility spike "+StringFormat("%.2f",fast/slow)+"x"; return false; }
   }
   if(XE_EnableHTFBias) {
      if(PeriodSeconds(XE_HTFBiasTF)<PeriodSeconds(g_tf)) {why="Bias timeframe below chart";return false;}
      XEHtfRefresh();
      if(g_xeHtfEma<=0 || g_xeHtfClose<=0) {why="Waiting for HTF data";return false;}
      if(g_xeHtfEma>0 && direction*(g_xeHtfClose-g_xeHtfEma)<=0) { why="HTF "+IntegerToString(XE_HTFEmaLen)+" EMA bias opposes this entry"; return false; }
      if(XE_HTFAdxMin>0 && g_adx<XE_HTFAdxMin) { why="ADX "+StringFormat("%.0f",g_adx)+" below "+StringFormat("%.0f",XE_HTFAdxMin); return false; }
   }
   return true;
}
void XESessionHarvest() {
   if(!XE_EnableSessionHarvest) return;
   MqlDateTime d; TimeToStruct(TimeCurrent(),d);
   if(d.hour!=XE_HarvestHour) return;
   int code=DayCode();
   if(g_xeHarvestDay==code || (int)ReadGV("pdHarvest",0)==code) return;
   WriteGV("pdHarvest",code); GlobalVariablesFlush();
   g_xeHarvestDay=code;
   ConsoleLoadPositions();
   if(ArraySize(g_positions)>0) BPClosePositions(1);
}
bool BPEntryGate(int direction,string &why) {
   // Portfolio guard checks that also protect manual entries
   if(!XEMarginAllows(why)) return false;
   if(!XEExposureAllows(direction,why)) return false;
   if(g_bpShieldOn && BPShieldHit()) { why="CVT LT DRIOD BOT NO ERRORS daily drawdown shield"; return false; }
   if(XE_MaxSpreadPts>0 && !NoSpreadQuoteLimits()) {
      double sp=(SymbolInfoDouble(g_symbol,SYMBOL_ASK)-SymbolInfoDouble(g_symbol,SYMBOL_BID))/g_consolePoint;
      if(sp>XE_MaxSpreadPts) { why="CVT LT DRIOD BOT NO ERRORS spread guard"; return false; }
   }
   if(g_bpManualTrade) return true;
   if(g_xeEqTrailOn && g_xeEqLocked && !NoProfitLock()) { why="Trailing equity lock: day gain gave back from peak "+StringFormat("%+.2f",g_xeEqPeakGain)+"%"; return false; }
   BPRefreshIntel();
   XEUpdateStreak();
   if(g_xeSessOn) {
      MqlDateTime sdt; TimeToStruct(TimeCurrent(),sdt);
      bool inSess=(XE_SessionStartHour<=XE_SessionEndHour)
         ? (sdt.hour>=XE_SessionStartHour && sdt.hour<XE_SessionEndHour)
         : (sdt.hour>=XE_SessionStartHour || sdt.hour<XE_SessionEndHour);
      if(!inSess) { why="Smart Session AI: outside "+IntegerToString(XE_SessionStartHour)+":00-"+IntegerToString(XE_SessionEndHour)+":00"; return false; }
   }
   if(g_xeSpAtrOn && XE_MaxSpreadATRPct>0 && g_atr>0 && !NoSpreadQuoteLimits()) {
      double spCost=SymbolInfoDouble(g_symbol,SYMBOL_ASK)-SymbolInfoDouble(g_symbol,SYMBOL_BID);
      double spPct=100.0*spCost/g_atr;
      if(spPct>XE_MaxSpreadATRPct) { why="Smart Spread/ATR guard ("+StringFormat("%.1f",spPct)+"% > "+StringFormat("%.0f",XE_MaxSpreadATRPct)+"%)"; return false; }
   }
   if(g_xeStreakOn && XE_MaxConsecLosses>0 && g_xeConsecLoss>=XE_MaxConsecLosses) {
      why="Streak guard: "+IntegerToString(g_xeConsecLoss)+" consecutive losses"; return false;
   }
   if(g_xeTickVetoOn && g_xeTickDir!=0 && direction!=0 && g_xeTickDir==-direction) {
      why="Tick quote-pressure veto"; return false;
   }
   if(g_xeMTFOn && direction*g_xeMTFScore<XE_MinMTFScore) {
      why="MTF alignment "+StringFormat("%+.0f",g_xeMTFScore)+" below "+IntegerToString(XE_MinMTFScore); return false;
   }
   if(g_bpProfitOn && XE_DailyProfitLockPct>0 && g_bpDayGain>=XE_DailyProfitLockPct) {
      why="Daily profit lock: "+StringFormat("%+.2f",g_bpDayGain)+"% target reached"; return false;
   }
   if(g_bpSpaceOn && XE_SpacingMinutes>0) {
      datetime nowT=TimeCurrent();
      for(int i=0;i<ArraySize(g_positions);i++)
         if(g_positions[i].opened>0 && nowT-g_positions[i].opened<(datetime)(XE_SpacingMinutes*60)) { why="Entry spacing guard"; return false; }
   }
   if(g_bpExhaustOn) {
      if(direction>0 && g_rsi>=XE_ExhaustRSI && g_bpPB>1.0) { why="Exhaustion guard: stretched long"; return false; }
      if(direction<0 && g_rsi<=100.0-XE_ExhaustRSI && g_bpPB<0.0) { why="Exhaustion guard: stretched short"; return false; }
   }
   if(g_bpIQOn) {
      int iq=BPIQ(direction);
      if(iq<XE_MinIQScore) { why="Smart IQ "+IntegerToString(iq)+"/100 below "+IntegerToString(XE_MinIQScore); return false; }
   }
   if(g_bpRegimeOn && XE_BlockHighVol && g_bpRegime==3) { why="Regime AI: high-volatility regime"; return false; }
   if(XE_SpikeGuardATR>0 && g_bpSpike>XE_SpikeGuardATR) { why="Spike guard: oversized bar"; return false; }
   if(g_bpConfOn && direction*g_bpScore<XE_MinConfluence) {
      why="Confluence "+StringFormat("%+.0f",g_bpScore)+" below "+StringFormat("%.0f",XE_MinConfluence); return false;
   }
   return XEPrideGate(direction,why);
}
void BPTick() {
   XESessionHarvest();
   XEUpdateTickPressure();
   BPRefreshIntel();
   XEGuardTick();
   XECheckKronosBasket();
   if(!BPShieldHit()) { g_bpShieldFired=false; return; }
   if(XE_ShieldClosesAll && !g_bpShieldFired && PortfolioExposureCount()>0) {
      g_bpShieldFired=true; g_auto=false;
      RequestPortfolioExit("CVT LT DRIOD BOT NO ERRORS daily drawdown shield");
      Log("Drawdown shield closed owned exposure");
   }
}

//--------------------------------------------------------------------
// 27 Smart Positive Trailing SL modes, TP runner & partial close
//--------------------------------------------------------------------
bool CTMomentumFading(int direction) {
   if(!g_consoleReady || g_n<3 || (direction!=1 && direction!=-1)) return false;
   int last=g_n-1,votes=0;
   if(direction*(g_rsi-50.0)<0) votes++;
   if(g_superDir!=0 && g_superDir!=direction) votes++;
   if(ArraySize(g_fastSeries)>last && ArraySize(g_slowSeries)>last && direction*(g_fastSeries[last]-g_slowSeries[last])<0) votes++;
   double body=g_rates[last].close-g_rates[last].open;
   if(g_atr>0 && direction*body<=-0.6*g_atr) votes++;
   return votes>=2;
}
bool CTSessionAllowed() {
   MqlDateTime dt; TimeToStruct(TimeCurrent(),dt);
   int h=dt.hour;
   if(CT_SessionStartHour<=CT_SessionEndHour) return (h>=CT_SessionStartHour && h<=CT_SessionEndHour);
   return (h>=CT_SessionStartHour || h<=CT_SessionEndHour);
}
double BPFibFrac(double r) {
   if(r>=5.0) return 0.786;
   if(r>=3.0) return 0.618;
   if(r>=2.0) return 0.500;
   if(r>=1.0) return 0.382;
   return 0.0;
}
double BPPositiveSL(int dir,double entry,double market,double curSL,double atr,double risk,double spreadPts,double pt,double tick,double hi8,double lo8,double prevHi,double prevLo,double bestPrice,double utLine) {
   if(pt<=0 || risk<=0 || atr<=0 || dir==0) return 0.0;
   double profit=dir*(market-entry);
   if(profit<=0) return 0.0;
   double r=profit/risk,buffer=(spreadPts+5.0)*pt,best=0.0,cand=0.0,mult=XE_PosATR_Mult;
   if(r>=XE_PosBE_TriggerR) best=entry+dir*(risk*XE_PosBE_LockR+buffer);
   if(CT_EnableMomFadeBE && r>=0.45 && CTMomentumFading(dir)) {
      double earlyBE=entry+dir*(risk*0.12+buffer);
      if(best==0.0 || dir*(earlyBE-best)>0) best=earlyBE;
   }
   int mode=g_bpTrailMode;
   if(mode==1) {
      double lockR=0;
      if(r>=4.0) lockR=3.0; else if(r>=3.0) lockR=2.0; else if(r>=2.0) lockR=1.0; else if(r>=1.0) lockR=0.25;
      if(lockR>0) cand=entry+dir*risk*lockR;
   } else if(mode==4) {
      double ext=dir>0 ? hi8 : lo8;
      if(ext>0) cand=ext-dir*atr*mult;
   } else if(mode==5) {
      double sw=dir>0 ? prevLo : prevHi;
      if(sw>0) cand=sw-dir*buffer;
   } else if(mode==8) {
      double f=BPFibFrac(r);
      if(f>0) cand=entry+dir*profit*f;
   } else if(mode==11) {
      double m2=mult*((g_bpRegime==1) ? 1.25 : (g_bpRegime==2 ? 1.00 : (g_bpRegime==3 ? 0.85 : 0.75)));
      if(dir*g_bpScore<-10.0) m2*=0.60;
      cand=market-dir*MathMax(atr*m2,buffer*2.0);
      double f2=BPFibFrac(r),fib=f2>0 ? entry+dir*profit*f2 : 0.0;
      if(fib>0 && dir*(fib-cand)>0) cand=fib;
   } else if(mode==12) { // Neuro Structure Positive
      int iq=BPIQ(dir);
      double iqScale=(iq>=70) ? 1.15 : ((iq>=45) ? 0.85 : 0.55);
      double sw=dir>0 ? prevLo : prevHi;
      double c1=market-dir*MathMax(atr*mult*iqScale,buffer*2.0);
      cand=c1;
      if(sw>0 && dir*(sw-entry)>buffer && dir*(sw-cand)>0) cand=sw-dir*buffer;
   } else if(mode==13) { // Time-Decay Positive Lock
      double decay=MathMax(0.40,1.0-0.08*MathMin(8.0,r*2.0));
      cand=market-dir*MathMax(atr*mult*decay,buffer*2.0);
      double floorP=entry+dir*profit*MathMin(0.75,0.25+0.12*r);
      if(r>=1.0 && dir*(floorP-cand)>0) cand=floorP;
   } else if(mode==14) { // Reversal Shield Positive
      bool rev=(dir*g_bpScore<-15.0) || (dir>0 && g_rsi>74.0) || (dir<0 && g_rsi<26.0);
      double rm=rev ? 0.40 : 1.05;
      cand=market-dir*MathMax(atr*mult*rm,buffer*1.5);
   } else if(mode==15) { // Profit Step-Ladder Positive (+0.5R steps)
      double steps=MathFloor(r*2.0)/2.0;
      if(steps>=1.0) cand=entry+dir*risk*(steps-0.50);
   } else if(mode==16) { // Kronos Positive Basket Lock
      double bMult=g_xeBasketArmed ? 0.55 : 1.00;
      cand=market-dir*MathMax(atr*mult*bMult,buffer*2.0);
   } else if(mode==17) { // Gold Reaper Turbo Positive
      double gm=MathMax(0.45,MathMin(1.10,0.85/MathMax(0.7,g_bpVolRatio)));
      cand=market-dir*MathMax(atr*mult*gm,buffer*2.0);
   } else if(mode==18) { // Ichimoku Tenkan Positive
      double thh=-DBL_MAX,tll=DBL_MAX;
      for(int j=g_n-1;j>=g_n-9 && j>=0;j--) { if(g_rates[j].high>thh) thh=g_rates[j].high; if(g_rates[j].low<tll) tll=g_rates[j].low; }
      double tenk=0.5*(thh+tll);
      if(tenk>0) cand=tenk-dir*buffer;
   } else if(mode==19) { // Vector Apex Omni (highest positive floor across engines)
      double m2=mult*((g_bpRegime==1) ? 1.20 : (g_bpRegime==2 ? 0.95 : (g_bpRegime==3 ? 0.75 : 0.70)));
      if(dir*g_bpScore<-10.0) m2*=0.50;
      double cATR=market-dir*MathMax(atr*m2,buffer*2.0);
      double f2=BPFibFrac(r),cFib=f2>0 ? entry+dir*profit*f2 : 0.0;
      double sw=dir>0 ? prevLo : prevHi;
      double cSw=(sw>0 && dir*(sw-entry)>buffer) ? sw-dir*buffer : 0.0;
      double cStep=(r>=1.0) ? entry+dir*risk*(MathFloor(r*2.0)/2.0-0.50) : 0.0;
      cand=cATR;
      if(cFib>0 && dir*(cFib-cand)>0) cand=cFib;
      if(cSw>0 && dir*(cSw-cand)>0) cand=cSw;
      if(cStep>0 && dir*(cStep-cand)>0) cand=cStep;
   } else if(mode==20) { // BasicoBot Peak-Excursion Positive Lock + Momentum-Fade bonus
      double lockPct=30.0+12.0*MathMax(0.0,r-0.8);
      if(CTMomentumFading(dir)) lockPct+=14.0;
      lockPct=MathMax(30.0,MathMin(85.0,lockPct));
      cand=entry+dir*profit*(lockPct/100.0);
   } else if(mode==21) { // VectorVictor Velocity Positive Ratchet
      double vm=mult;
      double alignedVel=dir*g_velocity;
      if(alignedVel>=0.35) vm*=1.20;
      else if(alignedVel<0.0) vm*=0.75;
      cand=market-dir*MathMax(atr*vm,buffer*2.0);
   } else if(mode==22) { // SuperTrend + VWAP Institutional Positive Anchor
      double st=g_superLine>0 ? g_superLine-dir*buffer : 0.0;
      double vw=g_vwap>0 ? g_vwap-dir*buffer : 0.0;
      if(st>0 && dir*(st-entry)>buffer) cand=st;
      if(vw>0 && dir*(vw-entry)>buffer && (cand==0.0 || dir*(vw-cand)>0)) cand=vw;
   } else if(mode==24 || mode==25 || mode==26) { // Adaptive Apex Lock, Giveback Governor, UT Positive Chandelier
      double peak=profit;
      if(bestPrice>0 && dir*(bestPrice-entry)>peak) peak=dir*(bestPrice-entry);
      double pR=peak/risk;
      double startR=MathMax(0.2,XE_GivebackStartR);
      double kMin=MathMax(0.05,MathMin(0.90,XE_GivebackKeepMinPct/100.0));
      double kMax=MathMax(kMin,MathMin(0.95,XE_GivebackKeepMaxPct/100.0));
      double span=MathMax(1.0,5.0-startR);
      double keep=kMin+(kMax-kMin)*MathMin(1.0,MathMax(0.0,(pR-startR)/span));
      double regK=(g_bpRegime==1) ? -0.06 : ((g_bpRegime==3) ? 0.08 : ((g_bpRegime==0) ? 0.05 : 0.0));
      keep=MathMax(kMin,MathMin(0.95,keep+regK));
      double room=MathMax(buffer*2.0,atr*0.25);
      double regM=(g_bpRegime==1) ? 1.20 : ((g_bpRegime==2) ? 0.95 : ((g_bpRegime==3) ? 0.75 : 0.70));
      double momM=(dir*g_velocity<0) ? 0.70 : 1.0;
      if(dir*g_bpScore<-10.0) momM*=0.60;
      double tight=MathMax(0.45,1.0-0.06*MathMin(8.0,pR));
      double ref=(bestPrice>0 && dir*(bestPrice-market)>=0) ? bestPrice : market;
      double cGive=(pR>=startR) ? entry+dir*peak*keep : 0.0;
      if(cGive>0) cGive=dir>0 ? MathMin(cGive,market-room) : MathMax(cGive,market+room);
      double ext=dir>0 ? hi8 : lo8;
      if(mode==25) {
         cand=cGive;
      } else if(mode==26) {
         double vfac=(dir*g_velocity<0) ? 0.70 : 1.0;
         double cCh=(ext>0) ? ext-dir*MathMax(atr*mult*vfac,buffer*2.0) : 0.0;
         double cUt=(utLine>0 && dir*(utLine-entry)>buffer && dir*(market-utLine)>buffer) ? utLine-dir*buffer : 0.0;
         cand=cCh;
         if(cUt>0 && (cand<=0.0 || dir*(cUt-cand)>0)) cand=cUt;
      } else {
         double dist=MathMax(atr*mult*regM*momM*tight,buffer*2.0);
         double cCh=ref-dir*dist;
         double sw=dir>0 ? prevLo : prevHi;
         double cSw=(sw>0 && dir*(sw-entry)>buffer && dir*(market-sw)>buffer) ? sw-dir*buffer : 0.0;
         double cUt=(utLine>0 && dir*(utLine-entry)>buffer && dir*(market-utLine)>buffer) ? utLine-dir*buffer : 0.0;
         cand=cCh;
         if(cGive>0 && dir*(cGive-cand)>0) cand=cGive;
         if(cSw>0 && dir*(cSw-cand)>0) cand=cSw;
         if(cUt>0 && dir*(cUt-cand)>0) cand=cUt;
      }
   } else if(mode==23) { // Vector Apex Omni-Lock (highest positive floor across all engines)
      double m2=mult*((g_bpRegime==1) ? 1.20 : (g_bpRegime==2 ? 0.95 : (g_bpRegime==3 ? 0.75 : 0.70)));
      if(dir*g_velocity<0.0) m2*=0.78;
      if(dir*g_bpScore<-10.0) m2*=0.55;
      double cATR=market-dir*MathMax(atr*m2,buffer*2.0);
      double f2=BPFibFrac(r),cFib=f2>0 ? entry+dir*profit*f2 : 0.0;
      double pkPct=MathMax(30.0,MathMin(85.0,30.0+12.0*MathMax(0.0,r-0.8)+(CTMomentumFading(dir) ? 14.0 : 0.0)));
      double cPk=(r>=0.8) ? entry+dir*profit*(pkPct/100.0) : 0.0;
      double sw=dir>0 ? prevLo : prevHi;
      double cSw=(sw>0 && dir*(sw-entry)>buffer) ? sw-dir*buffer : 0.0;
      double cStep=(r>=1.0) ? entry+dir*risk*(MathFloor(r*2.0)/2.0-0.50) : 0.0;
      cand=cATR;
      if(cFib>0 && dir*(cFib-cand)>0) cand=cFib;
      if(cPk>0 && dir*(cPk-cand)>0) cand=cPk;
      if(cSw>0 && dir*(cSw-cand)>0) cand=cSw;
      if(cStep>0 && dir*(cStep-cand)>0) cand=cStep;
   } else {
      if(mode==2) mult*=(dir*g_velocity>0) ? 1.20 : 0.65;
      else if(mode==6) mult*=(g_bpRegime==1) ? 1.25 : (g_bpRegime==2 ? 1.00 : (g_bpRegime==3 ? 0.85 : 0.75));
      else if(mode==7) mult*=MathMax(0.45,1.0-0.10*r);
      else if(mode==9) mult*=(g_bpVolRatio<0.80) ? 0.70 : ((g_bpVolRatio>1.40) ? 1.30 : 1.0);
      else if(mode==10) mult*=(dir*g_bpScore<-10.0) ? 0.45 : ((dir*g_bpScore<15.0) ? 0.80 : 1.20);
      cand=market-dir*MathMax(atr*mult,buffer*2.0);
   }
   if(cand>0 && dir*(cand-entry)>buffer && (best==0.0 || dir*(cand-best)>0)) best=cand;
   if(best<=0.0) return 0.0;
   if(curSL>0 && dir*(best-curSL)<MathMax(XE_PosStep_MinPts*pt,tick)) return 0.0;
   return SXRoundPrice(best,tick,dir);
}
bool BPModifyTP(SXPosition &position,double tp) {
   if(!CanTrade()) return false;
#ifdef __MQL5__
   if(!PositionSelectByTicket(position.ticket) || PositionGetString(POSITION_SYMBOL)!=g_symbol || PositionGetInteger(POSITION_MAGIC)!=ConsoleMagic) return false;
   if(IsNetting() && (!NettingExclusive() || !PositionSelectByTicket(position.ticket))) return false;
   MqlTradeRequest request={}; bool already=false;
   request.action=TRADE_ACTION_SLTP; request.position=position.ticket; request.symbol=g_symbol; request.magic=(ulong)ConsoleMagic;
   request.sl=PositionGetDouble(POSITION_SL); request.tp=tp;
   return SendRequestStatus(request,"Runner TP #"+StringFormat("%I64u",position.ticket),already);
#else
   if(!OrderSelect((int)position.ticket,SELECT_BY_TICKET,MODE_TRADES) || OrderCloseTime()!=0 || OrderSymbol()!=g_symbol || OrderMagicNumber()!=ConsoleMagic) return false;
   ResetLastError();
   bool ok=OrderModify((int)position.ticket,OrderOpenPrice(),OrderStopLoss(),tp,0,clrNONE);
   if(!ok) Log("TP modify failed: "+IntegerToString(GetLastError()));
   return ok;
#endif
}
void BPManageTP(SXPosition &position,double market,double risk,double tick,double minDistance) {
   if(!g_bpTPOn || risk<=0 || position.tp<=0 || tick<=0) return;
   if(position.direction*(market-position.open)<risk) return;
   if(position.sl<=0 || position.direction*(position.sl-position.open)<=0) return;
   double toTP=position.direction*(position.tp-market);
   if(toTP<0 || toTP>XE_PosTP_NearR*risk) return;
   string key=PositionPartialKey(position.ticket)+"_TP";
   int count=GlobalVariableCheck(key) ? (int)GlobalVariableGet(key) : 0;
   if(count>=6) return;
   double newTP=position.tp+position.direction*XE_PosTP_ExtendR*risk;
   newTP=NormalizeDouble(MathRound(newTP/tick)*tick,g_consoleDigits);
   if(position.direction*(newTP-position.tp)<=tick) return;
   if(position.direction*(newTP-market)<minDistance) return;
   if(BPModifyTP(position,newTP)) { GlobalVariableSet(key,count+1); Log("Positive TP runner extended #"+StringFormat("%I64u",position.ticket)); }
}
bool BPSmartPartial(SXPosition &position,double market,double risk) {
   if(!g_bpPartialOn || risk<=0) return false;
   string key=PositionPartialKey(position.ticket)+"_BP";
   if(GlobalVariableCheck(key)) return false;
   if(position.direction*(market-position.open)<XE_PartialR*risk) return false;
   double minVol=SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN);
   double part=ConsoleNormalizeLots(position.lots*XE_PartialPct/100.0);
   if(part<minVol || position.lots-part<minVol-1e-9) return false;
   if(ClosePosition(position,part)) {
      GlobalVariableSet(key,1.0);
      Log("Smart partial close #"+StringFormat("%I64u",position.ticket));
      return true;
   }
   return false;
}
void BPClosePositions(int mode) {
   ConsoleLoadPositions();
   int n=ArraySize(g_positions); if(n<1) { Log("No owned positions on this symbol"); return; }
   SXPosition copy[]; ArrayResize(copy,n);
   for(int i=0;i<n;i++) copy[i]=g_positions[i];
   int closed=0;
   for(int i=0;i<n;i++) {
      if(mode==1 && copy[i].profit<=0) continue;
      if(mode==2 && copy[i].profit>=0) continue;
      if(ClosePosition(copy[i],copy[i].lots)) closed++;
   }
   Log("Closed "+IntegerToString(closed)+(mode==1 ? " winning" : mode==2 ? " losing" : "")+" position(s)");
}

//--------------------------------------------------------------------
// Cute Android robot art (8 selectable palettes + theme sync)
//--------------------------------------------------------------------
color XELogoBodyColor() {
   if(g_xeLogoPal==1) return C'61,220,132';
   if(g_xeLogoPal==2) return C'0,245,255';
   if(g_xeLogoPal==3) return C'255,204,54';
   if(g_xeLogoPal==4) return C'196,104,255';
   if(g_xeLogoPal==5) return C'255,68,108';
   if(g_xeLogoPal==6) return C'148,224,255';
   if(g_xeLogoPal==7) return C'72,255,198';
   if(g_xeLogoPal==8) return C'255,118,86';
   if(g_xeLogoPal==9) return C'255,126,184';
   if(g_xeLogoPal==10) return C'76,172,255';
   if(g_xeLogoPal==11) return C'186,255,32';
   return SX_GOLD;
}
void BPDome(uint &pixels[],int side,double cx,double cy,double r,color fill,int opacity) {
   int left=(int)MathMax(0,MathFloor(cx-r)),right=(int)MathMin(side-1,MathCeil(cx+r));
   int top=(int)MathMax(0,MathFloor(cy-r)),bottom=(int)MathMin(side-1,MathCeil(cy));
   uint packed=DroidPackARGB(fill,opacity);
   for(int y=top;y<=bottom;y++) {
      double dy=(y+0.5)-cy;
      for(int x=left;x<=right;x++) {
         double dx=(x+0.5)-cx;
         if(dx*dx+dy*dy<=r*r && (y+0.5)<=cy) pixels[y*side+x]=packed;
      }
   }
}
void BPRobotArt(uint &pixels[],int size,int alpha,bool watermark) {
   if(ArrayResize(pixels,size*size)!=size*size) return;
   ArrayInitialize(pixels,0);
   double s=(double)size;
   color body=XELogoBodyColor(),shade=BlendThemeColor(body,SX_BG,38),ring=SX_EDGE,disc=BlendThemeColor(SX_CARD,SX_BG,22);
   color eye=SX_BG,hi=SX_TEXT,cheek=BlendThemeColor(body,SX_RED,52);
   if(!watermark) {
      DroidCircle(pixels,size,0.50*s,0.50*s,0.49*s,ring,alpha);
      DroidCircle(pixels,size,0.50*s,0.50*s,0.46*s,disc,alpha);
   }
   // Twin antennas with glowing tips
   LogoTrace(pixels,size,0.37,0.19,0.28,0.07,0.013,body,alpha);
   LogoTrace(pixels,size,0.63,0.19,0.72,0.07,0.013,body,alpha);
   DroidCircle(pixels,size,0.28*s,0.07*s,0.028*s,hi,alpha);
   DroidCircle(pixels,size,0.72*s,0.07*s,0.028*s,hi,alpha);
   // Cute rounded arms & feet
   DroidRoundRect(pixels,size,0.12*s,0.51*s,0.11*s,0.25*s,0.055*s,body,alpha);
   DroidRoundRect(pixels,size,0.77*s,0.51*s,0.11*s,0.25*s,0.055*s,body,alpha);
   DroidRoundRect(pixels,size,0.33*s,0.76*s,0.13*s,0.16*s,0.055*s,shade,alpha);
   DroidRoundRect(pixels,size,0.54*s,0.76*s,0.13*s,0.16*s,0.055*s,shade,alpha);
   // Torso & Xeon pulse screen
   DroidRoundRect(pixels,size,0.25*s,0.49*s,0.50*s,0.33*s,0.09*s,body,alpha);
   DroidRoundRect(pixels,size,0.33*s,0.55*s,0.34*s,0.19*s,0.05*s,disc,alpha);
   LogoTrace(pixels,size,0.36,0.645,0.43,0.645,0.012,body,alpha);
   LogoTrace(pixels,size,0.43,0.645,0.47,0.58,0.012,body,alpha);
   LogoTrace(pixels,size,0.47,0.58,0.52,0.71,0.012,body,alpha);
   LogoTrace(pixels,size,0.52,0.71,0.56,0.645,0.012,body,alpha);
   LogoTrace(pixels,size,0.56,0.645,0.64,0.645,0.012,body,alpha);
   // Cute dome head, sparkling eyes, rosy cheeks & friendly smile
   BPDome(pixels,size,0.50*s,0.455*s,0.31*s,body,alpha);
   DroidRoundRect(pixels,size,0.20*s,0.452*s,0.60*s,0.026*s,0.013*s,disc,alpha);
   DroidCircle(pixels,size,0.39*s,0.33*s,0.054*s,eye,alpha);
   DroidCircle(pixels,size,0.61*s,0.33*s,0.054*s,eye,alpha);
   DroidCircle(pixels,size,0.405*s,0.315*s,0.018*s,hi,alpha);
   DroidCircle(pixels,size,0.625*s,0.315*s,0.018*s,hi,alpha);
   DroidCircle(pixels,size,0.29*s,0.395*s,0.029*s,cheek,alpha);
   DroidCircle(pixels,size,0.71*s,0.395*s,0.029*s,cheek,alpha);
   LogoTrace(pixels,size,0.45,0.395,0.50,0.420,0.009,eye,alpha);
   LogoTrace(pixels,size,0.50,0.420,0.55,0.395,0.009,eye,alpha);
}
void BPBitmap(string id,string res,int x,int y,int size,int alpha,bool back,bool watermark,string &cache) {
   string obj=g_prefix+"bp_"+id,rsc="::"+g_prefix+res;
   string key=IntegerToString(size)+"|"+IntegerToString(alpha)+"|"+IntegerToString(g_xeLogoPal)+"|"+IntegerToString((int)SX_GOLD)+"|"+IntegerToString((int)SX_BG)+"|"+
              IntegerToString((int)SX_CARD)+"|"+IntegerToString((int)SX_EDGE)+"|"+IntegerToString((int)SX_TEXT)+"|"+IntegerToString((int)SX_RED);
   bool created=ObjectFind(0,obj)<0;
   if(key!=cache || created) {
      uint pixels[];
      BPRobotArt(pixels,size,alpha,watermark);
      if(ArraySize(pixels)!=size*size || !ResourceCreate(rsc,pixels,(uint)size,(uint)size,0,0,(uint)size,COLOR_FORMAT_ARGB_NORMALIZE)) return;
      cache=key;
      if(created && !ObjectCreate(0,obj,OBJ_BITMAP_LABEL,0,0,0)) return;
      ObjectSetString(0,obj,OBJPROP_BMPFILE,0,rsc); ObjectSetString(0,obj,OBJPROP_BMPFILE,1,rsc);
      ObjectSetInteger(0,obj,OBJPROP_CORNER,CORNER_LEFT_UPPER); ObjectSetInteger(0,obj,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
      ObjectSetInteger(0,obj,OBJPROP_BACK,back); ObjectSetInteger(0,obj,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(0,obj,OBJPROP_HIDDEN,true); ObjectSetString(0,obj,OBJPROP_TOOLTIP,"CVT LT DRIOD BOT NO ERRORS");
   }
   ObjectSetInteger(0,obj,OBJPROP_XSIZE,size); ObjectSetInteger(0,obj,OBJPROP_YSIZE,size);
   ObjectSetInteger(0,obj,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,obj,OBJPROP_YDISTANCE,y);
}

//--------------------------------------------------------------------
// Vector Control Deck (5 pages, 16 indicators, 42 interactive controls)
//--------------------------------------------------------------------
double g_bpScale=1.0;
int BPPx(int n) { return (int)MathFloor(n*g_bpScale+0.5); }
void BPPut(string id,ENUM_OBJECT kind,int x,int y,int w,int h,string text,color fg,color bg,color border,int font,bool bold,string tip) {
   string obj=g_prefix+"bp_"+id;
   if(ObjectFind(0,obj)<0 && !ObjectCreate(0,obj,kind,0,0,0)) return;
   ObjectSetInteger(0,obj,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSetInteger(0,obj,OBJPROP_XDISTANCE,g_bpX+BPPx(x)); ObjectSetInteger(0,obj,OBJPROP_YDISTANCE,g_bpY+BPPx(y));
   ObjectSetInteger(0,obj,OBJPROP_BACK,false); ObjectSetInteger(0,obj,OBJPROP_HIDDEN,true); ObjectSetInteger(0,obj,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,obj,OBJPROP_ZORDER,kind==OBJ_BUTTON ? 30 : 0);
   if(kind!=OBJ_LABEL) {
      ObjectSetInteger(0,obj,OBJPROP_XSIZE,(int)MathMax(1,BPPx(w))); ObjectSetInteger(0,obj,OBJPROP_YSIZE,(int)MathMax(1,BPPx(h)));
      ObjectSetInteger(0,obj,OBJPROP_BGCOLOR,bg); ObjectSetInteger(0,obj,OBJPROP_BORDER_COLOR,border);
   }
   if(kind==OBJ_RECTANGLE_LABEL) {
      ObjectSetInteger(0,obj,OBJPROP_BORDER_TYPE,BORDER_FLAT); ObjectSetInteger(0,obj,OBJPROP_COLOR,border);
      ObjectSetString(0,obj,OBJPROP_TOOLTIP,"\n"); return;
   }
   ObjectSetInteger(0,obj,OBJPROP_COLOR,fg);
   ObjectSetInteger(0,obj,OBJPROP_FONTSIZE,(int)MathMax(6,BPPx(font)));
   ObjectSetString(0,obj,OBJPROP_FONT,bold ? "Segoe UI Semibold" : "Segoe UI");
   ObjectSetString(0,obj,OBJPROP_TEXT,text);
   ObjectSetString(0,obj,OBJPROP_TOOLTIP,tip=="" ? text : tip);
   if(kind==OBJ_LABEL) ObjectSetInteger(0,obj,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
   if(kind==OBJ_BUTTON) ObjectSetInteger(0,obj,OBJPROP_STATE,false);
}
void BPRect(string id,int x,int y,int w,int h,color bg,color border) { BPPut(id,OBJ_RECTANGLE_LABEL,x,y,w,h,"",border,bg,border,8,false,""); }
void BPText(string id,int x,int y,string text,color c,int font,bool bold) { BPPut(id,OBJ_LABEL,x,y,0,0,text,c,SX_CARD,SX_CARD,font,bold,""); }
void BPBtn(string id,int x,int y,int w,string text,bool on,string tip) {
   color bg=on ? BlendThemeColor(SX_CARD,SX_GOLD,26) : SX_CARD;
   BPPut("d_b_"+id,OBJ_BUTTON,x,y,w,26,text,on ? SX_GOLD : SX_MUTED,bg,on ? SX_GOLD : SX_EDGE,8,on,tip);
}
void BPChip(string id,int x,int y,int w,int h,string title,string value,color vc) {
   BPRect("d_c_"+id,x,y,w,h,SX_CARD,SX_EDGE);
   BPText("d_ct_"+id,x+6,y+3,title,SX_MUTED,7,false);
   BPText("d_cv_"+id,x+6,y+h/2-1,value,vc,9,true);
}
color BPVoteColor(int v) { return v>0 ? SX_GREEN : (v<0 ? SX_RED : SX_MUTED); }
string BPVoteMark(int v) { return ShortToString((ushort)(v>0 ? 0x25B2 : (v<0 ? 0x25BC : 0x25CF)))+" "; }
string BPBias() { return g_bpScore>=XE_MinConfluence ? "BUY BIAS" : (g_bpScore<=-XE_MinConfluence ? "SELL BIAS" : "NEUTRAL"); }

void BPTabBtn(string id,int x,int w,string text,bool on,string tip) {
   color bg=on ? BlendThemeColor(SX_CARD,SX_GOLD,30) : SX_BG;
   BPPut("d_b_"+id,OBJ_BUTTON,x,172,w,22,text,on ? SX_GOLD : SX_MUTED,bg,on ? SX_GOLD : SX_EDGE,7,on,tip);
}
string BPThemeLabel() {
   return "Theme: "+(g_bpTheme>=0 ? BPThemeName(g_bpTheme)+" ("+IntegerToString(g_bpTheme+1)+"/104)" : "Classic");
}
void BPPaintDeck() {
   int cw=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0),ch=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
   g_bpScale=MathMax(65,MathMin(150,g_bpScalePct))/100.0;
   const int W=344,HF=456,HC=192;
   if(!XE_ShowControlDeck || cw<BPPx(W)+20 || ch<BPPx(HC)+20) { ObjectsDeleteAll(0,g_prefix+"bp_d_"); g_bpLayout=0; return; }
   bool compact=g_bpCollapsed || ch<BPPx(HF)+24;
   int layout=compact ? 100 : 1+g_bpPage;
   if(layout!=g_bpLayout) { ObjectsDeleteAll(0,g_prefix+"bp_d_"); g_bpLayout=layout; }
   int H=compact ? HC : HF;
   int pw=BPPx(W),ph=BPPx(H);
   if(g_xeDeckCustomPos) {
      g_bpX=(int)MathMax(4,MathMin(g_xeDeckX,MathMax(4,cw-pw-4)));
      g_bpY=(int)MathMax(4,MathMin(g_xeDeckY,MathMax(4,ch-ph-4)));
   } else {
      g_bpX=g_right ? 12 : (int)MathMax(4,cw-pw-12);
      g_bpY=(int)MathMax(4,MathMin(XE_DeckY,MathMax(4,ch-ph-4)));
   }
   g_xeDeckW=pw; g_xeDeckH=ph; g_xeDeckHeadH=BPPx(76);
   BPRect("d_frame",0,0,W,H,SX_GOLD,SX_GOLD); BPRect("d_back",1,1,W-2,H-2,SX_BG,SX_BG);
   BPRect("d_mast",2,2,W-4,76,SX_CARD,SX_CARD);
   if(g_bpRobotOn) BPBitmap("d_robot","BPRobot",g_bpX+BPPx(8),g_bpY+BPPx(6),BPPx(68),255,false,false,g_bpRobotKey);
   BPText("d_title",84,8,"CVT LT DRIOD BOT NO ERRORS",SX_GOLD,11,true);
   BPText("d_sub",84,29,"Drag header to move  |  "+IntegerToString(g_bpScalePct)+"%",SX_TEXT,8,false);
#ifdef __MQL5__
   string plat="MT5";
#else
   string plat="MT4";
#endif
   BPText("d_sym",84,50,plat+"  |  "+g_chartSymbol+"  "+ConsoleTFName(g_tf)+"  |  104 Themes",SX_MUTED,8,false);
   BPPut("d_b_dsdec",OBJ_BUTTON,W-94,6,20,20,"-",SX_TEXT,SX_BG,SX_EDGE,9,true,"Shrink Control Deck (-5%)");
   BPPut("d_b_dsinc",OBJ_BUTTON,W-72,6,20,20,"+",SX_TEXT,SX_BG,SX_EDGE,9,true,"Enlarge Control Deck (+5%)");
   BPPut("d_b_drst",OBJ_BUTTON,W-50,6,20,20,"R",SX_GOLD,SX_BG,SX_EDGE,8,true,"Reset all dashboard positions & sizes");
   BPPut("d_b_collapse",OBJ_BUTTON,W-28,6,20,20,compact ? "+" : "_",SX_MUTED,SX_CARD,SX_EDGE,9,false,"Collapse / expand the Control Deck");
   // status chips
   double thr=BPSizeMult(g_bpScore>=0 ? 1 : -1);
   BPChip("st",10,86,104,38,"STATE",UiState(),g_auto ? SX_GREEN : SX_MUTED);
   BPChip("rg",120,86,104,38,"REGIME",g_bpRegimeName[g_bpRegime],g_bpRegime==1 ? SX_GREEN : (g_bpRegime==3 ? SX_RED : SX_GOLD));
   BPChip("th",230,86,104,38,"LOT THROTTLE",StringFormat("x%.2f",thr),thr>=0.99 ? SX_GREEN : (thr>=0.5 ? SX_GOLD : SX_RED));
   // confluence meter
   color sc=g_bpScore>=XE_MinConfluence ? SX_GREEN : (g_bpScore<=-XE_MinConfluence ? SX_RED : SX_GOLD);
   BPText("d_cf",12,130,"CONFLUENCE (16 IND)",SX_MUTED,8,true);
   BPText("d_cfv",202,127,StringFormat("%+.0f",g_bpScore)+"  "+BPBias(),sc,11,true);
   BPRect("d_bar",10,152,324,10,SX_CARD,SX_EDGE);
   int fill=(int)MathMin(161,MathAbs(g_bpScore)*1.61);
   if(g_bpScore>=0) BPRect("d_barf",172,153,(int)MathMax(1,fill),8,sc,sc);
   else BPRect("d_barf",172-(int)MathMax(1,fill),153,(int)MathMax(1,fill),8,sc,sc);
   BPRect("d_barm",171,150,2,14,SX_TEXT,SX_TEXT);
   if(compact) {
      BPText("d_cmp",12,168,"Expand for 16 indicators, 24 trail modes & controls",SX_MUTED,7,false);
      return;
   }
   // page tabs
   string tabNames[6]={"SIGNALS","TRAIL","SMART","ACTIONS","THEME","GUARD"};
   for(int t=0;t<6;t++) BPTabBtn("tab"+IntegerToString(t),10+t*54,52,tabNames[t],g_bpPage==t,"Control Deck page: "+tabNames[t]);
   // open position summary
   int np=ArraySize(g_positions); double pl=0,lockR=-99;
   for(int i=0;i<np;i++) {
      pl+=g_positions[i].profit;
      double rk=InitialRiskPrice(g_positions[i],PositionATR(g_positions[i].ticket,g_atr));
      if(rk>0 && g_positions[i].sl>0) { double r=g_positions[i].direction*(g_positions[i].sl-g_positions[i].open)/rk; if(r>lockR) lockR=r; }
   }
   int xs[3]={10,122,234};
   if(g_bpPage==0) {
      for(int i=0;i<16;i++) {
         int col=i%4,row=i/4;
         BPChip("i"+IntegerToString(i),10+col*82,200+row*44,78,40,g_bpIndName[i],BPVoteMark(g_bpVote[i])+g_bpVal[i],BPVoteColor(g_bpVote[i]));
      }
      BPRect("d_iq",10,378,324,68,SX_CARD,SX_EDGE);
      BPText("d_iqh",18,382,"SMART IQ "+(g_bpIQOn ? "ON" : "OFF")+" (min "+IntegerToString(XE_MinIQScore)+")  |  MTF "+StringFormat("%+.0f",g_xeMTFScore),g_bpIQOn ? SX_GREEN : SX_MUTED,8,true);
      BPText("d_iqv",18,399,"BUY "+IntegerToString(BPIQ(1))+"  /  SELL "+IntegerToString(BPIQ(-1))+"   |   TICK "+(g_xeTickDir>0 ? "UP" : (g_xeTickDir<0 ? "DN" : "FLAT")),SX_TEXT,10,true);
      string mtfLine="MTF:";
      for(int m=0;m<5;m++) mtfLine+=" "+g_xeMTFName[m]+(g_xeMTFVote[m]>0 ? "+" : (g_xeMTFVote[m]<0 ? "-" : "="));
      BPText("d_iqs",18,424,mtfLine+"  |  vol x"+StringFormat("%.2f",g_bpVolRatio)+"  ER "+StringFormat("%.2f",g_bpER),SX_MUTED,8,false);
   } else if(g_bpPage==1) {
      BPRect("d_tr",10,200,324,66,SX_CARD,SX_EDGE);
      BPText("d_trh",18,204,"SMART POSITIVE TRAIL  "+(g_bpTrailOn ? "ON" : "OFF"),g_bpTrailOn ? SX_GREEN : SX_MUTED,8,true);
      BPText("d_trm",18,221,g_bpTrailName[g_bpTrailMode],SX_TEXT,10,true);
      string lockTxt=lockR>-90 ? StringFormat("lock %+.2fR",lockR) : "no position";
      BPText("d_trs",18,242,IntegerToString(np)+" pos  |  P/L "+StringFormat("%+.2f",pl)+"  |  "+lockTxt,lockR>0 ? SX_GREEN : SX_MUTED,8,false);
      BPBtn("ptrail",xs[0],274,100,"POS TRAIL",g_bpTrailOn,"Smart positive trailing stop");
      BPBtn("pmode",xs[1],274,100,"MODE  >",false,"Next positive trailing mode (27 modes)");
      BPBtn("pmodeb",xs[2],274,100,"<  MODE",false,"Previous positive trailing mode");
      BPBtn("tp",xs[0],306,100,"TP RUNNER",g_bpTPOn,"Positive trailing take-profit extension");
      BPBtn("partial",xs[1],306,100,"PARTIAL",g_bpPartialOn,"Smart partial close at trigger R");
      BPBtn("be",xs[2],306,100,"POSITIVE BE",false,"Move eligible stops to positive breakeven");
      BPBtn("basket",xs[0],338,100,"KRONOS BSKT",g_xeBasketOn,"Kronos Positive Basket trailing profit lock");
      BPBtn("lock50",xs[1],338,100,"LOCK +50%",false,"Snap positive SL to lock 50% of open profit");
      BPBtn("qmax",xs[2],338,100,"APEX OMNI",g_bpTrailMode==23,"Switch directly to Vector Apex Omni");
      BPText("d_trn",12,376,"Mode "+IntegerToString(g_bpTrailMode+1)+" of 27  |  positive-only, ratchet-only, broker-stop safe",SX_MUTED,8,false);
      BPText("d_trn2",12,396,"Arms at +"+StringFormat("%.2f",XE_PosBE_TriggerR)+"R  |  min step "+StringFormat("%.0f",XE_PosStep_MinPts)+" pts  |  Basket "+(g_xeBasketArmed ? "ARMED" : "STANDBY"),SX_MUTED,8,false);
      BPText("d_trn3",12,416,"Kronos trigger $"+StringFormat("%.0f",XE_BasketTriggerUSD)+"  |  keep "+StringFormat("%.0f",XE_BasketKeepPct)+"% of peak",SX_MUTED,8,false);
   } else if(g_bpPage==2) {
      BPText("d_sh",12,200,"15 SMART AI FUNCTIONS & GUARDS",SX_MUTED,8,true);
      BPBtn("regime",xs[0],218,100,"REGIME AI",g_bpRegimeOn,"Block entries in High-Vol regime, adaptive trail");
      BPBtn("throttle",xs[1],218,100,"THROTTLE",g_bpThrottleOn,"Equity-curve lot throttle");
      BPBtn("conf",xs[2],218,100,"CONFLUENCE",g_bpConfOn,"Require 16-indicator agreement for entries");
      BPBtn("iq",xs[0],248,100,"SMART IQ",g_bpIQOn,"Weighted 0-100 directional quality gate");
      BPBtn("size",xs[1],248,100,"SMART SIZE",g_bpSizeOn,"Lots follow IQ, regime & streak (reduce-only)");
      BPBtn("exh",xs[2],248,100,"EXHAUST",g_bpExhaustOn,"Do not chase stretched RSI + Bollinger extremes");
      BPBtn("space",xs[0],278,100,"SPACING",g_bpSpaceOn,"Minimum gap after an owned position opens");
      BPBtn("plock",xs[1],278,100,"PROFIT LOCK",g_bpProfitOn,"Stop new entries once daily profit target is met");
      BPBtn("shield",xs[2],278,100,"DD SHIELD",g_bpShieldOn,"Daily drawdown shield");
      BPBtn("tveto",xs[0],308,100,"TICK VETO",g_xeTickVetoOn,"Block entries opposing live tick quote pressure");
      BPBtn("mtfg",xs[1],308,100,"MTF ALIGN",g_xeMTFOn,"Require M5-H4 multi-timeframe alignment");
      BPBtn("streak",xs[2],308,100,"STREAK GRD",g_xeStreakOn,"Pause/throttle after consecutive losses");
      BPBtn("sessai",xs[0],338,100,"SESSION AI",g_xeSessOn,"Smart liquidity session hour filter");
      BPBtn("spatr",xs[1],338,100,"SPREAD/ATR",g_xeSpAtrOn,"Smart spread-to-ATR cost filter");
      BPBtn("sboost",xs[2],338,100,"SMART BOOST",g_xeBoostOn,"Smart profit-curve confidence recovery (<=1.0x)");
      BPText("d_s1",12,374,"IQ min "+IntegerToString(XE_MinIQScore)+"  |  MTF min "+IntegerToString(XE_MinMTFScore)+"  |  Session "+IntegerToString(XE_SessionStartHour)+"-"+IntegerToString(XE_SessionEndHour)+"h",SX_MUTED,8,false);
      BPText("d_s2",12,394,"Day gain "+StringFormat("%+.2f",g_bpDayGain)+"% / "+StringFormat("%.1f",XE_DailyProfitLockPct)+"%  |  Day loss "+StringFormat("%.2f",g_dayLoss)+"%",g_bpDayGain>=XE_DailyProfitLockPct && XE_DailyProfitLockPct>0 ? SX_GOLD : SX_MUTED,8,false);
      BPText("d_s3",12,414,"Lot mult x"+StringFormat("%.2f",thr)+"  |  Spread/ATR cap "+StringFormat("%.0f",XE_MaxSpreadATRPct)+"%  |  Streak "+IntegerToString(g_xeConsecLoss)+"/"+IntegerToString(XE_MaxConsecLosses),SX_MUTED,8,false);
   } else if(g_bpPage==3) {
      BPText("d_ah",12,202,"EXECUTION & POSITION CONTROLS",SX_MUTED,8,true);
      BPBtn("auto",xs[0],220,100,g_auto ? "AUTO  ON" : "AUTO  OFF",g_auto,"Toggle automatic entries");
      BPBtn("buynow",xs[1],220,100,"BUY NOW",false,"Open instant market BUY on chart symbol");
      BPBtn("sellnow",xs[2],220,100,"SELL NOW",false,"Open instant market SELL on chart symbol");
      BPBtn("be",xs[0],252,100,"POSITIVE BE",false,"Move eligible stops to positive breakeven");
      BPBtn("lock50",xs[1],252,100,"LOCK +50%",false,"Lock 50% of open floating profit via positive SL");
      BPBtn("cwin",xs[2],252,100,"CLOSE WIN",false,"Close profitable positions");
      BPBtn("closs",xs[0],284,100,"CLOSE LOSS",false,"Close losing positions");
      BPBtn("call",xs[1],284,100,"CLOSE ALL",false,"Close all owned positions on this symbol");
      BPBtn("panic",xs[2],284,100,"PANIC EXIT",false,"Press twice: stop auto and exit whole portfolio");
      BPText("d_a1",12,326,IntegerToString(np)+" owned position(s)   |   P/L "+StringFormat("%+.2f",pl),pl>=0 ? SX_GREEN : SX_RED,10,true);
      BPText("d_a2",12,350,"Kronos Basket Peak: $"+StringFormat("%.2f",g_xeBasketPeak)+"   |   Status: "+(g_xeBasketArmed ? "ARMED" : "STANDBY"),SX_MUTED,8,false);
      BPText("d_a3",12,372,"PANIC EXIT: press twice within five seconds",SX_MUTED,8,false);
      BPText("d_a4",12,394,"Broker trade comments: strictly blank (stealth)",SX_MUTED,8,false);
   } else if(g_bpPage==5) {
      string gs=XEGuardStatus();
      BPText("d_gh",12,200,"PORTFOLIO GUARD  |  ENTRY STATUS: "+gs,gs=="CLEAR" ? SX_GREEN : SX_GOLD,8,true);
      BPBtn("eqtrail",xs[0],218,100,"EQUITY TRAIL",g_xeEqTrailOn,"Trailing equity lock: block entries after giving back the day's peak gain");
      BPBtn("expo",xs[1],218,100,"CCY STACK",g_xeExpoOn,"Currency stack cap across all symbols (correlated exposure)");
      BPBtn("margin",xs[2],218,100,"MARGIN GRD",g_xeMarginOn,"Block new entries while margin level is low");
      BPBtn("timebe",xs[0],248,100,"STALE BE",g_xeTimeBEOn,"Stale-trade breakeven: lock a small profit on trades that stall");
      BPBtn("volsl",xs[1],248,100,"VOL SL/TP",g_xeVolSLOn,"Volatility-adaptive initial SL (TP follows R)");
      BPBtn("eqreset",xs[2],248,100,"EQ UNLOCK",false,"Clear today's trailing equity lock");
      double gainNow=g_dayEquity>0 ? 100.0*(ConsoleEquity()-g_dayEquity)/g_dayEquity : 0.0;
      double ml=AccountInfoDouble(ACCOUNT_MARGIN)>0 ? AccountInfoDouble(ACCOUNT_MARGIN_LEVEL) : 0.0;
      BPText("d_g1",12,288,"Equity trail: day "+StringFormat("%+.2f",gainNow)+"%  peak "+StringFormat("%+.2f",g_xeEqPeakGain)+"%  arm "+StringFormat("%.1f",XE_EqTrailArmPct)+"%  "+(g_xeEqLocked ? "LOCKED" : "OPEN"),g_xeEqLocked ? SX_RED : SX_TEXT,8,false);
      BPText("d_g2",12,308,"Exposure: "+IntegerToString(g_xeOwnedTotal)+"/"+IntegerToString(InpMaxPortfolioPositions)+" pos  |  top "+g_xeTopCcy+" "+StringFormat("%+d",g_xeTopStack)+" / "+(XE_MaxCurrencyStack>0 ? IntegerToString(XE_MaxCurrencyStack) : "off"),SX_TEXT,8,false);
      BPText("d_g3",12,328,"Margin level: "+(ml>0 ? StringFormat("%.0f",ml)+"%" : "no margin used")+"  |  min "+StringFormat("%.0f",XE_MinMarginLevelPct)+"%",ml>0 && ml<XE_MinMarginLevelPct ? SX_RED : SX_TEXT,8,false);
      BPText("d_g4",12,348,"Stale BE: "+IntegerToString(XE_TimeBEBars)+" bars, +"+StringFormat("%.2f",XE_TimeBEMinR)+"R -> lock +"+StringFormat("%.2f",XE_TimeBELockR)+"R  |  moves "+IntegerToString(g_xeTimeBECount),SX_TEXT,8,false);
      BPText("d_g5",12,368,"Adaptive SL x"+StringFormat("%.2f",g_xeVolSLOn ? XEVolSLMult() : 1.0)+"  (clamp "+StringFormat("%.2f",XE_VolAdaptMinMult)+"-"+StringFormat("%.2f",XE_VolAdaptMaxMult)+")  vol x"+StringFormat("%.2f",g_bpVolRatio),SX_TEXT,8,false);
      BPText("d_g6",12,392,"Emergency X-X, PANIC EXIT and CLOSE ALL always close",SX_GREEN,8,false);
      BPText("d_g7",12,410,"No martingale / grid added  |  guards only block entries",SX_MUTED,8,false);
   } else {
      BPText("d_thn",12,202,BPThemeLabel(),SX_GOLD,9,true);
      color sw[9]; sw[0]=SX_BG; sw[1]=SX_CARD; sw[2]=SX_EDGE; sw[3]=SX_TEXT; sw[4]=SX_MUTED; sw[5]=SX_GOLD; sw[6]=SX_BLUE; sw[7]=SX_GREEN; sw[8]=SX_RED;
      for(int i=0;i<9;i++) BPRect("d_sw"+IntegerToString(i),10+i*36,224,32,18,sw[i],SX_EDGE);
      BPBtn("thprev",xs[0],250,100,"<  THEME",false,"Previous Vector colour theme");
      BPBtn("thnext",xs[1],250,100,"THEME  >",false,"Next Vector colour theme");
      BPBtn("trand",xs[2],250,100,"RANDOM",false,"Random Vector colour theme");
      BPBtn("thjb",xs[0],282,100,"<<  8",false,"Jump back eight themes");
      BPBtn("thjf",xs[1],282,100,"8  >>",false,"Jump forward eight themes");
      BPBtn("logoclr",xs[2],282,100,"LOGO CLR",false,"Cycle cute Android robot logo colour palette");
      BPBtn("wm",xs[0],314,100,"ROBOT MARK",g_bpWM,"Toggle chart Android robot watermark");
      BPBtn("logo",xs[1],314,100,"ROBOT LOGO",g_bpRobotOn,"Toggle Android robot logo on dashboard");
      BPBtn("dsize",xs[2],314,100,"SIZE "+IntegerToString(g_bpScalePct)+"%",false,"Cycle Control Deck scale (70-130%)");
      BPText("d_tn",12,354,"88 Vector Colour Themes  |  Logo: "+g_xeLogoName[g_xeLogoPal],SX_MUTED,8,false);
      BPText("d_tn2",12,374,"88 curated dark, cyber, luxury & day themes + 694 classic",SX_MUTED,8,false);
   }
}
void BPChartText(string id,int x,int y,string text,color c,int font,bool bold) {
   string obj=g_prefix+"bp_"+id;
   if(ObjectFind(0,obj)<0 && !ObjectCreate(0,obj,OBJ_LABEL,0,0,0)) return;
   ObjectSetInteger(0,obj,OBJPROP_CORNER,CORNER_LEFT_UPPER); ObjectSetInteger(0,obj,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
   ObjectSetInteger(0,obj,OBJPROP_XDISTANCE,x); ObjectSetInteger(0,obj,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,obj,OBJPROP_COLOR,c); ObjectSetInteger(0,obj,OBJPROP_FONTSIZE,font);
   ObjectSetInteger(0,obj,OBJPROP_HIDDEN,true); ObjectSetInteger(0,obj,OBJPROP_SELECTABLE,false);
   ObjectSetString(0,obj,OBJPROP_FONT,bold ? "Segoe UI Semibold" : "Segoe UI"); ObjectSetString(0,obj,OBJPROP_TEXT,text);
}
void BPPaintChart() {
   int cw=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0),ch=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
   if(XE_ChartWatermark && g_bpWM && g_bpRobotOn && cw>260 && ch>200) {
      int sz=(int)MathMax(64,MathMin(XE_WatermarkPixels,MathMin(cw*0.4,ch*0.5)));
      BPBitmap("c_wm","BPRobotW",(cw-sz)/2,(ch-sz)/2,sz,36,true,true,g_bpWMKey);
   } else ObjectDelete(0,g_prefix+"bp_c_wm");
   string tag=g_prefix+"bp_c_tag";
   if(ObjectFind(0,tag)<0) ObjectCreate(0,tag,OBJ_LABEL,0,0,0);
   color sc=g_bpScore>=XE_MinConfluence ? SX_GREEN : (g_bpScore<=-XE_MinConfluence ? SX_RED : SX_GOLD);
   ObjectSetInteger(0,tag,OBJPROP_CORNER,CORNER_LEFT_UPPER); ObjectSetInteger(0,tag,OBJPROP_ANCHOR,ANCHOR_UPPER);
   ObjectSetInteger(0,tag,OBJPROP_XDISTANCE,cw/2); ObjectSetInteger(0,tag,OBJPROP_YDISTANCE,8);
   ObjectSetInteger(0,tag,OBJPROP_COLOR,sc); ObjectSetInteger(0,tag,OBJPROP_FONTSIZE,9);
   ObjectSetInteger(0,tag,OBJPROP_HIDDEN,true); ObjectSetInteger(0,tag,OBJPROP_SELECTABLE,false);
   ObjectSetString(0,tag,OBJPROP_FONT,"Segoe UI Semibold");
   ObjectSetString(0,tag,OBJPROP_TEXT,"CVT LT DRIOD BOT NO ERRORS EA  |  "+g_bpRegimeName[g_bpRegime]+"  |  CONF "+StringFormat("%+.0f",g_bpScore)+" "+BPBias()+"  |  IQ "+IntegerToString(BPIQ(1))+"/"+IntegerToString(BPIQ(-1))+"  |  MTF "+StringFormat("%+.0f",g_xeMTFScore)+"  |  TRAIL "+(g_bpTrailOn ? g_bpTrailName[g_bpTrailMode] : "OFF"));
   // cute android robot badge, bottom right of chart
   if(g_bpRobotOn && cw>720 && ch>320) {
      BPBitmap("c_badge","BPRobotB",cw-310,ch-64,38,255,false,false,g_bpBadgeKey);
      BPChartText("c_b1",cw-264,ch-62,"CVT LT DRIOD BOT NO ERRORS",SX_GOLD,9,true);
      BPChartText("c_b2",cw-264,ch-44,g_bpRegimeName[g_bpRegime]+"  |  IQ "+IntegerToString(BPIQ(g_bpScore>=0 ? 1 : -1))+"  |  lots x"+StringFormat("%.2f",BPSizeMult(g_bpScore>=0 ? 1 : -1)),SX_MUTED,8,false);
   } else { ObjectDelete(0,g_prefix+"bp_c_badge"); ObjectDelete(0,g_prefix+"bp_c_b1"); ObjectDelete(0,g_prefix+"bp_c_b2"); }
   // positive lock line
   string lk=g_prefix+"bp_c_lock";
   double lockSL=0; int lockDir=0;
   if(g_symbol==g_chartSymbol) for(int i=0;i<ArraySize(g_positions);i++)
      if(g_positions[i].sl>0 && g_positions[i].direction*(g_positions[i].sl-g_positions[i].open)>0) { lockSL=g_positions[i].sl; lockDir=g_positions[i].direction; break; }
   if(lockSL>0) {
      if(ObjectFind(0,lk)<0) ObjectCreate(0,lk,OBJ_HLINE,0,0,lockSL);
      ObjectSetDouble(0,lk,OBJPROP_PRICE,lockSL); ObjectSetInteger(0,lk,OBJPROP_COLOR,SX_GREEN);
      ObjectSetInteger(0,lk,OBJPROP_STYLE,STYLE_DASHDOT); ObjectSetInteger(0,lk,OBJPROP_WIDTH,1);
      ObjectSetInteger(0,lk,OBJPROP_HIDDEN,true); ObjectSetInteger(0,lk,OBJPROP_SELECTABLE,false);
      ObjectSetString(0,lk,OBJPROP_TOOLTIP,lockDir>0 ? "CVT LT DRIOD BOT NO ERRORS Positive SL Lock (long)" : "CVT LT DRIOD BOT NO ERRORS Positive SL Lock (short)");
   } else ObjectDelete(0,lk);
}
void BPPaintAll() {
   BPPaintDeck();
   BPPaintChart();
   ChartRedraw(0);
}
void BPApplyThemeNow() {
   ApplyTheme(g_consoleTheme,g_themeStyle); ClearUI(); RefreshLayers();
   g_bpRobotKey=""; g_bpWMKey=""; g_bpBadgeKey="";
   Log("Theme: "+BPThemeName(g_bpTheme));
}
void BPHandleClick(string action) {
   ObjectSetInteger(0,g_prefix+"bp_d_b_"+action,OBJPROP_STATE,false);
   if(action=="collapse") { g_bpCollapsed=!g_bpCollapsed; }
   else if(StringLen(action)==4 && StringFind(action,"tab")==0) {
      int page=(int)StringToInteger(StringSubstr(action,3,1));
      if(page>=0 && page<6) g_bpPage=page;
   }
   else if(action=="auto") { g_auto=!g_auto; Log("Automatic entries "+Yes(g_auto)); }
   else if(action=="buynow" || action=="sellnow") {
      if(!g_consoleReady) BuildSnapshot();
      g_bpManualTrade=true;
      OpenPosition(action=="buynow" ? 1 : -1,true);
      g_bpManualTrade=false;
   }
   else if(action=="ptrail") { g_bpTrailOn=!g_bpTrailOn; Log("Smart positive trailing "+Yes(g_bpTrailOn)); }
   else if(action=="pmode") { g_bpTrailMode=(g_bpTrailMode+1)%27; Log("Positive trail mode: "+g_bpTrailName[g_bpTrailMode]); }
   else if(action=="pmodeb") { g_bpTrailMode=(g_bpTrailMode+26)%27; Log("Positive trail mode: "+g_bpTrailName[g_bpTrailMode]); }
   else if(action=="qmax") { g_bpTrailMode=23; g_bpTrailOn=true; Log("Positive trail mode: Vector Apex Omni"); }
   else if(action=="basket") { g_xeBasketOn=!g_xeBasketOn; Log("Kronos Positive Basket "+Yes(g_xeBasketOn)); }
   else if(action=="lock50") { XELockProfitHalf(); }
   else if(action=="regime") { g_bpRegimeOn=!g_bpRegimeOn; Log("Regime AI "+Yes(g_bpRegimeOn)); }
   else if(action=="throttle") { g_bpThrottleOn=!g_bpThrottleOn; Log("Equity throttle "+Yes(g_bpThrottleOn)); }
   else if(action=="conf") { g_bpConfOn=!g_bpConfOn; Log("Confluence gate "+Yes(g_bpConfOn)); }
   else if(action=="iq") { g_bpIQOn=!g_bpIQOn; Log("Smart IQ gate "+Yes(g_bpIQOn)); }
   else if(action=="size") { g_bpSizeOn=!g_bpSizeOn; Log("Smart sizing "+Yes(g_bpSizeOn)); }
   else if(action=="exh") { g_bpExhaustOn=!g_bpExhaustOn; Log("Exhaustion guard "+Yes(g_bpExhaustOn)); }
   else if(action=="space") { g_bpSpaceOn=!g_bpSpaceOn; Log("Entry spacing guard "+Yes(g_bpSpaceOn)); }
   else if(action=="plock") { g_bpProfitOn=!g_bpProfitOn; Log("Daily profit lock "+Yes(g_bpProfitOn)); }
   else if(action=="tveto") { g_xeTickVetoOn=!g_xeTickVetoOn; Log("Tick quote-pressure veto "+Yes(g_xeTickVetoOn)); }
   else if(action=="mtfg") { g_xeMTFOn=!g_xeMTFOn; Log("MTF alignment gate "+Yes(g_xeMTFOn)); }
   else if(action=="streak") { g_xeStreakOn=!g_xeStreakOn; Log("Consecutive-loss streak guard "+Yes(g_xeStreakOn)); }
   else if(action=="sessai") { g_xeSessOn=!g_xeSessOn; Log("Smart Session AI "+Yes(g_xeSessOn)); }
   else if(action=="spatr") { g_xeSpAtrOn=!g_xeSpAtrOn; Log("Smart Spread/ATR cost filter "+Yes(g_xeSpAtrOn)); }
   else if(action=="eqtrail") { g_xeEqTrailOn=!g_xeEqTrailOn; Log("Trailing equity lock "+Yes(g_xeEqTrailOn)); }
   else if(action=="expo") { g_xeExpoOn=!g_xeExpoOn; Log("Currency stack cap "+Yes(g_xeExpoOn)); }
   else if(action=="margin") { g_xeMarginOn=!g_xeMarginOn; Log("Margin-level guard "+Yes(g_xeMarginOn)); }
   else if(action=="timebe") { g_xeTimeBEOn=!g_xeTimeBEOn; Log("Stale-trade breakeven "+Yes(g_xeTimeBEOn)); }
   else if(action=="volsl") { g_xeVolSLOn=!g_xeVolSLOn; Log("Volatility-adaptive SL/TP "+Yes(g_xeVolSLOn)); }
   else if(action=="eqreset") { g_xeEqLocked=false; g_xeEqFired=false; g_xeEqPeakGain=0; WriteGuard("xeeqlk",0); WriteGuard("xeeqpk",0); Log("Trailing equity lock cleared for today"); }
   else if(action=="sboost") { g_xeBoostOn=!g_xeBoostOn; Log("Smart Profit-Curve Boost "+Yes(g_xeBoostOn)); }
   else if(action=="tp") { g_bpTPOn=!g_bpTPOn; Log("Positive TP runner "+Yes(g_bpTPOn)); }
   else if(action=="partial") { g_bpPartialOn=!g_bpPartialOn; Log("Smart partial close "+Yes(g_bpPartialOn)); }
   else if(action=="shield") { g_bpShieldOn=!g_bpShieldOn; Log("Drawdown shield "+Yes(g_bpShieldOn)); }
   else if(action=="wm") { g_bpWM=!g_bpWM; Log("Robot watermark "+Yes(g_bpWM)); }
   else if(action=="logo") { g_bpRobotOn=!g_bpRobotOn; ObjectDelete(0,g_prefix+"bp_d_robot"); g_bpRobotKey=""; }
   else if(action=="logoclr") { g_xeLogoPal=(g_xeLogoPal+1)%12; g_bpRobotKey=""; g_bpWMKey=""; g_bpBadgeKey=""; Log("Robot logo palette: "+g_xeLogoName[g_xeLogoPal]); }
   else if(action=="dsdec") {
      g_bpScalePct=(int)MathMax(65,g_bpScalePct-5); GlobalVariableSet(g_prefix+"xe_ds",g_bpScalePct);
      g_bpLayout=-1; g_bpRobotKey=""; Log("Control Deck scale "+IntegerToString(g_bpScalePct)+"%");
   }
   else if(action=="dsinc") {
      g_bpScalePct=(int)MathMin(150,g_bpScalePct+5); GlobalVariableSet(g_prefix+"xe_ds",g_bpScalePct);
      g_bpLayout=-1; g_bpRobotKey=""; Log("Control Deck scale "+IntegerToString(g_bpScalePct)+"%");
   }
   else if(action=="drst") { XEResetAllDashboards(); }
   else if(action=="dsize") {
      int sizes[6]={70,85,100,115,130,145},next=sizes[0];
      for(int i=0;i<6;i++) if(sizes[i]>g_bpScalePct) { next=sizes[i]; break; }
      g_bpScalePct=next; GlobalVariableSet(g_prefix+"xe_ds",g_bpScalePct);
      g_bpLayout=-1; g_bpRobotKey=""; Log("Control Deck size "+IntegerToString(g_bpScalePct)+"%");
   }
   else if(action=="thprev" || action=="thnext" || action=="thjb" || action=="thjf") {
      int step=action=="thnext" ? 1 : (action=="thprev" ? 103 : (action=="thjf" ? 8 : 96));
      if(g_bpTheme<0) g_bpTheme=0;
      g_bpTheme=(g_bpTheme+step)%104;
      BPApplyThemeNow();
   }
   else if(action=="trand") {
      int pick=(int)(GetTickCount()%104);
      if(pick==g_bpTheme) pick=(pick+11)%104;
      g_bpTheme=pick; BPApplyThemeNow();
   }
   else if(action=="be") ApplyPositiveBE();
   else if(action=="cwin") BPClosePositions(1);
   else if(action=="closs") BPClosePositions(2);
   else if(action=="call") BPClosePositions(0);
   else if(action=="panic") {
      if(g_bpPanicArmed==0 || TimeCurrent()>g_bpPanicArmed) { g_bpPanicArmed=TimeCurrent()+5; Log("Press PANIC EXIT again within five seconds"); }
      else { g_auto=false; RequestPortfolioExit("CVT LT DRIOD BOT NO ERRORS panic exit"); g_bpPanicArmed=0; }
   }
   SaveAsset(); GlobalVariablesFlush(); PaintPanel(); BPPaintAll();
}
void XEResetAllDashboards() {
   g_xeMainCustomPos=false; g_xeDeckCustomPos=false;
   g_xeMainX=InpPanelX; g_xeMainY=InpPanelY;
   g_xeDeckX=XE_DeckX; g_xeDeckY=XE_DeckY;
   g_xeMainScalePct=(int)MathMax(65,MathMin(150,XE_MainScalePct));
   g_bpScalePct=(int)MathMax(65,MathMin(150,XE_DeckScalePct));
   GlobalVariableDel(g_prefix+"xe_mx"); GlobalVariableDel(g_prefix+"xe_my"); GlobalVariableDel(g_prefix+"xe_ms");
   GlobalVariableDel(g_prefix+"xe_dx"); GlobalVariableDel(g_prefix+"xe_dy"); GlobalVariableDel(g_prefix+"xe_ds");
   g_bpLayout=-1; g_bpRobotKey=""; ClearUI();
   Log("All dashboards reset to default positions & scales");
}
void XEHandleMouseMove(int mx,int my,uint flags) {
   if(!XE_EnableDragMove) return;
   bool down=((flags & 1)!=0);
   if(down && !g_xePrevMouseDown) {
      // Check Control Deck header first (higher z-order)
      if(XE_ShowControlDeck && g_bpLayout!=0 && mx>=g_bpX && mx<=g_bpX+g_xeDeckW-BPPx(98) && my>=g_bpY && my<=g_bpY+g_xeDeckHeadH) {
         g_xeDragTarget=2; g_xeDragOffX=mx-g_bpX; g_xeDragOffY=my-g_bpY;
         g_xeSavedScroll=(bool)ChartGetInteger(0,CHART_MOUSE_SCROLL);
         ChartSetInteger(0,CHART_MOUSE_SCROLL,false);
      } else if(ConsoleShowDashboard && mx>=g_x && mx<=g_x+g_xeMainW-Px(100) && my>=g_y && my<=g_y+g_xeMainHeadH) {
         g_xeDragTarget=1; g_xeDragOffX=mx-g_x; g_xeDragOffY=my-g_y;
         g_xeSavedScroll=(bool)ChartGetInteger(0,CHART_MOUSE_SCROLL);
         ChartSetInteger(0,CHART_MOUSE_SCROLL,false);
      }
   } else if(down && g_xeDragTarget!=0) {
      int cw=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0),ch=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
      if(g_xeDragTarget==2) {
         int nx=(int)MathMax(4,MathMin(mx-g_xeDragOffX,MathMax(4,cw-g_xeDeckW-4)));
         int ny=(int)MathMax(4,MathMin(my-g_xeDragOffY,MathMax(4,ch-g_xeDeckH-4)));
         if(MathAbs(nx-g_xeDeckX)>=2 || MathAbs(ny-g_xeDeckY)>=2) {
            g_xeDeckX=nx; g_xeDeckY=ny; g_xeDeckCustomPos=true;
            BPPaintDeck(); ChartRedraw(0);
         }
      } else if(g_xeDragTarget==1) {
         int nx=(int)MathMax(4,MathMin(mx-g_xeDragOffX,MathMax(4,cw-g_xeMainW-4)));
         int ny=(int)MathMax(4,MathMin(my-g_xeDragOffY,MathMax(4,ch-g_xeMainH-4)));
         if(MathAbs(nx-g_xeMainX)>=2 || MathAbs(ny-g_xeMainY)>=2) {
            g_xeMainX=nx; g_xeMainY=ny; g_xeMainCustomPos=true;
            PaintPanel(); ChartRedraw(0);
         }
      }
   } else if(!down && g_xeDragTarget!=0) {
      if(g_xeDragTarget==2) { GlobalVariableSet(g_prefix+"xe_dx",g_xeDeckX); GlobalVariableSet(g_prefix+"xe_dy",g_xeDeckY); }
      else if(g_xeDragTarget==1) { GlobalVariableSet(g_prefix+"xe_mx",g_xeMainX); GlobalVariableSet(g_prefix+"xe_my",g_xeMainY); }
      g_xeDragTarget=0;
      ChartSetInteger(0,CHART_MOUSE_SCROLL,g_xeSavedScroll);
   }
   g_xePrevMouseDown=down;
}


bool vectorInitialized=false;
int OnInit() {
   if(!MQLInfoInteger(MQL_TESTER) && !PrideEnableRealAccounts && AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_REAL) {
      Print("CVT LT DRIOD BOT NO ERRORS EA | Real-account use is disabled. Use a demo account or Strategy Tester.");
      return INIT_FAILED;
   }
   if(PrideCI<=0 || PrideCI>100 || PrideRetreat<=0 || PrideRetreat>5 || PrideKeep<0.30 ||
      PrideKeep>0.95 || PrideMaxSpreadATR<0 || PrideMaxSpreadATR>1) return INIT_PARAMETERS_INCORRECT;
   if(PridePathBars<3 || PridePathBars>100 || PrideTrendFloor<=0 || PrideTrendFloor>=1 ||
      PrideMaxDelaySeconds<0 || InpUTMAPeriod<1 || InpUTMAPeriod>400) return INIT_PARAMETERS_INCORRECT;
   if(ApexGate<=0 || ApexGate>=1 || ApexRate<=0 || ApexRate>=1 || ApexRetain<=0 || ApexRetain>=1 || VectorArmR<=0 || VectorCostTicks<0 || VectorStepTicks<1 || MathAbs(VectorServerUTCMinutes)>840) return INIT_PARAMETERS_INCORRECT;
   int result=InpWorkspace==VECTOR_CHART ? ChartOnInit() : ConsoleOnInit();
   vectorInitialized=(result==INIT_SUCCEEDED);
   return result;
}
void OnDeinit(const int reason) {
   if(!vectorInitialized) return;
   if(InpWorkspace==VECTOR_CHART) ChartOnDeinit(reason); else ConsoleOnDeinit(reason);
   vectorInitialized=false;
}
void OnTick() { if(InpWorkspace==VECTOR_CHART) ChartOnTick(); else ConsoleOnTick(); }
void OnTimer() { if(InpWorkspace==VECTOR_CHART) ChartOnTimer(); else ConsoleOnTimer(); }
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam) {
   if(InpWorkspace==VECTOR_CHART) ChartOnChartEvent(id,lparam,dparam,sparam);
   else ConsoleOnChartEvent(id,lparam,dparam,sparam);
}
