BSD 3-Clause "New" or "Revised" License

技术解读

以下内容由 GitRead 中文社区 编辑团队基于项目 README 与官方资料整理, 结合中文开发者的常见使用场景补充技术选型建议。具体以项目官方文档为准。

elrizwiraswara/nyao_scalper_mt5 深度技术分析

项目背景与痛点

elrizwiraswara/nyao_scalper_mt5 项目是一款专为 MetaTrader 5(MT5)平台打造的自动化交易机器人(Auto Trading EA Robot)。这类工具旨在解决手动交易的痛点,如交易疲劳、错误判断、及时性和反应速度等方面的问题。对于那些希望更高效进行交易操作的交易者而言,自动化交易机器人成为实现这一目标的利器。特别是在高频交易场景下,自动化的精确性和快速响应能力能够显著提升交易的盈利能力。

核心技术揭秘

从技术角度看,elrizwiraswara/nyao_scalper_mt5 采用了复杂的数据处理和算法模型来实现交易决策。在设计上,开发者注入了丰富的市场分析工具,包括但不限于趋势分析、时间序列预测和市场情绪分析等。

架构图

以下是自动化交易系统的架构图,描述了核心的组件以及它们之间的数据流。

graph TD A[市场数据] --> B[数据清洗] B --> C{"条件判断"} C -->|"满足条件"| D[生成交易信号] C -->|"不满足"| E[继续监听市场] D --> F[交易执行] F --> G[回测评估] G --> H[策略调整] H --> B

该图描绘了一个完整的自动化交易循环,从市场数据收集开始到最后的策略调整,专注于闭环优化策略的有效性。

功能亮点与差异

elrizwiraswara/nyao_scalper_mt5 的独特之处在于其强大的自适应机制,可以根据市场的实时变化动态调整交易策略。这种灵活性使其能够在不同市场条件下的表现都得以优化。相较其他同类产品,此 EA 机器人多配置有更细致的参数调整和高级算法支持,提供更丰富的策略覆盖范围,更能满足高级交易者的需求。

应用场景与落地建议

此自动化交易机器人适用于希望在时间投入和操作自动化之间取得平衡的高频交易者。但在部署之前,需要评估策略的风险承受范围,确保交易资金的合理管理。

部署此类机器人时,应注意平台资源的限制,避免因频繁操作导致资源耗尽。此外,务必充分验证交易策略的有效性,即在小额资金测试其表现,之后逐步增加交易金额来验证长期效果。

综合评价

elrizwiraswara/nyao_scalper_mt5 是一款功能全面且灵活的自动交易机器人,提供强大的市场分析工具和丰富的策略配置支持,特别适合追求极致交易效率和准确性的人群。其动态调整策略的能力是在多变市场环境中保持竞争力的关键。不足之处包括需要较高的技术背景和对策略的理解,以及资源和风险的合理管理。

综上所述,elrizwiraswara/nyao_scalper_mt5 项目既拥有了领先的自动化交易策略,也为交易者提供了一个强大的工具,值得深入研究和应用。

关于

GitHub 原始描述(英文)

Auto Trading EA Robot with Comprehensive Features for MetaTrader 5

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

简要分析

热度分
471
价值分
174
活跃状态
活跃

语言占比

MQL5

README

Nyao Scalper v54.0

Nyao Scalper MT5: a gold trade on a 7.4 trend score, the stop climbing behind the price at each $20 checkpoint until the exit

Indicator-Based Signal Strength EA for MetaTrader 5

Disclaimer: This Expert Advisor is an experimental project for educational purposes. Trading Forex/CFDs involves significant risk. Past performance is not indicative of future results. Use at your own risk.

Nyao Scalper is an automated trading EA designed for scalping on lower timeframes (M1, M5). It scores how strongly price has trended over the last several hours (range position, EMA distance, directional efficiency and net move) into a single score from 0.0 to 10.0, and trades in the direction of the daily trend.

It includes position management, adaptive trailing stops, and lot sizing based on equity performance and signal quality.

The repository also contains Nyao Straddle (nyao_straddle.mq5), a separate and more experimental EA that trades gold only in extreme markets and can run next to Nyao Scalper on the same account. See Nyao Straddle.

Key Features

Signal Scoring

The EA scores buys and sells from 0.0 to 10.0 on every tick (see Strategy Logic):

  • Trend score: how strongly price has trended over the last several hours: its position in the recent high-low range, its distance from a slow EMA, how efficiently it moved and its net move. Every part is continuous and directional, so the score changes smoothly and buy + sell always add up to 10.
  • Velocity (informational): Tracks the change in signal score between bars and shows it on the dashboard. It is not used for any trading decision.
  • Blended Weighted Average Signal Smoothing: Combining recent closed candle signals with a configurable dampened current candle contribution for improved responsiveness while maintaining signal stability.
  • Dead-Market Filter (off in the default profile: MinVolRatioToTrade = 0): When the last closed candle’s ATR collapses relative to its average (ATR/AvgATR < MinVolRatioToTrade), new entries, re-entries and pending limits are blocked — the EA does not scalp a market too quiet to overcome costs. (Open positions are still managed normally.)
  • New-Bar Entry Evaluation (default on): With EnableNewBarEntryOnly, entries are evaluated once per closed bar on closed candles only (the forming candle is ignored for the entry decision, because on the first tick of a bar it holds just that one tick). Position management still runs every tick. This removes intrabar signal repaint and makes backtests representative of live behavior.
  • Per-Tick Caching: Signal scores are computed once per tick and cached, eliminating redundant calculations across position management, trailing, and dashboard systems.
  • Range Filter (off by default): MinEfficiencyToTrade blocks entries unless the last RangeFilterPeriod closed bars moved efficiently in the signal’s direction (directional efficiency ratio = net move ÷ path travelled). In a sideways market the score peaks right at the range edges — buying the top, selling the bottom — and this filter refuses those entries. Try 0.30 with a 20-bar lookback.
  • ATR-Based Stops (opt-in): every distance input type (SLInputType, TPInputType, TSInputType) accepts ATR Multiple, so stops and trailing scale with current volatility instead of fixed dollars that become too tight as price and volatility rise. BreakEvenTriggerATR and TrailStartATR delay the break-even lock and trailing until the trade has moved that many ATRs in its favor (0 = legacy dollar/spread triggers).
  • Higher-Timeframe Trend Filter (EnableHTFTrendFilter, on in the default profile, D1 EMA50): only allows buys above a rising higher-timeframe EMA, and sells below a falling one. HTFMinDistancePct (0.5 in the default profile, 0 = off) also requires the last closed higher-timeframe bar to close at least that % beyond the EMA, so entries are skipped while price hugs it and the trend is unclear.

