Trailing Stop Resolution??? Critic

 

It's about amonth or so, since I introduced this problem on a different thread. Thank you for the earlier constructive criticsand advise. It has finally come together and here it is, open for further critic. The code does perform trailing stop functions. It has the Lots Optimized, Calulates orders for a Decrease Factor, Sells (although the conditions are amendable), and it does exit (conditions here are also amendable), but please have a look when you have the time and critic.

Cheers to all and good trading

      double Lots               = 0.1;
       double StopLoss;      
       double MaximumRisk        = 0.1;
       double DecreaseFactor     = 1;
       double MovingPeriodPri    = 20;
       double MovingPeriodSec    = 10;
       double MovingShift        = 1;
       int    MAGICMA            = 20110818;
       double DMadderraStop       = 55;

   //++++ These are adjusted for 5 digit brokers.
double  pips2points,    // slippage  3 pips        3=points        30=points
                pips2dbl;          // Stoploss 15 pips     0.0015          0.00150
int        Digits.pips; // DoubleToStr(dbl/pips2dbl, Digits.pips)
int      init()
         {
          if (Digits == 3 || Digits == 5)
           {            // Adjust for five (5) digit brokers.
                pips2dbl        = Point*10;     pips2points = 10;       Digits.pips = 1;
        }
       else 
         {
           pips2dbl     = Point;        pips2points =  1;       Digits.pips = 0;
        }
        }//Thank You WHRoder
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
  
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/250.0,1);
//---- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
        double minLot     =MarketInfo(Symbol(),MODE_MINLOT),//--------------------correction WHRoeder
               lotStep    =MarketInfo(Symbol(),MODE_LOTSTEP);//-------------------correction WHRoeder
      if(losses>0) lot=lot-lot*losses/DecreaseFactor;       //--------------------correction WHRoeder
      
      lot=MathRound(lot/lotStep)*lotStep;  //-------------------------------------correction WHRoeder
      if (lot<minLot)//-----------------------------------------------------------correction WHRoeder
      lot=minLot;//---------------------------------------------------------------correction WHRoeder
     }
//---- return lot size
   return(lot);//                      
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double maPri;
   double maSec;
   int    res;
   
//---- go trading only for first tiks of new bar
  static datetime Time0;//----------------------------------------correction WHRoeder
  if (Time0 == Time[0]) return; Time0 = Time[0];//----------------correction WHRoeder
  
//---- get Moving Average 
   maPri=iMA(NULL,0,MovingPeriodPri,MovingShift,MODE_SMA,PRICE_CLOSE,0);
   maSec=iMA(NULL,0,MovingPeriodSec,MovingShift,MODE_SMA,PRICE_CLOSE,0);
  
//---- sell conditions
   if( maPri>maSec && Low[1]<Low[2] && Low[2]<Low[3] && Low[3]<Low[4] )
  // if(Low[1]<maSec&&maSec<maPri)  
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
//----
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double maPri;
   double maSec;
//---- go trading only for first tiks of new bar
   
static datetime Time0;  //--------------------------------------------------correction WHRoeder
  if (Time0 ==Time[0]) 
return; 
  Time0 = Time[0];  //---------------------------correction WHRoeder
  
//---- get Moving Average 
   maPri=iMA(NULL,0,MovingPeriodPri,MovingShift,MODE_SMA,PRICE_CLOSE,0);
   maSec=iMA(NULL,0,MovingPeriodSec,MovingShift,MODE_SMA,PRICE_CLOSE,0);

int pos;
for(pos = OrdersTotal()-1; pos >= 0 ; pos--) 
if ( OrderSelect(pos, SELECT_BY_POS)              // Only my orders w/
    &&  OrderMagicNumber()  == MAGICMA             // my magic number
    &&  OrderSymbol()       == Symbol())           // and my pair.
    {

//--------------------------------------------------------------------------------

      if(OrderType()==OP_SELL)
        { 
        if (maPri<maSec)
         OrderClose(OrderTicket(),OrderLots(),Ask,3,Blue);
         }

//+---------------Maddarra Trailing Stop Function----------
          if(OrderOpenPrice()+Ask>pips2dbl*DMadderraStop)
           {
            if((OrderStopLoss()>(Ask+pips2dbl*DMadderraStop))||(OrderStopLoss()==0))
             {
              OrderModify(OrderTicket(),OrderOpenPrice(),Ask+pips2dbl*DMadderraStop,
              OrderTakeProfit(),0,Red);
              Print( "Maddarra Trailing Stop :", OrderClosePrice());
              return;
             }
           }
         }
       }
                   
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
  {
//---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
   return;
//---- calculate open orders by current symbol
   
   if(CalculateCurrentOrders(Symbol())==0)
    CheckForOpen();
   else                                   
    CheckForClose();                              
//----
}

//+------------------------------------------------------------------+
 
//+---------------Maddarra Trailing Stop Function----------
          if(OrderOpenPrice()+Ask>pips2dbl*DMadderraStop)
Price + Price is meaningless. Maybe Ask < OrderOpenPrice - pips2dbl*DMadderraStop
Reason: