0% found this document useful (0 votes)
293 views14 pages

Gold Beat

The document is a script for a trading expert advisor (EA) named 'Gold Beat' written in MQL5, designed for trading gold. It includes customizable parameters for trading strategies such as take profit, stop loss, and risk management, along with indicators like ATR, EMA, and RSI for signal filtering. The EA manages trading sessions, checks equity targets, and implements trailing stops while providing debugging options for monitoring performance.

Uploaded by

sarwarcryp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
293 views14 pages

Gold Beat

The document is a script for a trading expert advisor (EA) named 'Gold Beat' written in MQL5, designed for trading gold. It includes customizable parameters for trading strategies such as take profit, stop loss, and risk management, along with indicators like ATR, EMA, and RSI for signal filtering. The EA manages trading sessions, checks equity targets, and implements trailing stops while providing debugging options for monitoring performance.

Uploaded by

sarwarcryp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 14

//+------------------------------------------------------------------+

//| Gold Beat.mq5 |


//+------------------------------------------------------------------+
#property copyright "SM Sarwar Hossain"
#property version "1.00"
#property strict

// Input parameters
input int Amplitude = 2; // Amplitude for trend calculation
input int ChannelDeviation = 2; // Channel Deviation multiplier
input int ATR_Period = 100; // ATR period (now customizable)
input double TakeProfit = 100; // Take Profit in points
input double StopLoss = 300; // Stop Loss in points
input double InitialLotSize = 0.1; // Initial trading lot size
input bool UseFixedLot = false; // Use fixed lot size (true) or
dynamic based on equity (false)
input double RiskPercent = 1.0; // Risk percent when using risk-
based sizing
input int MagicNumber = 12345; // Magic number for trades
input bool AllowBuy = true; // Allow buy trades
input bool AllowSell = true; // Allow sell trades
input bool EnableDebug = true; // Enable debugging messages

// Target equity and time parameters


input double TargetEquityPercent = 5.0; // Target equity profit in percent
input string StartTime = "08:00"; // EA start time (HH:MM)
input string EndTime = "16:00"; // EA end time (HH:MM)

// EMA filter parameters


input int EMA_Period = 200; // EMA period for trade filter

// RSI filter parameters


input bool UseRSIFilter = true; // Enable RSI filter
input int RSI_Period = 14; // RSI period
input double RSI_Overbought = 70; // RSI overbought level
input double RSI_Oversold = 30; // RSI oversold level

// Trailing stop parameters


input bool UseTrailingStop = true; // Enable trailing stop
input double TrailingStopPoints = 5.0; // Trailing stop distance in
points

// Dynamic lot sizing parameters


input bool UseEquityBasedLotScaling = true; // Enable automatic lot scaling
based on equity changes

// Global variables
int trend = 0;
int prevTrend = 0;
int nextTrend = 0;
double maxLowPrice = 0;
double minHighPrice = 0;
double up = 0;
double down = 0;
double atrHigh = 0;
double atrLow = 0;
double halfTrend = 0;
bool buySignal = false;
bool sellSignal = false;
int handle_atr;
int handle_ema;
int handle_rsi;

// Price buffers
double highBuffer[];
double lowBuffer[];
double closeBuffer[];
double emaBuffer[];
double rsiBuffer[];

// Equity tracking
double initialEquity = 0; // Starting equity when EA first runs
double targetEquity = 0;
bool targetReached = false;
datetime startTimeSeconds = 0;
datetime endTimeSeconds = 0;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize ATR indicator with customizable period
handle_atr = iATR(_Symbol, PERIOD_CURRENT, ATR_Period);
if(handle_atr == INVALID_HANDLE)
{
Print("Failed to create handle for ATR indicator");
return INIT_FAILED;
}

// Initialize EMA indicator


handle_ema = iMA(_Symbol, PERIOD_CURRENT, EMA_Period, 0, MODE_EMA,
PRICE_CLOSE);
if(handle_ema == INVALID_HANDLE)
{
Print("Failed to create handle for EMA indicator");
return INIT_FAILED;
}

// Initialize RSI indicator if enabled


if(UseRSIFilter)
{
handle_rsi = iRSI(_Symbol, PERIOD_CURRENT, RSI_Period, PRICE_CLOSE);
if(handle_rsi == INVALID_HANDLE)
{
Print("Failed to create handle for RSI indicator");
return INIT_FAILED;
}
}

// Initialize arrays
ArraySetAsSeries(highBuffer, true);
ArraySetAsSeries(lowBuffer, true);
ArraySetAsSeries(closeBuffer, true);
ArraySetAsSeries(emaBuffer, true);
if(UseRSIFilter) ArraySetAsSeries(rsiBuffer, true);