Risk & Equity Management

  • Equity Protection:
    • Min Equity Stop: If equity falls below a specific dollar amount (MinimumEquity), closes everything and removes the EA from the chart.
    • Max Drawdown Pause: Pauses new entries (with growing pause lengths) when equity drops 100 − MinEquityPercent% below its peak; MaxMinEquityTriggers turns repeated triggers into a full stop.
    • Target Equity: Optional absolute equity level (TargetEquity) at which the EA closes everything and stops for good (not a daily target).
  • Basket Stop: Portfolio-level backstop. Closes all non-chain positions and pauses when their floating loss exceeds a % of equity (MaxBasketLossPct) — protects against compounding drawdown from stacked positions, independent of per-position stops.
  • Total Loss Hard Stop: MaxTotalLossPct closes everything, including hedge chains, and pauses when the total floating loss crosses the limit. This is the one cap that bounds every position the EA holds.
  • Max-Spread Filter: Blocks new entries when the spread is too wide (fixed MaxSpreadPoints, or auto-derived from ATR via MaxSpreadATRRatio). Critical for cost control on M1 gold.
  • Signal Dampening: Position-aware system that penalizes signal scores when holding losing positions and raises entry thresholds during drawdown periods. The drawdown is the whole account’s by default; DrawdownScope = This EA's Own Trades measures only the chart’s own trades (for several symbols on one account).
  • Loss-Streak Pause (LossStreakPauseCount, default 4, 0 = off): losing trades cluster — after a loss the next trade wins noticeably less often, i.e. the market is temporarily not suited to the signal. After N losses in a row the EA stops opening real trades and paper-trades every signal instead (same entry price, stop and first checkpoint/TP). Real trading resumes on the first paper win, or when a still-open real position closes in profit.
  • News Filter: Automatically pauses new entries before and after high-impact news events. News, basket-stop and drawdown pauses each run on their own timer, so one can’t cancel or shorten another.
  • Market-Close Filter: Stops opening positions MinutesBeforeClose minutes before the symbol’s quote session ends (daily break or weekend). Back-to-back sessions (e.g. 24:00 → 00:00) count as one continuous session.
  • Trading Hours: Configurable start and end times to avoid low-liquidity sessions.
  • Leverage Guard: Pauses new entries if account leverage changes and resumes when it’s restored. CloseAllOnLeverageChange (default on) also closes all positions — set it off on brokers with dynamic leverage.
  • Restart-Safe State: With EnablePersistState (default on) the EA saves its per-position and account-level state to MQL5\Files\NyaoScalper\ and restores it after a terminal/VPS restart, recompile, input change or timeframe switch. Set ResetSavedState = true once to start fresh (then set it back to false). Not used in the Strategy Tester.
    • Open positions the saved state doesn’t cover (no file, reset, or a crash before the save) are still protected. Each gets a stop if it has none, and its checkpoint exit is re-armed.
    • At terminal start the EA waits for the trade-server connection before reading the account.
    • Deposits and withdrawals shift the peak-equity baseline, so a withdrawal is never treated as a drawdown.

Position Management

  • Duplicate Signal Filter: Uses “Zone Points” and minimum distance multipliers to prevent over-stacking positions.
  • Adaptive Trailing (off in the default profile, which uses the checkpoint trailing stop instead):
    • Standard trailing stop logic.
    • Signal-Based Adaptation: Tightens or loosens TP/SL based on real-time changes in the Signal Score.
  • Loss Management (off in the default profile):
    • Position Health Revalidation: Continuously evaluates trade thesis using trend alignment, RSI zone, adverse ATR excursion, and swing structure — weighted health score determines hold/exit decisions.
    • Scaled Partial Close: Gradually reduces position volume as signal decays (75% → close 25%, 50% → close 50%, 25% → full exit). Each level is evaluated on its own; a level whose partial volume is below the broker minimum (e.g. 25% of 0.01 lot) is skipped, so the 25% full exit still fires on minimum-lot positions.
    • Dynamic SL Tightening: Pulls stop-loss closer proportionally as position health weakens below a threshold.
    • Break-Even Lock: Moves SL to entry price once profit exceeds spread cost, protecting gains.
    • Virtual SL + Re-entry: Closes positions at the health threshold, then immediately re-enters at the current (better) price if the signal is still valid. A re-entry goes through the same checks as a fresh entry (cooldown, per-candle limit, dampening, spread, HTF filter — only the duplicate-distance filter is skipped), and is skipped when a new position would fail the health check itself (otherwise it would just be closed again after its grace bars).
    • Profit Offset SL: Tightens SL of losing positions using accumulated profits from consecutive winning trades.

Hedge Chain Recovery (Optional, Off in the Default Profile)

⚠️ This is a martingale. Lot size grows as a losing trade is hedged and re-hedged. It can recover many drawdowns smoothly but carries genuine ruin risk in strongly trending or choppy markets — it converts frequent small losses into rarer large ones. It is opt-in (EnableHedgeChain) and off in the default profile. Size HedgeMaxLot and the loss caps for an account you can afford to draw down.

What to expect: a hedge is a new bet in the opposite direction, against the trend the original trade followed, so it cannot recover losses for free. A covered chain ends near break-even, a stopped chain loses its cap. With the trend-turn gate and the 1.5× SL cap it was roughly neutral in backtests; with a loose gate and a 5%-of-equity cap it lost noticeably.

When a position moves into loss by HedgeTriggerATR × ATR and the reverse-direction signal confirms (HedgeRequireSignal: the opposite-side score ≥ HedgeMinSignalScore, default 6.5: the multi-hour trend has clearly turned against the position), the EA opens a reversed hedge and manages the pair as a rolling chain — at most two legs open at a time. The signal gate is an anti-spike filter: a wick that crosses the ATR trigger intrabar but isn’t a real reversal won’t have a strong opposite-side score, so no hedge is opened — the chain waits for the move to be confirmed (or the position to recover).

  • Recovery Sizing (HedgeAutoLot): each hedge lot is computed so its profit covers HedgeRecoveryPct% of the leg it hedges within a HedgeRecoveryATR × ATR favorable move — instead of a blind fixed multiplier (which often can’t catch up before price reverses). Falls back to HedgeLotMultiplier when auto-sizing is off, and is always clamped to HedgeMaxLot.
  • Covered: hedge profit covers the older leg’s current loss → close the older leg; the hedge graduates and trails to ride for more. Two safeguards on the graduated hedge:
    • Recovery-locked SL: its stop is floored at the price that keeps HedgeRecoveryPct% of the (now-closed) older leg’s loss locked, so the pair can never give back into a net loss below the recovery target — the trail only ever rides the SL above that floor.
    • ATR trailing: because a graduated hedge carries a large (martingale) lot, it trails at HedgeTrailATR × ATR (lot-independent) rather than the dollar-based TrailingDistanceValue — a small dollar distance on a big lot becomes a near-zero price gap that would close the position instantly. Set HedgeTrailATR = 0 to fall back to the normal trailing settings.
  • Roll: hedge is losing but the older leg has recovered to break-even → close the older leg (free) and open a larger reverse hedge against the current one. Repeats up to HedgeCycleLevels per cycle.
  • Reseed: at the cycle/lot limit, partial-close the deepest hedge by HedgeCyclePartialPct% and start a fresh, smaller cycle (up to HedgeMaxCycles) — capping lot growth instead of stacking ever-larger legs.
  • Exhausted → release (not closed): once the chain can no longer expand (HedgeMaxCycles reached, or the HedgeMaxLot / HedgeMaxTotalLots ceiling hit with reseed off), the legs are handed back to the adaptive loss management — trailing, health-revalidation, partial close — and flagged so no new hedge is started on them. The chain is not force-closed at this point.
  • Chain loss stop (HedgeMaxChainLossSL / HedgeMaxChainLossPct / HedgeMaxChainLossUSD; the tightest wins): closes the whole chain when its combined loss crosses the cap. It is checked before any roll. By default a chain may lose at most 1.5× the base lot’s SL loss ($30 with the default $20 stop at 0.01 lot) or 5% of equity, so it can never cost much more than the stop it replaced.
  • Entry gates: anything that adds exposure — starting a chain, rolling to a bigger leg, reseeding a cycle — obeys the same blocks as a fresh entry: news window, pauses, trading hours, market close, leverage change and the spread filter. While blocked, an existing pair is simply held (still bounded by the chain loss stop and the total hard stop). Closing actions (covered, stop, release) always run.
  • Concurrency caps: HedgeMaxActiveChains (default 1) limits how many chains can run at once, so a sharp reversal can’t open a hedge for every stacked position on the same tick. HedgeMaxTotalLots caps the combined volume of all active chain legs; a roll that would exceed it reseeds or releases instead.

While a chain is active its legs are excluded from the standard trailing/loss-management and from the portfolio basket stop (a chain’s transient drawdown must not trip it). They are still covered by their own chain loss stop and by the total loss hard stop (MaxTotalLossPct), which includes every position. Once released (or after a stop), the legs become normal positions again and the basket stop covers them. The first position’s stop-loss is cleared on chain start (HedgeClearRootSL) — only after its hedge has actually been opened — so the chain logic alone governs the pair.

