Gold Beat
Gold Beat
// 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
// 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 arrays
ArraySetAsSeries(highBuffer, true);
ArraySetAsSeries(lowBuffer, true);
ArraySetAsSeries(closeBuffer, true);
ArraySetAsSeries(emaBuffer, true);
if(UseRSIFilter) ArraySetAsSeries(rsiBuffer, true);
// Reset signals
buySignal = false;
sellSignal = 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"));
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Parse time settings from string inputs |
//+------------------------------------------------------------------+
void ParseTimeSettings()
{
// Get current date components
MqlDateTime timeStruct;
TimeToStruct(TimeCurrent(), timeStruct);
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);
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);
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if equity target has been reached
if(CheckEquityTarget())
return;
CheckForOpenPositions();
}
//+------------------------------------------------------------------+
//| Apply EMA filter to trading signals |
//+------------------------------------------------------------------+
void ApplyEMAFilter()
{
// Get current close price
double currentPrice = closeBuffer[0];
//+------------------------------------------------------------------+
//| Apply RSI filter to trading signals |
//+------------------------------------------------------------------+
void ApplyRSIFilter()
{
if(!UseRSIFilter) return;
//+------------------------------------------------------------------+
//| Manage trailing stop for open positions |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
if(!UseTrailingStop) return;
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;
}
//+------------------------------------------------------------------+
//| Check if target equity has been reached |
//+------------------------------------------------------------------+
bool CheckEquityTarget()
{
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
if(EnableDebug) {
Print("Target equity reached! Current: ", currentEquity,
" Target: ", targetEquity);
Print("EA trading stopped due to target equity being reached");
}
return false;
}
//+------------------------------------------------------------------+
//| Check if current time is within trading hours |
//+------------------------------------------------------------------+
bool IsWithinTradingHours()
{
datetime currentTime = TimeCurrent();
// 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;
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);
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);
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;
}
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;
}
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);
}
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 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(EnableDebug) {
Print("Equity-based lot sizing: Initial equity=", initialEquity,
" Current equity=", currentEquity,
" Ratio=", equityRatio,
" Scaled lot=", scaledLot);
}
return scaledLot;
}
return calculatedLot;
}
//+------------------------------------------------------------------+
//| Open a new position |
//+------------------------------------------------------------------+
bool OpenPosition(ENUM_ORDER_TYPE orderType, double volume, double stopLoss, double
takeProfit)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
// Send order
if(!OrderSend(request, result))
{
Print("OrderSend failed with error: ", GetLastError());
return false;
}