EA GoldenRobberGoldenRobber EA
Workflow & logicWorkflow & logic
EA GoldenRobber 1.42 b3 làm gì từ lúc gắn lên chart, trong mỗi tick, và trong suốt một round — kèm Manual Init, hot-reload, EA Link và leader election. Mọi hành vi ở đây đã được đối chiếu với mã nguồn. What GoldenRobber 1.42 b3 does from the moment it is attached to a chart, on every tick, and across a whole round — plus Manual Init, hot-reload, EA Link and leader election. Every behaviour here was checked against the source code.
GoldenRobber-1.42 build b3 — production, đang chạy trên tài khoản thật. Bản cũ: 1.41.4 b21 và hotfix b21.1 (Manual Init Pause = 4, không deploy). 1.42 tách từ b21.1 nên logic giao dịch giống b21.1, cộng thêm EA Link và Manual Init Close all. Giá trị ví dụ lấy từ config ổn định v1.42.b7-pass58.set — xem Config ổn định.
GoldenRobber-1.42 build b3 — production, running on live accounts. Previous builds: 1.41.4 b21 and hotfix b21.1 (Manual Init Pause = 4, never deployed). 1.42 was branched from b21.1, so its trading logic equals b21.1 plus EA Link and Manual Init Close all. Example values come from the stable config v1.42.b7-pass58.set — see Stable config.
Bức tranh tổng thểThe big picture
GoldenRobber là lưới DCA hai chiều cho XAUUSD, không có hard stop-loss. Mỗi round (R{n}) bắt đầu bằng một Init, được bồi thêm (Add) khi giá đi đủ MinPips, và được đóng dần bằng TP từng lệnh, cụm Tia, hoặc đóng sạch bằng Global TP. Toàn bộ logic chạy trong bốn hàm sự kiện của MT5:
GoldenRobber is a two-sided DCA grid for XAUUSD with no hard stop-loss. Each round (R{n}) starts with an Init, grows through Adds whenever price travels MinPips, and is closed piece by piece through per-order TP, Tia clusters, or flattened in one go by Global TP. All logic lives in four MT5 event handlers:
| HàmHandler | Khi nào chạyWhen it runs | Việc chínhMain job |
|---|---|---|
OnInit |
Gắn EA / đổi input / khởi động lại terminalEA attached / inputs changed / terminal restart | Định danh, schema, handle indicator, nạp ticket map, heartbeat đầu tiên, cấu hình EA Link, bật timerIdentity, schema, indicator handles, ticket map load, first heartbeat, EA Link setup, start timer |
OnTimer |
200 ms khi EA Link bật, ngược lại 1 s (không chạy trong tester)200 ms when EA Link is on, otherwise 1 s (not in the tester) | Đọc socket EA Link, heartbeat / cloud sync, vẽ panel — độc lập với tickDrain the EA Link socket, heartbeat / cloud sync, draw the panel — independent of ticks |
OnTick |
Mỗi tick giáEvery price tick | Toàn bộ logic giao dịch: bảo vệ, chốt lời, Init, Add, cân bằng lotAll trading logic: protections, exits, Init, Add, lot balance |
OnDeinit |
Gỡ EA / đổi chart / tắt terminalEA removed / chart change / terminal shutdown | Tắt timer, đóng EA Link, lưu ticket map, xoá object và handleKill timer, close EA Link, save ticket map, delete objects and handles |
OnTradeTransaction |
Mỗi giao dịch mớiEvery new deal | Ghi thời điểm đóng lệnh gần nhất (deal OUT/INOUT cùng magic) cho cooldownRecord the last close time (OUT/INOUT deal with our magic) for cooldowns |
OnInit — khởi độngOnInit — start-up
- Banner & định danh. In dòng
GoldenRobber v1.42 (b3) loaded …; đặtg_magic = InpMagic; dựngcomposite_id=slug(ACCOUNT_COMPANY)::slug(ACCOUNT_SERVER)::login; lấy tên broker; dựngconfig_schema(JSON các key admin chỉnh được). - Global hot-reload. Chép input vào biến global mà logic thật sự đọc: lot balance, hedge, weekend,
g_manualInit(log nếu đang PAUSE / CLOSE ALL),g_singleRoundMode, các cờ StrongMove. - Lệnh giao dịch. Deviation 30 point, filling IOC (hardcode); tính kích thước pip từ
InpPipPoints. - Trạng thái. Equity tham chiếu cho lot balance, ring buffer flash crash (nếu bật),
g_roundId= số round lớn nhất đọc từ comment lệnh đang mở, balance đầu ngày / đầu tuần, đỉnh equity. - Indicator. Tạo handle theo input đang bật: ATR StrongMove, ATR S/R, EMA trend, Bollinger sideway, ATR pivot Auto; tính pivot, vẽ zone S/R, vẽ panel lần đầu.
- Ticket map (TMap) — xem mục dưới.
- Heartbeat đầu tiên (khi
InpCloudSyncEnable, ngoài tester) để biết node này là leader hay follower trước khi chạy logic giao dịch, đồng thời nhận config hot-reload. - EA Link. Nếu
InpLinkMode = HYBRIDvà cloud sync bật: tách slug từInpCloudMyApiDomain(…/easupported/{slug}), host =InpLinkHosthoặc host của domain. Thiếu slug / host / token / port → log[EaLink] TẮTvà chạy HTTP only. - Timer.
EventSetMillisecondTimer(200)khi Link bật, ngược lạiEventSetTimer(1). Tester không có timer.
- Banner & identity. Prints
GoldenRobber v1.42 (b3) loaded …; setsg_magic = InpMagic; buildscomposite_id=slug(ACCOUNT_COMPANY)::slug(ACCOUNT_SERVER)::login; reads the broker name; buildsconfig_schema(JSON of admin-editable keys). - Hot-reload globals. Copies inputs into the globals the logic actually reads: lot balance, hedge, weekend,
g_manualInit(logged when PAUSE / CLOSE ALL),g_singleRoundMode, StrongMove flags. - Trade object. Deviation 30 points, IOC filling (hardcoded); pip size from
InpPipPoints. - State. Lot-balance reference equity, flash-crash ring buffer (if enabled),
g_roundId= highest round number found in open-position comments, start-of-day / start-of-week balance, equity peak. - Indicators. Creates handles for enabled features: StrongMove ATR, S/R ATR, trend EMA, sideway Bollinger, pivot Auto ATR; computes pivots, draws S/R zones and the first panel.
- Ticket map (TMap) — see below.
- First heartbeat (when
InpCloudSyncEnable, outside the tester) so the node knows whether it is leader or follower before any trading logic runs; hot-reload config arrives with it. - EA Link. If
InpLinkMode = HYBRIDand cloud sync is on: slug is parsed fromInpCloudMyApiDomain(…/easupported/{slug}), host =InpLinkHostor the domain's host. Missing slug / host / token / port → logs[EaLink] TẮTand runs HTTP only. - Timer.
EventSetMillisecondTimer(200)when Link is on, otherwiseEventSetTimer(1). No timer in the tester.
Nạp ticket mapTicket map loading
Ticket map lưu ticket → round, add#, DCAPos/DCANeg, loại lệnh, comment để EA nhận lại round sau khi khởi động lại. Chuỗi ưu tiên trong OnInit:
- File local
GR_TicketMap_<magic>.csv(thư mục Common) — chỉ nạp ticket còn mở. - Nếu map vẫn rỗng, cloud sync bật và không phải tester: Cloudflare (
InpCloudCfDomain), thất bại thì MyApi (InpCloudMyApiDomain); nạp được thì ghi lại file local. TicketMapRebuild()dựng lại từ comment của các lệnh đang mở.
The ticket map stores ticket → round, add#, DCAPos/DCANeg, position type, comment so the EA can recognise its rounds after a restart. Priority chain in OnInit:
- Local file
GR_TicketMap_<magic>.csv(Common folder) — only tickets that are still open are loaded. - If the map is still empty, cloud sync is on and this is not the tester: Cloudflare (
InpCloudCfDomain), then MyApi (InpCloudMyApiDomain); a successful load is written back to the local file. TicketMapRebuild()rebuilds from the comments of open positions.
Comment trong OnInit ghi là rebuild "bổ sung" cho lệnh chưa có trong map, nhưng TicketMapRebuild() trong 1.42 b3 đặt g_ticketMapCount = 0 trước rồi dựng lại toàn bộ từ comment. Nghĩa là sau OnInit, map phản ánh comment của lệnh đang mở. Quy trình khôi phục khi MT5 sập: Khôi phục TMap.
The OnInit comment says the rebuild "supplements" positions missing from the map, but TicketMapRebuild() in 1.42 b3 sets g_ticketMapCount = 0 first and rebuilds everything from comments. So after OnInit the map reflects the open positions' comments. Crash-recovery procedure: TMap disaster recovery.
OnTimer — nhịp độc lập với tickOnTimer — the tick-independent pulse
GR_LinkPump()mỗi lần timer chạy (200 ms) khi Link bật: đọc frame, kéo config khi có tín hiệu (xem EA Link).- Việc nặng giữ nhịp 1 s (đo bằng
GetTickCount64):CloudSyncPulse()rồiUpdateInfoPanel(). CloudSyncPulse()tự throttle theoInpCloudSyncIntervalSec(pass58 = 10 s): gửi heartbeat (leader + config), sau đó chỉ leader đẩy ticket map lên Cloudflare và MyApi.
Nhờ timer, panel và heartbeat vẫn chạy khi thị trường lặng. Từ 1.42 b3, chu kỳ CloudSyncPulse đo bằng GetTickCount64() nên heartbeat định kỳ chạy cả khi đóng cửa thị trường. Các build cũ hơn (≤ 1.42 b2, production b21, b21.1) còn sai lệch D1 (EA-HOTRELOAD-STANDARD.md §17): đo bằng TimeCurrent() nên heartbeat ngừng khi không có tick và web báo Offline.
GR_LinkPump()on every timer event (200 ms) when Link is on: drains frames and pulls config when signalled (see EA Link).- Heavy work is gated to 1 s (measured with
GetTickCount64):CloudSyncPulse()thenUpdateInfoPanel(). CloudSyncPulse()self-throttles toInpCloudSyncIntervalSec(10 s in pass58): sends the heartbeat (leader status + config), then only the leader pushes the ticket map to Cloudflare and MyApi.
Thanks to the timer, panel and heartbeat keep running in a quiet market. Since 1.42 b3 the CloudSyncPulse interval is measured with GetTickCount64(), so periodic heartbeats keep running while the market is closed. Older builds (≤ 1.42 b2, production b21, b21.1) still have deviation D1 (EA-HOTRELOAD-STANDARD.md §17): they measure with TimeCurrent(), so heartbeats stop without ticks and the web shows Offline.
OnTick — thứ tự xử lý mỗi tickOnTick — processing order on every tick
Thứ tự dưới đây đúng như trong OnTick(). Thứ tự quan trọng: các lệnh đóng (Global TP, Tia…) chạy trước việc mở lệnh mới, và Close all chặn toàn bộ phần sau.
The order below is exactly as in OnTick(). The order matters: closing logic (Global TP, Tia…) runs before any new orders, and Close all short-circuits everything after it.
RefreshTickCache()— quét lệnh một lần, cache lot Buy/Sell (có / không tính Hedge) và tổng profit.- Mỗi 30 s:
TicketMapCleanup()(bỏ ticket đã đóng),RoundChainCleanup()(bỏ round đã chết khỏi chain persistent), xoá map trên cloud nếu map vừa trở thành rỗng,TicketMapSave()(ghi file +CloudSyncPulse). - Manual Init = Close all (5) →
ManualCloseAllPulse()rồireturn. Không chạy bất cứ bước nào bên dưới. CheckFlashCrash()— phát hiện cú chạy giá, trong cooldown thì cân bằng nhanh.CheckWeekendCloseAll(),CheckWeekendBalance().- Nếu có lệnh mở:
CheckGlobalTP(),CheckGlobalSL(),CheckGlobalSLClearStuck(); nếu không trong flash crash:CheckVirtualDcaTp(),CheckTiaClusters();CheckHedging()(throttle 5 s);CleanResiduePositions(). CheckMaxDrawdown(),CheckMaxLossPerDay(),CheckDailyLimit().- Nếu không cờ nào ở bước 7 bật:
ProcessNewBarEntries()(Init),ProcessAddEntries()(Add),CheckLotBalance()(throttle 3 s). - Panel mỗi
InpPanelRefreshSecgiây (refresh cache sideway nếu bật).
RefreshTickCache()— one scan of positions caching Buy/Sell lots (with / without Hedge) and total profit.- Every 30 s:
TicketMapCleanup()(drop closed tickets),RoundChainCleanup()(drop dead rounds from the persistent chain), clear the cloud map if the map just became empty,TicketMapSave()(file +CloudSyncPulse). - Manual Init = Close all (5) →
ManualCloseAllPulse()thenreturn. Nothing below runs. CheckFlashCrash()— detects a price burst; during cooldown it runs fast balancing.CheckWeekendCloseAll(),CheckWeekendBalance().- If any position is open:
CheckGlobalTP(),CheckGlobalSL(),CheckGlobalSLClearStuck(); unless a flash crash is active:CheckVirtualDcaTp(),CheckTiaClusters();CheckHedging()(5 s throttle);CleanResiduePositions(). CheckMaxDrawdown(),CheckMaxLossPerDay(),CheckDailyLimit().- If none of the step-7 flags is set:
ProcessNewBarEntries()(Init),ProcessAddEntries()(Add),CheckLotBalance()(3 s throttle). - Panel every
InpPanelRefreshSecseconds (refreshes the sideway cache if enabled).
flowchart TD
T(["Tick mới"]) --> C["RefreshTickCache"]
C --> M{"Đủ 30 s?"}
M -- "có" --> MC["Dọn ticket map + round chain, lưu map"]
M -- "không" --> CA
MC --> CA{"Manual Init = Close all?"}
CA -- "có" --> CAP["ManualCloseAllPulse (leader)"] --> END(["Kết thúc tick"])
CA -- "không" --> FC["CheckFlashCrash"]
FC --> WK["Weekend: close all + balance thứ 6"]
WK --> HP{"Có lệnh mở?"}
HP -- "có" --> EX["Global TP / Global SL / Clear Stuck"]
EX --> FA{"Flash crash đang active?"}
FA -- "không" --> TP["Virtual DCA TP + Tia cluster"]
FA -- "có" --> HG
TP --> HG["Hedging (5 s) + dọn residue"]
HP -- "không" --> RK
HG --> RK["Max drawdown / lỗ ngày / daily limit"]
RK --> RB{"Có cờ rủi ro nào bật?"}
RB -- "không" --> EN["Init (nến M1 mới) → Add → Lot balance (3 s)"]
RB -- "có" --> PN
EN --> PN["Panel theo InpPanelRefreshSec"]
PN --> ENDLuồng OnTick() của GoldenRobber 1.42 b3. Heartbeat và EA Link chạy riêng trong OnTimer().
flowchart TD
T(["New tick"]) --> C["RefreshTickCache"]
C --> M{"30 s elapsed?"}
M -- "yes" --> MC["Clean ticket map + round chain, save map"]
M -- "no" --> CA
MC --> CA{"Manual Init = Close all?"}
CA -- "yes" --> CAP["ManualCloseAllPulse (leader)"] --> END(["End of tick"])
CA -- "no" --> FC["CheckFlashCrash"]
FC --> WK["Weekend: Friday close all + balance"]
WK --> HP{"Any open position?"}
HP -- "yes" --> EX["Global TP / Global SL / Clear Stuck"]
EX --> FA{"Flash crash active?"}
FA -- "no" --> TP["Virtual DCA TP + Tia cluster"]
FA -- "yes" --> HG
TP --> HG["Hedging (5 s) + residue clean"]
HP -- "no" --> RK
HG --> RK["Max drawdown / daily loss / daily limit"]
RK --> RB{"Any risk flag set?"}
RB -- "no" --> EN["Init (new M1 bar) → Add → Lot balance (3 s)"]
RB -- "yes" --> PN
EN --> PN["Panel every InpPanelRefreshSec"]
PN --> ENDGoldenRobber 1.42 b3 OnTick() flow. Heartbeat and EA Link run separately in OnTimer().
MaxDrawdown và MaxLossPerDay chỉ chặn Init / Add / lot balance (trừ khi InpMaxDrawdownCloseAll=true). DailyLimit đóng hết lệnh khi đạt mục tiêu lời/lỗ và dừng tới hết ngày server. Trong pass58 cả ba đều tắt — không có phanh cứng.
MaxDrawdown and MaxLossPerDay only block Init / Add / lot balance (unless InpMaxDrawdownCloseAll=true). DailyLimit closes everything when the daily profit/loss target is hit and stops until the server day ends. All three are off in pass58 — there is no hard brake.
OnDeinit — tắt EAOnDeinit — shutdown
EventKillTimer() → đóng EA Link (Close("deinit")) → TicketMapSaveImmediate() (ghi file; khi cloud sync bật thì gửi heartbeat và, nếu là leader, đẩy map lên Cloudflare + MyApi) → xoá panel, zone S/R, đường pivot → giải phóng mọi handle indicator. Lệnh đang mở không bị đóng.
EventKillTimer() → close EA Link (Close("deinit")) → TicketMapSaveImmediate() (writes the file; with cloud sync on it sends a heartbeat and, if leader, pushes the map to Cloudflare + MyApi) → deletes panel, S/R zones, pivot lines → releases every indicator handle. Open positions are not closed.
Một round từ Init đến khi đóngA round from Init to close
Round là đơn vị sổ lệnh: mọi lệnh cùng R{n} trong comment. Comment chuẩn: Init R12 P |init_minpips, DCAPos R12 B#3 |add_minpips, DCANeg R12 S#1 |add_sr, Hedge R12 |hedge. Danh sách tag đầy đủ: Order Comment Tags.
A round is the bookkeeping unit: every order carrying the same R{n} in its comment. Typical comments: Init R12 P |init_minpips, DCAPos R12 B#3 |add_minpips, DCANeg R12 S#1 |add_sr, Hedge R12 |hedge. Full tag list: Order Comment Tags.
Cổng Init — ProcessNewBarEntriesInit gates — ProcessNewBarEntries
Chỉ leader, chỉ khi vừa sang nến M1 mới. Các bước theo đúng thứ tự mã nguồn:
Leader only, and only when a new M1 bar has just started. Steps in source order:
| # | BướcStep | Điều kiện / hiệu ứngCondition / effect |
|---|---|---|
| 1 | Được phép mở roundMay open a round | Trong khung giờ InpStartHour:Minute–InpEndHour:Minute; nếu đang trống lệnh thì đã qua InpWaitAfterCloseSec từ lần đóng cuối; đã qua InpInitCooldownSec từ Init cuối.Inside InpStartHour:Minute–InpEndHour:Minute; when flat, InpWaitAfterCloseSec has passed since the last close; InpInitCooldownSec has passed since the last Init. |
| 2 | Lý do Init (tag)Init reason (tag) | Trống lệnh → init_flat; gần S/R hoặc pivot → init_sr / init_pivot; InpInitRequireMinPips=false → init_nomindist; ngược lại so với ref round cuối (nến xanh dùng khoảng DCAPos, nến đỏ dùng khoảng DCANeg) → init_minpips (không có ref → init_noref).Flat → init_flat; near S/R or pivot → init_sr / init_pivot; InpInitRequireMinPips=false → init_nomindist; otherwise distance from the last round's refs (green bar uses DCAPos spacing, red bar uses DCANeg spacing) → init_minpips (no ref → init_noref). |
| 3 | StrongMove | Nến trên InpStrongMoveTF có range ≥ MinPips × InpStrongMoveMultiplier và ≥ ATR × InpVolatilityATRMult (tuỳ chọn phải đóng vượt đỉnh/đáy InpStrongMoveSRLookback nến) → cho phép với tag init_strong. Tắt trong pass58.A bar on InpStrongMoveTF with range ≥ MinPips × InpStrongMoveMultiplier and ≥ ATR × InpVolatilityATRMult (optionally closing beyond the InpStrongMoveSRLookback-bar high/low) → allowed with tag init_strong. Off in pass58. |
| 4 | Fallback | Đang có lệnh và đã ≥ InpInitNaturalFallbackMinBars nến M1 không Init → init_fallback (pass58 = 8).Positions open and ≥ InpInitNaturalFallbackMinBars M1 bars without an Init → init_fallback (8 in pass58). |
| 5 | Chặn phụSecondary blocks | Weekend (thứ 6 sau giờ / thứ 2 trước giờ), range nến < InpInitMinBarRangePips, vùng giá đã đủ InpMaxOrdersInPriceZone, tổng lệnh ≥ InpMaxOpenPositions.Weekend (Friday after hour / Monday before hour), bar range < InpInitMinBarRangePips, price zone already holds InpMaxOrdersInPriceZone, total positions ≥ InpMaxOpenPositions. |
| 6 | SingleRoundMode | Buy và Sell là hai tiến trình riêng. Một phía sẵn sàng khi: không còn lệnh phía đó, hoặc round mới nhất phía đó đã đạt InpSingleRoundMaxAdds (theo số B#/S# lớn nhất), hoặc chỉ còn một lệnh Init lẻ. Có phía sẵn sàng → cho phép. Không phía nào sẵn sàng → Gap Init khi Buy thấp nhất nằm trên Sell cao nhất, gap > InpDCAPosMinPips, gap ≤ InpSingleRoundGapMaxPips (0 = không giới hạn) và số round trong gap < InpSingleRoundGapInits → init_gap.Buy and Sell are independent processes. A side is ready when: it has no positions, or its latest round has reached InpSingleRoundMaxAdds (highest B#/S#), or only a lone Init remains. Any side ready → allowed. No side ready → Gap Init when lowest Buy is above highest Sell, gap > InpDCAPosMinPips, gap ≤ InpSingleRoundGapMaxPips (0 = unlimited) and rounds inside the gap < InpSingleRoundGapInits → init_gap. |
| 7 | MinPips xuyên roundCross-round MinPips | Đang có lệnh: Buy mới phải cách Buy gần nhất (mọi round, bỏ Hedge và residue) ≥ InpDCAPosMinPips; Sell mới cách Sell gần nhất ≥ InpDCANegMinPips. Tắt từng phía vi phạm; cả hai vi phạm → chặn.With positions open: a new Buy must be ≥ InpDCAPosMinPips from the nearest Buy (any round, excluding Hedge and residue); a new Sell ≥ InpDCANegMinPips from the nearest Sell. The violating side is disabled; both violating → blocked. |
| 8 | Bộ lọc cấp roundRound-level filters | Sideway (BlockInit) → chặn; trend neutral với InpTrendFilterApplyInit → chặn; đang có lệnh: không phía nào gần pivot → chặn (SingleRound: tắt phía không gần pivot); cả hai phía bị râu nến reject → chặn (SingleRound: tắt phía bị reject).Sideway (BlockInit) → block; trend neutral with InpTrendFilterApplyInit → block; with positions open: neither side near a pivot → block (SingleRound: disable the side not near a pivot); both sides wick-rejected → block (SingleRound: disable the rejected side). |
| 9 | Chặn cuốiFinal blocks | Flash crash đang active; Auto Balance đang ACT; InpMaxTotalLot đã đầy hoặc lot Init sau scale rơi xuống min lot và < 50% start lot.Flash crash active; Auto Balance in ACT; InpMaxTotalLot reached, or the scaled Init lot drops to min lot and below 50% of the start lot. |
| 10 | Thực thiExecute | InpEntryTimingProfileEnable=true → hẹn giờ trong cùng nến (0 s hoặc trễ ngẫu nhiên); ngược lại gọi ExecuteInitRoundNow() ngay.InpEntryTimingProfileEnable=true → scheduled within the same bar (0 s or a random delay); otherwise ExecuteInitRoundNow() is called at once. |
Khi SingleRoundMode=true và có một phía sẵn sàng, bước 6 đặt lại allowNewRound = true — nên các chặn ở bước 2 và bước 5 (lý do Init, weekend, range nến, vùng giá, InpMaxOpenPositions) bị ghi đè. Các bước 7–9 chạy sau nên vẫn có hiệu lực. Với pass58 các chặn ở bước 5 đều tắt nên không có ảnh hưởng thực tế, nhưng cần nhớ nếu bật Weekend Protection cùng SingleRoundMode.
With SingleRoundMode=true and a side ready, step 6 sets allowNewRound = true again — so the step-2 and step-5 blocks (Init reason, weekend, bar range, price zone, InpMaxOpenPositions) are overridden. Steps 7–9 run afterwards and still apply. In pass58 the step-5 blocks are all off, so there is no practical effect, but keep it in mind if Weekend Protection is enabled together with SingleRoundMode.
Chọn hướng Init — ExecuteInitRoundNowChoosing the Init side — ExecuteInitRoundNow
- Manual Init Pause (4) / Close all (5) → trả về ngay, không Init. Đây là chốt chặn ưu tiên cao nhất.
- Tag
init_strongvàg_strongMoveBypassbật → xác định chiều nến mạnh (bypass). - Trend filter + ApplyInit mà trend neutral → dừng (trừ khi Manual Init khác OFF hoặc StrongMove bypass).
- Nhãn hướng
labelDir= hướng trend (EMAInpTrendFilterMAPeriodtrênInpTrendFilterTF± NeutralPips); neutral thì theo màu nến M1 vừa đóng. StrongMove bypass hoặc Manual BUY/SELL ghi đè. - Trend filter + ApplyInit → chỉ giữ phía P (UP: Buy, DOWN: Sell).
- Theo từng phía: Multi-TF (HTF phải cùng hướng, neutral = chặn) → Pivot (Buy gần Support, Sell gần Resistance) → Wick rejection → Choppy ADX (chặn cả hai) → Dual-Direction (đang chop + chỉ có một phía mở → chặn phía kia) → Anti-Whipsaw cooldown (chặn cả hai). Multi-TF, Choppy, Dual-Dir, Anti-Whipsaw và Adaptive NeutralPips chỉ có tác dụng khi Choppy Defense Group đang active (pass58: ≥ 24 lệnh không tính Hedge).
- StrongMove bypass → ép đúng một phía theo nến. Manual BUY/SELL → ép đúng phía đã chọn.
- SingleRoundMode → áp cờ per-side từ
ProcessNewBarEntries. OpenInitRoundPosNegPair()kiểm lại Pause/Close all,InpDCAPos/NegMaxTrades, exposure scale, lot ≥ min lot; tăngg_roundIdvà gửi lệnhInit R{n} P/Init R{n} N.
- Manual Init Pause (4) / Close all (5) → return immediately, no Init. This is the highest-priority block.
- Tag
init_strongwithg_strongMoveBypasson → determine the strong bar's direction (bypass). - Trend filter + ApplyInit with a neutral trend → stop (unless Manual Init is not OFF or StrongMove bypass applies).
- Direction label
labelDir= trend direction (EMAInpTrendFilterMAPeriodonInpTrendFilterTF± NeutralPips); if neutral, the colour of the last closed M1 bar. StrongMove bypass or Manual BUY/SELL override it. - Trend filter + ApplyInit → keep only the P side (UP: Buy, DOWN: Sell).
- Per side: Multi-TF (HTF must agree, neutral = block) → Pivot (Buy near Support, Sell near Resistance) → Wick rejection → Choppy ADX (blocks both) → Dual-Direction (choppy + only one side open → block the other) → Anti-Whipsaw cooldown (blocks both). Multi-TF, Choppy, Dual-Dir, Anti-Whipsaw and Adaptive NeutralPips only act while the Choppy Defense Group is active (pass58: ≥ 24 non-hedge positions).
- StrongMove bypass → force exactly the bar's side. Manual BUY/SELL → force exactly the chosen side.
- SingleRoundMode → apply the per-side flags from
ProcessNewBarEntries. OpenInitRoundPosNegPair()re-checks Pause/Close all,InpDCAPos/NegMaxTrades, exposure scale, lot ≥ min lot; incrementsg_roundIdand sendsInit R{n} P/Init R{n} N.
Chi tiết từng bộ lọc: Trend · Pivot · Wick · Whipsaw defense · Sideway · S/R · Phòng thủ whipsaw.Filter details: Trend · Pivot · Wick · Whipsaw defense · Sideway · S/R · Whipsaw defense.
Nhãn P/N và loại roundP/N labels and round type
- P = chân theo trend, dùng lot/TP nhóm DCAPos. N = chân ngược trend, dùng nhóm DCANeg. UP: Buy = P, Sell = N; DOWN: Sell = P, Buy = N.
- Không bật trend ApplyInit thì một Init mở cả cặp P + N. Bật (như pass58) thì thực tế chỉ mở chân P.
InpDCANegEnablekhông được kiểm khi Init — nó chỉ tắt nhánh Add DCANeg. Chân N vẫn có thể mở nếu bộ lọc cho phép cả hai phía. Với pass58 thì không:InpTrendFilterApplyInit=truenên trend có hướng chỉ mở chân P, trend neutral thì không Init — dữ liệu production không có lệnh DCANeg nào.GetRoundInfo()suy ra loại round từ comment: đếm nhãn InitP/N, rồi đếnDCAPos/DCANeg; hoà (Init có cả P và N) thì theo trend hiện tại. Loại round quyết định nhánh Add.
- P = with-trend leg using DCAPos lot/TP. N = counter-trend leg using DCANeg. UP: Buy = P, Sell = N; DOWN: Sell = P, Buy = N.
- Without trend ApplyInit an Init opens a P + N pair. With it (as in pass58) only the P leg opens in practice.
InpDCANegEnableis not checked at Init — it only disables the DCANeg Add branch. An N leg can still open if the filters allow both sides. Not under pass58:InpTrendFilterApplyInit=truemeans a directional trend opens only the P leg and a neutral trend opens nothing — live data contains no DCANeg order.GetRoundInfo()infers the round type from comments: counts InitP/Nlabels, thenDCAPos/DCANeg; on a tie (Init with both P and N) it follows the current trend. The round type selects the Add branch.
Add — ProcessAddEntriesAdds — ProcessAddEntries
Chạy mỗi tick (leader). Chặn toàn bộ khi: flash crash active, InpMaxTotalLot đầy, thứ 6 sau InpFridayNoInitAfterHour (khi Weekend Protection bật), sideway (trừ khi đang cân bằng lot), range nến < InpInitMinBarRangePips, hoặc Auto Balance ACT mà không có phía cần cân bằng. Sau đó duyệt từng round:
- Nhịp: cách lần Add trước ≥
InpAddCooldownSec(0 = dùng profile timing hoặcInpWaitAfterCloseSec); tối đaInpMaxAddsPerBarPerSidemỗi nến M1 (0 = không giới hạn); thành công một Add thì dừng vòng lặp tới lượt sau. - Giới hạn: SingleRound max adds mỗi phía,
InpMaxOrdersPerRound,InpDCAPos/NegMaxTrades(0 = không giới hạn; lot balance có thể vượt nếuInpLotBalanceBypassMaxTrades), vùng giá. - DCAPos (thuận giá): Add Buy khi
ask ≥ Buy cao nhất + MinPips; Add Sell khibid ≤ Sell thấp nhất − MinPips(thiếu phía nào thì ref lấy từ phía kia). - DCANeg (ngược giá): Add Sell khi
bid ≥ Sell cao nhất + MinPips; Add Buy khiask ≤ Buy thấp nhất − MinPips. Bỏ qua hoàn toàn khiInpDCANegEnable=false(pass58). - MinPips:
InpDCAMinPipsModeFixed =InpDCAPos/NegMinPips; Pivot =max(Floor, K × nửa range pivot của InpDCAMinPipsPivotTF). S/R chỉ là điều kiện bổ sung (tagadd_sr), trừ khiInpSRGateAdd=truebắt buộc gần S/R. - Bộ lọc Add: Trend ApplyAdd (UP chỉ Buy, DOWN chỉ Sell, neutral chặn cả hai), Multi-TF ApplyAdd, Pivot ApplyAdd, Wick ApplyAdd, Choppy ApplyAdd. Phía đang cần cân bằng lot được miễn các bộ lọc này.
- Lot: DCAPos =
StartLot × Multiplier^n, DCANeg =StartLot × Multiplier^(n−1), chặn trênMaxLot, nhân exposure scale. Legacy (InpDcaChainPersistent=false, pass58):n= số lệnh cùng phía đang mở trong round nên lot có thể reset nhỏ lại sau khi Tia/TP đóng bớt. Persistent:n= sốB#/S#lớn nhất từng đạt, chỉ reset khi cả round chết — xem DCA chain persistent.
Ví dụ pass58, round DCAPos Buy: Init 0.10 → Add 0.15 → 0.22 → 0.33 → 0.50 (trần), mỗi bước cách 34 pips (lot sau chuẩn hoá theo bước lot của broker).
Runs on every tick (leader). Fully blocked when: flash crash active, InpMaxTotalLot reached, Friday after InpFridayNoInitAfterHour (with Weekend Protection on), sideway (unless lot balancing), bar range < InpInitMinBarRangePips, or Auto Balance in ACT with no side needing balance. Then it walks every round:
- Pacing: ≥
InpAddCooldownSecsince the last Add (0 = timing profile orInpWaitAfterCloseSec); at mostInpMaxAddsPerBarPerSideper M1 bar (0 = unlimited); after one successful Add the loop stops until the next call. - Caps: SingleRound max adds per side,
InpMaxOrdersPerRound,InpDCAPos/NegMaxTrades(0 = unlimited; lot balance may exceed it withInpLotBalanceBypassMaxTrades), price zone. - DCAPos (with price): Add Buy when
ask ≥ highest Buy + MinPips; Add Sell whenbid ≤ lowest Sell − MinPips(a missing side borrows its ref from the other side). - DCANeg (against price): Add Sell when
bid ≥ highest Sell + MinPips; Add Buy whenask ≤ lowest Buy − MinPips. Skipped entirely whenInpDCANegEnable=false(pass58). - MinPips:
InpDCAMinPipsModeFixed =InpDCAPos/NegMinPips; Pivot =max(Floor, K × half pivot range of InpDCAMinPipsPivotTF). S/R is only an extra condition (tagadd_sr) unlessInpSRGateAdd=truemakes nearness mandatory. - Add filters: Trend ApplyAdd (UP Buy only, DOWN Sell only, neutral blocks both), Multi-TF ApplyAdd, Pivot ApplyAdd, Wick ApplyAdd, Choppy ApplyAdd. The side that needs lot balancing is exempt.
- Lot: DCAPos =
StartLot × Multiplier^n, DCANeg =StartLot × Multiplier^(n−1), capped atMaxLot, times the exposure scale. Legacy (InpDcaChainPersistent=false, pass58):n= same-side positions currently open in the round, so the lot can reset smaller after Tia/TP closes some. Persistent:n= highestB#/S#ever reached, reset only when the whole round dies — see DCA chain persistent.
pass58 example, DCAPos Buy round: Init 0.10 → Add 0.15 → 0.22 → 0.33 → 0.50 (cap), 34 pips apart (lots normalised to the broker's volume step).
Chốt lời và đóng lệnhExits
| Cơ chếMechanism | Đóng khiCloses when | Ghi chúNotes |
|---|---|---|
| TP từng lệnhPer-order TP DCA |
Lệnh lời đủ InpDCAPosTPUSD / InpDCANegTPUSD (USD đổi ra khoảng giá theo lot).A position earns InpDCAPosTPUSD / InpDCANegTPUSD (USD converted to a price distance by lot). |
InpVirtualDcaTpEnable=true: lệnh gửi TP = 0, EA tự đóng (không chạy khi MT5 mất kết nối). Tạm giữ không đóng khi: có lệnh lỗ stuck bất kỳ phía (lỗ ≥ InpTiaStuckLossUSD hoặc tuổi ≥ InpTiaStuckAgeHours, với InpTiaBlockSameSideWhenStuck), hoặc phía đối diện lỗ ≥ InpDcaTpSkipWhenOpposLossUSD trong khi phía mình chưa lỗ tới ngưỡng.InpVirtualDcaTpEnable=true: orders carry TP = 0 and the EA closes them (not while MT5 is disconnected). Held back when: any losing position is stuck (loss ≥ InpTiaStuckLossUSD or age ≥ InpTiaStuckAgeHours, with InpTiaBlockSameSideWhenStuck), or the opposite side is down ≥ InpDcaTpSkipWhenOpposLossUSD while this side is not. |
| Tia cluster Tia |
Một nhóm lệnh có tổng lời ≥ target (InpTiaProfitUSD; rescue InpTiaProfitWhenLossUSD khi tổng floating ≤ −InpTiaHighTargetLossUSD).A group of positions whose combined profit ≥ target (InpTiaProfitUSD; rescue InpTiaProfitWhenLossUSD when total floating ≤ −InpTiaHighTargetLossUSD). |
Path A (InpTiaPartialCloseEnable): lệnh lời tỉa lỗ trong budget, có anchor. Path B: tìm tổ hợp trên tối đa InpTiaMaxPositions lệnh cũ nhất (clamp 8–22), yêu cầu BotDCA style, anchor / ladder-roll / release valve. Có lệnh stuck → bỏ qua Path B, chỉ Path A được chạy.Path A (InpTiaPartialCloseEnable): winners trim losers within a budget, anchor-aware. Path B: subset search over at most InpTiaMaxPositions oldest positions (clamped 8–22) with BotDCA-style mix and anchor / ladder-roll / release valve. Any stuck position → Path B is skipped, only Path A may run. |
| Global TP / SL Global |
Tổng floating ≥ InpGlobalTPUSD → đóng tất cả; ≤ −InpGlobalSLUSD → đóng tất cả (≥ 999999 = tắt).Total floating ≥ InpGlobalTPUSD → close all; ≤ −InpGlobalSLUSD → close all (≥ 999999 = off). |
Global TP là "bias close-all" của chiến lược. RELEASES.md: đóng hết mà không kiểm lại, slippage trên book lớn có thể biến +$10 thành lỗ.Global TP is the strategy's "bias close-all". RELEASES.md: it closes everything without re-checking, so slippage on a large book can turn +$10 into a loss. |
| Clear Stuck ClearStuck |
Tổng floating âm, lệnh lỗ nặng nhất đã bị giá đi ngược ≥ DistancePips, và lợi nhuận đã chốt trong kỳ (ngày/tuần) > 0.Total floating is negative, the worst loser is ≥ DistancePips against its open price, and realised profit in the period (day/week) > 0. |
Budget = % lợi nhuận kỳ; chế độ All / WorstOnly / FarOnly / SameSideOnly / FarPartial; EmergencyPips bỏ qua điều kiện lợi nhuận.Budget = % of period profit; modes All / WorstOnly / FarOnly / SameSideOnly / FarPartial; EmergencyPips skips the profit condition. |
pass58 đặt InpTiaPartialCloseEnable=false, InpTiaBlockSameSideWhenStuck=true, InpTiaStuckLossUSD=500, InpTiaStuckAgeHours=4. Theo code, chỉ cần một lệnh đang lỗ có lỗ ≥ $500 hoặc tuổi ≥ 4 giờ thì TP ảo bị giữ, Path B bị bỏ qua và Path A đang tắt — Tia không đóng gì. Lối thoát duy nhất còn lại là Global TP $10 (Global SL, Clear Stuck, Max DD đều tắt). Đây chính là cơ chế "stuck-lock deadlock" mà docs/BACKTEST_COMPARISON.md mô tả trong vụ cháy 2023 của bản M3.
pass58 sets InpTiaPartialCloseEnable=false, InpTiaBlockSameSideWhenStuck=true, InpTiaStuckLossUSD=500, InpTiaStuckAgeHours=4. Per the code, a single losing position with loss ≥ $500 or age ≥ 4 hours holds the virtual TPs, skips Path B, and Path A is disabled — Tia closes nothing. The only remaining exit is Global TP $10 (Global SL, Clear Stuck and Max DD are all off). This is the "stuck-lock deadlock" mechanism docs/BACKTEST_COMPARISON.md describes for the 2023 blow-up of the M3 build.
HedgeHedging
CheckHedging() mỗi 5 s (leader, g_hedgeEnable). ByMainRound / ByTotal / ByAccountProfit: khi số lệnh Buy (không tính Hedge) ≥ g_hedgeAfterTrades, phía Buy đang lỗ và chưa có Sell hedge → mở Sell Hedge |hedge với volume theo chế độ (vd ByTotal = g_hedgeLotPercent % tổng lot Buy); ngược lại cho Sell. PerRound: một hedge cho mỗi round đạt ngưỡng (Hedge R{n} |hedge). Hedge bỏ qua exposure scale, không tính vào round/counter, được đóng bởi Global TP/SL, Tia hoặc Close all. pass58: tắt (InpHedgeEnable=false, InpHedgeAfterTrades=9999). Tham số.
CheckHedging() every 5 s (leader, g_hedgeEnable). ByMainRound / ByTotal / ByAccountProfit: when non-hedge Buy count ≥ g_hedgeAfterTrades, the Buy side is losing and there is no Sell hedge → open a Sell Hedge |hedge sized by mode (e.g. ByTotal = g_hedgeLotPercent % of total Buy lots); mirrored for Sell. PerRound: one hedge per qualifying round (Hedge R{n} |hedge). Hedges bypass the exposure scale, are excluded from rounds/counters, and close via Global TP/SL, Tia or Close all. pass58: off (InpHedgeEnable=false, InpHedgeAfterTrades=9999). Parameters.
Cân bằng lot (Auto Balance)Lot balance (Auto Balance)
Trạng thái được tính trong ProcessAddEntries: cần g_lotBalanceEnable và |Buy − Sell| > min lot. Normal: ACT khi |net| > g_lotBalanceTrigger. LossTriggered: chỉ khi equity đã giảm ≥ InpLotBalanceLossTriggerUSD so với equity tham chiếu (tham chiếu tăng theo equity, đặt lại khi ACT → WAIT). InpLotBalanceUseTargetLevel=true giữ ACT tới khi |net| ≤ g_lotBalanceTarget. Khi ACT: chặn Init mới, chặn Add thường, chỉ Add phía nhẹ (miễn bộ lọc trend/pivot/wick/choppy/sideway), và CheckLotBalance() mở lệnh AutoBal Direct tối đa InpLotBalanceMaxLotPerOrder mỗi InpAddCooldownSec (0 → 60 s). pass58: tắt. Tham số.
The state is computed in ProcessAddEntries: requires g_lotBalanceEnable and |Buy − Sell| > min lot. Normal: ACT when |net| > g_lotBalanceTrigger. LossTriggered: only once equity has dropped ≥ InpLotBalanceLossTriggerUSD from the reference equity (the reference rises with equity and resets on ACT → WAIT). InpLotBalanceUseTargetLevel=true keeps ACT until |net| ≤ g_lotBalanceTarget. While ACT: new Inits blocked, normal Adds blocked, only lighter-side Adds allowed (exempt from trend/pivot/wick/choppy/sideway), and CheckLotBalance() opens AutoBal Direct orders of up to InpLotBalanceMaxLotPerOrder every InpAddCooldownSec (0 → 60 s). pass58: off. Parameters.
Flash crashFlash crash
Mỗi giây lấy mẫu bid vào ring buffer InpFlashCrashWindowSec. Giá lệch ≥ InpFlashCrashPips so với mẫu bất kỳ trong cửa sổ → active trong InpFlashCrashCooldownSec: đóng băng TP ảo và Tia, chặn mọi Init / Add / CheckLotBalance, ép Auto Balance, và FlashCrashFastBalance() mở lệnh phía nhẹ mỗi InpFlashCrashBalanceIntervalSec (tối đa InpFlashCrashBalanceMaxLot) tới khi |net| ≤ max(min lot, target). pass58: tắt. Tham số.
Samples the bid every second into an InpFlashCrashWindowSec ring buffer. A move ≥ InpFlashCrashPips versus any sample in the window → active for InpFlashCrashCooldownSec: virtual TP and Tia frozen, every Init / Add / CheckLotBalance blocked, Auto Balance forced, and FlashCrashFastBalance() opens lighter-side orders every InpFlashCrashBalanceIntervalSec (up to InpFlashCrashBalanceMaxLot) until |net| ≤ max(min lot, target). pass58: off. Parameters.
Bảo vệ cuối tuầnWeekend protection
Khi g_weekendProtectEnable (giờ server): thứ 6 từ InpFridayNoInitAfterHour chặn Init và Add, và nếu g_weekendBalanceEnable thì mỗi nến M1 mở một lệnh BalanceFri phía nhẹ (tối đa InpWeekendBalanceMaxLotPerOrder, bỏ qua khi > 80 lệnh) tới khi |net| ≤ g_weekendMaxNetLot; thứ 6 từ InpFridayCloseAllBeforeHour đóng tất cả nếu tổng profit ≥ InpFridayCloseMinProfitUSD; thứ 2 trước InpMondayNoInitUntilHour chặn Init. pass58: tắt. Tham số.
With g_weekendProtectEnable (server time): on Friday from InpFridayNoInitAfterHour Inits and Adds are blocked, and with g_weekendBalanceEnable one lighter-side BalanceFri order per M1 bar (up to InpWeekendBalanceMaxLotPerOrder, skipped above 80 positions) until |net| ≤ g_weekendMaxNetLot; on Friday from InpFridayCloseAllBeforeHour everything is closed if total profit ≥ InpFridayCloseMinProfitUSD; on Monday before InpMondayNoInitUntilHour Inits are blocked. pass58: off. Parameters.
Sơ đồ trạng thái của một roundRound state diagram
stateDiagram-v2 state "Trống lệnh" as Flat state "Chờ cooldown" as Cooldown state "Round mở (Init P)" as Open state "Đang bồi DCA" as Adding state "Giữ lệnh lời (stuck-lock)" as Stuck state "Pause - không Init" as Paused state "Close all - đang đóng" as Closing [*] --> Flat Flat --> Open : qua cổng Init và bộ lọc Open --> Adding : giá đi đủ MinPips Adding --> Adding : Add tiếp, lot nhân hệ số Adding --> Open : TP lệnh hoặc Tia đóng bớt Adding --> Stuck : lệnh lỗ vượt $ hoặc quá tuổi Stuck --> Adding : lệnh stuck được đóng Open --> Cooldown : Global TP đóng tất cả Adding --> Cooldown : Global TP đóng tất cả Stuck --> Cooldown : Global TP đóng tất cả Cooldown --> Flat : hết WaitAfterClose Open --> Paused : Manual Init = Pause Paused --> Paused : round đang mở vẫn được quản lý tới khi đóng Adding --> Closing : Manual Init = Close all Closing --> Paused : đã đóng hết lệnh Paused --> Flat : đổi Manual Init về OFF
Rút gọn: bỏ qua hedge, lot balance, flash crash. Trong SingleRoundMode, Buy và Sell chạy song song như hai round độc lập.
stateDiagram-v2 state "Flat" as Flat state "Cooldown" as Cooldown state "Round open (Init P)" as Open state "DCA adding" as Adding state "Winners held (stuck-lock)" as Stuck state "Pause - no Init" as Paused state "Close all - closing" as Closing [*] --> Flat Flat --> Open : passes Init gates and filters Open --> Adding : price travels MinPips Adding --> Adding : next Add, lot multiplied Adding --> Open : order TP or Tia closes some Adding --> Stuck : loser exceeds $ or age Stuck --> Adding : stuck order closed Open --> Cooldown : Global TP closes all Adding --> Cooldown : Global TP closes all Stuck --> Cooldown : Global TP closes all Cooldown --> Flat : WaitAfterClose elapsed Open --> Paused : Manual Init = Pause Paused --> Paused : open round still managed until it closes Adding --> Closing : Manual Init = Close all Closing --> Paused : all orders closed Paused --> Flat : Manual Init switched back to OFF
Simplified: hedging, lot balance and flash crash omitted. In SingleRoundMode, Buy and Sell run in parallel like two independent rounds.
Manual Init — các trạng tháiManual Init — states
Công cụ vận hành, đặt bằng InpManualInit trong .set hoặc key hot-reload manual_init trên /admin/easupported/goldenrobber. Giá trị enum trong 1.42 b3:
An operator tool, set with InpManualInit in the .set or the hot-reload key manual_init on /admin/easupported/goldenrobber. Enum values in 1.42 b3:
| Giá trịValue | TênName | Init mớiNew Init | Add / TP / Tia / Hedge / cân bằngAdd / TP / Tia / Hedge / balance | Ghi chúNotes |
|---|---|---|---|---|
| 0 | OFF |
Bộ lọc quyết địnhFilters decide | ON | Mặc định.Default. |
| 1 | Only BUY |
Ép Buy làm chân PForces Buy as the P leg | ON | Trong ExecuteInitRoundNow bỏ qua bộ lọc hướng (Trend, Multi-TF, Pivot, Wick, Choppy, Dual-Dir, Anti-Whipsaw). Vẫn phải qua cổng của ProcessNewBarEntries: timing, SingleRound, MinPips xuyên round, sideway, trend neutral, pivot/wick per-side khi đang có lệnh, flash crash, Auto Balance, exposure. Add không bị ảnh hưởng: ví dụ Only BUY trong trend DOWN mở được Init Buy nhưng Trend ApplyAdd vẫn chặn Add Buy. Chạy liên tục khi bật.Inside ExecuteInitRoundNow the direction filters are bypassed (Trend, Multi-TF, Pivot, Wick, Choppy, Dual-Dir, Anti-Whipsaw). The ProcessNewBarEntries gates still apply: timing, SingleRound, cross-round MinPips, sideway, trend neutral, per-side pivot/wick when positions exist, flash crash, Auto Balance, exposure. Adds are unaffected: e.g. Only BUY in a DOWN trend can open a Buy Init, but Trend ApplyAdd still blocks Buy Adds. Runs continuously while set. |
| 2 | Only SELL |
Ép Sell làm chân PForces Sell as the P leg | ON | |
| 3 | Auto |
— | — | Chỉ có ở dòng test 1.41.4 b22–b28. 1.42 không có giá trị này: hot-reload từ chối 3 và giữ giá trị cũ.Exists only on the 1.41.4 b22–b28 test line. 1.42 has no such value: hot-reload rejects 3 and keeps the previous value. |
| 4 | Pause |
BLOCKED | ON | Chặn ở đầu ExecuteInitRoundNow và OpenInitRoundPosNegPair. Round đang mở vẫn được quản lý và tự đóng dần, sau đó EA đứng yên. Panel [PAUSED], dòng Hot Reload manual_init=PAUSE.Blocked at the top of ExecuteInitRoundNow and OpenInitRoundPosNegPair. Open rounds are still managed and wind down, then the EA sits idle. Panel [PAUSED], Hot Reload line manual_init=PAUSE. |
| 5 | Close all |
BLOCKED | OFF | Mỗi tick (leader) đóng mọi lệnh của EA trên chart: đúng symbol + magic, gồm Hedge; lệnh tay / EA khác không bị đụng. Kiểm retcode, lỗi thì thử lại tối đa 1 lượt/giây. OnTick return ngay nên không chạy flash crash, weekend, Global TP/SL, Clear Stuck, TP ảo, Tia, hedge, rủi ro, Init, Add, cân bằng. Hết lệnh → log đã đóng hết lệnh, đứng yên như Pause tới khi về OFF. Panel [CLOSE ALL]. Không hoàn tác được. b21 / b21.1 / b28 không hiểu giá trị 5 và bỏ qua.Every tick (leader) closes all of the EA's positions on the chart: same symbol + magic, Hedge included; manual trades / other EAs are untouched. Checks retcodes and retries failures at most once per second. OnTick returns early, so flash crash, weekend, Global TP/SL, Clear Stuck, virtual TP, Tia, hedge, risk checks, Init, Add and balance do not run. When flat → logs đã đóng hết lệnh and idles like Pause until set back to OFF. Panel [CLOSE ALL]. Irreversible. b21 / b21.1 / b28 do not understand 5 and ignore it. |
Build không hiểu một giá trị sẽ bỏ qua và giữ giá trị cũ (không về OFF). Pause qua override global chỉ có tác dụng trên account đã chạy b21.1 hoặc 1.42. Muốn tắt thì chọn OFF. Chi tiết: Build & release · Release note 1.42 b2 · tham số Manual Init.
A build that does not understand a value ignores it and keeps its previous value (it does not fall back to OFF). A global Pause override only works on accounts already running b21.1 or 1.42. To stop, choose OFF. Details: Builds & releases · Release note 1.42 b2 · Manual Init parameters.
Hot-reload — 14 keyHot-reload — 14 keys
Input MQL5 bất biến khi chạy, nên mỗi key hot-reload có một biến global được khởi tạo từ input trong OnInit và logic chỉ đọc biến global. Server gửi giá trị trong response heartbeat; EA đẩy config_schema mỗi heartbeat để web vẽ form.
MQL5 inputs are immutable at runtime, so every hot-reload key has a global initialised from its input in OnInit, and the logic reads only the global. The server sends values in the heartbeat response; the EA pushes config_schema on every heartbeat so the web can render the form.
| KeyKey | Input | Kiểu / miềnType / domain | Ghi chúNotes |
|---|---|---|---|
manual_init | InpManualInit | enum 0, 1, 2, 4, 5 | Đổi giá trị thì reset bộ đếm Close all.A change resets the Close all attempt counter. |
single_round | InpSingleRoundMode | bool | Áp ở vòng Init kế tiếp.Takes effect on the next Init pass. |
strong_bypass | InpStrongMoveBypassFilter | bool | Không có tác dụng nếu InpStrongMoveEnable=false (không hot-reload được; pass58 = false). Đổi strong_tf sẽ tạo lại handle ATR.No effect while InpStrongMoveEnable=false (not hot-reloadable; false in pass58). Changing strong_tf recreates the ATR handle. |
strong_tf | InpStrongMoveTF | enum TF (schema: M1, M5, M15, M30, H1, H4, D1)TF enum (schema: M1, M5, M15, M30, H1, H4, D1) | |
strong_require_sr | InpStrongMoveRequireSRBreak | bool | |
lot_balance_enable | InpLotBalanceEnable | bool | Chế độ (InpLotBalanceMode) và ngưỡng lỗ không hot-reload được.Mode (InpLotBalanceMode) and the loss trigger are not hot-reloadable. |
lot_balance_trigger | InpLotBalanceTrigger | float | |
lot_balance_target | InpLotBalanceTarget | float | |
hedge_enable | InpHedgeEnable | bool | Tắt chỉ ngừng mở hedge mới. pass58 cần hạ cả hedge_after_trades (9999) thì hedge mới có thể kích hoạt.Turning off only stops new hedges. In pass58 hedge_after_trades (9999) must also be lowered before a hedge can trigger. |
hedge_after_trades | InpHedgeAfterTrades | int | |
hedge_lot_percent | InpHedgeLotPercent | float | |
weekend_protect_enable | InpWeekendProtectionEnable | bool | Các giờ thứ 6 / thứ 2 vẫn lấy từ input.Friday / Monday hours still come from inputs. |
weekend_max_net_lot | InpMaxNetLotBeforeWeekend | float | |
weekend_balance_enable | InpWeekendBalanceEnable | bool |
Server áp và revert thế nào (TicketMapParseHeartbeatResponse):
- Key nào có trong response thì ghi vào biến global (
manual_initkiểm miền;strong_tfphải là TF hợp lệ). hot_keyslà CSV các key server đang override cho account (theocomposite_id+ magic). Có field này thì mọi key không nằm trong đó được trả về giá trị input — đó là cách nút Clear trên web thực sự tắt override. Response không cóhot_keysthì không revert gì.- Dựng dòng panel
Hot Reload: …từ các key đang áp. - Cuối cùng mới đọc trạng thái leader (
is_leader, leader hiện tại, số node sống).
Sai lệch đã biết (D4): tìm key trong hot_keys bằng substring không bao dấu phẩy. Giá trị default trong schema là hằng số trong code, không phải giá trị của .set đang nạp (vd hedge_enable default true trong khi pass58 = false).
How the server applies and reverts (TicketMapParseHeartbeatResponse):
- Every key present in the response is written into its global (
manual_initis range-checked;strong_tfmust be a valid TF). hot_keysis a CSV of the keys the server is currently overriding for this account (bycomposite_id+ magic). When the field is present, every key not listed is reset to its input value — that is how Clear on the web actually removes an override. A response withouthot_keysreverts nothing.- The panel line
Hot Reload: …is rebuilt from the applied keys. - Only then is leader state read (
is_leader, current leader, alive nodes).
Known deviation (D4): keys are looked up in hot_keys by substring without comma delimiters. The schema's default values are constants in code, not the loaded .set values (e.g. hedge_enable defaults to true while pass58 = false).
EA Link — hot-reload trong ~1 giâyEA Link — hot-reload in about a second
Không có Link, config mới chỉ tới ở heartbeat kế tiếp (InpCloudSyncIntervalSec). 1.42 thêm kênh TLS TCP tới EaLinkBroker (cổng InpLinkPort, mặc định 9607). Kênh này chỉ mang tín hiệu {"t":"cfg","rev"}; giá trị luôn được kéo qua HTTPS heartbeat vì SocketTlsHandshake của MT5 không kiểm chứng chỉ. Xác thực bằng challenge + HMAC-SHA256 trên sha256(token), token thô không đi qua socket.
Without Link, new config only arrives with the next heartbeat (InpCloudSyncIntervalSec). 1.42 adds a TLS TCP channel to EaLinkBroker (port InpLinkPort, default 9607). The channel carries only a signal {"t":"cfg","rev"}; values are always pulled over the HTTPS heartbeat because MT5's SocketTlsHandshake does not verify certificates. Authentication is a challenge + HMAC-SHA256 over sha256(token); the raw token never crosses the socket.
sequenceDiagram
participant A as Admin (web)
participant F as fxconsole
participant B as EaLinkBroker :9607
participant E as EA (OnTimer 200 ms)
A->>F: Apply / Clear config
F->>B: Redis publish ea:link:cfg (rev)
B->>E: {"t":"cfg","rev"}
Note over E: đánh dấu cần kéo, gộp nhiều tín hiệu
E->>F: HTTPS heartbeat (tối đa 1 lần/giây)
F-->>E: giá trị config + hot_keys + leader
E->>B: {"t":"cfg_ack","rev","ok"}sequenceDiagram
participant A as Admin (web)
participant F as fxconsole
participant B as EaLinkBroker :9607
participant E as EA (OnTimer 200 ms)
A->>F: Apply / Clear config
F->>B: Redis publish ea:link:cfg (rev)
B->>E: {"t":"cfg","rev"}
Note over E: mark pull pending, coalesce signals
E->>F: HTTPS heartbeat (at most once per second)
F-->>E: config values + hot_keys + leader
E->>B: {"t":"cfg_ack","rev","ok"}GR_LinkPump()chạy mỗi 200 ms; kéo heartbeat khi cócfgđang chờ và đã ≥ 1 s từ lần kéo trước (debounce). Log[EaLink] cfg rev=… đã áp trong N ms.- Vừa kết nối lại (
hello_ok) mà heartbeat OK gần nhất cũ hơn 5 s → kéo bù một lần. - Kết nối lại với backoff 2 → 60 s ±20%;
bad_sig/unknown_eachờ 300 s; im lặng 60 s thì đóng. Broker chết → EA vẫn chạy như b21.1 bằng heartbeat định kỳ, panel báoLink: DOWN. - Host của Link phải có trong Allow WebRequest. Chi tiết protocol:
EA-HOTRELOAD-STANDARD.md§9 · Chuẩn tích hợp EA · Các broker realtime.
GR_LinkPump()runs every 200 ms; it pulls a heartbeat when acfgis pending and ≥ 1 s has passed since the previous pull (debounce). Logs[EaLink] cfg rev=… đã áp trong N ms.- Right after reconnecting (
hello_ok), if the last OK heartbeat is older than 5 s → one catch-up pull. - Reconnects with 2 → 60 s backoff ±20%;
bad_sig/unknown_eawait 300 s; 60 s of silence closes the link. Broker down → the EA keeps working like b21.1 on periodic heartbeats, panel showsLink: DOWN. - The Link host must be in Allow WebRequest. Protocol details:
EA-HOTRELOAD-STANDARD.md§9 · EA integration standard · Realtime brokers.
Leader election — chỉ leader giao dịchLeader election — only the leader trades
Dùng khi cùng account + magic chạy trên nhiều terminal/VPS để dự phòng. Leader = node còn sống có InpCloudNodePriority nhỏ nhất (hoà thì node_id nhỏ hơn); còn sống = heartbeat trong InpCloudHeartbeatTimeoutSec. CanTradeAsLeader() trả true khi cloud sync tắt, khi đang backtest, hoặc khi node không phải follower.
- Có kiểm leader: Init, Add,
CheckLotBalance, flash-crash fast balance, hedge, Tia, TP ảo, Global TP / SL / Clear Stuck, dọn residue, Close all, và đẩy ticket map lên cloud. - Không kiểm leader (đã xem code):
CheckWeekendCloseAll,CheckWeekendBalance, nhánh đóng hết củaCheckMaxDrawdownvàCheckDailyLimit, xoá map trên cloud khi map local rỗng. Trong pass58 các tính năng này đều tắt. - Fail-safe: chưa từng nhận heartbeat thành công → là leader; cả Cloudflare và MyApi lỗi quá
2 × InpCloudHeartbeatTimeoutSec→ tự xưng leader để không bỏ mặc vị thế. - Mỗi node phải có priority khác nhau và nên đặt
InpCloudNodeIdrõ ràng (ID auto đổi khi đổi thư mục terminal). Chi tiết và kịch bản failover.
Used when the same account + magic runs on several terminals/VPSes for redundancy. Leader = the alive node with the lowest InpCloudNodePriority (ties broken by the smaller node_id); alive = heartbeat within InpCloudHeartbeatTimeoutSec. CanTradeAsLeader() returns true when cloud sync is off, in the tester, or when the node is not a follower.
- Leader-gated: Init, Add,
CheckLotBalance, flash-crash fast balance, hedging, Tia, virtual TP, Global TP / SL / Clear Stuck, residue clean, Close all, and pushing the ticket map to the cloud. - Not leader-gated (checked in code):
CheckWeekendCloseAll,CheckWeekendBalance, the close-all branches ofCheckMaxDrawdownandCheckDailyLimit, clearing the cloud map when the local map becomes empty. All of these are off in pass58. - Fail-safe: never had a successful heartbeat → leader; both Cloudflare and MyApi failing for more than
2 × InpCloudHeartbeatTimeoutSec→ the node claims leadership so positions are not abandoned. - Every node needs a distinct priority and should set
InpCloudNodeIdexplicitly (the auto ID changes when the terminal folder changes). Details and failover scenarios.
Đọc tiếpFurther reading
- Config ổn định — từng giá trị của pass58 cho 1.42 b3.
- Tham số input — tham chiếu đầy đủ.
- Giải thích chiến lược · So sánh backtest · Rủi ro & lệnh kẹt.
- Stable config — every pass58 value for 1.42 b3.
- Input parameters — full reference.
- Strategy explained · Backtest comparison · Risk & stuck orders.