﻿//+------------------------------------------------------------------+
//|                                           MidasHawkEA.mq5 |
//|  Recreation of Midas Hawk Breakout & Tick-BE Scalper       |
//|  Built on EarnForex MT5-EA-Template + smizxe/mt5-agent-toolkit   |
//+------------------------------------------------------------------+
#property copyright     "EarnForex Template + smizxe/mt5-agent-toolkit Integration"
#property link          "https://github.com/EarnForex/MT5-Expert-Advisor-Template"
#property version       "1.00"
#property description   "Midas Hawk Gold Breakout Strategy: Multi-TF H1/H4 Liquidity Breakout Bracket"
#property description   "with Stale Order Expiration and Tick-by-Tick Profit Locking Break-Even."
#property icon          "\\Files\\EF-Icon-64x64px.ico"

#include <Trade\Trade.mqh>

//--- Inlined Error Handling Helper (100% Standalone - No external .mqh required)
string GetLastErrorText(int Error)
  {
   switch(Error)
     {
      case ERR_SUCCESS:                     return("The operation completed successfully");
      case ERR_INTERNAL_ERROR:              return("Unexpected internal error");
      case ERR_WRONG_INTERNAL_PARAMETER:    return("Wrong parameter in inner call");
      case ERR_INVALID_PARAMETER:           return("Invalid parameter");
      case ERR_NOT_ENOUGH_MEMORY:           return("Not enough memory");
      case ERR_STRUCT_WITHOBJECTS_ORCLASS:  return("Structure contains objects/classes");
      case ERR_INVALID_ARRAY:               return("Invalid array");
      case ERR_ARRAY_RESIZE_ERROR:          return("Array resize error");
      case ERR_STRING_RESIZE_ERROR:         return("String resize error");
      case ERR_INVALID_DATETIME:            return("Invalid datetime");
      case ERR_ARRAY_BAD_SIZE:              return("Array bad size");
      case ERR_INVALID_POINTER:             return("Invalid pointer");
      case ERR_INVALID_POINTER_TYPE:        return("Invalid pointer type");
      case ERR_FUNCTION_NOT_ALLOWED:        return("Function not allowed");
      case ERR_CHART_NOT_FOUND:             return("Chart not found");
      case ERR_CHART_NO_EXPERT:             return("No expert in chart");
      case ERR_MARKET_UNKNOWN_SYMBOL:       return("Unknown symbol");
      case ERR_MARKET_NOT_SELECTED:         return("Symbol not selected in MarketWatch");
      case ERR_HISTORY_NOT_FOUND:           return("History not found");
      case ERR_TRADE_DISABLED:              return("Trading by Expert Advisors prohibited");
      case ERR_TRADE_POSITION_NOT_FOUND:    return("Position not found");
      case ERR_TRADE_ORDER_NOT_FOUND:       return("Order not found");
      case ERR_TRADE_DEAL_NOT_FOUND:        return("Deal not found");
      case ERR_TRADE_SEND_FAILED:           return("Trade request sending failed");
      case ERR_TRADE_CALC_FAILED:           return("Failed to calculate profit or margin");
      case ERR_INDICATOR_CANNOT_CREATE:     return("Indicator cannot be created");
      case ERR_INDICATOR_WRONG_HANDLE:      return("Wrong indicator handle");
      default:                              return(StringFormat("Error code %d", Error));
     }
  }

//--- EarnForex Template Enumerations
enum ENUM_RISK_BASE
  {
   RISK_BASE_EQUITY     = 1, // EQUITY
   RISK_BASE_BALANCE    = 2, // BALANCE
   RISK_BASE_FREEMARGIN = 3  // FREE MARGIN
  };

enum ENUM_RISK_DEFAULT_SIZE
  {
   RISK_DEFAULT_FIXED = 1, // FIXED SIZE
   RISK_DEFAULT_AUTO  = 2  // AUTOMATIC SIZE BASED ON RISK
  };

