Skip to main content

risk-engine

Indestructible risk management for MQL5 EAs. Use for: position sizing (fixed %, ATR-based, volatility-scaled, half-Kelly); daily and total drawdown guards; equity-stop implementation; configurable prop firm rule sets; consecutive loss tracking with auto-risk reduction; correlation-based exposure limits; and any "how do I protect the account" question. This module is always Layer 1 — the first gate before any trade. Trigger: "position size", "lot size", "drawdown", "risk", "prop firm", "daily loss limit", "max DD", "equity stop", "Kelly", "correlation risk", "exposure", "account protection", "halt trading".

v1.0.0New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, or use the command that detects it for you.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install metatrader-risk-engine
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/metatrader-risk-engine/SKILL.md

Setup guide →
0Save

Instructions

Risk Engine

The risk engine is the most critical module. All trade execution is gated
through it. If risk fails, everything fails. Never bypass this layer.


Purpose

Defines Layer 1 of the 5-layer EA architecture: capital preservation through
drawdown limits, position sizing, consecutive-loss protection, and configurable
rule-set support for prop firm challenges. Every trade must pass through
IsTradeAllowed() before any other layer runs.


When to Use

  • Writing or reviewing any EA that manages real positions
  • Configuring an EA for a prop firm challenge
  • Diagnosing why an EA blew a funded account (usually missing this layer)
  • Implementing Kelly or volatility-scaled position sizing
  • Looking up order/position/deal property identifiers

Do NOT use for:

  • Post-entry trade management → use trade-manager
  • Market regime filtering → use market-regime
  • Multi-asset correlation books → use multi-asset
  • EA architecture / module wiring → use ea-architect

Core Guidance

CRiskManager Architecture

The risk manager gates every trade through drawdown checks, halts trading
when limits are breached, and auto-reduces risk after losses or near limits.

class CRiskManager : public IModule {
private:
   double   m_riskPercent;
   double   m_maxDailyDD;
   double   m_maxTotalDD;
   double   m_dayStartBalance;
   double   m_peakBalance;
   bool     m_haltTrading;
   bool     m_reducedMode;
   int      m_consecutiveLosses;
   datetime m_lastDayReset;

public:
   CRiskManager(double riskPct, double maxDailyDD, double maxTotalDD) {
      m_riskPercent = riskPct; m_maxDailyDD = maxDailyDD; m_maxTotalDD = maxTotalDD;
      m_dayStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
      m_peakBalance = m_dayStartBalance;
      m_haltTrading = false; m_reducedMode = false;
      m_consecutiveLosses = 0; m_lastDayReset = TimeCurrent();
   }
   bool   IsReady()   { return true; }
   void   Reset()     { DailyReset(); }
   bool   IsHalted()  { return m_haltTrading; }
   bool   IsReduced() { return m_reducedMode; }
   string GetStatus() { /* daily/total DD strings */ }
};

Drawdown Guards

void DailyReset() {
   MqlDateTime now, last;
   TimeToStruct(TimeCurrent(), now);
   TimeToStruct(m_lastDayReset, last);
   if(now.day != last.day) {
      m_dayStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
      m_haltTrading = false; m_reducedMode = false;
      m_consecutiveLosses = 0;
      m_lastDayReset = TimeCurrent();
   }
}

bool IsTradeAllowed() {
   DailyReset();
   if(m_haltTrading) return false;
   double balance = AccountInfoDouble(ACCOUNT_BALANCE);
   double equity  = AccountInfoDouble(ACCOUNT_EQUITY);
   if(balance > m_peakBalance) m_peakBalance = balance;
   double dailyDD = (m_dayStartBalance - equity) / m_dayStartBalance * 100.0;
   if(dailyDD >= m_maxDailyDD) {
      m_haltTrading = true;
      Alert("DAILY DD LIMIT HIT — trading halted. DD: ", DoubleToString(dailyDD, 2), "%");
      return false;
   }
   m_reducedMode = (dailyDD >= m_maxDailyDD * 0.6);
   double totalDD = (m_peakBalance - equity) / m_peakBalance * 100.0;
   if(totalDD >= m_maxTotalDD) {
      m_haltTrading = true;
      Alert("TOTAL DD LIMIT HIT — trading halted. DD: ", DoubleToString(totalDD, 2), "%");
      return false;
   }
   return true;
}

Prop Firm Rule Set (Configurable Struct)

Prop firm rules use a generic struct loaded from configuration. Concrete
presets live in references/prop-firm-presets.md.

struct PropFirmRules {
   double daily_dd_limit;
   double total_dd_limit;
   double halt_daily_buffer;   // EA halts this % before the hard limit
   double halt_total_buffer;
   bool   no_weekend_hold;
   bool   news_restricted;
   int    min_trading_days;
};

