I need you to develop an MT5 Expert Advisor (EA) in MQL5 specifically for BTCUSD, primarily trading on the 1-minute timeframe (M1).
The goal is to build a professional, rule-based automated trading system that trades strong impulsive BTCUSD moves in the direction of the trend, while using strict risk and money management.
The EA should NOT randomly buy or sell.
The basic sequence should be:
Trend → Impulse → Momentum confirmation → Entry → Risk-based position sizing → Trade management
The EA should be capable of trading both:
BUY/Bullish moves
SELL/Bearish moves
It should work across different market conditions and avoid trading when the market is too choppy or the signal quality is poor.
Primary execution timeframe:
M1 / 1-minute
The EA should also be capable of checking higher timeframes for trend confirmation:
M5
M15
Optional H1
All timeframe settings should be configurable.
For example:
UseM5TrendFilter = true/false
UseM15TrendFilter = true/false
UseH1TrendFilter = true/false
Use EMA alignment as one of the main trend filters.
Default:
EMA 9
EMA 21
EMA 50
Bullish trend:
EMA 9 > EMA 21 > EMA 50
and price should preferably be above EMA 50.
Bearish trend:
EMA 9 < EMA 21 < EMA 50
and price should preferably be below EMA 50.
The EA should NOT enter solely because of EMA alignment. EMA alignment is a directional filter.
The main strategy is based on identifying strong impulsive movements.
Use ATR on M1.
Default:
ATR Period = 14
Calculate:
Candle Body = ABS(Close - Open)
Candle Range = High - Low
An impulse candle should satisfy conditions such as:
Body >= ATR × ImpulseATRMultiplier
Default:
ImpulseATRMultiplier = 1.20
Also require a strong body relative to the total candle range.
Default:
MinimumBodyRatio = 0.65
For bullish impulses:
Close > Open
Large candle body
Body >= ATR × multiplier
Close near the upper portion of the candle
Preferably increased volume/tick volume
For bearish impulses:
Close < Open
Large candle body
Body >= ATR × multiplier
Close near the lower portion of the candle
Preferably increased volume/tick volume
All these parameters need to be adjustable.
Use available BTCUSD tick volume from the broker.
Compare current volume with the average volume over a configurable period.
Default:
VolumePeriod = 20
VolumeMultiplier = 1.30
Example:
Current volume >= Average volume × 1.30
If volume confirmation is enabled and the requirement isn't met, the EA should reject the trade.
Make the volume filter optional.
Use RSI as a momentum confirmation rather than a reversal signal.
Default:
RSI Period = 14
BUY:
RSI > 55
SELL:
RSI < 45
Do NOT use the logic:
RSI > 70 = automatically sell
RSI < 30 = automatically buy
The strategy is trying to participate in momentum, not automatically fade it.
All RSI levels should be adjustable.
Add an optional ADX filter to help avoid extremely weak/choppy markets.
Default:
ADX Period = 14
Minimum ADX = 20
Only allow trades when:
ADX >= MinimumADX
Make this filter optional.
I want two configurable entry modes.
MODE 1 — IMPULSE CLOSE
Wait for the impulse candle to close.
If all conditions are satisfied, enter in the direction of the impulse.
MODE 2 — BREAKOUT
For bullish setups:
Wait for price to break above the impulse candle high.
For bearish setups:
Wait for price to break below the impulse candle low.
Make this an input:
EntryMode:
0 = Candle Close
1 = Breakout
The EA should avoid entering after BTC has already moved too far away from the original signal.
Create an adjustable:
MaxEntryExtensionATR
Default:
0.50 ATR
If price has already extended beyond the allowed distance before entry, cancel the setup.
This is intended to prevent chasing extremely extended M1 candles.
I want a configurable scoring system.
Example:
Bullish EMA alignment = +2
Strong bullish impulse = +3
RSI confirmation = +1
Volume confirmation = +1
M5 bullish trend = +2
M15 bullish trend = +1
ADX confirmation = +1
Maximum score = 11.
Default minimum score:
7
The same logic should be reversed for SELL signals.
The minimum score must be adjustable.
This allows me to make the EA more selective or more aggressive during testing.
This is extremely important.
The EA must use percentage-based risk, NOT fixed lot sizes.
Default:
RiskPerTrade = 0.50%
The lot size should automatically be calculated using:
Account equity
Risk percentage
Stop-loss distance
Tick size
Tick value
Minimum lot
Maximum lot
Lot step
Broker symbol specifications
Do NOT hard-code BTCUSD contract specifications because different brokers can use different specifications.
Add:
MaximumDailyLoss = 2%
MaximumWeeklyLoss = 5%
MaximumDrawdown = 10%
If the daily loss limit is reached:
STOP OPENING NEW TRADES FOR THE REST OF THE DAY.
If weekly loss is reached:
STOP OPENING NEW TRADES UNTIL THE NEXT WEEK.
If maximum account drawdown is reached:
STOP THE EA FROM OPENING NEW TRADES.
These must be configurable.
Default:
MaxConsecutiveLosses = 3
After 3 consecutive losing trades:
Stop opening new trades.
Optionally use:
CooldownAfterLosses = 60 minutes
Do NOT increase the lot size after a loss.
The EA must NEVER:
Double the lot after a loss
Increase lot size to recover losses
Open progressively larger trades after losing
Use a recovery grid
Use unlimited averaging down
Every trade should calculate its risk independently.
Use dynamic ATR-based stop loss.
Default:
ATR Period = 14
SL ATR Multiplier = 1.50
The stop should also consider the structure of the impulse candle.
For BUY:
Stop should be below a logical bullish invalidation point, such as the impulse candle low, with an appropriate ATR-based buffer.
For SELL:
Stop should be above a logical bearish invalidation point, such as the impulse candle high, with an appropriate ATR-based buffer.
The final SL calculation should avoid stops that are unrealistically tight.
Use risk/reward based TP.
Default:
RiskReward = 2.0
Example:
If the trade risks $5:
TP should initially target approximately $10.
The risk/reward ratio must be adjustable.
Add optional break-even management.
Default:
UseBreakEven = true
BreakEvenAtR = 1.0
Once the trade reaches +1R, move the stop toward breakeven.
Allow an adjustable small offset so the trade can potentially cover costs.
Do not move to breakeven too early.
Add optional ATR-based trailing stop.
Default:
UseTrailingStop = true
TrailingATRMultiplier = 1.0
The trailing stop should follow the market while allowing reasonable M1 pullbacks.
Add optional partial closing.
Example:
UsePartialClose = false by default.
If enabled:
PartialCloseAtR = 1.5
PartialClosePercent = 50%
At +1.5R:
Close 50% of the position.
Allow the remaining position to continue using TP/trailing management.
Default:
MaxPositions = 1
I do NOT want the EA opening many positions from the same signal.
Also add:
OneTradePerImpulse = true
Once an impulse has been traded, don't repeatedly enter the same impulse.
After a position closes:
Default:
CooldownMinutes = 5
Do not immediately open another trade unless the cooldown has expired and a completely new valid setup exists.
Make it adjustable from 0–60 minutes.
Before entering a trade, check the current BTCUSD spread.
If spread is above the configured maximum:
DO NOT ENTER.
The maximum spread should be adjustable.
Add maximum allowed execution deviation.
If the requested execution price is significantly different from the acceptable price:
Reject the trade rather than chasing the market.
BTCUSD operates 24/7, so the EA should support 24-hour operation.
However, allow an optional trading-session filter.
Inputs:
UseTradingSession = true/false
StartTime
EndTime
If disabled, the EA can operate continuously.
The EA should distinguish between:
Bullish trend
Bearish trend
Choppy/sideways market
Bullish:
EMA alignment + bullish momentum.
Bearish:
EMA alignment + bearish momentum.
Choppy:
Weak trend, conflicting indicators, low directional movement.
In a choppy environment, preferably NO TRADE.
Add an optional daily profit target.
Example:
UseDailyProfitLock = false by default.
DailyProfitTarget = 3%
If enabled and the account reaches the daily profit target:
Stop opening new trades for the rest of the day.
This is a capital-protection feature, not a guaranteed profit target.
Add an emergency equity protection system.
If account drawdown reaches the configured maximum:
Stop opening trades
Optionally close EA-managed positions
Display a clear warning
Require a reset/new trading period before trading resumes
Use a unique Magic Number.
Example:
MagicNumber = 25092501
The EA should only manage positions that belong to its own Magic Number.
It must NOT accidentally modify manual trades or trades belonging to another EA.
For every trade, log:
Date/time
BUY/SELL
Entry price
Stop loss
Take profit
Lot size
Account equity
Risk percentage
ATR
RSI
ADX
Volume ratio
Signal score
Spread
Reason for entry
Reason for exit
Profit/loss
R multiple
Maximum favorable excursion if possible
Maximum adverse excursion if possible
Also log rejected signals and the reason.
Example:
"BUY rejected — score 6/7"
"SELL rejected — spread too high"
"BUY rejected — daily loss limit reached"
This will make debugging and optimization much easier.
If possible, create an MT5 dashboard showing:
BTCUSD
Current timeframe
Current trend
Current ATR
RSI
ADX
Volume ratio
Signal score
Current spread
Account balance
Account equity
Risk per trade
Today's P/L
Today's number of trades
Consecutive losses
Current position
EA status
Example:
TREND: BULLISH
SIGNAL SCORE: 8/11
ATR: ...
RSI: 61
ADX: 27
VOLUME: 1.45x
SPREAD: ...
RISK: 0.50%
DAILY P/L: +1.2%
STATUS: WAITING FOR ENTRY
Please make these configurable:
GENERAL
Symbol
Timeframe
Magic Number
Enable/Disable EA
TREND
Fast EMA
Medium EMA
Slow EMA
M5 filter
M15 filter
H1 filter
IMPULSE
ATR period
Impulse ATR multiplier
Minimum body ratio
Minimum close location
Volume period
Volume multiplier
MOMENTUM
RSI period
Bullish RSI level
Bearish RSI level
ADX period
Minimum ADX
ENTRY
Entry mode
Minimum signal score
Maximum entry extension
RISK
Risk per trade
Maximum daily loss
Maximum weekly loss
Maximum drawdown
Maximum consecutive losses
TRADE MANAGEMENT
SL ATR multiplier
Risk/reward
Break-even
Break-even R
Trailing stop
Trailing ATR multiplier
Partial close
Partial close percentage
SAFETY
Maximum positions
One trade per impulse
Cooldown
Maximum spread
Maximum deviation
SESSION
Trading session enabled/disabled
Start time
End time
Please write the EA using clean, modular MQL5 code.
Separate functions for:
Trend detection
Impulse detection
Volume analysis
RSI analysis
ADX analysis
Signal scoring
Risk calculation
Lot calculation
Entry
SL calculation
TP calculation
Break-even
Trailing stop
Partial close
Daily loss protection
Drawdown protection
Trade logging
Use proper error handling.
After every trade operation, verify the trade-server response/retcode rather than assuming the operation succeeded.
I want the EA designed specifically so it can be tested and optimized in MT5 Strategy Tester.
Test:
Bull markets
Bear markets
Sideways markets
High volatility
Low volatility
Different BTCUSD conditions
Different spreads
Slippage
Different periods
Do NOT optimize only for maximum historical profit.
The goal is:
Robustness + controlled drawdown + realistic execution + consistent behavior.
Use out-of-sample/forward testing after optimization to reduce overfitting.
I understand that no EA can guarantee a specific weekly/monthly return.
I do NOT want the code artificially optimized to produce a certain percentage such as 30% every week.
I want the strategy to have:
Controlled risk
Strict money management
Clear entry rules
Clear exit rules
Limited drawdown
No martingale
No revenge trading
No unlimited positions
Robust testing
Adjustable parameters
The EA should essentially operate like this:
NEW M1 CANDLE
↓
Check EA enabled
↓
Check daily/weekly loss limits
↓
Check maximum drawdown
↓
Check consecutive losses
↓
Check cooldown
↓
Check existing positions
↓
Check spread
↓
Determine M5/M15/H1 trend
↓
Determine M1 trend
↓
Calculate ATR
↓
Detect bullish/bearish impulse
↓
Check RSI
↓
Check volume
↓
Check ADX
↓
Calculate signal score
↓
If score is below minimum → NO TRADE
↓
Check price isn't overextended
↓
Determine entry
↓
Calculate structural/ATR stop
↓
Calculate TP
↓
Calculate position size based on account risk
↓
Check maximum exposure
↓
Execute trade
↓
Monitor trade
↓
Break-even / trailing / partial close
↓
Close at SL/TP/management rule
↓
Record result
↓
Cooldown
↓
Wait for NEW setup
The most important requirement is that the EA should trade high-quality impulsive BTCUSD moves rather than continuously trading every M1 candle.