Termos de Referência
أريد تدقيقا مهنيا كاملا، وتصحيحا، وتحسين، وتحسينا لمستشار BTCUSD الخبير الحالي مع الحفاظ على جميع الوظائف الناجحة حاليا.
لا تعيد بناء EA من الصفر ولا تزيل الوحدات العاملة بدون دليل إحصائي يثبت أن ذلك يحسن النظام ككل.
الهدف الأساسي هو إنشاء نظام تداول BTCUSD أكثر دقة ومتانة وتكيفا وتحكم في المخاطر، مستهدفا معدل فوز بين 85٪–95٪ حيث يكون ذلك ممكنا إحصائيا ومستداما، دون الإفراط في التكييف أو التلاعب بملف المخاطرة/المكافأة أو تقليل عدد الصفقات بشكل مصطنع.
1. تدقيق كامل للكود
قم بإجراء تدقيق كامل لكود مصدر MQL5 بالكامل وحدد:
-
أخطاء وتحذيرات في التجميع.
-
أخطاء منطقية.
-
أخطاء مخفية في وقت التشغيل.
-
ظروف تداول متضاربة.
-
منطق مكرر أو مكرر.
-
حسابات أسعار خاطئة.
-
أخطاء في حساب حجم النقطة/البندق.
-
تصحيح مشكلات مزدوجة.
-
أخطاء في حساب وقف الخسارة وأخذ الأرباح.
-
أخطاء في تحديد حجم الموضع.
-
أخطاء إدارة أوامر الانتظار (pending orders).
-
مشاكل في توافق الحوط والشبكات.
-
تعارضات الأرقام السحرية.
-
أخطاء في مقبض المؤشر.
-
فشل CopyBuffer/CopyRates.
-
مخاطر خارج النطاق في الصفوف.
-
مخاطر القسمة بالصفر.
-
قيم NaN/INF.
-
عدم معالجة بيانات السوق بشكل كاف.
-
أخطاء تنفيذ الوسيط.
-
تنفيذ إشارة مكررة.
-
مشاكل تنفيذ تشبه حالة العرق.
-
تسربات مقبض الموارد/المؤشر.
-
معالجة مفرطة في OnTick.
يجب أن يتم تجميع النسخة النهائية بشكل نظيف دون تحذيرات أو أخطاء حرجة.
2. الحفاظ على العمارة القائمة
يحتوي EA الحالي بالفعل على عدة أنظمة تداول وحماية.
لا تستبدل النظام بأكمله باستراتيجية جديدة.
اتبع عملية التطوير هذه:
حلل → قياس → تحديد نقاط الضعف → تحسين → الاختبار → التحقق من صحته.
يجب أن يكون لكل تعديل سبب موثق ونتائج قابلة للقياس قبل أو بعد.
3. تحليلات التجارة الكاملة
طور تحليلات مفصلة قادرة على تحديد سبب كل من:
-
نجح النجاح في الصفقة.
-
فشل فقدان التجارة.
-
خرجت التجارة مبكرا جدا.
-
دخل التجارة متأخرا جدا.
-
الإشارة المرفوضة كانت ستنجح.
-
في النهاية، فشل الإشارة المقبولة.
سجل السياق الكامل للسوق عند كل قرار.
4. معرف الإشارة الفريد
خصص معرف إشارة فريد لكل فرصة تداول.
لكل إشارة، سجل:
الوقت، الاتجاه، الوحدة، سعر الدخول، نسبة ATR، الفارق، نظام السوق، الاتجاه، الزخم، الحجم، مؤشر RSI، درجة MTF، درجة الثقة، ظروف SMC، ظروف السيولة، وقف الخسارة، جني الربح، سبب الخروج، والنتيجة النهائية.
يجب أن تجعل هذه المعلومات كل صفقة قابلة للتفسير بالكامل.
5. Dynamic Signal Confidence Engine
Improve the existing confidence-scoring system into a dynamic 0–100 scoring engine.
Potential components should include:
-
Primary trend.
-
Multi-timeframe alignment.
-
Momentum strength.
-
Market structure.
-
ATR.
-
Volume.
-
RSI.
-
Candle-close strength.
-
Price location.
-
Support/Resistance.
-
Liquidity Sweep.
-
BOS/CHoCH.
-
FVG.
-
Order Blocks.
-
Market Regime.
-
Stop Loss quality.
-
Risk/Reward.
-
Spread conditions.
-
Volatility conditions.
Weights must be determined through statistical testing rather than arbitrary assumptions.
6. Module-Level Performance Analysis
Evaluate every strategy/module independently, including where applicable:
Main Trend, H1 Fast Trend, M10 Fast Trend, M5 Fast Trend, Momentum, Shallow Pullback, Range Reversion, Range Breakout, Failed Breakout, Candle Patterns, Fast U-Turn, Counter-Trend, Internal Structure, SMC/FVG, and any other existing modules.
Calculate for every module:
Win Rate, Profit Factor, Expectancy, Average Win, Average Loss, Maximum Drawdown, Consecutive Losses, Total Trades, and Risk-Adjusted Performance.
Identify statistically useful and statistically weak modules.
7. Advanced Market Regime Engine
Improve market classification so the EA can dynamically identify:
Strong Bull Trend, Weak Bull Trend, Strong Bear Trend, Weak Bear Trend, Range, Compression, Breakout, High Volatility, Low Volatility, Exhaustion, and Reversal Risk.
Only strategies suitable for the detected regime should be permitted.
The same entry logic should not be blindly applied to every market condition.
8. Multi-Timeframe Architecture
Improve hierarchical multi-timeframe analysis.
Suggested architecture:
D1/W1 = Macro Context.
H4 = Primary Trend.
H1 = Trend Structure.
M15 = Entry Confirmation.
M10/M5 = Entry Timing.
M1 = Diagnostics or precision execution only when justified.
Prevent irrational conflicts between different timeframes.
9. Entry Timing Optimization
Prevent late entries after a move is already exhausted.
Evaluate:
Entry Efficiency.
Distance from Swing.
Distance from ATR Expansion.
Candle Extension.
Momentum Exhaustion.
Distance from Support/Resistance.
Do not chase excessively extended price movements.
10. Pre-Entry Reversal Detection
Improve detection of:
Divergence.
Momentum Loss.
Failed Breakout.
Liquidity Sweep.
Rejection Candles.
Double Tops/Bottoms.
Micro Structure Shift.
BOS/CHoCH.
Volume Exhaustion.
The objective is to avoid entering near the end of a move.
11. Dynamic Stop Loss
Stop Loss should be based on market conditions rather than an arbitrary fixed distance.
Consider:
Market Structure + ATR + Swing High/Low + Liquidity Level + Volatility + Spread Buffer.
Prevent:
Excessively tight stops.
Unnecessarily wide stops.
Stops placed directly inside obvious liquidity zones.
12. Dynamic Take Profit
Develop adaptive profit targets based on:
Support/Resistance.
Previous High/Low.
ATR.
Market Structure.
Liquidity Targets.
Risk/Reward.
Support TP1/TP2/Runner management when testing demonstrates an advantage.
13. Advanced Profit Protection
Improve multi-stage profit protection using statistically validated combinations of:
Break-Even.
Partial Close.
Profit Lock.
Trailing Stop.
Structure-Based Trailing.
ATR Trailing.
Momentum-Based Exit.
A substantially profitable trade should not unnecessarily turn into a major loss.
14. Intelligent Early Exit
Continuously reassess whether the original trade thesis remains valid.
Possible exit triggers include:
Trend Flip.
Momentum Collapse.
Opposite BOS.
Opposite CHoCH.
Strong Rejection.
Failed Continuation.
Loss of MTF Alignment.
Market Regime Change.
However, early exits must be statistically validated to prevent excessive premature closures.
15. Re-Entry Protection
Implement dynamic cooldown mechanisms following:
Loss.
Stop Loss.
False Breakout.
Trend Flip.
Extreme Volatility.
Prevent the EA from repeatedly entering from the same stale signal.
16. Dynamic Risk Management
Develop position sizing based on:
Account Balance/Equity.
Stop Distance.
Volatility.
Confidence Score.
Market Regime.
Recent Strategy Performance.
Apply strict maximum risk limits.
17. Account Protection
Implement or improve:
Daily Loss Limit.
Daily Drawdown Limit.
Maximum Consecutive Losses.
Maximum Open Risk.
Maximum Spread.
Emergency Stop.
Equity Protection.
Abnormal Volatility Protection.
Connection/Data Protection.
18. Spread and Slippage Intelligence
Because BTCUSD spreads can change substantially, record and analyze actual spread behavior.
Block entries when:
Spread is abnormally high.
Expected slippage is excessive.
Liquidity conditions are poor.
19. Prevent Overtrading
The objective is not to maximize the number of trades.
Use the principle:
Quality > Quantity.
A trade should only be executed when it has a statistically supported edge.
20. Prevent Overfitting
Never optimize the strategy on the entire historical dataset and then claim the result is validated.
Use separate:
Training Data.
Validation Data.
Out-of-Sample Data.
Walk-Forward Analysis.
Monte Carlo Testing.
Forward Demo Testing.
21. Different Market Conditions
Test the strategy across:
Bull Markets.
Bear Markets.
Sideways Markets.
High Volatility.
Low Volatility.
Flash Moves.
Weekend Trading.
Major News/Event Conditions.
Results must not depend on one favorable historical period.
22. Real-Tick Backtesting
Use the highest-quality MT5 Strategy Tester data available, preferably:
Every Tick Based on Real Ticks.
Include realistic:
Spread.
Commission.
Slippage.
Execution assumptions.
23. Performance Metrics
Do not judge the system by Win Rate alone.
Measure:
Win Rate.
Profit Factor.
Expected Payoff.
Expectancy.
Maximum Drawdown.
Relative Drawdown.
Recovery Factor.
Sharpe Ratio.
Average R Multiple.
Average Win/Loss Ratio.
Consecutive Wins/Losses.
Total Trades.
Monthly Stability.
24. Target Win Rate
The desired target is an 85%–95% Win Rate, if it can be achieved genuinely and sustainably.
Do not artificially achieve this target by:
Using extremely small Take Profits.
Using excessively large Stop Losses.
Eliminating nearly all trading opportunities.
Martingale.
Unlimited Grid systems.
Dangerous Averaging Down.
Ignoring unrealized losses.
The target Win Rate must be supported by healthy Profit Factor, Expectancy, and Drawdown statistics.
25. Statistically Meaningful Sample Size
Do not claim an 85%–95% success rate based on 10 or 20 trades.
Use a statistically meaningful number of trades across different periods and market regimes.
26. Automatic Losing-Trade Analysis
After every losing trade, save a market-state snapshot explaining:
Why was the trade entered?
Which conditions approved it?
What changed after entry?
Was the Stop Loss appropriate?
Was the entry late?
Was the trend assessment wrong?
Was the Market Regime unsuitable?
The system must not automatically modify itself because of one losing trade.
27. Shadow Mode
Every new strategy, filter, or experimental feature should initially run in Shadow Mode.
Record:
Trades it would have opened.
Hypothetical results.
Signals it would have blocked.
Performance impact.
Only activate the feature for live execution after collecting sufficient evidence.
28. Before/After Comparison
Every significant modification must produce a comparison:
Before vs. After
including:
Trades.
Win Rate.
Net Profit.
Profit Factor.
Drawdown.
Expectancy.
Do not accept a modification merely because it increases Win Rate while severely damaging other performance metrics.
29. Eliminate Look-Ahead Bias
Verify that every trading decision uses only information genuinely available at that exact point in time.
No future candles or future-confirmed structures may influence historical entry decisions.
30. Prevent Repainting
Verify that indicators and structural signals used for trading decisions do not repaint after future data becomes available.
31. Trading State Machine
Where beneficial, organize the trading lifecycle as:
IDLE → SETUP → CONFIRMATION → READY → ENTRY → MANAGE → EXIT → COOLDOWN
This should reduce duplicate entries and conflicting module behavior.
32. Central Trade Manager
Where architecturally appropriate, route strategy requests through a centralized Trade Manager responsible for:
Risk Validation.
Position Limits.
Conflict Resolution.
Order Execution.
SL/TP Management.
Position Management.
Emergency Protection.
Individual modules should generate opportunities, while centralized logic controls whether execution is permitted.
33. Signal Conflict Resolution
If one module produces BUY while another produces SELL, implement explicit conflict-resolution logic.
A trade must not win arbitration simply because its module reaches ExecuteEntry first in the program execution sequence.
34. Code Performance Optimization
Reduce unnecessary OnTick workload.
Implement:
Shared Data Caching.
Efficient Indicator Updates.
Reduced CopyRates/CopyBuffer Calls.
New-Bar Processing for modules that do not require tick-level calculations.
Efficient object and memory management.
35. Self-Health Monitoring
Improve the Self-Health Monitor to supervise:
Price Feed.
Indicator Handles.
Missing Bars.
Spread.
Trade Server.
Order Errors.
Abnormal Execution.
Time Synchronization.
Critical failures should temporarily disable new entries until conditions normalize.
36. Professional Logging System
Implement structured logging levels:
INFO.
SIGNAL.
TRADE.
WARNING.
ERROR.
DEBUG.
Heavy diagnostic logging should be optionally disabled during normal live operation.
37. Clean Trading Dashboard
Display only decision-critical information to reduce visual clutter:
Current Market Regime.
H4 Trend.
MTF Consensus.
Current Signal.
Confidence Score.
Spread.
ATR.
Open Position.
Floating P/L.
Daily P/L.
Drawdown.
Trading Status.
Reason for Blocking Entry.
38. Rejected Signal Analytics
Do not merely record "No Trade."
Record the exact rejection reason:
Rejected: Spread.
Rejected: MTF.
Rejected: Weak Momentum.
Rejected: Market Regime.
Rejected: Late Entry.
Rejected: Risk.
Rejected: Structure Conflict.
Measure how many signals each filter blocks and whether those blocked signals would actually have succeeded or failed.
39. Feature Attribution and Ablation Testing
Determine the actual contribution of every major feature.
Test scenarios such as:
System without RSI.
System without Volume.
System without SMC.
System without MTF.
System without Market Regime.
System without individual filters.
This is required to determine whether each feature genuinely adds predictive value.
40. Controlled Parameter Optimization
Optimize only meaningful parameters.
Do not optimize hundreds of variables simultaneously.
Use economically and logically reasonable ranges rather than simply selecting the historically best combination.
41. Walk-Forward Optimization
Optimize parameters on one historical segment and test them on the next unseen segment.
Repeat the process through multiple market periods to measure adaptability and parameter stability.
42. Monte Carlo Stress Testing
Stress-test the strategy by simulating:
Different trade sequences.
Higher Slippage.
Higher Spread.
Execution Delays.
Different distributions of wins and losses.
The strategy should remain viable without depending on a lucky historical trade sequence.
43. Robustness Testing
Change important parameters by approximately ±5% and ±10%.
If performance collapses after a minor parameter change, treat the configuration as potentially overfitted.
Prefer broad parameter stability zones over isolated optimization peaks.
44. Validated Preset Profiles
After testing, create separate profiles where appropriate: .set
Conservative.
Balanced.
Aggressive.
No preset should be approved until independently validated.
45. Final Acceptance Criteria
Do not consider the new version superior simply because its Net Profit is higher.
The improved system should demonstrate:
Better stability.
Controlled Drawdown.
Strong Profit Factor.
Positive Expectancy.
Sufficient Trade Count.
Robust Out-of-Sample Performance.
Stable Walk-Forward Results.
Acceptable Forward Demo Results.
No critical execution errors.
46. Evidence-Based Development Principle
Do not keep adding indicators, filters, and conditions merely to make the EA more complicated.
The development process must follow:
Evidence-Based Strategy Development.
Every filter, strategy, parameter, and modification must demonstrate measurable value.
If a feature does not improve robustness or risk-adjusted performance, it should not be activated merely because it sounds theoretically useful.
FINAL OBJECTIVEThe final objective is to produce a robust, explainable, testable, and maintainable BTCUSD Expert Advisor that:
Selects high-quality opportunities.
Rejects statistically weak setups.
Adapts to changing market regimes.
Improves entry timing.
Reduces avoidable losses.
Protects profitable positions.
Controls account risk.
Avoids overtrading.
Avoids overfitting.
Maintains complete diagnostic records.
The desired target is an 85%–95% Win Rate, but this target must never override risk management or statistical integrity.
The true acceptance standard must be:
High Win Rate + Positive Expectancy + Strong Profit Factor + Controlled Drawdown + Robust Out-of-Sample Performance.
The system must successfully pass:
Backtest → Out-of-Sample Test → Walk-Forward Test → Monte Carlo Stress Test → Forward Demo Test
before being considered suitable for live trading