Chain state is saved to disk (see Restart-Safe State), so a restart doesn’t turn live legs into “new” losing positions that start fresh chains. If no saved state exists, open positions whose comment starts with Hedge L are flagged so they never seed a new chain.

Lot Sizing

  • Risk-Based Lot (RiskPerTradePct, default 1.25): each entry uses the largest lot whose stop-out loses at most this % of equity, capped at MaxLotSize (default 0.05), the broker limits and available margin. The lot is rounded down, so it shrinks as a balance shrinks. With the default $20 stop: 0.01 lot on a $2,000 standard account (about 1% risk), 0.05 lot on a $100 cent account (10,000 cents). Works only with a lot-independent stop (Points, ATR); set 0 to trade a fixed BaseLotSize instead.
  • Small-Account Cap (MaxRiskPerTradePct, default 5): when even the broker’s minimum lot loses more than RiskPerTradePct, the EA still trades the minimum lot as long as its stop-out loses no more than this % of equity, and says so (an orange Lot line on the dashboard and a daily [RISK SIZING] note in the Experts tab, even with logging off). Above the cap the entry is skipped instead of over-risking. With the default $20 stop a standard account trades 0.01 lot at up to 1.25% risk from about $1,600, at 1.25-5% between about $400 and $1,600, and opens nothing below about $400. Set 0 to skip every entry that would risk more than RiskPerTradePct.
  • Base Lot: With RiskPerTradePct = 0, every entry starts at BaseLotSize, capped at MaxLotSize, the broker limits and available margin.
  • Drawdown Recovery Steps (EnableDynamicLots): Adds LotStepSize for every EquityDropPercent% the equity is below its peak — but only when the entry’s signal score is at least MinSignalStrengthForLot (default 8.0). The score is a gate for these steps, not a separate lot boost. Guardrails: capped at MaxEquityDropLotSteps total steps, and disabled while in a post-loss cooldown or while the basket is in floating loss — so size never scales up while actively bleeding.

Dashboard & Alerts

  • On-Chart Dashboard: Display of Signal Scores, Equity, Drawdown, hedge-chain usage and Statistics (refreshed once per second; hidden in non-visual backtests). Statistics count one trade per closed position (partial closes summed, entry commission included) and show average win / average loss, expectancy per trade and profit factor — the numbers that decide profitability, which a high win rate alone can hide.
    • Lot: the lot the next entry would use and what it risks at the stop. It turns orange when the broker’s minimum lot risks more than RiskPerTradePct but is still traded (within MaxRiskPerTradePct), and reads NONE with the reason when even the minimum lot is over that cap (the status then reads No Entries (Account Too Small) and the Experts tab gets a [RISK SIZING] warning at start-up and hourly, even with logging off).
    • BUY / SELL SCORE: the live score (closed bars blended with the forming one). Below it, Entry is what the next bar’s entry decision actually uses: the closed-bar score after the losing-position penalty against the effective minimum, with each boost listed (consecutive candles, drawdown).
    • Ready / Blocked: the first gate that currently stops a new trade that way, e.g. needs a D1 uptrend, score 4.80 below 5.00, spread 620 pts > cap 500, 2 positions open (max 2), loss cooldown or account too small. Entries are decided once per new bar.
  • Discord Integration: Sends alerts to Discord via Webhook for:
    • Trade Open/Close
    • Equity Milestones
    • News Events
    • Trading Pauses/Resumes

Strategy Logic

The EA scores both sides from 0.0 to 10.0 and opens a trade when a side’s score reaches MinBuySignalScore / MinSellSignalScore (default 5.0), only in the direction the D1 trend filter allows.

Trend Score

Four readings of the closed bars, each from -1 (strong down) to +1 (strong up), averaged into s:

Part Measures Input (default)
Range Where the close sits in the high-low range TrendRangeBars (200)
EMA Distance from the EMA, in ATRs (TrendATRPeriod, 14) TrendEMAPeriod (200)
Efficiency Net move / total path: a clean trend vs. a whipsaw TrendERBars (100)
Momentum Net move over the lookback, in ATRs TrendROCBars (192)
  • Buy score = 5 + 5s, sell score = 5 - 5s, so the two always add up to 10: 5 means no trend, 7.5 a clear uptrend for buys (2.5 for sells).
  • A small price change moves the score a little, never in fixed jumps, and nothing adds points for volatility alone.
  • With the default minimum of 5.0 the EA buys while the multi-hour trend leans up and the D1 filter allows buys, and the mirror for sells. On M5 the lookbacks cover about 8 to 17 hours; scale them for other timeframes.
  • On XAUUSDm M5 (2022-2026) the buy score’s median was 4.7-5.9 per year, following gold’s direction, and the score spread fairly evenly from 1 to 9: it spends little time near 5.
  • The checkpoint hold (CheckpointHoldMode = Score) keeps a trade while its side still scores higher, i.e. while the multi-hour trend agrees.
  • The dashboard shows the four parts as Rng, EMA, Eff and Mom.

Why a multi-hour score: up to v53.0 the EA also offered an older short-term score (EMA 5/12, RSI 8, candle body and wicks, breakouts, volatility points). On XAUUSDm M5 history it barely separated winning entries from losing ones, and it jumped 1 to 3 points on tiny price changes; multi-hour trend readings carried the most information. v54.0 removed it with its inputs. It is still a modest edge: the score measures trend strength, it is not a probability.

Score Smoothing & Filters

  • Dead-Market Block: if the last closed candle’s ATR/AvgATR < MinVolRatioToTrade, entries are blocked (off by default).
  • Velocity Tracking (informational): tracks the change in signal score between bars and shows it on the dashboard (Vel). It does not drive trailing or lot sizing.
  • Signal Smoothing (Blended Weighted Average):
    • Combines weighted average of recent closed candles with a dampened current candle contribution.
    • SignalSmoothingCandles: Number of closed candles to average (1-10, default 2).
    • CurrentCandleBlend: Weight factor for the forming candle (0.0-1.0, where 0.0 = closed candles only, 1.0 = current candle only). It applies to the live dashboard score and to the loss-management and trailing features that compare the score with the entry score. Entries (with EnableNewBarEntryOnly, default), the checkpoint hold and the trend-flip exit use closed candles only.
    • Results in smooth yet responsive signal scoring that adapts to market conditions.

Entry Condition: the side’s score >= MinBuySignalScore / MinSellSignalScore (plus the HTF trend filter and the entry guards)

Entry Execution (Market vs. Limit)

By default, a qualifying signal opens at market (current Ask/Bid). Optionally, fresh entries can be placed as a pending pullback limit instead:

  • EnableLimitEntry (default off): When on, a fresh signal places a Buy Limit below the Ask (or Sell Limit above the Bid), aiming for a better fill on a small retracement rather than chasing the move at market.
  • LimitEntryAnchor: Where the limit is placed —
    • Fixed ATR (default): a flat depth of LimitEntryATRFraction × ATR below/above price. Simplest; easiest to reason about.
    • EMA: at the fast EMA (a natural M1 retracement target).
    • Swing: at the recent swing low/high (HealthSwingLookback bars) — pure structure.
    • Smart: the nearer-to-price of the swing level and the fast EMA, so the limit lands at a price that means something.
    • For EMA/Swing/Smart, LimitEntryATRFraction acts as a cap — the limit is never placed deeper than that ATR fraction (so you never wait absurdly far), and it always respects the broker stop level. If no valid level sits on the pullback side, it falls back to the fixed depth.
  • LimitEntryATRFraction: Fixed pullback depth (Fixed-ATR mode) / maximum pullback cap (EMA/Swing/Smart modes), as a fraction of ATR.
  • LimitEntryExpiryBars: Cancels an unfilled limit after N bars (managed internally, broker-agnostic). When the symbol supports it, the order also gets a broker-side expiry one bar later as a backstop in case the EA isn’t running.
  • LimitEntryCancelOnFlip: Cancels the pending if the directional signal drops back below its threshold before filling.
  • Safety: All pending limits are cancelled whenever new entries are blocked (news, pause, trading hours, market close, leverage change), when an equity stop fires, and when the EA is removed — a resting limit can never fill into a window the EA meant to avoid, or fill unmanaged.
  • Scope: This affects fresh entries only. Virtual-SL re-entries always execute at market — their purpose is to restore exposure immediately, so they must not risk going unfilled.