enum ENUM_MODE_SL
  {
   SL_FIXED = 0, // FIXED STOP LOSS
   SL_AUTO  = 1  // ATR STOP LOSS
  };

enum ENUM_MODE_TP
  {
   TP_FIXED = 0, // FIXED TAKE PROFIT
   TP_AUTO  = 1  // ATR TAKE PROFIT (R:R)
  };

#define DIAG_GATE_COUNT 8

//+------------------------------------------------------------------+
//| EA Parameters (EarnForex Groups + Gold Beaver Reverse-Engineered)|
//+------------------------------------------------------------------+
input string Comment_0 = "====================  STRATEGY  ======================";
input ENUM_TIMEFRAMES InpRangeTimeframe     = PERIOD_H1;        // Range / Level Timeframe (H1/H4)
input int             InpRangeLookbackBars  = 24;               // Lookback Bars for Range High/Low
input int             InpBreakoutBufferPts  = 30;               // Order Distance Beyond Range High/Low (points)
input int             InpOrderExpiryMinutes = 240;              // Pending Order Lifetime (minutes)
input bool            InpStaleSweep         = true;             // Cancel Pending Orders On New Bar / Opp Signal

input string Comment_be = "====================  BREAK-EVEN LOCK  ================";
input bool            InpBeOnTick           = true;             // Enable Real-Time Tick-by-Tick Break-Even Check
input double          InpBETriggerATR       = 0.40;             // Profit Distance to Trigger BE (x ATR14)
input double          InpBELockProfitPts    = 60;               // Profit Points to Lock Past Entry (e.g. +60 pts = +$0.60/oz)

input string Comment_risk = "====================  LOT & RISK  ======================";
input ENUM_RISK_DEFAULT_SIZE RiskDefaultSize = RISK_DEFAULT_AUTO;// Position Size Mode
input double          InpFixedLot           = 0.01;             // Fixed / Fallback Lot Size
input double          Inp_Lot_Percent       = 1.0;              // Percentage to Risk Each Trade (%)
input double          MinLotSize            = 0.01;             // Minimum Lot Allowed
input double          MaxLotSize            = 100.0;            // Maximum Lot Allowed
input int             MaxPositions          = 2;                // Max Simultaneous Open Positions
input int             InpMaxSpreadPoints    = 300;              // Max Allowed Spread in Points
input int             InpMaxTradesPerDay    = 6;                // Max Entries Per Server Day (0 = unlimited)
input int             InpLossLockoutMin     = 15;               // Stand-Down After Loss (minutes, 0 = off)
input double          InpMaxMarginPct       = 20.0;             // Max Free Margin Per Trade (%, 0 = no cap)

input string Comment_sl = "====================  PROTECTION  ======================";
input ENUM_MODE_SL    StopLossMode          = SL_AUTO;          // Stop-Loss Mode
input int             ATRPeriod             = 14;               // ATR Period
input ENUM_TIMEFRAMES ATRTimeFrame          = PERIOD_CURRENT;   // ATR Timeframe
input double          ATRMultiplierSL       = 2.0;              // ATR Multiplier for Stop-Loss
input double          InpMinStopATR         = 0.03;             // Min Stop Floor vs Daily ATR(14)
input int             DefaultStopLoss       = 400;              // Fixed Stop-Loss (points, 0 = none)
input ENUM_MODE_TP    TakeProfitMode        = TP_AUTO;          // Take-Profit Mode
input double          ATRMultiplierTP       = 3.0;              // ATR Multiplier for Take-Profit
input double          InpMinRewardRisk      = 1.2;              // Min Reward-to-Risk Ratio
input int             DefaultTakeProfit     = 800;              // Fixed Take-Profit (points, 0 = none)

input string Comment_prop = "====================  PROP FIRM GUARD  ================";
input double          InpPropDailyLoss      = 0.0;              // Max Daily Loss % (0 = disabled)
input double          InpPropMaxLoss        = 0.0;              // Max Account Loss % (0 = disabled)
input bool            InpPropCloseAll       = true;             // Emergency Close All Positions If Hit

