GoldenRobber EA

MQL5 Expert Advisor · XAUUSD · DCA Hedging · SR / Trend / Sideway / Pivot Point (4 methods + Auto) Filters · Tia Cluster + DCA TP synergy · EA v1.41.1 (config pass58) · doc v2.3

🚀 PHIÊN BẢN HIỆN TẠI: EA v1.41.1 · config pass58CURRENT VERSION: EA v1.41.1 · pass58 config

v1.41.1 = fork từ v1.41 (KHÔNG chứa stair-step 1.42–1.47 — nhánh đó là thử nghiệm riêng, đã dừng). File: GoldenRobber-1.41.1.mq5 / .ex5. Compile sạch (0 errors). Mặc định (mode=Fixed, cả 2 nhóm DCA bật) → chạy Y HỆT v1.41.

v1.41.1 = fork of v1.41 (does NOT include stair-step 1.42–1.47 — that is a separate, parked experimental branch). File: GoldenRobber-1.41.1.mq5 / .ex5. Compiles clean (0 errors). Defaults (mode=Fixed, both DCA groups on) reproduce v1.41 exactly.

2 tính năng mới (opt-in):2 new features (opt-in):

  1. Bật/tắt nhóm DCAInpDCAPosEnable / InpDCANegEnable: tắt một nhánh để bỏ qua add-branch của nó (tiết kiệm CPU + giảm rổ). Gate ở nhánh ADD; không đụng lệnh đang mở, không chặn Init.DCA group togglesInpDCAPosEnable / InpDCANegEnable: disable a branch to skip its add-processing (CPU save + smaller book). Gates the ADD branch; open positions still managed, Init not blocked.
  2. Flexible MinPipsInpDCAMinPipsMode (Fixed | Pivot) + PivotTF/K/Floor: khoảng cách ADD cố định (như cũ) hoặc động = max(Floor, K × nửa range pivot của TF chọn, mặc định H4). Chỉ áp cho ADD spacing; init-round spacing giữ cố định.Flexible MinPipsInpDCAMinPipsMode (Fixed | Pivot) + PivotTF/K/Floor: fixed ADD spacing (as before) or adaptive = max(Floor, K × half pivot-range of chosen TF, default H4). Applies to ADD spacing only.

Config hiện tại: pass58Current config: pass58

v1.41.1-pass58-choppyUpgrade-StairMarket-…set — nền M3 + DCANeg OFF. Backtest 2023–2026 / $100k: +$332,040, equity DD ~38% (reconstruct, dồn ở staircase 2023), min equity $69k — lãi cao nhất trong các bản SỐNG mọi regime. Bản M3 đầu tiên qua được staircase 2023 (nơi MEDIUM chết) nhờ DCANeg-off chặn rổ ngược trend phình.

v1.41.1-pass58-choppyUpgrade-StairMarket-…set — M3 base + DCANeg OFF. Backtest 2023–2026 / $100k: +$332,040, equity DD ~38% (reconstructed, concentrated in the 2023 staircase), min equity $69k — highest profit among all-regime survivors. First M3-family config to survive the 2023 staircase (where MEDIUM died), via DCANeg-off capping the counter-trend basket.

✅ STABLE / production hiện tại. Risk profile để tính vốn: DD ~38% dồn hết ở staircase 2023 (min equity $69k trên $100k; giai đoạn 2024-26 chỉ ~33%). Trên $140k → DD ~29%, min equity $109k — cần vốn đệm cho cú sụt năm đầu. Bản bảo thủ hơn (an toàn đầu-kỳ tốt hơn, profit thấp hơn): RANK1 (H4-origin) / TrueScale.

✅ STABLE / current production. Risk profile for capital sizing: DD ~38% concentrated in the 2023 staircase (min equity $69k on $100k; the 2024-26 period is only ~33%). On $140k → DD ~29%, min equity $109k — size capital for the year-1 dip. More conservative (better early safety, lower profit): RANK1 (H4-origin) / TrueScale.

📋 Mục lục / Contents

  1. Tổng quan / Overview
  2. Cách EA vận hành / How it works
  3. DCA Positive vs DCA Negative
  4. Order Execution
  5. Lot Balance
  6. Flash Crash Protection
  7. Exposure Scale (MaxTotalLot)
  8. Single Round Mode
  9. Support / Resistance
  10. Trend Filter
  11. Sideway Filter
  12. Pivot Point Filter (coop / independent)
  13. Wick Rejection Filter (multi-TF strict)
  14. DCA Parameters
  15. DCA Chain Persistent Mode (v1.35+)
  16. Whipsaw Defense Suite (v1.36-1.37+)
  17. Hedging
  18. Tia (Cluster Scalping)
  19. Tia + DCA TP — cách hoạt động / how it works
  20. Ladder integrity — Anchor / Ladder-roll / Release valve (v1.07+)
  21. Global TP / SL
  22. Clear Stuck Orders
  23. Daily Profit Limit
  24. Risk Management
  25. Trading Time & Weekend
  26. Symbol & Magic
  27. Remote Config & Cloud Sync
  28. Multi-Node Leader Election
  29. Residue Position Management
  30. Info Panel
  31. Panel — 3 dòng Filter (Pivot/Wick/Whip)Panel — 3 Filter lines (Pivot/Wick/Whip)
  32. Order Comment Tags
  33. Preset Config Files

1. Tổng quan

GoldenRobber là Expert Advisor MQL5 được xây dựng cho XAUUSD (vàng), hoạt động theo chiến lược DCA hai chiều có bộ lọc thông minh. Mỗi lần Init mở một round (cùng số R): một chân P (theo trend) và một chân N (ngược trend), lot/TP DCAPos vs DCANeg tương ứng; Add tiếp tục theo loại round (comment). Chốt lời chủ yếu qua Tia cluster; tùy chọn Tia + DCA TP kết hợp TP từng lệnh trên sàn với ngưỡng đóng cụm.

Điểm nổi bật: S/R zones chọn entry chính xác, Trend Filter EMA chặn lệnh ngược xu hướng, Sideway Filter Bollinger tránh mở lệnh trong giai đoạn giá đi ngang, AutoBalance LossTriggered tự động follow-trend để giảm thiệt hại khi flash crash xảy ra. EA tự động quản lý toàn bộ vòng lệnh, cân bằng lot và bảo vệ tài khoản qua nhiều lớp kiểm soát rủi ro.

GoldenRobber is an MQL5 Expert Advisor built for XAUUSD (Gold), operating on a two-sided DCA strategy with intelligent filters. Each Init opens one round (same R id): one P leg (with trend) and one N leg (counter-trend), with DCAPos vs DCANeg lots/TP; Add continues per round type (comments). Profit is harvested mainly via Tia clusters; optional Tia + DCA TP synergy coordinates broker per-order TPs with cluster targets.

Key strengths: S/R zones for precise entries, Trend Filter EMA to block counter-trend orders, Sideway Filter Bollinger to avoid flat markets, AutoBalance LossTriggered to automatically follow-trend and reduce damage during flash crashes. The EA autonomously manages all trade rounds, lot balancing, and account protection through multiple risk-control layers.

Phù hợp vớiSuitable for

  • XAUUSD M15 (khuyến nghị)
  • XAUUSD M15 (recommended)
  • Tài khoản có spread thấp (< 30 điểm)
  • Low spread accounts (< 30 pts)
  • MetaTrader 5 (hedging mode)
  • MetaTrader 5 (hedging mode)
  • Vốn khuyến nghị: $1,000+
  • Recommended capital: $1,000+

⚙️ Tính năng chínhKey features

  • DCA Positive + DCA Negative
  • Support / Resistance zones
  • Trend Filter (EMA)
  • Sideway Filter (Bollinger Bandwidth)
  • Pivot Point Filter (Classic/Fib/Camarilla/Woodie · coop hoặc independent)
  • Lot Balance (Normal / LossTriggered)
  • Daily Profit Limit (target lời/lỗ mỗi ngày)
  • Tỉa lệnh theo cluster (Tia)
  • Cluster scalping (Tia)
  • Bảo vệ cuối tuần
  • Weekend gap protection

2. Cách EA vận hànhHow the EA works

Chu kỳ vòng lệnhTrade Round Cycle

Mỗi round bắt đầu khi EA mở một cặp Init (cùng R{n}): BuySell với nhãn P hoặc N trong comment — UP: Buy=P (lot DCAPos), Sell=N (lot DCANeg); DOWN: Sell=P, Buy=N. MA neutral khi vẫn Init: phân P/N theo nến M1 vừa đóng. Add mở rộng round theo DCAPos hoặc DCANeg (xem mục 3). Vòng có thể kết thúc khi Global TP, Tia cluster / partial, hoặc TP từng lệnh (nếu bật).

Each round starts with one Init pair (same R{n}): Buy and Sell tagged P or N in the comment — uptrend: Buy=P (DCAPos lot), Sell=N (DCANeg lot); downtrend: Sell=P, Buy=N. If MA is neutral but Init is still allowed, P/N follows the last closed M1 candle. Add extends the round as DCAPos or DCANeg (see §3). Rounds may end on Global TP, Tia cluster/partial, or per-order TP (if enabled).

Chu kỳ vòng lệnh GoldenRobber

Sơ đồ: Chu kỳ vòng lệnh của GoldenRobber

Diagram: GoldenRobber trade round lifecycle

Logic mở InitInit trigger logic

Init được kích hoạt khi tất cả điều kiện sau thỏa mãn:

Init is triggered when all of the following conditions are met:

  1. Đang trong cửa sổ giao dịch (StartHour–EndHour)
  2. Within trading window (StartHour–EndHour)
  3. Đã qua cooldown sau lần đóng lệnh cuối (InpWaitAfterCloseSec)
  4. Past cooldown since last close (InpWaitAfterCloseSec)
  5. Đã qua Init cooldown giữa các vòng (InpInitCooldownSec)
  6. Past Init cooldown between rounds (InpInitCooldownSec)
  7. Nến M1 vừa đóng (mỗi bar mới)
  8. New M1 bar just closed
  9. Không có Max Drawdown / Max Loss/Day bị kích hoạt
  10. No Max Drawdown / Max Loss/Day triggered
  11. Chưa đạt Daily Limit (nếu bật: đạt target lời/lỗ trong ngày thì không mở lệnh mới đến hết ngày)
  12. Daily limit not reached (if enabled: once daily profit/loss target hit, no new orders until next day)
  13. Nếu bật Sideway Filter và BlockInit: thị trường không đang sideway
  14. If Sideway Filter on and BlockInit: market is not sideways
  15. Nếu bật Trend Filter + InpTrendFilterApplyInit: vùng neutral quanh MA → không Init (xu hướng không rõ). Khi Init được phép, EA vẫn mở cả Buy và Sell (một P + một N); không còn chặn một phía Init theo trend.
  16. If Trend Filter + InpTrendFilterApplyInit: neutral zone around MA → no Init. When Init is allowed, the EA still opens both Buy and Sell (one P + one N); Init no longer skips one side by trend.

Nhãn Init trong cùng round: Xu hướng UPInit R… P trên Buy, Init R… N trên Sell. Xu hướng DOWN… P trên Sell, … N trên Buy. InpInitRequireMinPips vẫn dùng màu nến M1 để chọn khoảng cách ref (DCAPos vs DCANeg spacing), không đổi nhãn P/N của Init.

Init labels in one round: UPInit R… P on Buy, Init R… N on Sell. DOWN… P on Sell, … N on Buy. InpInitRequireMinPips still uses M1 candle color for distance ref logic (Pos vs Neg spacing), not for changing Init P/N tags.

3. DCA Positive vs DCA Negative

Init luôn có hai chân trong một R: một lệnh gắn P (theo trend tại thời điểm Init, lot/TP DCAPos) và một lệnh N (ngược trend, lot/TP DCANeg). Add thêm lệnh theo loại round suy ra từ comment (DCAPos hoặc DCANeg) và quy tắc MinPips/SR bên dưới.

Init always has two legs in one R: one order tagged P (with trend at Init time, DCAPos lot/TP) and one N (counter-trend, DCANeg lot/TP). Add extends the round per inferred type (DCAPos or DCANeg) using the rules below.

DCAPos — Theo xu hướngTrend-following

Init: một trong hai lệnh mở đầu mang nhãn P (Buy nếu UP, Sell nếu DOWN).

Init: one opening leg is tagged P (Buy if UP, Sell if DOWN).

  • Add: chỉ khi round được phân loại DCAPos (theo comment / ref)
  • Add: only when the round is classified as DCAPos (from comments / refs)
  • Add Buy: giá lên thêm MinPips từ lệnh Buy cao nhất
  • Add Buy: price rises MinPips above highest Buy
  • Add Sell: giá giảm thêm MinPips từ lệnh Sell thấp nhất
  • Add Sell: price drops MinPips below lowest Sell
  • Thêm lệnh cùng chiều di chuyển của giá → average up/down
  • Adds in the same direction as price movement → average up/down

⟹ Phù hợp khi thị trường có xu hướng rõ. Lệnh Buy lời khi giá tăng tiếp, lệnh Sell lời khi giá giảm.

⟹ Best when market has clear trend. Buy profits when price keeps rising, Sell profits when price falls.

DCANeg — Ngược xu hướngCounter-trend

Init: một trong hai lệnh mở đầu mang nhãn N (Sell nếu UP, Buy nếu DOWN).

Init: one opening leg is tagged N (Sell if UP, Buy if DOWN).

  • Add: chỉ khi round được phân loại DCANeg
  • Add: only when the round is classified as DCANeg
  • Add Sell: giá lên thêm MinPips từ Sell cao nhất (DCA ngược — giá tăng nhưng ta thêm Sell)
  • Add Sell: price rises MinPips above highest Sell (counter-DCA — adds Sell as price rises)
  • Add Buy: giá giảm thêm MinPips từ Buy thấp nhất (DCA ngược — giá giảm nhưng ta thêm Buy)
  • Add Buy: price drops MinPips below lowest Buy (counter-DCA — adds Buy as price falls)
  • Thêm lệnh ngược chiều di chuyển → tích lũy kỳ vọng hồi giá
  • Adds against price direction → accumulates expecting reversal

⟹ Rủi ro cao hơn trong trending mạnh. Cần Trend Filter + Sideway Filter để giới hạn.

⟹ Higher risk in strong trends. Use Trend Filter + Sideway Filter to constrain it.

DCAPos vs DCANeg

DCAPos thêm lệnh cùng chiều giá | DCANeg thêm lệnh ngược chiều — chờ hồi giá

DCAPos adds with price direction | DCANeg adds against price — waits for reversal

4. Order Execution

ParameterMặc địnhDefaultMô tảDescription
InpWaitAfterCloseSec60 Cooldown (giây) sau khi đóng hết lệnh trước khi mở Init mới. Tránh vào lệnh ngay sau khi chốt. Cooldown (sec) after all positions close before opening new Init. Prevents re-entry immediately after close.
InpInitCooldownSec60 Thời gian tối thiểu (giây) giữa 2 lần Init liên tiếp. 0 = không giới hạn. Minimum time (sec) between consecutive Inits. 0 = no limit.
InpAddCooldownSec0 Thời gian tối thiểu giữa 2 lần Add. 0 = dùng EntryTimingProfile hoặc WaitAfterClose. Minimum time between Add orders. 0 = use EntryTimingProfile or WaitAfterClose interval.
InpEntryTimingProfileEnabletrue Bật profile timing nội bộ: Init rải ngẫu nhiên trong phút, Add chạy theo tick với interval 1s. Khi bật, InpAddCooldownSec sẽ ghi đè interval của profile nếu > 0. Enable internal timing profile: Init randomized within the minute, Add runs tick-based with 1s interval. When on, InpAddCooldownSec overrides profile interval if > 0.
InpStrongMoveEnabletrue Cho phép mở vòng mới ngay khi nến M1 có range lớn (StrongMove) và volatility cao (ATR). Không cần chờ cooldown thông thường. Allow new round immediately on large M1 candle range (StrongMove) + high ATR volatility. Bypasses normal cooldown.
InpStrongMoveMultiplier1.5 Range nến ≥ MinPips × giá trị này để trigger StrongMove. Candle range ≥ MinPips × this value triggers StrongMove.
InpStrongMoveTFPERIOD_M1 v1.41.2: TF đo range nến StrongMove. M1 = như cũ; M5/M15 để bắt cú chạy mạnh rải nhiều nến (không dồn 1 phút). v1.41.2: TF used to measure StrongMove candle range. M1 = legacy; M5/M15 catch strong runs spread over several candles (not compressed into one minute).
InpStrongMoveBypassFilterfalse v1.41.2: true = init do StrongMove BỎ QUA mọi filter hướng (Trend/Choppy/Wick/Pivot/MultiTf/DualDir/AntiWhip), ép chiều theo màu nến TF trên. VẪN giữ MinPips spacing + timing. v1.41.2: true = StrongMove-triggered init BYPASSES every direction filter (Trend/Choppy/Wick/Pivot/MultiTf/DualDir/AntiWhip), forcing side from the candle colour on the TF above. Still keeps MinPips spacing + timing.
InpStrongMoveRequireSRBreakfalse v1.41.4: StrongMove chỉ hợp lệ khi nến mạnh ĐÓNG vượt đỉnh/đáy N nến gần nhất (breakout thật, lọc spike giả). Decoupled với SR feature — bật riêng, không đụng pass58. v1.41.4: StrongMove only valid when the strong candle CLOSES beyond the recent N-bar high/low (a real breakout, filters fake spikes). Decoupled from the SR feature — independently toggled, does not touch pass58.
InpStrongMoveSRLookback20 Số nến (trên StrongMove TF) để xác định đỉnh/đáy 'cản' gần nhất mà nến mạnh phải phá. Number of candles (on the StrongMove TF) used to define the nearest S/R high/low the strong candle must break.
InpVolatilityATRPeriod14 Chu kỳ ATR để xác nhận volatility cho StrongMove. ATR period for volatility confirmation in StrongMove.
InpVolatilityATRMult1.0 Range nến ≥ ATR × giá trị này để xác nhận volatility đủ mạnh. Candle range ≥ ATR × this value to confirm sufficient volatility.
InpInitRequireMinPipsfalse true = Init round chỉ khi giá đủ xa ref (MinPips). false = cho phép Init theo các nhánh khác (flat, SR, noref, strong, fallback). true = Init only when price is far enough from ref (MinPips). false = allow Init via other branches (flat, SR, noref, strong, fallback).
InpInitNaturalBypassTrendtrue Init tự nhiên (flat / noref / fallback): true = bỏ qua chặn neutral của Trend (vẫn mở cặp P+N); false = vẫn áp Trend — neutral thì không Init. Natural init (flat/noref/fallback): true = bypass Trend neutral block (still opens P+N pair); false = apply Trend — no Init when neutral.
InpInitNaturalFallbackMinBars0 Sau N nến M1 không Init (do filter chặn), cho phép Init tự nhiên (fallback). 0 = tắt. Giá trị nhỏ (vd 5) = fallback rất dễ; nên 60+ để tránh Init toàn fallback. After N M1 bars with no Init (filters blocking), allow natural Init (fallback). 0 = off. Low value (e.g. 5) = fallback very often; use 60+ to avoid init_fallback dominating.
InpInitMinBarRangePips0 Range tối thiểu (pips) của N nến M1 gần nhất để được phép Init. 0 = tắt. Lọc sideway nhẹ. Minimum range (pips) of N recent M1 candles required to Init. 0 = off. Light sideway filter.
InpInitMinBarRangeBars3 Số nến M1 dùng để tính range trung bình (dùng cùng InpInitMinBarRangePips). Number of M1 candles to average range over (with InpInitMinBarRangePips).
InpNoAddWhenInitSameBartrue Không Add trong cùng nến M1 đã mở Init. Tránh đặt quá nhiều lệnh trong cùng một thời điểm. No Add on the same M1 bar that opened Init. Prevents order clustering at a single moment.
InpAddRequireSameSideReffalse true = Add chỉ khi round đã có ít nhất 1 lệnh cùng phía (Init hoặc Add) để làm ref; false = cho phép ref fallback phía kia (Add phía thiếu khi giá đi đủ MinPips). true = Add only when round already has at least one same-side order (Init or Add) as ref; false = allow fallback ref from the other side.
InpMaxAddsPerBarPerSide1 Max lệnh Add mỗi phía (Buy/Sell) mỗi nến M1. 0 = không giới hạn. Luôn áp dụng khi > 0 (kể cả bật Entry Timing Profile) để tránh add_sr/add_minpips nhồi liên tục trong cùng nến. Max Add orders per side (Buy/Sell) per M1 bar. 0 = unlimited. Always enforced when > 0 (even with Entry Timing Profile on) to avoid add_sr/add_minpips clustering in the same bar.
InpMaxOrdersPerRound0 Giới hạn tổng lệnh mỗi phía trong một round. 0 = không giới hạn. Limit total orders per side per round. 0 = unlimited.
InpPriceZonePips0 Kích thước vùng giá (pips). Không Init/Add nếu đã có đủ lệnh trong vùng. 0 = tắt. Price zone size (pips). No Init/Add if enough orders already in zone. 0 = off.
InpMaxOrdersInPriceZone0 Số lệnh tối đa mỗi phía trong một vùng giá. Phải bật cùng InpPriceZonePips > 0. Max orders per side within a price zone. Must use with InpPriceZonePips > 0.
InpMaxOpenPositions0 Tổng vị thế mở tối đa để cho phép mở Init round mới. 0 = không giới hạn. Chặn nhồi lệnh sau crash/sideway — EA vẫn Add DCA vào các round đang mở, chỉ ngăn round mới. Max total open positions allowed before blocking new Init rounds. 0 = unlimited. Prevents over-ordering post-crash/sideways — EA still DCA-adds to existing rounds, only new rounds are blocked.

5. Lot Balance

Lot Balance giúp duy trì sự cân bằng giữa tổng lot Buy và Sell, giảm nguy cơ bị kẹt lệnh khi giá di chuyển một chiều mạnh. Thay vì mở lệnh "Balance" riêng, EA thiên lệch (bias) các lệnh Add DCA về phía yếu hơn.

Lot Balance keeps total Buy and Sell lots approximately equal, reducing stuck-order risk when price moves strongly in one direction. Instead of opening separate "Balance" orders, the EA biases DCA Add orders towards the weaker side.

Lot Balance flow

Khi |Buy−Sell| vượt Trigger → EA chỉ Add về phía yếu hơn cho đến khi đạt Target

When |Buy−Sell| exceeds Trigger → EA only Adds to weaker side until Target is reached

🛡️ LossTriggered — Cơ chế phòng thủ Flash CrashLossTriggered — Flash Crash Defense Khi dùng InpLotBalanceMode = LossTriggered, AutoBalance không hoạt động trong điều kiện bình thường — chỉ kích hoạt khi floating loss ≤ −InpLotBalanceLossTriggerUSD. Khi đó:
(1) InpLotBalanceTrigger bị bỏ qua — balance kích hoạt ngay với bất kỳ chênh lệch lot nào.
(2) Nếu có nhiều Buy hơn Sell: EA ưu tiên Add Sell (follow crash DOWN). Ngược lại: Add Buy (follow rally UP).
(3) InpSRGateAdd=true bị bypass cho phía cần cân bằng — đảm bảo balance add được ngay cả khi không có SR zone gần (giá đang "open air" trong flash crash).
(4) Hoạt động đối xứng cả 2 chiều: crash DOWN hoặc rally UP đều được xử lý đúng, bất kể loại round (DCAPos hay DCANeg).
When using InpLotBalanceMode = LossTriggered, AutoBalance stays idle during normal conditions — only activates when floating loss ≤ −InpLotBalanceLossTriggerUSD. When triggered:
(1) InpLotBalanceTrigger is bypassed — balance fires immediately on any lot imbalance.
(2) If Buy > Sell: EA prioritizes adding Sell (follow crash DOWN). Vice versa: adds Buy (follow rally UP).
(3) InpSRGateAdd=true is bypassed for the balance direction — ensures adds happen even with no SR zone nearby (price in "open air" during a flash crash).
(4) Fully symmetric for both directions: crash DOWN or rally UP both handled correctly, regardless of round type (DCAPos or DCANeg).
Auto Balance ưu tiên — không bị filter chặnAuto Balance priority — not blocked by filters Khi Auto Balance đang ACT (useBalanceBias = true), EA ưu tiên cân bằng và bỏ qua mọi filter cho phía cần Add: Sideway (Block Add), Trend filter, SR gate (InpSRGateAdd), và InpAddRequireSameSideRef (cho phép ref fallback phía cần balance). Áp dụng cả Normal và LossTriggered. When Auto Balance is ACT (useBalanceBias = true), the EA prioritizes rebalancing and bypasses all filters for the side being Added: Sideway (Block Add), Trend filter, SR gate (InpSRGateAdd), and InpAddRequireSameSideRef (allows ref fallback for the balance side). Applies to both Normal and LossTriggered modes.
ParameterMặc địnhDefaultMô tảDescription
InpLotBalanceModeNormal Normal: bias khi |Buy−Sell| > Trigger (hoạt động liên tục). LossTriggered: chỉ kích hoạt khi floating loss ≤ −InpLotBalanceLossTriggerUSD — dùng để phòng thủ flash crash, không can thiệp trong điều kiện bình thường. Normal: bias when |Buy−Sell| > Trigger (always active). LossTriggered: only activates when floating loss ≤ −InpLotBalanceLossTriggerUSD — used for flash crash defense, does not interfere under normal conditions.
InpLotBalanceLossTriggerUSD100 [LossTriggered] Ngưỡng kích hoạt: floating loss ≤ −$N. Đặt phù hợp với kích thước tài khoản (ví dụ: $100k → $2,000). Quá thấp = trigger sai trong DCA bình thường; quá cao = phản ứng chậm. [LossTriggered] Activation threshold: floating loss ≤ −$N. Set according to account size (e.g. $100k → $2,000). Too low = false triggers during normal DCA; too high = slow response to crashes.
InpLotBalanceEnabletrue Bật/tắt Lot Balance.Enable/disable Lot Balance.
InpLotBalanceBypassMaxTradestrue Cho phép Add balance dù đã chạm MaxTrades.Allow balance Add even if MaxTrades is reached.
InpLotBalanceUseTargetLeveltrue Bật: bias cho đến khi |net| ≤ Target. Tắt: chỉ active khi > Trigger. On: bias until |net| ≤ Target. Off: only active when > Trigger.
InpLotBalanceTrigger2.0 [Normal] Ngưỡng (lot): |Buy−Sell| > giá trị này thì bắt đầu bias. [Normal] Threshold (lots): |Buy−Sell| > this starts bias.
InpLotBalanceTarget0.5 Mục tiêu cân bằng (lot): bias dừng khi |Buy−Sell| ≤ giá trị này. Balance target (lots): bias stops when |Buy−Sell| ≤ this.
⚠ Lưu ý về Hedge và Lot Balance Lot Balance tính toán dựa trên lot loại trừ lệnh Hedge. Nếu bật Hedge cùng lúc, Hedge có thể tạo lot ảo làm sai lệch tính toán cân bằng. Khuyến nghị: đặt InpHedgeAfterTrades = 999 để vô hiệu hoá Hedge. Lot Balance calculations exclude Hedge orders. Enabling Hedge simultaneously can create phantom lot differences that skew balance calculations. Recommendation: set InpHedgeAfterTrades = 999 to disable Hedge.

5b. Flash Crash Protection

