//+------------------------------------------------------------------+ //| sma9ema45crosstp.mq4 | //| Zubair | //| https://www.mql5.com | //+------------------------------------------------------------------+ // Expert Advisor parameters extern int fastMA = 9; // Period for the fast moving average extern int slowMA = 45; // Period for the slow moving average extern double lotSize = 0.05; // Fixed lot size for trades extern int takeProfit = 200; // Take profit distance in pips // Global variables int maCrossOver = 0; // Variable to store the moving average crossover signal // Initialization function int init() { return(0); } // Deinitialization function int deinit() { return(0); } // Entry point function int start() { // Calculate the moving averages double fastMAValue = iMA(NULL, 0, fastMA, 0, MODE_SMA, PRICE_CLOSE, 0); double slowMAValue = iMA(NULL, 0, slowMA, 0, MODE_EMA, PRICE_CLOSE, 0); // Determine the moving average crossover signal if (fastMAValue > slowMAValue) { maCrossOver = 1; // Fast MA above slow MA (bullish signal) } else if (fastMAValue < slowMAValue) { maCrossOver = -1; // Fast MA below slow MA (bearish signal) } else { maCrossOver = 0; // No crossover } // Open trades based on the crossover signal if (maCrossOver > 0 && OrdersTotal() == 0) { // Calculate take profit price double takeProfitPrice = Ask + takeProfit * Point; // Open a buy trade with take profit int ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, 0, 0, takeProfitPrice, "Buy Order", 0, 0, Green); if (ticket > 0) { // Trade opened successfully Print("Buy trade opened with ticket: ", ticket); } else { // Failed to open trade Print("Failed to open buy trade. Error code: ", GetLastError()); } } else if (maCrossOver < 0 && OrdersTotal() == 0) { // Calculate take profit price //double takeProfitPrice = Bid - takeProfit * Point; // Open a sell trade with take profit // int ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, 0, 0, takeProfitPrice, "", 0, 0, clrRed); if (ticket > 0) { // Trade opened successfully Print("Sell trade opened with ticket: ", ticket); } else { // Failed to open trade Print("Failed to open sell trade. Error code: ", GetLastError()); } } return(0); } void OnTick() { // Calculate the SMA and EMA values double sma9 = iMA(NULL, 0, 9, 0, MODE_SMA, PRICE_CLOSE, 0); double ema45 = iMA(NULL, 0, 45, 0, MODE_EMA, PRICE_CLOSE, 0); // Check for a negative crossover if (sma9 < ema45) { // Close all buy orders for (int i = OrdersTotal() - 1; i >= 0; i--) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderType() == OP_BUY) { OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 0, Red); } } } } }