Please edit your post and use the code button (Alt+S) when pasting code.
EDIT your original post, please do not just post the code properly in a new post.
Topics concerning MT4 and MQL4 have their own section.
In future please post in the correct section.
I will move your topic to the MQL4 and Metatrader 4 section.

You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
In my code to detect a MA cross and only buy when two MAs cross, it somehow does not detect a cross but still goes on and starts a position. Furthermore, these positions start by being a 'Buy', then closing, then all positions after that are a 'Sell'. What am I doing wrong?
input double Lots = 0.1;
int TakeProfit = 40; // The take profit level (0 disable)
int MAGICNUM;
input int PeriodOne = 10; // The period for the first SMA
input int PeriodTwo = 20; // The period for the second SMA
double LotsOptimized()
{
double lot = Lots;
lot = NormalizeDouble(AccountFreeMargin()/1000.0,1);
if(lot<0.1) lot=0.1; //Ensure the minimal amount is 0.1 lots
return(lot);
}
int CheckForCross(double input1, double input2)
{
static int previous_direction = 0;
static int current_direction = 0;
// Up Direction = 1
if(input1 > input2){
current_direction = 1;
}
// Down Direction = 2
if(input1 < input2){
current_direction = 2;
}
// Detect a direction change
if(current_direction != previous_direction){
previous_direction = current_direction;
return (previous_direction);
} else {
return (0);
}
}
void OnTick()
{
int ticket, total;
double ShortTP, LongTP, shortSma, longSma;
shortSma = iMA(NULL, PERIOD_M1, PeriodOne, 0, MODE_SMMA, PRICE_CLOSE, 0);
longSma = iMA(NULL, PERIOD_M1, PeriodTwo, 0, MODE_SMMA, PRICE_CLOSE, 0);
int isCrossed = CheckForCross(shortSma, longSma);
total = OrdersTotal();
for(int pos=0;pos<total;pos++)
{
if(OrderSelect(pos,SELECT_BY_POS)==false) continue;
MAGICNUM = OrderMagicNumber();
}
ShortTP = Bid-(TakeProfit*Point);
LongTP = Ask+(TakeProfit*Point);
if(total = 0){
// Buy - Long position
if(isCrossed == 1){
ticket = OrderSend(Symbol(), OP_BUY, LotsOptimized(),Ask,5, 0, LongTP, "Double SMA Crossover",MAGICNUM,0);
TakeProfit = (0.1-(shortSma-longSma))*1000;
}
if(isCrossed ==2){
ticket = OrderSend(Symbol(), OP_SELL, LotsOptimized(),Bid,5, 0, ShortTP, "Double SMA Crossover",MAGICNUM,0);
TakeProfit = (0.1-(shortSma-longSma))*-1000;
}
}
}
Thank you so much!