input string Comment_other = "====================  OTHER  ==========================";
input long            InpBaseMagic          = 20260910;         // Magic Number
input string          OrderNote             = "MidasHawk";// Comment for Orders
input int             Slippage              = 20;               // Slippage Deviation Points

//+------------------------------------------------------------------+
//| Global EA Objects & State                                        |
//+------------------------------------------------------------------+
CTrade   Trade;
int      ATRHandle   = INVALID_HANDLE;
int      ATRD1Handle = INVALID_HANDLE;
double   ATR_current = 0.0, ATR_previous = 0.0, ATR_D1 = 0.0;
datetime g_lastBarTime = 0;
bool     g_isHedging   = false;
double   g_dayStartBalance = 0.0;

// Diagnostics
long   g_diag[DIAG_GATE_COUNT];
string g_diagName[DIAG_GATE_COUNT] =
  {
   "connection / autotrading blocked",
   "spread above MaxSpread",
   "prop firm guard stop",
   "max positions / daily cap / loss lockout",
   "no breakout setup / range too small",
   "stop too tight / min stop rail",
   "order placement rejected",
   "be modification error"
  };

// Forward Declarations
bool Prechecks();
bool InitializeHandles();
void SetTradeObject();
bool GetATRData();
void ProcessTick();
void ManageBreakEven();
void CheckBracketSetup();
void CancelStalePendingOrders();
bool CheckPropFirmLimits();
double ComputeValidatedSL(const ENUM_ORDER_TYPE orderType, const double openPrice, const double rangeExtremum);
double ComputeValidatedTP(const ENUM_ORDER_TYPE orderType, const double openPrice, const double slPrice);
double LotSize(const double stopLoss, const double openPrice);
double NormalizeLot(double lot);
double CapLotByMargin(double lot, const ENUM_ORDER_TYPE type, const double price);
double NormalizePrice(const double price);
int    CountPositions();
int    CountPendingOrders();
int    CountMyEntriesToday();
bool   IsInLossLockout();
void   CloseAllPositions();
void   LogBrokerCapabilities();
ENUM_ORDER_TYPE_FILLING PickFillingMode();
string RetcodeText(const uint retcode);
void   PrintDiagnostics();

//+------------------------------------------------------------------+
//| Expert Initialization & Deinitialization                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!Prechecks()) return(INIT_PARAMETERS_INCORRECT);
   if(!InitializeHandles())
     {
      PrintFormat("Error initializing handles - %s - %d", GetLastErrorText(GetLastError()), GetLastError());
      return(INIT_FAILED);
     }

   g_lastBarTime     = 0;
   g_dayStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
   ArrayInitialize(g_diag, 0);

   g_isHedging = (AccountInfoInteger(ACCOUNT_MARGIN_MODE) == ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);
   SetTradeObject();
   LogBrokerCapabilities();

   PrintFormat("%s started on %s %s. Range TF: %s, Magic: %d.",
               OrderNote, _Symbol, EnumToString(_Period), EnumToString(InpRangeTimeframe), InpBaseMagic);
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   if(ATRHandle   != INVALID_HANDLE) { IndicatorRelease(ATRHandle);   ATRHandle   = INVALID_HANDLE; }
   if(ATRD1Handle != INVALID_HANDLE) { IndicatorRelease(ATRD1Handle); ATRD1Handle = INVALID_HANDLE; }
   PrintDiagnostics();
  }

void OnTick()
  {
   ProcessTick();
  }