Phát hiện biến động giá cực mạnh (flash crash) và đóng băng EA để bảo toàn cấu trúc lệnh. Khi trigger: freeze Tia (ngăn đóng cluster non), freeze Init/Add, chạy Fast Balance để cân bằng lot nhanh.

Detects extreme price movements (flash crash) and freezes the EA to preserve order structure. When triggered: freeze Tia (prevent premature cluster closes), freeze Init/Add, run Fast Balance to quickly equalize lots.

Tại sao cần freeze Tia?Why freeze Tia? Trong flash crash, Tia có thể đóng lệnh lời ở phía crash → "đốt" phía đó → tạo gap cấu trúc không thể phục hồi. Freeze giữ nguyên tất cả lệnh, chỉ cân bằng lot. During a flash crash, Tia may close profitable orders on the crash side → "burn" that side → create an unrecoverable structural gap. Freeze preserves all orders, only balancing lots.
ParameterMô tảDescription
InpFlashCrashEnable Bật/tắt Flash Crash detection. Mặc định tắt. Enable/disable Flash Crash detection. Default off.
InpFlashCrashPips Giá chạy ≥ N pips trong window → trigger. Khuyến nghị: 400 (XAUUSD). Price moves ≥ N pips within window → trigger. Recommended: 400 (XAUUSD).
InpFlashCrashWindowSec Cửa sổ thời gian (giây). 180 = 3 phút. Ring buffer sample mỗi giây. Time window (seconds). 180 = 3 minutes. Ring buffer sampled every second.
InpFlashCrashCooldownSec Sau trigger, giữ freeze bao lâu (giây). 1800 = 30 phút. After trigger, keep freeze for how long (seconds). 1800 = 30 minutes.
InpFlashCrashBalanceIntervalSec Interval giữa các lệnh Fast Balance khi crash active (giây). Interval between Fast Balance orders during active crash (seconds).
InpFlashCrashBalanceMaxLot Max lot mỗi lệnh Fast Balance. Lệnh balance không có TP, không bị VirtualTP đóng. Max lot per Fast Balance order. Balance orders have no TP, not closed by VirtualTP.

5c. Exposure Scale (MaxTotalLot)

Giới hạn tổng lot (Buy+Sell) bằng cách giảm dần lot mới khi gần ngưỡng — không bao giờ block hoàn toàn, tránh deadlock. Áp dụng cho Init, DCA Add, và Hedge.

Limits total lots (Buy+Sell) by gradually reducing new lot sizes as exposure approaches the cap — never fully blocks, avoiding deadlock. Applies to Init, DCA Add, and Hedge.

ParameterMô tảDescription
InpMaxTotalLot Tổng lot tối đa. 0 = không giới hạn. Scale bắt đầu giảm từ 80% max. Ví dụ: max=5.0 → lot bình thường cho đến 4.0, giảm dần 4.0–5.0, minLot tại 5.0. Max total lots. 0 = unlimited. Scale starts reducing at 80% of max. Example: max=5.0 → normal lots up to 4.0, gradual reduction 4.0–5.0, minLot at 5.0.
Tại sao dùng scale thay vì hard block?Why scale instead of hard block? Hard block (MaxTrades, MaxOpenPositions) gây deadlock: khi đạt max, EA không mở lệnh mới → Tia không có nguyên liệu → lệnh kẹt vĩnh viễn. Scale giảm lot nhưng vẫn mở → Tia luôn có lệnh mới để tạo cluster. Hard block (MaxTrades, MaxOpenPositions) causes deadlock: at max, EA can't open new orders → Tia has no material → orders stuck forever. Scale reduces lots but still opens → Tia always has new orders for clusters.

5d. Single Round Mode

Chế độ chạy 1 round tại 1 thời điểm — chỉ Init round mới sau khi round trước đã đóng hết tất cả lệnh. Giới hạn số adds per round để kiểm soát exposure.

One round at a time mode — only Init a new round after all positions from the previous round are fully closed. Limits adds per round to control exposure.

ParameterMô tảDescription
InpSingleRoundMode true = chỉ Init round mới khi round trước đã đóng hết. false = cho phép nhiều round chạy song song (mặc định). true = only Init new round when previous round is fully closed. false = allow multiple concurrent rounds (default).
InpSingleRoundMaxAdds Max tổng adds (Buy+Sell) trong round hiện tại. 0 = không giới hạn. Ví dụ: 20 → tối đa 20 lệnh DCA add (không tính Init). Max total adds (Buy+Sell) in current round. 0 = unlimited. Example: 20 → max 20 DCA add orders (excluding Init).

6. Support / Resistance

EA tự động phát hiện vùng S/R từ swing high/low và ưu tiên đặt lệnh tại các vùng này thay vì chỉ dựa vào khoảng cách MinPips. Vùng được chấm điểm dựa trên số lần touch, impulse sau swing và confluence với timeframe cao hơn.

The EA auto-detects S/R zones from swing highs/lows and prioritizes entries at these zones instead of relying solely on MinPips distance. Zones are scored by touch count, post-swing impulse, and higher timeframe confluence.

Cơ chế 3 lớp3-Layer mechanism

#LớpLayerCơ chếMechanism
1 Phát hiện SwingSwing Detection Tìm swing high/low trong LookbackBars nến với SwingLeft/Right nến xác nhận Find swing H/L within LookbackBars candles, confirmed by SwingLeft/Right candles
2 Chấm điểm ZoneZone Scoring +1 điểm mỗi touch, +1 nếu impulse sau swing ≥ ATR×ImpulseMult, +2 nếu trùng với HTF +1 per touch, +1 if post-swing impulse ≥ ATR×ImpulseMult, +2 if HTF confluence
3 Xác nhận nếnCandle Confirmation Buy ở Support cần nến xanh trên InpSRTF; Sell ở Resistance cần nến đỏ Buy at Support needs green candle on InpSRTF; Sell at Resistance needs red
ParameterGiá trị gợi ý (M15/H1)Suggested (M15/H1)Mô tảDescription
InpSupportResistanceEnablefalse Bật S/R entry mode.Enable S/R entry mode.
InpSupportResistancePips15–20 Khoảng cách "gần" zone (pips). XAUUSD: 15–25. "Near zone" distance (pips). XAUUSD: 15–25.
InpSRTFM15 Timeframe build zone (nên = TF chart đang chạy). Zone-building timeframe (should match chart TF).
InpSRConfluenceTFH1 / H4 TF cao hơn để confluence. Zone trùng → score cao hơn. Higher TF for confluence. Matching zone → higher score.
InpSRMinScore2–3 Score tối thiểu để zone được dùng. Tăng → chặt chẽ hơn. Minimum score to use zone. Higher = stricter.
InpSRRequireCandleConfirmtrue Yêu cầu xác nhận nến tại zone (khuyến nghị bật). Require candle confirmation at zone (recommended on).
InpSRDrawZonestrue Hiển thị vùng S/R lên chart (chỉ visual, không ảnh hưởng logic khi SR trading tắt). Draw S/R zones on chart (visual only; works independently of SR trading toggle).
InpSupportResistanceApplyInittrue Áp dụng S/R cho Init: khi giá gần zone đủ điểm → cho phép Init (bỏ qua MinPips nếu bật). Apply S/R to Init: when price near zone with enough score → allow Init (bypass MinPips if required).
InpSupportResistanceApplyAddtrue Áp dụng S/R cho Add: Add tại zone có thể bỏ qua MinPips (hoặc bắt buộc gần SR nếu InpSRGateAdd=true). Apply S/R to Add: Add at zone may bypass MinPips (or require near SR when InpSRGateAdd=true).
InpSRGateAddfalse false = Add khi gần SR (bypass MinPips) HOẶC đủ MinPips. true = CHỈ Add khi gần SR zone (SR là cổng bắt buộc). false = Add when near SR (bypass MinPips) OR when MinPips satisfied. true = Add ONLY when near SR zone (SR is mandatory gate).

7. Trend Filter

Sử dụng EMA trên timeframe cao hơn để chặn Init khi trend không rõ. Vùng neutral (giá trong band quanh MA): không Init. Khi trend rõ (UP/DOWN), Init vẫn mở cả hai phía với nhãn P/N đúng chân (không còn “chỉ Buy” hay “chỉ Sell” Init). Add vẫn có thể dùng filter để hạn chế lệnh ngược trend (InpTrendFilterApplyAdd). Init tự nhiên + InpInitNaturalBypassTrend bỏ qua chặn neutral cho nhánh flat/noref/fallback.

Uses a higher timeframe EMA to block Init when trend is unclear. Neutral zone (price inside band around MA): no Init. When trend is clear (UP/DOWN), Init still opens both sides with correct P/N legs (no longer “Buy-only” or “Sell-only” Init). Add can still use the filter to limit counter-trend orders (InpTrendFilterApplyAdd). Natural init + InpInitNaturalBypassTrend bypasses the neutral block for flat/noref/fallback.

Lưu ý: Trend Filter + Tia BotDCA StyleNote: Trend Filter + Tia BotDCA Style Khi Trend Filter chỉ cho phép 1 chiều mở lệnh (vd chỉ Sell trong downtrend), Tia BotDCA Style sẽ tự động chuyển sang fallback mode: cho phép đóng cluster cùng chiều khi đủ profit. Điều này đảm bảo lệnh luôn có cơ chế thoát, không bị kẹt vô thời hạn. When Trend Filter allows only one direction (e.g. only Sell in downtrend), Tia BotDCA Style automatically switches to fallback mode: allows same-direction cluster close when profit target met. This ensures positions always have an exit mechanism and don't get stuck indefinitely.
ParameterMặc địnhDefaultMô tảDescription
InpTrendFilterEnablefalse Bật/tắt Trend Filter.Enable/disable Trend Filter.
InpTrendFilterTFH4 Timeframe tính EMA. H1 hoặc H4 là phổ biến cho XAUUSD M15. EMA timeframe. H1 or H4 common for XAUUSD M15.
InpTrendFilterMAPeriod50 Chu kỳ EMA. 50 hoặc 200 phổ biến. EMA period. 50 or 200 are common.
InpTrendFilterApplyInittrue Áp dụng cho Init: neutral → không mở vòng mới; UP/DOWN → vẫn mở cặp P+N (không chặn một phía). Apply to Init: neutral → no new round; UP/DOWN → still opens P+N pair (no one-sided Init skip).
InpTrendFilterApplyAddtrue Áp dụng cho Add (chặn thêm lệnh ngược trend). Apply to Add (block counter-trend Add orders).
InpTrendFilterNeutralPips5 Vùng neutral (pips) quanh MA. Trong vùng này: không đặt Init (trend không rõ); Add vẫn được phép. Neutral zone (pips) around MA. In this zone: no Init (trend unclear); Add still allowed.

🎯 Tune Trend Filter — 2 input numeric quan trọng 🎯 Tune Trend Filter — 2 key numeric inputs

Section này focus vào 2 input bạn cần gõ số: InpTrendFilterMAPeriod (chu kỳ EMA) và InpTrendFilterNeutralPips (deadzone). Combo MA + Neutral quyết định Trend Filter responsive hay strict.

This section focuses on the 2 inputs you actually type numbers into: InpTrendFilterMAPeriod (EMA period) and InpTrendFilterNeutralPips (deadzone). The MA + Neutral combo determines whether Trend Filter is responsive or strict.

   ↑
   │  price > EMA + NeutralPips  →  trend = UP ✅
+N ─┼─────── ─────── ─────── ─── (EMA + NeutralPips)
   │  ┌─────────────────────┐
   │  │   NEUTRAL DEADZONE   │  ← price in band → trend = 0 (Init blocked)
   │  │   (trend not clear)  │
0  ─┼── ──── EMA line ──── ── (EMA, period = MAPeriod)
   │  │                      │
   │  └─────────────────────┘
-N ─┼─────── ─────── ─────── ─── (EMA - NeutralPips)
   │  price < EMA - NeutralPips  →  trend = DOWN ✅
   ↓

📊 Bảng khuyến nghị: MAPeriod + NeutralPips theo TF (XAU) 📊 Recommended values: MAPeriod + NeutralPips by TF (XAU)

Cho mỗi TF, chọn 1 trong 3 style. Số trong cell = giá trị bạn gõ trực tiếp vào EA Inputs. Cột Balanced ⭐ là default khuyến nghị.

For each TF, pick 1 of 3 styles. Numbers in cells = values you type directly into EA Inputs. Balanced ⭐ column is the recommended default.

TF 🔥 Aggressive (nhiều trade, noise)🔥 Aggressive (more trades, noise) ⭐ Balanced (default)⭐ Balanced (default) 🛡️ Conservative (ít trade, chất lượng)🛡️ Conservative (fewer trades, quality)
MAPeriodNeutralPips MAPeriodNeutralPips MAPeriodNeutralPips
M5 105 2010 5020
M15 1010 2025 5050
M30 1015 2040 5080
H1 2025 5060 200120
H4 2060 50120 200250

📌 Configs đã backtest dùng số nào? 📌 What did backtested configs use?

ConfigConfig TF MAPeriod NeutralPips Kết quảResult
A baseline (17-05-2026_02-43.set) M30 20 50 $212k, PF 1.10, Win 72% (Conservative cho M30) $212k, PF 1.10, Win 72% (Conservative for M30)
21-05-2026 (Sharpe 3.24) ⭐ M15 20 50 $119k, PF 1.12, Win 80% (Conservative cho M15) $119k, PF 1.12, Win 80% (Conservative for M15)
❌ $194k disaster M3 50 5 PF 1.05, avg loss DOUBLE — AVOID PF 1.05, avg loss DOUBLES — AVOID

🎚️ Hiểu hành vi của 2 input 🎚️ Understanding behavior of the 2 inputs

InpTrendFilterMAPeriod
  • 10–20: EMA chạy sát giá → trend đổi nhanh → bắt reversal sớm. Phù hợp scalp.
  • 10–20: EMA hugs price → trend changes fast → catches reversals early. Suited for scalp.
  • 50: EMA mượt vừa phải → classic balance. Phổ biến nhất.
  • 50: Moderately smooth → classic balance. Most common.
  • 200: EMA chậm, chỉ phản ánh trend dài hạn. Phù hợp swing/position.
  • 200: Slow, only reflects long-term trend. Suited for swing/position.
InpTrendFilterNeutralPips
  • Nhỏ (5–15): deadzone hẹp → trend confirm sớm → nhiều trade, nhiều noise.
  • Small (5–15): narrow deadzone → trend confirms early → more trades, more noise.
  • Trung bình (20–50): balance. Phù hợp với MA period 20–50.
  • Medium (20–50): balance. Pairs with MA period 20–50.
  • Lớn (60–250): deadzone rộng → strict confirmation → ít trade nhưng quality cao.
  • Large (60–250): wide deadzone → strict confirmation → fewer trades but higher quality.
💡 Quy tắc match TFTF matching rule TF cao hơn → biên độ giá rộng hơn → NeutralPips lớn hơn. Khi đổi TF từ M15 → H1, nhân NeutralPips ~2–3 lần để giữ ngữ nghĩa "strict tương đương". VD M15 NeutralPips=25 → H1 NeutralPips=60. Higher TF → wider price swings → larger NeutralPips. When switching TF from M15 → H1, multiply NeutralPips by ~2–3× to keep "equivalent strictness". E.g. M15 NeutralPips=25 → H1 NeutralPips=60.
⚠️ Combo cần tránhAvoid combos

8. Sideway Filter (Bollinger)

Phát hiện thị trường đi ngang bằng Bollinger Bandwidth: (Upper−Lower)/Middle < ngưỡng = sideway. Có thể chọn chặn Init và/hoặc chặn Add khi sideway. Cache refresh mỗi bar M1 và trước khi cập nhật panel.

Detects ranging market via Bollinger Bandwidth: (Upper−Lower)/Middle < threshold = sideways. You can block Init and/or block Add when sideways. Cache refreshes on each M1 bar and before panel update.

📊 Chế độ thông thường (ATRNormalize = false)Standard mode (ATRNormalize = false) Bandwidth tuyệt đối: (Upper−Lower)/Middle. M1 median ~0.002. Dùng InpSidewayBBBandwidthMax ≈ 0.002. Đơn giản, nhưng bị ảnh hưởng bởi mức giá — sau flash crash bandwidth phồng cao làm filter kém hiệu quả. Absolute bandwidth: (Upper−Lower)/Middle. M1 median ~0.002. Use InpSidewayBBBandwidthMax ≈ 0.002. Simple, but affected by price level — post-crash bandwidth inflates, reducing filter effectiveness.
📊 Chế độ ATR-normalized (ATRNormalize = true)ATR-normalized mode (ATRNormalize = true) Bandwidth chia cho ATR tương đối: (U−L)/M ÷ (ATR/M) = (U−L)/ATR. Dimensionless, tự adapt theo volatility — dùng chung cho XAU, BTC v.v. Ngưỡng khuyến nghị ≈ 3.10. Bandwidth divided by relative ATR: (U−L)/M ÷ (ATR/M) = (U−L)/ATR. Dimensionless, self-adapts to volatility — works across XAU, BTC etc. Recommended threshold ≈ 3.10.
ParameterMặc địnhDefaultMô tảDescription
InpSidewayFilterEnablefalse Bật/tắt Sideway Filter.Enable/disable Sideway Filter.
InpSidewayTFM1 Timeframe Bollinger. M1 = nhạy cao, phản ứng nhanh với sideway ngắn hạn. Bollinger timeframe. M1 = high sensitivity, reacts fast to short-term sideways.
InpSidewayBBPeriod14 Chu kỳ Bollinger Bands (nên bằng InpSidewayATRPeriod). Bollinger Bands period (should equal InpSidewayATRPeriod).
InpSidewayBBDeviation2.0 Độ lệch chuẩn (2.0 chuẩn).Standard deviation (2.0 standard).
InpSidewayBBBandwidthMax0.002 Ngưỡng sideway. ATRNormalize=false: (U−L)/M < giá trị này (~0.002 cho M1). ATRNormalize=true: (U−L)/ATR < giá trị này (~3.10). Sideways threshold. ATRNormalize=false: (U−L)/M < this value (~0.002 for M1). ATRNormalize=true: (U−L)/ATR < this value (~3.10).
InpSidewayATRNormalizefalse true = dùng (U−L)/ATR — tự adapt theo volatility, hiệu quả sau flash crash. false = bandwidth tuyệt đối (mặc định). true = use (U−L)/ATR — self-adapts to volatility, effective post-crash. false = absolute bandwidth (default).
InpSidewayATRPeriod14 Chu kỳ ATR cho chế độ normalized. Nên bằng InpSidewayBBPeriod. ATR period for normalized mode. Should equal InpSidewayBBPeriod.
InpSidewayBlockInittrue Chặn mở round mới (Init) khi sideway.Block new round (Init) when sideways.
InpSidewayBlockAddtrue Chặn Add (cả DCAPos và DCANeg) khi sideway. Block Add (both DCAPos and DCANeg) when sideways.
InpSidewayAllowNaturalInittrue true = Init tự nhiên (flat / noref / fallback) không bị Sideway chặn; false = Sideway cũng chặn Init tự nhiên. true = natural init (flat/noref/fallback) is not blocked by Sideway; false = Sideway also blocks natural init.

8b. Pivot Point Filter (v1.19+, Auto-method v1.21+)

EA tính các mức Pivot Point (PP) + 3 cấp Support/Resistance (S1–S3 / R1–R3) từ H/L/C của bar đã đóng trên InpPivotTF (D1 / W1 / MN1). Logic gate: Buy chỉ được phép khi ask gần một level Support (PP/S1/S2/S3); Sell chỉ được khi bid gần một level Resistance (PP/R1/R2/R3). Khoảng "gần" cấu hình qua InpPivotProximityPips.

The EA computes Pivot Point (PP) + three S/R levels (S1–S3 / R1–R3) from the H/L/C of the previous closed bar on InpPivotTF (D1 / W1 / MN1). Gate logic: Buy allowed only when ask is near a Support level (PP/S1/S2/S3); Sell allowed only when bid is near a Resistance level (PP/R1/R2/R3). The "near" threshold is configured via InpPivotProximityPips.

🎯 Coop vs IndependentCoop vs Independent
Pivot Point hỗ trợ 2 chế độ vận hành thông qua InpPivotFilterIndependent: Pivot Point operates in 2 modes via InpPivotFilterIndependent:

4 phương pháp tính + Auto4 calculation methods + Auto

InpPivotMethod PP R1 / S1 R2 / S2 R3 / S3 Đặc tínhCharacteristic
0 — Classic (H+L+C)/3 2·PP − L / 2·PP − H PP ± (H−L) H + 2·(PP−L) / L − 2·(H−PP) Tiêu chuẩn truyền thống, dùng phổ biến nhất.Traditional standard, most widely used.
1 — Fibonacci (H+L+C)/3 PP ± 0.382·(H−L) PP ± 0.618·(H−L) PP ± 1.000·(H−L) Levels theo tỉ lệ Fibonacci, tạo cụm gần PP hơn.Levels via Fibonacci ratios, clustered closer to PP.
2 — Camarilla (H+L+C)/3 C ± (H−L)·1.1/12 C ± (H−L)·1.1/6 C ± (H−L)·1.1/4 Levels xoay quanh Close. Cấp gần (R1/S1) rất sát giá → nhiều cơ hội intraday.Levels orbit around Close. Inner levels (R1/S1) tightly hug price → many intraday opportunities.
3 — Woodie (H+L+2C)/4 2·PP − L / 2·PP − H PP ± (H−L) H + 2·(PP−L) / L − 2·(H−PP) Giống Classic nhưng PP trọng số Close ×2 → nhạy hơn với close gần đây.Similar to Classic but PP weights Close ×2 → more responsive to recent close.
4 — Auto (v1.21+) EA tự chọn 1 trong 4 method (0-3) dựa trên phân tích bar 1 của InpPivotTF. Resolved method lock trong cả pivot bar (D1/W1/MN1), re-evaluate khi bar mới đóng. Xem cây quyết định bên dưới. EA picks one of 4 methods (0-3) by analyzing bar 1 of InpPivotTF. Resolved method is locked for the entire pivot bar (D1/W1/MN1), re-evaluated on bar close. See decision tree below. Adaptive — tự thích nghi market regime hàng ngày, không cần user pick.Adaptive — auto-adapts to daily market regime, no manual selection needed.
🤖 Cây quyết định Auto (InpPivotMethod=4)Auto decision tree (InpPivotMethod=4)

Mỗi khi bar mới của InpPivotTF đóng, EA phân tích 3 tín hiệu từ bar 1:

When a new bar of InpPivotTF closes, the EA analyzes 3 signals from bar 1:

Tín hiệuSignal Công thứcFormula Ý nghĩaMeaning
Range ratio(H−L) / ATR(InpPivotTF, 14) < InpPivotAutoLowVolRatio = sideway; > InpPivotAutoHighVolRatio = breakout < InpPivotAutoLowVolRatio = sideway; > InpPivotAutoHighVolRatio = breakout
Body ratio|C−O| / (H−L) > InpPivotAutoBodyThresh = nến full body (strong directional) > InpPivotAutoBodyThresh = full body candle (strong directional)
Close position(C−L) / (H−L) ≥ 0.7 hoặc ≤ 0.3 = close cực (bullish/bearish bias) ≥ 0.7 or ≤ 0.3 = extreme close (bullish/bearish bias)
1. range_ratio < LowVolRatio (0.7)?           → Camarilla  [sideway, scalp tight zones]
2. body_ratio > BodyThresh (0.65)
   AND close_position ≥0.7 hoặc ≤0.3 ?       → Woodie     [strong momentum, close-weighted PP]
3. range_ratio > HighVolRatio (1.4)?         → Classic    [breakout day, wide levels]
4. default (medium range, no clear bias)     → Fibonacci  [conservative entry near PP]

Khi method switch, EA log Print("Pivot auto-resolved: <name>") để theo dõi trong tab Experts.

On method switch, the EA logs Print("Pivot auto-resolved: <name>") for tracking in Experts tab.

Tham sốParameters

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpPivotFilterEnablefalse Bật/tắt Pivot Point filter. Tắt = không gate, không vẽ lines. Enable/disable Pivot Point filter. Off = no gating, no lines.
InpPivotFilterIndependentfalse false (coop) = AND với Trend/Sideway/S-R. true (independent) = bypass tất cả filter khác, chỉ Pivot quyết định direction. false (coop) = AND with Trend/Sideway/S-R. true (independent) = bypass all other filters, only Pivot decides direction.
InpPivotTFD1 Timeframe lấy H/L/C: D1 (daily — chuẩn, reset lúc server midnight), W1 (weekly — reset thứ 2), MN1 (monthly). Hỗ trợ tất cả 21 TF của MQL5 nhưng <H1 không khuyến khích (levels nhảy liên tục). TF for H/L/C source: D1 (daily — standard, resets at server midnight), W1 (weekly — resets Monday), MN1 (monthly). All 21 MQL5 TFs supported but <H1 not recommended (levels reset too frequently).
InpPivotMethodClassic Dropdown (v1.22+, ENUM_PivotMethod): Classic / Fibonacci / Camarilla / Woodie / Auto. Chọn trực tiếp tên method trong EA Properties → Inputs tab, không cần nhớ số. Xem bảng phương pháp. Dropdown (v1.22+, ENUM_PivotMethod): Classic / Fibonacci / Camarilla / Woodie / Auto. Pick directly by name in EA Properties → Inputs tab — no need to memorize numbers. See methods table.
InpPivotProximityPips30.0 Khoảng "gần" pivot: |price − level| ≤ N pips. Lớn = nhiều trigger; nhỏ = chính xác hơn. "Near" threshold: |price − level| ≤ N pips. Larger = more triggers; smaller = stricter.
InpPivotMaxLevel2 Cấp S/R cao nhất xét: 0 = chỉ PP, 1 = PP + S1/R1, 2 = + S2/R2, 3 = + S3/R3. Càng cao càng nhiều entry zone, nhưng cấp xa (S3/R3) thường ở vùng extreme đầu/cuối phiên. Highest S/R level used: 0 = PP only, 1 = PP + S1/R1, 2 = + S2/R2, 3 = + S3/R3. Higher = more zones, but far levels (S3/R3) sit at session extremes.
InpPivotApplyInittrue Áp dụng cho Init: chặn phía không gần pivot level tương ứng. Apply to Init: block side not near the matching pivot level.
InpPivotApplyAddtrue Áp dụng cho Add (DCAPos + DCANeg): chặn phía không gần pivot. AutoBalance ACT bypass cho phía cần cân. Apply to Add (DCAPos + DCANeg): block side not near pivot. AutoBalance ACT bypasses for the side needing rebalance.
InpPivotDrawLinestrue Vẽ pivot lines (HLINE dotted) lên chart. Tự refresh khi sang bar mới của InpPivotTF, tự cleanup khi tắt EA. Draw pivot lines (HLINE dotted) on chart. Auto-refresh on new bar of InpPivotTF, auto-cleanup on EA detach.
InpPivotColorPPclrYellow Màu đường Pivot Point.Pivot Point line color.
InpPivotColorSupportclrLime Màu các đường Support (S1/S2/S3).Support line color (S1/S2/S3).
InpPivotColorResistanceclrTomato Màu các đường Resistance (R1/R2/R3).Resistance line color (R1/R2/R3).