Trade-off: A pullback limit improves average fill price but lowers fill rate — strong momentum/breakout moves (which this EA’s scoring favors) often run without retracing, so the best moves may be missed while weaker, stalling signals fill preferentially. Backtest both modes before committing; it is off by default for this reason.

Checkpoint Exit (On in the Default Profile)

With EnableCheckpointExit the take-profit is not sent to the broker — it becomes a checkpoint. When price reaches it, the EA re-checks the trade instead of closing it:

  • Still valid → keep it. The SL is moved to lock CheckpointLockPct% of the move (default 50%), and the next checkpoint is set one TP-distance further. This repeats as long as the trade keeps qualifying, so winners can run with the trend while profit is progressively locked.
  • No longer valid → close at the checkpoint.
  • What “valid” means (CheckpointHoldMode): the higher-timeframe trend still agrees (uses the EnableHTFTrendFilter settings — turn it on), the signal score still points the same way, or both.
  • Trailing stop (CheckpointTrailPct, CheckpointTrailStartPct; 0 = off): both are a % of the checkpoint distance (the TP distance), so they follow it automatically if you change it. Once the trade is CheckpointTrailStartPct% of that distance in profit, the SL follows the price CheckpointTrailPct% of it behind and never moves back. With a start of 0, trailing begins after the first held checkpoint. The checkpoint lock still applies, and whichever stop is tighter wins. The default profile uses 100% / 50%: with its $20 checkpoint, the SL trails $20 behind the price from +$10.
  • Break-even lock (CheckpointBreakEvenPct, default 75 = +$15 of the $20 checkpoint; 0 = off): once the trade is this % of the checkpoint distance in profit, the SL moves to the smallest possible profit: one tick beyond the entry plus commission and any negative swap. On a fast market the stop can still fill a little below that level. Tested on Jan-Sep 2026 real ticks (M5, monthly runs): the +$15 lock raised the default from +83.3% to +93.8% with a slightly smaller drawdown (19.2% vs 20.0%); a +$5 lock cut the profit by more than half, because most trades were closed at about $0 before they could run.
  • All checkpoint settings at a glance:
    • distance: TPInputType / TPValue
    • what keeps a trade: CheckpointHoldMode
    • profit locked per checkpoint: CheckpointLockPct
    • trailing distance and start: CheckpointTrailPct / CheckpointTrailStartPct
    • loss-side skips: CheckpointMaxSkips
    • early exit when the trend turns: TrendFlipExitScore
    • smallest-profit lock: CheckpointBreakEvenPct
  • Loss side (CheckpointMaxSkips, default 0 = off): when the SL is touched while the signal score still agrees, the stop may be pushed one SL-distance further, at most this many times. The broker always holds a hard stop at the maximum distance ((1 + skips) × SL), so the worst case is fixed even if the EA or terminal is offline; the inner stops are managed by the EA. Risk sizing uses the full worst-case distance.
  • Trend-flip exit (TrendFlipExitScore, default 6.0, 0 = off): a losing trade is closed as soon as the opposite side’s closed-candle score reaches this value, i.e. the trend it was opened with has turned against it, instead of waiting for the full SL. With the Trend score, 6.0 to 7.0 means the multi-hour trend has clearly reversed. It cut the average loss in backtests without hurting results. Hedge chain legs are left to the chain logic.

Risk:Reward TP/SL (Optional)

By default the EA places SL and TP from the manual Trailing TP/SL inputs (SLValue / TPValue). Enabling Independent Risk:Reward instead derives both stops from a single risk leg and a target ratio — so every trade carries the same R:R geometry regardless of the manual TP/SL tuning.

  • EnableRiskReward (default off): When on, the R:R engine overrides the manual Stop Loss and Take Profit entirely — EnableStopLoss / SLValue and EnableTakeProfit / TPValue are ignored for fresh entries.
  • RRRiskMode: How the risk (SL) leg is sized —
    • Auto (ATR-Based) (default): SL distance = ATR × RRAtrMultiplier, computed per entry from the last closed bar’s ATR — the stop scales with current volatility.
    • Manual Distance: a fixed SL distance from RRRiskValue, in the units set by RRRiskInputType.
  • RRRiskInputType: Units for the manual risk distance (Dollar Amount / Percent of Equity / Points) — used only when RRRiskMode = Manual.
  • RRRiskValue (default 200): Manual SL distance for the risk leg (used only when RRRiskMode = Manual).
  • RRAtrMultiplier (default 1.5): ATR multiple for the SL leg (used only when RRRiskMode = ATR).
  • RiskRewardRatio (default 1.5): Reward-to-risk ratio — TP distance = SL distance × RiskRewardRatio. The default targets 1.5× the risked distance in profit (a 1:1.5 R:R).

Once set at entry, the TP is fixed at the R:R level — the adaptive trailing system will not recompute or overwrite it, so the intended reward target is preserved for the life of the trade. Trailing and break-even still manage the SL as normal. Applies to both market and pullback-limit entries.

Scope: This is a per-entry geometry override, independent of the per-trade and basket equity stops, which still apply. Leave it off to keep the manual/adaptive TP/SL behavior.

Settings Profile

Three profiles are bundled: settings/xauusd-default.set, settings/xauusd-high-risk.set (see High-Risk Profile) and settings/usdjpy-default.set, which runs next to gold on the same account (see Gold + USDJPY). xauusd-default.set holds the same values as the EA’s built-in input defaults, except DrawdownScope: the file uses This EA’s Own Trades (see Using the Profiles Together), which gives the same results when the EA trades the account alone. To load it, attach the EA to a chart, open the Inputs tab, click Load and pick the file (in the Strategy Tester: right-click the inputs list → Load). The file lists every input, so loading it fully defines the EA’s behavior.

Profiles are named after their symbol (xauusd-…, usdjpy-…), and reports after the profile and the tick data they were tested on (reports/xauusd-default-2026-real-ticks, reports/usdjpy-default-2025-generated-ticks, …). settings/xauusd-straddle.set belongs to the separate Nyao Straddle EA.

default
Symbol / timeframe Gold (written for XAUUSDm, 3-digit quotes; 2-digit brokers are rescaled automatically) on M5
Entries Trend score ≥ 5 (the multi-hour trend agrees), only in the D1 trend direction (close at least 0.5% beyond a rising / falling EMA50)
Stop Fixed $20 move (20000 points on 3-digit quotes)
Lot size Largest lot that loses at most 1.25% at the stop (RiskPerTradePct), capped at 0.05: 0.01 lot on $2,000, 0.05 lot on a $100 cent account
Exit Checkpoint every $20: held while the score agrees (locking 50%), otherwise closed; $20 trailing stop from +$10; break-even lock at +$15, so a trade that got that far can’t end as a loss; a losing trade is closed early once the trend flips against it (opposite score ≥ 6)
Loss-streak pause After 4 losses in a row, paper-trades until a paper win
Hedge chain Off
Account Standard account: the reports use $2,000 (0.01 lot risks $20, about 1%). Below about $1,600 the 0.01 minimum lot risks more than 1.25%: the EA still trades it down to about $400 (up to 5% per trade, MaxRiskPerTradePct, shown in orange on the dashboard) and opens nothing below that. Cent account: $100 or more (10,000 cents, 0.05 lot, the same ~1%). See Account Size, Risk & Account Type

High-Risk Profile