double OnTester()
  {
   double netProfit       = TesterStatistics(STAT_PROFIT);
   double initialDeposit  = TesterStatistics(STAT_INITIAL_DEPOSIT);
   double maxDrawDownPerc = TesterStatistics(STAT_EQUITYDD_PERCENT);
   double totalTrades     = TesterStatistics(STAT_TRADES);
   if(initialDeposit == 0.0) return(0.0);
   if(totalTrades == 0.0)    return(-100.0);
   if(totalTrades > 0.0 && maxDrawDownPerc == 0.0) maxDrawDownPerc = 0.01;

   double netProfitPerc = netProfit / initialDeposit * 100.0;
   double res = 0.0;
   if(netProfitPerc > 0.0) res = netProfitPerc / maxDrawDownPerc;
   if(netProfitPerc < 0.0) res = netProfitPerc;
   return(res);
  }

//+------------------------------------------------------------------+
//| Main Processing Loop                                             |
//+------------------------------------------------------------------+
void ProcessTick()
  {
   if(!TerminalInfoInteger(TERMINAL_CONNECTED) ||
      !MQLInfoInteger(MQL_TRADE_ALLOWED) ||
      !AccountInfoInteger(ACCOUNT_TRADE_EXPERT))
      return;

   // 1. Prop Firm Daily & Overall Equity Limits
   if(!CheckPropFirmLimits()) return;

   // 2. Real-Time Tick-by-Tick Break-Even Locking (The Gold Beaver Secret)
   if(InpBeOnTick && CountPositions() > 0 && GetATRData())
      ManageBreakEven();

   // 3. Evaluate Breakout Pending Orders on closed bar
   datetime curBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(curBarTime == 0 || curBarTime == g_lastBarTime)
      return;

   if(!GetATRData()) return;
   g_lastBarTime = curBarTime;

   if(InpStaleSweep)
      CancelStalePendingOrders();

   if(CountPositions() + CountPendingOrders() < MaxPositions)
      CheckBracketSetup();
  }

//+------------------------------------------------------------------+
//| Tick Break-Even Management                                       |
//+------------------------------------------------------------------+
void ManageBreakEven()
  {
   long   stopsLevel  = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   long   freezeLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL);
   double minDist     = MathMax(stopsLevel, freezeLevel + 1) * _Point;
   double triggerDist = ATR_previous * InpBETriggerATR;
   double lockProfit  = InpBELockProfitPts * _Point;

   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      if(InpBaseMagic != 0 && PositionGetInteger(POSITION_MAGIC) != InpBaseMagic) continue;

      long   type   = PositionGetInteger(POSITION_TYPE);
      double openP  = PositionGetDouble(POSITION_PRICE_OPEN);
      double curP   = PositionGetDouble(POSITION_PRICE_CURRENT);
      double curSL  = PositionGetDouble(POSITION_SL);
      double tp     = PositionGetDouble(POSITION_TP);

      if(type == POSITION_TYPE_BUY)
        {
         // Once price is up by triggerDist, lock SL to entry + lockProfit
         if(curP - openP >= triggerDist)
           {
            double targetSL = NormalizePrice(openP + lockProfit);
            if((curSL == 0.0 || targetSL > curSL + _Point) && (curP - targetSL >= minDist))
              {
               Trade.PositionModify(ticket, targetSL, tp);
              }
           }
        }
      else if(type == POSITION_TYPE_SELL)
        {
         if(openP - curP >= triggerDist)
           {
            double targetSL = NormalizePrice(openP - lockProfit);
            if((curSL == 0.0 || targetSL < curSL - _Point) && (targetSL - curP >= minDist))
              {
               Trade.PositionModify(ticket, targetSL, tp);
              }
           }
        }
     }
  }

