placing new order based off of previous order with OrdersHistoryTotal()

 
#include <CustomFunctions010.mqh>
int MN = 73;
int shortmaPeriod = 8;
int longmaPeriod = 200;
double maxRiskPerTrade = 0.01;
double lots = OrderLots();
int orderid;
int slippage = 10; 
static double longcurrentprice = Close[0] + (Point*40);
static double shortcurrentprice = Close[0] - (Point*40);
static double longSL = Close[0] - (Point*80);
static double shortSL = Close[0] + (Point*80);
int OnInit()
  {
   Alert("");
   Alert("The EA just started.");
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   Alert("");
   Alert("The EA just closed.");
  }

void OnTick()
{
 double ATR = NormalizeDouble(iATR(NULL,0,14,0),Digits); 
 double longentry = Ask;
 double shortentry = Bid;
// double longstopLossPrice = Bid - (Point*80);
 //double shortstopLossPrice = Ask + (Point*80);

if(!CheckIfOpenOrdersByMagicNumber(MN))
{
 
   {int orderid = OrderSend(NULL,OP_BUY, lotsize(maxRiskPerTrade,longentry,longSL),longentry,slippage,longSL,0,NULL,MN);}
    if (orderid < 0) Alert("order rejected. Order error: " + GetLastError()); 
 
}
for(int i = OrdersTotal()-1;i>=0;i--)
{ 
 if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
 {
  if(OrderType() == OP_BUY && OrderMagicNumber() == MN && ChartSymbol() == Symbol())
  { 
   if (Close[0] >= longcurrentprice)
   {
    longcurrentprice = Close[0] + (Point*40);   
    double newlongSL = Close[0] - (Point*80);
 
    bool ans = OrderModify(OrderTicket(),OrderOpenPrice(),newlongSL,0,0);
    if (ans == true)
    {
     Alert("order modified");
    }          
   }
  }
  else if (OrderType() == OP_SELL && OrderMagicNumber() == MN && ChartSymbol() == Symbol())
  {
   if (Close[0] <= shortcurrentprice) 
   {
    shortcurrentprice = Close[0] - (Point*40);   
    double newshortSL = Close[0] + (Point*80);
    
    bool ans = OrderModify(OrderTicket(),OrderOpenPrice(),newshortSL,0,0);
    if (ans == true)
    {
     Alert("order modified");
    } 
   }
  }
 }
}

for(int i = OrdersHistoryTotal()-1;i>=0;i--)
{ 
 if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
 {
  if(OrderType() == OP_BUY && OrderMagicNumber() == MN && ChartSymbol() == Symbol())
  {
   if (OrderClosePrice() <= OrderStopLoss())
   {
    shortcurrentprice = Close[0] - (Point*40);   
    double shortSL = Close[0] + (Point*80);
    int orderid = OrderSend(NULL,OP_SELL,lotsize(maxRiskPerTrade,shortentry,shortSL),shortentry,slippage,shortSL,0,NULL,MN);  
    if (orderid < 0) Alert("order rejected. Order error: " + GetLastError()); 
   }
  }
  else if (OrderType() == OP_SELL && OrderMagicNumber() == MN && ChartSymbol() == Symbol())
  {
   if (OrderClosePrice() >= OrderStopLoss())
   {
    longcurrentprice = Close[0] + (Point*40);   
    double longSL = Close[0] - (Point*80);
    int orderid = OrderSend(NULL,OP_BUY,lotsize(maxRiskPerTrade,longentry,longSL),longentry,slippage,longSL,0,NULL,MN);
    if (orderid < 0) Alert("order rejected. Order error: " + GetLastError()); 
   }      
  }
 } 
}
}

Happy Thursday earthlings! I place an order inside the checkMN function, outside of that code block I have 2 separate for loops. One for modifying the current open order and one for checking the prev closed orders. the one that checks the prev order is to take a position in the direction of the stoploss for that order.

Problem(prev order for loop): It will execute regardless of whether i am in a trade or not, if i put it inside of the checkMN code block it will still execute since it compares itself to closed orders. How do I get around this?

To clarify: Starting with a simple buy order, my goal is to adjust the stop-loss once, every time the price moves 4 pips in my favor. I have made the currentprice and SL static so it will not update every tick.  The stop-loss is to remain at 8 pips away. When I get stopped out, I take a position in that direction and follow the same parameters.

I appreciate the help! 

 
static double longcurrentprice = Close[0] + (Point*40);
static double shortcurrentprice = Close[0] - (Point*40);
static double longSL = Close[0] - (Point*80);
static double shortSL = Close[0] + (Point*80);

That is not an assignment; it's initialization of a common (globally declared), or static variable with a constant. They 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 2013.02.10

 

Thank you for that piece of information. How do I get around the ordershistorytotal loop executing an order regardless of whether I am in a trade or not? Ignoring the current variables in the code above, a simple look at the last order to see if I was stopped out and take the trade in SL direction. This was my main concern. 

 
Actually, I am thinking I may not need the ordershistory for loop if i set a parameter at the initial buy/sell trade. Something like... if Close[1] > Close[0]) go short. so instead of finding the prev orders info to determine its direction, this will tell me in a similar way. the only issue if the order gets stopped out at the close of a bar and the next tick is above or below the close[1] which can trick the EA into reentering a trade in the direction of the previous order. So I am thinking now if there is a way to compare prices from x ticks ago.
 
nicholas herrera So I am thinking now if there is a way to compare prices from x ticks ago.

Only if you store the ticks as they come.

static int iTick=0; static double ticks[X];
iTick = (iTick+1) % X;           // Circular buffer.
double bidXticks = ticks[iTick]; // Save X ticks ago.
ticks[iTick] = Bid;              // Update buffer.