settings/xauusd-high-risk.set uses the default rules with twice the risk per trade. Only two inputs differ: RiskPerTradePct 2.5 (0.02 lot on $2,000, dropping to 0.01 lot below about $1,600; below about $800 that 0.01 lot risks more than 2.5% and is traded down to about $400, the same 5% cap as the default) and MaxLotSize 0.10 (so a $100 cent account can trade 0.10 lot). It was tested on M5.

Jan-Sep 2026, real ticks, v54.0 (with the +$15 break-even lock), M5, $2,000 per month: xauusd-default.set +93.8% (worst month -2.7%, max DD 19.2%), xauusd-high-risk.set +187.6% (worst month -14.4%, max DD 35.5%).

Every month since 2022 under v54.0 (2022-2025 ticks generated from 1-minute bars, 2026 real ticks), from the reports in this repository:

M5, $2,000 per month 2022 2023 2024 2025 Jan-Sep 2026 57 months Months up Worst month Max DD
xauusd-default.set (1.25%) -5.3% -9.0% +0.9% +65.3% +93.8% +145.8% 27/57 -6.5% 19.2%
xauusd-high-risk.set (2.5%) -17.5% -4.3% -9.0% +95.4% +187.6% +252.2% 27/57 -15.7% 35.5%

Monthly reports with every run’s balance & equity graph, M1 and M5, real ticks Jan-Sep 2026 (v54.0): reports/xauusd-default-2026-real-ticks (M5 +93.8%, M1 +24.1%) and reports/xauusd-high-risk-2026-real-ticks (M5 +187.6%, M1 +20.9%). For 2025, M5 with ticks generated from 1-minute bars (v54.0): reports/xauusd-default-2025-generated-ticks (+65.3%, 10/12 months up) and reports/xauusd-high-risk-2025-generated-ticks (+95.4%, 10/12 months up).

Doubling the risk doubles the size of the edge, not the edge itself: the return per unit of drawdown stays the same, and the profile still loses when gold moves sideways. Higher risk (3.75% and 5%) returned more but with 52-64% drawdowns. A frequent-trading M1 variant (entries during the bar, up to 4 positions $1.50 apart, a faster trend score) was tested and rejected: at 2.5% risk it lost up to 60% in a single month.

Gold + USDJPY on One Account

The default rules also trend-follow USDJPY, and USDJPY tends to trend when gold moves sideways (their prices move opposite: monthly correlation -0.36 since 2022). settings/usdjpy-default.set is the default profile with every distance scaled by USDJPY’s daily volatility, nothing tuned: a 786-point (0.786 yen) stop and checkpoint, entries at least 590 points apart (ZonePoints 393), a 0.309% D1 trend distance, a 2-pip spread cap, PointInputDigits 0, MaxLotSize 0.20 (about $100 at the stop, like gold’s 0.05 lot) and gold’s smallest-profit lock at 75% of the checkpoint (CheckpointBreakEvenPct 75).

M5, $2,000 per month, 1.25% risk each 2022 2023 2024 2025 Jan-Sep 2026 57 months Months up Worst month Drawdown across months
Gold (xauusd-default.set) -5.3% -9.0% +0.9% +65.3% +93.8% +145.8% 27/57 -6.5% 24.0%
USDJPY (usdjpy-default.set) +55.8% +1.3% +38.9% -6.8% -5.2% +84.0% 25/57 -6.9% 18.8%
Both on one account +50.5% -7.7% +39.8% +58.5% +88.6% +229.8% 33/57 -6.9% 26.7%

“Both” is the sum of the two monthly runs (the tester runs one EA at a time), measured with v54.0; 2022-2025 use ticks generated from 1-minute bars, 2026 real ticks. The smallest-profit lock helped USDJPY the way it helped gold: without it, USDJPY made +81.5% with a 23.2% drawdown across months, and both together +227.4% (27.3%). To run it:

One hedging account, two M5 charts: XAUUSD with xauusd-default.set, USDJPY with usdjpy-default.set. Both profiles already carry their own magic number and DrawdownScope = This EA’s Own Trades; see Using the Profiles Together. Up to 4 positions and about 5% of equity can be at risk at the same time.

USDJPY reports (M5, v54.0): reports/usdjpy-default-2026-real-ticks (-5.2%, 2/9 months up) and reports/usdjpy-default-2025-generated-ticks (-6.8%, 5/12 months up). The Nyao Straddle can be added as a third chart.

Alone, USDJPY was a weak earner (it lost in 2025 and 2026); it was tested as a partner for gold. Using the opposite movement as a filter instead (gold buys only while USDJPY falls, and back) was tested and rejected: it cut gold to +86-112% and USDJPY to +12-14%, because the two also trend together at times (2024). The same scaled test (57 months) found no other partner: EURUSD -49%, AUDUSD -145%, silver -185%, platinum -518% and GBPUSD +11% (added nothing); US stock indices US500 -70%, USTEC -35%, US30 -46%; crypto BTCUSD -18% and ETHUSD -1% (both raised the combined drawdown), XRPUSD and LTCUSD far worse (their spread is 35-62% of the scaled stop). The edge of these rules is gold’s, with USDJPY as the one partner that balances it.

Brokers with other quote decimals: point values are written for a 3-digit gold quote (0.001), and PointInputDigits (default 3) rescales them to the symbol’s own decimals so every distance keeps the same price meaning. Where gold is quoted with 2 decimals, 20000 points become 2000, still a $20 move, instead of a $200 stop with 10× the risk. This covers SLValue, TPValue, TrailingDistanceValue and RRRiskValue when their type is Points, plus ZonePoints and MaxSpreadPoints. The EA prints a [POINTS] line at start-up when it rescales. Set PointInputDigits = 0 to use point values exactly as typed (for example on forex, where your own values are written for that symbol).

Account Size, Risk & Account Type

The EA sizes every trade from equity: it uses the largest lot whose stop-out loses at most RiskPerTradePct of equity, capped at MaxLotSize. When even the broker’s minimum lot (0.01) is over that budget, it still trades the minimum lot as long as its stop-out loses no more than MaxRiskPerTradePct (5%), and opens nothing above that. With gold’s $20 stop, 0.01 lot loses $20. Both profiles need a hedging account; leverage changes only the margin a trade needs, not what it risks.

Standard account (balance in dollars):

Equity xauusd-default.set (1.25% per trade) xauusd-high-risk.set (2.5% per trade)
under $400 no trades (0.01 lot would lose more than 5%) no trades
$400 0.01 lot, 5% per trade 0.01 lot, 5%
$800 0.01 lot, 2.5% 0.01 lot, 2.5%
$1,600 0.01 lot, 1.25% 0.02 lot, 2.5%
$2,000 (as in the reports) 0.01 lot, 1.0% 0.02 lot, 2.0%
$4,000 0.02 lot, 1.0% 0.05 lot, 2.5%
$8,000 0.05 lot (the cap), 1.25% 0.10 lot (the cap), 2.5%
$16,000 0.05 lot, 0.6% 0.10 lot, 1.25%
  • It trades from $400; the reports use $2,000. Below $1,600 the default trades the 0.01 minimum lot above its 1.25% budget (up to 5%); the dashboard shows this as an orange Lot line and the Experts tab gets a [RISK SIZING] note.
  • Above $8,000 the lot cap (0.05 for the default, 0.10 for high-risk) holds each trade below the set percentage. Raise MaxLotSize if you want the risk to keep scaling with the account.

Cent account (balance in US cents, e.g. 10,000 = $100):

  • The EA reads every amount in the account currency, so a cent account is sized like a standard account with 100× the number: on a $100 cent account the default trades 0.05 lot (about 1% per trade) and xauusd-high-risk.set 0.10 lot (about 2%). Above about $80 the 0.05 cap keeps the default below 1.25%.
  • This assumes the cent gold symbol has the standard lot size with profit counted in cents (the usual setup). The EA calculates from the symbol’s own values either way, so check the dashboard’s Lot line: it shows the lot and the % it risks. A cent symbol has not been backtested.
  • Money inputs are also read in cents: MinimumEquity 20 means 20 cents, so set it to 2000 for a $20 floor. Cent gold spreads can be wider: above 500 points ($0.50) the spread filter blocks entries.