//+------------------------------------------------------------------+
//| Check Range & Place Pending Breakout Stop Orders                 |
//+------------------------------------------------------------------+
void CheckBracketSetup()
  {
   if(SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) > InpMaxSpreadPoints)
     { g_diag[1]++; return; }
   if(CountPositions() >= MaxPositions ||
      (InpMaxTradesPerDay > 0 && CountMyEntriesToday() >= InpMaxTradesPerDay) ||
      IsInLossLockout())
     { g_diag[3]++; return; }

   // Calculate Higher Timeframe (H1/H4) Range High and Low
   MqlRates rangeRates[];
   ArraySetAsSeries(rangeRates, true);
   int copied = CopyRates(_Symbol, InpRangeTimeframe, 1, InpRangeLookbackBars, rangeRates);
   if(copied < InpRangeLookbackBars)
     { g_diag[4]++; return; }

   double rangeHigh = rangeRates[0].high;
   double rangeLow  = rangeRates[0].low;
   for(int i = 1; i < copied; i++)
     {
      if(rangeRates[i].high > rangeHigh) rangeHigh = rangeRates[i].high;
      if(rangeRates[i].low  < rangeLow)  rangeLow  = rangeRates[i].low;
     }

   double rangeSpan = rangeHigh - rangeLow;
   if(rangeSpan <= ATR_previous * 0.5)
     { g_diag[4]++; return; } // range too tight / dead market

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   if(ask <= 0.0 || bid <= 0.0) return;

   double bufPts = InpBreakoutBufferPts * _Point;
   double buyStopPrice  = NormalizePrice(rangeHigh + bufPts);
   double sellStopPrice = NormalizePrice(rangeLow  - bufPts);

   long   stopsLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   double brokerMin  = (stopsLevel + 2) * _Point;

   datetime expiry = (InpOrderExpiryMinutes > 0)
                   ? (datetime)(TimeCurrent() + (long)InpOrderExpiryMinutes * 60)
                   : 0;

   // 1. Place Buy Stop if market is comfortably below rangeHigh
   if(buyStopPrice - ask >= brokerMin && CountPendingOrders() == 0)
     {
      double sl = ComputeValidatedSL(ORDER_TYPE_BUY, buyStopPrice, rangeLow);
      double tp = ComputeValidatedTP(ORDER_TYPE_BUY, buyStopPrice, sl);
      double lot = LotSize(sl, buyStopPrice);
      lot = CapLotByMargin(lot, ORDER_TYPE_BUY, buyStopPrice);

      if(lot > 0.0 && sl > 0.0 && tp > 0.0)
        {
         Trade.BuyStop(lot, buyStopPrice, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, expiry, OrderNote);
        }
     }

   // 2. Place Sell Stop if market is comfortably above rangeLow
   if(bid - sellStopPrice >= brokerMin && CountPendingOrders() <= 1)
     {
      double sl = ComputeValidatedSL(ORDER_TYPE_SELL, sellStopPrice, rangeHigh);
      double tp = ComputeValidatedTP(ORDER_TYPE_SELL, sellStopPrice, sl);
      double lot = LotSize(sl, sellStopPrice);
      lot = CapLotByMargin(lot, ORDER_TYPE_SELL, sellStopPrice);

      if(lot > 0.0 && sl > 0.0 && tp > 0.0)
        {
         Trade.SellStop(lot, sellStopPrice, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, expiry, OrderNote);
        }
     }
  }

//+------------------------------------------------------------------+
//| Stale Order Cleanup                                              |
//+------------------------------------------------------------------+
void CancelStalePendingOrders()
  {
   for(int i = OrdersTotal() - 1; i >= 0; i--)
     {
      ulong ticket = OrderGetTicket(i);
      if(ticket == 0) continue;
      if(OrderGetString(ORDER_SYMBOL) != _Symbol) continue;
      if(InpBaseMagic != 0 && OrderGetInteger(ORDER_MAGIC) != InpBaseMagic) continue;

      ENUM_ORDER_TYPE type = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE);
      if(type == ORDER_TYPE_BUY_STOP || type == ORDER_TYPE_SELL_STOP)
        {
         datetime setupTime = (datetime)OrderGetInteger(ORDER_TIME_SETUP);
         if(InpOrderExpiryMinutes > 0 && TimeCurrent() - setupTime > InpOrderExpiryMinutes * 60)
            Trade.OrderDelete(ticket);
        }
     }
  }