PropFirmRules LoadDefaultRules() {
   PropFirmRules r = {};
   r.daily_dd_limit    = 5.0;   // set per firm from presets
   r.total_dd_limit    = 10.0;
   r.halt_daily_buffer = 1.0;   // stays below the configured hard limit
   r.halt_total_buffer = 2.0;
   r.no_weekend_hold   = false;
   r.news_restricted   = false;
   r.min_trading_days  = 0;
   return r;
}

Use in IsTradeAllowed():

if((equity_peak - equity) / equity_peak * 100.0 >= total_dd_limit - halt_total_buffer)
   HaltTrading("Close to total DD limit");

Consecutive Loss Tracking

void RecordTradeResult(bool isWin) {
   if(isWin) {
      m_consecutiveLosses = 0;
      if(m_reducedMode && GetDailyDD() < m_maxDailyDD * 0.3)
         m_reducedMode = false;
   } else {
      m_consecutiveLosses++;
      if(m_consecutiveLosses >= 3) m_reducedMode = true;
      if(m_consecutiveLosses >= 6) {
         m_haltTrading = true;
         Alert("6 consecutive losses — halting EA for review.");
      }
   }
}

Correlation-Based Exposure Guard

bool IsCorrelatedPositionOpen(string sym1, string sym2, int magic) {
   for(int i = 0; i < PositionsTotal(); i++) {
      if(!PositionGetTicket(i)) continue;
      string s = PositionGetString(POSITION_SYMBOL);
      long   m = PositionGetInteger(POSITION_MAGIC);
      if(m != magic) continue;
      if(s == sym1 || s == sym2) return true;
   }
   return false;
}

Code Patterns — Position Sizing

Method 1: Fixed Percentage Risk (default)

double CalculateLotSize(double slDistancePoints) {
   if(slDistancePoints <= 0) return 0;
   double effectiveRisk = m_reducedMode ? m_riskPercent * 0.5 : m_riskPercent;
   double balance    = AccountInfoDouble(ACCOUNT_BALANCE);
   double riskAmount = balance * effectiveRisk / 100.0;
   double tickValue  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tickSize   = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double lotStep    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double minLot     = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot     = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double riskPerLot = slDistancePoints * (tickValue / tickSize);
   if(riskPerLot <= 0) return 0;
   double rawLot  = riskAmount / riskPerLot;
   double lotSize = MathFloor(rawLot / lotStep) * lotStep;
   return MathMax(minLot, MathMin(maxLot, lotSize));
}

Method 2: ATR-Based Dynamic SL

double atr = iATR(_Symbol, PERIOD_H1, 14, 1);
double slPoints = atr * 1.5 / _Point;
double lots = CalculateLotSize(slPoints);

Method 3: Volatility-Scaled Risk

double currentATR  = iATR(_Symbol, PERIOD_H1, 14, 1);
double historicATR = iATR(_Symbol, PERIOD_H1, 14, 20);
double volRatio    = currentATR / historicATR;
double adjustedRisk = MathMax(0.25, MathMin(m_riskPercent, m_riskPercent / volRatio));

Method 4: Half-Kelly Criterion

Kelly% = WinRate - (1 - WinRate) / AvgWin_AvgLoss_Ratio
Half-Kelly = Kelly% / 2
Example: 55% WR, 1.8 RR -> Kelly = 0.55 - (0.45/1.8) = 0.30 -> use 15%

Common Mistakes

  • Bypassing risk for "quick" trades — every trade must pass IsTradeAllowed().
    Skipping it even once defeats the layer.
  • Hardcoding tick value assumptions — SYMBOL_TRADE_TICK_VALUE and
    SYMBOL_TRADE_TICK_SIZE differ per symbol. Read at runtime.
  • Using ACCOUNT_BALANCE for intraday DD — balance only changes on settled
    trades; use equity for true intraday drawdown.
  • Full Kelly instead of half-Kelly — full Kelly is too aggressive for
    sequential trading; half-Kelly preserves capital during drawdowns.
  • Not resetting daily limits after a new trading day — DailyReset() must
    run on the first tick of each new day or the DD accumulator holds stale values.

References