Gold + USDJPY: USDJPY’s 0.786-yen stop costs about $5 per 0.01 lot (it moves with the yen rate), so on $2,000 the USDJPY chart trades about 0.04 lot (about 1%) and is blocked only below about $100. The pair needs gold’s minimums above; with both charts running (up to 2 positions each), about 4-5% of equity can be at risk at once.

Using the Profiles Together

Every profile in settings/ can share one hedging account with any of the others, each on its own chart:

Profile EA Chart MagicNumber
xauusd-default.set Nyao Scalper XAUUSD M5 6926268
xauusd-high-risk.set Nyao Scalper XAUUSD M5 6926269
usdjpy-default.set Nyao Scalper USDJPY M5 6926270
xauusd-straddle.set Nyao Straddle XAUUSD M1 25102501
  • Separate trades. Each chart manages only the positions and orders with its own magic number on its own symbol, so two profiles on gold never touch each other’s trades. Nyao Scalper’s saved state (EnablePersistState) is also kept per symbol and magic number.
  • Separate drawdown. The Nyao Scalper profiles use DrawdownScope = This EA’s Own Trades: another chart’s losses don’t raise this chart’s entry score. When one EA trades the account alone, this gives the same results as measuring the whole account.
  • Shared account checks. The per-trade, basket and total-loss stops count only the chart’s own trades. The account-wide checks (MinEquityPercent drawdown pause, MinimumEquity, TargetEquity, leverage pause) watch the whole account, and each EA then closes only its own positions.
  • The risk adds up. Every chart sizes its lots from the whole account’s equity. Gold + USDJPY can hold up to 4 positions with about 5% of equity at risk at once; the straddle adds one more position, about $1 at 0.01 lot.
  • What was tested together (sums of separate monthly tester runs, since the tester runs one EA at a time): gold + USDJPY over 57 months (above) and gold + the straddle in 2026 (below). xauusd-default and xauusd-high-risk on the same account take the same trades twice, which amounts to a higher risk setting, not a second strategy.
  • Load the files. The magic numbers and the drawdown setting come from the profile files. An EA attached without loading a profile uses its built-in magic number (6926268 for Nyao Scalper) and measures drawdown on the whole account.

Nyao Straddle (Companion EA)

nyao_straddle.mq5 is a second, separate EA for gold on M1, built on a different idea from Nyao Scalper. Nyao Scalper trades with the daily trend and makes its money in steady trends. Nyao Straddle stays out of the market almost all the time and trades only when gold becomes extremely volatile, the kind of market where a $1 move tends to keep going. It can run on the same account as the Nyao Scalper profiles (see Using the Profiles Together).

More experimental than Nyao Scalper. It has been backtested on one year of real ticks (2026), and most of its profit comes from a single event, the gold crash of late January 2026. Trading CFDs involves significant risk; past results are not indicative of future results.

Profile: settings/xauusd-straddle.set (= the EA’s built-in input defaults). Report: reports/xauusd-straddle-2026-real-ticks.

How It Works

  1. Extreme markets only. Gold’s H1 ATR(14), measured on closed bars, must be at least $34. That was gold’s most extreme 10% of the time in 2026. In January, March and April 2026 it held for hours or days; in May and July-October it never happened.
  2. The market must be speeding up. The ATR of the last 7 one-minute bars must be at least 2× its average over the last 288 bars.
  3. Straddle. While both hold, the EA keeps a buy stop $1 above and a sell stop $1 below the price. The first one to fill cancels the other.
  4. Exit. The position has a $1 stop that trails $1 behind the price from the moment it fills. There is no take profit: the trailing stop ends every trade.
  5. Again. As soon as the position closes, a new pair goes out, as long as the market is still extreme. In a crash this means many trades an hour.
  6. Pause. After 10 losing trades in a row it places nothing for 30 minutes.
  7. Lot. Fixed 0.01: about $1 at the stop, plus slippage.

Untriggered orders are deleted when the market calms down.

On-chart dashboard (v1.6, the same panel as Nyao Scalper’s, refreshed once per second, hidden in non-visual backtests):

  • Status, balance, equity and the peak since the EA started.
  • Market Filters: the lot and what it risks at the stop, the H1 ATR next to the $34 it needs and the M1 speed-up ratio next to the 2× it needs (each turns green when it passes), then Ready / Blocked with the first check that stops a new pair, e.g. calm market, not speeding up, losing-streak pause or spread > cap.
  • Orders: the open position with its stop and profit, the waiting buy stop / sell stop, and the losing streak against the pause limit.
  • Statistics: trades, wins / losses, average win / loss, expectancy, profit factor and net profit of this EA’s closed positions (magic number and symbol).

The dashboard changes nothing in the trading: v1.6 trades exactly like v1.5, the version all the results below come from.

xauusd-straddle.set
Symbol / timeframe Gold (XAUUSD) on M1
Extreme-market filter H1 ATR(14) ≥ $34 (RegimeMinATR)
Speed-up filter M1 ATR(7) ≥ 2× its 288-bar average (VolATRPeriod, VolMinRatio)
Entry Buy stop and sell stop $1 from the price; the first fill cancels the other
Exit $1 stop, trailing $1 behind the price from the fill; no take profit
Pause 10 losing trades in a row → 30 minutes without new orders
Lot size 0.01 (Lots; RiskPercent > 0 sizes from equity, never below Lots). On a cent account (balance in cents) 0.01 lot loses 1 cent at the stop; 0.05 lot, or RiskPercent 0.05, on a $100 cent account is the same ~0.05% per trade as 0.01 lot on $2,000. Cent gold spreads can be wider, and the straddle pays the spread on every trade; a cent symbol has not been backtested
Account Hedging account (it can share gold with Nyao Scalper). At 0.01 lot a trade risks about $1 plus slippage

Straddle Results

Real ticks, Jan-Sep 2026, $2,000 per month (each month a fresh run), 0.01 lot, sums of monthly returns (full report):

Month M1 (the timeframe it was tuned on) M5
January +120.0% +109.7%
February +75.5% +27.7%
March +33.0% +45.5%
April +10.7% +1.5%
June -0.2% no trades
May, July-September no trades no trades
Total +239.0% +184.5%
Profit factor / max drawdown 2.02 / 2.7% 1.74 / 4.0%
Trades / win rate 9,985 / 45% 10,486 / 43%
Avg win / loss $2.12 / -$0.85 $1.93 / -$0.84

October 2026 (to the 23rd) had no trades either.

  • 82% of the profit is one event: January 29 - February 9, 2026, the crash and its aftermath. Outside it the edge is a few cents per trade (about $0.09 per 0.01-lot trade in the tests below).
  • It sits idle most of the time. It traded in 5 of 10 months in 2026.
  • The tester fills orders instantly. It models slippage from real ticks (fills averaged about $0.10 worse than the order price) but not execution delay. In a crash the EA can trade every few seconds; a real broker may fill later, requote, or limit that.
  • 2025 can’t be tested properly. Real ticks only go back to 2026 at the test broker. With ticks generated from 1-minute bars, only October 2025 reached the $34 level (gold was cheaper then, so $34 was a bigger move): +37.6% with an 83% win rate and a profit factor of 41.8. Generated price paths are far smoother than real ones, which makes a $1 trailing stop look almost perfect, so that number is not usable (2025 report). 2022-2024 on generated ticks: no trades: gold, at about $1,600-2,800 then, never reached a $34 hourly ATR (report).
  • The defaults were chosen on 2026 data. There is no untouched period left to confirm them on.

Straddle Coin Flip Test

A control test: the EA trades at exactly the same moments, with the same filters and exits, but a coin flip picks the direction (EntryMode input, three random seeds each). If random directions did about as well, the profit would come from the market and the exits, not from the straddle.