Auto-method tuning (chỉ dùng khi InpPivotMethod=4)Auto-method tuning (only when InpPivotMethod=4)

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpPivotAutoUseATRtrue Dùng ATR ratio (range/ATR14) làm gate cho rule 1 (sideway→Cam) và rule 3 (breakout→Cls). Tắt = bỏ qua 2 rule đó, chỉ còn rule 2 (body→Wood) và rule 4 (default→Fib). Cần thêm 1 ATR handle trên InpPivotTF (auto release on detach). Use ATR ratio (range/ATR14) to gate rule 1 (sideway→Cam) and rule 3 (breakout→Cls). Off = skip those rules, only rule 2 (body→Wood) and rule 4 (default→Fib) remain. Requires one extra ATR handle on InpPivotTF (auto-released on detach).
InpPivotAutoLowVolRatio0.7 Rule 1: bar 1 range/ATR14 < ngưỡng này → coi là sideway/low-vol → chọn Camarilla. Tăng = Camarilla được chọn rộng hơn; giảm = strict hơn. Rule 1: bar 1 range/ATR14 < this threshold → treated as sideway/low-vol → pick Camarilla. Increase = wider Camarilla zone; decrease = stricter.
InpPivotAutoHighVolRatio1.4 Rule 3: bar 1 range/ATR14 > ngưỡng này → coi là breakout day → chọn Classic (levels trải rộng, không bị xuyên ngay). Giảm = Classic active sớm hơn. Rule 3: bar 1 range/ATR14 > this threshold → treated as breakout day → pick Classic (wide levels, less likely to be pierced immediately). Decrease = Classic activates earlier.
InpPivotAutoBodyThresh0.65 Rule 2: |C-O|/(H-L) > ngưỡng này AND close cực (≥0.7 hoặc ≤0.3) → coi là full-body directional → chọn Woodie. Tăng = strict (cần body lớn hơn mới chọn Woodie). Rule 2: |C-O|/(H-L) > this threshold AND extreme close (≥0.7 or ≤0.3) → treated as full-body directional → pick Woodie. Increase = stricter (need larger body to pick Woodie).

Init reason tag mớiNew Init reason tag

Khi Pivot là trigger cho phép Init (không gần S/R nhưng gần pivot level), comment lệnh sẽ chứa tag |init_pivot thay vì |init_sr. Dùng để phân biệt nguồn entry khi review history. Khi gần cả S/R và Pivot, ưu tiên tag |init_sr (giữ tương thích với log cũ).

When Pivot is the trigger that allows Init (price not near S/R but near a pivot level), the order comment carries |init_pivot instead of |init_sr. Useful for filtering entry sources during history review. When near both S/R and Pivot, the |init_sr tag wins (backward compatible with existing logs).

Hiển thị panelInfo Panel display

Khi InpPivotFilterEnable=true, panel hiện thêm dòng:

When InpPivotFilterEnable=true, the panel shows an extra line:

Manual:  Pivot[Cls/COOP]: SUPP | PP=2345.67
Auto:    Pivot[auto→Cam/INDEP]: RES | PP=2345.67

Màu xanh lá = đang gần ít nhất 1 level (có thể trade); xám = giá xa tất cả (filter chặn).

Lime = near at least one level (trades allowed); silver = price far from all (filter blocks).

Use cases khuyến nghịRecommended use cases

🤝 Coop modeCoop mode

  • Thêm "second opinion" cho cấu hình hiện có (Trend + Sideway + S-R đang chạy ổn).
  • Add a "second opinion" to existing setups (Trend + Sideway + S-R already running well).
  • Lọc thêm để giảm false signal: chỉ trade khi giá ở vùng pivot quan trọng.
  • Tighter filtering to reduce false signals: only trade at key pivot zones.
  • Set InpPivotMaxLevel=1 nếu muốn restrictive (chỉ trade quanh PP và S1/R1).
  • Set InpPivotMaxLevel=1 for restrictive mode (only trade around PP and S1/R1).