//+------------------------------------------------------------------+
//| Prop Firm Loss Guard                                             |
//+------------------------------------------------------------------+
bool CheckPropFirmLimits()
  {
   double balance = AccountInfoDouble(ACCOUNT_BALANCE);
   double equity  = AccountInfoDouble(ACCOUNT_EQUITY);

   // Check Max Account Loss
   if(InpPropMaxLoss > 0.0)
     {
      double lossPct = (10000.0 - equity) / 10000.0 * 100.0;
      if(lossPct >= InpPropMaxLoss)
        {
         g_diag[2]++;
         if(InpPropCloseAll) CloseAllPositions();
         return(false);
        }
     }

   // Reset daily anchor at midnight
   MqlDateTime dt;
   TimeToStruct(TimeCurrent(), dt);
   if(dt.hour == 0 && dt.min == 0)
      g_dayStartBalance = balance;

   // Check Daily Loss
   if(InpPropDailyLoss > 0.0 && g_dayStartBalance > 0.0)
     {
      double dailyLossPct = (g_dayStartBalance - equity) / g_dayStartBalance * 100.0;
      if(dailyLossPct >= InpPropDailyLoss)
        {
         g_diag[2]++;
         if(InpPropCloseAll) CloseAllPositions();
         return(false);
        }
     }
   return(true);
  }

//+------------------------------------------------------------------+
//| Stop Loss & Take Profit Validation                               |
//+------------------------------------------------------------------+
double ComputeValidatedSL(const ENUM_ORDER_TYPE orderType, const double openPrice, const double rangeExtremum)
  {
   long   stopsLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   double brokerMin  = (stopsLevel + 2) * _Point;
   double railMin    = MathMax(InpMinStopATR * ATR_D1, brokerMin);

   if(StopLossMode == SL_FIXED)
     {
      if(DefaultStopLoss <= 0) return(0.0);
      double dist = MathMax(DefaultStopLoss * _Point, railMin);
      return(NormalizePrice(orderType == ORDER_TYPE_BUY ? openPrice - dist : openPrice + dist));
     }

   // Structure-based stop beyond range extreme, fallback to ATR
   double dist = MathMax(MathAbs(openPrice - rangeExtremum), ATR_previous * ATRMultiplierSL);
   if(dist < railMin) dist = railMin;

   return(NormalizePrice(orderType == ORDER_TYPE_BUY ? openPrice - dist : openPrice + dist));
  }

double ComputeValidatedTP(const ENUM_ORDER_TYPE orderType, const double openPrice, const double slPrice)
  {
   long   stopsLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   double brokerMin  = (stopsLevel + 2) * _Point;
   int    dir        = (orderType == ORDER_TYPE_BUY) ? 1 : -1;

   if(TakeProfitMode == TP_FIXED)
     {
      if(DefaultTakeProfit <= 0) return(0.0);
      double dist = MathMax(DefaultTakeProfit * _Point, brokerMin);
      return(NormalizePrice(openPrice + dir * dist));
     }

   double riskDist = MathAbs(openPrice - slPrice);
   double dist     = MathMax(riskDist * ATRMultiplierTP, brokerMin);
   if(riskDist > 0.0 && (dist / riskDist) + 1e-6 < InpMinRewardRisk)
      dist = riskDist * InpMinRewardRisk;

   return(NormalizePrice(openPrice + dir * dist));
  }

//+------------------------------------------------------------------+
//| Sizing, Normalization & Accounting Rails                         |
//+------------------------------------------------------------------+
double LotSize(const double stopLoss, const double openPrice)
  {
   double size = InpFixedLot;
   if(RiskDefaultSize == RISK_DEFAULT_AUTO)
     {
      double dist = MathAbs(openPrice - stopLoss);
      if(stopLoss > 0.0 && dist > 0.0)
        {
         double balance = AccountInfoDouble(ACCOUNT_BALANCE);
         double tickVal = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
         double tickSz  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
         if(tickVal <= 0.0 || tickSz <= 0.0) return(0.0);

         double lossPerLot = (dist / tickSz) * tickVal;
         if(lossPerLot <= 0.0) return(0.0);

         size = (balance * Inp_Lot_Percent / 100.0) / lossPerLot;
        }
     }
   return(NormalizeLot(size));
  }