Jan-Sep 2026, M1, $2,000 per month Total Profit factor Max drawdown Trades
Straddle +239.0% 2.02 2.7% 9,985
Coin flip, market order now (3 seeds) +16.9% / +33.3% / +51.5% 1.08-1.20 13-17% 6,400-8,600
Coin flip, one stop order $1 away (3 seeds) +13.7% / +23.7% / +27.0% 1.53-2.09 1-1.5% about 1,030

The straddle beats all six. The comparison also shows where the edge is: entering only after price has already moved $1. A single random stop order earns about the same per trade as the straddle (it also waits for a $1 move), while random market orders barely make money and lost 13-16% in March. The straddle catches every breakout in either direction, so it gets about 10 times as many of those trades.

Gold Only

The straddle needs price to run well past its entry after paying the spread. On gold in 2026 a typical minute moved about 8 times the spread ($2.17 vs $0.26); on USDJPY only 1.8 times (1.8 pips vs 1 pip).

USDJPY, Jan-Oct 2026, M1, $2,000 per month, about $1 per stop Total Months up Profit factor
$1 scaled by 1-minute volatility (0.83-pip stop, inside the 1-pip spread) -165.2% 0/10 0.06
$1 scaled by daily volatility, like usdjpy-default.set (3.9-pip stop) -16.3% 0/10 0.68

Both used USDJPY’s own most extreme 10% (H1 ATR ≥ 0.303 yen) as the extreme-market level. Nyao Scalper works on USDJPY because its distances are wide (78.6 pips); a $1-style straddle needs gold’s large moves next to its cost.

Next to Nyao Scalper

The two earn at different times: Nyao Scalper in steady trends (January, March, June 2026), the straddle in the crash (late January - early February).

Jan-Sep 2026, $2,000 per month Nyao Scalper (M5, xauusd-default.set) Straddle (M1, xauusd-straddle.set) Both on one account
Total +93.8% +239.0% +332.8%
Months up 5/9 4/9 6/9
Worst point within a month -14.7% (March) -0.8% -14.8% (March)

“Both” adds up the two monthly test runs (the tester runs one EA at a time). The straddle added its profit without deepening Nyao Scalper’s worst dip. The earlier 1.5× version of the straddle did deepen it: it lost in early March at the same time as Nyao Scalper (worst point -$610 together vs -$293 alone), which the 2× filter avoided. October 2026 (Nyao Scalper -6.5%, straddle no trades) is not in the table. How to run them together: Using the Profiles Together.

What a Demo Test Should Check

  • Fills during fast markets. Compare the fills with the order prices. Fills much worse than about $0.10, especially in fast moves, shrink the straddle’s edge (about $0.48 per 0.01-lot trade in 2026) quickly.
  • Broker limits. In a crash it opens a new trade every few seconds to minutes.
  • Spread. The test broker’s gold spread was $0.16 in January 2026 and $0.24-0.36 later. The straddle pays it on every trade.
  • Latency. The straddle reacts to every tick, so the delay between the terminal and the broker matters more for it than for Nyao Scalper.
  • Idle time. Weeks without a trade are normal. The dashboard shows the H1 ATR next to the $34 it needs.
  • Gold’s price level. $34 and $1 are dollar distances set at a gold price of about $4,500. If gold moves far from that, the same distances describe a different market.

How the Straddle’s Defaults Were Found

Each change below was tested in the Strategy Tester on 2026 real ticks and kept only when it held up (usually with a pass rule written down before the run). The numbers come from the version current at the time, so rows aren’t always comparable with each other.

The idea and the first versions

Version / test Result
v1.0: straddle whenever the M1 or M5 ATR was 1.5× its recent average, stops in ATR multiples, 0.50 lot M5: 8 of 9 months lost the whole $2,000 (only April +$4,691). M1 with a 0.5-ATR stop: profit factor 0.83-0.95
Fixed $1 / $2 / $3 stops instead of ATR (M1, 0.50 lot) Still 8 of 9 months drained. February made +$123k / +$71k / +$35k, all of it in the week after the crash
Why February? Hourly profit vs the H1 ATR at that hour Below $30 every level lost (-$40k); from $30 up it won (+$156k). The crash also had the year’s lowest spread ($0.16)
What separated winning hours from losing ones (H1 ATR ≥ $30)? Crash hours won 79% of the time, other periods 12-37%: the crash had bigger moves next to the $1 distances and the year’s lowest spread. One-way vs back-and-forth movement made no difference (directional efficiency 0.103 vs 0.101), and more ticks or bigger bars helped in the crash but hurt from April on
v1.1: H1 ATR ≥ $30 filter Profitable in the crash; outside it about 3 cents per trade, with a March drawdown that a $2,000 account at 0.50 lot couldn’t survive

Filters

Test Result Decision
Which volatility window? M1, M15, H1, D1 ATR, each allowed its most extreme 5/10/20% of 2026 Minute windows lost outside the crash; D1 was too slow (caught a third of the crash); hour-scale windows worked. H1 ATR(14), top 10% (≥ $33.77) was the only one positive in all three non-crash periods H1 ATR(14) ≥ $34
$34 vs $30 (0.05 lot, one account) $53,069 vs $50,896, profit factor 1.63 vs 1.47, drawdown 3.6% vs 7.0%; outside the crash +$1,216 vs +$699 per 0.01 lot $34
Speed-up level 1× / 1.5× / 2× +674.9% / +400.1% / +207.2%, drawdown 20.2% / 7.3% / 1.9%. 1×'s extra profit all came from the crash 2×
ATR period of the speed-up filter: 5 / 7 / 14 / 21 / 30 / 60 minutes (at 1.5×) +417% / +414% / +400% / +365% / +349% / +296%: shorter is slightly better; drawdowns jumped around (one March path decides them) 7
7 minutes at 2× +239.0%, profit factor 2.02, drawdown 2.7%, no month below -0.8% default (v1.5)
London + New York hours only $7,972 vs $12,214 for all hours (0.01 lot, one account); Asia hours carried much of the crash, and the quiet hours after New York were profitable rejected (EnableSessions, off)
Spread cap Within each period, low-spread trades did not do consistently better (spreads widen exactly when the market spikes) rejected

Stops, trailing and locks (0.01 lot, one account from $2,000, Jan-Oct 2026)

Test Net Profit factor Drawdown Decision
$1 stop, $1 trail from the fill +$10,214 1.63 -3.1% kept
$1 + lock at entry +$0.20 once +$0.50 +$10,332 1.66 -4.5% rejected: the gain was all crash, worse elsewhere
$2 stop and trail +$7,101 1.49 -2.4% rejected
$2 + lock once +$1 +$7,425 1.54 -2.8% rejected
$5 stop + lock once +$0.50 (trail from +$1.20) +$6,878 1.52 -2.9% rejected (82% winners, but about 2,500 full -$5.30 stops)
$5 stop + lock once +$1.00 / no lock +$6,267 / +$5,818 1.45 / 1.40 -4.1% rejected

In fast markets a tight stop that is hit often but costs little beat a wide one. The break-even lock inputs (BreakEvenTrigger, BreakEvenLock) stay in the EA, off.

Trade frequency and risk

Test Result Decision
One trade per candle Same edge per trade (about $0.31), 93% fewer trades, profit /14 removed
Pause after 10 losses in a row for 30 minutes (also 10/120, 15/30) Net -22%, drawdown halved (-$171 vs -$344), profit factor 1.63 → 1.81. All three settings beat no pause adopted (v1.4)
Daily loss limit (stop for the day after -$5 to -$40) No change to the worst drawdown (it builds over several days) rejected
Lot size on a fresh $2,000 month 0.50 lot: most months lost the account. 0.05: March fell to $405 (-80%) before recovering. 0.01: worst month -16% before the pause, -0.8% with it 0.01 default