🎯 Independent modeIndependent mode

  • Strategy mean-reversion thuần: trade bounce ở các pivot level mà không cần trend confirm.
  • Pure mean-reversion strategy: trade bounces at pivot levels without trend confirmation.
  • Set InpPivotMaxLevel=2-3 để có nhiều entry zone hơn (do không có filter khác bù đắp).
  • Set InpPivotMaxLevel=2-3 for more entry zones (since other filters won't compensate).
  • Phù hợp khi thị trường range-bound (sideway dài), nơi Trend/Sideway filter thường chặn quá nhiều.
  • Suited for range-bound markets where Trend/Sideway filters tend to over-block.

🤖 Khi nào dùng Auto-method (v1.21+)When to use Auto-method (v1.21+)

Khuyến nghị bật AutoRecommended ON

  • Bạn chưa quyết được method nào hợp nhất với XAU/symbol của mình — để EA tự thử nghiệm hàng ngày.
  • You're not sure which method fits your XAU/symbol best — let the EA auto-adapt daily.
  • Thị trường thường xuyên đổi regime (trending ↔ ranging) — Auto đảm bảo dùng đúng method cho mỗi ngày.
  • Market regime shifts frequently (trending ↔ ranging) — Auto ensures the right method per day.
  • Backtest dài hạn (≥ 6 tháng) — Auto cho recovery factor cao hơn vs single method cố định trong môi trường biến đổi.
  • Long backtest periods (≥ 6 months) — Auto produces higher recovery factor than fixed single method in changing environments.
  • Setup gợi ý: InpPivotMethod=4, InpPivotAutoUseATR=true, giữ mặc định ngưỡng.
  • Suggested setup: InpPivotMethod=4, InpPivotAutoUseATR=true, keep default thresholds.

Khi không nên dùng AutoWhen NOT to use Auto

  • Bạn đã backtest và verify method cụ thể (vd Camarilla) hoạt động tốt nhất → set thẳng InpPivotMethod=2, không cần Auto.
  • You've backtested and verified a specific method (e.g. Camarilla) works best → set InpPivotMethod=2 directly, no Auto needed.
  • Cần predictability tuyệt đối (vd strategy chính xác cho từng level cụ thể) — Auto switch method giữa các ngày có thể tạo log khó debug.
  • Need absolute predictability (e.g. strategy keyed to specific levels) — Auto's method switching creates harder-to-debug logs.
  • Backtest ngắn hạn (< 1 tháng) — Auto có thể chưa hit đủ regime variety để rule kick in, kết quả như fixed method nhưng overhead ATR cao hơn.
  • Short backtest (< 1 month) — Auto may not hit enough regime variety for rules to activate; behaves like fixed method but with ATR overhead.
💡 Cách verify Auto đang chọn method nàoHow to verify which method Auto picks 3 cách check: (1) panel hiển thị auto→Cam, (2) tab Experts/Journal log Pivot auto-resolved: Camarilla (bar YYYY.MM.DD), (3) so sánh giá trị PP/S/R trên chart với công thức từng method để verify đúng. 3 ways to check: (1) panel shows auto→Cam, (2) Experts/Journal tab logs Pivot auto-resolved: Camarilla (bar YYYY.MM.DD), (3) compare chart PP/S/R values against each method's formula.

8c. Wick Rejection Filter (v1.24+)

Phân tích râu nến (wick/shadow) trên 2 TF cùng lúc để loại bỏ Init/Add ở vùng giá vừa bị từ chối. Logic Mode A directional: râu trên dài → sellers reject high → block BUY; râu dưới dài → buyers reject low → block SELL. Multi-TF AND: CẢ TF1 (default M15) và TF2 (default H1) phải đồng thuận có rejection → giảm false signals.

Analyzes candle wicks/shadows on 2 TFs simultaneously to skip Init/Add in price-rejection zones. Mode A directional: long upper wick → sellers reject high → block BUY; long lower wick → buyers reject low → block SELL. Multi-TF AND: BOTH TF1 (default M15) AND TF2 (default H1) must agree on rejection → reduced false signals.

        H ─┬─    H ─┬─        H ─┬─    H ─┬─
           │       │              │   ┌──┘
           │   ┌──┘               │   │
        ┌──┘   │                  │   └──┐
        │     │                   │      │
        └──┐  │                   └──┐   │
           │  └──┐                   │   │
           │     │                   │   │
        L ─┴─    L ─┴─               L ─┴─
        NORMAL   UPPER WICK         LOWER WICK
        candle    REJECT BUY ❌      REJECT SELL ❌
                  (sellers strong)   (buyers strong)

Khi RÂU TRÊN dài trên cả TF1 + TF2 → sellers thắng tại high → không Buy (vẫn cho Sell nếu thoả filter khác).

When UPPER WICK long on both TF1 + TF2 → sellers won at high → no Buy (Sell still allowed if other filters pass).

Công thức rejectionRejection formula

Thành phầnComponent Công thứcFormula Ý nghĩaMeaning
body|C − O| Độ rộng thân nếnBody height
upperWickH − max(C, O) Râu trên (từ thân lên đến high)Upper wick (from body to high)
lowerWickmin(C, O) − L Râu dướiLower wick
rangeH − L Tổng biên độ nếnTotal candle range
Rejection condition wick ≥ body × ToBodyRatio
AND
wick ≥ range × ToRangeMin
Cả 2 điều kiện phải thoả mới count rejectionBoth conditions must hold
Doji edge caseDoji edge case body == 0 Bỏ qua ToBodyRatio, chỉ check ToRangeMinSkip ToBodyRatio, only check ToRangeMin

Tham sốParameters

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpWickFilterEnablefalse Bật/tắt master switch.Master on/off.
InpWickFilterTF1M15 TF kiểm tra wick #1 (fast — phản ánh nhịp gần). Khuyến nghị M15 cho XAU intraday DCA. Wick check TF #1 (fast — recent action). M15 recommended for XAU intraday DCA.
InpWickFilterTF2H1 TF kiểm tra wick #2 (slow — confirmation mạnh hơn). AND logic với TF1 — cả 2 phải agree mới block. Wick check TF #2 (slow — stronger confirmation). AND logic with TF1 — both must agree to block.
InpWickLookbackBars2 Check N bar gần nhất (bar 1 đến bar N). 1=chỉ bar vừa đóng. 2-3=có lookback ngắn. ≥5=xét pattern dài. Check last N closed bars (bar 1 to N). 1=just-closed bar only. 2-3=short lookback. ≥5=long pattern window.
InpWickToBodyRatio2.0 Wick phải lớn hơn body × ratio mới count. Lớn = strict (cần râu nổi bật hơn body). 1.5=lenient, 3.0=strict. Wick must exceed body × ratio. Larger = stricter. 1.5=lenient, 3.0=strict.
InpWickToRangeMin0.5 Wick phải chiếm ít nhất N × tổng range (0.5 = 50% nến là wick). Loại bỏ false positive khi body nhỏ + wick cũng nhỏ. Wick must occupy at least N × total range (0.5 = wick is half the candle). Filters out false positives when both body and wick are tiny.
InpWickApplyInittrue Áp dụng cho Init: chặn phía bị reject (Buy nếu upper, Sell nếu lower). Apply to Init: block rejected side (Buy if upper, Sell if lower).
InpWickApplyAddfalse Áp dụng cho Add (DCAPos + DCANeg). Mặc định tắt để DCA recovery free, AutoBalance ACT bypass. Apply to Add (DCAPos + DCANeg). Default off to preserve DCA recovery, AutoBalance ACT bypass.

Tham số tuning theo styleTuning by style

StyleStyle ToBodyRatio ToRangeMin LookbackBars Số rejection event/tháng (XAU M15+H1)Rejection events/month (XAU M15+H1)
🔥 Lenient (nhiều trade) 1.5 0.4 1 ~30-50 events → block ~10-15% Init~30-50 events → blocks ~10-15% Init
⭐ Balanced (default) 2.0 0.5 2 ~15-25 events → block ~5-8% Init~15-25 events → blocks ~5-8% Init
🛡️ Strict (ít trade, chất lượng cao) 3.0 0.6 3 ~5-10 events → block ~2-4% Init~5-10 events → blocks ~2-4% Init

Ví dụ thực tế (XAU M15, InpPipPoints=10)Real example (XAU M15, InpPipPoints=10)

Bar OHLCBar OHLC body upper lower range Reject?Reject?
O=2398, H=2400, L=2390, C=2392
(normal red candle)
$6.0 $2.0 $2.0 $10.0 ❌ none
upper/body=0.33 < 2.0
O=2395, H=2400, L=2393, C=2394
(long upper wick)
$1.0 $5.0 $1.0 $7.0 UPPER reject
5/1=5 ≥ 2.0 ✓, 5/7=0.71 ≥ 0.5 ✓
O=2392, H=2393, L=2385, C=2391
(long lower wick)
$1.0 $1.0 $6.0 $8.0 LOWER reject
6/1=6 ≥ 2.0 ✓, 6/8=0.75 ≥ 0.5 ✓

Multi-TF AND logicMulti-TF AND logic

TF1 (M15):  ✅ upper wick reject  ─┐
                                   ├── BOTH agree → BLOCK Buy
TF2 (H1):   ✅ upper wick reject  ─┘

TF1 (M15):  ✅ upper wick reject  ─┐
                                   ├── only TF1 → OK to Buy (need both)
TF2 (H1):   ❌ no rejection       ─┘

TF1 (M15):  ❌ no rejection       ─┐
                                   ├── neither → OK to Buy
TF2 (H1):   ✅ upper wick reject  ─┘

Hiển thị panelInfo Panel display

Khi InpWickFilterEnable=true, panel hiện thêm dòng:

When InpWickFilterEnable=true, the panel shows an extra line:

Clean:        Wick[PERIOD_M15+PERIOD_H1]: clean ✓        (lime — both sides OK)
Buy blocked:  Wick[PERIOD_M15+PERIOD_H1]: UP (block Buy)  (orange — upper wick reject)
Sell blocked: Wick[PERIOD_M15+PERIOD_H1]: DN (block Sell) (orange — lower wick reject)
Both blocked: Wick[PERIOD_M15+PERIOD_H1]: BOTH ❌         (red — round skipped)

Use cases khuyến nghịRecommended use cases

Bật khi:Enable when:

  • XAU có nhiều spike/whipsaw (đặc biệt phiên Mỹ overlap London).
  • XAU has frequent spikes/whipsaws (especially US-London overlap).
  • Backtest A baseline ($212k) bạn thấy nhiều Init ngay sau wick lớn → wick filter sẽ giúp avoid.
  • A baseline backtest ($212k) shows many Inits right after big wicks → wick filter helps avoid these.
  • Bạn muốn kết hợp với Trend H1 + Pivot D1 → wick M15+H1 đồng pha → high-quality entries.
  • You want to combine with Trend H1 + Pivot D1 → wick M15+H1 aligned → high-quality entries.

KHÔNG dùng khi:DON'T use when:

  • Market trending mạnh, ít wick (đầu tuần Châu Á trend rõ) → filter sẽ giảm trades không cần thiết.
  • Market in strong trend, few wicks (early Asia trending sessions) → filter unnecessarily reduces trades.
  • Bạn dùng DCA dày + lot nhỏ — filter sẽ làm DCA chain ngắt → khó recover.
  • You use dense DCA + small lots — filter breaks chain → harder recovery.
  • Bật InpWickApplyAdd=true trên config A baseline → có thể block Add ở pullback hợp lệ.
  • Setting InpWickApplyAdd=true on A baseline config → may block valid pullback Adds.
💡 Cấu hình tối ưu cho XAU intraday DCAOptimal config for XAU intraday DCA
InpWickFilterEnable  = true
InpWickFilterTF1     = M15          # Match Trend Filter TF
InpWickFilterTF2     = H1           # Confirmation TF
InpWickLookbackBars  = 2            # Bar vừa đóng + bar trước
InpWickToBodyRatio   = 2.0          # Balanced default
InpWickToRangeMin    = 0.5
InpWickApplyInit     = true         # ✅ Gate Init quality
InpWickApplyAdd      = false        # ❌ Giữ DCA recovery free

9. DCA Parameters

DCA Positive

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpDCAPosStartLot0.05 Lot chân P tại Init (và chuỗi Add DCAPos).Lot for P leg at Init (and DCAPos Add chain).
InpDCAPosMultiplier1.3 Hệ số nhân lot khi Add. Lot(n) = StartLot × Mult^n. Lot multiplier on Add. Lot(n) = StartLot × Mult^n.
InpDCAPosMinPips27 Khoảng cách tối thiểu giữa các lệnh Add (pips). Minimum distance between Add orders (pips).
InpDCAPosMaxLot0.5 Lot tối đa mỗi lệnh.Max lot per order.
InpDCAPosMaxTrades68 Tổng lệnh DCAPos tối đa (tất cả round). 0 = không giới hạn. Total max DCAPos orders (all rounds). 0 = unlimited.
InpDCAPosTPEnablefalse Bật TP từng lệnh DCAPos theo pips. InpVirtualDcaTpEnable=true → EA đóng (TP=0 sàn); false → gửi TP lên broker. Dùng với synergy Tia+DCA. Enable per-order DCAPos TP (pips). InpVirtualDcaTpEnable=true → EA-managed close (broker TP 0); false → broker TP. Works with Tia+DCA synergy.
InpDCAPosTPPips100 Khoảng TP (pips) mỗi lệnh DCAPos khi Enable bật. TP distance (pips) per DCAPos order when Enable is on.
InpVirtualDcaTpEnabletrue Áp cho cả DCAPos/DCANeg khi TP từng lệnh bật: true = EA đóng theo pip (TP=0 sàn); false = gửi TP lên broker. Xem hộp Virtual DCA TP bên dưới. Applies to both DCAPos/DCANeg when per-order TP is on: true = EA closes by pips (broker TP 0); false = send TP to broker. See Virtual DCA TP box below.

DCA Negative

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpDCANegStartLot0.02 Lot chân N tại Init (và chuỗi Add DCANeg).Lot for N leg at Init (and DCANeg Add chain).
InpDCANegMultiplier1.2 Hệ số nhân lot khi Add.Lot multiplier on Add.
InpDCANegMinPips34 Khoảng cách tối thiểu giữa các lệnh Add. Minimum distance between Add orders.
InpDCANegMaxLot0.5 Lot tối đa mỗi lệnh.Max lot per order.
InpDCANegMaxTrades53 Tổng lệnh DCANeg tối đa (tất cả round). Total max DCANeg orders (all rounds).
InpDCANegTPEnablefalse Bật TP từng lệnh DCANeg theo pips. Virtual/broker giống cột DCAPos (InpVirtualDcaTpEnable). Enable per-order DCANeg TP (pips). Virtual vs broker same as DCAPos (InpVirtualDcaTpEnable).
InpDCANegTPPips100 Khoảng TP (pips) mỗi lệnh DCANeg khi Enable bật. TP distance (pips) per DCANeg order when Enable is on.
Virtual DCA TPVirtual DCA TPInpVirtualDcaTpEnable (mặc định: true)(default: true) Bật (true): Khi InpDCAPosTPEnable / InpDCANegTPEnable và pips TP bật, lệnh mở với TP = 0 trên sàn; EA đóng từng lệnh khi giá đạt giá mở ± khoảng pip config (giống công thức cũ, gồm stops level). Synergy Tia+DCA dùng cùng mức ảo để tính “gần TP”. Tắt (false): Gửi TP lên broker — sàn có thể khớp khi EA/ngắt mạng; phù hợp khi cần chốt TP dù terminal tắt. On (true): When DCAPos/DCANeg per-order TP is enabled, orders open with TP = 0 at the broker; the EA closes each leg when price reaches open ± the configured pip distance (same formula as before, including stops level). Tia+DCA synergy uses the same virtual level for “near TP”. Off (false): Send TP to the broker — fills can occur while the EA is disconnected; use when you need server-side TP protection.
Multiplier và rủi ro exposureMultiplier and exposure risk Multiplier cao (1.5–2.0) tăng tốc phục hồi khi giá hồi nhưng cũng tăng nhanh drawdown. Với XAUUSD: DCAPos Multiplier 1.3–1.5, DCANeg 1.2–1.3 là cân bằng. High multiplier (1.5–2.0) speeds recovery when price reverses but also accelerates drawdown. For XAUUSD: DCAPos 1.3–1.5, DCANeg 1.2–1.3 is balanced.

9b. DCA Chain Persistent Mode (v1.35+)

Cách EA tính exponent multiplier khi mở lệnh Add. Quyết định lot = StartLot × Multiplier^exponent. Có 2 chế độ qua input InpDcaChainPersistent (default false = legacy):

How the EA calculates the multiplier exponent on Add orders. Determines lot = StartLot × Multiplier^exponent. Two modes via InpDcaChainPersistent (default false = legacy):

🐛 Vấn đề thực tế phát hiện trong backtestReal issue found in backtest Init Buy mở với StartLot=0.10. Tia cluster close Init Buy → vài giờ sau, B#1 (first Buy add) fire với lot 0.10 (KHÔNG phải 0.15 như user expect). Lý do: legacy mode dùng nBuy (count Buy ĐANG MỞ). Sau Tia close, nBuy = 0 → exponent = 0 → lot reset về StartLot. v1.35 thêm option chain persistent để address scenario này. Init Buy opens with StartLot=0.10. Tia cluster closes Init Buy → hours later, B#1 (first Buy add) fires with lot 0.10 (NOT 0.15 as user expected). Reason: legacy mode uses nBuy (count of currently OPEN Buys). After Tia close, nBuy = 0 → exponent = 0 → lot resets to StartLot. v1.35 adds chain persistent option to address this scenario.

So sánh 2 modeTwo modes compared

Aspect InpDcaChainPersistent = false (legacy, default) InpDcaChainPersistent = true (v1.35 new)
Công thức exponentExponent formula exp = nBuy (or nSell) = count POSITIONS đang mở= currently OPEN positions count exp = persistentMaxNum + 1 = chain progression count (per round)= chain progression count (per round)
Reset chain khiChain resets when BẤT KỲ position nào close (Tia/partial/manual) → count giảm → next add lot RESET CHỈ khi entire round dies (không còn position nào của round)
StorageStorage Live scan position countLive scan position count RoundChainEntry g_roundChain[] — persistent struct per round— persistent struct per round
Lot consistencyLot consistency B#1 lot CÓ THỂ KHÁC tùy state (0.10 hoặc 0.15) B#1 luôn = 0.15, B#2 luôn = 0.225, B#3 luôn = 0.3375 (chain progression strict)
Risk profileRisk profile 🟢 Recovery-friendly — risk giảm sau Tia close🟢 Recovery-friendly — risk reduces after Tia close 🟠 Aggressive — lot leo cao bất kể closes (cap by MaxLot)🟠 Aggressive — lot keeps growing regardless of closes (cap by MaxLot)
Backward compatBackward compat ✅ Behavior identical v1.34 và trước✅ Behavior identical to v1.34 and earlier ⚠️ Cần re-backtest — dynamics khác⚠️ Re-backtest required — different dynamics

Walkthrough scenario chi tiếtDetailed scenario walkthrough

Setup: InpDCAPosStartLot=0.10, InpDCAPosMultiplier=1.5. Round R đang chạy.

Setup: InpDCAPosStartLot=0.10, InpDCAPosMultiplier=1.5. Round R running.

Sự kiệnEvent Legacy (false) Persistent (true)
Init Buy fires nBuy=1 (after), lot 0.10 maxBuyNum=0 (init has no B#), lot 0.10
Price up → B#1 fires nBuy=1 (before fire), exp=1 → lot 0.15 nextBuyNum=1, exp=1 → lot 0.15
B#2 fires nBuy=2, exp=2 → lot 0.225 nextBuyNum=2, exp=2 → lot 0.225
Tia close Init Buy nBuy=2 (B#1+B#2 alive) maxBuyNum=2 persistent (no change)
B#3 fires nBuy=2, exp=2 → lot 0.225 (chain hơi lệch) nextBuyNum=3, exp=3 → lot 0.3375
Tia close B#1, B#2 (all Buy closed) nBuy=0 maxBuyNum=2 (still persistent — round alive due to other side)
B#4 fires (round still alive — Sell side) nBuy=0, exp=0 → lot 0.10RESET về StartLotRESET to StartLot nextBuyNum=3, exp=3 → lot 0.3375chain continueschain continues
All round members closed → round dies RoundChainCleanup() removes R entry
New round R' Init fires Fresh start: nBuy=1, lot 0.10 Fresh start: maxBuyNum=0, lot 0.10

ImplementationImplementation

// Struct lưu chain counter per round (persistent across partial closes)
struct RoundChainEntry {
   int roundId;
   int maxBuyNum;     // highest B#N ever assigned in round
   int maxSellNum;    // highest S#N ever assigned in round
};
RoundChainEntry g_roundChain[];

// Khi add fire:
int nextBuyNum = (InpDcaChainPersistent
                  ? MathMax(maxBuyNum, RoundChainGetMaxBuy(roundId)) + 1
                  : maxBuyNum + 1);
int lotExp = (InpDcaChainPersistent ? nextBuyNum : nBuy);
double rawLot = MathMin(StartLot * MathPow(Multiplier, lotExp), MaxLot);

// Sau khi add thành công:
if (InpDcaChainPersistent) RoundChainSetMaxBuy(roundId, nextBuyNum);

// Cleanup mỗi 30s (hook với TicketMapCleanup):
// Xóa entries của rounds không còn position nào (round dies)
RoundChainCleanup();

Khuyến nghị sử dụngUsage recommendations

✅ Dùng Legacy (false)

  • Backward compat với configs cũ (Pass 10, ScalpingTrending, A baseline)
  • Conservative — recovery-friendly
  • Default — không cần thay đổi gì
  • Phù hợp account capital nhỏ
  • Backward compat with old configs
  • Conservative — recovery-friendly
  • Default — no change needed

🟠 Dùng Persistent (true)

  • Martingale strict chain progression
  • Lot và B#N label phải nhất quán
  • Equity cao, chấp nhận risk lớn hơn
  • Đã backtest verified behavior tốt hơn legacy
  • Strict Martingale chain
  • Lot/label consistency required
  • Higher capital, higher risk tolerance
Cảnh báo khi bật Persistent modePersistent mode warnings

📄 Tài liệu đầy đủ với 9 sections: CHAIN_PERSISTENT.md📄 Full documentation in 9 sections: CHAIN_PERSISTENT.md

9c. Whipsaw Defense Suite (v1.36-1.37+)

5 features adaptive để bảo vệ EA khỏi whipsaw chop markets (đặc biệt scenarios như 5-11/02/2025 gây stuck Pass 10 floating loss -$55k). Triết lý: preserve Pass 10 profit trong trending markets, block entries trong choppy markets.

5 adaptive features protecting EA against whipsaw chop markets (like the 5-11/02/2025 scenario which caused Pass 10 to accumulate -$55k floating loss). Philosophy: preserve Pass 10 profit in trending markets, block entries in choppy markets.

📋 Tổng quan 5 features5 Features overview
FeatureVersionDefaultMechanismMechanism
Choppy Filter (ADX)v1.36+ONBlock Init khi ADX < thresholdBlock Init when ADX < threshold
Anti-Whipsaw Cooldownv1.36+ONCooldown sau realized loss trong windowCooldown after realized loss in window
Adaptive Trend NeutralPipsv1.37+ONNeutralPips tự scale theo ADX regimeNeutralPips scales by ADX regime
Multi-TF Trend Confirmationv1.37+OFFRequire HTF agreementRequire HTF agreement
Dual-Direction Prohibitionv1.37+OFFBlock opposite side khi choppyBlock opposite side when choppy

1. Choppy Filter (ADX-based)Choppy Filter (ADX-based)

Phát hiện chop bằng ADX (Average Directional Index). ADX đo trend STRENGTH (không quan tâm direction). ADX cao = trending, ADX thấp = range/chop.

Detects chop using ADX (Average Directional Index). ADX measures trend STRENGTH (regardless of direction). High ADX = trending, low ADX = range/chop.

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpChoppyFilterEnabletrue Bật/tắt filterEnable/disable
InpChoppyFilterTFPERIOD_M15 (v1.36) / PERIOD_H1 (recommended) TF tính ADX. H1 cho stable signal, M15 cho fast (noisy) TF for ADX. H1 for stable signal, M15 for fast (noisy)
InpChoppyAdxPeriod14 ADX period (standard 14)ADX period (standard 14)
InpChoppyAdxMinForTrend22.0 ADX < ngưỡng = choppy. M15 dùng 25, H1 dùng 22, H4 dùng 20 ADX < threshold = choppy. M15 use 25, H1 use 22, H4 use 20
InpChoppyApplyInittrue Block Init khi choppyBlock Init when choppy
InpChoppyApplyAddfalse Block Add (mặc định OFF để preserve DCA recovery) Block Add (default OFF to preserve DCA recovery)
📊 TF comparison cho ADX detectionTF comparison for ADX detection
TFSpeedStabilityFalse+False-Best for
M15🟢 Fast🔴 Noisy🔴 High🟢 LowIntraday flash chop
H1🟡 Medium🟢 Stable🟡 Med🟡 MedRecommended cho Pass 10 ⭐
H4🔴 Slow🟢 Very stable🟢 Low🔴 HighSwing trading

2. Anti-Whipsaw CooldownAnti-Whipsaw Cooldown

Reactive feedback: nếu realized loss trong sliding window vượt ngưỡng → cooldown N giờ (block Init mới). Cho EA thời gian "thở" sau bad trades.

Reactive feedback: if realized loss in sliding window exceeds threshold → cooldown N hours (block new Init). Gives EA time to "breathe" after bad trades.

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpAntiWhipsawEnabletrue Bật/tắtEnable/disable
InpAntiWhipsawLookbackH8 (or 12 for stable) Sliding window N giờ check realized loss Sliding window N hours for realized loss
InpAntiWhipsawMaxLossUSD200.0 Trigger cooldown khi realized loss ≥ X USD Trigger cooldown when realized loss ≥ X USD
InpAntiWhipsawCooldownH4 (or 6 for stable) Cooldown N giờ (no Init) Cooldown N hours (no Init)

3. Adaptive Trend NeutralPips (regime-aware)Adaptive Trend NeutralPips (regime-aware)

Key innovation v1.37: TrendFilter NeutralPips tự động scale theo ADX. Strong trend → sensitive (giữ Pass 10 character). Chop → strict (block noise). Best balance giữa profit và defense.

Key innovation v1.37: TrendFilter NeutralPips automatically scales by ADX. Strong trend → sensitive (preserves Pass 10 character). Chop → strict (blocks noise). Best balance between profit and defense.

ADX RangeRegimeNeutralPipsBehavior
ADX ≥ InpTrendAdaptiveADXStrong (default 30)🟢 Strong trendInpTrendNeutralStrong = 5Sensitive — same as Pass 10 baseline
Weak ≤ ADX < Strong🟡 Medium/ambiguousInpTrendNeutralMid = 15Moderate filter
ADX < InpTrendAdaptiveADXWeak (default 20)🔴 ChopInpTrendNeutralWeak = 50Strict — block noise
⚠ Important: Khi InpTrendAdaptive=true, value của InpTrendFilterNeutralPips bị override bởi adaptive thresholds. Để dùng static value (Pass 10 legacy), set InpTrendAdaptive=false. ⚠ Important: When InpTrendAdaptive=true, InpTrendFilterNeutralPips value is overridden by adaptive thresholds. To use static value (Pass 10 legacy), set InpTrendAdaptive=false.

4. Multi-TF Trend Confirmation (default OFF)Multi-TF Trend Confirmation (default OFF)

Require HTF (vd H1) trend phải agree với primary TF trước khi vào lệnh. Strict defense layer. Default OFF vì có thể giảm profit 10-25%. v1.41: tách InpMultiTfTrendApplyInit / InpMultiTfTrendApplyAdd — áp HTF confirm cho Init và/hoặc Add riêng biệt (giống Trend Filter).

Require HTF (e.g. H1) trend agreement with primary TF before entering. Strict defense layer. Default OFF as it may reduce profit 10-25%. v1.41: split into InpMultiTfTrendApplyInit / InpMultiTfTrendApplyAdd — apply HTF confirm to Init and/or Add independently (like Trend Filter).

ParameterMặc địnhDefaultÝ nghĩaMeaning
InpMultiTfTrendEnablefalse Bật HTF confirmation. Enable cho ultra-conservative deployment Master switch for HTF confirmation. Enable for ultra-conservative deployment
InpMultiTfTrendHigherTFPERIOD_H1 HTF để confirm. H1 cho intraday, H4 cho swing HTF to confirm with. H1 for intraday, H4 for swing
InpMultiTfTrendHigherMAPeriod50 MA period trên HTF MA period on HTF
InpMultiTfTrendApplyInittrue v1.41: áp HTF confirm cho Init (giữ behavior cũ). Cần InpMultiTfTrendEnable=true v1.41: apply HTF confirm to Init (legacy behavior). Requires InpMultiTfTrendEnable=true
InpMultiTfTrendApplyAddfalse v1.41: áp HTF confirm cho Add (bồi). Bật để HTF (vd H4) phủ quyết lệnh bồi ngược trend — fix root-cause blow-up trong trend bền (giai đoạn kiểu 2023). Áp cả DCAPos + DCANeg v1.41: apply HTF confirm to Add (DCA). Enable so HTF (e.g. H4) vetoes counter-trend adds — fixes the sustained-trend blow-up root cause (2023-style periods). Applies to both DCAPos + DCANeg
💡 Use-case: sống sót trend một chiều bền (vd 2023)Use-case: surviving sustained one-way trends (e.g. 2023) Khi primary Trend TF nhanh (vd M3), các cú hồi nhỏ làm td lật liên tục → EA bồi lệnh ngược trend giữa uptrend bền → rổ 2 chiều phình to → stuck-lock deadlock → margin call. Bật InpMultiTfTrendApplyAdd=true (với HTF=H4) để H4 phủ quyết các lệnh bồi ngược trend, giữ rổ nghiêng theo trend để Global TP đóng sạch được — không cần cắt lỗ. When the primary Trend TF is fast (e.g. M3), small pullbacks flip td repeatedly → the EA adds counter-trend DCA mid-uptrend → the two-sided basket balloons → stuck-lock deadlock → margin call. Enable InpMultiTfTrendApplyAdd=true (with HTF=H4) so H4 vetoes counter-trend adds, keeping the basket trend-aligned so Global TP can close it all — no hard stop-loss needed.

4b. Stair-Step Market Filter (v1.42, default OFF) — dynamic trend-TF overrideStair-Step Market Filter (v1.42, default OFF) — dynamic trend-TF override

Chuyển đổi động primary trend TF theo số lệnh mở: book khỏe → TF nhanh (vd M3, aggressive, profit cao); book phình (dấu hiệu kẹt trong staircase-trend) → override sang TF chậm (vd H4, defensive, survival). Mục tiêu: gộp profit của M3 (regime êm) + survival của H4 (trend bậc thang) trong một config.

Dynamically switches the primary trend TF by open-order count: healthy book → fast TF (e.g. M3, aggressive, high profit); bloated book (sign of being trapped in a staircase trend) → override to a slow TF (e.g. H4, defensive, survival). Goal: combine M3's profit (calm regime) with H4's survival (staircase trend) in one config.

🔑 Khác ApplyAdd thế nào (vì sao không cháy)How it differs from ApplyAdd (why it doesn't blow up) ApplyAdd = M3 AND H4 (2 cổng) → gác add 2 lớp → starve DCA recovery → cháy. Stair-step = THAY THẾ tín hiệu hướng (M3→H4, vẫn 1 cổng) → khi active chính là hành vi H4-origin (đã kiểm chứng sống) → không starve recovery. ApplyAdd = M3 AND H4 (two gates) → double-gates adds → starves DCA recovery → blow-up. Stair-step REPLACES the direction signal (M3→H4, still one gate) → when active it IS H4-origin behavior (proven to survive) → does not starve recovery.
ParameterMặc địnhDefaultÝ nghĩaMeaning
InpStairStepEnablefalse Bật override động. Cần InpTrendFilterEnable=true Enable dynamic override. Requires InpTrendFilterEnable=true
InpStairStepTriggerOrders24 Số lệnh mở ≥ N → BẬT override (dùng slow-TF). Thấp = phòng thủ sớm hơn Open orders ≥ N → turn override ON (use slow-TF). Lower = defends earlier
InpStairStepReleaseOrders8 Số lệnh mở < N → TẮT override (về primary). Hysteresis chống flip-flop; nên < Trigger Open orders < N → turn override OFF (back to primary). Hysteresis vs flip-flop; keep < Trigger
InpStairStepTFPERIOD_H4 TF chậm dùng khi override active Slow TF used while override is active
InpStairStepMAPeriod30 Chu kỳ EMA cho InpStairStepTF EMA period for InpStairStepTF
InpStairStepNeutralPips50 v1.43: Vùng neutral (pips) khi override active — static (không adaptive theo ADX). Lớn = cam kết trend hơn, khó lật ở pullback v1.43: Neutral zone (pips) while override active — static (not ADX-adaptive). Larger = more trend-committed, harder to flip on pullbacks
InpStairStepApplyInittrue v1.43: Override InpTrendFilterApplyInit khi active v1.43: Overrides InpTrendFilterApplyInit while active
InpStairStepApplyAddtrue v1.43: Override InpTrendFilterApplyAdd khi active. Cho phép "khỏe→add tự do (base ApplyAdd=false), trap→gác add theo H4 (=true)" v1.43: Overrides InpTrendFilterApplyAdd while active. Enables "healthy→free adds (base ApplyAdd=false), trapped→gate adds by H4 (=true)"
InpStairStepStableBars0 v1.45 SMART TRIGGER: stair-TF phải GIỮ 1 hướng ≥ N bar (của InpStairStepTF) mới coi là trend ổn định (staircase) → mới cho override; đang override mà stair-TF LẬT (whipsaw) → bail về primary. 0 = tắt smart (chỉ theo count như v1.42) v1.45 SMART TRIGGER: the stair-TF must HOLD one direction for ≥ N bars (of InpStairStepTF) to count as a stable trend (staircase) before override is allowed; while overriding, if stair-TF FLIPS (whipsaw) → bail back to primary. 0 = smart disabled (count-only, v1.42)

v1.43 — full override: stair-step giờ override trọn bộ thông số direction của trend filter khi active: {TF, MAPeriod, NeutralPips, ApplyInit, ApplyAdd}. Tức nó là một "trend-filter thay thế" hoàn chỉnh, không chỉ đổi TF. Neutral riêng (static) giúp giữ cam kết trend, không lật ở pullback như adaptive neutral=5 của primary.

v1.43 — full override: stair-step now overrides the complete direction param set of the trend filter while active: {TF, MAPeriod, NeutralPips, ApplyInit, ApplyAdd} — a full drop-in replacement, not just a TF swap. Its own static neutral keeps the trend commitment instead of the primary's adaptive neutral=5.

Cơ chế: state cập nhật 1 lần/tick trong RefreshTickCache (đếm order). Khi active, GetTrendDirection() đọc EMA của InpStairStepTF thay vì primary → áp cho cả Init lẫn Add. Lưu ý reactive: tới lúc chạm Trigger thì rổ ngược trend đã dựng — override chỉ chặn dựng thêm, nên chọn Trigger đủ thấp để cap sớm; đây là biến cần optimize (thử 16/24/32).

Mechanism: state updates once/tick in RefreshTickCache (order count). When active, GetTrendDirection() reads the InpStairStepTF EMA instead of the primary → applies to both Init and Add. Note (reactive): by the time Trigger is hit the counter-trend basket is already built — the override only stops further growth, so pick a low enough Trigger to cap early; this is the key parameter to optimize (try 16/24/32).

Info panel (v1.44): dòng Stair: báo trạng thái — ẩn khi OFF; Stair: primary PERIOD_M3 (count/trigger) (bạc) khi chưa trigger; Stair: OVERRIDE PERIOD_H4 (count, rel<N) (cam) khi đang override.

Info panel (v1.44): a Stair: row shows state — hidden when OFF; Stair: primary PERIOD_M3 (count/trigger) (silver) when not yet triggered; Stair: OVERRIDE PERIOD_H4 (count, rel<N) (orange) while override is active. v1.45 adds [stable]/[flip].

🧠 v1.45 SMART TRIGGER — phân biệt staircase vs whipsawv1.45 SMART TRIGGER — distinguishing staircase from whipsaw Vấn đề: switching theo count đơn thuần không phân biệt được staircase (trend bền — cần H4) với whipsaw (2 chiều dữ dội — cần M3). Backtest cho thấy count-only sống 2023 (staircase) nhưng cháy 2025 (whipsaw: giá lật 3352↔3202↔3423 → H4-override bị khoá → tích luỹ 121 lệnh → margin call). Discriminator đúng là độ ổn định hướng của stair-TF. Problem: count-only switching can't tell a staircase (sustained trend — needs H4) from a whipsaw (violent two-way — needs M3). Backtests: count-only survived 2023 (staircase) but blew up 2025 (whipsaw: price flipping 3352↔3202↔3423 → H4-override locked → 121-order pileup → margin call). The right discriminator is stair-TF direction stability.
Mỗi tick (RefreshTickCache):
  h4dir  = dir(price vs stair-EMA, InpStairStepNeutralPips)
  if h4dir đổi dấu:  lastFlipTime = now
  h4Stable = (now − lastFlipTime) ≥ StableBars × PeriodSeconds(StairStepTF)

  OFF (primary/M3):
     → BẬT override  nếu  count ≥ Trigger  AND  h4Stable      (staircase xác nhận)
  ON (override/H4):
     → TẮT về primary nếu  count < Release  OR  NOT h4Stable   (book vơi HOẶC whipsaw)

GetTrendDirection(): override ON → stair-EMA ; else → primary EMA

Vì sao vá được 2025: whipsaw làm stair-TF lật → h4Stable=false → EA không khoá trong H4 nữa, bail về M3 → M3 clear book nhanh (như config MEDIUM sống 2025). Staircase 2023: stair-TF ổn định nhiều tuần → override giữ nguyên → chặn counter-trend → sống. Cũng vá luôn cú đảo ở đỉnh staircase (H4 lật → bail về M3 xử lý reversal).

Why it fixes 2025: a whipsaw flips the stair-TF → h4Stable=false → the EA no longer locks into H4, bailing to M3 → M3 clears the book fast (like the MEDIUM config that survived 2025). In the 2023 staircase the stair-TF is stable for weeks → override holds → blocks counter-trend → survives. It also handles the staircase-top reversal (stair-TF flips → bail to M3 to manage the turn).

🪜 v1.47 STAIRCASE DETECTOR — trigger REGIME-based (fire SỚM) thay order-countv1.47 STAIRCASE DETECTOR — regime-based trigger (fires EARLY) instead of order-count

Vấn đề còn lại của count/StableBars: trigger fire khi rổ ĐÃ phình → override lúc đó = bàn giao rổ hai chiều to cho H4 → H4 khoá bên ngược trend, bên đó bị bỏ lại phình lỗ → equity crater (ca 05/02/2025: 65 lot, equity −76%, suýt cháy). Cách chữa: phát hiện staircase SỚM (khi trend vừa chớm, rổ còn nhỏ) rồi mới override → không có rổ to để bàn giao.

Remaining flaw of count/StableBars: the trigger fires once the basket is already bloated → overriding then hands a large two-way basket to H4, which freezes the counter-trend side → it's left to bleed → equity crater (the 05/02/2025 case: 65 lots, equity −76%, near-liquidation). Fix: detect the staircase EARLY (trend just forming, basket still small), then override → no large basket to hand over.

detector = ER ≥ InpStairStepERMin  AND  ADX ≥ InpStairStepDetAdxMin  AND  dir(stair-EMA) ≠ 0
  ER (Kaufman Efficiency Ratio) = |close[0]−close[N]| / Σ|close[i]−close[i-1]|   trên InpStairStepTF
     ER→1 = đi thẳng (staircase/trend sạch) ; ER→0 = chop

OFF (primary/M3):
   → BẬT override  nếu  detector≠0  AND  tổng_lot_rổ ≤ InpStairStepMaxBasketLots   (SỚM + rổ nhỏ)
ON (override/H4):
   → TẮT về primary nếu  detector=0                                               (staircase kết thúc)

CHỐT AN TOÀN InpStairStepMaxBasketLots: chỉ VÀO override khi rổ còn nhỏ → né bàn giao rổ. Nếu detect trễ (rổ đã to) → từ chối switch (an toàn hơn là bàn giao). False-positive (thực ra whipsaw) mà rổ nhỏ → H4 quản rổ nhỏ vẫn sống (như H4-origin qua whipsaw).

SAFETY GATE InpStairStepMaxBasketLots: only enter override while the basket is small → avoids the handoff. If detection is late (basket already big) it refuses to switch (safer than handing over). A false positive (actually a whipsaw) on a small basket → H4 manages a small basket and still survives (like H4-origin through whipsaws).

ParamDefaultÝ nghĩaMeaning
InpStairStepUseDetectorfalse v1.47: true = trigger bằng staircase-detector (ER+ADX) + small-basket gate, THAY order-count. false = count-based (v1.42/1.45) v1.47: true = trigger via staircase detector (ER+ADX) + small-basket gate, INSTEAD of order-count. false = count-based (v1.42/1.45)
InpStairStepERPeriod20 Số bar (trên InpStairStepTF) tính Efficiency Ratio. 20×H4 ≈ 3.3 ngày lookback Bars (on InpStairStepTF) for the Efficiency Ratio. 20×H4 ≈ 3.3 days lookback
InpStairStepERMin0.55 ER ≥ này = trend "sạch"/bền (staircase). Cao hơn = strict hơn. 0 = tắt điều kiện ER ER ≥ this = clean/sustained trend (staircase). Higher = stricter. 0 = disable ER condition
InpStairStepDetAdxPeriod14 ADX period cho detector (trên InpStairStepTF) ADX period for the detector (on InpStairStepTF)
InpStairStepDetAdxMin25.0 ADX ≥ này = đang trending. 0 = tắt điều kiện ADX ADX ≥ this = trending. 0 = disable ADX condition
InpStairStepMaxBasketLots3.0 CHỐT AN TOÀN: chỉ VÀO override khi tổng lot rổ ≤ N (né bàn giao rổ to). 0 = tắt gate (KHÔNG khuyến nghị) SAFETY GATE: only enter override when total basket lots ≤ N (avoids handing over a big basket). 0 = disable gate (NOT recommended)
Config KHUYẾN NGHỊ (điểm khởi đầu để backtest — CHƯA validate)RECOMMENDED config (starting point to backtest — NOT yet validated)
InpTrendFilterEnable      = true          ; bắt buộc
InpTrendFilterTF          = PERIOD_M3      ; primary = M3 (profit ở regime êm)
InpTrendFilterMAPeriod    = 10
InpTrendFilterApplyInit   = true
InpTrendFilterApplyAdd    = false          ; M3 mode: để DCA recovery tự do (clear nhanh)

InpStairStepEnable        = true           ; bắt buộc
InpStairStepUseDetector   = true           ; ← BẬT detector (v1.47)
InpStairStepTF            = PERIOD_H4       ; override → H4 khi staircase
InpStairStepMAPeriod      = 30
InpStairStepNeutralPips   = 50
InpStairStepApplyInit     = true
InpStairStepApplyAdd      = true           ; override mode: H4 gác add (= H4-origin, 1 cổng, chống staircase)
InpStairStepERPeriod      = 20
InpStairStepERMin         = 0.55           ; tune 0.50–0.65
InpStairStepDetAdxPeriod  = 14
InpStairStepDetAdxMin     = 25.0           ; tune 22–28
InpStairStepMaxBasketLots = 3.0            ; tune theo lot ladder (start 0.1 → ~3 lot là "còn nhỏ")
InpStairStepStableBars    = 0              ; không dùng ở detector mode

Ý tưởng: chạy M3 (lãi cao) bình thường; khi detector thấy staircase SỚM + rổ còn nhỏ → flip sang H4 (chặn bồi ngược trend) → sống staircase; staircase hết → về M3. Mục tiêu cần backtest: sống CẢ staircase 2023 LẪN whipsaw 2024/2025, equity DD (reconstruct) thấp hơn Pass 2 (76%). Nếu đạt → bản đầu tiên đánh bại always-H4 về profit mà vẫn an toàn.

Idea: run M3 (high profit) normally; when the detector sees a staircase EARLY with the basket still small → flip to H4 (block counter-trend adds) → survive the staircase; staircase ends → back to M3. Backtest target: survive BOTH the 2023 staircase AND the 2024/2025 whipsaws, with a (reconstructed) equity DD lower than Pass 2's 76%. If met → the first config to beat always-H4 on profit while staying safe.

⚠️ Rủi ro còn lại: nếu staircase "lẻn" tới sau giai đoạn chop (M3 đã trap trước khi detector kịp báo, rổ > gate) → gate từ chối switch → M3 có thể chết staircase. Chỉ backtest mới trả lời được độ trễ này có chấp nhận được không.

⚠️ Residual risk: if the staircase sneaks in after a choppy phase (M3 already trapped before the detector fires, basket > gate) → the gate refuses to switch → M3 may die in the staircase. Only a backtest can tell whether this latency is acceptable.

5. Dual-Direction Prohibition during chop (default OFF)Dual-Direction Prohibition during chop (default OFF)

Khi chop detected + đã có positions side X → block Init side đối diện. Prevent bidirectional stuck. Default OFF vì kill hedge opportunity (DCA Hedging strategy core feature).

When chop detected + already have positions on side X → block Init opposite side. Prevents bidirectional stuck. Default OFF since it kills hedge opportunity (core DCA Hedging feature).

InpDualDirChopEnable = false (default)

6. Info Panel display — Whipsaw Defense statusInfo Panel display — Whipsaw Defense status

v1.37 thêm dòng "Whip: ..." trong info panel hiển thị real-time status của tất cả 5 features.

v1.37 adds "Whip: ..." row in info panel showing real-time status of all 5 features.

Whip: ADX=28.5(strong) NP=5 HTF↑✓
       │     │     │      │   │  └─ Agreement: ✓ (HTF agree với primary) hoặc ✗ (disagree)
       │     │     │      │   └──── HTF direction: ↑/↓/=  (Multi-TF feature)
       │     │     │      └──────── Effective NeutralPips (Adaptive feature)
       │     │     └─────────────── ADX regime: strong/mid/chop
       │     └───────────────────── Current ADX value
       └─────────────────────────── Combined status row label

Examples với active blocks:
  Whip: ADX=17.3(chop) NP=50 HTF=✗ [BLK: CHOP HTF-MISS ]     ← red — full block
  Whip: ADX=22.1(mid) NP=20 HTF↑✓ [BLK: AW 142m ]           ← red — cooldown
  Whip: ADX=24.8(mid) NP=20 HTF↑✗ [BLK: HTF-MISS ]          ← orange — partial
ColorConditionCondition
🟢 LimeNo blocks, HTF agreement (entries allowed)No blocks, HTF agreement (entries allowed)
🟠 OrangeChỉ HTF-MISS (directional block, Multi-TF disagree)HTF-MISS only (directional block, Multi-TF disagree)
🔴 OrangeRedGlobal block active (CHOP / AW / DD)Global block active (CHOP / AW / DD)
Default behavior change v1.37Default behavior change v1.37 v1.37 đổi 3 defaults: InpChoppyFilterEnable, InpAntiWhipsawEnable, InpTrendAdaptiveON. Existing .set files load vào EA v1.37 sẽ có behavior khác (safer in chop). Để revert legacy behavior, set 3 inputs về false. v1.37 changes 3 defaults: InpChoppyFilterEnable, InpAntiWhipsawEnable, InpTrendAdaptiveON. Existing .set files loaded into v1.37 will have different behavior (safer in chop). To revert legacy behavior, set these 3 inputs to false.

7. Recommended configsRecommended configs

H1-Stable Config (recommended)

InpChoppyFilterEnable    = true
InpChoppyFilterTF        = PERIOD_H1
InpChoppyAdxMinForTrend  = 22.0

InpAntiWhipsawEnable     = true
InpAntiWhipsawLookbackH  = 12
InpAntiWhipsawMaxLossUSD = 250
InpAntiWhipsawCooldownH  = 6

InpTrendAdaptive          = true
InpTrendAdaptiveADXStrong = 28.0
InpTrendAdaptiveADXWeak   = 18.0
InpTrendNeutralStrong     = 5
InpTrendNeutralMid        = 20
InpTrendNeutralWeak       = 50

InpMultiTfTrendEnable     = true
InpMultiTfTrendHigherTF   = PERIOD_H1

InpDualDirChopEnable      = true
Stable signal toàn diện. Trade-off: -20-29% profit, +30-40% smoothness Comprehensive stable signal. Trade-off: -20-29% profit, +30-40% smoothness

Default v1.37 (balanced)

InpChoppyFilterEnable     = true  (default)
InpChoppyFilterTF         = PERIOD_M15 (or H1)
InpChoppyAdxMinForTrend   = 22.0

InpAntiWhipsawEnable      = true  (default)
InpAntiWhipsawLookbackH   = 8     (default)
InpAntiWhipsawMaxLossUSD  = 200   (default)

InpTrendAdaptive          = true  (default)
InpTrendAdaptiveADXStrong = 30.0  (default)
InpTrendAdaptiveADXWeak   = 20.0  (default)

InpMultiTfTrendEnable     = false (default)
InpDualDirChopEnable      = false (default)
3 features adaptive ON, 2 strict OFF. Best balance cho Pass 10 character preservation 3 adaptive features ON, 2 strict OFF. Best balance for Pass 10 character preservation

10. Hedging

Khi số lệnh cùng chiều đạt InpHedgeAfterTrades, EA mở lệnh ngược chiều (Hedge). Lot và cách kích hoạt phụ thuộc InpHedgeMode (v1.23+: dropdown 4 chế độ): ByMainRound (% volume round lớn nhất, 1 hedge/phía), ByTotal (% tổng lot, 1 hedge/phía), ByAccountProfit (lot theo lỗ USD), PerRound (1 hedge cho mỗi round đạt N, lot = % volume round đó). Mục đích: giảm đà loss khi giá đi ngược.

When same-direction orders reach InpHedgeAfterTrades, the EA opens a counter-direction order (Hedge). Lot and trigger depend on InpHedgeMode (v1.23+: dropdown with 4 modes): ByMainRound (% of largest round's volume, 1 hedge per side), ByTotal (% of total lot, 1 hedge per side), ByAccountProfit (lot by USD loss), PerRound (one hedge per round that reached N, lot = % of that round's volume). Purpose: cushion further losses if price moves against the position.

🚫 Khuyến nghị tắt Hedge khi dùng Lot BalanceRecommended: disable Hedge when using Lot Balance Hedge tạo lot ảo trên một phía làm Lot Balance tính sai. Kết quả là EA không thể cân bằng hiệu quả. Đặt InpHedgeAfterTrades = 999 để vô hiệu hoá. Hedge adds phantom lots on one side, causing Lot Balance to miscalculate. Result: EA cannot balance effectively. Set InpHedgeAfterTrades = 999 to disable.
📌 InpHedgeMode = PerRoundInpHedgeMode = PerRound Trigger theo từng round: round nào có ≥ N lệnh một phía (và tổng profit phía đó đang âm) thì mở một hedge riêng cho round đó; lot = InpHedgeLotPercent% volume của chính round đó. Comment lệnh hedge: Hedge R{roundId} |hedge. Nhiều round đạt N → nhiều lệnh hedge (mỗi round một hedge). Trigger per round: any round with ≥ N orders on one side (and that side's total profit negative) gets its own hedge; lot = InpHedgeLotPercent% of that round's volume. Hedge comment: Hedge R{roundId} |hedge. Multiple rounds reaching N → multiple hedge orders (one per round).
ParameterMô tảDescription
InpHedgeAfterTrades Kích hoạt khi số lệnh cùng phía ≥ N. Đặt 999 để tắt. Activates when same-side orders ≥ N. Set 999 to disable.
InpHedgeMode Dropdown (v1.23+, ENUM_HedgeMode):
  • ByMainRound — lot = InpHedgeLotPercent% volume của round lớn nhất phía đó. 1 hedge/phía.
  • ByTotal (default) — lot = InpHedgeLotPercent% tổng lot phía đó. 1 hedge/phía.
  • ByAccountProfit — lot = (lỗ tài khoản USD / 100) × InpHedgeLotPer100USD. 1 hedge/phía.
  • PerRound — mở 1 hedge cho MỖI round đạt N lệnh, lot = % volume round đó (comment Hedge R{id}).
Dropdown (v1.23+, ENUM_HedgeMode):
  • ByMainRound — lot = InpHedgeLotPercent% of largest round's volume. 1 hedge per side.
  • ByTotal (default) — lot = InpHedgeLotPercent% of side's total lot. 1 hedge per side.
  • ByAccountProfit — lot = (account loss USD / 100) × InpHedgeLotPer100USD. 1 hedge per side.
  • PerRound — one hedge per qualifying round, lot = % of that round's volume (comment Hedge R{id}).
InpHedgeLotPercent % lot hedge so với tổng lot phía đó (chế độ ByMainRound/ByTotal/PerRound). Bỏ qua khi ByAccountProfit. Hedge lot as % of that side's total lot (ByMainRound/ByTotal/PerRound modes). Ignored in ByAccountProfit.
InpHedgeLotPer100USD [ByAccountProfit] Lot hedge mỗi 100 USD lỗ (vd: 0.01 → lỗ 500$ = 0.05 lot). [ByAccountProfit] Hedge lot per 100 USD loss (e.g. 0.01 → $500 loss = 0.05 lot).

11. Tia (Cluster Scalping)

Tia là cơ chế tỉa lệnh theo cluster: khi tìm thấy một nhóm lệnh Buy + Sell hỗn hợp có tổng profit ≥ InpTiaProfitUSD, EA đóng toàn bộ cluster đó. Đây là cơ chế chốt lời chính của GoldenRobber — kết hợp partial close và fallback thông minh giúp xử lý lệnh kẹt ngay cả trong các điều kiện thị trường phức tạp.

Tia is a cluster scalping mechanism: when a group of mixed Buy+Sell orders has combined profit ≥ InpTiaProfitUSD, the EA closes the entire cluster. This is GoldenRobber's primary profit-harvesting mechanism — combining partial close and smart fallback to handle stuck orders even in complex market conditions.

Tia + DCA TP (tóm tắt)Tia + DCA TP (summary) Một công tắc InpTiaDcaTpSynergyEnable. Khi bật, mọi luật Tia (nhóm InpGroupTia: InpTiaProfitUSD, BotDCA style, partial, chọn mask, …) giữ nguyên; EA thêm tín hiệu khoảng cách tới TP (mức broker hoặc mức ảo khi InpVirtualDcaTpEnable=true, vẫn từ cùng pips DCAPos/DCANeg) để đóng cụm linh hoạt hơn. Chi tiết: 11.1. Single toggle InpTiaDcaTpSynergyEnable. When on, all Tia rules (InpGroupTia: InpTiaProfitUSD, BotDCA style, partial, mask selection, …) stay the same; the EA layers in distance to TP (broker level or virtual level when InpVirtualDcaTpEnable=true, same DCAPos/DCANeg pip config) for more flexible cluster exits. Details: §11.1.

11.1. Tia + DCA TP — cách hoạt động / How it works

Tia (đóng cụm theo profit) và TP từng lệnh trên sàn vẫn hoạt động độc lập: broker có thể khớp TP bất cứ lúc nào. Synergy không thay thế Tia; nó chỉ điều chỉnh ngưỡng $thứ tự / ưu tiên khi EA đang tính toán đóng theo logic Tia trong cùng một tick.

Tia (cluster profit closes) and per-order broker TPs still run independently: the server can fill a TP at any time. Synergy does not replace Tia; it only adjusts the USD threshold and ordering / tie-breaks while the EA evaluates Tia-style closes on a given tick.

  1. “Gần TP” — EA đo pips tới mức chốt: TakeProfit trên sàn nếu có; nếu TP = 0InpVirtualDcaTpEnable + TP DCA bật thì dùng mức ảo open ± pip config. Nếu còn ≤ 10 pips tới mức đó → gần TP. Không có TP broker và không áp virtual/config → không tính gần TP.
  2. Hạ ngưỡng profit cho cụm — Trên tập lệnh symbol/magic đang được Tia xét, nếu có ít nhất một lệnh gần TP và synergy bật, target $ dùng trong vòng xử lý đó trở thành max(0.5, minTarget − 3.0) USD. Ở đây minTarget là target Tia bình thường: InpTiaProfitUSDMin nếu > 0, không thì InpTiaProfitUSD (hoặc InpTiaProfitWhenLossUSD khi rescue mode bật bằng InpTiaHighTargetLossUSD và loss vượt ngưỡng). Áp dụng cho cả partial closeđóng full cluster (vòng mask).
  3. Partial close — Khi chọn lệnh lời để ghép tỉa lỗ: mặc định synergy sắp xếp gần TP trướh, cùng khoảng cách thì lời lớn trước. Nếu InpTiaCloseOldestFirst = true thì vẫn FIFO theo thời gian mở (synergy không đổi thứ tự lời). Thứ tự lệnh lỗ và các tùy chọn khác (InpTiaPrioritizeByDistance, InpTiaMaxHoldHours, …) không đổi.
  4. Chọn tổ hợp mask (full cluster) — Khi nhiều cụm con cùng đạt ngưỡng và tổng profit gần bằng nhau (trong biên ±0.5 USD), EA dùng điểm ưu tiên: vẫn tính điểm cho lệnh lỗ xa giá như trước; synergy cộng thêm 50 × (số lệnh trong mask đang gần TP) để ưu tiên cụm có nhiều chân sắp chốt theo TP (broker hoặc ảo).

Khi nào nên bật: Khi bạn dùng TP DCA (trên sàn hoặc ảo) và muốn Tia nhường đường hơn cho các lệnh sắp TP (đóng cụm sớm hơn vài USD, ưu tiên chốt lời gần TP trong partial). Khi nào để tắt: Nếu bạn muốn Tia chỉ theo đúng số $ cố định, không phụ thuộc khoảng cách tới TP. Các mức số trong mục trên (10 pips, 3 USD, 0.5 USD, hệ số 50) là cố định theo bản EA — không chỉnh qua input.

  1. “Near TP” — Pips to the exit level: broker TakeProfit if set; if TP = 0 and virtual DCA TP is on with per-leg TP enabled, the EA uses the virtual level open ± pip distance. If within 10 pips of that level, the leg is near TP. No broker TP and no applicable virtual/config → not near TP.
  2. Lower cluster USD target — On the symbol/magic set Tia is evaluating, if synergy is on and at least one leg is near TP, the USD target for that evaluation becomes max(0.5, minTarget − 3.0) USD. Here minTarget is the normal Tia target: InpTiaProfitUSDMin if > 0, else InpTiaProfitUSD (or InpTiaProfitWhenLossUSD when rescue mode is active via InpTiaHighTargetLossUSD and loss exceeds it). This applies to both partial close and full-cluster mask closes.
  3. Partial close — When picking profitable legs to pair with losers: with synergy, sort is closest to TP first, then larger profit at the same distance. If InpTiaCloseOldestFirst = true, FIFO by open time wins (synergy does not reorder winners). Loser ordering and other options (InpTiaPrioritizeByDistance, InpTiaMaxHoldHours, …) are unchanged.
  4. Mask selection (full cluster) — When several candidate subsets meet the threshold with similar total profit (within ±0.5 USD), the EA uses a priority score: the existing “far loss” tie-break remains; synergy adds 50 × (near-TP legs in that mask) so subsets with more legs near exit (broker or virtual TP) are preferred.

When to enable: You use DCA per-order TPs (broker or virtual) and want Tia to be slightly more accommodating near those TPs (cluster target a few dollars lower, winners near TP closed first in partial). When to leave off: You want Tia to follow a fixed USD target only, with no TP-distance influence. The numeric thresholds above (10 pips, $3, $0.5 floor, ×50 tie-break) are fixed for a given EA build — not exposed as inputs.

📌 Mixed-Side Mode — Cơ chế 2 tình huốngMixed-Side Mode — Two-scenario logic Khi InpTiaBotDCAStyle = true, Tia hoạt động theo 2 tình huống:
(1) Cả 2 chiều đang mở (bình thường / neutral): yêu cầu cluster có cả Buy + Sell theo InpTiaBotDCAMinSide.
(2) Chỉ 1 chiều đang mở (do Trend Filter chặn chiều kia): fallback — cho phép đóng cluster cùng chiều khi đủ profit. Tránh bị kẹt vô thời hạn khi filter tạo 1 chiều.
When InpTiaBotDCAStyle = true, Tia uses two-scenario logic:
(1) Both directions open (normal/neutral): cluster requires both Buy + Sell sides per InpTiaBotDCAMinSide.
(2) Only one direction open (Trend Filter blocked the other): fallback — allows same-direction cluster close when profit is met. Prevents infinite lock-in when filters create one-sided positions.
ParameterMặc địnhDefaultMô tảDescription
InpTiaClusterMin1 Số lệnh tối thiểu trong cluster (Buy+Sell). Minimum orders in cluster (Buy+Sell mixed).
InpTiaClusterMax0 Số lệnh tối đa trong cluster. 0 = không giới hạn. Max orders in cluster. 0 = unlimited.
InpTiaMaxPositions14
MIN=8, MAX=22
Cap số positions được sample cho vòng mask BotDCA (2^N tổ hợp). Clamp cứng [8, 22] trong code — vượt biên → đẩy về biên gần nhất. 14=16k OK; 16=64k chậm 4×; 18=256k chậm 16×; 20=1M chậm 64×; 22=4M chậm 256×. Vượt cap → sample N oldest. Flexible partial close KHÔNG bị giới hạn này (xét toàn bộ positions). Cap on positions sampled for mask iteration (2^N subsets). Hard clamp [8, 22] in code — out-of-range values pinned to nearest bound. 14=16k OK; 16=64k 4× slower; 18=256k 16×; 20=1M 64×; 22=4M 256×. Exceeds cap → sample N oldest. Flexible partial close NOT subject to this limit (sees all positions).
InpTiaProfitUSD5.0 Chốt cluster khi tổng profit ≥ $N. Giá trị nhỏ = đóng thường xuyên (nhiều lần nhỏ). Giá trị lớn = giữ cluster lâu hơn, mỗi lần đóng bù nhiều lệnh hơn. Close cluster when combined profit ≥ $N. Small value = frequent closes (many small gains). Large value = hold cluster longer, each close offsets more orders.
InpTiaBotDCAStyletrue true = Mixed-Side Mode: yêu cầu cluster có cả Buy+Sell theo InpTiaBotDCAMinSide, với fallback khi chỉ 1 chiều tồn tại. False = đóng bất kỳ mix đủ profit (không phân biệt chiều). true = Mixed-Side Mode: cluster requires both Buy+Sell per InpTiaBotDCAMinSide, with fallback when only one direction exists. False = close any mix with sufficient profit (direction-agnostic).
InpTiaBotDCAMinSide2 Số lệnh tối thiểu mỗi phía khi Mixed-Side Mode bật và cả 2 chiều đang mở:
2 = conservative (2+1): cần ít nhất 1 lần DCA add trước khi đóng cluster.
1 = fast (1+1): đóng ngay sau Init — phù hợp thị trường biến động nhanh.
Min positions per side when Mixed-Side Mode is on and both directions are open:
2 = conservative (2+1): requires at least one DCA add before cluster close.
1 = fast (1+1): closes immediately after Init — suitable for fast-moving markets.
InpTiaProfitUSDMin0 Target tối thiểu (USD): 0 = dùng InpTiaProfitUSD. >0 = cho phép chốt sớm khi tổng lời ≥ giá trị này. Minimum target (USD): 0 = use InpTiaProfitUSD. >0 = allow early close when combined profit ≥ this value.
InpTiaProfitWhenLossEnablefalse Bật/tắt chế độ Tia rescue mode (target cao hơn). ĐỘC LẬP với LotBalance — chỉ phụ thuộc InpTiaHighTargetLossUSD và total loss hiện tại. Khi active: thay vì đóng cluster ngay ở $5, Tia giữ profit-side tích lũy đến target cao hơn → mỗi cluster bù được nhiều lệnh kẹt hơn. Enable/disable Tia rescue mode (higher target). INDEPENDENT from LotBalance — depends only on InpTiaHighTargetLossUSD and current total loss. When active: instead of closing clusters at $5, Tia holds the profit side to accumulate to a higher target → each close offsets more stuck orders.
InpTiaProfitWhenLossUSD30.0 Target cluster (USD) khi rescue mode active. Giá trị lớn hơn = profit-side giữ lâu hơn, mỗi cluster bù nhiều hơn. Chỉ có hiệu lực khi Enable=true và loss vượt ngưỡng InpTiaHighTargetLossUSD. Cluster target (USD) when rescue mode is active. Higher value = profit-side held longer, more offset per close. Only applies when Enable=true and loss exceeds InpTiaHighTargetLossUSD.
InpTiaHighTargetLossUSD0 Ngưỡng total loss (USD, dương) để kích hoạt rescue mode. 0 = disabled (Tia luôn dùng InpTiaProfitUSD). Vd: 3000 = active khi g_cachedTotalProfitUSD ≤ -$3000. Hoàn toàn độc lập với InpLotBalanceLossTriggerUSD. Threshold of total loss (USD, positive) to activate rescue mode. 0 = disabled (Tia always uses InpTiaProfitUSD). E.g. 3000 = active when g_cachedTotalProfitUSD ≤ -$3000. Fully decoupled from InpLotBalanceLossTriggerUSD.
InpTiaPartialCloseEnabletrue Bật/tắt nhánh Flexible partial close (lập kế hoạch trước: lời đủ target → budget tỉa lỗ; chỉ tỉa khi khả thi). Không tắt partial trong vòng mask — dùng InpTiaMaskPartialCloseEnable. Tắt cả hai input Tia partial → không gọi PositionClosePartial trong Tia (vẫn có thể đóng full). Enable/disable the Flexible partial-close branch (plan first: winners hit target → loss-trim budget; trim only when feasible). This does not disable mask partials — use InpTiaMaskPartialCloseEnable. With both Tia partial toggles off, Tia won’t call PositionClosePartial (full closes may still occur).
InpTiaMaskPartialCloseEnabletrue Bật/tắt partial close trong vòng mask sau khi chọn cụm: đóng lệnh lời (full), rồi dùng remainingBudget để đóng lệnh lỗ — full hoặc partial. Tắt = không gọi partial ở bước này (chỉ full khi đủ điều kiện). Enable/disable partial closes in the mask pass after a cluster is chosen: close winners (full), then use remainingBudget on losers — full or partial. Off = no PositionClosePartial in this step (full only when applicable).
InpTiaPrioritizeByDistancetrue true = ưu tiên lệnh lỗ xa giá trước; false = ưu tiên lỗ lớn trước. Phân tích live (ReportHistory-21478308): trong mẫu cluster, xa giá và lỗ lớn thường trùng thứ tự → hai chế độ có thể cho kết quả giống nhau. true = prioritize loss orders farthest from price; false = prioritize largest loss first. Live account analysis (ReportHistory-21478308): in sampled clusters, distance and loss order often coincide, so both settings may behave the same.
InpTiaCloseOldestFirstfalse Chọn lệnh lời để chốt: true = FIFO (cũ nhất trước), false = lời lớn nhất trước. Choose which profit orders to close: true = FIFO (oldest first), false = largest profit first.
InpTiaMaxHoldHours0 Ưu tiên đóng lệnh lỗ cũ hơn N giờ trong partial close. 0 = tắt. Prioritize closing loss orders older than N hours in partial close. 0 = off.
InpTiaDcaTpSynergyEnablefalse Bật synergy Tia + TP sàn: xem mục 11.1. Tóm lại: giữ nguyên nhóm Tia; khi có lệnh gần TP → hạ nhẹ target $, partial ưu tiên lời gần TP (trừ FIFO), mask cộng điểm tie-break. Enable Tia + broker TP synergy: see §11.1. Summary: all Tia inputs unchanged; when a leg is near TP → slightly lower USD target, partial prefers winners near TP (unless FIFO), mask tie-break scoring.
InpTiaPartialCloseLogEnablefalse Bật ghi log partial close ra file (để xem lệnh nào đã partial trong backtest).Enable logging partial closes to file (for backtest inspection).
InpTiaPartialCloseLogFile"" Tên file log (vd: PartialClose.csv). Trống = dùng PartialClose.csv.Log file name (e.g. PartialClose.csv). Empty = PartialClose.csv.
InpTiaAnchorRequire
v1.07+
true Cluster phải bao gồm anchor — lệnh xa+lâu nhất ở chiều ngược với chiều đang lời. Nếu anchor không vào được kế hoạch tỉa (budget không đủ để partial-close anchor ≥ minLot) → hoãn toàn bộ cluster. Mục đích: tránh để rung ngoài cùng cô lập khi rung trong bị đóng. Xem §11.2. Cluster must include the anchor — the farthest+oldest loss on the side opposite the profit-side. If anchor can't be partial-closed within budget (≥ minLot) → hold the whole cluster. Goal: prevent isolating the outermost rung after inner rungs close. See §11.2.
InpTiaLadderRollClose
v1.08+
true "Quấn chiếu" — opposite-side losses chỉ được đóng theo prefix liên tục của ladder tính theo distance descending. Cluster mở các rung 0..K trong cùng một lần đóng; cấm skip rung giữa. Strictly mạnh hơn AnchorRequire (đảm bảo cả rank 1, 2, ... không bị skip, không chỉ rank 0). Mục đích: ladder rút từ ngoài vào, không tạo gap khi giá chạy 1 hướng. Xem §11.2. "Rolling-mat" — opposite-side losses can only be closed as a contiguous prefix of the distance-descending ladder. Cluster opens rungs 0..K together; skipping inner rungs is forbidden. Strictly stronger than AnchorRequire (guarantees ranks 1, 2, ... can't be skipped either, not just rank 0). Goal: ladder shrinks from the outer end inward, no gaps on one-way price runs. See §11.2.
InpTiaAnchorMaxDistPips
v1.10+
0 Release valve cho anchor/ladder. 0 = không giới hạn (anchor strict). >0 = positions xa hơn N pips bị loại khỏi anchor/ladder consideration → cluster có thể đóng các lệnh gần hơn mà không bị anchor xa cô lập gate. Chống deadlock khi hedge cũ bị bỏ lại quá xa. Pip trong EA này theo InpPipPoints: với XAUUSD 2-digit và InpPipPoints=1, 1 pip = $0.01 price → recommended 2000–3000 (= $20–$30). Với InpPipPoints=10, 1 pip = $0.10 → recommended 200–300. Release valve for anchor/ladder. 0 = unlimited (strict anchor). >0 = positions farther than N pips are excluded from anchor/ladder consideration → cluster can close closer positions without being gated by an unreachable far anchor. Prevents deadlock when old hedges drift very far. Pip definition follows InpPipPoints: with XAUUSD 2-digit and InpPipPoints=1, 1 pip = $0.01 → recommended 2000–3000 (= $20–$30). With InpPipPoints=10, 1 pip = $0.10 → recommended 200–300.
InpTiaBlockSameSideWhenStuck
v1.29+, extended v1.30
true Same-side stuck guard: chặn Tia cluster đốt winners cùng side mà bỏ stuck losers cùng side. Anchor logic chỉ force-include opposite-side anchor; v1.29 lấp gap khi profit cluster pure same-side (vd cụm Buy winners với stuck Buys ngoài cluster). Logic: mask phải include ít nhất 1 stuck loser ở side X nếu mask có profitable position cùng side X AND side X có stuck. Mixed cluster (winners cả 2 side) pass tự do — anchor đã handle opposite. v1.30 extension: cũng GATE per-order TP path (broker TP + Virtual DCA TP) — same-side có stuck → HOLD ALL winners cùng side, bất kể v1.28 deadlock guard. Lý do: per-order TP đóng winners từng cái → reset accumulation → Tia không bao giờ đủ profit cover stuck. Hold winners để stack lên cho Tia BnB fire mixed cluster với stuck anchor. Escape valve: trong trend mạnh, side thuận trend tích lũy nhiều winners+lot lớn → Global TP USD reach → close all (bao gồm stuck). Không cần escape riêng. Risk: account trapped (stuck quá xa giá) có thể hold winners vĩnh viễn → cần Global SL Clear Stuck mode=2 (FarOnly) làm safety net. Same-side stuck guard: blocks Tia from firing pure-same-side clusters that burn winners while leaving stuck losers on the same side behind. Anchor logic only force-includes the opposite-side anchor; v1.29 plugs the gap when the profit cluster is single-sided (e.g., Buy winners cluster with stuck Buys outside). Logic: mask must include ≥1 stuck loser on side X if mask has profitable positions on side X AND side X has stuck. Mixed cluster (winners both sides) passes freely — anchor already handles opposite. v1.30 extension: also GATES per-order TP path (broker TP + Virtual DCA TP) — when same-side has stuck → HOLD ALL winners on that side, bypassing v1.28 deadlock guard. Reason: per-order TP closes winners one at a time → resets accumulation → Tia never has enough profit to cover stuck loser. Holding winners lets them stack for Tia BnB to fire a mixed cluster with the stuck anchor. Escape valve: in strong trend, the trend-following side accumulates many winners + bigger lots → Global TP USD reaches → closes all (including stuck). No separate escape needed. Risk: trapped account (stuck too far from price) may hold winners indefinitely → use Global SL Clear Stuck mode=2 (FarOnly) as safety net.
InpTiaStuckLossUSD
v1.29+
200 Ngưỡng coi 1 lệnh là "stuck" theo lỗ USD. Loss ≥ ngưỡng → stuck. 0 = tắt check theo lỗ (chỉ dùng Age). Tuning: 200 cho scalping (lệnh nhỏ); 500-1000 cho swing/heavy DCA. Set thấp = nhiều lệnh bị coi stuck → Tia khắt khe hơn → ít cluster fire → equity smoother nhưng chốt chậm hơn. Threshold to mark a position as "stuck" by USD loss. Loss ≥ threshold → stuck. 0 = disable loss check (use Age only). Tuning: 200 for scalping (small positions); 500-1000 for swing/heavy DCA. Lower value = more positions marked stuck → stricter Tia → fewer cluster fires → smoother equity, slower realization.
InpTiaStuckAgeHours
v1.29+
4 HOẶC coi 1 lệnh là "stuck" nếu mở quá N giờ. Stuck = thoả Loss OR Age. 0 = tắt. Tuning: 4 cho XAU scalp intraday (lệnh không clear trong nửa session = stuck); 24 cho swing dài ngày. Hỗ trợ flag những lệnh nhỏ-lỗ-nhưng-cũ mà chưa đạt threshold USD. OR mark a position as "stuck" if open longer than N hours. Stuck = Loss OR Age. 0 = disable. Tuning: 4 for XAU intraday scalp (positions not clearing within half a session = stuck); 24 for multi-day swing. Catches small-loss-but-old positions that don't hit the USD threshold.

Phân biệt InpTiaMaxPositions vs InpTiaClusterMaxInpTiaMaxPositions vs InpTiaClusterMax — common confusion

2 input nghe giống nhau nhưng làm việc ở 2 layer hoàn toàn khác trong mask pipeline:

Two inputs sound similar but operate at completely different layers in the mask pipeline:

Aspect InpTiaMaxPositions InpTiaClusterMax
Vai trò Role Sample size — bao nhiêu lệnh được "nhìn" Sample size — how many positions get sampled Cluster size — mỗi cluster max bao nhiêu lệnh Cluster size — max positions per cluster
Layer Layer Layer 1: trước khi duyệt maskbefore mask iteration Layer 2: filter từng subset trong maskfilter each subset within mask
Tác động performance Perf impact Lớn: 2^N tổ hợp (exponential) High: 2^N subsets (exponential) Nhỏ: chỉ filter, không đổi số iteration Low: only filters, doesn't change iteration count
Code Code if (count > tiaMaxPos) count = tiaMaxPos; if (bits < ClusterMin || bits > maxSize) continue;
Default Default 14 0 (= unlimited, max = sample size)
Min / Max Min / Max MIN=8, MAX=22 (hard clamp trong code) Min=0 (no lower limit), Max = số position đang sample

Ví dụ với 100 positions mởExample with 100 open positions

Pipeline minh hoạPipeline visualization

100 positions mở
       │
       ▼
[1] InpTiaMaxPositions cap (sample 14 oldest, drop 86)
       │
       ▼
14 positions cho mask iteration
       │
       ▼
2^14 = 16,384 subset tổ hợp
       │
       ▼
[2] InpTiaClusterMin / InpTiaClusterMax filter (size ∈ [Min, Max])
       │
       ▼
[3] BotDCA filter (≥3 Buy & ≥3 Sell)
       │
       ▼
[4] Profit filter (sum ≥ effectiveTarget)
       │
       ▼
[5] Side-balance guard
       │
       ▼
Best cluster → close
Khi nào tăng InpTiaMaxPositionsWhen to increase InpTiaMaxPositions Khi tổng positions thường xuyên > 14 và 14 oldest có thể skewed 1 phía (vd. toàn Sells từ DOWN trend cũ) → mask không tạo được cluster Buy+Sell mix → tăng lên 16-18 để sample bao gồm cả lệnh mới hơn. Trade-off: 2× mỗi increment → backtest chậm 4×, 16×, 64×. When total positions regularly > 14 and the 14 oldest may be skewed to one side (e.g., all Sells from old DOWN trend) → mask can't form Buy+Sell mix cluster → bump to 16-18 to include newer entries. Trade-off: 4×, 16×, 64× slower per increment.

11.2 Ladder integrity — Anchor / Ladder-roll / Release valve

Bộ 3 input từ v1.07–v1.10 giải quyết một class lỗi sâu của cluster scalping: khi giá chạy 1 hướng dài, các hedge cũ ở chiều ngược dồn lại xa giá hiện tại. Cluster cũ chỉ chốt theo "P_sum ≥ target" sẽ có xu hướng đóng lệnh lỗ gần giá (lỗ nhỏ, fit budget) và để lệnh lỗ xa giá (lỗ lớn) cô lập → ladder bị gãy thành nhiều mảnh, mỗi rung lẻ là một anchor cô lập kéo equity. Các flag dưới đây bắt cluster "quấn chiếu" từ rung ngoài cùng vào, đồng thời cho release valve khi rung ngoài quá xa.

A trio of inputs from v1.07–v1.10 fixes a subtle failure mode in cluster scalping: when price runs one direction for a long stretch, old hedges on the opposite side drift far from the current price. The original "close when P_sum ≥ target" logic naturally picks the near losses (small, fit budget) and leaves far losses isolated → the ladder breaks into multiple stranded rungs, each acting as an equity-dragging mini-anchor. The flags below force cluster closes to "roll the mat" from the outermost rung inward, with a release valve when the outer rung is unreachable.

Ba thuật ngữ / Three concepts

Khái niệmConcept Định nghĩaDefinition Input gateInput flag
Anchor Lệnh xa nhất + lâu nhất ở chiều ngược với chiều đang lời trong cluster. Là rung 0 của ladder. The farthest+oldest loss on the side opposite the profit-side within a cluster. Rank 0 of the ladder. InpTiaAnchorRequire
Ladder Toàn bộ lệnh lỗ ở chiều ngược, sort theo distance descending. Prefix liên tục = đóng rung 0..K trong cùng cluster, không skip giữa. All opposite-side losses sorted by distance descending. Contiguous prefix = close rungs 0..K together in one cluster, no skipping. InpTiaLadderRollClose
Release valve Khoảng cách tối đa (pips) để position được tính vào anchor/ladder. Xa hơn → "free agent", không gate cluster. Max distance (pips) for a position to be considered for anchor/ladder. Beyond that → "free agent", doesn't gate cluster. InpTiaAnchorMaxDistPips

Ví dụ trực quanWorked example

Giả sử ladder Sell (đối diện Buy đang lời), giá hiện tại 86, sắp xếp theo distance descending:

Suppose a Sell ladder (opposite to Buy profit-side), current price 86, sorted by distance descending:

Rank 0 (anchor)  Sell@100  → 14.00 distance (1400 pip @ InpPipPoints=1)
Rank 1           Sell@96   →  10.00 distance
Rank 2           Sell@94   →   8.00 distance
Rank 3           Sell@90   →   4.00 distance
Rank 4           Sell@88   →   2.00 distance
Closing set (opposite-side sells)Closing set (opposite-side sells) AnchorRequire only LadderRollClose Ghi chúNotes
{Sell@100}✅ has anchor✅ prefix K=1Đóng rung ngoài cùng, ladder rút từ ngoài vàoClose outer rung only — ladder shrinks from outside
{Sell@100, Sell@96}✅ prefix K=2Đóng 2 rung ngoàiClose two outer rungs
{Sell@100, Sell@94}✅ has anchor❌ skips rank 1Bị reject: tạo gap ở rank 1 (Sell@96)Rejected: leaves a gap at rank 1 (Sell@96)
{Sell@100, Sell@90}❌ skips rank 1, 2
{Sell@96}❌ no anchor❌ no anchorBị reject: bỏ rung ngoài cùng → tách lonelyRejected: leaves outer rung isolated
{Sell@94, Sell@90}❌ no anchor

Deadlock & Release valveDeadlock & release valve

Rủi ro Anchor strictRisk of strict anchor mode Khi anchor xa quá (vd 37 USD = 3725 pip với XAUUSD trong 1 lệnh hedge bị bỏ lại), budget cluster không bao giờ đủ để trim anchor → cluster bị hoãn vĩnh viễn → lỗ tích lũy. Đây là deadlock thật trong production. When the anchor sits very far (e.g. a stranded hedge at 37 USD = 3725 pip away on XAUUSD), the cluster budget never grows enough to trim it → cluster is held indefinitely → losses accumulate. This is a real production deadlock.

InpTiaAnchorMaxDistPipsrelease valve: positions xa hơn N pips bị loại khỏi anchor/ladder. Anchor mới sẽ là position xa nhất CÒN trong ngưỡng → cluster có thể đóng các rung trong ngưỡng mà không bị positions ngoài ngưỡng gate. Các positions ngoài ngưỡng trở thành "free agents" — cluster có thể chọn gom chúng (nếu budget cho phép) hoặc để dành Global SL Clear Stuck dọn.

InpTiaAnchorMaxDistPips is the release valve: positions farther than N pips are excluded from anchor/ladder. The new anchor becomes the farthest position WITHIN range → cluster can close in-range rungs without out-of-range positions gating it. Out-of-range positions become "free agents" — cluster may opt to bundle them (if budget allows) or defer them to Global SL Clear Stuck.

Đơn vị pip — chú ý quan trọngPip unit — critical caveat

InpTiaAnchorMaxDistPips dùng pip theo định nghĩa của EA, không phải pip forex chuẩn. Pip size = _Point × InpPipPoints: InpTiaAnchorMaxDistPips uses the EA's own pip definition, not standard forex pip. Pip size = _Point × InpPipPoints: → Verify bằng panel: Gap: X pip | LowB=Y HiS=Z. Tính (Y - Z) / X = pip size thực tế. → Verify via panel: Gap: X pip | LowB=Y HiS=Z. Compute (Y - Z) / X = effective pip size.

Khuyến nghị giá trịRecommended values

Setup InpTiaAnchorRequire InpTiaLadderRollClose InpTiaAnchorMaxDistPips Khi nào dùngWhen to use
Legacy (≤v1.06 behavior) falsefalse0 Backtest so sánh với v1.06; chấp nhận lonely-anchor risk Compare backtests against v1.06; accept lonely-anchor risk
Anchor-only truefalse0 Bảo vệ rung ngoài cùng, nới rung giữa (có thể skip) Protect outermost rung, allow middle rungs to be skipped
Strict (default v1.08) truetrue0 No gap tuyệt đối; rủi ro deadlock nếu anchor xa Absolute no-gap; deadlock risk if anchor drifts far
Strict + valve (recommended) truetrue 2000–3000
(InpPipPoints=1)
200–300
(InpPipPoints=10)
No gap trong ngưỡng $20-30, lệnh hedge cũ quá xa được giải phóng cho Global SL Clear Stuck xử lý No gap within $20-30 range, very-far hedges released to Global SL Clear Stuck
Lịch sử thay đổiChangelog

12. Global TP / SL

Đóng toàn bộ lệnh khi tổng profit nổi đạt ngưỡng. Đây là lưới an toàn cuối cùng.

Closes all positions when total floating profit hits a threshold. This is the final safety net.

ParameterMặc địnhDefaultMô tảDescription
InpGlobalTPUSD70.0 Đóng hết khi tổng profit ≥ $N.Close all when total profit ≥ $N.
InpGlobalSLUSD999999 Đóng hết khi tổng lỗ ≥ $N. Đặt lớn (999999) = tắt Global SL. Close all when total loss ≥ $N. Set large (999999) = disabled.

13. Clear Stuck Orders

Cơ chế cắt lệnh kẹt khi lỗ nổi vượt một khoảng cách pips nhất định. Khác với Global SL — chỉ nhắm vào lệnh xa giá, không đóng hết.

Mechanism to cut stuck orders when floating loss exceeds a pip distance threshold. Unlike Global SL — targets only orders far from price, not a full close.

Nguyên tắc "không dùng SL""No SL" principle Chiến lược này không dùng Stop Loss truyền thống. Mặc định InpGlobalSLClearStuckEnable = false. Chỉ bật nếu hiểu rõ rủi ro. This strategy does not use traditional Stop Losses. Default InpGlobalSLClearStuckEnable = false. Only enable if you understand the risk.
ParameterMô tảDescription
InpGlobalSLClearStuckEnable Bật/tắt cơ chế cắt lệnh kẹt. Mặc định tắt. Enable/disable stuck order cutting. Default off.
InpGlobalSLClearStuckDistancePips Khoảng cách tối thiểu (pips) từ giá để coi là "kẹt". Min distance (pips) from price to consider "stuck".
InpGlobalSLClearStuckMode 0=đóng hết, 1=worst only, 2=xa only, 3=cùng phía worst, 4=partial xa 0=close all, 1=worst only, 2=far only, 3=same side as worst, 4=far partial
InpGlobalSLClearStuckMaxLossPctOfDayProfit Chỉ cắt khi loss < % này của profit trong ngày. Tránh cắt khi ngày đang lỗ nặng. Only cut when loss < this % of today's profit. Prevents cutting on already bad days.
InpGlobalSLClearStuckProfitPeriod Kỳ tính profit: 0 = Daily (balance - balance 00:00), 1 = Weekly (balance - balance thứ 2 00:00). Weekly cho phép tích lũy profit nhiều ngày để dọn lệnh kẹt lớn. Profit period: 0 = Daily (balance - balance 00:00), 1 = Weekly (balance - Monday 00:00). Weekly allows accumulating multi-day profit for clearing large stuck orders.
InpGlobalSLClearStuckEmergencyPips Nếu lệnh tệ nhất xa hơn N pips → cắt ngay, bỏ qua điều kiện profit. 0 = tắt. If worst order is N pips away → cut immediately, ignoring profit condition. 0 = off.
Budget-based: không bao giờ làm profit period âmBudget-based: never makes period profit negative Tất cả modes đều kiểm tra budget trước khi đóng: max loss = profitInPeriod × maxLossPct%. Ví dụ: tuần này lời $500, maxLoss=50% → budget $250 → chỉ đóng lệnh kẹt trong $250, profit tuần vẫn ≥ $250. Emergency mode bypass budget. All modes check budget before closing: max loss = profitInPeriod × maxLossPct%. Example: this week's profit $500, maxLoss=50% → budget $250 → only closes stuck orders within $250, weekly profit remains ≥ $250. Emergency mode bypasses budget.

14. Daily Profit LimitDaily Profit Limit

Khi bật: đạt target lời trong ngày (balance − balance đầu ngày) hoặc target lỗ (tổng profit nổi âm) thì EA đóng hết lệnhkhông mở lệnh mới đến hết ngày. Sang ngày mới tự reset.

When enabled: when daily profit target (balance − start-of-day balance) or daily loss target (floating P/L) is reached, the EA closes all positions and stops opening new orders for the rest of the day. Resets at the start of the next day.

ParameterMặc địnhDefaultMô tảDescription
InpDailyLimitEnablefalse Bật/tắt limit lời/lỗ mỗi ngày.Enable/disable daily profit/loss limit.
InpDailyLimitTargetProfitUSD0 Đạt profit trong ngày ≥ $N → đóng hết, dừng trade. 0 = tắt. Daily profit ≥ $N → close all, stop trading. 0 = off.
InpDailyLimitTargetLossUSD0 Đạt lỗ nổi ≥ $N (số dương, vd 500 = lỗ 500$) → đóng hết, dừng trade. 0 = tắt. Floating loss ≥ $N (positive number) → close all, stop. 0 = off.

15. Risk Management

ParameterMặc địnhDefaultMô tảDescription
InpMaxDrawdownEnablefalse Bật bảo vệ drawdown tối đa.Enable max drawdown protection.
InpMaxDrawdownPercent80 Dừng mở lệnh mới khi equity giảm N% từ đỉnh. 0 = không dùng %. Stop new orders when equity drops N% from peak. 0 = don't use %.
InpMaxDrawdownUSD0 Dừng mở lệnh khi equity giảm $N từ đỉnh. 0 = tắt. Stop new orders when equity drops $N from peak. 0 = off.
InpMaxDrawdownCloseAllfalse True = đóng hết lệnh khi vi phạm drawdown. False = chỉ dừng Init/Add. True = close all when drawdown breached. False = only stop Init/Add.
InpMaxLossPerDayEnablefalse Bật giới hạn lỗ trong ngày.Enable daily loss limit.
InpMaxLossPerDayUSD5000 Dừng mở lệnh mới khi lỗ ngày ≥ $N. Stop new orders when daily loss ≥ $N.

16. Thời gian giao dịch & Bảo vệ cuối tuầnTrading Time & Weekend Protection

ParameterMặc địnhDefaultMô tảDescription
InpStartHour / InpStartMinute0 / 1 Bắt đầu cửa sổ giao dịch (giờ:phút server). EA không Init trước thời điểm này. Start of trading window (hour:minute server). EA won't Init before this time.
InpEndHour / InpEndMinute23 / 59 Kết thúc cửa sổ giao dịch. Ngoài khoảng [Start, End] EA không Init. End of trading window. EA won't Init outside [Start, End].
InpWeekendProtectionEnabletrue Bảo vệ gap cuối tuần.Enable weekend gap protection.
InpFridayNoInitAfterHour13 Thứ 6: không mở Init sau giờ này (giờ server). Friday: no new Init after this hour (server time).
InpFridayCloseAllBeforeHour21 Thứ 6: đóng hết lệnh trước giờ này (server). 0 = tắt. Friday: close all before this hour (server). 0 = off.
InpFridayCloseMinProfitUSD-999999 Chỉ đóng thứ 6 khi tổng profit ≥ $N. -999999 = luôn đóng; -50 = bỏ qua đóng nếu đang lỗ > 50. Only close on Fri when total profit ≥ $N. -999999 = always close.
InpMaxNetLotBeforeWeekend0.5 Không Init khi |Buy−Sell| > N lot vào thứ 6. 0 = tắt. No Init if |Buy−Sell| > N lots on Friday. 0 = off.
InpWeekendBalanceEnabletrue Tự động cân bằng lot vào thứ 6 trước khi đóng cửa. Auto-balance lots on Friday before close.
InpMondayNoInitUntilHour2 Thứ 2: không Init trước giờ này (tránh gap mở cửa). Monday: no Init before this hour (avoid open gap).
InpWeekendBalanceMaxLotPerOrder0.2 Lot tối đa mỗi lệnh cân bằng thứ 6 (throttle 1 lệnh/nến M1). Max lot per Friday balance order (throttled 1 per M1 bar).

Symbol & MagicSymbol & Magic

ParameterMặc địnhDefaultMô tảDescription
InpPipPoints10 Số points cho 1 pip (XAU thường 10; ≤0 = tự detect). Dùng cho MinPips, range, S/R, Pivot proximity, etc. Points per pip (XAU typically 10; ≤0 = auto-detect). Used for MinPips, range, S/R, Pivot proximity, etc.
InpMagic21478308 Magic number của EA. Chỉ quản lý lệnh cùng magic. EA magic number. Only manages orders with this magic.

📐 Bảng quy đổi USD ↔ Pip (XAU 2-digit broker, _Point=0.01) 📐 USD ↔ Pip conversion tables (XAU 2-digit broker, _Point=0.01)

Công thức: pipSize = _Point × InpPipPoints. Mọi input có chứa Pips trong tên (vd InpDCAPosMinPips, InpPivotProximityPips) đều được nhân với pipSize này để ra giá trị USD price thực tế.

Formula: pipSize = _Point × InpPipPoints. Every input with Pips in its name (e.g. InpDCAPosMinPips, InpPivotProximityPips) is multiplied by this pipSize to get actual USD price distance.

InpPipPoints = 1 — 1 pip = $0.01 (1 cent)
Price (USD)Price (USD) Pip countPip count
$0.011 pip
$0.1010 pips
$0.5050 pips
$1.00100 pips
$5.00500 pips
$10.001,000 pips
$50.005,000 pips

Pip rất nhỏ → các config dùng giá trị Pips lớn (vd MinPips=270, Anchor=6000). Phù hợp scalp tight. Pip very small → configs use large Pips values (e.g. MinPips=270, Anchor=6000). Suited for tight scalps.

InpPipPoints = 10 — DEFAULT, 1 pip = $0.10
Price (USD)Price (USD) Pip countPip count
$0.101 pip
$0.505 pips
$1.0010 pips
$2.7027 pips (DCAPosMinPips)
$3.4034 pips (DCANegMinPips)
$5.0050 pips
$10.00100 pips
$50.00500 pips
$100.001,000 pips

Khuyến nghị cho XAU 2-digit broker. Tương đương "pip forex chuẩn" mở rộng cho gold. Các config A baseline / 21-05-2026 đều dùng giá trị này. Recommended for XAU 2-digit broker. Equivalent to "standard forex pip" extended to gold. All A baseline / 21-05-2026 configs use this setting.

InpPipPoints = 100 — 1 pip = $1.00
Price (USD)Price (USD) Pip countPip count
$0.500.5 pip
$1.001 pip
$5.005 pips
$10.0010 pips
$27.0027 pips (=$27 movement!)
$50.0050 pips
$100.00100 pips

Pip lớn → các config Pips số nhỏ. Không khuyến nghị trừ khi muốn thiết kế cho macro-scale trading (vd swing tuần). Pip very large → configs use small Pips values. Not recommended unless designing for macro-scale trading (e.g. weekly swing).

💰 PnL mỗi pip theo lot size (XAU) 💰 PnL per pip by lot size (XAU)

1 lot XAU = 100 oz. PnL/pip = lot × 100 oz × pipSize. 1 lot XAU = 100 oz. PnL/pip = lot × 100 oz × pipSize.

Lot sizeLot size =1 ($0.01/pip) =10 ($0.10/pip) =100 ($1.00/pip)
0.01 (min)$0.01$0.10$1.00
0.02 (DCANeg start)$0.02$0.20$2.00
0.05 (DCAPos start)$0.05$0.50$5.00
0.10$0.10$1.00$10.00
0.20 (MaxLot config A)$0.20$2.00$20.00
0.50$0.50$5.00$50.00
1.00 (standard)$1.00$10.00$100.00

Ví dụ: InpPipPoints=10 + lot 0.10 → mỗi pip giá chạy = $1 PnL. Nến XAU di chuyển 50 pip → ±$50 PnL trên 0.10 lot. Example: InpPipPoints=10 + 0.10 lot → each pip of price = $1 PnL. XAU candle moving 50 pips → ±$50 PnL on 0.10 lot.

⚠️ Lưu ý broker 3-digitNote: 3-digit broker Một số broker XAU dùng _Digits=3, _Point=0.001 (3 chữ số sau dấu phẩy thay vì 2). Khi đó InpPipPoints=10 → pipSize = 0.001 × 10 = $0.01 → $1 = 100 pips thay vì 10 pips. Đặt InpPipPoints≤0 để EA tự detect đúng theo _Digits hoặc explicit =100 để giữ ngữ nghĩa "$0.10 = 1 pip". Some XAU brokers use _Digits=3, _Point=0.001 (3 decimals instead of 2). Then InpPipPoints=10 → pipSize = 0.001 × 10 = $0.01 → $1 = 100 pips instead of 10. Set InpPipPoints≤0 for EA to auto-detect by _Digits, or explicit =100 to preserve "$0.10 = 1 pip" semantics.

🧮 Pip Calculator tương tác 🧮 Interactive Pip Calculator

Nhập lot size và InpPipPoints để tự động tính mỗi pip = bao nhiêu USD PnL. Dùng cho XAU 2-digit (_Point=0.01, contract size 100 oz).

Enter lot size and InpPipPoints to auto-calculate USD PnL per pip. For XAU 2-digit (_Point=0.01, contract size 100 oz).

📐 pipSize = _Point × InpPipPoints = 0.01 × 10 = $0.10 price movement / pip 📐 pipSize = _Point × InpPipPoints = 0.01 × 10 = $0.10 price movement / pip

💰 PnL/pip = lot × 100 oz × pipSize = 0.10 × 100 × $0.10 = $1.00 per pip 💰 PnL/pip = lot × 100 oz × pipSize = 0.10 × 100 × $0.10 = $1.00 per pip

Số pip thay đổiPip change USD price movementUSD price movement PnL (USD)PnL (USD) Ghi chúReference

17. Remote Config & Cloud Sync

Module này (input group === Remote Config & Cloud Sync ===) làm 2 việc trên cùng 1 kênh heartbeat: (1) Cloud Sync — đồng bộ Ticket Map để phục hồi khi MT5 sập; (2) Remote Config — nhận config chỉnh từ web (hot-reload) và đẩy telemetry panel lên console. EA dùng Ticket Mapping để track roundId/addNum/isDCAPos per ticket — cần thiết khi PositionClosePartial tạo position mới mất comment trên hedging account.

This module (input group === Remote Config & Cloud Sync ===) does two jobs over one heartbeat channel: (1) Cloud Sync — replicate the Ticket Map for crash recovery; (2) Remote Config — receive web-adjusted config (hot-reload) and push panel telemetry to the console. EA uses Ticket Mapping to track roundId/addNum/isDCAPos per ticket — required because PositionClosePartial creates a new position with lost comment on hedging accounts.

Kiến trúc 3 lớp3-Layer architecture

#SourceKhi nàoWhenMục đíchPurpose
1MQL5/Files/Common/GR_TicketMap_<magic>.csv Luôn (kể cả backtest)Always (incl. backtest) Primary, nhanh nhất, hoạt động offline Primary, fastest, works offline
2Cloudflare Worker + D1Cloudflare Worker + D1 Live (skip backtest)Live only (skip backtest) Backup #1, HA toàn cầu, free tier 100k req/day Backup #1, global HA, free tier 100k req/day
3fxconsole REST API → MySQL Live (skip backtest)Live only (skip backtest) Backup #2, tự host (phòng CF sập) Backup #2, self-hosted (in case CF outage)

Tham số inputInput parameters

ParameterMặc địnhDefaultMô tảDescription
InpCloudSyncEnablefalse Bật/tắt sync. Khi false → chỉ save file local. Backtest LUÔN skip cloud bất kể giá trị này. Enable/disable sync. When false → file local only. Backtest always skips cloud regardless.
InpCloudBearerToken"" Bearer token xác thực API. Với fxconsole = Secret token của EA/admin/easupported/{slug} (mỗi EA product 1 token riêng, không còn dùng chung TMAP_SECRET_KEY .env). Với Cloudflare = secret của Worker. API bearer token. For fxconsole = the EA's Secret token from /admin/easupported/{slug} (per-EA product, no longer the shared TMAP_SECRET_KEY .env). For Cloudflare = the Worker secret.
InpCloudCfDomain"" v1.38: Cloudflare Worker DOMAIN (vd: https://gr-tmap.your-account.workers.dev). EA tự append /tmap/{save,load,clear,heartbeat}. Để trống = skip CF. v1.38: Cloudflare Worker DOMAIN (e.g. https://gr-tmap.your-account.workers.dev). EA appends /tmap/{save,load,clear,heartbeat} itself. Empty = skip CF.
InpCloudMyApiDomain"" v1.38: fxconsole DOMAIN + slug EA (vd: https://fxconsole.gamelau.uk/easupported/goldenrobber). EA tự append /api/tmap/{save,load,clear,heartbeat}. Để trống = skip MyApi. v1.38: fxconsole DOMAIN + EA slug (e.g. https://fxconsole.gamelau.uk/easupported/goldenrobber). EA appends /api/tmap/{save,load,clear,heartbeat} itself. Empty = skip MyApi.
InpCloudSyncIntervalSec30 Throttle interval đồng bộ định kỳ (giây). Cũng là chu kỳ heartbeat → độ trễ nhận config web ≈ giá trị này. Chạy theo OnTimer (không phụ thuộc tick). Critical events (partial close, OnDeinit) bypass throttle. Throttle interval for periodic sync (seconds). Also the heartbeat cadence → web-config apply latency ≈ this value. Runs on OnTimer (tick-independent). Critical events (partial close, OnDeinit) bypass throttle.
InpCloudWebTimeoutMs5000 WebRequest timeout (ms). WebRequest timeout (ms).
InpCloudNodePriority100 Priority node cho leader election (1 = cao nhất, 999 = thấp). Số nhỏ ưu tiên cao hơn khi nhiều instance cùng magic. Node priority for leader election (1 = highest, 999 = lowest). Lower wins when multiple instances share a magic.
InpCloudNodeId"" ID unique cho node (vd vps-tokyo). Trống = auto từ TerminalInfoString. Unique node id (e.g. vps-tokyo). Empty = auto from TerminalInfoString.
InpCloudHeartbeatTimeoutSec90 Coi node là chết nếu không heartbeat trong N giây (server dùng để bầu leader mới). Treat a node as dead if no heartbeat within N seconds (server uses this to elect a new leader).

Remote Config & hot-reload (v1.41.2+)Remote Config & hot-reload (v1.41.2+)

Mỗi EA product được đăng ký ở web console /admin/easupported với 1 URL riêng (đặt vào InpCloudMyApiDomain) + 1 Secret token riêng (đặt vào InpCloudBearerToken). Qua heartbeat, EA tự khai báo danh sách config chỉnh được (config_schema) và đẩy toàn bộ Info Panel lên làm payload telemetry; server render UI động và trả về config đã chỉnh. EA đọc từ global mutable (không phải input) nên áp dụng ngay không cần gỡ EA. Server trả hot_keys (danh sách param đang override) làm nguồn chân lý → nút Clear revert param về default. 13 config hot-reload: manual_init, strong_bypass, strong_tf, strong_require_sr, lot_balance_enable/trigger/target, hedge_enable/after_trades/lot_percent, weekend_protect_enable/max_net_lot/balance_enable. Chi tiết standard + skeleton phát triển EA mới: xem EA-HOTRELOAD-STANDARD.md / .pdf.

Each EA product is registered in the web console /admin/easupported with its own URL (set as InpCloudMyApiDomain) + its own Secret token (set as InpCloudBearerToken). Over the heartbeat the EA self-declares its adjustable config list (config_schema) and pushes the whole Info Panel as payload telemetry; the server renders the UI dynamically and returns the adjusted config. The EA reads from mutable globals (not input), so changes apply live without re-attaching the EA. The server returns hot_keys (params currently overridden) as the source of truth → the Clear button reverts a param to its default. 13 hot-reloadable configs: manual_init, strong_bypass, strong_tf, strong_require_sr, lot_balance_enable/trigger/target, hedge_enable/after_trades/lot_percent, weekend_protect_enable/max_net_lot/balance_enable. Full standard + skeleton for building new EAs: see EA-HOTRELOAD-STANDARD.md / .pdf.

Save flowSave flow

TriggerModeModeHành viBehavior
Init mới, DCA add, Tia close, OnTick cleanupNew Init, DCA add, Tia close, OnTick cleanup TicketMapSave() File LUÔN save. Cloud throttle theo InpCloudSyncIntervalSec File always saves. Cloud throttled by InpCloudSyncIntervalSec
Sau PositionClosePartialAfter PositionClosePartial TicketMapSaveImmediate() File + Cloud NGAY (bypass throttle) — critical: ticket mới phải sync ngay File + Cloud immediately (bypass throttle) — critical: new ticket must sync right away
OnDeinit TicketMapSaveImmediate() Save full trước khi EA tắt Full save before EA shuts down
Map về 0 (clean state)Map back to 0 (clean state) TicketMapClearCloud() DELETE ở cả 2 cloud backends DELETE on both cloud backends

Load priority (OnInit)Load priority (OnInit)

  1. TicketMapLoad()đọc file local (nhanh nhất)read local file (fastest)
  2. Nếu file rỗng → If file empty → TicketMapLoadCloudflare()
  3. Nếu CF cũng rỗng → If CF also empty → TicketMapLoadMyApi()
  4. TicketMapRebuild()fallback cuối: parse từ comment positions đang mởfinal fallback: parse from open position comments
⚠ Whitelist URL trong MT5 (BẮT BUỘC)⚠ Whitelist URL in MT5 (REQUIRED) Mở Tools → Options → Expert Advisors → Allow WebRequest for listed URL và thêm origin của cả 2 URL (không cần path): Open Tools → Options → Expert Advisors → Allow WebRequest for listed URL and add origins of both URLs (no path needed):
https://gr-tmap.your-account.workers.dev
https://your-server.com
Backtest tự skip cloudBacktest auto-skips cloud WebRequest() không hoạt động trong Strategy Tester. EA check MQLInfoInteger(MQL_TESTER) và skip cloud sync để backtest không bị chậm. File local vẫn save bình thường. WebRequest() doesn't work in Strategy Tester. EA checks MQLInfoInteger(MQL_TESTER) and skips cloud sync to avoid backtest slowdown. Local file still saves normally.

Disaster recovery scenariosDisaster recovery scenarios

Panel info — dòng "Cloud Sync"Panel info — "Cloud Sync" line

Khi InpCloudSyncEnable = true, panel hiển thị status HTTP của lần sync gần nhất:

When InpCloudSyncEnable = true, panel displays last sync HTTP status:

Cloud: CF=OK | MyApi=OK         (lime — cả 2 OK / both OK)
Cloud: CF=500 | MyApi=OK        (orange — CF lỗi 500 / CF 500 error)
Cloud: CF=OK | MyApi=-1         (orange — MyApi WebRequest fail)

Setup chi tiếtDetailed setup

Xem hướng dẫn từng bước (deploy CF Worker, migrate fxconsole, set Bearer token):

See step-by-step guide (deploy CF Worker, migrate fxconsole, set Bearer token):

18. Multi-Node Leader Election

Khi chạy ≥ 2 node (cùng magic+account trên nhiều VPS/máy) để dự phòng, EA dùng cơ chế leader election theo priority + heartbeat để tránh mở lệnh trùng. Một node làm LEADER (full quyền giao dịch); các node còn lại làm FOLLOWER (chỉ đồng bộ dữ liệu, không gửi lệnh). Khi leader chết > InpCloudHeartbeatTimeoutSec, follower có priority thấp nhất tự động lên thay.

When running ≥ 2 nodes (same magic+account across multiple VPS/machines) for redundancy, the EA uses a priority + heartbeat leader-election mechanism to prevent duplicate trades. One node is the LEADER (full trading rights); the rest are FOLLOWERS (sync data only, send no orders). When the leader misses heartbeats for > InpCloudHeartbeatTimeoutSec, the surviving follower with the lowest priority takes over automatically.

Tham số inputInput parameters

ParameterMặc địnhDefaultMô tảDescription
InpCloudNodePriority100 Priority của node (số nhỏ = ưu tiên cao). Ví dụ: VPS chính = 1, VPS dự phòng = 2, máy nhà = 100. Giữa 2 node phải KHÁC giá trị nhau. Node priority (lower = higher precedence). E.g. main VPS = 1, backup VPS = 2, home PC = 100. Two nodes must use DIFFERENT values.
InpCloudNodeId"" Định danh duy nhất của node. Để trống = tự sinh từ TerminalInfoString(TERMINAL_NAME) + path. Tie-breaker khi 2 node cùng priority. Unique node identifier. Empty = auto-generated from TerminalInfoString(TERMINAL_NAME) + path. Used as tie-breaker when two nodes share the same priority.
InpCloudHeartbeatTimeoutSec90 Số giây heartbeat trễ trước khi node bị coi là chết. Khuyến nghị ≥ 3× InpCloudSyncIntervalSec để tránh false failover. Seconds without heartbeat before a node is considered dead. Recommended ≥ 3× InpCloudSyncIntervalSec to avoid false failover.

Quy tắc bầu leaderElection rules

  1. Mỗi node gửi POST /tmap/heartbeat mỗi InpCloudSyncIntervalSec giây (ghi đè last_heartbeat trên cloud).Each node sends POST /tmap/heartbeat every InpCloudSyncIntervalSec seconds (upserts last_heartbeat on cloud).
  2. Server trả về danh sách alive nodes (heartbeat trong vòng timeout) đã sort theo priority ASC, rồi node_id ASC (tie-breaker).Server returns the list of alive nodes (heartbeat within timeout) sorted by priority ASC then node_id ASC (tie-breaker).
  3. Phần tử đầu tiên = leader. Node tự nhận biết qua field is_leader trong response.First element = leader. Each node learns its role from the is_leader field in the response.
  4. Khi leader chết → mất heartbeat > timeout → bị loại khỏi alive list → follower có priority nhỏ nhất kế tiếp tự động lên leader trong chu kỳ heartbeat tiếp theo.When leader dies → heartbeat lapses > timeout → removed from alive list → next-lowest-priority follower auto-promotes on the next heartbeat cycle.
  5. Fail-safe: nếu cả heartbeat lẫn cloud đều fail (CF + MyApi đều chết) → node tự coi mình là leader để không treo giao dịch (CanTradeAsLeader() mặc định trả true khi không xác định được role).Fail-safe: if both heartbeat and cloud fail (CF + MyApi both down) → node assumes it is leader to avoid stalling trading (CanTradeAsLeader() defaults to true when role cannot be determined).

Quyền của Leader vs FollowerLeader vs Follower permissions

Hành độngAction LEADERFOLLOWER
Mở Init mới (ProcessNewBarEntries)Open new Init (ProcessNewBarEntries)
DCA Add (ProcessAddEntries)DCA Add (ProcessAddEntries)
Lot Balance (CheckLotBalance)Lot Balance (CheckLotBalance)
Flash Crash Fast BalanceFlash Crash Fast Balance
Hedging (CheckHedging)Hedging (CheckHedging)
Tia close (CheckTiaClusters)Tia close (CheckTiaClusters)
Virtual DCA TP (CheckVirtualDcaTp)Virtual DCA TP (CheckVirtualDcaTp)
Global TP / SL / SL ClearStuckGlobal TP / SL / SL ClearStuck
Save TMap lên cloudSave TMap to cloud(không ghi đè data của leader)(must not overwrite leader's data)
Save TMap file localSave TMap to local file(file riêng từng máy)(per-machine file)
Đọc TMap từ cloud (OnInit)Load TMap from cloud (OnInit)
Gửi heartbeatSend heartbeat
Hiển thị panelDisplay panel

Kịch bản failoverFailover scenarios

# Tình huốngSituation Hành viBehavior
0 Single node — chỉ 1 instance đang chạy Single node — only 1 instance running Node đó tự động là leader → giao dịch bình thường. That node is automatically leader → trades normally.
1 2 node OK — VPS chính (priority=1) + VPS dự phòng (priority=2) 2 nodes OK — main VPS (priority=1) + backup VPS (priority=2) VPS chính = LEADER (giao dịch). VPS dự phòng = FOLLOWER (đồng bộ tickets, không gửi lệnh). Main VPS = LEADER (trades). Backup VPS = FOLLOWER (syncs tickets, sends no orders).
2 VPS chính chết — heartbeat dừng Main VPS down — heartbeat stops Sau InpCloudHeartbeatTimeoutSec giây → VPS dự phòng tự động trở thành LEADER → tiếp tục manage tickets từ TMap đã đồng bộ. After InpCloudHeartbeatTimeoutSec seconds → backup VPS auto-promotes to LEADER → continues managing tickets from the synced TMap.
3 VPS chính sống lại Main VPS comes back Heartbeat resume → priority=1 < priority=2 → VPS chính lấy lại LEADER. VPS dự phòng quay về FOLLOWER. Cần test kỹ chuyển giao state để tránh open/close conflict. Heartbeat resumes → priority=1 < priority=2 → main VPS reclaims LEADER. Backup demotes to FOLLOWER. Test the handover thoroughly to avoid open/close conflicts.

Hiển thị panel — dòng "NodeRole"Panel display — "NodeRole" line

Khi InpCloudSyncEnable = true, panel hiển thị thêm dòng vai trò node:

When InpCloudSyncEnable = true, the panel shows an extra role line:

NodeRole: LEADER (P=1, alive=2)              (lime)
NodeRole: FOLLOWER (P=2, leader=<id> P=1, alive=2)   (orange)
NodeRole: LEADER (fallback, no cloud)        (yellow — heartbeat fail)

API endpointAPI endpoint

POST /tmap/heartbeat
Authorization: Bearer <TMAP_SECRET_KEY>
Content-Type: application/json

{
  "magic": "21478308",
  "account": "12345678",
  "node_id": "MT5-VPS01-abc123",
  "priority": 1,
  "timeout_sec": 90
}

→ 200 OK
{
  "ok": true,
  "is_leader": true,
  "current_leader_id": "MT5-VPS01-abc123",
  "current_leader_priority": 1,
  "alive_count": 2,
  "alive_nodes": [
    { "node_id": "MT5-VPS01-abc123", "priority": 1, "age_sec": 5 },
    { "node_id": "MT5-VPS02-xyz789", "priority": 2, "age_sec": 12 }
  ]
}

Endpoint giống nhau ở cả Cloudflare Worker và fxconsole REST API. EA gọi cả 2 song song; chỉ cần một trong hai trả về thành công là đủ để xác định role.

Endpoint is identical on both Cloudflare Worker and fxconsole REST API. The EA calls both in parallel; either returning successfully is enough to determine role.

Priority phải duy nhất giữa các nodePriority must be unique across nodes Nếu 2 node cùng priority, tie-breaker theo node_id ASC (alphabet). Khi InpCloudNodeId để trống, ID tự sinh có thể đổi giữa các lần restart → role có thể flip. Khuyến nghị luôn set cả InpCloudNodePriority lẫn InpCloudNodeId rõ ràng cho từng node. If two nodes share the same priority, tie-breaker uses node_id ASC (alphabetical). When InpCloudNodeId is empty, the auto-generated ID may change between restarts → role may flip. Recommended: always explicitly set both InpCloudNodePriority and InpCloudNodeId per node.
Khoảng cách timeout vs intervalTimeout vs interval gap Đặt InpCloudHeartbeatTimeoutSec ≥ 3× InpCloudSyncIntervalSec. Ví dụ: interval=30s → timeout=90s cho phép node mất tối đa 2 chu kỳ heartbeat (network glitch tạm thời) mà chưa bị coi là chết → tránh false failover. Set InpCloudHeartbeatTimeoutSec ≥ 3× InpCloudSyncIntervalSec. Example: interval=30s → timeout=90s allows up to 2 missed heartbeats (transient network glitch) before declaring a node dead → avoids false failover.

19. Residue Position Management

Residue = position có lot rất nhỏ (vd. 0.01 lot) sót lại sau khi Tia / ClearStuck partial close. Residue gây 3 vấn đề: (1) phá cấu trúc Gap detection (1 Buy nhỏ ở vùng giá thấp làm lowestBuy sai → gap không hình thành); (2) làm sai refBuy/refSell trong round → DCA Add bị block; (3) tích luỹ nhiều residue qua thời gian = stuck positions không bao giờ close. Module này có 3 lớp xử lý: Prevent (ngăn ở source), Auto-clean (dọn residue tồn dư), Defensive filter (loại residue khỏi tính toán structural).

Residue = position with very small lot (e.g. 0.01) left over after Tia / ClearStuck partial close. Residue causes 3 issues: (1) breaks Gap detection structure (a small Buy at low price corrupts lowestBuy → gap never forms); (2) corrupts refBuy/refSell in round → DCA Add blocked; (3) residue accumulates over time = stuck positions that never close. This module has 3 layers: Prevent (avoid creating), Auto-clean (close existing), Defensive filter (exclude from structural calculations).

Tham số inputInput parameters

ParameterMặc địnhDefaultMô tảDescription
InpResiduePreventEnabletrue Ngăn partial close tạo residue. Khi remaining sau partial < threshold → đóng FULL nếu budget cho phép, SKIP nếu không. Prevent partial close from creating residue. When remaining after partial < threshold → close FULL if budget allows, SKIP otherwise.
InpResidueAutoCleanEnabletrue Tự động đóng residue khi profit ≥ floor (chạy mỗi tick). Auto-close residue when profit ≥ floor (runs every tick).
InpResidueAutoCleanProfitFloor-2.0 Đóng residue nếu profit ≥ ngưỡng này (USD). 0 = chỉ đóng khi lời. Âm = chấp nhận lỗ nhỏ để dọn residue. Close residue if profit ≥ this floor (USD). 0 = only close profitable. Negative = accept small loss to clean residue.
InpResidueLotMultiplier1.5 Threshold = SYMBOL_VOLUME_MIN × this. Vd. minLot=0.01, mult=1.5 → threshold=0.015 → lot < 0.015 = residue. Threshold = SYMBOL_VOLUME_MIN × this. E.g. minLot=0.01, mult=1.5 → threshold=0.015 → lot < 0.015 = residue.
InpResidueFilterGapDetectiontrue Loại residue khỏi tính toán Gap (lowestBuy/highestSell, CountInitsInGap, panel display). Exclude residue from Gap calculation (lowestBuy/highestSell, CountInitsInGap, panel display).
InpResidueFilterRoundRefstrue Loại residue khỏi tính refBuy/refSell trong GetRoundInfo (cho DCA Add MinPips check). Exclude residue from refBuy/refSell calculation in GetRoundInfo (for DCA Add MinPips check).

3 lớp xử lý — chi tiết3-layer mechanism — detailed

Lớp 1 — Prevent (ngăn ở source)Layer 1 — Prevent (at source)

Áp dụng tại 3 site partial close:

Applied at 3 partial close sites:

Logic: trước khi PositionClosePartial, check remaining = curVol − volToClose. Nếu remaining < threshold:

Logic: before PositionClosePartial, check remaining = curVol − volToClose. If remaining < threshold:

Lớp 2 — Auto-clean (dọn residue tồn dư)Layer 2 — Auto-clean (residual cleanup)

CleanResiduePositions() chạy mỗi tick (sau Hedge check trong OnTick):

CleanResiduePositions() runs every tick (after Hedge check in OnTick):

for each position:
   if Hedge → skip
   if volume ≥ threshold → skip   ← không phải residue
   if profit < floor → skip       ← chưa đủ lời
   PositionClose()                ← đóng residue

Mỗi tick đóng tất cả residue đáp ứng điều kiện. Cost: O(n) scan, ~µs với 100 positions.

Closes all qualifying residue every tick. Cost: O(n) scan, ~µs for 100 positions.

Lớp 3 — Defensive filter (residue lỗ sâu chưa kịp dọn)Layer 3 — Defensive filter (residue with deep loss not yet cleaned)

Filter residue khỏi 4 vị trí structural:

Filter residue from 4 structural sites:

  1. GetRoundInfotính lowB/highB/lowS/highS cho refBuy/refSellcomputes lowB/highB/lowS/highS for refBuy/refSell
  2. CountInitsInGapđếm rounds in gap zonecounts rounds in gap zone
  3. Gap detection trongGap detection in ProcessNewBarEntries
  4. Panel "Gap" displayPanel "Gap" display

Đảm bảo residue lỗ sâu (chưa thoả điều kiện auto-clean) không phá structural analysis.

Ensures deep-loss residue (not yet eligible for auto-clean) doesn't break structural analysis.

Vì sao residue phá Gap detectionWhy residue breaks Gap detection Gap yêu cầu highestSell < lowestBuy. Một Buy 0.01 lot ở giá thấp sẽ kéo lowestBuy xuống dưới highestSell → cấu trúc gap không tồn tại → Gap Init không kích hoạt mặc dù có vùng giá trống lớn ở giữa. Gap requires highestSell < lowestBuy. A 0.01 lot Buy at low price pulls lowestBuy below highestSell → gap structure doesn't exist → Gap Init won't trigger even though there's a large empty zone.
Backward compatibilityBackward compatibility Set tất cả 4 input bool về false → behavior = trước fix (legacy). Có thể dùng để A/B test backtest. Set all 4 bool inputs to false → behavior = pre-fix (legacy). Useful for A/B backtest comparison.
Tương tác với Multi-Node Leader ElectionInteraction with Multi-Node Leader Election CleanResiduePositions() check CanTradeAsLeader() đầu hàm — chỉ leader node mới đóng residue. Follower không thực thi để tránh duplicate close. CleanResiduePositions() checks CanTradeAsLeader() at function start — only leader node closes residue. Followers skip to avoid duplicate closes.

Khi nào tắt từng phầnWhen to disable each part

TắtDisable Khi nàoWhen
InpResiduePreventEnable = false Muốn giữ legacy partial close behavior. Tia có thể tạo residue nhưng auto-clean sẽ dọn. Want legacy partial close behavior. Tia may create residue but auto-clean handles it.
InpResidueAutoCleanEnable = false Không muốn EA tự đóng position nhỏ. Residue tồn tại nhưng vẫn được filter ở structural sites. Don't want EA to auto-close small positions. Residue persists but is filtered at structural sites.
InpResidueFilterRoundRefs = false Muốn refBuy/refSell vẫn dùng residue (legacy). Có thể block Add khi residue ở extreme. Want refBuy/refSell to include residue (legacy). May block Add when residue at extreme.

20. Info Panel

Panel thông tin hiển thị trên chart thời gian thực. Bố cục 3 cột: trái · giữa · phải. 5 dòng chính + nhiều dòng debug/status tùy chọn (FlashCrash, Daily Limit, TMap, Gap, Cloud, NodeRole).

Real-time info panel on chart. 3-column layout: left · center · right. 5 main rows + multiple optional debug/status rows (FlashCrash, Daily Limit, TMap, Gap, Cloud, NodeRole).

Buy: 3        0.15 lot              12.30 $
Sell: 2        0.10 lot              -4.50 $
DCAPos max: 3    Net: 0.05 lot     DCANeg max: 2
Profit: 7.80 $       Eq: 100453.80 $    Bal: 100445.83 $
Trend: UP        AutoBal: ON       Sideway: NO (BW=0.0039)
Pivot[Cam/COOP]: BOTH | PP=4619.26
Wick[PERIOD_M30+PERIOD_H1]: BOTH ❌
Whip: [BYPASS] ADX=32.2(strong) NP=10 HTF↑✗ [BLK: HTF-MISS ]
Daily Limit: TP=$200 | SL=$500
TMap: 5 entries | 1 rounds | B:3 S:2
Gap: 12 pip | LowB=2345.67 HiS=2344.45 | InGap=1/2
Cloud: CF=OK | MyApi=OK
Node: MT5-VPS01-abc123 (pri=1) | LEADER | Alive=2

Minh họa panel — 3 cột trái / giữa / phải. AutoBal ở giữa dòng Trend. Các dòng TMap / Gap / Cloud / NodeRole là debug/status tùy chọn.

Panel demo — 3-column left / center / right. AutoBal at the center of the Trend row. TMap / Gap / Cloud / NodeRole rows are optional debug/status lines.

Bố cục dòngRow layout

DòngRow TráiLeft GiữaCenter PhảiRight
1 Buy: <N>Buy: <N> X.XX lotX.XX lot X.XX $X.XX $
2 Sell: <N>Sell: <N> X.XX lotX.XX lot X.XX $X.XX $
3 DCAPos max: NDCAPos max: N Net: X.XX lotNet: X.XX lot DCANeg max: NDCANeg max: N
4 Profit: X.XX $Profit: X.XX $ Eq: X.XX $Eq: X.XX $ Bal: X.XX $Bal: X.XX $
5 Trend: UP/DOWN/neutral *Trend: UP/DOWN/neutral * AutoBal: ON / ACT / WAIT / LOSS / OFF AutoBal: ON / ACT / WAIT / LOSS / OFF Sideway: YES/NO (BW=…) *Sideway: YES/NO (BW=…) *
5b* Pivot[<method>/<mode>]: SUPP/RES/BOTH/- | PP=<price> — chỉ khi InpPivotFilterEnable = true. Method có prefix auto→ khi InpPivotMethod=4. Lime khi giá gần ít nhất 1 level, Silver khi xa tất cả. Pivot[<method>/<mode>]: SUPP/RES/BOTH/- | PP=<price> — only when InpPivotFilterEnable = true. Method has auto→ prefix when InpPivotMethod=4. Lime when price near at least one level, Silver when far from all.
5c* Wick[<TF1>+<TF2>]: clean ✓ / UP (block Buy) / DN (block Sell) / BOTH ❌ — chỉ khi InpWickFilterEnable = true. Lime = clean (cả 2 side OK), OrangeRed = có rejection. v1.24+. Wick[<TF1>+<TF2>]: clean ✓ / UP (block Buy) / DN (block Sell) / BOTH ❌ — only when InpWickFilterEnable = true. Lime = clean (both sides OK), OrangeRed = rejection active. v1.24+.
6* FlashCrash: OFF / ACT Ns | Net X.XX (khi bật) FlashCrash: OFF / ACT Ns | Net X.XX (when enabled)
7* Daily Limit: TP=$N | SL=$N (khi bật) Daily Limit: TP=$N | SL=$N (when enabled)
8 TMap: <N> entries | <R> rounds | B:<N> S:<N> — luôn hiện. Bạc khi có entry, xám khi map rỗng. TMap: <N> entries | <R> rounds | B:<N> S:<N> — always shown. Silver when map has entries, gray when empty.
9* Gap: <P> pip | LowB=<price> HiS=<price> | InGap=<n>/<max> — chỉ khi InpSingleRoundMode = trueInpSingleRoundGapInits > 0. Vàng khi gap đủ lớn để nhận GapInit, xám nếu chưa. Gap: <P> pip | LowB=<price> HiS=<price> | InGap=<n>/<max> — only when InpSingleRoundMode = true and InpSingleRoundGapInits > 0. Yellow when gap is large enough to allow a GapInit, gray otherwise.
10* Cloud: CF=<status> | MyApi=<status> — chỉ khi InpCloudSyncEnable = true. Lime khi cả 2 OK; OrangeRed khi có lỗi (HTTP code hoặc -1 = WebRequest fail). Cloud: CF=<status> | MyApi=<status> — only when InpCloudSyncEnable = true. Lime when both OK; OrangeRed on error (HTTP code or -1 = WebRequest fail).
11* Node: <id> (pri=<P>) | LEADER/FOLLOWER | … — chỉ khi InpCloudSyncEnable = true. Lime = LEADER, Gray = FOLLOWER, Silver = INITIALIZING. Node: <id> (pri=<P>) | LEADER/FOLLOWER | … — only when InpCloudSyncEnable = true. Lime = LEADER, Gray = FOLLOWER, Silver = INITIALIZING.

* Trend và Sideway chỉ hiện khi bật tính năng tương ứng. Cột giữa dòng 5 luôn hiển thị AutoBal (phụ thuộc vào InpLotBalanceEnable). Dòng 5b (Pivot) chỉ khi InpPivotFilterEnable = true. Dòng 5c (Wick) chỉ khi InpWickFilterEnable = true. Dòng 6 (FlashCrash) chỉ hiện khi InpFlashCrashProtectionEnable = true; dòng 7 (Daily Limit) khi InpDailyLimitEnable = true hoặc đã đạt limit. Dòng 8 (TMap) luôn hiện. Dòng 9 (Gap) chỉ khi SingleRoundMode + GapInits. Dòng 10–11 (Cloud + NodeRole) chỉ khi InpCloudSyncEnable = true. Background panel tự auto-resize theo số dòng đang hiện.

* Trend and Sideway only show when their feature is enabled. Row 5 center always shows AutoBal (depends on InpLotBalanceEnable). Row 5b (Pivot) only when InpPivotFilterEnable = true. Row 5c (Wick) only when InpWickFilterEnable = true. Row 6 (FlashCrash) only when InpFlashCrashProtectionEnable = true; row 7 (Daily Limit) when InpDailyLimitEnable = true or limit is reached. Row 8 (TMap) always shows. Row 9 (Gap) only when SingleRoundMode + GapInits. Rows 10–11 (Cloud + NodeRole) only when InpCloudSyncEnable = true. Panel background auto-resizes to fit visible rows.

Dòng debug/status — chi tiết hiển thịDebug / status rows — display details

DòngRow FormatFormat TrườngFields Khi nào hiệnVisibility
Pivot Pivot[<method>/<mode>]: <near> | PP=<price> method: Cls / Fib / Cam / Wood (manual); prefix auto→ khi InpPivotMethod=4
mode: COOP (AND với filter khác) hoặc INDEP (bypass tất cả)
near: SUPP / RES / BOTH / - — vị trí giá so với pivot levels
PP: giá trị Pivot Point hiện tại
method: Cls / Fib / Cam / Wood (manual); auto→ prefix when InpPivotMethod=4
mode: COOP (AND with other filters) or INDEP (bypass all)
near: SUPP / RES / BOTH / - — price location vs pivot levels
PP: current Pivot Point value
InpPivotFilterEnable = true. Lime khi giá gần ≥1 level (trade được); Silver khi xa tất cả (filter chặn). InpPivotFilterEnable = true. Lime when price near ≥1 level (trade allowed); Silver when far from all (filter blocks).
TMap TMap: <N> entries | <R> rounds | B:<N> S:<N> entries: số ticket trong map
rounds: số roundId duy nhất
B / S: số ticket Buy / Sell trong map
entries: total tickets in map
rounds: distinct roundId count
B / S: Buy / Sell tickets in map
Luôn hiện. Bạc khi có entry, xám khi rỗng. Always. Silver when populated, gray when empty.
Gap Gap: <P> pip | LowB=<price> HiS=<price> | InGap=<n>/<max> P: pip giữa Buy thấp nhất và Sell cao nhất (0 nếu Buy ≤ Sell)
LowB / HiS: giá Buy thấp nhất / Sell cao nhất
n / max: số GapInit đã mở / InpSingleRoundGapInits
P: pip between lowest Buy and highest Sell (0 if Buy ≤ Sell)
LowB / HiS: lowest Buy / highest Sell open prices
n / max: GapInits already opened / InpSingleRoundGapInits
InpSingleRoundMode = true && InpSingleRoundGapInits > 0. Vàng khi P > InpDCAPosMinPips && P ≤ InpSingleRoundGapMaxPips; xám nếu không. InpSingleRoundMode = true && InpSingleRoundGapInits > 0. Yellow when P > InpDCAPosMinPips && P ≤ InpSingleRoundGapMaxPips; gray otherwise.
Cloud Cloud: CF=<status> | MyApi=<status> OK: HTTP 2xx
-: chưa gọi (URL trống hoặc backtest)
-1: WebRequest fail (URL chưa whitelist?)
401 / 500 / …: HTTP error code
OK: HTTP 2xx
-: not called yet (empty URL or backtest)
-1: WebRequest fail (URL not whitelisted?)
401 / 500 / …: HTTP error code
InpCloudSyncEnable = true. Lime khi cả 2 OK / không cấu hình; OrangeRed khi có lỗi. InpCloudSyncEnable = true. Lime when both OK / not configured; OrangeRed on any error.
NodeRole Node: <id> (pri=<P>) | LEADER | Alive=<N>
Node: <id> (pri=<P>) | FOLLOWER | Leader=<id> pri=<P> | Alive=<N>
Node: <id> (pri=<P>) | INITIALIZING...
id: InpCloudNodeId hoặc auto
pri: InpCloudNodePriority
Alive: tổng node đang sống (heartbeat trong timeout)
Leader=… pri=…: thông tin leader hiện tại (chỉ FOLLOWER)
id: InpCloudNodeId or auto
pri: InpCloudNodePriority
Alive: total live nodes (heartbeat within timeout)
Leader=… pri=…: current leader info (FOLLOWER only)
InpCloudSyncEnable = true. Lime = LEADER, Gray = FOLLOWER, Silver = INITIALIZING (chưa nhận heartbeat đầu tiên). InpCloudSyncEnable = true. Lime = LEADER, Gray = FOLLOWER, Silver = INITIALIZING (no first heartbeat yet).
Trend Trend: UP / DOWN / neutral UP (xanh) = giá > trend-EMA + neutral · DOWN (đỏ) = giá < EMA − neutral · neutral (xám) = trong vùng neutral. Đây là GetTrendDirection() — dùng để chặn Init/Add ngược trend. UP (green) = price > trend-EMA + neutral · DOWN (red) = price < EMA − neutral · neutral (gray) = inside neutral band. This is GetTrendDirection() — used to block counter-trend Init/Add. InpTrendFilterEnable = true InpTrendFilterEnable = true
AutoBal AutoBal: OFF / ON / ACT / WAIT / LOSS / DONE OFF (xám) = LotBalance tắt · Normal mode: ON = standby, ACT = đang cân bias về phía yếu · LossTriggered mode: WAIT = chưa đủ lỗ trigger, LOSS (cam) = đang cân, DONE = đã đạt Target. OFF (gray) = LotBalance disabled · Normal mode: ON = standby, ACT = actively biasing toward the weak side · LossTriggered mode: WAIT = loss trigger not reached, LOSS (orange) = balancing, DONE = Target reached. Luôn hiện (cột giữa dòng 5); nội dung theo InpLotBalanceEnable + InpLotBalanceMode. Always shown (row 5 center); content depends on InpLotBalanceEnable + InpLotBalanceMode.
Sideway Sideway: YES / NO (BW=X.XXXX) YES (cam) = đang sideway (Bollinger bandwidth ≤ ngưỡng) → chặn Init/Add · NO (bạc) = không · BW = bandwidth hiện tại. YES (orange) = ranging (Bollinger bandwidth ≤ threshold) → blocks Init/Add · NO (silver) = not · BW = current bandwidth. InpSidewayFilterEnable = true InpSidewayFilterEnable = true
Wick Wick[<TF1>+<TF2>]: <state> clean ✓ (lime) = không reject, vào lệnh được · UP (block Buy) = râu TRÊN reject → chặn Buy · DN (block Sell) = râu DƯỚI reject → chặn Sell · BOTH ❌ (đỏ) = cả 2 → chặn cả Buy lẫn Sell. TF1/TF2 = 2 khung kiểm (AND logic). clean ✓ (lime) = no rejection, entries allowed · UP (block Buy) = UPPER wick rejection → blocks Buy · DN (block Sell) = LOWER wick rejection → blocks Sell · BOTH ❌ (red) = both → blocks Buy and Sell. TF1/TF2 = the two checked TFs (AND). InpWickFilterEnable = true InpWickFilterEnable = true
Whip
(obj: Choppy)
Whip: [group] ADX=X.X(regime) NP=N HTF<dir><✓/✗> [BLK: …] [group] (chỉ khi InpChoppyDefenseGroupEnable): [BYPASS] = account khoẻ, 5 defense TẮT (aggressive) · [ACTIVE ord=X loss=$Y lotDiff=Z] = có trigger, defense BẬT.
ADX=X.X(regime): strong (≥ ADXStrong) / mid (≥ ADXWeak) / chop.
NP=N: NeutralPips hiệu dụng (adaptive theo ADX; = static InpTrendFilterNeutralPips khi defense bypass).
HTF↑/↓/=: hướng Higher-TF (Multi-TF confirm) + khớp / lệch primary.
[BLK: …]: block đang bật — CHOP (ADX chop) · AW<m>m (Anti-Whipsaw còn m phút) · DD (Dual-Dir) · HTF-MISS (Multi-TF lệch). Màu ĐỎ = có block toàn cục (CHOP/AW/DD); CAM = chỉ HTF-MISS.
[group] (only if InpChoppyDefenseGroupEnable): [BYPASS] = account healthy, all 5 defenses OFF (aggressive) · [ACTIVE ord=X loss=$Y lotDiff=Z] = a trigger fired, defenses ON.
ADX=X.X(regime): strong (≥ ADXStrong) / mid (≥ ADXWeak) / chop.
NP=N: effective NeutralPips (adaptive by ADX; = static InpTrendFilterNeutralPips when defenses bypassed).
HTF↑/↓/=: Higher-TF (Multi-TF) direction + agrees / disagrees with primary.
[BLK: …]: active blocks — CHOP (ADX chop) · AW<m>m (Anti-Whipsaw, m min left) · DD (Dual-Dir) · HTF-MISS (Multi-TF mismatch). RED = a global block (CHOP/AW/DD); ORANGE = HTF-MISS only.
InpChoppyFilterEnable / InpTrendAdaptive / InpMultiTfTrendEnable. ⚠️ Khi [BYPASS]: [BLK: HTF-MISS] chỉ HIỂN THỊ, KHÔNG enforced (defense đang tắt → HTF check trả "agree"). InpChoppyFilterEnable / InpTrendAdaptive / InpMultiTfTrendEnable. ⚠️ When [BYPASS]: [BLK: HTF-MISS] is DISPLAY-ONLY, NOT enforced (defenses off → the HTF check returns "agree").
FlashCrash FlashCrash: OFF / ACT Ns | Net X.XX OFF (bạc) = bình thường · ACT Ns (đỏ) = phát hiện flash-crash, còn N giây cooldown; Net = net lot (Buy−Sell) hiện tại. OFF (silver) = normal · ACT Ns (red) = flash crash detected, N seconds of cooldown left; Net = current net lot (Buy−Sell). InpFlashCrashEnable = true InpFlashCrashEnable = true
DailyLimit Daily Limit: P>=X / L<=-Y $ | REACHED P>=X / L<=-Y $ (bạc) = ngưỡng đang theo dõi · REACHED (no new trades) (cam) = đã đạt limit ngày → ngừng mở lệnh mới. P>=X / L<=-Y $ (silver) = thresholds being tracked · REACHED (no new trades) (orange) = daily limit hit → no new entries. InpDailyLimitEnable = true hoặc đã đạt limit InpDailyLimitEnable = true or limit reached
TiaRescue TiaRescue: STBY / ACT | Loss=$X … | Target=$Z STBY (bạc) = lỗ nổi chưa chạm InpTiaHighTargetLossUSD → Tia đóng cụm ở target thường (InpTiaProfitUSD); hiện "Need $Z more" · ACT (đỏ) = lỗ ≥ ngưỡng → chuyển sang target LỚN InpTiaProfitWhenLossUSD ($Z): giữ, chờ cụm net lớn (rescue) thay vì nibble. STBY (silver) = floating loss below InpTiaHighTargetLossUSD → Tia closes clusters at the normal target (InpTiaProfitUSD); shows "Need $Z more" · ACT (red) = loss ≥ threshold → switches to the HIGH target InpTiaProfitWhenLossUSD ($Z): holds and waits for a large net (rescue) instead of nibbling. InpTiaProfitWhenLossEnable = true & InpTiaHighTargetLossUSD > 0 InpTiaProfitWhenLossEnable = true & InpTiaHighTargetLossUSD > 0

AutoBal — Trạng thái Lot Balance— Lot Balance status

Hiển thịDisplay MàuColor Ý nghĩaMeaning
AutoBal: OFF XámGray InpLotBalanceEnable = false InpLotBalanceEnable = false
AutoBal: ON TrắngWhite Normal mode — bật, đang chờ |Buy−Sell| > Trigger (dễ đọc) Normal mode — enabled, waiting for |Buy−Sell| > Trigger (readable)
AutoBal: ACT Xanh lá vàngYellowGreen Normal mode — bias cân bằng đang hoạt động (g_balanceModeActive = true) Normal mode — balance bias is actively firing (g_balanceModeActive = true)
AutoBal: WAIT BạcSilver LossTriggered mode — đang chờ profit nổi ≤ −$InpLotBalanceLossTriggerUSD LossTriggered mode — waiting for floating profit ≤ −$InpLotBalanceLossTriggerUSD
AutoBal: LOSS CamOrange LossTriggered mode — đã đạt ngưỡng lỗ, bias đang chạy (cân về phía yếu). Trigger threshold bị bỏ qua — kích hoạt ngay khi có bất kỳ chênh lệch nào. LossTriggered mode — loss threshold reached, bias is actively rebalancing. Trigger threshold bypassed — activates immediately on any imbalance.
AutoBal: DONE Xanh lá vàngYellowGreen LossTriggered mode — loss vẫn đang active nhưng |net| đã về ≤ Target → bias dừng lại (dễ đọc) LossTriggered mode — loss still active but |net| reached Target → bias stopped (readable)
LossTriggered: Trigger threshold bị bỏ qua khi loss activeLossTriggered: Trigger threshold bypassed when loss is active Trong Normal mode, balance chỉ kích hoạt khi |Buy−Sell| > InpLotBalanceTrigger. Trong LossTriggered mode khi đã vượt ngưỡng lỗ, threshold này bị bỏ qua — balance bắt đầu bias ngay với bất kỳ chênh lệch nào và tiếp tục cho đến khi |net| ≤ InpLotBalanceTarget. Nên đặt InpLotBalanceTarget đủ thấp (ví dụ 0.3) để cân bằng hiệu quả. In Normal mode, balance only activates when |Buy−Sell| > InpLotBalanceTrigger. In LossTriggered mode once the loss threshold is exceeded, this trigger is bypassed — balance starts biasing immediately on any imbalance and continues until |net| ≤ InpLotBalanceTarget. Set InpLotBalanceTarget low enough (e.g. 0.3) for effective rebalancing.

Màu sắc panelPanel colors

MàuColor Áp dụng choApplied to
■ Xanh dươngBuy, Trend UPBuy, Trend UP
■ Cam đỏSell, Trend DOWNSell, Trend DOWN
■ VàngNet lot trung tính (Buy≈Sell)Net lot neutral (Buy≈Sell)
■ Xanh lá vàng (YellowGreen)AutoBal ACT, AutoBal DONE — mặc định dễ đọcAutoBal ACT, AutoBal DONE — default readable
■ Trắng (AutoBal standby)AutoBal ON (Normal chờ) — mặc định dễ đọcAutoBal ON (Normal standby) — default readable
■ Xanh lá sángProfit dươngPositive profit
■ Cam vàngSideway YES, Daily Limit REACHED, AutoBal LOSSSideway YES, Daily Limit REACHED, AutoBal LOSS
■ BạcSideway NO (bình thường), AutoBal WAITSideway NO (normal), AutoBal WAIT
■ XámAutoBal OFF, TMap rỗng, NodeRole FOLLOWERAutoBal OFF, TMap empty, NodeRole FOLLOWER
■ TrắngBalance tài khoản, EquityAccount balance, Equity
■ LimeCloud OK (cả CF + MyApi), NodeRole LEADERCloud OK (both CF + MyApi), NodeRole LEADER
■ OrangeRedCloud lỗi (HTTP error hoặc WebRequest fail)Cloud error (HTTP error or WebRequest fail)
Parameter Mặc địnhDefault Mô tảDescription
InpPanelRefreshSec1 Tần suất cập nhật panel (giây).Panel refresh interval (seconds).
InpPanelX / InpPanelY12 / 25 Vị trí panel trên chart (pixel từ góc trái-trên). Panel position on chart (pixels from top-left).
InpPanelBackgroundtrue Hiển thị nền mờ phía sau text.Show background behind panel text.
InpPanelBgColorclrBlack Màu nền panel.Panel background color.
InpPanelBgWidth / InpPanelBgHeight240 / 78 Kích thước nền panel (pixel). Tăng Height nếu thêm dòng. Panel background size (px). Increase Height if rows are added.
InpPanelColorBuy / InpPanelColorSellDodgerBlue / OrangeRed Màu text dòng Buy / Sell.Buy / Sell row text colors.
InpPanelColorNetLotYellow Màu text Net lot khi cân bằng.Net lot text color when balanced.
InpPanelColorDCAMaxSilver Màu text DCAPos max / DCANeg max.DCAPos max / DCANeg max text color.
InpPanelColorProfitLime Màu text Profit (profit dương).Profit text color (positive).
InpPanelColorBalanceWhite Màu text Equity / Balance.Equity / Balance text color.
InpPanelColorAutoBalActiveYellowGreen Màu text AutoBal ACT (bias đang chạy) và AutoBal DONE (đã đạt target). Mặc định dễ đọc trên nền tối.AutoBal ACT and DONE text color. Default tuned for readability on dark background.
InpPanelColorAutoBalStandbyWhite Màu text AutoBal ON (chế độ Normal, đang chờ). Mặc định trắng thay xanh dương để dễ đọc.AutoBal ON (Normal standby) text color. Default white for better readability than blue.

20b. Panel — 3 dòng Filter Status (Pivot / Wick / Whip)Panel — 3 Filter Status lines (Pivot / Wick / Whip)

Ba dòng này cho biết vì sao EA đang / KHÔNG vào lệnh ngay lúc này. Đọc chung 3 dòng để biết filter nào đang chặn.

These three lines tell you why the EA is / is not entering right now. Read them together to see which filter is blocking.

Pivot[Cam/COOP]: BOTH | PP=4619.26
Wick[PERIOD_M30+PERIOD_H1]: BOTH ❌
Whip: [BYPASS] ADX=32.2(strong) NP=10 HTF↑✗ [BLK: HTF-MISS ]

Ví dụ thật: Pivot gần cả 2 bên · Wick chặn cả Buy lẫn Sell · Whip đang bypass (defense tắt) nhưng báo HTF lệch.

Live example: Pivot near both sides · Wick blocking both Buy and Sell · Whip bypassed (defenses off) but flags an HTF mismatch.

1) Pivot[<method>/<mode>]: <near> | PP=<price>

Chỉ hiện khi InpPivotFilterEnable = true.

Only shown when InpPivotFilterEnable = true.

TokenGiá trịValuesÝ nghĩaMeaning
methodCam / Fib / Wood / Cls (+auto→) Cách tính pivot: Camarilla / Fibonacci / Woodie / Classic. Prefix auto→ khi InpPivotMethod=Auto. Pivot method: Camarilla / Fibonacci / Woodie / Classic. auto→ prefix when InpPivotMethod=Auto.
modeCOOP / INDEP COOP = AND với Trend/Sideway/S-R · INDEP = độc lập, bypass các filter đó. COOP = AND with Trend/Sideway/S-R · INDEP = independent, bypasses those filters.
nearBOTH / SUPP / RES / - Vị trí giá vs pivot: gần cả support+resistance / chỉ support / chỉ resistance / không gần. Price vs pivot: near both support+resistance / support only / resistance only / not near.
PP4619.26 Giá Pivot Point hiện tại.Current Pivot Point price.
MàuColorlime / silver lime = giá gần ≥1 level (được xét vào lệnh) · silver = xa tất cả level. lime = price near ≥1 level (entry considered) · silver = far from all levels.

2) Wick[<TF1>+<TF2>]: <state>

Chỉ hiện khi InpWickFilterEnable = true. TF1/TF2 = 2 khung kiểm râu nến (AND logic).

Only shown when InpWickFilterEnable = true. TF1/TF2 = the two wick-check timeframes (AND logic).

Trạng tháiStateMàuColorÝ nghĩaMeaning
clean ✓lime Không có râu reject → vào lệnh được cả 2 chiều. No wick rejection → entries allowed both sides.
UP (block Buy)orangered Râu TRÊN reject → chặn Buy (vẫn cho Sell). UPPER wick rejection → blocks Buy (Sell still allowed).
DN (block Sell)orangered Râu DƯỚI reject → chặn Sell (vẫn cho Buy). LOWER wick rejection → blocks Sell (Buy still allowed).
BOTH ❌red Cả 2 râu reject → chặn CẢ Buy lẫn Sell. Both wicks reject → blocks BOTH Buy and Sell.

3) Whip: [group] ADX=X.X(regime) NP=N HTF<dir><✓/✗> [BLK: …]

Trạng thái Choppy Defense Group (gộp 5 filter chống whipsaw). Hiện khi bật InpChoppyFilterEnable / InpTrendAdaptive / InpMultiTfTrendEnable.

Choppy Defense Group status (the 5 whipsaw-defense filters combined). Shown when InpChoppyFilterEnable / InpTrendAdaptive / InpMultiTfTrendEnable is on.

TokenGiá trịValuesÝ nghĩaMeaning
[group][BYPASS] / [ACTIVE ord=X loss=$Y lotDiff=Z] [BYPASS] = account khoẻ (chưa chạm trigger) → 5 defense TẮT, trade aggressive · [ACTIVE …] = có trigger (orders/loss/lotDiff) → defense BẬT. Chỉ hiện khi InpChoppyDefenseGroupEnable=true. [BYPASS] = account healthy (no trigger) → all 5 defenses OFF, aggressive · [ACTIVE …] = a trigger fired (orders/loss/lotDiff) → defenses ON. Only when InpChoppyDefenseGroupEnable=true.
ADX=X.X(regime)strong / mid / chop ADX + regime: strong (≥ ADXStrong) / mid (≥ ADXWeak) / chop (< ADXWeak). ADX + regime: strong (≥ ADXStrong) / mid (≥ ADXWeak) / chop (< ADXWeak).
NP=N5 / 20 / 50 / static NeutralPips hiệu dụng (adaptive theo ADX). = static InpTrendFilterNeutralPips khi defense bypass. Effective NeutralPips (adaptive by ADX). = static InpTrendFilterNeutralPips when defenses bypassed.
HTF↑/↓/= ✓/✗HTF↑✓ / HTF↑✗ / … Hướng Higher-TF (Multi-TF confirm): ↑ lên / ↓ xuống / = neutral. = khớp hướng primary · = lệch. Higher-TF (Multi-TF) direction: ↑ up / ↓ down / = neutral. = agrees with primary · = disagrees.
[BLK: …]CHOP · AW<m>m · DD · HTF-MISS Block đang bật: CHOP (ADX chop) · AW<m>m (Anti-Whipsaw còn m phút) · DD (Dual-Dir) · HTF-MISS (Multi-TF lệch). Màu ĐỎ = block toàn cục (CHOP/AW/DD); CAM = chỉ HTF-MISS. Active blocks: CHOP (ADX chop) · AW<m>m (Anti-Whipsaw, m min left) · DD (Dual-Dir) · HTF-MISS (Multi-TF mismatch). RED = global block (CHOP/AW/DD); ORANGE = HTF-MISS only.

⚠️ Lưu ý: khi [BYPASS], dòng [BLK: HTF-MISS] chỉ là hiển thị cảnh báo — KHÔNG thực sự chặn init (defense đang tắt → hàm check HTF trả "agree"). Chỉ enforced khi [ACTIVE].

⚠️ Note: during [BYPASS], [BLK: HTF-MISS] is a display warning only — it does NOT actually block init (defenses off → the HTF check returns "agree"). Enforced only under [ACTIVE].

Đọc chung 3 dòng → EA có vào lệnh không?Reading all 3 together → will the EA enter?

Init bị chặn nếu bất kỳ filter nào chặn: Pivot (giá xa hết level khi COOP) · Wick (UP/DN/BOTH) · Whip có [BLK: CHOP/AW/DD] (khi ACTIVE). Ví dụ ảnh trên: Wick BOTH ❌ đang chặn cả 2 chiều → EA chưa vào lệnh, dù Whip đang bypass và HTF-MISS chỉ là cảnh báo.

Init is blocked if any filter blocks: Pivot (price far from all levels in COOP) · Wick (UP/DN/BOTH) · Whip with [BLK: CHOP/AW/DD] (when ACTIVE). In the example above: Wick BOTH ❌ is blocking both sides → the EA won't enter, even though Whip is bypassed and HTF-MISS is only a warning.

21. Thẻ comment lệnhOrder Comment Tags

Mỗi lệnh có comment theo format: Init R{roundId} P|… / N|…, DCAPos R{roundId} B#…, DCANeg R{roundId} S#…, v.v. Chữ P / N sau số round trên lệnh Init = chân theo trend / ngược trend. Có thể đọc comment để biết round và nhánh DCA.

Comments follow patterns like Init R{roundId} P|… / N|…, DCAPos R{roundId} B#…, DCANeg R{roundId} S#…, etc. P / N right after the round number on Init = with-trend / counter-trend leg. Use comments to identify round and DCA branch.

TagÝ nghĩaMeaning
Init R… P / NCặp mở đầu round: cùng R, một lệnh P (DCAPos lot/TP) và một N (DCANeg lot/TP) theo trend tại Init.Round openers: same R, one P (DCAPos lot/TP) and one N (DCANeg lot/TP) from trend at Init.
|init…Hậu tố ngữ cảnh: |init_flat, |init_sr, |init_minpips, … (đi kèm sau P/N)Context suffix: |init_flat, |init_sr, |init_minpips, … (after P/N)
|init_flatInit khi không còn lệnh (flat)Init when no positions (flat)
|init_norefInit khi không có ref round trước (noref)Init when no prior round ref (noref)
|init_fallbackInit fallback: đã N nến M1 không Init (filter chặn) → cho phép InitInit fallback: N M1 bars without Init (filters blocking) → allow Init
|init_minpipsInit khi giá đủ xa ref (MinPips)Init when price far enough from ref (MinPips)
|init_srInit tại vùng S/R (bỏ qua MinPips)Init at S/R zone (MinPips bypassed)
|init_pivotInit tại vùng pivot point (PP / S1-3 / R1-3) — chỉ tag khi pivot là trigger độc lập (không gần S/R). v1.19+.Init at pivot zone (PP / S1-3 / R1-3) — tagged only when pivot is the standalone trigger (not near S/R). v1.19+.
|init_strongInit khi StrongMove + volatilityInit on StrongMove + volatility
|add_minpipsAdd bằng khoảng cách MinPipsAdd by MinPips distance
|add_srAdd tại vùng S/R (bỏ qua MinPips)Add at S/R zone (MinPips bypassed)
|strong_moveInit khi phát hiện StrongMoveInit triggered by StrongMove
|balance_biasAdd thiên lệch về phía yếu (Lot Balance)Add biased to weaker side (Lot Balance)
|balance_overmaxAdd vượt MaxTrades vì Lot BalanceAdd exceeds MaxTrades for Lot Balance
HedgeLệnh hedge ngược chiềuCounter-direction hedge order
Weekend BalanceLệnh cân bằng tự động thứ 6Auto-balance order on Friday
AutoBal Direct |balance_directLệnh balance trực tiếp khi AutoBalance ACT (không qua DCA Add)Direct balance order when AutoBalance ACT (bypasses DCA Add)
FlashCrash Balance |balance_flashLệnh Fast Balance khi Flash Crash activeFast Balance order during Flash Crash active

22. File Config Gợi ýPreset Config Files

Stable GoldenRobber-SR_M15-H4-SidewayM1BalanceDailyLimit.set

Config chuẩn — Sideway Filter M1 (ATR-normalized), SR M15/H4, Trend Filter H4. Phù hợp cho trading ổn định hàng ngày.

Standard config — Sideway Filter M1 (ATR-normalized), SR M15/H4, Trend Filter H4. Suitable for stable daily trading.

  • Sideway: Bollinger M1, InpSidewayATRNormalize=true, ngưỡng 3.10
  • SR: M15, Confluence H4, MinScore=4
  • SR: M15, Confluence H4, MinScore=4
  • Trend Filter: H4 EMA50, chặn cả Init và Add
  • Trend Filter: H4 EMA50, blocks Init and Add
  • GlobalTP: $70, Tia: $5, InpTiaBotDCAMinSide=2

New ★ GoldenRobber-SR_M15-H4-Optimized-v1.set

Config đề xuất sử dụng. Tối ưu cả tốc độ chốt lời lẫn kiểm soát rủi ro: Tia nhanh (1+1), DCA khoảng cách nhỏ, giới hạn Init, zone control, và AutoBalance LossTriggered để phòng thủ flash crash.

Recommended config. Optimized for both profit frequency and risk control: fast Tia (1+1), tight DCA spacing, Init throttling, zone control, and AutoBalance LossTriggered for flash crash defense.

  • 🔵 Tia:🔵 Tia: InpTiaBotDCAMinSide=1 (fast 1+1), InpTiaPartialCloseEnable=false
  • 🔵 DCA (khoảng cách ngắn, đóng nhanh):🔵 DCA (tight spacing, fast close): InpDCAPosMinPips=27, InpDCAPosMultiplier=1.5, MaxTrades Pos=68 / Neg=53, InpAddCooldownSec=0
  • 🟠 Init control:🟠 Init control: InpInitCooldownSec=180, InpStrongMoveMultiplier=1.5
  • 🟠 Zone control:🟠 Zone control: InpPriceZonePips=80, InpMaxOrdersInPriceZone=2, InpSRGateAdd=true
  • 🛡️ Flash crash defense:🛡️ Flash crash defense: InpLotBalanceMode=LossTriggered, InpLotBalanceLossTriggerUSD=2000, InpLotBalanceBypassMaxTrades=true
  • Filters: SR M15/H4, Sideway M1 ATR-normalized, Trend H4 EMA50 (chặn cả Init + Add) Filters: SR M15/H4, Sideway M1 ATR-normalized, Trend H4 EMA50 (blocks Init + Add)

Alt GoldenRobber-SR_M15-H4-BotDCAStyle-v1.set

Tập trung vào Tia nhanh và DCA khoảng cách ngắn — chưa có zone/Init control. Phù hợp để so sánh ảnh hưởng của zone control.

Focuses on fast Tia and tight DCA spacing — without zone/Init throttling. Useful for comparing zone control impact.

  • InpTiaBotDCAMinSide=1, InpTiaPartialCloseEnable=false
  • InpDCAPosMinPips=27, InpDCANegMinPips=34, InpAddCooldownSec=0

Alt GoldenRobber-SR_M15-H4-SidewayM1-v2-LessTrade.set

Tập trung giảm tần suất Init và kiểm soát zone — chưa có Tia fast (MinSide=2) và DCA khoảng cách ngắn. Phù hợp để so sánh ảnh hưởng của DCA spacing.

Focuses on reduced Init frequency and zone control — without fast Tia (MinSide=2) and tight DCA spacing. Useful for comparing DCA spacing impact.

  • InpInitCooldownSec=180, InpStrongMoveMultiplier=1.5
  • InpPriceZonePips=80, InpMaxOrdersInPriceZone=2, InpSRGateAdd=true

Base GoldenRobber-M15-H4-BalancedRF.set

Config cân bằng Recovery Factor cao, drawdown thấp. Phù hợp cho trading ổn định dài hạn. Không dùng SR filter hay Sideway filter.

High Recovery Factor, low drawdown balanced config. Suitable for stable long-term trading. No SR or Sideway filter.

  • TF: M15, Trend Filter: H4 EMA50
  • TF: M15, Trend Filter: H4 EMA50
  • GlobalTP: $70, LotBalance bật, Hedge tắt (999)
  • GlobalTP: $70, LotBalance on, Hedge disabled (999)
💡 Hướng dẫn load configHow to load config Trong MetaTrader 5: mở Strategy Tester hoặc EA Properties → tab Inputs → click Load → chọn file .set. Hoặc drag & drop file .set vào EA đang chạy trên chart. In MetaTrader 5: open Strategy Tester or EA Properties → Inputs tab → click Load → select .set file. Or drag & drop the .set file onto the running EA on chart.