FileContentsRead when
references/live-execution-safety.mdBridge-agnostic governance rules for live trading: per-action confirmation, demo-first, no credential harvesting, no mass action, surface account identityGoverning agent-driven or programmatic trade execution on live accounts
references/prop-firm-presets.mdConcrete daily/total DD limits for common prop firm challenges, weekend/news restrictions, minimum trading daysSetting up EA for a specific prop firm evaluation; verifying current limits
references/order-property-enums.mdENUM_ORDER_PROPERTY_*, ENUM_ORDER_TYPE, ENUM_ORDER_STATE, ENUM_ORDER_TYPE_FILLING, filling compatibility matrix, ENUM_ORDER_TYPE_TIMEReading/writing order properties; choosing fill policy
references/position-property-enums.mdENUM_POSITION_PROPERTY_*, ENUM_POSITION_TYPE, ENUM_POSITION_REASONReading open position state; iterating positions
references/deal-property-enums.mdENUM_DEAL_PROPERTY_*, ENUM_DEAL_TYPE (19 values), ENUM_DEAL_ENTRY, ENUM_DEAL_REASONAnalysing deal history; filtering P&L by deal type
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
market-regimeMarket regime detection and filtering for MQL5 EAs. Use for all logic that determines WHETHER to trade: trend vs range classification via ADX; volatility regime via ATR (high/normal/reduced); session filtering (London/NY/Asian killzones); news event avoidance; spread spike detection; weekend and holiday blocking. This is Layer 2 — signals are never generated without passing through regime first. Trigger: "market regime", "trending vs ranging", "session filter", "news filter", "volatility filter", "spread filter", "when to trade", "ATR regime", "ADX trend strength", "killzone", "dead zone", "regime detection", "Layer 2".0 installsstdlib-utilitiesMQL4/MQL5 language and runtime utilities reference skill. Use for: magic number isolation; OrderSend retry logic; .set file parameter presets; MQL4 vs MQL5 differences; file I/O and sandbox rules; string manipulation; array operations; date/time functions; terminal global variables; SQLite database access; runtime error codes; type conversion; matrix/vector stubs. Trigger: "magic number", "OrderSend retry", ".set file", "MQL4 vs MQL5", "file I/O", "string functions", "array functions", "date and time", "global variables", "database", "type conversion", "runtime error", "MqlDateTime", "terminal global".0 installstrade-managerPost-entry trade lifecycle management for MQL5 EAs. Use for: ATR-based, swing-based, and chandelier trailing stops; breakeven logic; partial close and scale-out strategies; multi-target take profit; position scaling (pyramiding); trade modification via CTrade; managing multiple open positions; OrderSend/OrderSendAsync retcode handling; position, order, and history iteration APIs; pre-trade margin and profit calculation; standard-library trade wrapper classes (CTrade, CPositionInfo, COrderInfo, CDealInfo, CSymbolInfo, CAccountInfo). Trigger: "trailing stop", "breakeven", "partial close", "scale out", "pyramiding", "take profit", "manage positions", "move SL", "CTrade", "position management", "trade modification", "multi-target TP", "trail", "BE", "OrderSend", "OrderCheck".0 installssignal-engineEntry and exit signal generation for MQL5 EAs. Use for: STradeSignal contract design; signal generation flow with confluence scoring (min 2 factors); SMC/ICT concepts (Order Blocks, Fair Value Gaps, CHoCH, BoS, liquidity sweeps); multi-timeframe analysis; technical indicator handles (ATR, EMA, RSI, ADX, MACD, Bollinger); candlestick pattern detection; breakout and mean reversion entries; multi-asset signal profiles; MQL5 Signals subscription API. Every signal requires minimum 2 confluence factors. Pair with market-regime to gate signals by market state. Trigger: "entry logic", "signal", "Order Block", "FVG", "CHoCH", "SMC", "ICT", "buy signal", "sell signal", "confluence", "indicator", "pattern", "liquidity sweep", "signal engine".0 installsimported-backtestHandles importing MT5 Strategy Tester HTML reports uploaded by users as first-class backtest results. Covers parsing via the canonical ReportParser, equity reconstruction from broker or Darwinex fallback price data, broker server resolution, and integrating imported results into comparison and analysis pipelines. Use for: uploading .htm reports from external MT5 sessions; reconstructing equity curves when no live terminal is available; making imported tests indistinguishable from native runs. Trigger on: "import backtest", "upload HTML report", "imported test", "import report".0 installseconomic-calendarMQL5 economic calendar API reference skill. Use for: querying calendar countries or events; looking up calendar metadata by id, country, or currency code; retrieving historical or latest economic values; incremental polling with change_id for efficient live filters; wiring calendar-based trade-blocking logic into Expert Advisors. Trigger: "CalendarCountries", "CalendarEventById", "CalendarValueHistory", "CalendarValueLast", "economic calendar", "calendar filter", "news filter", "CalendarEventByCountry", "CalendarValueHistoryByEvent", "change_id".0 installs

More from MetaTrader Skills