double NormalizeLot(double lot)
  {
   double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double minLot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   if(lotStep <= 0.0) return(0.0);

   lot = MathFloor(lot / lotStep) * lotStep;
   if(lot > MaxLotSize) lot = MaxLotSize;
   if(lot > maxLot)     lot = maxLot;
   if(lot < MinLotSize || lot < minLot) return(0.0);
   return(NormalizeDouble(lot, 2));
  }

double CapLotByMargin(double lot, const ENUM_ORDER_TYPE type, const double price)
  {
   if(lot <= 0.0 || InpMaxMarginPct <= 0.0) return(lot);
   double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
   double allowed    = freeMargin * InpMaxMarginPct / 100.0;
   double needed     = 0.0;
   if(!OrderCalcMargin(type, _Symbol, lot, price, needed) || needed <= 0.0) return(lot);
   if(needed <= allowed) return(lot);

   return(NormalizeLot(lot * allowed / needed));
  }

double NormalizePrice(const double price)
  {
   double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   if(tickSize <= 0.0) return(NormalizeDouble(price, _Digits));
   return(NormalizeDouble(MathRound(price / tickSize) * tickSize, _Digits));
  }

int CountPositions()
  {
   int count = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      if(InpBaseMagic != 0 && PositionGetInteger(POSITION_MAGIC) != InpBaseMagic) continue;
      count++;
     }
   return(count);
  }

int CountPendingOrders()
  {
   int count = 0;
   for(int i = OrdersTotal() - 1; i >= 0; i--)
     {
      ulong ticket = OrderGetTicket(i);
      if(ticket == 0) continue;
      if(OrderGetString(ORDER_SYMBOL) != _Symbol) continue;
      if(InpBaseMagic != 0 && OrderGetInteger(ORDER_MAGIC) != InpBaseMagic) continue;
      count++;
     }
   return(count);
  }

int CountMyEntriesToday()
  {
   MqlDateTime now;
   TimeToStruct(TimeCurrent(), now);
   now.hour = 0; now.min = 0; now.sec = 0;
   datetime dayStart = StructToTime(now);
   if(!HistorySelect(dayStart, TimeCurrent())) return(0);

   int count = 0;
   int total = HistoryDealsTotal();
   for(int i = 0; i < total; i++)
     {
      ulong ticket = HistoryDealGetTicket(i);
      if(ticket == 0) continue;
      if(InpBaseMagic != 0 && HistoryDealGetInteger(ticket, DEAL_MAGIC) != InpBaseMagic) continue;
      if(HistoryDealGetString(ticket, DEAL_SYMBOL) != _Symbol) continue;
      if(HistoryDealGetInteger(ticket, DEAL_ENTRY) == DEAL_ENTRY_IN) count++;
     }
   return(count);
  }

bool IsInLossLockout()
  {
   if(InpLossLockoutMin <= 0) return(false);
   datetime from = (datetime)(TimeCurrent() - (long)InpLossLockoutMin * 60);
   if(!HistorySelect(from, TimeCurrent())) return(false);

   int total = HistoryDealsTotal();
   for(int i = total - 1; i >= 0; i--)
     {
      ulong ticket = HistoryDealGetTicket(i);
      if(ticket == 0) continue;
      if(InpBaseMagic != 0 && HistoryDealGetInteger(ticket, DEAL_MAGIC) != InpBaseMagic) continue;
      if(HistoryDealGetString(ticket, DEAL_SYMBOL) != _Symbol) continue;
      if(HistoryDealGetInteger(ticket, DEAL_ENTRY) != DEAL_ENTRY_OUT) continue;

      double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT)
                    + HistoryDealGetDouble(ticket, DEAL_SWAP)
                    + HistoryDealGetDouble(ticket, DEAL_COMMISSION);
      if(profit < 0.0) return(true);
     }
   return(false);
  }

