31 October 2024
#include <Trade/Trade.mqh>
// Initialize trading class
CTrade trade;
// Input parameters for moving averages
input int fastLength = 10; // Fast MA period
input int slowLength = 20; // Slow MA period
// Input parameters for position management
input double tp1Percent = 2.0; // Take Profit 1 (% from entry price)
input double tp2Percent = 4.0; // Take Profit 2 (% from entry price)
input double tp3Percent = 6.0; // Take Profit 3 (% from entry price)
input double initialStopLossPercent = 2.0; // Initial Stop-Loss (% from entry price)
input double trailingStopPercent = 3.0; // Trailing Stop (% from current price)
input double positionSize = 0.1; // Position size in lots
// Global variables
double fastMA[], slowMA[];
double entryPrice, currentStopLoss;
double tp1Price, tp2Price, tp3Price;
bool trailingStopActive = false;
// Indicator handles
int fastMAHandle;
int slowMAHandle;
// Initialization function
int OnInit()
{
// Create handles for moving averages
fastMAHandle = iMA(_Symbol, PERIOD_CURRENT, fastLength, 0, MODE_EMA, PRICE_CLOSE);
slowMAHandle = iMA(_Symbol, PERIOD_CURRENT, slowLength, 0, MODE_EMA, PRICE_CLOSE);
if (fastMAHandle == INVALID_HANDLE || slowMAHandle == INVALID_HANDLE)
{
Print("Failed to get indicator handles.");
return INIT_FAILED;
}
return INIT_SUCCEEDED;
}
// OnTick function - main strategy logic
void OnTick()
{
// Copy moving average values into the arrays
if (CopyBuffer(fastMAHandle, 0, 0, 1, fastMA) <= 0 || CopyBuffer(slowMAHandle, 0, 0, 1, slowMA) <= 0)
{
Print("Failed to copy buffer data.");
return;
}
// Retrieve the current position
double currentPositionSize = PositionGetDouble(POSITION_VOLUME);
int positionType = (currentPositionSize > 0) ? POSITION_TYPE_BUY : (currentPositionSize < 0) ? POSITION_TYPE_SELL : -1;
// Long condition: Fast MA crosses above Slow MA
if (fastMA[0] > slowMA[0] && positionType !=
else if (currentPositionSize < 0) // Short position
{
double newStopLoss = SymbolInfoDouble(_Symbol, SYMBOL_ASK) * (1 + trailingStopPercent / 100);
if (newStopLoss < currentStopLoss)
{
currentStopLoss = newStopLoss;
trade.PositionModify(_Symbol, currentStopLoss, 0);
}
}
}
// Deinitialization function
void OnDeinit(const int reason)
{
// Release indicator handles
IndicatorRelease(fastMAHandle);
IndicatorRelease(slowMAHandle);
}
🚀