// Initialize variables with current prices


int copied = CopyLow(_Symbol, PERIOD_CURRENT, 0, 2, lowBuffer);
if(copied > 0)
maxLowPrice = lowBuffer[1];

copied = CopyHigh(_Symbol, PERIOD_CURRENT, 0, 2, highBuffer);


if(copied > 0)
minHighPrice = highBuffer[1];

// Reset signals
buySignal = false;
sellSignal = false;

// Record initial equity and calculate target


initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
targetEquity = initialEquity * (1 + TargetEquityPercent / 100.0);
targetReached = false;

if(EnableDebug) {
Print("Gold Beat EA initialized successfully");
Print("Initial equity: ", initialEquity);
Print("Target equity: ", targetEquity);
Print("Initial lot size: ", InitialLotSize);
Print("Equity-based lot scaling: ", (UseEquityBasedLotScaling ? "Enabled" :
"Disabled"));
}

// Parse time inputs


ParseTimeSettings();

return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Parse time settings from string inputs |
//+------------------------------------------------------------------+
void ParseTimeSettings()
{
// Get current date components
MqlDateTime timeStruct;
TimeToStruct(TimeCurrent(), timeStruct);

// Parse start time


int startHour = (int)StringToInteger(StringSubstr(StartTime, 0, 2));
int startMinute = (int)StringToInteger(StringSubstr(StartTime, 3, 2));

// Parse end time


int endHour = (int)StringToInteger(StringSubstr(EndTime, 0, 2));
int endMinute = (int)StringToInteger(StringSubstr(EndTime, 3, 2));

// Create datetime for start and end


MqlDateTime startStruct, endStruct;
startStruct.year = timeStruct.year;
startStruct.mon = timeStruct.mon;
startStruct.day = timeStruct.day;
startStruct.hour = startHour;
startStruct.min = startMinute;
startStruct.sec = 0;

endStruct.year = timeStruct.year;
endStruct.mon = timeStruct.mon;
endStruct.day = timeStruct.day;
endStruct.hour = endHour;
endStruct.min = endMinute;
endStruct.sec = 0;

startTimeSeconds = StructToTime(startStruct);
endTimeSeconds = StructToTime(endStruct);

// Handle overnight sessions


if(endTimeSeconds <= startTimeSeconds)
endTimeSeconds += 24*60*60; // Add one day

if(EnableDebug) {
Print("Trading session: ", TimeToString(startTimeSeconds, TIME_MINUTES),
" to ", TimeToString(endTimeSeconds, TIME_MINUTES));
}
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Release indicator handles
if(handle_atr != INVALID_HANDLE)
IndicatorRelease(handle_atr);

if(handle_ema != INVALID_HANDLE)
IndicatorRelease(handle_ema);

if(UseRSIFilter && handle_rsi != INVALID_HANDLE)


IndicatorRelease(handle_rsi);

if(EnableDebug) Print("Gold Beat EA deinitialized");


}

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if equity target has been reached
if(CheckEquityTarget())
return;

// Check if we're within trading hours


if(!IsWithinTradingHours())
return;

// Update price arrays


if(!UpdatePriceArrays())
return;

// Reset signals before calculation


buySignal = false;
sellSignal = false;

// Calculate indicators and check for signals


if(CalculateHalfTrend())
{
// Apply EMA filter to signals
ApplyEMAFilter();

// Apply RSI filter if enabled


if(UseRSIFilter)
ApplyRSIFilter();

if(EnableDebug && (buySignal || sellSignal))


{
Print("Trend: ", trend, " PrevTrend: ", prevTrend);
Print("BuySignal: ", buySignal, " SellSignal: ", sellSignal);
Print("Current price: ", closeBuffer[0], " EMA: ", emaBuffer[0]);
if(UseRSIFilter) Print("RSI: ", rsiBuffer[0]);
}

CheckForOpenPositions();
}

// Manage trailing stop if enabled


if(UseTrailingStop)
ManageTrailingStop();
}

//+------------------------------------------------------------------+
//| Apply EMA filter to trading signals |
//+------------------------------------------------------------------+
void ApplyEMAFilter()
{
// Get current close price
double currentPrice = closeBuffer[0];

// Filter buy signals - only valid if price is above EMA


if(buySignal && currentPrice <= emaBuffer[0])
{
if(EnableDebug) Print("Buy signal filtered out - price below EMA");
buySignal = false;
}

// Filter sell signals - only valid if price is below EMA


if(sellSignal && currentPrice >= emaBuffer[0])
{
if(EnableDebug) Print("Sell signal filtered out - price above EMA");
sellSignal = false;
}
}

