//+------------------------------------------------------------------+ //| Candle_Pressure_Gold_Silver_EA.mq5 | //| Candlestick pressure + market context trading system | //| Target instruments: XAU (gold) and XAG (silver) | //+------------------------------------------------------------------+ #property copyright "Candle Pressure EA - refactored from Quantum Gold & Silver Trader" #property link "https://forge.mql5.io" #property version "1.00" #property description "Reads candlestick pressure (body, wick, close position) and only acts when price sits in a valid context:" #property description "higher timeframe pressure, break of structure, premium/discount, liquidity sweep, order block or fair value gap." #property description "Hard equity rules: 5 percent daily loss cap, 8 percent static drawdown cap from balance, 10 percent equity growth target." #include //+------------------------------------------------------------------+ //| Inputs | //+------------------------------------------------------------------+ input group "=== Identity ===" input long InpMagicNumber = 20261102; // Magic number input string InpTradeComment = "CandlePressure"; // Order comment input bool InpShowDashboard = true; // Show on-chart status input group "=== Timeframes and bias ===" input ENUM_TIMEFRAMES InpWorkTimeframe = PERIOD_M30; // Signal timeframe input ENUM_TIMEFRAMES InpHtfTimeframe = PERIOD_H4; // Higher timeframe for bias input int InpHtfEmaPeriod = 50; // Higher timeframe EMA period input bool InpRequireHtfBias = true; // Require higher timeframe alignment input group "=== Candle pressure ===" input double InpRejectionWickRatio = 0.55; // Rejection: minimum wick share of range input double InpRejectionMaxBody = 0.35; // Rejection: maximum body share of range input double InpRejectionClosePos = 0.60; // Rejection: required close position in range input double InpDominantBodyRatio = 0.60; // Dominant body share of range input group "=== Market context ===" input bool InpRequireBos = false; // Require break of structure input int InpSwingLookback = 12; // Swing reference lookback (bars) input int InpBosConfirmBars = 2; // Bars allowed to print the break input bool InpRequireDiscountPremium = true; // Discount for buys, premium for sells input int InpRangeLookback = 60; // Dealing range lookback (bars) input double InpEquilibriumTolerance = 0.05; // Equilibrium tolerance (share of range) input bool InpRequireLiquiditySweep = false; // Require a liquidity sweep input int InpSweepLookback = 6; // Sweep detection window (bars) input int InpSweepDepth = 20; // Swing depth used as sweep reference input bool InpRequireZoneTouch = true; // Require order block or FVG touch input int InpZoneLookback = 30; // Zone search lookback (bars) input double InpZoneToleranceATR = 0.35; // Zone tolerance in ATR input double InpDisplacementATR = 1.10; // Displacement body in ATR (order blocks) input group "=== Signal quality ===" input double InpMinSignalScore = 0.50; // Minimum signal score (0.10 - 1.00) input int InpMinBarsBetweenTrades = 2; // Minimum bars between entries input bool InpUseAdxFilter = true; // Use ADX trend-strength filter input int InpAdxPeriod = 14; // ADX period input double InpAdxMinLevel = 18.0; // Minimum ADX value input int InpAtrPeriod = 14; // ATR period input group "=== Position sizing ===" input double InpRiskPercentMin = 0.50; // Minimum risk per trade (% of balance) input double InpRiskPercentMax = 1.20; // Maximum risk per trade (% of balance) input int InpMaxOpenPositions = 1; // Maximum simultaneous positions input double InpStopAtrMultiplier = 1.60; // Minimum stop distance in ATR input double InpStopBufferATR = 0.20; // Stop buffer beyond candle extreme (ATR) input double InpRewardRiskRatio = 2.50; // Reward to risk ratio input double InpMaxSpreadPoints = 80.0; // Maximum allowed spread (points) input bool InpAllowMinLotOverride = false; // Allow the broker minimum volume even when it exceeds the risk budget input double InpMaxLotAbsolute = 5.00; // Hard cap on volume per order in lots (0 = disabled) input group "=== Hard equity limits ===" input double InpDailyMaxLossPercent = 5.0; // Daily maximum loss (% of day-start equity) input double InpStaticMaxDdPercent = 8.0; // Static maximum drawdown (% of initial balance) input double InpEquityGrowthTargetPct = 10.0; // Equity growth target (% of initial balance) input bool InpCloseOnDailyLimit = true; // Close positions when daily limit is hit input bool InpCloseOnStaticDd = true; // Close positions when static limit is hit input bool InpStopEaOnStaticDd = false; // Detach the EA after the static limit (not recommended: it disables the month) input bool InpCloseOnTarget = true; // Close positions when growth target is reached input bool InpResetRiskState = false; // One-shot: authorise risk period provisioning (never implicit) input bool InpTesterPersistState = false; // Keep risk state across Strategy Tester runs (breaks run isolation) input group "=== Risk state identity ===" input string InpRiskScopeId = "MAIN"; // Risk scope id: the account level risk ledger input string InpRiskPeriodId = "P01"; // Risk period id: change only with explicit authorisation input group "=== Trade management ===" input bool InpUseBreakeven = false; // Enable breakeven input double InpBreakevenTriggerATR = 1.00; // Breakeven trigger distance in ATR input double InpBreakevenOffsetPts = 20.0; // Breakeven offset in points input bool InpUseAtrTrailing = false; // Enable ATR trailing stop input double InpTrailAtrMultiplier = 2.00; // Trailing distance in ATR input double InpTrailStepPoints = 50.0; // Minimum trailing step (points) input group "=== Instrument profiles ===" input bool InpUseGoldProfile = true; // Use gold profile on XAU symbols input double InpGoldStopAtrMult = 1.60; // Gold: stop distance in ATR input double InpGoldRewardRisk = 2.50; // Gold: reward to risk ratio input int InpGoldRangeLookback = 60; // Gold: dealing range lookback (bars) input bool InpUseSilverProfile = true; // Use silver profile on XAG symbols input double InpSilverStopAtrMult = 2.20; // Silver: stop distance in ATR input double InpSilverRewardRisk = 2.50; // Silver: reward to risk ratio input int InpSilverRangeLookback = 70; // Silver: dealing range lookback (bars) //+------------------------------------------------------------------+ //| Data structures | //+------------------------------------------------------------------+ struct SCandle { datetime time; double open; double high; double low; double close; double range; double body; double upperWick; double lowerWick; double bodyRatio; double upperWickRatio; double lowerWickRatio; double closePosition; // 0.0 = close at low, 1.0 = close at high bool bullish; bool valid; }; //+------------------------------------------------------------------+ //| Global state | //+------------------------------------------------------------------+ CTrade g_trade; int g_htfEmaHandle = INVALID_HANDLE; int g_atrHandle = INVALID_HANDLE; int g_adxHandle = INVALID_HANDLE; // Effective parameters after the instrument profile is resolved double g_stopAtrMultiplier = 1.60; double g_rewardRiskRatio = 2.00; int g_rangeLookback = 60; int g_historyBars = 200; bool g_isGold = false; bool g_isSilver = false; // Symbol geometry int g_digits = 2; double g_point = 0.01; double g_tickSize = 0.01; double g_volumeMin = 0.01; double g_volumeMax = 100.0; double g_volumeStep = 0.01; int g_stopsLevel = 0; int g_freezeLevel = 0; //+------------------------------------------------------------------+ //| Persistent risk state (R-01 v1.2) | //| The FILE_COMMON archive is authoritative. Global Variables are a | //| cache/coordination mirror only, because the terminal expires | //| unused global variables after four weeks. Losing or corrupting | //| the archive is a hard stop, never a licence to rebuild a baseline.| //| | //| R01-H3: the archive is stored in two slots (A and B). A write | //| always targets the slot that does NOT hold the newest valid | //| record, so the last good archive is never sacrificed. | //| R01-H8: recovery reads both slots, keeps the highest valid | //| sequence and resolves ties deterministically towards slot A. | //| The struct holds no strings so it stays a POD for FileWriteStruct.| //+------------------------------------------------------------------+ #define CP_STATE_MAGIC 0x43504753 #define CP_STATE_VERSION 103 #define CP_SLOT_A 0 #define CP_SLOT_B 1 #define CP_REC_NONE 0 // no recoverable archive for this identity #define CP_REC_RESTORED 1 // highest valid slot restored #define CP_REC_MISMATCH 2 // archive exists but belongs to another identity //+------------------------------------------------------------------+ //| Persistent provisioning acknowledgement (R-01 v1.2) | //| The marker is the local proof that the one-shot provisioning | //| authorization of ONE risk period was consumed. Its identity is | //| login|server|risk_scope_id|risk_period_id, so it survives a | //| symbol, magic or timeframe change and it is never removed by | //| archive recovery. It freezes the initial baseline, so an | //| interrupted provisioning resumes from that snapshot instead of | //| re-baselining on the live balance. | //| Documented limit: deleting the marker AND both archive slots | //| destroys every piece of local evidence. A local store cannot | //| detect that and must not claim to. | //+------------------------------------------------------------------+ #define CP_PROV_MAGIC 0x43505052 // 'CPPR' marker schema marker #define CP_PROV_VERSION 100 #define CP_PSTAT_NONE 0 #define CP_PSTAT_PROVISIONING 1 // authorization consumed, provisioning unfinished #define CP_PSTAT_PROVISIONED 2 // archives verified, provisioning complete #define CP_MARK_NONE 0 // no marker file for this risk period #define CP_MARK_PROVISIONING 1 #define CP_MARK_PROVISIONED 2 #define CP_MARK_CORRUPT 3 #define CP_INIT_RESTORED 0 #define CP_INIT_PROVISIONED 1 #define CP_INIT_DENIED 2 #define CP_INIT_FAILED 3 struct SProvisionMarker { uint magic; // schema marker uint version; // marker schema version ulong identity; // login|server|scope|period long login; ulong server_hash; ulong scope_hash; ulong period_hash; ulong prov_id; // unique provisioning identifier int status; // CP_PSTAT_PROVISIONING / CP_PSTAT_PROVISIONED double b_init; // frozen initial balance double e_init; // frozen initial equity long day_id; // day id of the frozen snapshot double e_day0; // daily equity anchor of the frozen snapshot double cfg_fingerprint; long provision_time; ulong checksum; int valid; }; struct SRiskState { uint magic; // schema marker uint version; // schema version ulong seq; // monotonic sequence, one step per durable write int slot; // slot that produced this record (diagnostic) ulong identity; // composite hash of the identity components below long login; // R01-H4: account login ulong server_hash; // R01-H4: trade server ulong scope_hash; // R01-H4: risk scope id ulong period_hash; // R01-H4: risk period id double b_init; // frozen initial BALANCE (static DD and target) double e_init; // initial EQUITY (record only) long day_id; // YYYYMMDD of the daily anchor double e_day0; // equity at the start of the server day int daily_halt; int static_halt; int target_triggered; // realised balance touched the goal int target_secured; // flat and still above the goal double cfg_fingerprint; // hash of the risk inputs long provision_time; // time of the authorised provisioning ulong checksum; int valid; }; SRiskState g_state; bool g_riskStateValid = false; bool g_stateStorageFault = false; // R01-H1/H2: a save that is not durable blocks entries int g_stateSlot = CP_SLOT_A; // slot holding the newest durable record bool g_stateSlotKnown = false; // false until a durable record exists // Bookkeeping datetime g_lastBarTime = 0; datetime g_lastEntryTime = 0; //+------------------------------------------------------------------+ //| Normalize a price to the symbol tick grid | //+------------------------------------------------------------------+ double NormalizePrice(const double price) { if(g_tickSize <= 0.0) return NormalizeDouble(price, g_digits); return NormalizeDouble(MathRound(price / g_tickSize) * g_tickSize, g_digits); } //+------------------------------------------------------------------+ //| Number of decimals implied by the volume step | //+------------------------------------------------------------------+ int VolumeDigits() { if(g_volumeStep >= 1.0) return 0; if(g_volumeStep >= 0.1) return 1; if(g_volumeStep >= 0.01) return 2; return 3; } //+------------------------------------------------------------------+ //| Descriptive message for a trade server return code | //+------------------------------------------------------------------+ string RetcodeDescription(const uint code) { switch((int)code) { case TRADE_RETCODE_REQUOTE: return "requote"; case TRADE_RETCODE_REJECT: return "request rejected"; case TRADE_RETCODE_CANCEL: return "request cancelled by trader"; case TRADE_RETCODE_PLACED: return "order placed"; case TRADE_RETCODE_DONE: return "request completed"; case TRADE_RETCODE_DONE_PARTIAL: return "request partially completed"; case TRADE_RETCODE_TIMEOUT: return "request timed out"; case TRADE_RETCODE_INVALID: return "invalid request"; case TRADE_RETCODE_INVALID_VOLUME: return "invalid volume"; case TRADE_RETCODE_INVALID_PRICE: return "invalid price"; case TRADE_RETCODE_INVALID_STOPS: return "invalid stops"; case TRADE_RETCODE_TRADE_DISABLED: return "trading is disabled"; case TRADE_RETCODE_MARKET_CLOSED: return "market is closed"; case TRADE_RETCODE_NO_MONEY: return "not enough money"; case TRADE_RETCODE_PRICE_CHANGED: return "price changed"; case TRADE_RETCODE_PRICE_OFF: return "no quotes to process the request"; case TRADE_RETCODE_INVALID_EXPIRATION: return "invalid expiration"; case TRADE_RETCODE_ORDER_CHANGED: return "order state changed"; case TRADE_RETCODE_TOO_MANY_REQUESTS: return "too many requests"; case TRADE_RETCODE_NO_CHANGES: return "no changes in the request"; case TRADE_RETCODE_LOCKED: return "request locked"; case TRADE_RETCODE_FROZEN: return "order or position is frozen"; case TRADE_RETCODE_INVALID_FILL: return "unsupported filling mode"; case TRADE_RETCODE_CONNECTION: return "no connection to the trade server"; case TRADE_RETCODE_LIMIT_ORDERS: return "order limit reached"; case TRADE_RETCODE_LIMIT_VOLUME: return "volume limit reached"; case TRADE_RETCODE_ONLY_REAL: return "operation allowed on live accounts only"; default: return "unclassified return code"; } } //+------------------------------------------------------------------+ //| Load a rates series indexed from the newest bar | //+------------------------------------------------------------------+ bool LoadRates(const ENUM_TIMEFRAMES timeframe, const int count, MqlRates &rates[]) { ArraySetAsSeries(rates, true); const int copied = CopyRates(_Symbol, timeframe, 0, count, rates); return (copied >= count); } //+------------------------------------------------------------------+ //| Convert a raw rate into a normalized candle view | //+------------------------------------------------------------------+ void BuildCandle(const MqlRates &rate, SCandle &candle) { candle.time = rate.time; candle.open = rate.open; candle.high = rate.high; candle.low = rate.low; candle.close = rate.close; candle.range = rate.high - rate.low; candle.body = MathAbs(rate.close - rate.open); candle.upperWick = rate.high - MathMax(rate.open, rate.close); candle.lowerWick = MathMin(rate.open, rate.close) - rate.low; candle.bullish = (rate.close > rate.open); candle.valid = (candle.range > 0.0); if(candle.valid) { candle.bodyRatio = candle.body / candle.range; candle.upperWickRatio = candle.upperWick / candle.range; candle.lowerWickRatio = candle.lowerWick / candle.range; candle.closePosition = (rate.close - rate.low) / candle.range; } else { candle.bodyRatio = 0.0; candle.upperWickRatio = 0.0; candle.lowerWickRatio = 0.0; candle.closePosition = 0.5; } } //+------------------------------------------------------------------+ //| Highest high and lowest low inside a bar window | //+------------------------------------------------------------------+ void WindowExtremes(const MqlRates &rates[], const int startShift, const int length, double &highest, double &lowest) { highest = -DBL_MAX; lowest = DBL_MAX; const int total = ArraySize(rates); for(int i = startShift; i < startShift + length && i < total; i++) { if(rates[i].high > highest) highest = rates[i].high; if(rates[i].low < lowest) lowest = rates[i].low; } if(highest == -DBL_MAX) highest = 0.0; if(lowest == DBL_MAX) lowest = 0.0; } //+------------------------------------------------------------------+ //| Rejection structure: one side pushed, the other took over | //+------------------------------------------------------------------+ bool IsBullishRejection(const SCandle &candle) { if(!candle.valid) return false; if(candle.lowerWickRatio < InpRejectionWickRatio) return false; if(candle.bodyRatio > InpRejectionMaxBody) return false; if(candle.closePosition < InpRejectionClosePos) return false; return true; } bool IsBearishRejection(const SCandle &candle) { if(!candle.valid) return false; if(candle.upperWickRatio < InpRejectionWickRatio) return false; if(candle.bodyRatio > InpRejectionMaxBody) return false; if((1.0 - candle.closePosition) < InpRejectionClosePos) return false; return true; } //+------------------------------------------------------------------+ //| Engulfing structure: one side takes control aggressively | //+------------------------------------------------------------------+ bool IsBullishEngulfing(const SCandle &previous, const SCandle ¤t) { if(!previous.valid || !current.valid) return false; if(!current.bullish || previous.bullish) return false; if(current.open > previous.close) return false; if(current.close <= previous.open) return false; return (current.body > previous.body); } bool IsBearishEngulfing(const SCandle &previous, const SCandle ¤t) { if(!previous.valid || !current.valid) return false; if(current.bullish || !previous.bullish) return false; if(current.open < previous.close) return false; if(current.close >= previous.open) return false; return (current.body > previous.body); } //+------------------------------------------------------------------+ //| Break of structure on the signal timeframe | //| Returns +1 for a bullish break, -1 for a bearish break, 0 none | //+------------------------------------------------------------------+ int DetectBos(const MqlRates &rates[]) { double refHigh = 0.0; double refLow = 0.0; WindowExtremes(rates, InpBosConfirmBars + 1, InpSwingLookback, refHigh, refLow); if(refHigh <= 0.0 || refLow <= 0.0 || refHigh <= refLow) return 0; // Scan from the newest confirmation bar so the freshest break wins for(int i = 1; i <= InpBosConfirmBars; i++) { if(rates[i].close > refHigh) return 1; if(rates[i].close < refLow) return -1; } return 0; } //+------------------------------------------------------------------+ //| Higher timeframe pressure from an EMA and its slope | //+------------------------------------------------------------------+ int HtfBias() { if(g_htfEmaHandle == INVALID_HANDLE) return 0; double ema[]; ArraySetAsSeries(ema, true); if(CopyBuffer(g_htfEmaHandle, 0, 0, 5, ema) < 5) return 0; const double closePrice = iClose(_Symbol, InpHtfTimeframe, 1); if(closePrice <= 0.0) return 0; const bool above = (closePrice > ema[1]); const bool rising = (ema[1] > ema[3]); const bool falling = (ema[1] < ema[3]); if(above && rising) return 1; if(!above && falling) return -1; return 0; } //+------------------------------------------------------------------+ //| Indicator accessors | //+------------------------------------------------------------------+ double AtrValue(const int shift) { if(g_atrHandle == INVALID_HANDLE) return 0.0; double buffer[]; ArraySetAsSeries(buffer, true); if(CopyBuffer(g_atrHandle, 0, shift, 1, buffer) < 1) return 0.0; return buffer[0]; } double AdxValue() { if(g_adxHandle == INVALID_HANDLE) return -1.0; double buffer[]; ArraySetAsSeries(buffer, true); if(CopyBuffer(g_adxHandle, 0, 1, 1, buffer) < 1) return -1.0; if(buffer[0] <= 0.0) return -1.0; return buffer[0]; } //+------------------------------------------------------------------+ //| Zone helpers | //+------------------------------------------------------------------+ bool ZoneContains(const double zoneLow, const double zoneHigh, const double price, const double tolerance) { if(zoneHigh <= zoneLow) return false; return (price >= zoneLow - tolerance && price <= zoneHigh + tolerance); } // Demand zone: bullish fair value gap or bullish order block bool FindBullishZone(const MqlRates &rates[], const double atr, const double price, double &zoneLow, double &zoneHigh) { const double tolerance = atr * InpZoneToleranceATR; const int total = ArraySize(rates); for(int i = 2; i < InpZoneLookback && (i + 2) < total; i++) { // Fair value gap: the low of the newer candle stays above the high of the older candle if(rates[i].low > rates[i + 2].high) { if(ZoneContains(rates[i + 2].high, rates[i].low, price, tolerance)) { zoneLow = rates[i + 2].high; zoneHigh = rates[i].low; return true; } } // Order block: last bearish candle before a bullish displacement if(rates[i].close < rates[i].open && rates[i - 1].close > rates[i - 1].open) { const double displacement = MathAbs(rates[i - 1].close - rates[i - 1].open); if(displacement >= atr * InpDisplacementATR && rates[i - 1].close > rates[i].high) { if(ZoneContains(rates[i].low, rates[i].high, price, tolerance)) { zoneLow = rates[i].low; zoneHigh = rates[i].high; return true; } } } } return false; } // Supply zone: bearish fair value gap or bearish order block bool FindBearishZone(const MqlRates &rates[], const double atr, const double price, double &zoneLow, double &zoneHigh) { const double tolerance = atr * InpZoneToleranceATR; const int total = ArraySize(rates); for(int i = 2; i < InpZoneLookback && (i + 2) < total; i++) { // Fair value gap: the high of the newer candle stays below the low of the older candle if(rates[i].high < rates[i + 2].low) { if(ZoneContains(rates[i].high, rates[i + 2].low, price, tolerance)) { zoneLow = rates[i].high; zoneHigh = rates[i + 2].low; return true; } } // Order block: last bullish candle before a bearish displacement if(rates[i].close > rates[i].open && rates[i - 1].close < rates[i - 1].open) { const double displacement = MathAbs(rates[i - 1].close - rates[i - 1].open); if(displacement >= atr * InpDisplacementATR && rates[i - 1].close < rates[i].low) { if(ZoneContains(rates[i].low, rates[i].high, price, tolerance)) { zoneLow = rates[i].low; zoneHigh = rates[i].high; return true; } } } } return false; } //+------------------------------------------------------------------+ //| Liquidity sweep: price takes a pool then closes back inside | //+------------------------------------------------------------------+ bool DetectSweep(const MqlRates &rates[], const int direction) { double refHigh = 0.0; double refLow = 0.0; WindowExtremes(rates, InpSweepLookback + 1, InpSweepDepth, refHigh, refLow); if(refHigh <= 0.0 || refLow <= 0.0) return false; for(int i = 1; i <= InpSweepLookback; i++) { if(direction > 0) { if(rates[i].low < refLow && rates[i].close > refLow) return true; } else { if(rates[i].high > refHigh && rates[i].close < refHigh) return true; } } return false; } //+------------------------------------------------------------------+ //| Signal engine | //| The candle itself is never enough: it must sit in a valid context | //+------------------------------------------------------------------+ int DetectSignal(double &score, SCandle &trigger) { score = 0.0; MqlRates rates[]; if(!LoadRates(InpWorkTimeframe, g_historyBars, rates)) return 0; if(ArraySize(rates) < g_historyBars) return 0; if(ArraySize(rates) < InpSwingLookback + InpBosConfirmBars + 8) return 0; const double atr = AtrValue(1); if(atr <= 0.0) return 0; if(InpUseAdxFilter) { const double adx = AdxValue(); if(adx < 0.0) return 0; // indicator not ready: fail closed if(adx < InpAdxMinLevel) return 0; } SCandle current; SCandle previous; BuildCandle(rates[1], current); BuildCandle(rates[2], previous); if(!current.valid) return 0; // The trigger candle must be a rejection or an engulfing, never a random shape const bool bullishTrigger = IsBullishRejection(current) || IsBullishEngulfing(previous, current); const bool bearishTrigger = IsBearishRejection(current) || IsBearishEngulfing(previous, current); int direction = 0; if(bullishTrigger && !bearishTrigger) direction = 1; else if(bearishTrigger && !bullishTrigger) direction = -1; else return 0; // --- Hard context filters ------------------------------------- const int htfBias = HtfBias(); if(InpRequireHtfBias && htfBias != direction) return 0; const int bos = DetectBos(rates); if(InpRequireBos && bos != direction) return 0; // Dealing range location: buy in discount, sell in premium double rangeHigh = 0.0; double rangeLow = 0.0; // The dealing range is measured on the bars BEFORE the trigger candle so the // trigger's own extreme cannot shift the location it is judged against WindowExtremes(rates, 2, g_rangeLookback, rangeHigh, rangeLow); if(rangeHigh <= 0.0 || rangeLow <= 0.0 || rangeHigh <= rangeLow) return 0; const double positionInRange = (current.close - rangeLow) / (rangeHigh - rangeLow); if(InpRequireDiscountPremium) { if(direction > 0 && positionInRange > 0.5 + InpEquilibriumTolerance) return 0; if(direction < 0 && positionInRange < 0.5 - InpEquilibriumTolerance) return 0; } const double price = current.close; const bool sweep = DetectSweep(rates, direction); if(InpRequireLiquiditySweep && !sweep) return 0; double zoneLow = 0.0; double zoneHigh = 0.0; const bool zoneTouch = (direction > 0) ? FindBullishZone(rates, atr, price, zoneLow, zoneHigh) : FindBearishZone(rates, atr, price, zoneLow, zoneHigh); if(InpRequireZoneTouch && !zoneTouch) return 0; // --- Soft scoring --------------------------------------------- const bool rejection = (direction > 0) ? IsBullishRejection(current) : IsBearishRejection(current); const bool engulfing = (direction > 0) ? IsBullishEngulfing(previous, current) : IsBearishEngulfing(previous, current); const bool dominantBody = (current.bodyRatio >= InpDominantBodyRatio) && (current.bullish == (direction > 0)); score = 0.0; score += (rejection ? 0.35 : 0.0); score += (engulfing ? 0.20 : 0.0); score += (dominantBody ? 0.15 : 0.0); score += (sweep ? 0.15 : 0.0); score += (zoneTouch ? 0.15 : 0.0); if(score < InpMinSignalScore) return 0; trigger = current; return direction; } //+------------------------------------------------------------------+ //| Persistent risk state primitives | //+------------------------------------------------------------------+ ulong StateHash(const string text) { ulong h = 1469598103934665603; // FNV-1a 64 offset basis const int n = StringLen(text); for(int i = 0; i < n; i++) { h ^= (ulong)StringGetCharacter(text, i); h *= 1099511628211; // FNV prime } return h; } // R01-H4: every component that defines the risk ledger is explicit. A change to the // account, the trade server, the risk scope or the risk period produces a different // identity, and a different identity never inherits a baseline. ulong StateIdentityServer() { return StateHash(AccountInfoString(ACCOUNT_SERVER)); } ulong StateIdentityScope() { return StateHash(InpRiskScopeId); } ulong StateIdentityPeriod() { return StateHash(InpRiskPeriodId); } ulong StateIdentity() { return StateHash(StringFormat("%I64d|%I64u|%I64u|%I64u|%I64d|%s|%d", AccountInfoInteger(ACCOUNT_LOGIN), StateIdentityServer(), StateIdentityScope(), StateIdentityPeriod(), InpMagicNumber, _Symbol, (int)InpWorkTimeframe)); } double StateConfigFingerprint() { const string cfg = StringFormat("%.4f|%.4f|%.4f|%.4f|%.4f|%d|%.4f", InpDailyMaxLossPercent, InpStaticMaxDdPercent, InpEquityGrowthTargetPct, InpRiskPercentMin, InpRiskPercentMax, InpMaxOpenPositions, InpMaxLotAbsolute); return (double)(StateHash(cfg) % 1000000007); } ulong StateChecksum(const SRiskState &s) { return StateHash(StringFormat("%u|%u|%I64u|%d|%I64u|%I64d|%I64u|%I64u|%I64u|%.10f|%.10f|%I64d|%.10f|%d|%d|%d|%d|%.4f|%I64d", s.magic, s.version, s.seq, s.slot, s.identity, s.login, s.server_hash, s.scope_hash, s.period_hash, s.b_init, s.e_init, s.day_id, s.e_day0, s.daily_halt, s.static_halt, s.target_triggered, s.target_secured, s.cfg_fingerprint, s.provision_time)); } // Strategy Tester runs must stay isolated or every run inherits the previous result bool StatePersistenceEnabled() { if(MQLInfoInteger(MQL_TESTER) && !InpTesterPersistState) return false; return true; } string StateKey(const string suffix) { return StringFormat("CP_%016I64X_%s", StateIdentity(), suffix); } // R01-H3: two archive slots, both keyed by the risk identity string StateSlotName(const int slot) { return StringFormat("CP_RISK_%016I64X_%s.bin", StateIdentity(), (slot == CP_SLOT_A ? "A" : "B")); } void StateInitFresh() { ZeroMemory(g_state); g_state.magic = CP_STATE_MAGIC; g_state.version = CP_STATE_VERSION; g_state.seq = 0; // assigned by the next durable write g_state.slot = CP_SLOT_A; g_state.identity = StateIdentity(); g_state.login = AccountInfoInteger(ACCOUNT_LOGIN); g_state.server_hash = StateIdentityServer(); g_state.scope_hash = StateIdentityScope(); g_state.period_hash = StateIdentityPeriod(); g_state.b_init = AccountInfoDouble(ACCOUNT_BALANCE); g_state.e_init = AccountInfoDouble(ACCOUNT_EQUITY); if(g_state.e_init <= 0.0) g_state.e_init = g_state.b_init; g_state.day_id = 0; // forces a fresh daily anchor g_state.e_day0 = 0.0; g_state.daily_halt = 0; g_state.static_halt = 0; g_state.target_triggered = 0; g_state.target_secured = 0; g_state.cfg_fingerprint = StateConfigFingerprint(); g_state.provision_time = (long)TimeCurrent(); g_state.valid = 1; g_state.checksum = StateChecksum(g_state); } // Mirror the critical flags so sibling instances can see them immediately. // The mirror is a coordination cache only; the archive stays authoritative. void StateMirrorPublish(const SRiskState &s) { GlobalVariableSet(StateKey("valid"), (double)s.valid); GlobalVariableSet(StateKey("daily"), (double)s.daily_halt); GlobalVariableSet(StateKey("static"), (double)s.static_halt); GlobalVariableSet(StateKey("target"), (double)s.target_secured); GlobalVariableSet(StateKey("seq"), (double)(long)s.seq); GlobalVariablesFlush(); } // R01-H6: compare-and-swap on the shared sequence mirror. The tentative value is written // and read back, so an instance that already advanced the sequence makes this writer lose // the swap instead of overwriting state that it never observed. bool StateCasAcquire(const ulong expectedSeq) { const string key = StateKey("seq"); if(GlobalVariableCheck(key)) { const double mirror = GlobalVariableGet(key); if(mirror > 0.0 && (ulong)(long)mirror != expectedSeq) { PrintFormat("CAS rejected: mirror sequence %.0f is not the expected %I64u", mirror, expectedSeq); return false; } } GlobalVariableSet(key, (double)(long)(expectedSeq + 1)); GlobalVariablesFlush(); return ((ulong)(long)GlobalVariableGet(key) == expectedSeq + 1); } // R01-H6: true when the peer slot already moved past the sequence this writer swapped from bool StatePeerAdvanced(const int peerSlot, const ulong expectedSeq) { SRiskState peer; if(!StateReadSlot(peerSlot, peer)) return false; if(!StateRecordValid(peer)) return false; if(!StateIdentityMatches(peer)) return false; return (peer.seq > expectedSeq); } // R01-H1: the record must reach the disk before the handle is released, otherwise a // terminal or power failure silently loses the write while the EA believes it saved. // R01-H2: the record is read back from the file and compared field by field, so a // partial or truncated write is detected instead of being trusted. // R01-H3: the write targets the slot that does NOT hold the newest valid record, so the // last good archive survives any failed or torn candidate write. // R01-H6: the sequence is swapped under CAS before the write and re-checked on the peer // slot afterwards, so two instances in one terminal cannot both commit. // R01-H7: the candidate is opened with an exclusive write handle (read sharing only), so // a second terminal cannot interleave its own writer with this record. // Any failure latches the storage fault and is reported as a failed save. bool StateSave() { if(!g_riskStateValid) { g_stateStorageFault = true; Print("CRITICAL: refusing to persist an invalid risk state"); return false; } if(!StatePersistenceEnabled()) { g_state.checksum = StateChecksum(g_state); StateMirrorPublish(g_state); g_stateStorageFault = false; return true; } const ulong expectedSeq = g_state.seq; const int targetSlot = (g_stateSlotKnown && g_stateSlot == CP_SLOT_A) ? CP_SLOT_B : CP_SLOT_A; const int peerSlot = (targetSlot == CP_SLOT_A) ? CP_SLOT_B : CP_SLOT_A; const string slotTag = (targetSlot == CP_SLOT_A ? "A" : "B"); const string name = StateSlotName(targetSlot); // R01-H6: no writer may advance the sequence from a stale view of the state if(!StateCasAcquire(expectedSeq)) { g_stateStorageFault = true; PrintFormat("CRITICAL: risk state not persisted, the sequence swap on %I64u failed", expectedSeq); return false; } bool ok = false; do { SRiskState next = g_state; next.seq = expectedSeq + 1; next.slot = targetSlot; next.checksum = StateChecksum(next); const int h = FileOpen(name, FILE_BIN | FILE_WRITE | FILE_COMMON | FILE_SHARE_READ); if(h == INVALID_HANDLE) { PrintFormat("CRITICAL: risk archive slot %s could not be opened for writing (error %d) at %s", slotTag, GetLastError(), name); break; } ResetLastError(); const bool wrote = FileWriteStruct(h, next); if(wrote) FileFlush(h); // R01-H1: push the buffer to the disk, not only to cache const int writeError = GetLastError(); FileClose(h); if(!wrote || writeError != 0) { PrintFormat("CRITICAL: risk archive slot %s write or flush failed (error %d) at %s", slotTag, writeError, name); break; } // R01-H2: verify the candidate by reading it back from the file itself SRiskState verify; if(!StateReadSlot(targetSlot, verify)) { PrintFormat("CRITICAL: risk archive slot %s read-back failed at %s", slotTag, name); break; } if(!StateRecordValid(verify) || !StateIdentityMatches(verify) || verify.seq != next.seq || verify.checksum != next.checksum) { PrintFormat("CRITICAL: risk archive slot %s read-back verification failed at %s", slotTag, name); break; } // R01-H6: the peer slot must not have moved past the sequence we swapped from if(StatePeerAdvanced(peerSlot, expectedSeq)) { PrintFormat("CRITICAL: risk sequence advanced past %I64u in the peer slot, the candidate is not authoritative", expectedSeq); break; } g_state = next; ok = true; } while(false); if(!ok) { g_stateStorageFault = true; StateMirrorPublish(g_state); // republish the durable sequence, dropping the tentative swap return false; } g_stateSlot = targetSlot; g_stateSlotKnown = true; g_stateStorageFault = false; StateMirrorPublish(g_state); return true; } // R01-H3: raw slot read. False when the slot is absent, short or unreadable. bool StateReadSlot(const int slot, SRiskState &record) { ZeroMemory(record); const int h = FileOpen(StateSlotName(slot), FILE_BIN | FILE_READ | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(h == INVALID_HANDLE) return false; const bool ok = FileReadStruct(h, record); FileClose(h); return ok; } // Structural validation of a single archive record. Balance drift is deliberately NOT // a validity test: trading changes the balance by design. bool StateRecordValid(const SRiskState &s) { if(s.magic != CP_STATE_MAGIC) return false; if(s.version != CP_STATE_VERSION) return false; if(s.valid != 1) return false; if(s.seq == 0) return false; if(s.slot != CP_SLOT_A && s.slot != CP_SLOT_B) return false; if(s.checksum != StateChecksum(s)) return false; if(s.b_init <= 0.0) return false; if(s.e_init <= 0.0) return false; if(s.day_id <= 0) return false; if(s.e_day0 <= 0.0) return false; if(s.provision_time <= 0) return false; return true; } // R01-H4: the record may only be used by the identity that created it. Every component // is compared, not only the composite hash, so a change of login, server, scope or // period can never be absorbed by a hash coincidence. bool StateIdentityMatches(const SRiskState &s) { if(s.identity != StateIdentity()) return false; if(s.login != AccountInfoInteger(ACCOUNT_LOGIN)) return false; if(s.server_hash != StateIdentityServer()) return false; if(s.scope_hash != StateIdentityScope()) return false; if(s.period_hash != StateIdentityPeriod()) return false; return true; } // R01-H8: deterministic recovery. Both slots are validated independently, the highest // valid sequence wins and an equal sequence resolves to slot A. A record that belongs to // another identity never authorises entries, so it is reported separately from a // missing or corrupt archive. int StateRecover(SRiskState &best, int &bestSlot, ulong &maxSeqSeen) { bestSlot = CP_SLOT_A; maxSeqSeen = 0; ZeroMemory(best); SRiskState recA; SRiskState recB; const bool okA = StateReadSlot(CP_SLOT_A, recA); const bool okB = StateReadSlot(CP_SLOT_B, recB); const bool validA = okA && StateRecordValid(recA); const bool validB = okB && StateRecordValid(recB); const bool matchA = validA && StateIdentityMatches(recA); const bool matchB = validB && StateIdentityMatches(recB); if(validA && !matchA) PrintFormat("Archive anomaly: slot A holds a foreign identity (sequence %I64u)", recA.seq); if(validB && !matchB) PrintFormat("Archive anomaly: slot B holds a foreign identity (sequence %I64u)", recB.seq); // Sequence continuity is derived from records of this identity only if(matchA && recA.seq > maxSeqSeen) maxSeqSeen = recA.seq; if(matchB && recB.seq > maxSeqSeen) maxSeqSeen = recB.seq; if(!matchA && !matchB) return ((validA || validB) ? CP_REC_MISMATCH : CP_REC_NONE); if(matchA && matchB) { if(recA.seq < recB.seq) { best = recB; bestSlot = CP_SLOT_B; return CP_REC_RESTORED; } if(recA.seq == recB.seq) PrintFormat("Archive anomaly: both slots carry sequence %I64u, slot A is used", recA.seq); best = recA; bestSlot = CP_SLOT_A; return CP_REC_RESTORED; } if(matchA) { best = recA; bestSlot = CP_SLOT_A; return CP_REC_RESTORED; } best = recB; bestSlot = CP_SLOT_B; return CP_REC_RESTORED; } //+------------------------------------------------------------------+ //| Provisioning marker: identity, durability and validation | //+------------------------------------------------------------------+ // The provisioning authorization belongs to the risk period, not to the chart, so a // symbol, magic or timeframe change can never hand out a second authorization. ulong StatePeriodIdentity() { return StateHash(StringFormat("%I64d|%I64u|%I64u|%I64u", AccountInfoInteger(ACCOUNT_LOGIN), StateIdentityServer(), StateIdentityScope(), StateIdentityPeriod())); } ulong StateProvisionId() { ulong id = StateHash(StringFormat("%I64d|%I64u|%I64u|%I64d", (long)TimeCurrent(), (ulong)GetMicrosecondCount(), StatePeriodIdentity(), (long)AccountInfoInteger(ACCOUNT_LOGIN))); return (id == 0 ? 1 : id); } string StateMarkerName() { return StringFormat("CP_PROV_%016I64X.ack", StatePeriodIdentity()); } string StateLockName() { return StringFormat("CP_PROV_%016I64X.lck", StatePeriodIdentity()); } ulong StateMarkerChecksum(const SProvisionMarker &m) { return StateHash(StringFormat("%u|%u|%I64u|%I64d|%I64u|%I64u|%I64u|%I64u|%d|%.10f|%.10f|%I64d|%.10f|%.4f|%I64d", m.magic, m.version, m.identity, m.login, m.server_hash, m.scope_hash, m.period_hash, m.prov_id, m.status, m.b_init, m.e_init, m.day_id, m.e_day0, m.cfg_fingerprint, m.provision_time)); } bool StateMarkerValid(const SProvisionMarker &m) { if(m.magic != CP_PROV_MAGIC) return false; if(m.version != CP_PROV_VERSION) return false; if(m.valid != 1) return false; if(m.checksum != StateMarkerChecksum(m)) return false; if(m.identity != StatePeriodIdentity()) return false; if(m.login != AccountInfoInteger(ACCOUNT_LOGIN)) return false; if(m.server_hash != StateIdentityServer()) return false; if(m.scope_hash != StateIdentityScope()) return false; if(m.period_hash != StateIdentityPeriod()) return false; if(m.prov_id == 0) return false; if(m.status != CP_PSTAT_PROVISIONING && m.status != CP_PSTAT_PROVISIONED) return false; if(m.b_init <= 0.0) return false; if(m.e_init <= 0.0) return false; if(m.day_id <= 0) return false; if(m.e_day0 <= 0.0) return false; if(m.provision_time <= 0) return false; return true; } // A marker that exists but cannot be validated is reported as CORRUPT, never as absent, // so a damaged marker can never be mistaken for a first provisioning. int StateMarkerLoad(SProvisionMarker &m) { ZeroMemory(m); const string name = StateMarkerName(); const int h = FileOpen(name, FILE_BIN | FILE_READ | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(h == INVALID_HANDLE) { if(FileIsExist(name, FILE_COMMON)) { PrintFormat("CRITICAL: provisioning marker %s exists but could not be opened (error %d)", name, GetLastError()); return CP_MARK_CORRUPT; } return CP_MARK_NONE; } const bool ok = FileReadStruct(h, m); FileClose(h); if(!ok) return CP_MARK_CORRUPT; if(!StateMarkerValid(m)) { PrintFormat("CRITICAL: provisioning marker %s failed validation", name); return CP_MARK_CORRUPT; } if(m.status == CP_PSTAT_PROVISIONING) return CP_MARK_PROVISIONING; if(m.status == CP_PSTAT_PROVISIONED) return CP_MARK_PROVISIONED; return CP_MARK_CORRUPT; } // R01-H1/H2 applied to the marker: flush before close, then read the record back and // compare every frozen field. A marker that cannot be read back is a failed marker. bool StateMarkerStore(const SProvisionMarker &src, const string stage) { SProvisionMarker m = src; m.checksum = StateMarkerChecksum(m); const string name = StateMarkerName(); const int h = FileOpen(name, FILE_BIN | FILE_WRITE | FILE_COMMON | FILE_SHARE_READ); if(h == INVALID_HANDLE) { PrintFormat("CRITICAL: provisioning marker could not be opened for writing (error %d) at %s", GetLastError(), name); return false; } ResetLastError(); const bool wrote = FileWriteStruct(h, m); if(wrote) FileFlush(h); const int writeError = GetLastError(); FileClose(h); if(!wrote || writeError != 0) { PrintFormat("CRITICAL: provisioning marker write or flush failed in stage %s (error %d) at %s", stage, writeError, name); return false; } SProvisionMarker verify; ZeroMemory(verify); const int rh = FileOpen(name, FILE_BIN | FILE_READ | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(rh == INVALID_HANDLE) { PrintFormat("CRITICAL: provisioning marker read-back failed in stage %s (error %d) at %s", stage, GetLastError(), name); return false; } const bool readBack = FileReadStruct(rh, verify); FileClose(rh); if(!readBack || !StateMarkerValid(verify) || verify.checksum != m.checksum || verify.status != m.status || verify.prov_id != m.prov_id || verify.b_init != m.b_init || verify.e_init != m.e_init || verify.day_id != m.day_id || verify.e_day0 != m.e_day0 || verify.cfg_fingerprint != m.cfg_fingerprint || verify.provision_time != m.provision_time) { PrintFormat("CRITICAL: provisioning marker read-back verification failed in stage %s at %s", stage, name); return false; } PrintFormat("Provisioning marker verified: stage '%s', status %s, id %016I64X, baseline %.2f/%.2f, day %I64d anchor %.2f", stage, (m.status == CP_PSTAT_PROVISIONED ? "PROVISIONED" : "PROVISIONING"), m.prov_id, m.b_init, m.e_init, m.day_id, m.e_day0); return true; } // R01-H7: one exclusive writer at a time across terminals. The handle is held for the whole // decision, so a sibling terminal cannot interleave its own marker or archive write. int StateLockAcquire() { const int h = FileOpen(StateLockName(), FILE_BIN | FILE_WRITE | FILE_COMMON | FILE_SHARE_READ); if(h == INVALID_HANDLE) PrintFormat("CRITICAL: the exclusive provisioning lock could not be acquired (error %d) at %s", GetLastError(), StateLockName()); return h; } void StateLockRelease(const int handle) { if(handle != INVALID_HANDLE) FileClose(handle); } // The sequence mirror is a coordination cache, but a tentative base must never sit below // it, otherwise the compare-and-swap would reject a legitimate write after a restart. ulong StateMirrorSequence() { const string key = StateKey("seq"); if(!GlobalVariableCheck(key)) return 0; const double mirror = GlobalVariableGet(key); if(mirror <= 0.0) return 0; return (ulong)(long)mirror; } void StateAdoptRestored(const SRiskState &record, const int slot) { g_state = record; g_stateSlot = slot; g_stateSlotKnown = true; g_riskStateValid = true; g_stateStorageFault = false; } void StateComputeDailyAnchor(long &dayId, double &eDay0) { MqlDateTime now; TimeToStruct(TimeCurrent(), now); dayId = (long)now.year * 10000 + (long)now.mon * 100 + (long)now.day; eDay0 = AccountInfoDouble(ACCOUNT_EQUITY); if(eDay0 <= 0.0) eDay0 = AccountInfoDouble(ACCOUNT_BALANCE); } // The frozen snapshot is authoritative for provisioning and for its resumption. The live // balance is never consulted here, which is what stops a crashed provisioning from opening // a second baseline. void StateApplyMarkerSnapshot(const SProvisionMarker &m, const ulong seqBase) { ZeroMemory(g_state); g_state.magic = CP_STATE_MAGIC; g_state.version = CP_STATE_VERSION; g_state.seq = seqBase; g_state.slot = CP_SLOT_A; g_state.identity = StateIdentity(); g_state.login = AccountInfoInteger(ACCOUNT_LOGIN); g_state.server_hash = StateIdentityServer(); g_state.scope_hash = StateIdentityScope(); g_state.period_hash = StateIdentityPeriod(); g_state.b_init = m.b_init; g_state.e_init = m.e_init; g_state.day_id = m.day_id; g_state.e_day0 = m.e_day0; g_state.daily_halt = 0; g_state.static_halt = 0; g_state.target_triggered = 0; g_state.target_secured = 0; g_state.cfg_fingerprint = m.cfg_fingerprint; g_state.provision_time = m.provision_time; g_state.valid = 1; g_state.checksum = StateChecksum(g_state); } // The archive of a provisioned period must carry the frozen baseline it was created from. bool StateArchiveMatchesMarker(const SProvisionMarker &m, const SRiskState &s) { if(s.b_init != m.b_init || s.e_init != m.e_init || s.provision_time != m.provision_time) { PrintFormat("Archive/marker mismatch: archive %.2f/%.2f at %I64d, marker %.2f/%.2f at %I64d", s.b_init, s.e_init, s.provision_time, m.b_init, m.e_init, m.provision_time); return false; } return true; } // Step 3 of the state machine: both slots are built from the frozen snapshot and then read // back independently, so an incomplete provisioning is detected here and not later. bool StateProvisionArchives(const ulong seqBase) { g_state.seq = seqBase; g_stateSlot = CP_SLOT_A; g_stateSlotKnown = false; g_riskStateValid = true; g_stateStorageFault = false; if(!StateSave()) { Print("CRITICAL: provisioning could not persist archive slot A"); return false; } if(!StateSave()) { Print("CRITICAL: provisioning could not persist archive slot B"); return false; } SRiskState recA; SRiskState recB; const bool okA = StateReadSlot(CP_SLOT_A, recA) && StateRecordValid(recA) && StateIdentityMatches(recA); const bool okB = StateReadSlot(CP_SLOT_B, recB) && StateRecordValid(recB) && StateIdentityMatches(recB); if(!okA || !okB) { PrintFormat("CRITICAL: provisioning archive verification failed (slot A %s, slot B %s)", (okA ? "valid" : "invalid"), (okB ? "valid" : "invalid")); return false; } if(recA.b_init != g_state.b_init || recB.b_init != g_state.b_init) { Print("CRITICAL: provisioning archive baseline does not match the frozen snapshot"); return false; } if(recA.provision_time != g_state.provision_time || recB.provision_time != g_state.provision_time) { Print("CRITICAL: provisioning archive provisioning time does not match the frozen snapshot"); return false; } if(recA.day_id != g_state.day_id || recB.day_id != g_state.day_id) { Print("CRITICAL: provisioning archive day does not match the frozen snapshot"); return false; } PrintFormat("Provisioning archives verified: slot A sequence %I64u, slot B sequence %I64u", recA.seq, recB.seq); return true; } // Step 4 of the state machine: the marker is committed to PROVISIONED only after the // archives verify, and only a durable, verified marker enables entries. bool StateCommitMarker(const SProvisionMarker &base, const SRiskState &snapshot) { SProvisionMarker m = base; m.status = CP_PSTAT_PROVISIONED; m.b_init = snapshot.b_init; m.e_init = snapshot.e_init; m.day_id = snapshot.day_id; m.e_day0 = snapshot.e_day0; m.checksum = StateMarkerChecksum(m); return StateMarkerStore(m, "commit"); } // The archive itself proves the period was provisioned, so a missing or damaged marker is // rebuilt from it instead of being treated as a licence to provision again. bool StateReconstructMarker(const SRiskState &snapshot) { SProvisionMarker m; ZeroMemory(m); m.magic = CP_PROV_MAGIC; m.version = CP_PROV_VERSION; m.identity = StatePeriodIdentity(); m.login = AccountInfoInteger(ACCOUNT_LOGIN); m.server_hash = StateIdentityServer(); m.scope_hash = StateIdentityScope(); m.period_hash = StateIdentityPeriod(); m.prov_id = StateProvisionId(); m.status = CP_PSTAT_PROVISIONED; m.b_init = snapshot.b_init; m.e_init = snapshot.e_init; m.day_id = snapshot.day_id; m.e_day0 = snapshot.e_day0; m.cfg_fingerprint = StateConfigFingerprint(); m.provision_time = snapshot.provision_time; m.valid = 1; m.checksum = StateMarkerChecksum(m); if(!StateMarkerStore(m, "reconstruct")) return false; PrintFormat("Provisioning marker reconstructed from the archive: baseline %.2f, provisioned %I64d", m.b_init, m.provision_time); return true; } int StateFinishRestore(const int slot) { PrintFormat("Risk state restored: slot %s, sequence %I64u, balance baseline %.2f, equity baseline %.2f, day %I64d anchor %.2f", (slot == CP_SLOT_A ? "A" : "B"), g_state.seq, g_state.b_init, g_state.e_init, g_state.day_id, g_state.e_day0); // A changed risk configuration invalidates a latched halt, not the baseline if(g_state.cfg_fingerprint != StateConfigFingerprint() && (g_state.daily_halt != 0 || g_state.static_halt != 0 || g_state.target_triggered != 0)) { g_riskStateValid = false; Print("CRITICAL: RISK_STATE_INVALID. Risk parameters changed while a halt was latched."); return CP_INIT_DENIED; } return CP_INIT_RESTORED; } // Steps 3 and 4 of the state machine, shared by the first provisioning and by the // resumption of an interrupted one, so both paths consume the same frozen snapshot. int StateCompleteProvisioning(const SProvisionMarker &marker, const ulong seqBase) { StateApplyMarkerSnapshot(marker, seqBase); if(!StateProvisionArchives(seqBase)) { g_riskStateValid = false; Print("Entries stay disabled until the provisioning marker is PROVISIONED and both archive slots verify."); return CP_INIT_FAILED; } if(!StateCommitMarker(marker, g_state)) { g_riskStateValid = false; Print("CRITICAL: the provisioning marker could not be committed; entries stay disabled"); return CP_INIT_FAILED; } PrintFormat("Provisioning complete: marker PROVISIONED, archives verified at sequence %I64u", g_state.seq); PrintFormat("New risk period: slot %s, sequence %I64u, initial balance %.2f, static floor %.2f, target balance %.2f", (g_stateSlot == CP_SLOT_A ? "A" : "B"), g_state.seq, g_state.b_init, g_state.b_init * (1.0 - InpStaticMaxDdPercent / 100.0), g_state.b_init * (1.0 + InpEquityGrowthTargetPct / 100.0)); Print("Provisioning is one-shot: set InpResetRiskState=false before the next start."); return CP_INIT_PROVISIONED; } // Step 2 of the state machine: the authorization is consumed by a durable, verified // PROVISIONING marker before a single archive byte is written. int StateProvisionFirst(const ulong seqBase) { long dayId = 0; double eDay0 = 0.0; StateComputeDailyAnchor(dayId, eDay0); SProvisionMarker marker; ZeroMemory(marker); marker.magic = CP_PROV_MAGIC; marker.version = CP_PROV_VERSION; marker.identity = StatePeriodIdentity(); marker.login = AccountInfoInteger(ACCOUNT_LOGIN); marker.server_hash = StateIdentityServer(); marker.scope_hash = StateIdentityScope(); marker.period_hash = StateIdentityPeriod(); marker.prov_id = StateProvisionId(); marker.status = CP_PSTAT_PROVISIONING; marker.b_init = AccountInfoDouble(ACCOUNT_BALANCE); marker.e_init = AccountInfoDouble(ACCOUNT_EQUITY); if(marker.e_init <= 0.0) marker.e_init = marker.b_init; marker.day_id = dayId; marker.e_day0 = eDay0; marker.cfg_fingerprint = StateConfigFingerprint(); marker.provision_time = (long)TimeCurrent(); marker.valid = 1; marker.checksum = StateMarkerChecksum(marker); if(marker.b_init <= 0.0 || marker.e_init <= 0.0 || marker.day_id <= 0 || marker.e_day0 <= 0.0) { Print("CRITICAL: RISK_STATE_INVALID. The account baseline is not available; provisioning is refused."); Print("Entries disabled."); return CP_INIT_DENIED; } PrintFormat("PROVISIONING AUTHORISED by InpResetRiskState=true: scope '%s', period '%s', sequence base %I64u.", InpRiskScopeId, InpRiskPeriodId, seqBase); PrintFormat("Provisioning snapshot frozen: initial balance %.2f, initial equity %.2f, day %I64d anchor %.2f, id %016I64X", marker.b_init, marker.e_init, marker.day_id, marker.e_day0, marker.prov_id); if(!StateMarkerStore(marker, "consume")) { Print("CRITICAL: RISK_STATE_INVALID. The provisioning marker could not be stored; no archive was written."); Print("Entries disabled."); return CP_INIT_DENIED; } Print("Provisioning authorization consumed and durably stored; entries stay disabled until the archives verify."); return StateCompleteProvisioning(marker, seqBase); } // Recovery decision table of R-01 v1.2 int StateProvisionOrRestoreLocked() { SRiskState recovered; int recoveredSlot = CP_SLOT_A; ulong maxSeqSeen = 0; const int recovery = StateRecover(recovered, recoveredSlot, maxSeqSeen); SProvisionMarker marker; const int mark = StateMarkerLoad(marker); ulong seqBase = maxSeqSeen; const ulong mirrorSeq = StateMirrorSequence(); if(mirrorSeq > seqBase) seqBase = mirrorSeq; PrintFormat("Provisioning marker %s: %s. Archive recovery: %s, highest sequence %I64u", StateMarkerName(), (mark == CP_MARK_PROVISIONED ? "PROVISIONED" : mark == CP_MARK_PROVISIONING ? "PROVISIONING" : mark == CP_MARK_CORRUPT ? "CORRUPT (untrusted)" : "ABSENT"), (recovery == CP_REC_RESTORED ? "RESTORED" : recovery == CP_REC_MISMATCH ? "IDENTITY_MISMATCH" : "NONE"), maxSeqSeen); // --- The risk period is already provisioned --------------------- if(mark == CP_MARK_PROVISIONED) { if(recovery == CP_REC_RESTORED) { StateAdoptRestored(recovered, recoveredSlot); if(!StateArchiveMatchesMarker(marker, g_state)) { g_riskStateValid = false; Print("CRITICAL: RISK_STATE_INVALID. The archive does not match the frozen provisioning snapshot."); Print("Entries disabled."); return CP_INIT_DENIED; } if(InpResetRiskState) Print("WARNING: InpResetRiskState=true ignored: the provisioning authorization is already consumed and the existing archive stays authoritative"); return StateFinishRestore(recoveredSlot); } Print("CRITICAL: RISK_STATE_INVALID. The provisioning marker says this risk period is already PROVISIONED but no valid archive remains."); Print("Provisioning authorization already consumed."); Print("Existing risk period cannot be reinitialized."); if(InpResetRiskState) Print("WARNING: InpResetRiskState=true ignored: the authorization of this risk period was consumed by an earlier provisioning."); Print("Entries disabled."); Print("CRITICAL: define a new InpRiskPeriodId and authorise that provisioning deliberately to start a new risk period."); return CP_INIT_DENIED; } // --- The provisioning was interrupted --------------------------- if(mark == CP_MARK_PROVISIONING) { if(recovery == CP_REC_MISMATCH) { Print("CRITICAL: RISK_STATE_INVALID. The archive belongs to a different risk identity."); Print("Entries disabled."); return CP_INIT_DENIED; } if(InpResetRiskState) Print("WARNING: InpResetRiskState=true ignored: the authorization is already consumed and provisioning is resumed, not restarted"); if(recovery == CP_REC_RESTORED) { StateAdoptRestored(recovered, recoveredSlot); if(!StateArchiveMatchesMarker(marker, g_state)) { g_riskStateValid = false; Print("CRITICAL: RISK_STATE_INVALID. The archive does not match the frozen provisioning snapshot."); Print("Entries disabled."); return CP_INIT_DENIED; } PrintFormat("Provisioning commit: the archive from the frozen snapshot verifies at sequence %I64u", g_state.seq); if(!StateCommitMarker(marker, g_state)) { g_riskStateValid = false; Print("CRITICAL: the provisioning marker could not be committed; entries stay disabled"); return CP_INIT_FAILED; } Print("Provisioning complete: the interrupted provisioning was committed by this start."); return StateFinishRestore(recoveredSlot); } Print("Provisioning resume: the marker holds a consumed authorization whose provisioning never completed."); PrintFormat("Provisioning resume: the frozen snapshot is reused (initial balance %.2f, initial equity %.2f, day %I64d anchor %.2f).", marker.b_init, marker.e_init, marker.day_id, marker.e_day0); Print("Provisioning resume: the live balance is not used as a new baseline."); return StateCompleteProvisioning(marker, seqBase); } // --- The marker is damaged, the archive is trusted -------------- if(mark == CP_MARK_CORRUPT) { if(recovery == CP_REC_RESTORED) { Print("Provisioning marker is corrupt: it is reconstructed from the valid archive before entries are allowed"); StateAdoptRestored(recovered, recoveredSlot); if(!StateReconstructMarker(g_state)) { g_riskStateValid = false; Print("CRITICAL: RISK_STATE_INVALID. The provisioning marker could not be reconstructed."); Print("Entries disabled."); return CP_INIT_DENIED; } if(InpResetRiskState) Print("WARNING: InpResetRiskState=true ignored: the existing archive stays authoritative"); return StateFinishRestore(recoveredSlot); } Print("CRITICAL: RISK_STATE_INVALID. The provisioning marker is corrupt and no valid archive remains."); Print("Provisioning authorization already consumed."); Print("Existing risk period cannot be reinitialized."); Print("Entries disabled."); return CP_INIT_DENIED; } // --- No marker for this risk period ----------------------------- if(recovery == CP_REC_RESTORED) { // Installation upgraded from R-01 v1.1: the archive itself proves the period was // provisioned, so the acknowledgement is rebuilt from it, never re-provisioned. Print("Provisioning marker absent: it is rebuilt from the valid archive before entries are allowed"); StateAdoptRestored(recovered, recoveredSlot); if(!StateReconstructMarker(g_state)) { g_riskStateValid = false; Print("CRITICAL: RISK_STATE_INVALID. The provisioning marker could not be created."); Print("Entries disabled."); return CP_INIT_DENIED; } if(InpResetRiskState) Print("WARNING: InpResetRiskState=true ignored: the provisioning authorization is already consumed and the existing archive stays authoritative"); return StateFinishRestore(recoveredSlot); } if(recovery == CP_REC_MISMATCH) { Print("CRITICAL: RISK_STATE_INVALID. The archive belongs to a different risk identity."); Print("CRITICAL: entries are disabled. Repair the archive or start a new risk period."); return CP_INIT_DENIED; } if(!InpResetRiskState) { Print("CRITICAL: RISK_STATE_INVALID. No valid archive slot could be recovered."); Print("CRITICAL: entries are disabled. Repair the archive or set InpResetRiskState=true to start a new period."); return CP_INIT_DENIED; } return StateProvisionFirst(seqBase); } int StateProvisionOrRestore() { const int lock = StateLockAcquire(); if(lock == INVALID_HANDLE) { Print("CRITICAL: RISK_STATE_INVALID. The exclusive provisioning lock could not be acquired; entries are disabled."); g_riskStateValid = false; return CP_INIT_DENIED; } const int result = StateProvisionOrRestoreLocked(); StateLockRelease(lock); return result; } //+------------------------------------------------------------------+ //| Equity protection: daily loss, static drawdown, growth target | //+------------------------------------------------------------------+ bool InitializeDailyAnchor() { MqlDateTime now; TimeToStruct(TimeCurrent(), now); const long dayId = (long)now.year * 10000 + (long)now.mon * 100 + (long)now.day; if(dayId == g_state.day_id) return true; const long prevDayId = g_state.day_id; const double prevDay0 = g_state.e_day0; const int prevHalt = g_state.daily_halt; g_state.day_id = dayId; g_state.e_day0 = AccountInfoDouble(ACCOUNT_EQUITY); if(g_state.e_day0 <= 0.0) g_state.e_day0 = AccountInfoDouble(ACCOUNT_BALANCE); g_state.daily_halt = 0; // R01-H1/H2: the new anchor is only trusted once it is durable and verified. // A rejected anchor is rolled back so the next tick retries it instead of // trading on an anchor that was never stored. if(!StateSave()) { g_state.day_id = prevDayId; g_state.e_day0 = prevDay0; g_state.daily_halt = prevHalt; Print("CRITICAL: the daily anchor could not be stored; entries stay disabled"); return false; } PrintFormat("New trading day %04d-%02d-%02d: daily loss anchor set to equity %.2f (cap %.2f%%)", now.year, now.mon, now.day, g_state.e_day0, InpDailyMaxLossPercent); return true; } bool EvaluateEquityGuard() { // Fail closed: an unreadable or inconsistent risk state never authorises entries if(!g_riskStateValid) return false; // R01-H1/H2: a state that could not be made durable is a failed save, and a failed // save never authorises entries until a later verified save clears the latch. if(g_stateStorageFault) return false; if(g_state.static_halt != 0) return false; if(g_state.target_triggered != 0) return false; // The daily anchor must be refreshed BEFORE the daily flag is trusted, otherwise a // halt latched yesterday would block every future day and never clear itself. if(!InitializeDailyAnchor()) return false; if(g_state.daily_halt != 0) return false; const double equity = AccountInfoDouble(ACCOUNT_EQUITY); if(equity <= 0.0) return false; // Static drawdown is measured from the frozen initial balance (C-11) const double staticFloor = g_state.b_init * (1.0 - InpStaticMaxDdPercent / 100.0); if(g_state.b_init > 0.0) { const double staticDd = (g_state.b_init - equity) / g_state.b_init * 100.0; if(equity <= staticFloor) { g_state.static_halt = 1; StateSave(); PrintFormat("STATIC DRAWDOWN CAP HIT: %.2f%% of initial balance %.2f (floor %.2f, cap %.2f%%).", staticDd, g_state.b_init, staticFloor, InpStaticMaxDdPercent); if(InpCloseOnStaticDd) CloseOwnPositions("static drawdown cap"); if(InpStopEaOnStaticDd) { Print("EA detached after the static drawdown cap. Restart manually to trade again."); ExpertRemove(); } return false; } } // Daily loss is measured against the equity recorded at the start of the day if(g_state.daily_halt == 0 && g_state.e_day0 > 0.0) { const double dailyLoss = (g_state.e_day0 - equity) / g_state.e_day0 * 100.0; if(dailyLoss >= InpDailyMaxLossPercent) { g_state.daily_halt = 1; StateSave(); PrintFormat("DAILY LOSS CAP HIT: %.2f%% (cap %.2f%%). No new trades until the next day.", dailyLoss, InpDailyMaxLossPercent); if(InpCloseOnDailyLimit) CloseOwnPositions("daily loss cap"); } } if(g_state.daily_halt != 0) return false; // TARGET_TRIGGERED is a realised result measured on balance, never on floating // equity: a temporary spike must not latch the target while the position reverses. // TARGET_SECURED additionally requires the account to be flat, so the 10 percent // is only claimed once nothing can give it back (G7). const double targetBalance = g_state.b_init * (1.0 + InpEquityGrowthTargetPct / 100.0); const double balance = AccountInfoDouble(ACCOUNT_BALANCE); if(g_state.target_triggered == 0 && targetBalance > 0.0 && balance >= targetBalance) { g_state.target_triggered = 1; StateSave(); PrintFormat("TARGET TRIGGERED: realised balance %.2f >= target %.2f. No new entries.", balance, targetBalance); if(InpCloseOnTarget) CloseOwnPositions("growth target reached"); } if(g_state.target_triggered != 0) { if(g_state.target_secured == 0 && CountOwnPositions() == 0 && balance >= targetBalance) { g_state.target_secured = 1; StateSave(); PrintFormat("TARGET SECURED: account flat at %.2f, target %.2f.", balance, targetBalance); } return false; } return true; } //+------------------------------------------------------------------+ //| Position helpers restricted to this EA | //+------------------------------------------------------------------+ int CountOwnPositions() { int count = 0; const int total = PositionsTotal(); for(int i = 0; i < total; i++) { const ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue; if((long)PositionGetInteger(POSITION_MAGIC) != (long)InpMagicNumber) continue; count++; } return count; } void CloseOwnPositions(const string tag) { for(int i = PositionsTotal() - 1; i >= 0; i--) { const ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue; if((long)PositionGetInteger(POSITION_MAGIC) != (long)InpMagicNumber) continue; if(!g_trade.PositionClose(ticket)) PrintFormat("Close request for #%s failed (%s): %d - %s", IntegerToString((long)ticket), tag, g_trade.ResultRetcode(), RetcodeDescription(g_trade.ResultRetcode())); } } //+------------------------------------------------------------------+ //| Volume sizing with margin and symbol constraints | //+------------------------------------------------------------------+ double CalculateLotSize(const double riskPercent, const double stopDistance) { // Risk is measured on equity so an open drawdown cannot inflate the position double equity = AccountInfoDouble(ACCOUNT_EQUITY); if(equity <= 0.0) equity = AccountInfoDouble(ACCOUNT_BALANCE); if(equity <= 0.0 || stopDistance <= 0.0) return 0.0; const double tickSize = g_tickSize; if(tickSize <= 0.0 || g_volumeStep <= 0.0) return 0.0; double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE_LOSS); if(tickValue <= 0.0) tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); if(tickValue <= 0.0) return 0.0; const double riskMoney = equity * riskPercent / 100.0; const double lossPerLot = (stopDistance / tickSize) * tickValue; if(lossPerLot <= 0.0) return 0.0; double lots = riskMoney / lossPerLot; lots = MathFloor(lots / g_volumeStep + 1e-8) * g_volumeStep; lots = NormalizeDouble(lots, VolumeDigits()); lots = MathMin(lots, g_volumeMax); // Free margin alone is not a risk control: cap the absolute volume as well if(InpMaxLotAbsolute > 0.0 && lots > InpMaxLotAbsolute) { lots = MathFloor(InpMaxLotAbsolute / g_volumeStep + 1e-8) * g_volumeStep; lots = NormalizeDouble(lots, VolumeDigits()); } // Re-validate the money at risk after step rounding and capping if(lots > 0.0 && (lots * lossPerLot) > riskMoney * 1.05) { lots = MathFloor(riskMoney / lossPerLot / g_volumeStep + 1e-8) * g_volumeStep; lots = NormalizeDouble(lots, VolumeDigits()); } if(lots < g_volumeMin) { // The requested risk cannot be expressed with the broker minimum volume if(!InpAllowMinLotOverride) { PrintFormat("Entry skipped: computed volume %.4f is below the minimum %.4f and the override is disabled", lots, g_volumeMin); return 0.0; } lots = g_volumeMin; } const double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); const double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE); double marginRequired = 0.0; if(!OrderCalcMargin(ORDER_TYPE_BUY, _Symbol, lots, ask, marginRequired)) return 0.0; while(marginRequired > freeMargin && lots > g_volumeMin) { lots = NormalizeDouble(lots - g_volumeStep, VolumeDigits()); if(lots < g_volumeMin) return 0.0; if(!OrderCalcMargin(ORDER_TYPE_BUY, _Symbol, lots, ask, marginRequired)) return 0.0; } if(marginRequired > freeMargin) { PrintFormat("Not enough free margin: required %.2f, available %.2f", marginRequired, freeMargin); return 0.0; } return lots; } //+------------------------------------------------------------------+ //| True when the symbol currently has an open trading session | //| Session bounds are published as seconds from the start of the day.| //| If the broker publishes no session table at all the function | //| fails open instead of blocking every entry. | //+------------------------------------------------------------------+ bool IsSessionOpen() { MqlDateTime now; TimeToStruct(TimeCurrent(), now); const long secondsToday = (long)now.hour * 3600 + (long)now.min * 60 + (long)now.sec; bool anySession = false; for(int i = 0; i < 16; i++) { datetime from = 0; datetime to = 0; if(!SymbolInfoSessionTrade(_Symbol, (ENUM_DAY_OF_WEEK)now.day_of_week, (uint)i, from, to)) break; anySession = true; const long start = (long)from; const long end = (long)to; if(end > start) { if(secondsToday >= start && secondsToday < end) return true; } else if(end < start) { // Session runs past midnight if(secondsToday >= start || secondsToday < end) return true; } } return !anySession; } //+------------------------------------------------------------------+ //| Broker stop distance validation | //+------------------------------------------------------------------+ bool StopsAreValid(const int direction, const double entry, const double sl, const double tp) { double minDistance = (double)g_stopsLevel * g_point; const double freezeDistance = (double)g_freezeLevel * g_point; if(freezeDistance > minDistance) minDistance = freezeDistance; if(minDistance <= 0.0) return true; if(direction > 0) { if(sl > 0.0 && (entry - sl) < minDistance) return false; if(tp > 0.0 && (tp - entry) < minDistance) return false; } else { if(sl > 0.0 && (sl - entry) < minDistance) return false; if(tp > 0.0 && (entry - tp) < minDistance) return false; } return true; } //+------------------------------------------------------------------+ //| Risk percentage scaled by signal conviction | //+------------------------------------------------------------------+ double EffectiveRiskPercent(const double score) { const double span = 1.0 - InpMinSignalScore; double normalized = (span > 0.01) ? (score - InpMinSignalScore) / span : 1.0; normalized = MathMax(0.0, MathMin(1.0, normalized)); return InpRiskPercentMin + (InpRiskPercentMax - InpRiskPercentMin) * normalized; } //+------------------------------------------------------------------+ //| Entry execution | //+------------------------------------------------------------------+ bool OpenPosition(const int direction, const double score, const SCandle &trigger) { if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)) { Print("Trading is disabled in the terminal"); return false; } if(!MQLInfoInteger(MQL_TRADE_ALLOWED)) { Print("Trading is disabled for this program"); return false; } if((long)AccountInfoInteger(ACCOUNT_TRADE_EXPERT) == 0) { Print("Automated trading is disabled on the account"); return false; } if((long)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE) != (long)SYMBOL_TRADE_MODE_FULL) { Print("Entry skipped: the symbol is not in full trading mode"); return false; } if(!IsSessionOpen()) { Print("Entry skipped: no trading session is open for this symbol right now"); return false; } const double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); const double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); if(ask <= 0.0 || bid <= 0.0) return false; const double atr = AtrValue(1); if(atr <= 0.0) return false; const double entry = (direction > 0) ? ask : bid; const double buffer = atr * InpStopBufferATR; double sl = 0.0; double tp = 0.0; double stopDistance = 0.0; if(direction > 0) { const double structuralStop = trigger.low - buffer; const double volatilityStop = entry - atr * g_stopAtrMultiplier; sl = MathMin(structuralStop, volatilityStop); sl = NormalizePrice(sl); stopDistance = entry - sl; tp = NormalizePrice(entry + stopDistance * g_rewardRiskRatio); } else { const double structuralStop = trigger.high + buffer; const double volatilityStop = entry + atr * g_stopAtrMultiplier; sl = MathMax(structuralStop, volatilityStop); sl = NormalizePrice(sl); stopDistance = sl - entry; tp = NormalizePrice(entry - stopDistance * g_rewardRiskRatio); } sl = NormalizePrice(sl); tp = NormalizePrice(tp); stopDistance = MathAbs(entry - sl); if(stopDistance <= 0.0) { Print("Entry rejected: stop distance is zero after normalization"); return false; } if(!StopsAreValid(direction, entry, sl, tp)) { PrintFormat("Entry rejected: stop distance %.5f is below the broker minimum", stopDistance); return false; } const double riskPercent = EffectiveRiskPercent(score); const double lots = CalculateLotSize(riskPercent, stopDistance); if(lots <= 0.0) { Print("Entry rejected: position size cannot be calculated"); return false; } const bool sent = (direction > 0) ? g_trade.Buy(lots, _Symbol, 0.0, sl, tp, InpTradeComment) : g_trade.Sell(lots, _Symbol, 0.0, sl, tp, InpTradeComment); const uint retcode = g_trade.ResultRetcode(); // A market request must be filled, an accepted pending order is not an entry const bool filled = (retcode == TRADE_RETCODE_DONE || retcode == TRADE_RETCODE_DONE_PARTIAL); if(!sent || !filled) { PrintFormat("Order rejected: %d - %s", retcode, RetcodeDescription(retcode)); return false; } g_lastEntryTime = TimeCurrent(); const string side = (direction > 0) ? "BUY" : "SELL"; PrintFormat("%s opened on %s: volume %.2f, risk %.2f%%, score %.2f, SL %.5f, TP %.5f, ATR %.5f", side, _Symbol, lots, riskPercent, score, sl, tp, atr); return true; } //+------------------------------------------------------------------+ //| Breakeven and ATR trailing for EA-owned positions | //+------------------------------------------------------------------+ void ManageOpenPositions() { if(!InpUseBreakeven && !InpUseAtrTrailing) return; const double atr = AtrValue(1); if(atr <= 0.0) return; const double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); const double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); if(bid <= 0.0 || ask <= 0.0) return; double minDistance = (double)g_stopsLevel * g_point; if(minDistance < 10.0 * g_point) minDistance = 10.0 * g_point; for(int i = PositionsTotal() - 1; i >= 0; i--) { const ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue; if((long)PositionGetInteger(POSITION_MAGIC) != (long)InpMagicNumber) continue; const long type = PositionGetInteger(POSITION_TYPE); const double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); const double currentSl = PositionGetDouble(POSITION_SL); const double currentTp = PositionGetDouble(POSITION_TP); double targetSl = currentSl; if(type == (long)POSITION_TYPE_BUY) { if(InpUseBreakeven && bid >= openPrice + atr * InpBreakevenTriggerATR) { const double candidate = openPrice + InpBreakevenOffsetPts * g_point; if(currentSl <= 0.0 || candidate > targetSl) targetSl = candidate; } if(InpUseAtrTrailing) { const double candidate = bid - atr * InpTrailAtrMultiplier; if(currentSl <= 0.0 || candidate > targetSl) targetSl = candidate; } targetSl = NormalizePrice(targetSl); if(targetSl <= 0.0) continue; if(currentSl > 0.0 && targetSl <= currentSl) continue; if((bid - targetSl) < minDistance) continue; } else if(type == (long)POSITION_TYPE_SELL) { if(InpUseBreakeven && ask <= openPrice - atr * InpBreakevenTriggerATR) { const double candidate = openPrice - InpBreakevenOffsetPts * g_point; if(currentSl <= 0.0 || candidate < targetSl) targetSl = candidate; } if(InpUseAtrTrailing) { const double candidate = ask + atr * InpTrailAtrMultiplier; if(currentSl <= 0.0 || candidate < targetSl) targetSl = candidate; } targetSl = NormalizePrice(targetSl); if(targetSl <= 0.0) continue; if(currentSl > 0.0 && targetSl >= currentSl) continue; if((targetSl - ask) < minDistance) continue; } else { continue; } if(MathAbs(targetSl - currentSl) < InpTrailStepPoints * g_point) continue; if(!g_trade.PositionModify(ticket, targetSl, currentTp)) PrintFormat("Modify request for #%s failed: %d - %s", IntegerToString((long)ticket), g_trade.ResultRetcode(), RetcodeDescription(g_trade.ResultRetcode())); } } //+------------------------------------------------------------------+ //| On-chart status | //+------------------------------------------------------------------+ void UpdateDashboard() { if(!InpShowDashboard) return; // The chart label is diagnostic only: one refresh per second is enough static datetime lastRefresh = 0; const datetime now = TimeCurrent(); if(now == lastRefresh) return; lastRefresh = now; const double balance = AccountInfoDouble(ACCOUNT_BALANCE); const double equity = AccountInfoDouble(ACCOUNT_EQUITY); const double dailyPct = (g_state.e_day0 > 0.0) ? (equity - g_state.e_day0) / g_state.e_day0 * 100.0 : 0.0; const double staticDd = (g_state.b_init > 0.0) ? (g_state.b_init - equity) / g_state.b_init * 100.0 : 0.0; const double targetBalance = g_state.b_init * (1.0 + InpEquityGrowthTargetPct / 100.0); const double targetProgress = (targetBalance > g_state.b_init) ? (equity - g_state.b_init) / (targetBalance - g_state.b_init) * 100.0 : 0.0; string status = "ACTIVE"; if(!g_riskStateValid) status = "STOPPED - risk state invalid"; else if(g_stateStorageFault) status = "STOPPED - risk state storage fault"; else if(g_state.static_halt) status = "STOPPED - static drawdown cap"; else if(g_state.daily_halt) status = "PAUSED - daily loss cap"; else if(g_state.target_secured) status = "STOPPED - target secured"; else if(g_state.target_triggered) status = "STOPPED - target triggered, closing"; string text = ""; text += "Candle Pressure EA | " + _Symbol + " " + EnumToString(InpWorkTimeframe) + "\n"; text += "Status: " + status + "\n"; text += StringFormat("Equity %.2f | Balance %.2f\n", equity, balance); text += StringFormat("Day result %.2f%% (cap %.1f%%)\n", dailyPct, InpDailyMaxLossPercent); text += StringFormat("Static drawdown %.2f%% (cap %.1f%%)\n", staticDd, InpStaticMaxDdPercent); text += StringFormat("Target balance %.2f (%.1f%%)\n", targetBalance, targetProgress); text += StringFormat("Risk archive slot %s | sequence %I64u\n", (g_stateSlot == CP_SLOT_A ? "A" : "B"), g_state.seq); text += StringFormat("Open positions %d of %d\n", CountOwnPositions(), InpMaxOpenPositions); Comment(text); } //+------------------------------------------------------------------+ //| Expert initialization | //+------------------------------------------------------------------+ int OnInit() { // --- Input validation ------------------------------------------ if(InpStopAtrMultiplier <= 0.0 || InpRewardRiskRatio <= 0.0 || InpStopBufferATR < 0.0) { Print("Invalid input: stop distance and reward to risk must be positive, the stop buffer cannot be negative"); return INIT_PARAMETERS_INCORRECT; } if(InpAtrPeriod < 2 || (InpUseAdxFilter && InpAdxPeriod < 2)) { Print("Invalid input: the ATR and ADX periods must be at least 2"); return INIT_PARAMETERS_INCORRECT; } if(InpMinBarsBetweenTrades < 0) { Print("Invalid input: the minimum bars between trades cannot be negative"); return INIT_PARAMETERS_INCORRECT; } if(InpSweepLookback < 1 || InpSweepDepth < 2) { Print("Invalid input: the sweep window must be at least 1 bar and the sweep depth at least 2 bars"); return INIT_PARAMETERS_INCORRECT; } if(InpBosConfirmBars < 1) { Print("Invalid input: the break of structure confirmation window must be at least 1 bar"); return INIT_PARAMETERS_INCORRECT; } if(InpDailyMaxLossPercent <= 0.0 || InpDailyMaxLossPercent > 50.0) { Print("Invalid input: daily maximum loss must be between 0 and 50 percent"); return INIT_PARAMETERS_INCORRECT; } if(InpStaticMaxDdPercent <= 0.0 || InpStaticMaxDdPercent > 50.0) { Print("Invalid input: static maximum drawdown must be between 0 and 50 percent"); return INIT_PARAMETERS_INCORRECT; } if(InpEquityGrowthTargetPct <= 0.0 || InpEquityGrowthTargetPct > 1000.0) { Print("Invalid input: equity growth target must be between 0 and 1000 percent"); return INIT_PARAMETERS_INCORRECT; } if(InpRiskPercentMin <= 0.0 || InpRiskPercentMax < InpRiskPercentMin) { Print("Invalid input: risk range is inconsistent"); return INIT_PARAMETERS_INCORRECT; } if(InpMinSignalScore < 0.10 || InpMinSignalScore > 1.0) { Print("Invalid input: minimum signal score must be between 0.10 and 1.00"); return INIT_PARAMETERS_INCORRECT; } if(InpSwingLookback < 3 || InpRangeLookback < 10 || InpZoneLookback < 4) { Print("Invalid input: context lookbacks are too small"); return INIT_PARAMETERS_INCORRECT; } if(InpHtfTimeframe <= InpWorkTimeframe) { Print("Invalid input: the higher timeframe must be larger than the signal timeframe"); return INIT_PARAMETERS_INCORRECT; } if(InpMaxOpenPositions < 1) { Print("Invalid input: at least one position must be allowed"); return INIT_PARAMETERS_INCORRECT; } if(StringLen(InpRiskScopeId) == 0 || StringLen(InpRiskPeriodId) == 0) { Print("Invalid input: the risk scope id and the risk period id must not be empty"); return INIT_PARAMETERS_INCORRECT; } // --- Instrument recognition ----------------------------------- string symbolName = _Symbol; StringToUpper(symbolName); g_isGold = (StringFind(symbolName, "XAU") >= 0 || StringFind(symbolName, "GOLD") >= 0); g_isSilver = (StringFind(symbolName, "XAG") >= 0 || StringFind(symbolName, "SILVER") >= 0); g_stopAtrMultiplier = InpStopAtrMultiplier; g_rewardRiskRatio = InpRewardRiskRatio; g_rangeLookback = InpRangeLookback; if(g_isGold && InpUseGoldProfile) { g_stopAtrMultiplier = InpGoldStopAtrMult; g_rewardRiskRatio = InpGoldRewardRisk; g_rangeLookback = InpGoldRangeLookback; } else if(g_isSilver && InpUseSilverProfile) { g_stopAtrMultiplier = InpSilverStopAtrMult; g_rewardRiskRatio = InpSilverRewardRisk; g_rangeLookback = InpSilverRangeLookback; } // --- Symbol geometry ------------------------------------------ g_digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS); g_point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); g_tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); g_volumeMin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); g_volumeMax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); g_volumeStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); g_stopsLevel = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL); g_freezeLevel = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL); if(g_point <= 0.0 || g_digits <= 0) { Print("Symbol geometry is not available yet"); return INIT_FAILED; } if(g_tickSize <= 0.0) g_tickSize = g_point; if(g_volumeStep <= 0.0) g_volumeStep = g_volumeMin; // A broker can publish a per-order volume limit below the symbol maximum const double volumeLimit = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_LIMIT); if(volumeLimit > 0.0 && volumeLimit < g_volumeMax) g_volumeMax = volumeLimit; // --- History requirement -------------------------------------- g_historyBars = g_rangeLookback + InpSwingLookback + InpBosConfirmBars + InpZoneLookback + InpSweepLookback + InpSweepDepth + 30; if(g_historyBars < InpRangeLookback + InpSwingLookback + InpBosConfirmBars + 30) g_historyBars = InpRangeLookback + InpSwingLookback + InpBosConfirmBars + 30; // --- Indicator handles ---------------------------------------- g_htfEmaHandle = iMA(_Symbol, InpHtfTimeframe, InpHtfEmaPeriod, 0, MODE_EMA, PRICE_CLOSE); g_atrHandle = iATR(_Symbol, InpWorkTimeframe, InpAtrPeriod); g_adxHandle = InpUseAdxFilter ? iADX(_Symbol, InpWorkTimeframe, InpAdxPeriod) : INVALID_HANDLE; if(g_htfEmaHandle == INVALID_HANDLE || g_atrHandle == INVALID_HANDLE) { PrintFormat("Failed to create indicator handles, error %d", GetLastError()); return INIT_FAILED; } if(InpUseAdxFilter && g_adxHandle == INVALID_HANDLE) { PrintFormat("Failed to create the ADX handle, error %d", GetLastError()); return INIT_FAILED; } // --- Trade object --------------------------------------------- g_trade.SetExpertMagicNumber((ulong)InpMagicNumber); g_trade.SetDeviationInPoints(20); g_trade.SetTypeFillingBySymbol(_Symbol); g_trade.SetAsyncMode(false); // --- Equity baselines and persistent risk state ----------------- const double liveBalance = AccountInfoDouble(ACCOUNT_BALANCE); if(liveBalance <= 0.0) { Print("Account balance is not available yet"); return INIT_FAILED; } // R01-H4: make the risk identity explicit in the journal before any state decision PrintFormat("Risk identity %016I64X: login %I64d, server '%s', scope '%s', period '%s', magic %I64d, %s %s", StateIdentity(), AccountInfoInteger(ACCOUNT_LOGIN), AccountInfoString(ACCOUNT_SERVER), InpRiskScopeId, InpRiskPeriodId, InpMagicNumber, _Symbol, EnumToString(InpWorkTimeframe)); if(!StatePersistenceEnabled()) { // Tester isolation: every run must start from its own deposit StateInitFresh(); g_stateSlot = CP_SLOT_A; g_stateSlotKnown = false; g_riskStateValid = true; g_stateStorageFault = false; StateSave(); Print("Tester mode: risk state is deliberately not persisted between runs."); } else { // R-01 v1.2 provisioning state machine and recovery decision table const int initResult = StateProvisionOrRestore(); if(initResult == CP_INIT_FAILED) return INIT_FAILED; if(initResult == CP_INIT_DENIED) { // The EA stays loaded, but g_riskStateValid keeps every entry path closed g_riskStateValid = false; g_stateStorageFault = false; } } if(g_riskStateValid) { if(g_state.daily_halt != 0) Print("Restored state: daily loss cap already hit today, trading stays paused"); if(g_state.static_halt != 0) Print("Restored state: static drawdown cap already hit, trading stays stopped"); if(g_state.target_triggered != 0) Print("Restored state: growth target already reached, trading stays stopped"); } g_lastBarTime = 0; g_lastEntryTime = 0; if(g_riskStateValid && !InitializeDailyAnchor()) Print("CRITICAL: the daily anchor could not be stored; entries stay disabled"); // --- Diagnostics ---------------------------------------------- PrintFormat("Candle Pressure EA initialized on %s (%s), higher timeframe %s", _Symbol, EnumToString(InpWorkTimeframe), EnumToString(InpHtfTimeframe)); if(g_riskStateValid) PrintFormat("Baselines: initial balance %.2f, initial equity %.2f, target balance %.2f", g_state.b_init, g_state.e_init, g_state.b_init * (1.0 + InpEquityGrowthTargetPct / 100.0)); PrintFormat("Hard limits: daily loss %.2f%%, static drawdown %.2f%%", InpDailyMaxLossPercent, InpStaticMaxDdPercent); PrintFormat("Stop distance %.2f ATR, reward to risk %.2f, dealing range %d bars", g_stopAtrMultiplier, g_rewardRiskRatio, g_rangeLookback); if(g_isGold) Print("Gold profile active"); else if(g_isSilver) Print("Silver profile active"); else Print("No metal profile matched, generic parameters are used"); if((long)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE) != (long)SYMBOL_TRADE_MODE_FULL) Print("Warning: the symbol is not in full trading mode"); UpdateDashboard(); return INIT_SUCCEEDED; } //+------------------------------------------------------------------+ //| Expert deinitialization | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { if(g_htfEmaHandle != INVALID_HANDLE) IndicatorRelease(g_htfEmaHandle); if(g_atrHandle != INVALID_HANDLE) IndicatorRelease(g_atrHandle); if(g_adxHandle != INVALID_HANDLE) IndicatorRelease(g_adxHandle); g_htfEmaHandle = INVALID_HANDLE; g_atrHandle = INVALID_HANDLE; g_adxHandle = INVALID_HANDLE; Comment(""); if(reason == REASON_REMOVE) Print("Candle Pressure EA removed from the chart"); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { const bool tradingAllowed = EvaluateEquityGuard(); ManageOpenPositions(); UpdateDashboard(); if(!tradingAllowed) return; // Signals are evaluated once per closed bar const datetime barTime = iTime(_Symbol, InpWorkTimeframe, 0); if(barTime == 0) return; if(barTime == g_lastBarTime) return; // Gates that can clear inside the same bar must not consume the bar. Marking the bar // before them discarded every signal that appeared while the spread was wide or a // position was still open, which is exactly what happens at the daily rollover. if(CountOwnPositions() >= InpMaxOpenPositions) return; if(g_lastEntryTime > 0 && (TimeCurrent() - g_lastEntryTime) < (long)InpMinBarsBetweenTrades * PeriodSeconds(InpWorkTimeframe)) return; const double spreadPoints = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / g_point; if(spreadPoints > InpMaxSpreadPoints) { // Throttled because this path is now retried on every tick of the same bar static datetime lastSpreadLog = 0; if(TimeCurrent() - lastSpreadLog >= 60) { lastSpreadLog = TimeCurrent(); PrintFormat("Entry delayed: spread %.1f points exceeds the limit %.1f, retrying on the next tick", spreadPoints, InpMaxSpreadPoints); } return; } // The bar is consumed only once the signal engine actually runs g_lastBarTime = barTime; double score = 0.0; SCandle trigger; const int direction = DetectSignal(score, trigger); if(direction == 0) return; OpenPosition(direction, score, trigger); } //+------------------------------------------------------------------+ //| Trade transaction log for EA-owned deals | //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result) { if(trans.type != TRADE_TRANSACTION_DEAL_ADD) return; if(!HistoryDealSelect(trans.deal)) return; if((long)HistoryDealGetInteger(trans.deal, DEAL_MAGIC) != (long)InpMagicNumber) return; if(HistoryDealGetString(trans.deal, DEAL_SYMBOL) != _Symbol) return; if((long)HistoryDealGetInteger(trans.deal, DEAL_ENTRY) == (long)DEAL_ENTRY_IN) return; const double net = HistoryDealGetDouble(trans.deal, DEAL_PROFIT) + HistoryDealGetDouble(trans.deal, DEAL_SWAP) + HistoryDealGetDouble(trans.deal, DEAL_COMMISSION); if(net != 0.0) PrintFormat("Deal #%s closed with a net result of %.2f", IntegerToString((long)trans.deal), net); } //+------------------------------------------------------------------+