View source →
multi-assetMulti-asset and multi-pair EA management for MQL5. Use for all logic involving trading more than one instrument: per-symbol configuration profiles (SSymbolConfig struct); 17 pre-built asset profiles across forex, metals, indices, and crypto CFDs; portfolio-level risk with correlation group limits; CMultiAssetManager class for position discovery, group counting, and total-risk enforcement; magic number assignment per symbol; multi-symbol OnTick architecture that processes each symbol independently. Trigger: "multi-pair", "portfolio EA", "multiple symbols", "all pairs", "forex and gold", "symbol manager", "asset class", "per-pair settings", "correlation management", "basket trading", "run on all symbols", "trade everything", "SymbolInfoInteger", "SymbolSelect".0 installsfintech-web-systemsElite TypeScript/React fintech and trading systems engineering skill. Use for ALL web-based trading infrastructure: decimal-safe money arithmetic, core trading metric implementations (Sharpe, Calmar, Drawdown, Profit Factor), real-time WebSocket market data feeds using Cloudflare Durable Objects, React hooks for live prices, trading dashboard UI components (PriceTicker, OrderBook), and OHLCV data ingestion pipelines. Precision is non-negotiable — never approximate money calculations. Trigger on: "trading dashboard", "live prices", "WebSocket feed", "order book", "price ticker", "OHLCV ingestion", "Sharpe Ratio TypeScript", "money arithmetic", "Decimal library", "profit factor", "fintech frontend". Note: For MQL5 EA implementations, use the mql5-* skills instead.0 installsplatformMetaTrader 5 platform operations reference skill. Use for: installing MT5 on Windows/macOS/Linux; configuring startup modes and CLI keys; managing SSL certificates and 2FA/TOTP; understanding file/folder layout; managing accounts and transfers; reading platform logs, Task Manager, and live update behaviour; keyboard shortcuts; chart analysis workspace and templates; trading UI, DOM, Market Watch, margin models; platform drawing objects; custom symbols; MQL5 chart operations API; MQL5 object API. For MQL5 constants, use the constants skill. For the Python module, use the python skill. For the HTTP bridge, use the httpapi skill.0 installsjournal-monitorParse MT5 terminal journal logs (JournalLog-*.log) and surface execution anomalies — connection drops, slow fills, slow SL/TP modifies, failed orders, and fast SL hits — across one or many broker accounts. Trigger this skill whenever the user asks to analyse, compare, or monitor MT5 journals; investigate broker execution quality; compare latency or drops across brokers; set up nightly journal monitoring or alerts; debug why an EA performed differently on different accounts; or uploads files named JournalLog-<account>-<date>.log. Also trigger when the user mentions MT5 journal logs, broker execution quality, connection drops, slow fills, or fast SL hits, even if they do not explicitly say "journal".0 installspythonMetaTrader 5 Python package (MetaTrader5 module) integration. Use for: connecting Python code to a local MT5 terminal; initialising and shutting down sessions; reading account, terminal, symbol, tick, rate, order, position, and deal data; calculating margin or profit; validating and sending trade requests; building pandas-based MT5 data workflows; converting MT5 responses into DataFrame-friendly structures. Trigger: "MetaTrader5", "MT5 Python", "python mt5", "initialize MT5", "mt5 login", "mt5 order_send", "mt5 copy_rates", "mt5 account info", "pandas mt5", "mt5 symbol select".0 installsea-architectMaster MQL5 Expert Advisor architecture reference. Use for: wiring the 5-layer EA model (risk, regime, signal, trade mgmt, analytics); writing OnInit/OnTick/OnDeinit event handlers; setting up IsNewBar gating; designing include file layouts and .mqh module interfaces; applying naming conventions across all EA files; reading symbol properties in a broker-agnostic way; and integrating CExpert/CExpertSignal/CExpertMoney standard-library classes. Trigger: "5-layer architecture", "module wiring", "OnInit", "OnTick", "IsNewBar", "include files", "mqh", "CExpert", "event handlers", "EA template", "naming conventions", "broker-agnostic", "symbol data access".0 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.635 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.535 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.346 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.246 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.173 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions145 installs

Frequently asked questions about risk-engine

What does the risk-engine skill do?

Indestructible risk management for MQL5 EAs. Use for: position sizing (fixed %, ATR-based, volatility-scaled, half-Kelly); daily and total drawdown guards; equity-stop implementation; configurable prop firm rule sets; consecutive loss tracking with auto-risk reduction; correlation-based exposure limits; and any "how do I protect the account" question. This module is always Layer 1 — the first gate before any trade. Trigger: "position size", "lot size", "drawdown", "risk", "prop firm", "daily loss limit", "max DD", "equity stop", "Kelly", "correlation risk", "exposure", "account protection", "halt trading". It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the risk-engine skill?

Run `npx @skills-hub-ai/cli install metatrader-risk-engine` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/metatrader-risk-engine/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does risk-engine work with?

risk-engine runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the risk-engine skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use risk-engine after installing it?

In Claude Code, type `/metatrader-risk-engine` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the risk-engine skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.