//+------------------------------------------------------------------+
//| Apply RSI filter to trading signals |
//+------------------------------------------------------------------+
void ApplyRSIFilter()
{
if(!UseRSIFilter) return;

// Get current RSI value


double currentRSI = rsiBuffer[0];

// Filter buy signals - only valid if RSI is not overbought


if(buySignal && currentRSI >= RSI_Overbought)
{
if(EnableDebug) Print("Buy signal filtered out - RSI overbought");
buySignal = false;
}

// Filter sell signals - only valid if RSI is not oversold


if(sellSignal && currentRSI <= RSI_Oversold)
{
if(EnableDebug) Print("Sell signal filtered out - RSI oversold");
sellSignal = false;
}
}

//+------------------------------------------------------------------+
//| Manage trailing stop for open positions |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
if(!UseTrailingStop) return;

double trailingStop = TrailingStopPoints * SymbolInfoDouble(_Symbol,


SYMBOL_POINT);

for(int i = PositionsTotal() - 1; i >= 0; i--)


{
ulong ticket = PositionGetTicket(i);
if(ticket != 0)
{
if(PositionGetInteger(POSITION_MAGIC) == MagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
double currentSL = PositionGetDouble(POSITION_SL);
double currentPrice = (PositionGetInteger(POSITION_TYPE) ==
POSITION_TYPE_BUY) ?
SymbolInfoDouble(_Symbol, SYMBOL_BID) :
SymbolInfoDouble(_Symbol, SYMBOL_ASK);

double newSL;
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
newSL = currentPrice - trailingStop;
if(newSL > currentSL || currentSL == 0)
{
ModifyPosition(ticket, newSL,
PositionGetDouble(POSITION_TP));
}
}
else // POSITION_TYPE_SELL
{
newSL = currentPrice + trailingStop;
if(newSL < currentSL || currentSL == 0)
{
ModifyPosition(ticket, newSL,
PositionGetDouble(POSITION_TP));
}
}
}
}
}
}

//+------------------------------------------------------------------+
//| Modify position with new SL and TP |
//+------------------------------------------------------------------+
bool ModifyPosition(ulong ticket, double newSL, double newTP)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};

request.action = TRADE_ACTION_SLTP;
request.position = ticket;
request.symbol = _Symbol;
request.sl = newSL;
request.tp = newTP;

if(!OrderSend(request, result))
{
Print("Failed to modify position #", ticket, " Error: ", GetLastError());
return false;
}

if(EnableDebug) Print("Position #", ticket, " modified successfully");


return true;
}

//+------------------------------------------------------------------+
//| Check if target equity has been reached |
//+------------------------------------------------------------------+
bool CheckEquityTarget()
{
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);

// If target already reached previously


if(targetReached)
return true;

// Check if current equity meets or exceeds target


if(currentEquity >= targetEquity) {
targetReached = true;

if(EnableDebug) {
Print("Target equity reached! Current: ", currentEquity,
" Target: ", targetEquity);
Print("EA trading stopped due to target equity being reached");
}

// Close all open positions


CloseAllPositions();
return true;
}

return false;
}

//+------------------------------------------------------------------+
//| Check if current time is within trading hours |
//+------------------------------------------------------------------+
bool IsWithinTradingHours()
{
datetime currentTime = TimeCurrent();

// Get just the time part of current datetime


MqlDateTime timeStruct;
TimeToStruct(currentTime, timeStruct);

// Create a time that has current date but with hours/minutes from settings
MqlDateTime currentDateStruct;
currentDateStruct.year = timeStruct.year;
currentDateStruct.mon = timeStruct.mon;
currentDateStruct.day = timeStruct.day;

// Recreate start/end times for today


MqlDateTime startStruct, endStruct;
TimeToStruct(startTimeSeconds, startStruct);
TimeToStruct(endTimeSeconds, endStruct);

currentDateStruct.hour = startStruct.hour;
currentDateStruct.min = startStruct.min;
currentDateStruct.sec = 0;
datetime todayStartTime = StructToTime(currentDateStruct);

currentDateStruct.hour = endStruct.hour;
currentDateStruct.min = endStruct.min;
currentDateStruct.sec = 0;
datetime todayEndTime = StructToTime(currentDateStruct);

// Handle overnight sessions


if(todayEndTime <= todayStartTime)
todayEndTime += 24*60*60; // Add one day

// Check if current time is within range


bool withinHours = (currentTime >= todayStartTime && currentTime <=
todayEndTime);

if(!withinHours && EnableDebug) {


Print("Outside trading hours: ", TimeToString(currentTime, TIME_MINUTES),
" not between ", TimeToString(todayStartTime, TIME_MINUTES),
" and ", TimeToString(todayEndTime, TIME_MINUTES));
}

return withinHours;
}

