Need help for a simple crossover code
Hello, i'm new in MT4 editor and on this forum. I need some help to correct a code. I'm trying to code a simple crossover script that send a single buy order when the SMA20 cross over the SMA100, and that close the trade when the SMA100 crossover the SMA20. when I Backtest the code on a chart, the script work well on the beginning, there is indeed a buy order that is triggered when the SMA20 crosses above the SMA100. However, when the SMA100 crosses above the SMA20, the trade does not close. Can someone help me to correct this code, to ensure that the trade closes when the SMA100 goes above the SMA20?
- MACD - Oscillators - Technical Indicators - Price Charts, Technical and Fundamental Analysis
- MACD - Oscillators - Indicators - Charts - MetaTrader 5 for Android
- MACD - Oscillators - Indicators - Chart - MetaTrader 5 for iPhone
Greg MK: I'm trying to code a simple crossover script
double SlowMovingAverage = iMA(NULL,0,100,0,MODE_SMA,PRICE_CLOSE,0); double FastMovingAverage = iMA(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,0);
You only have the current values. For a cross, you need current and previous.
double aPrev = …(i+1), aCurr = …(i), bPrev = …(i+1), bCurr = …(i); bool wasUp = aPrev > bPrev, isUp = aCurr > bCurr, isCross = isUp != wasUp;
void OnTick() { //string variable signal string signal =""; //SMA double SlowMovingAverage = iMA(NULL,0,100,0,MODE_SMA,PRICE_CLOSE,0); double PrevSlowMovingAverage = iMA(NULL,0,100,0,MODE_SMA,PRICE_CLOSE,1); double FastMovingAverage = iMA(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,0); double PrevFastMovingAverage = iMA(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,1); { if ((PrevFastMovingAverage < PrevSlowMovingAverage) &&(FastMovingAverage > SlowMovingAverage)) { Comment ("BUY"); signal="buy"; } if ((PrevFastMovingAverage > PrevSlowMovingAverage) &&(FastMovingAverage < SlowMovingAverage)) { Comment ("SELL"); signal="sell"; } } if (signal=="buy" && OrdersTotal()==0) { OrderSend(Symbol(),OP_BUY,0.10,Ask,3,0,0,NULL,0,0,Green); } if (signal=="sell") { OrderClose(OrderTicket(),OrderLots(),Ask,5); } }Hre is the new code, still doesn"t work. there is always a buy order that is triggered when the SMA20 crosses above the SMA100. However, when the SMA100 goes above the SMA20, the trade does not close.