Research options left in the EA (off by default): EntryMode (coin flip control tests: a market order or one stop order in a random direction, CoinFlipSeed), EnableSessions (Asia / London / New York hours in UTC, SessionUTCOffset for the server clock), BreakEvenTrigger / BreakEvenLock, DistanceUnit = ATR multiples, VolMinATR, PendingExpiryBars, TakeProfit and RiskPercent.

Straddle Inputs

Group Input Default Meaning
Volatility Filter VolTimeframe / VolATRPeriod / VolBaseBars chart (M1) / 7 / 288 Current ATR and its normal level (average over the last N bars)
VolMinRatio 2.0 Trade only when the current ATR is at least this many times the normal level (0 = always)
VolMinATR 0 Also require this ATR as a price distance (0 = off)
CancelWhenCalm true Delete untriggered orders when the market calms down
Extreme Market Filter RegimeTimeframe / RegimeATRPeriod / RegimeMinATR H1 / 14 / 34 Trade only while this ATR is at least $34 (0 = off)
Trading Sessions EnableSessions and the session hours off Asia 0-9, London 7-16, New York 12-21 (UTC)
Orders Lots / RiskPercent 0.01 / 0 Lot size; RiskPercent > 0 sizes from equity at the stop, never below Lots
DistanceUnit Price Distances below in price ($ for gold) or ATR multiples
EntryDistance / StopLoss / TakeProfit 1.0 / 1.0 / 0 Pending order distance, initial stop, take profit (0 = none)
MaxSpread / PendingExpiryBars 0 / 0 Spread cap; re-place an untriggered pair after N bars (0 = off)
Trailing Stop TrailStart / TrailDistance / TrailStep 0 / 1.0 / 0.1 Start trailing at this profit (0 = from the fill), distance, minimum move
BreakEvenTrigger / BreakEvenLock 0 / 0.2 Lock the stop at entry + BreakEvenLock once profit reaches the trigger (0 = off)
Losing Streak Pause LossStreakPause / LossStreakPauseMinutes 10 / 30 Pause after this many losing trades in a row (0 = off)
Other EntryMode / CoinFlipSeed Straddle / 1 Research control test
MagicNumber 25102501 Different from every Nyao Scalper profile
TesterEquityLog true Strategy Tester only: balance & equity log for the report graphs

The backtest tool runs it with --ea nyao_straddle.mq5. Use real ticks only: with ticks generated from 1-minute bars the $1 trailing stop looks far better than it is.

Installation

  1. Copy File: Place nyao_scalper.mq5 into your MetaTrader 5 Experts folder.

    • File -> Open Data Folder -> MQL5 -> Experts
  2. Dependencies: Ensure the Controls and Generic standard libraries are available (standard in MT5). No DLLs are used.

  3. Allow WebRequest (For Discord Alerts):

    • Go to Tools -> Options -> Expert Advisors.
    • Check “Allow WebRequest for listed URL”.
    • Add your Discord Webhook URL (if using alerts).
  4. Compile: Open the file in MetaEditor and press F7 or click “Compile”.

    • Nyao Straddle (optional): copy nyao_straddle.mq5 to the same Experts folder and compile it the same way, then attach it to an XAUUSD M1 chart. It needs no extra libraries.
  5. Run: Drag the EA onto an M5 chart. Its built-in defaults are the xauusd-default.set profile.

    • The built-in defaults (= xauusd-default.set) are made for XAUUSDm on M5 with 3-digit quotes and a $2,000+ standard or $100+ cent account (see the Account row above).
    • 2-digit gold quotes are rescaled automatically (PointInputDigits); for other symbols set your own distances (see Settings Profile).
    • Requires a hedging account (the EA refuses to start on netting accounts).
    • When an equity stop fires (Min Equity, Target Equity or Max Times Trigger), the EA closes all its positions and pending orders and then removes itself from the chart. Other EAs in the terminal keep running.

Alternative Compilation (VS Code)

If you prefer coding in Visual Studio Code, you can compile .mq5 files directly using the MQL5/MQL4 extension (also known as Buraq).

  1. Install Extension:

    • Open VS Code Extensions (Ctrl+Shift+X).
    • Search for Buraq MQL5 or sarfrazfrompk.
    • Install MQL5/MQL4 by sarfrazfrompk.
  2. Configure Path:

    • Go to Extension Settings (Ctrl+,).
    • Search for MQL5.
    • Set Mql5: Metaeditor Path to your metaeditor64.exe location.
    • Example: C:\Program Files\MetaTrader 5\metaeditor64.exe
  3. Compile:

    • Open nyao_scalper.mq5 in VS Code.
    • Right-click anywhere in the code.
    • Select MQL5: Compile.
    • Check the Output terminal for success or errors.

Backtesting Honestly

The EA uses no DLLs, so it runs on local agents and on the MQL5 Cloud Network. State persistence is disabled in the tester (every test starts clean).

Results in the Strategy Tester only mean something if the test mirrors live conditions. For this EA specifically:

  1. Use “Every tick based on real ticks” (Strategy Tester → Modeling). Entries are decided on bar close, but almost everything after the entry — trailing, health exit, partial close, SL tightening, hedge chain start/roll and virtual-SL re-entries — is evaluated every tick. 1 minute OHLC can be used for a fast first sweep, but only real-tick results mean anything for this EA (especially with the hedge chain on). Set ReentryRespectsNewBarGate = true if you want re-entries to also wait for bar close.
  2. Include realistic costs. Set your broker’s commission in the tester and test on a realistic spread (ideally the symbol’s actual spread, not 0). On M1 XAUUSD, spread + commission is the dominant cost — a backtest without them is meaningless.
  3. Know what the tester can’t see. CalendarValueHistory (the high-impact news filter) generally returns nothing inside the Strategy Tester, so backtests run without news protection that live trading has. Treat tester drawdowns around news as optimistic.
  4. Validate out-of-sample. With this many tunable inputs, in-sample optimization overfits easily. Tune on one period, then confirm on a separate untouched period (or use walk-forward) before trusting a profile.
  5. Sanity-check guards via the journal (EnableLogging = true): confirm entries fire only on bar close, that trades are skipped when spread is wide or ATR has collapsed, that no entries or hedge starts happen in the MinutesBeforeClose window, and that the Basket Stop / Total Loss Hard Stop close positions once floating loss crosses their limits.
  6. Judge expectancy, not win rate. Tight trailing locks in small wins while the hard stop is much wider, so a high win rate is built into the design and says little on its own. Look at average win vs. average loss, expectancy per trade and profit factor (shown on the dashboard and in reports), plus the worst drawdown.

Capture your own report with the tool below (real ticks + your broker’s costs, out-of-sample) before running the EA on a funded account.

Coin Flip Test

Does the EA’s direction choice beat chance? A research copy of v54.0 opened its trades at exactly the same moments but let a coin flip pick buy or sell (three random seeds). The trend-flip exit was off in all runs, because it would otherwise close every random trade placed against the score within a minute. Fixed 0.01 lot, one account from $2,000, M5, Jan-Oct 2026 real ticks:

Result Profit factor Max drawdown Trades
Nyao Scalper (its own direction) +78.7% 1.18 13.2% 1,152
Coin flip, seeds 1 / 2 / 3 -30.0% / -15.2% / +14.3% 0.95 / 0.97 / 1.02 42.1% / 50.0% / 39.3% 1,451-1,532

The direction is the edge. With random directions wins and losses cancel out (profit factor about 1.0) and the drawdown triples. The profit comes from the trend months: per 0.01 lot, January +$928, June +$543, March +$399. The Nyao Straddle passed the same kind of test (Straddle Coin Flip Test).

Automated Backtests (tools/backtest)

tools/backtest/nyao_backtest.py runs Strategy Tester passes from the command line and writes a report to reports/<name>/.

Requirements:

  • Windows
  • MetaTrader 5, logged in to your broker at least once; the tester uses that account and its tick history
  • Python 3.8+ (s

README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。

评论

暂无评论