//+------------------------------------------------------------------+
//| Close all open positions for this EA |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket != 0)
{
if(PositionGetInteger(POSITION_MAGIC) == MagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};

request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.symbol = _Symbol;
request.volume = PositionGetDouble(POSITION_VOLUME);

// Close with opposite order type


if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
request.type = ORDER_TYPE_SELL;
}
else
{
request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
request.type = ORDER_TYPE_BUY;
}

request.deviation = 10;
request.magic = MagicNumber;
request.comment = "Gold Beat EA - Close on target";
request.type_filling = ORDER_FILLING_FOK;

if(!OrderSend(request, result))
{
Print("Failed to close position #", ticket, " Error: ",
GetLastError());
}
else if(EnableDebug)
{
Print("Position #", ticket, " closed successfully");
}
}
}
}
}

//+------------------------------------------------------------------+
//| Update price arrays with latest data |
//+------------------------------------------------------------------+
bool UpdatePriceArrays()
{
// Get recent price data - need to get enough data for calculations
if(CopyHigh(_Symbol, PERIOD_CURRENT, 0, Amplitude + 10, highBuffer) <= 0)
{
Print("Failed to copy high price data");
return false;
}

if(CopyLow(_Symbol, PERIOD_CURRENT, 0, Amplitude + 10, lowBuffer) <= 0)


{
Print("Failed to copy low price data");
return false;
}

if(CopyClose(_Symbol, PERIOD_CURRENT, 0, Amplitude + 10, closeBuffer) <= 0)


{
Print("Failed to copy close price data");
return false;
}

// Get EMA values


if(CopyBuffer(handle_ema, 0, 0, 10, emaBuffer) <= 0)
{
Print("Failed to copy EMA buffer data");
return false;
}

// Get RSI values if enabled


if(UseRSIFilter)
{
if(CopyBuffer(handle_rsi, 0, 0, 10, rsiBuffer) <= 0)
{
Print("Failed to copy RSI buffer data");
return false;
}
}

return true;
}

//+------------------------------------------------------------------+
//| Calculate HalfTrend values |
//+------------------------------------------------------------------+
bool CalculateHalfTrend()
{
// Get ATR values
double atr_buffer[];
ArraySetAsSeries(atr_buffer, true);
if(CopyBuffer(handle_atr, 0, 0, 1, atr_buffer) != 1)
{
Print("Failed to copy ATR buffer data");
return false;
}

double atr2 = atr_buffer[0] / 2;


double dev = ChannelDeviation * atr2;

// Find highest and lowest prices


int highestIndex = ArrayMaximum(highBuffer, 0, Amplitude);
int lowestIndex = ArrayMinimum(lowBuffer, 0, Amplitude);
double highPrice = highBuffer[highestIndex];
double lowPrice = lowBuffer[lowestIndex];

// Calculate moving averages


double highma = 0, lowma = 0;
for(int i = 0; i < Amplitude; i++)
{
highma += highBuffer[i];
lowma += lowBuffer[i];
}
highma /= Amplitude;
lowma /= Amplitude;

// Save previous trend


prevTrend = trend;
// HalfTrend logic calculation
if(nextTrend == 1)
{
maxLowPrice = MathMax(lowPrice, maxLowPrice);

if(highma < maxLowPrice && closeBuffer[0] < lowBuffer[1])


{
trend = 1;
nextTrend = 0;
minHighPrice = highPrice;
}
}
else // nextTrend == 0
{
minHighPrice = MathMin(highPrice, minHighPrice);

if(lowma > minHighPrice && closeBuffer[0] > highBuffer[1])


{
trend = 0;
nextTrend = 1;
maxLowPrice = lowPrice;
}
}

// Calculate up and down levels


if(trend == 0) // Uptrend
{
if(prevTrend != 0 && prevTrend == 1) // Trend change from down to up
{
up = down;
buySignal = true; // Buy signal on trend change
if(EnableDebug) Print("BUY SIGNAL TRIGGERED");
}
else
{
up = MathMax(maxLowPrice, up);
}

atrHigh = up + dev;
atrLow = up - dev;
halfTrend = up;
}
else // trend == 1 (Downtrend)
{
if(prevTrend != 1 && prevTrend == 0) // Trend change from up to down
{
down = up;
sellSignal = true; // Sell signal on trend change
if(EnableDebug) Print("SELL SIGNAL TRIGGERED");
}
else
{
down = MathMin(minHighPrice, down);
}

atrHigh = down + dev;


atrLow = down - dev;
halfTrend = down;
}

return true;
}