void CloseAllPositions()
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      if(InpBaseMagic != 0 && PositionGetInteger(POSITION_MAGIC) != InpBaseMagic) continue;
      Trade.PositionClose(ticket, Slippage);
     }
  }

bool Prechecks()
  {
   if(MaxLotSize < MinLotSize || MinLotSize <= 0.0) return(false);
   if(InpBreakoutBufferPts < 0 || InpRangeLookbackBars < 2) return(false);
   return(true);
  }

bool InitializeHandles()
  {
   ATRHandle = iATR(_Symbol, ATRTimeFrame, ATRPeriod);
   if(ATRHandle == INVALID_HANDLE) return(false);

   ATRD1Handle = iATR(_Symbol, PERIOD_D1, 14);
   if(ATRD1Handle == INVALID_HANDLE) return(false);

   return(true);
  }

void SetTradeObject()
  {
   Trade.SetExpertMagicNumber(InpBaseMagic);
   Trade.SetTypeFilling(PickFillingMode());
   Trade.SetDeviationInPoints(Slippage);
  }

bool GetATRData()
  {
   double buf[2], d1Buf[2];
   if(CopyBuffer(ATRHandle, 0, 0, 2, buf) < 2) return(false);
   if(buf[0] == EMPTY_VALUE || buf[1] == EMPTY_VALUE) return(false);
   ATR_current  = buf[1];
   ATR_previous = buf[0];

   if(CopyBuffer(ATRD1Handle, 0, 0, 2, d1Buf) >= 2 && d1Buf[0] != EMPTY_VALUE)
      ATR_D1 = d1Buf[0];
   else
      ATR_D1 = ATR_previous;
   return(true);
  }

void LogBrokerCapabilities()
  {
   long fillFlags = SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE);
   PrintFormat("Broker rails: %s | Digits=%d | Point=%f | Filling=0x%X",
               _Symbol, _Digits, _Point, (uint)fillFlags);
  }

ENUM_ORDER_TYPE_FILLING PickFillingMode()
  {
   long mode = SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE);
   if((mode & SYMBOL_FILLING_FOK) != 0) return(ORDER_FILLING_FOK);
   if((mode & SYMBOL_FILLING_IOC) != 0) return(ORDER_FILLING_IOC);
   return(ORDER_FILLING_RETURN);
  }

string RetcodeText(const uint retcode)
  {
   switch(retcode)
     {
      case TRADE_RETCODE_DONE:           return("Done");
      case TRADE_RETCODE_DONE_PARTIAL:   return("Done Partial");
      case TRADE_RETCODE_REJECT:         return("Rejected");
      case TRADE_RETCODE_REQUOTE:        return("Requote");
      case TRADE_RETCODE_PRICE_OFF:      return("Off Quotes");
      case TRADE_RETCODE_INVALID_STOPS:  return("Invalid Stops");
      case TRADE_RETCODE_NO_MONEY:       return("No Money");
      default:                           return(StringFormat("Retcode %u", retcode));
     }
  }

void PrintDiagnostics()
  {
   long total = 0;
   for(int i = 0; i < DIAG_GATE_COUNT; i++) total += g_diag[i];
   if(total == 0) return;

   Print("--- MidasHawkEA signal gate refusals ---");
   for(int i = 0; i < DIAG_GATE_COUNT; i++)
      if(g_diag[i] > 0)
         PrintFormat("  %-38s %8d  %5.1f%%", g_diagName[i], (int)g_diag[i], 100.0 * g_diag[i] / total);
  }
//+------------------------------------------------------------------+

