Automated Stop Loss & Take Profit EA Based on Your Risk-Reward Settings
I asked ChatGPT (GPTs) to create a handy MT4 tool (Expert Advisor – EA) that automatically sets stop loss (SL) or take profit (TP) according to a predefined risk-reward ratio.
With this EA, when you set either a stop loss or a take profit, it will automatically calculate and set the corresponding TP or SL based on your desired risk-reward ratio.
GPT Used:EA Creator
Development Request & Results
I made some minor adjustments, but the generated EA was almost ready to use as is.
First Request
I requested an EA with the following specifications:
# Parameters
- Lot Size: Number of lots per order
- Risk-Reward Ratio: Defines the profit target as a multiple of the risk (e.g., 2:1)
- Additional necessary parameters if required
# Functionality
- If a position has only a take profit set, the EA will automatically set a stop loss based on:
- Expected profit calculation from entry price and TP
- Risk-reward ratio to determine the stop-loss price
- If a position has only a stop loss set, the EA will automatically set a take profit based on:
- Expected loss calculation from entry price and SL
- Risk-reward ratio to determine the take-profit price
ChatGPT Output (First Version of the EA)
The following MQL4 code was generated, implementing an EA that sets stop loss and take profit based on a defined risk-reward ratio. The EA monitors open positions and adjusts SL/TP accordingly.
//+------------------------------------------------------------------+ //| RiskRewardEA | //| Copyright 2023, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property strict input double LotSize = 0.1; // Lot size input double RiskRewardRatio = 2.0; // Risk-reward ratio input int Slippage = 3; // Slippage input int MagicNumber = 0; // Magic number //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS)) { // Check and modify orders CheckModifyOrders(); } } } //+------------------------------------------------------------------+ //| Function to check and modify SL/TP | //+------------------------------------------------------------------+ void CheckModifyOrders() { double entryPrice = OrderOpenPrice(); double tp = OrderTakeProfit(); double sl = OrderStopLoss(); double newSl, newTp; if(tp > 0 && sl == 0) { double expectedProfit = MathAbs(tp - entryPrice); double risk = expectedProfit / RiskRewardRatio; if(OrderType() == OP_BUY) newSl = NormalizeDouble(entryPrice - risk, Digits); else if(OrderType() == OP_SELL) newSl = NormalizeDouble(entryPrice + risk, Digits); OrderModify(OrderTicket(), entryPrice, newSl, tp, 0, clrRed); } if(tp == 0 && sl > 0) { double expectedLoss = MathAbs(entryPrice - sl); double reward = expectedLoss * RiskRewardRatio; if(OrderType() == OP_BUY) newTp = NormalizeDouble(entryPrice + reward, Digits); else if(OrderType() == OP_SELL) newTp = NormalizeDouble(entryPrice - reward, Digits); OrderModify(OrderTicket(), entryPrice, sl, newTp, 0, clrGreen); } }
説明
- パラメータ
LotSize
: 注文ロット数RiskRewardRatio
: リスクリワード比率Slippage
: スリッページMagicNumber
: マジックナンバー
- 初期化 (
OnInit
)
- 特に初期化は必要ありません。
- ティックイベント (
OnTick
)
- 保有中のポジションをチェックし、逆指値または指値を設定します。
- ポジションのチェックおよび設定 (
CheckModifyOrders
)
- 保有中のポジションに対して、以下の条件に基づいて逆指値または指値を設定します。
- 指値のみが設定されている場合
- エントリー価格と指値より見込み利益を計算し、リスクリワード比率を使用して逆指値を設定します。
- 逆指値のみが設定されている場合
- エントリー価格と逆指値より見込み損益を計算し、リスクリワード比率を使用して指値を設定します。
このEAは、保有中のポジションを監視し、指定されたリスクリワード比率に基づいて逆指値および指値を設定します。MetaTrader 4のエディタにこのコードをコピーし、コンパイルして実行することで動作を確認できます。
Second Request (Improvements)
- Removed unnecessary parameters (only keeping RiskRewardRatio).
- Introduced a check interval parameter to reduce CPU load (checks positions at a defined time interval instead of every tick).
- Initialized
newSl
andnewTp
to zero to avoid undefined behavior.
Third Request (Precision Improvement)
Used
MarketInfo
to dynamically determine the number of decimal places (Digits
) based on the symbol of the order.
Final Version of the EA (Risk-Reward Manager)
//+——————————————————————+
//| EA_RiskRewardManager |
//| Copyright 2023, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+——————————————————————+
property strict
input double RiskRewardRatio = 2.0; // Risk-reward ratio
input int CheckIntervalSeconds = 60; // Position check interval (in seconds)
input int Slippage = 3; // Slippage
datetime lastCheckTime = 0;
//+——————————————————————+
//| Expert tick function |
//+——————————————————————+
void OnTick() {
datetime currentTime = TimeCurrent();
if (currentTime – lastCheckTime >= CheckIntervalSeconds) {
lastCheckTime = currentTime;
for(int i = OrdersTotal() - 1; i >= 0; i--) {
if(OrderSelect(i, SELECT_BY_POS)) {
CheckModifyOrders();
}
}
}
}
//+——————————————————————+
//| Function to check and modify SL/TP |
//+——————————————————————+
void CheckModifyOrders() {
string symbol = OrderSymbol();
int digits = (int)MarketInfo(symbol, MODE_DIGITS);
double entryPrice = OrderOpenPrice();
double tp = OrderTakeProfit();
double sl = OrderStopLoss();
double newSl = 0, newTp = 0;
if(tp > 0 && sl == 0) {
double expectedProfit = MathAbs(tp – entryPrice);
double risk = expectedProfit / RiskRewardRatio;
if(OrderType() == OP_BUY)
newSl = NormalizeDouble(entryPrice - risk, digits);
else if(OrderType() == OP_SELL)
newSl = NormalizeDouble(entryPrice + risk, digits);
OrderModify(OrderTicket(), entryPrice, newSl, tp, 0, clrRed);
}
if(tp == 0 && sl > 0) {
double expectedLoss = MathAbs(entryPrice – sl);
double reward = expectedLoss * RiskRewardRatio;
if(OrderType() == OP_BUY)
newTp = NormalizeDouble(entryPrice + reward, digits);
else if(OrderType() == OP_SELL)
newTp = NormalizeDouble(entryPrice - reward, digits);
OrderModify(OrderTicket(), entryPrice, sl, newTp, 0, clrGreen);
}
}
📥 Download the Indicator
🚀 Get instant access to the Higher Timeframe MA & High/Low Indicator!
You can download the created EA below. While basic functionality has been tested, we cannot compensate for any losses incurred from its use. Please use it at your own risk and verify its operation thoroughly.
👉 Download Now (Unlock content to access the file)
📢 Looking for More Trading Tools?
Explore my blog for more free MT4 indicators and trading strategies!
👉 Visit FX Trading Gym
🚀 Thank You for Using Our Tools! A Small Favor to Ask 🚀
Thank you so much for choosing our FX indicators and tools!
To support your success in FX trading, we’ve carefully selected some services that can help you achieve better results.
If you find them useful, we’d greatly appreciate your support.
Your participation will not only motivate us but also help us continue to develop even better tools for you in the future!
💼 Increase Your Profits with an Overseas FX Account!
🌍 Exness Account – The Broker I Trust the Most!
- Industry-low spreads to reduce trading costs
- Fully compatible with MT4/MT5, perfect for automated trading (EA)
- Instant withdrawals for smooth fund management
👉 Open an Exness Account Now (Special Offer)
💸 Reduce Trading Costs with Cashback from Overseas FX Accounts!
🚀 TariTali – High Cashback Rates That Make a Difference!
- Maximize savings with high-rate cashback on every trade
- Supports a wide range of MT4/MT5 brokers, ideal for EAs
- Real-time tracking of your cashback history
- Fast withdrawals to domestic bank accounts
👉 Cut Your Trading Costs Smartly with TariTali!
🔥 Money Charger – The New Standard for Forex Cashback!
- Automatic cashback on every trade → The more you trade, the more you earn!
- Industry-leading cashback rates for maximum profit efficiency
- Simple registration with instant cashback available
- Supports multiple brokers, giving you flexible account choices
👉 Start Earning Cashback with Money Charger Today!
More details: Complete Guide to Forex Cashback
🤖 Accelerate Your Profits with Automated Trading Systems (EAs)!
🔥 Introducing High-Performance EAs I’ve Developed
- Poundeur (HL Band M15 for GJ) → The best choice for stable profits
- BBHL Band H1 for EJ & BBHL Band H1 for AJ → Excellent performance even in high-volatility markets
👉 Discover Our Profitable MT4 EAs for FX Traders
📊 Check Out the Most Popular EAs!
- Handpicked EAs trusted by many traders
- Performance records and profit data are publicly available
👉 See the Top-Ranked EAs Now
コメント