명시
Project Overview: Advanced Adaptive Grid EA
This document outlines the development specifications for a sophisticated MQL4 Expert Advisor. The EA is designed to be a fully featured, institutional-grade trading tool employing an adaptive grid strategy with advanced risk management and user control.
Core Features
-
Advanced Risk Control:
-
Equity Protection: Automatically closes all trades and halts trading if drawdown exceeds a user-defined percentage of the account balance.
-
Adaptive Lot Sizing: Automatically calculates lot sizes based on account equity, a fixed value, or a risk percentage per trade.
-
ATR-Based Stop Loss: Sets dynamic stop losses based on market volatility using the Average True Range (ATR) indicator.
-
Margin Limit: Prevents new trades if the used margin percentage exceeds a specified limit.
-
Smarter Grid System:
-
Adaptive Grid Spacing: Dynamically adjusts the distance between grid orders using ATR or Bollinger Bands, widening the grid in volatile markets and tightening it in calm markets.
-
Asymmetric Spacing: Allows for different grid spacing for buy and sell trades.
-
Intelligent Exit Logic:
-
Partial Profit-Taking: Closes a portion of a trade at a preliminary take profit level (TP1), letting the remainder run.
-
Equity-Based Trailing Basket: Trails a stop loss for the entire basket of trades (buys or sells) based on the total floating profit, locking in gains as the basket becomes more profitable.
-
On-Chart Control & Transparency:
-
Quick Control Panel: Interactive buttons on the chart to immediately close all buys, close all sells, close all trades, or pause/resume new trading.
-
Expanded Dashboard: A comprehensive real-time display of account balance, equity, margin usage, floating P/L for buys and sells, current drawdown percentage, and EA status.
-
Dynamic Market Adaptability:
-
Dynamic Slippage Handling: Automatically increases allowed slippage during periods of high volatility (e.g., news events) to ensure order execution.
-
News & Session Filters: Avoids trading during high-impact news events (requires external URL) and outside of specified trading sessions.
-
Analysis & Optimization:
-
Detailed Trade Logs: Exports a detailed CSV log of every trading decision (order open, close, modify), including the reason, for easy performance review and optimization.
Part 1: EA Settings (Global extern Variables)
These inputs provide full control over the EA's behavior.
-
General Settings
-
MagicNumber: int - Unique identifier for the EA's trades.
-
TradeComment: string - Custom comment for trades.
-
Risk Management
-
LotSizing_Mode: enum - (EQUITY_BASED, FIXED_LOT, RISK_PERCENT)
-
Equity_Per_Lot: double - (e.g., 10000) Dollars of equity per 1.0 lot.
-
Lot_Size: double - Lot size to use(fixed,Equity percentage)
-
Risk_Percent_Per_Trade: double - Risk % of balance for SL calculation if mode is RISK_PERCENT.
-
Max_Drawdown_Percent: double - The drawdown % of balance at which to close all trades and stop.
-
Stop_Trading_After_DD: bool - If true, the EA will not trade again after hitting the max drawdown.
-
Max_Margin_Usage_Percent: double - Maximum allowed margin level % before new trades are blocked.
-
ATR_SL_Period: int - Period for the ATR indicator for stop loss calculation.
-
ATR_SL_Multiplier: double - Multiplier for the ATR value to set the stop loss distance.
-
Grid Strategy
-
Grid_Spacing_Mode: enum - (ATR_BASED, BOLLINGER_BANDS, FIXED_POINTS)
-
Grid_ATR_Period: int - Period for the ATR indicator for grid spacing.
-
Grid_ATR_Multiplier_Buy: double - Multiplier for ATR to determine buy grid spacing.
-
Grid_ATR_Multiplier_Sell: double - Multiplier for ATR to determine sell grid spacing.
-
Grid_Fixed_Points: int - Grid spacing in points if mode is FIXED_POINTS.
-
Exit Strategy
-
Enable_Partial_Close: bool - Master switch for partial closing.
-
Partial_Close_TP1_Points: int - Profit in points to trigger the first partial close.
-
Partial_Close_Percent: double - Percentage of the trade to close at TP1 (e.g., 50.0).
-
Enable_Equity_Trail: bool - Master switch for basket equity trailing.
-
Equity_Trail_Start_Profit: double - Amount of profit in account currency to activate the trail.
-
Equity_Trail_Distance: double - Amount of profit to give back before the trail stops out the basket.
-
Filters & Slippage
-
Enable_Session_Filter: bool - Enable trading only during specific hours.
-
Session_Start_Hour, Session_End_Hour: int - Trading session hours (server time).
-
Base_Slippage: int - Normal slippage in points.
-
Volatility_Slippage_Multiplier: double - Multiplier for slippage during high volatility.
-
Volatility_ATR_Threshold: double - ATR value (as % of price) to trigger higher slippage.
-
Logging & Dashboard
-
Enable_CSV_Log: bool - Enable writing detailed logs to a CSV file.
-
CSV_Log_Filename: string - Filename for the log.
Part 2: Program Structure
-
OnInit(): Initializes the EA. Creates the on-chart dashboard and control panel buttons. Opens the CSV file for logging if enabled.
-
OnDeinit(): Cleans up resources. Deletes all chart objects and closes the CSV file.
-
OnTick(): The main execution loop. The logic must be ordered carefully:
-
Check if trading is globally stopped.
-
Check for and handle any button clicks from the control panel.
-
Run all safety checks: Max Drawdown, Margin Limit, Session Filter.
-
Run all exit logic for existing trades: Equity Trailing, Partial Closing.
-
Run all management for existing trades: Apply ATR-based Stop Losses.
-
Run logic for placing new grid orders if conditions are met.
-
Update the on-chart dashboard with the latest information.
-
OnChartEvent(...): Handles user interaction with the on-chart control panel buttons.
Part 3: Helper Function Implementation
This EA will be composed of many specialized functions to keep the code clean and manageable.
-
Risk & Lot Size Functions: CheckMaxDrawdown(), CalculateLotSize(), IsMarginLevelOK().
-
Grid & Order Placement Functions: CalculateGridSpacing(), PlaceNewGridOrders().
-
Trade Management Functions: ManageOpenTrades(), ApplyATRStopLossToAll(), HandlePartialClosing(), HandleEquityTrailing().
-
Filter Functions: IsInTradingSession().
-
Dashboard & Control Functions: CreateDashboard(), UpdateDashboard(), CreateControlPanel(), HandleButtonClicks().
-
Logging Functions: InitializeCSVLog(), LogTradeAction(...).
-
Utility Functions: CloseAllByDirection(...), GetBasketProfit(...), GetCurrentDrawdownPercent().