//+------------------------------------------------------------------+
//| Check for open positions and manage trading signals |
//+------------------------------------------------------------------+
void CheckForOpenPositions()
{
// Check if we have a buy signal and no open long positions
if(buySignal && AllowBuy)
{
if(!HasOpenPosition(POSITION_TYPE_BUY))
{
if(EnableDebug) Print("Attempting to open BUY position");
double sl = (StopLoss > 0) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) -
StopLoss * SymbolInfoDouble(_Symbol, SYMBOL_POINT) : 0;
double tp = (TakeProfit > 0) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) +
TakeProfit * SymbolInfoDouble(_Symbol, SYMBOL_POINT) : 0;
OpenPosition(ORDER_TYPE_BUY, CalculateLotSize(StopLoss), sl, tp);
}
else if(EnableDebug) Print("BUY position already exists");
}

// Check if we have a sell signal and no open short positions


if(sellSignal && AllowSell)
{
if(!HasOpenPosition(POSITION_TYPE_SELL))
{
if(EnableDebug) Print("Attempting to open SELL position");
double sl = (StopLoss > 0) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) +
StopLoss * SymbolInfoDouble(_Symbol, SYMBOL_POINT) : 0;
double tp = (TakeProfit > 0) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) -
TakeProfit * SymbolInfoDouble(_Symbol, SYMBOL_POINT) : 0;
OpenPosition(ORDER_TYPE_SELL, CalculateLotSize(StopLoss), sl, tp);
}
else if(EnableDebug) Print("SELL position already exists");
}
}

//+------------------------------------------------------------------+
//| Check if there is an open position of given type |
//+------------------------------------------------------------------+
bool HasOpenPosition(ENUM_POSITION_TYPE posType)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket != 0)
{
if(PositionGetInteger(POSITION_MAGIC) == MagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol &&
PositionGetInteger(POSITION_TYPE) == posType)
{
return true;
}
}
}
return false;
}

//+------------------------------------------------------------------+
//| Calculate appropriate lot size based on risk or equity settings |
//+------------------------------------------------------------------+
double CalculateLotSize(double stopLossPoints)
{
// If fixed lot size is selected and equity-based scaling is disabled
if(UseFixedLot && !UseEquityBasedLotScaling)
return InitialLotSize;

// If using equity-based lot scaling


if(UseEquityBasedLotScaling)
{
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double equityRatio = currentEquity / initialEquity;

// Scale lot size based on equity ratio


double scaledLot = InitialLotSize * equityRatio;

// Apply min/max lot size constraints


double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

// Round to the nearest lot step


scaledLot = MathFloor(scaledLot / lotStep) * lotStep;
scaledLot = MathMax(minLot, MathMin(maxLot, scaledLot));

if(EnableDebug) {
Print("Equity-based lot sizing: Initial equity=", initialEquity,
" Current equity=", currentEquity,
" Ratio=", equityRatio,
" Scaled lot=", scaledLot);
}

return scaledLot;
}

// Using risk-based lot sizing


if(stopLossPoints <= 0) return InitialLotSize; // Use default if no SL

// Calculate based on risk percent


double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double pointValue = tickValue * SymbolInfoDouble(_Symbol, SYMBOL_POINT) /
tickSize;
double riskAmount = balance * RiskPercent / 100.0;

// Calculate lot size based on risk


double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double calculatedLot = MathFloor(riskAmount / (stopLossPoints * pointValue) /
lotStep) * lotStep;

// Apply min/max lot size constraints


double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
calculatedLot = MathMax(minLot, MathMin(maxLot, calculatedLot));

return calculatedLot;
}

//+------------------------------------------------------------------+
//| Open a new position |
//+------------------------------------------------------------------+
bool OpenPosition(ENUM_ORDER_TYPE orderType, double volume, double stopLoss, double
takeProfit)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};

// Fill trade request structure


request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = volume;
request.type = orderType;
request.price = (orderType == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol,
SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
request.sl = stopLoss;
request.tp = takeProfit;
request.deviation = 10;
request.magic = MagicNumber;
request.comment = "Gold Beat EA";
request.type_filling = ORDER_FILLING_FOK;

// Send order
if(!OrderSend(request, result))
{
Print("OrderSend failed with error: ", GetLastError());
return false;
}

Print("Order placed successfully. Ticket: ", result.order, " Volume: ",


volume);
return true;
}

You might also like