trades placed by EA when they should not

 
I am experiencing an issue. When I place the EA on my chart it buys or sells even when it should not. after the initial trade it makes imeadiatly when its placed on the chart, it begins running normal. I have a poor internet connection here and if I lose connection and then it comes back it will place a trade. I dont understand why this is happening. Glad I'm testing all this with a demo account. What might be the issue that causes the EA to make a trade when being initialized on the chart?
 
SirFency I dont understand why this is happening.
Do you really expect an answer? There are no mind readers here and our crystal balls are cracked. We can't see your broken code.
 
William Roeder:
Do you really expect an answer? There are no mind readers here and our crystal balls are cracked. We can't see your broken code.

I didnt think it was a code issue I figured it was a metatrader issue.

//+------------------------------------------------------------------+
//|                                                   TrendRider.mq4 |
//|                                               Erick_Fenstermaker |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Erick_Fenstermaker"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

double fastMovingAverage;
double lastFastMovingAverage;
double slowMovingAverage;
double lastSlowMovingAverage;

int extern fastPeriod = 20;
int extern slowPeriod = 200;

double newDiff;
double oldDiff;
int extern history = 1; //how many candles do you want to look back to decide if there is a trend
double extern buffer = 0.00025; //how much space do you want between the slow moving average and the fast moving average

double lotMax = MarketInfo(Symbol(), MODE_MAXLOT);
double lotMin = MarketInfo(Symbol(), MODE_MINLOT);

double extern takeProfit = 100;
double extern stopLoss = 5000;
int extern pip = 7;

double pips;
double ticket;


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   if(isNewCandle()==true)
   {
      if(upTrend()==true)
      buy();
      
      if(downTrend()==true)
      sell();
   }
}
//+------------------------------------------------------------------+
// Functions
//+------------------------------------------------------------------+

//Funtion to check for a new candle each tick
bool isNewCandle()
{
   static datetime savedCandleTime;
      if(Time[0]==savedCandleTime)
      return (false);
      else
      savedCandleTime=Time[0];
      return (true);
}

//Funtion that looks for a growing downward trend
bool downTrend()
{
bool diff = false;

fastMovingAverage = iMA(NULL,0,fastPeriod,0,MODE_SMA,PRICE_CLOSE,0);
lastFastMovingAverage = iMA(NULL,0,fastPeriod,0,MODE_SMA,PRICE_CLOSE,history);
slowMovingAverage = iMA(NULL,0,slowPeriod,0,MODE_SMA,PRICE_CLOSE,0);
lastSlowMovingAverage = iMA(NULL,0,slowPeriod,0,MODE_SMA,PRICE_CLOSE,history);

newDiff = (slowMovingAverage - fastMovingAverage);
oldDiff = (lastSlowMovingAverage - lastFastMovingAverage);
newDiff = newDiff - buffer;

if(newDiff > oldDiff && newDiff > 0 && oldDiff > 0)
diff = true;

Print("DownTrend "+"new diff : "+(string)newDiff+" old diff :" +(string)oldDiff+" diff :"+(string)diff);
return (diff);
}

//Funtion that looks for a growing upward trend
bool upTrend()
{
fastMovingAverage = iMA(NULL,0,fastPeriod,0,MODE_SMA,PRICE_CLOSE,0);
lastFastMovingAverage = iMA(NULL,0,fastPeriod,0,MODE_SMA,PRICE_CLOSE,history);
slowMovingAverage = iMA(NULL,0,slowPeriod,0,MODE_SMA,PRICE_CLOSE,0);
lastSlowMovingAverage = iMA(NULL,0,slowPeriod,0,MODE_SMA,PRICE_CLOSE,history);

bool diff = false;
newDiff = (fastMovingAverage - slowMovingAverage);
oldDiff = (lastFastMovingAverage - lastSlowMovingAverage);
newDiff = newDiff - buffer;

if(newDiff > oldDiff && newDiff > 0 && oldDiff > 0)
diff = true;

Print("UpTrend "+"new diff : "+(string)newDiff+" old diff :" +(string)oldDiff+" diff :"+(string)diff);
return (diff);
}

//Function for buy send order
void buy()
{
   ticket = OrderSend(Symbol(),OP_BUY,pips(),Ask,30,Bid-stopLoss*_Point,Bid+takeProfit*_Point,"My order ",16384,0,clrBlue);
      if(ticket <= 0){
      RefreshRates();
         ticket = OrderSend(Symbol(),OP_BUY,pips(),Ask,30,Bid-stopLoss*_Point,Bid+takeProfit*_Point,"My order ",16384,0,clrBlue);
         Print("OrderSend Buy failed with error #", GetLastError()); 
         }else Print("OrderSend placed successfully");
}

//Function for sell send order
void sell()
{
   ticket = OrderSend(Symbol(),OP_SELL,pips(),Bid,30,Ask+stopLoss*_Point,Ask-takeProfit*_Point,"My order ",16384,0,clrRed);
      if(ticket <= 0){
         RefreshRates();
         ticket = OrderSend(Symbol(),OP_SELL,pips(),Bid,30,Ask+stopLoss*_Point,Ask-takeProfit*_Point,"My order ",16384,0,clrRed);
         Print("OrderSend Sell failed with error #", GetLastError()); 
         }else Print("OrderSend placed successfully");
}

//Function pips size
double pips()
{
   double ticketSize = MarketInfo(Symbol(),MODE_TICKSIZE);
   if(ticketSize == 0.00001 || ticketSize == 0.001)
   pips = ticketSize*10;
   else pips = ticketSize;
   if(pips <= lotMin)
   pips = lotMin;
   if(pips >= lotMax)
   pips = lotMax;
   return (pips)*pip;
}
 
  1. double lotMax = MarketInfo(Symbol(), MODE_MAXLOT);
    double lotMin = MarketInfo(Symbol(), MODE_MINLOT);
    Global and static variables work exactly the same way in MT4/MT5/C/C++.
    1. They are initialized once on program load.
    2. They don't update unless you assign to them.
    3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5, or MT4 with strict (which you should always use.)

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:

      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
    4. Unlike indicators, EAs are not reloaded on chart change so you must reinitialize them, if necessary.
                external static variable - MQL4 programming forum

  2. SirFency it buys or sells even when it should not.
    You have Print Statments in your trend functions. Haven't you examined the log when it opens "when it should not"?


  3. fastMovingAverage = iMA(NULL,0,fastPeriod,0,MODE_SMA,PRICE_CLOSE,0);
    lastFastMovingAverage = iMA(NULL,0,fastPeriod,0,MODE_SMA,PRICE_CLOSE,history);
    You are looking at the opening of bar zero and the close of bar one. Why do you think that your tests are anything but noise of one tick.
 
William Roeder:
  1. Global and static variables work exactly the same way in MT4/MT5/C/C++.
    1. They are initialized once on program load.
    2. They don't update unless you assign to them.
    3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5, or MT4 with strict (which you should always use.)

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:

      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
    4. Unlike indicators, EAs are not reloaded on chart change so you must reinitialize them, if necessary.
                external static variable - MQL4 programming forum

  2. You have Print Statments in your trend functions. Haven't you examined the log when it opens "when it should not"?


  3. You are looking at the opening of bar zero and the close of bar one. Why do you think that your tests are anything but noise of one tick.

thank you. I moved the minLot and maxLot variables so that they are updated each time the are used. I also changed my code to look at candle 1 and 2 in order to decide if there is a strong enough u or down swing. Hopefully this will eliminate the random order send issue.

Reason: