MQL5 Algo Trading
555K subscribers
4.07K photos
6 videos
4.07K links
The best publications of the largest community of algotraders.

Subscribe to stay up-to-date with modern technologies and trading programs development.
Download Telegram
This part closes a common gap in MT5 EAs: risk-based position sizing can still generate lots the account cannot margin, especially when ATR stops get tight and computed volume rises. Risk (loss at stop) and margin (capital locked at entry) are independent constraints, and ignoring margin leads to rejected orders or trades that consume nearly all free margin.

The fix adds a margin-aware lot cap using OrderCalcMargin() to price 1 lot, then converts free margin into a broker-valid maximum volume with step-aware rounding. If even the minimum lot exceeds the cap, the trade is skipped; otherwise the risk-based lot is reduced.

An optional adaptive layer scales the cap by ACCOUNT_MARGIN_LEVEL, tightening exposure as margin level deteriorates and blocking new trades below a danger threshold.

Finally, checks are consolidated into a named pre-trade validation gate (pos...

πŸ‘‰ Read | CodeBase | @mql5dev
❀15πŸ‘10🀩3πŸ”₯1
LLM trading models can decay faster than they can be retrained: strong short-term accuracy collapses as regimes shift, and standard fine-tuning overwrites older behaviors that may return in cyclic markets.

SEAL (Self-Evolving Adaptive Learning) reframes the loop into continual learning from live outcomes. Each closed trade becomes feedback, but examples are weighted by move size and β€œconfident but wrong” cases to correct false pattern detection.

A prioritized ring-buffer memory blends freshness with retention of rare, high-value events, while retraining is triggered by quality/regime-change signals (volatility, volume, error distribution) and runs asynchronously to avoid blocking execution. Switching training data from raw JSON to narrative context improves indicator relationship learning.

Operational safeguards cover black swans (anomaly stop), overfitti...

πŸ‘‰ Read | Calendar | @mql5dev
❀19πŸ‘13🀩6πŸ‘5πŸ”₯2πŸ†1
Forum demand for indicator alerts and multi-timeframe signals remains constrained by a common limitation: many users only have compiled .ex5 files, not source, and maintaining custom edits across multiple indicators does not scale.

A standalone approach uses iCustom to load indicators by name and read their buffers without source. EXPLORE mode probes buffers, counts non-empty/zero/blank values across recent bars, and prints a per-bar table so the visible plot or sparse signal buffer can be identified reliably.

WATCH mode then applies triggers to the selected buffer: value appears, level cross, buffer-to-buffer cross, or value change. Closed bars are evaluated by default, with optional tick-by-tick evaluation on the forming bar, still limited to one alert per bar.

A separate change audit distinguishes late values (blank becomes populated later) from repain...

πŸ‘‰ Read | Quotes | @mql5dev
❀19πŸ‘8🀩5πŸ”₯2
An Expert Advisor built around a SuperTrend port where correctness is defined by matching TradingView output and by matching trades to signals, not by profit claims.

Execution is limited to closed bars to prevent transient intra-bar flips from generating trades that do not exist at bar close. The EA reads the SuperTrend direction via iCustom, trades one position at a time, tags orders with a magic number, and places the stop on the line with an optional points offset. On a flip, the position is closed and reversed.

A known edge case is handled: if the next-tick entry would place the stop on the wrong side (price already beyond the line), the signal is dropped and logged rather than forcing an invalid or near-instant stop-out.

An audit logs the indicator value on every closed bar, then a Python check verifies one entry per flip and zero mismatches (example:...

πŸ‘‰ Read | CodeBase | @mql5dev
❀24πŸ”₯9πŸ‘7🀩4
Trading-system costs are measurable, but commonly underestimated. A read-only Expert Advisor calculates one round-trip cost per broker and symbol using tick-sampled live spread, swap for long and short including the triple-charge day, and commission derived from closed deals. It also prints the spread value many tools rely on next to the measured one.

Bar β€œspread” fields are per-bar summaries, not the current quote. On XAUUSD, 60 live readings showed 20 points while the M1 field median was 6, which breaks spread filters and flatters backtests, especially with high trade counts.

Swap is often omitted in custom simulators. It is asymmetric and includes a triple weekday. Example on gold per 0.01 lot: βˆ’0.5842 long, +0.4098 short, Wednesday tripled.

Implementation details include counting distinct quotes, refusing closed-market sampling via TimeCurrent vs TimeTra...

πŸ‘‰ Read | AppStore | @mql5dev
❀30πŸ‘15πŸ”₯5🀩5πŸ‘Œ2πŸ†1
Prop Firm Rule Checker is a read-only diagnostic script that evaluates closed-trade history from a live/demo account or Strategy Tester runs against common prop-firm evaluation constraints. Results are printed as a PASS/FAIL report in the Experts/Journal log, reducing manual post-backtest calculations.

Checks include profit target versus starting balance, max daily loss by calendar day, peak-to-valley overall drawdown, a consistency limit to flag single-day profit concentration, and minimum distinct trading days.

Usage involves attaching the script to any chart or running it after a tester pass, then configuring inputs for balance, thresholds, and date range. It uses HistorySelect() only and does not open, modify, or close trades. Rules differ by firm and must be set from the official rule sheet.

πŸ‘‰ Read | VPS | @mql5dev
❀21πŸ‘15πŸ”₯8🀩6🀣2
Most position size calculators evaluate only the next trade and ignore existing exposure. That approach can overstate available risk when multiple symbols are correlated, such as stacking EURUSD and GBPUSD in the same direction and effectively increasing USD exposure.

This script estimates a standard risk-based lot size, then reviews all open positions across the account. It computes recent correlation between each open symbol and the target symbol using the last N bars on a selected timeframe, evaluates whether directions amplify or offset, and aggregates risk already allocated to correlated positions. If combined exposure approaches or exceeds a configurable basket limit, the recommended lot size is reduced.

Output is written to the Experts/Journal log with the positions flagged, correlation values, direction impact, and the adjusted lot size. If any ...

πŸ‘‰ Read | Signals | @mql5dev
❀19πŸ‘12πŸ”₯11🀩8πŸ€”3
Risk-Based Lot Size Calculator is a lightweight MQL5 script designed to standardize position sizing using fixed account risk.

Inputs are limited to InpRiskPercent (risk as a percent of balance, default 1.0) and InpStopLossPips (stop distance in pips, default 20). The script reads the current account balance and symbol trading properties including tick value, tick size, and volume limits (min, max, step).

Lot size is calculated so that a stop-out at the specified pip distance equals the configured risk amount. Output volume is rounded down to the nearest valid step and constrained to broker limits. The calculated lot size and a full breakdown are displayed on-chart and written to the Experts log. Live broker parameters are used, avoiding hard-coded pip assumptions across symbols and account types.

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘17❀15πŸ”₯13🀩9✍2🀯1πŸ‘¨β€πŸ’»1
MQL5 datetime is an integer epoch (seconds since 1970), but broker server timestamps are the broker’s wall clock stored as if it were UTC. When exported as a raw epoch and parsed as β€œ1970 UTC” in Python or spreadsheets, timestamps shift by the server’s UTC offset. On a UTC-3 server, a daily bar at 00:00 becomes 21:00 of the prior day, and session boundaries move without any parsing errors.

A diagnostic script prints the available clocks and deltas: TimeTradeServer() (server wall clock, works without ticks), TimeCurrent() (last tick time, freezes when ticks stop), TimeGMT() (UTC from the PC), and TimeLocal() (PC local time). It reports server-GMT, local-GMT, server-local, tick lag, plus optional last bar time in server time and real UTC (InpShowLastBar=true).

Guidance: export server timestamps as wall-clock text, or export epoch together with the measured...

πŸ‘‰ Read | Calendar | @mql5dev
❀19πŸ‘11πŸ”₯10🀩7
An account statement reports realised results, but omits what each trade offered intrabar. This indicator reads closed trades from account history and measures Maximum Favourable Excursion (MFE) and Maximum Adverse Excursion (MAE) using the bar high/low across the trade’s lifespan on the active timeframe.

Each position is rendered with a vertical span from worst to best excursion, an entry marker, and an exit line. A summary panel aggregates medians for winners (MFE, MAE, capture ratio), losers (MAE), trade count, and median bars per trade.

The key metric is capture ratio: realised profit versus the best unrealised profit seen on winning trades. Low medians often indicate exits that consistently give back gains, while tight stops can appear noisy when MAE barely exceeds the stop despite eventual direction being correct.

Limits are stated: intra-bar ...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀15πŸ‘3πŸ”₯2🀩1
A utility script generates a CSV report with one row per closed position, grouped by DEAL_POSITION_ID, supporting hedging and netting accounts. Output columns include ticket, symbol, direction, entry/exit timestamps, entry/exit prices, profit in points, MFE/MAE in points, capture ratio, bars spanned, and holding time.

Key inputs: InpDias (history days, default 365), InpSoEsteAtivo (restrict to chart symbol or read all symbols), InpTF (timeframe used for excursion measurement, default current), and InpArquivo (CSV name under MQL5\Files).

A summary is printed to the Experts log: trade count, winners/losers, net result, median MFE/MAE for winners, median MAE for losers, median capture ratio, median bars per trade, single-bar trade count, and a count of trades not measurable due to missing historical bars (reported explicitly).

Excursions are computed from bar...

πŸ‘‰ Read | Docs | @mql5dev
❀14πŸ‘9πŸ”₯2🀩1
CME gold has a daily maintenance break. Across an 11-year hourly sample, the first hour after the reopen shows a repeatable upward drift, while other hours are near flat.

An EA was built around a single rule: buy at the reopen, hold a fixed time, use a server-side stop sized by volatility, then stand down. One trade per session. No averaging, grid, martingale, or recovery logic.

Initial research assumed ~19 points round-trip cost and measured +3.34 bps with t=7.40 (59.3% wins, PF 1.63, 11/11 positive years). Real-tick testing showed the reopen cost is closer to ~60 points because bar-level spread summaries understate the reopen spread. After correction: +1.60 bps, t=3.42, ~50.8% wins, PF 1.30, 10/11 positive years.

Sizing for ~20% drawdown gives ~3.3%/yr with ~4.6% max drawdown, Sharpe ~1.23, ~200 trades/yr, implying non-trivial negative-year risk. Validat...

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘8❀7πŸ”₯2
Reusable MQL5 trade-management blocks were added to the Bootstrap library to standardize trailing-stop and break-even handling across EAs. The helpers focus on safe stop updates: validating broker stop levels, preventing β€œreverse” stop loosening when indicator values change, converting money targets into price distances correctly, and applying consistent symbol/magic and BUY/SELL filtering.

Trailing is covered in multiple styles: fixed points with step control, moving-average, ATR (volatility-adaptive with anti-reverse protection), Parabolic SAR, monetary trailing based on account currency, and periodic trailing that tightens stops over time rather than by price movement.

Break-even is implemented as a one-time stop move after an activation threshold, with optional offsets, available in both point-based and money-based forms. The result is less duplicated c...

πŸ‘‰ Read | Freelance | @mql5dev
❀13πŸ‘6πŸ”₯4✍1
M1 OHLC backtests rely on an implicit intra-bar path model. Since OHLC does not record the sequence of prints, the assumed order only becomes material when the bar that closes a trade touches both stop and target, leaving the outcome dependent on the model rather than the market.

A script quantifies this error rate by opening a virtual bracket each minute around the bar open, then advancing until one level is reached. If the closing minute touches both levels, the assumed OHLC path is checked against real tick history. Multiple bracket sizes are swept to produce an error curve.

XAUUSD results over 30 days (27,844 virtual trades): 20pt 62.6% contested, 23.84% wrong; 50pt 30.1%, 8.25%; 100pt 8.9%, 1.66%; 200pt 1.5%, 0.18%; 500pt 0.1%, 0.00%; 1000pt none.

Inputs include symbol, days, bracket list, horizon, sampling step, and optional CSV of mis-resolved cases...

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘5❀3✍1πŸ”₯1🀩1
This article turns Jesse Livermore’s β€œMarket Key” into a rule-driven MT5 Expert Advisor using a state machine: uptrend, natural reaction, natural rally, and downtrend. Signals come from a frozen consolidation β€œpivot” that must break by an ATR-based clearance on expanding volume, with a strict one-bar reversal filter.

Position building is explicit pyramiding across four tranches, sized from a single stored full-lot calculation to keep risk consistent. Adds occur only after follow-through and a low-volume reaction, then a high-volume resumption; exits trigger immediately on β€œabnormal” against-trend ATR moves with elevated volume, not just stop hits.

Correctness is enforced in OnInit(): tranche percents must total 100, parameters must be sane, and the account must support hedging so each tranche remains a separate ticket. Known gap: no state recovery after ter...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀21πŸ‘3⚑2🀩2πŸ”₯1
Gold trading automation often fails due to broker-side inconsistencies in symbol naming, contract size, and pricing format. Symbols may be XAUUSD, GOLD, XAUUSD.m, XAUUSDpro, or variants, while contracts can represent 100, 10, or 1 ounce, and quotes may use two or three digits.

A robust approach queries the terminal instead of relying on hardcoded constants. Symbol detection ranks available instruments by name match, avoids false positives such as XAGUSD, and optionally accepts an explicit override for non-standard broker symbols. Full specification is read from the terminal: contract size, digits, point, tick size, tick value loss, volume limits/steps, and stops/freeze levels.

Risk functions convert distance into account-currency loss and compute volume from money-at-risk via tick value loss, rounding down to volume steps and returning zero if even the minimu...

πŸ‘‰ Read | Forum | @mql5dev
❀12πŸ‘5🀩1
This EA update removes two hidden assumptions that break real trading workflows: risk is not always β€œ% of account,” and trades do not always enter at the current price. The code now exposes these as explicit choices and builds a cleaner interface for testing and reuse.

Risk per trade supports three models: percent (from balance or equity), fixed cash, or fixed lot. Percent and cash converge into one monetary pipeline; fixed lot treats risk as an outcome, with an optional drawdown override.

Position sizing is corrected for broker volume steps by always rounding down, with normalization to avoid floating-point truncation errors. When minimum lot exceeds the intended risk, the EA can either warn and trade the minimum or skip the trade.

Entry handling adds market, limit, and stop modes. Pending orders size stops/targets/volume from the intended entry price, no...

πŸ‘‰ Read | CodeBase | @mql5dev
❀14πŸ‘6πŸ‘€3πŸ”₯2πŸ‘¨β€πŸ’»2
Certain trading hours are measurably better than others, but generic session rules miss broker-specific behavior. This script quantifies hourly conditions using the broker’s own M1 history over the last N days.

For each hour it calculates average movement (M1 high-low range summed into points per hour) and average spread (from the M1 spread field). The key metric is movement-to-spread ratio: how many spreads of movement an hour provides, allowing direct comparison between high-volatility/high-cost hours and lower-volatility/low-cost hours.

Designed around XAUUSD but supports a comma-separated symbol list and prints results side by side. Inputs include symbols, lookback days (default 90), hour shift for timezone alignment, and optional per-symbol CSV output.

Example findings on one broker: XAUUSD spread stayed near 18.1–19.8 points; best hour 16:00 at 1...

πŸ‘‰ Read | Docs | @mql5dev
❀12πŸ‘6🀯1
ClockDiagnostic.mq5 samples TimeCurrent() and TimeLocal() every few seconds over a fixed observation window to detect server clock failure modes relevant to MT5 scripts and EAs.

Two cases are reported: TimeCurrent() freezing when no ticks arrive, and TimeCurrent() stepping backwards after symbol changes, reconnections, or cross-instrument ticks. Inputs include InpSeconds=60 for observation length and InpStep=2 for the sampling interval.

Output includes both clocks, the initial offset in seconds and hours, a β€œ>>> STEP BACK” line on each backward move, and a window summary: number of readings, seconds advanced by each clock, longest freeze, and step-back count, followed by a verdict. Documented rule: use TimeLocal() for timestamps, date/day transitions, and expiry; use TimeCurrent() for session hours and alignment with market data. The measurement is lim...

πŸ‘‰ Read | Forum | @mql5dev
πŸ‘9πŸ‘Œ3❀2