Lock&&PipsingXRENG





//+------------------------------------------------------------------+
//|                                             Lock&&PipsingXR1.mq4 |
//|                                 Copyright © 2008, XrustSolution. |
//|                                        http://www.xrust.ucoz.net |
//+------------------------------------------------------------------+
#property copyright "#Copyright © 2008, XrustSolution.#"
#property link      "#http://www.xrust.ucoz.net#"
#include <stdlib.mqh>
//-------------------------------------------------------------------+

extern int       MaxOrd_1=15;

extern int       StopLoss=0;

extern int       TakeProfit=0;

extern double    StartLots=0.01;

extern double    LotsIncrementValue=0.01;

extern bool      AutoLot=true;

extern double    Risk=10;

extern double    MInProfit=5;

extern int       MinTradePause=10;
extern int       per=9;

extern int       TralStep=5;

extern int       EqvTralStep=5;

extern bool      TradeOfTime=true;

extern int       StartTradeHour=20;

extern int       EndTradeHour=8;

extern bool      ShowComment=true;

extern bool      MargineVarning=true;
//----Variables for KimIV funcions ---------------------------------+
bool NumberOfTry=3,UseSound=false,print=false;
string NameFileSound = "expert.wav";   // Íàèìåíîâàíèå çâóêîâîãî ôàéëà
color  clOpenBuy     = Blue;           // Öâåò çíà÷êà îòêðûòèÿ Buy
color  clOpenSell    = Red;            // Öâåò çíà÷êà îòêðûòèÿ Sell
bool   MarketWatch=false;
bool   gbDisabled    = False;          // Áëîêèðîâêà
int BuyMagic1=2891,BuyMagic2=2892,BuyMagic3=2893;
int SellMagic1=73351,SellMagic2=73352,SellMagic3=73353;
static int PrevTime=0;double Lot;
double MinLot, MaxLot, MarginMinLot;   
int    MinLotDgts,period,GrossPeriod,GrossTrand=0;
int       Slippage=3;
//------------------------------------------------------------------+
static double StartDepo, gEqviti;
static double gPriseAp,gPriseDn,gMidPrise;
int gFrChSize,tP;
static bool asd=false;
int BuySell_1=0,BuySell_2=0,BuySell_3=0;
int gCountBuy_1=1,gCountSell_1=1;
double lot,gLotMin;
static string gTime;
static int bs=0,ss=0;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
void init()
  {
  MathSrand( GetTickCount() );
  gLotMin=MarketInfo(Symbol(),MODE_MINLOT);
  StartDepo = AccountBalance();
  if(StartLots<MarketInfo(Symbol(),MODE_MINLOT)){
    StartLots=MarketInfo(Symbol(),MODE_MINLOT);
  }
  if(LotsIncrementValue!=MarketInfo(Symbol(),MODE_LOTSTEP)){
    LotsIncrementValue=MarketInfo(Symbol(),MODE_LOTSTEP);
  }  
  lot=StartLots;
   return;
  }
//+------------------------------------------------------------------+
  void deinit(){Comment("  ");return(0);} //deinit                   |
//+------------------------------------------------------------------+
int start()
  {
   if(MargineVarning){if(Varning()){return(0);}}
   if(!IsDemo()&&!IsOptimization()&&!IsTesting()){
     if(AccountNumber()!=126354){Comment("ÍÅÂÅÐÍÛÉ Ñ×ÅÒ!!!");Sleep(500);Comment("  ");return(0);}
   }
   BuySell_1=0;BuySell_2=0;BuySell_3=0;
//----
  if(!TradeTime()){
  if(CountOpOrd("0")==1){LastOrdTral(TralStep);}
  if(CountOpOrd("0")>1){EcvitiTral();}
  }
  //LastOrdTral(TralStep);
  //OneOrdTral(BuyMagic1,TralStep);
  //OneOrdTral(SellMagic1,TralStep);
  DelDamage();
  EcvitiTral();
  if(CountOpOrd("0")>MaxOrd_1){
  CloseBy();
  //DelVs();
  }
  if((AccountBalance()-StartDepo)+(PorfitBuySell(0)+PorfitBuySell(1))>0){
  //OneOrdTral(BuyMagic1,TralStep);
  //OneOrdTral(SellMagic1,TralStep);  
  //LastOrdTral(TralStep);
  //DelOppositeOrder();
  //CloseBy();
  //DelVs();
  }  
  if(NevBar()){
  //Comment(PorfitBuySell(0),"\n",PorfitBuySell(1));
  if(ShowComment){Info();}

  lot=StartLots;
  if(GrPorfit()>MInProfit){CloseAll();}
  lot=StartLots;
  if(GrPorfit()>MInProfit*(CountOpOrd("0",-1,BuyMagic1)+CountOpOrd("0",-1,SellMagic1))){CloseAll();}
    if(TradeTime()){
      IfZZ();
      if(BuySell_1<0){
        if(CountOpOrd("0")<MaxOrd_1&&TimeOfTrade()&&OneOrdTral(BuyMagic1,TralStep)){
          lot=LotsIncrementValue*gCountBuy_1;
          if(AutoLot){lot=CalcLotsAuto()+CalcLotsAuto()*(gCountBuy_1/2);}
          if(lot<StartLots){lot=StartLots;}
          //OpenPosition("",0,lot*2,StopLoss,TakeProfit,BuyMagic1);
          //OpenPosition("",1,lot,StopLoss,TakeProfit,SellMagic1);
          if(PorfitBuySell(1)>=PorfitBuySell(0)){OpenPosition("",0,lot,StopLoss,TakeProfit,BuyMagic1);}
          if(PorfitBuySell(1)<PorfitBuySell(0)){OpenPosition("",1,lot,StopLoss,TakeProfit,BuyMagic1);}
        }
      }
      if(BuySell_1>0){
        if(CountOpOrd("0")<MaxOrd_1&&TimeOfTrade()&&OneOrdTral(SellMagic1,TralStep)){
          lot=LotsIncrementValue*gCountSell_1;
          if(AutoLot){lot=CalcLotsAuto()+CalcLotsAuto()*(gCountSell_1/2);}
          if(lot<StartLots){lot=StartLots;}
          //OpenPosition("",1,lot*2,StopLoss,TakeProfit,SellMagic1);
          //OpenPosition("",0,lot,StopLoss,TakeProfit,BuyMagic1);
          if(PorfitBuySell(0)>=PorfitBuySell(1)){OpenPosition("",1,lot,StopLoss,TakeProfit,SellMagic1);}
          if(PorfitBuySell(0)<PorfitBuySell(1)){OpenPosition("",0,lot,StopLoss,TakeProfit,BuyMagic1);}
        }
      }
    }
  }
    
  
//----
   return(0);
  }
//-----------------------------------------------------------------------------+
//                                    |
//-----------------------------------------------------------------------------+
//-----------------------------------------------------------------------------+
//                                      |
//-----------------------------------------------------------------------------+
int ProfitBuyOrSell(){double countbuy=0,countsell=0;
for(int i=0;i<OrdersTotal();i++){
  if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
    if(OrderSymbol()==Symbol()){
      if(OrderType()==0){countbuy=countbuy+OrderProfit();}
      if(OrderType()==1){countsell=countsell+OrderProfit();}
    }
  }
}  
if(countbuy>countsell){return(-1);}
if(countbuy<countsell){return(1);}
return(0);
}  
//-----------------------------------------------------------------------------+
//                                            |
//-----------------------------------------------------------------------------+
int BuyOrSell(){int countbuy=0,countsell=0;
for(int i=0;i<OrdersTotal();i++){
  if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
    if(OrderSymbol()==Symbol()){
      if(OrderType()==0){countbuy++;}
      if(OrderType()==1){countsell++;}
    }
  }
}  
if(countbuy>countsell){return(-1);}
if(countbuy<countsell){return(1);} 
return(0);
}
//-----------------------------------------------------------------------------+
//                                           |
//-----------------------------------------------------------------------------+
int LastOrdType(){int time=0,typ=-1;
if(OrdersTotal()<1){return(-1);}
for(int i=0;i<OrdersTotal();i++){
  if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
    if(OrderSymbol()==Symbol()){
      if(OrderOpenTime()>time){
        time=OrderOpenTime();
        typ=OrderType();
      }
    }
  }
}       
return(typ);
}
//-----------------------------------------------------------------------------+
//                                                |
//-----------------------------------------------------------------------------+
void Info(){

return;
}
//-----------------------------------------------------------------------------+
//                                          |
//-----------------------------------------------------------------------------+
bool Varning(){int ord;double depo;
if(AutoLot){StartLots=CalcLotsAuto();}
if((MarketInfo(Symbol(),MODE_MARGINREQUIRED)*StartLots*MaxOrd_1*2)>StartDepo){
  depo=MarketInfo(Symbol(),MODE_MARGINREQUIRED)*StartLots*MaxOrd_1*2;
  ord=StartDepo/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)*StartLots*2);
  if(!print){return(true);}

return(true);
}
return(false);
}
//-----------------------------------------------------------------------------+
//                                          |
//-----------------------------------------------------------------------------+
bool TradeTime(){
if(!TradeOfTime){
gTime="";
return(true);}
if(TimeDayOfWeek(TimeCurrent())==5){StartTradeHour=0;}
if(TimeDayOfWeek(TimeCurrent())==1){StartTradeHour=1;}
if(StartTradeHour<EndTradeHour){
  if(TimeHour(TimeCurrent())>=StartTradeHour&&TimeHour(TimeCurrent())<EndTradeHour
    ){//||(CountOpOrd("0")+CountOpOrd("1"))>0){
    gTime=StringConcatenate("",DoubleToStr((EndTradeHour-TimeHour(TimeCurrent())),0),"");
    return(true);}}
if(StartTradeHour>EndTradeHour){
  if(TimeHour(TimeCurrent())>=StartTradeHour||TimeHour(TimeCurrent())<EndTradeHour
    ){//||(CountOpOrd("0")+CountOpOrd("1"))>0){
    gTime=StringConcatenate("",DoubleToStr((EndTradeHour-TimeHour(TimeCurrent())),0),"");
    return(true);}}    
gTime=StringConcatenate("",StartTradeHour,": 00");    
return(false);
}
//-----------------------------------------------------------------------------+
//                                                        |
//-----------------------------------------------------------------------------+
int IfZZ(){
//if(Close[1]<Open[0]){
//if(MathRand() < 32767/2){
if(Close[1]<iMA(Symbol(),0,per,0,1,0,1)){
   BuySell_1=-1;
   gCountBuy_1++;
   gCountSell_1=1;
   bs++;
   //Comment(b,"\n",s);
return(1);}
//if(Close[1]>Open[0]){
//else{//if(MathRand() > 32767/2.615){
if(Close[1]>iMA(Symbol(),0,per,0,1,0,1)){
   BuySell_1=1;
   gCountBuy_1=1;
   gCountSell_1++; 
   ss++;
   //Comment(b,"\n",s);
return(-1);}
BuySell_1=0;
return(0);
}
//-----------------------------------------------------------------------------+
//                         |
//-----------------------------------------------------------------------------+
int FarOrder(){double dist=0;int tick=0;
//if(OrdersTotal()<1)return;
for(int i=0;i<OrdersTotal();i++){
  if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
    if(OrderSymbol()==Symbol()){
      if(OrderProfit()<0){
        RefreshRates();
        if((MathAbs(OrderOpenPrice()-Ask)/Point)>dist){
          dist=(MathAbs(OrderOpenPrice()-Ask))/Point;
          tick=OrderTicket();
        }
      }
    }
  }
}
return(tick);
}
//+----------------------------------------------------------------------------+
//                                              +
//-----------------------------------------------------------------------------+
void DelDamage(){double FarProfit=1,FarLot=0,profit=0;int count=-1,x;
//if(OrdersTotal()<1)return;
double spred=NormalizeDouble(MarketInfo(Symbol(),MODE_SPREAD)*MarketInfo(Symbol(),MODE_TICKVALUE),Digits);
double PipsPrise=MarketInfo(Symbol(),MODE_TICKVALUE);
double MinLot=MarketInfo(Symbol(),MODE_MINLOT);
int Ticket[];
  if(FarOrder()>0){
   if(OrderSelect(FarOrder(),SELECT_BY_TICKET)){if(OrderCloseTime()==0){FarLot=OrderLots();FarProfit=OrderProfit();}}
  }
  if(FarProfit<0){
   profit=0;
   for(int n=0;n<OrdersTotal();n++){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(OrderSymbol()==Symbol()){
         if(OrderProfit()>0){
            profit=profit+OrderProfit();
            count++;
            Ticket[count]=OrderTicket();
            profit=NormalizeDouble(profit,1);
            FarProfit=NormalizeDouble(FarProfit,1);
            if(profit+FarProfit>spred+(MInProfit*Bid*PipsPrise)){
              ArrayResize(Ticket,count+1);         
              for(x=0;x<count+1;x++){if(OrderSelect(Ticket[x],SELECT_BY_TICKET)){if(OrderCloseTime()==0){del(OrderTicket());}}}     
              if(OrderSelect(FarOrder(),SELECT_BY_TICKET)){if(OrderCloseTime()==0){del(FarOrder());return;}}
            }
            if(profit+FarProfit<0&&profit>0){
              if(FarLot<MinLot*2){return;}
              int lot=(FarLot/MinLot);
              double MinFarProfit=FarProfit/lot;
              int y;
              double lotstep;
              for(y=lot;y>0;y--){
                if(profit+(MinFarProfit*y)>0){
                  lotstep=MinLot*y;
                  break;
                }
              }
              if(lotstep>=MinLot){
                ArrayResize(Ticket,count+1);         
                for(x=0;x<count+1;x++){if(OrderSelect(Ticket[x],SELECT_BY_TICKET)){if(OrderCloseTime()==0){del(OrderTicket());}}}     
                if(OrderSelect(FarOrder(),SELECT_BY_TICKET)){if(OrderCloseTime()==0){dellot(FarOrder(),lotstep);return;}}     
              }          
            }
          }
        }
      }
    }           
  }  
return;  
}
//+----------------------------------------------------------------------------+
//                                                         +
//-----------------------------------------------------------------------------+
void DelVs(){int tick1=0,tick2=0,typ;double pr1=0,pr2=0;
if(OrdersTotal()<MaxOrd_1/2){return;}
   for(int n=0;n<OrdersTotal();n++){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(IfOrder("0")){
         tick1=OrderTicket();
         pr1=OrderProfit();
         if(OrderType()==0){typ=0;}
         if(OrderType()==1){typ=1;}
           if(pr1>0){
              for(int x=OrdersTotal()+1;x>=0;x--){
                if(OrderSelect(x,SELECT_BY_POS,MODE_TRADES)){  
                  if(IfOrder("0",typ)){
                    tick2=OrderTicket();
                    pr2=OrderProfit();
                      if(pr1-pr2==0){
                        if(tick2!=0){del(tick2);}
                        if(tick1!=0){del(tick1);}
                        return;
                      }
                  }
                }
              }               
           }
       } 
     }
   }
return;
}
//+----------------------------------------------------------------------------+
//                                                           +
//-----------------------------------------------------------------------------+
void CloseBy(){
double profit1=0, profit2=0;
int i, n, tip, tip2 ,ticket1=0, ticket2=0;
if(OrdersTotal()<MaxOrd_1/2){return;}
  for(n=0;n<OrdersTotal();n++){
    if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
      if(IfOrder("0")){
        if(OrderProfit()<0){
          tip=OrderType();
          profit1=OrderProfit();
          ticket1=OrderTicket();
          if(tip==1){tip2=0;}
          if(tip==0){tip2=1;}
          for(n=0;n<OrdersTotal();n++){
            if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
              if(IfOrder("0",tip2)){
                if((OrderProfit()+profit1)>=0){
                  if(ticket1!=0&&OrderTicket()!=0){OrderCloseBy(ticket1,OrderTicket(),White);}
                }
              }
            }
          }    
        }
      }
    }
  }      

}
//+----------------------------------------------------------------------------+
//                                              +
//-----------------------------------------------------------------------------+
double OrderDistanse(double prise=0){double gprise=0;int n;
if(OrdersTotal()<2){return;}
 if(prise==0){
   for(n=0;n<OrdersTotal();n++){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(IfOrder("0")){
         if(OrderProfit()<0){
           if(MathAbs(Bid-OrderOpenPrice())>prise){
             prise=OrderOpenPrice();
           }
         }
       }
     }
   }
 return(prise);
 } 
 if(prise!=0){
   for(n=0;n<OrdersTotal();n++){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(IfOrder("0")){
         if(OrderProfit()<0){
           if(MathAbs(Bid-OrderOpenPrice())>gprise&&(OrderOpenPrice()!=prise)){
             gprise=OrderOpenPrice();
           }
         }
       }
     }
   }
 return(gprise);
 } 
 return(0);
}
//+----------------------------------------------------------------------------+
//                                                        +
//-----------------------------------------------------------------------------+
void DelOppositeOrder(){
double prise=0,profit=0,Grprofit=0;
int n, tick=0,tip=-1,tip2=-1,countord=0;
int ticket[100];
//for(n=0;n<CountOpOrd(0);n++){

   Grprofit=0;
   for(n=0;n<OrdersTotal();n++){
   if(OrderDistanse(prise)!=0){
     prise=OrderDistanse(prise);
     tick=OrderTicket();
     profit=OrderProfit();
     tip=OrderType();
   }
if(tip==1){tip2=0;}
if(tip==0){tip2=1;}     
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(IfOrder("0",tip2)){
         if(OrderProfit()>0){
           Grprofit=Grprofit+OrderProfit();
           ticket[countord]=OrderTicket();
           countord++;
         }
       }
     }
   }        
           if(profit+Grprofit>MInProfit){
             ArrayResize(ticket,countord+1);
             double profit2=0;
             if(OrderSelect(tick,SELECT_BY_TICKET,MODE_TRADES)){
               if(OrderCloseTime()==0){
                 for(int i=0;i<CountOpOrd("0")+1;i++){
                   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
                     if(OrderProfit()>profit2){
                       if(OrderType()==tip2){
                         if(OrderCloseTime()==0){
                           profit2=OrderProfit();
                           int ticket2=OrderTicket();
                         }
                       }
                     }
                   }   
                 }
                 if(ticket2!=0&&tick>0){OrderCloseBy(tick,ticket2,White);}
                 for(i=0;i<countord+1;i++){
                   if(OrderSelect(ticket[i],SELECT_BY_TICKET,MODE_TRADES)){
                     if(OrderCloseTime()==0){del(OrderTicket());}
                   }
                 }
                 return;               
               }
             }
           }

}
//+------------------------------------------------------------------+
//|                                                   |
//+------------------------------------------------------------------+
void EcvitiTral(){int i, n ,x;double Gpr=0;
if(OrdersTotal()<1){gEqviti=AccountBalance();return;}
  for(i=0;i<OrdersTotal();i++){
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
      Gpr=Gpr+OrderProfit()+OrderSwap()+OrderCommission();
    }
  }
  if((AccountBalance()+Gpr)-EqvTralStep>gEqviti){gEqviti=gEqviti+EqvTralStep;}
  else{if(gEqviti>AccountBalance()&&gEqviti>StartDepo){
    CloseAll();if(OrdersTotal()<1){gEqviti=AccountBalance();return;}}}
return;
}
//+------------------------------------------------------------------+
//|     |
//+------------------------------------------------------------------+
bool IfOrder(string Sy="",int Typ=-1,int Magik=-1){
if(Sy=="0"||Sy==""){Sy=Symbol();}
  if(OrderSymbol()==Sy||Sy==""){
    if(OrderType()==Typ||Typ==(-1)){
      if(OrderMagicNumber()==Magik||Magik==(-1)){
        return(true);
      }
    }
  }
 return(false); 
}
//+------------------------------------------------------------------+
//|      |
//+------------------------------------------------------------------+
int CountOpOrd(string Sy="",int Typ=-1,int Magik=-1){int count=0;
if(Sy=="0"){Sy=Symbol();}
  for(int i=0;i<OrdersTotal();i++){
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
      if(OrderSymbol()==Sy||Sy==""){
        if(OrderType()==Typ||Typ==(-1)){
          if(OrderMagicNumber()==Magik||Magik==(-1)){
            count++;
          }
        }
      }
    }
  }
 return(count);  
}
//+----------------------------------------------------------------------------+
//            +
//-----------------------------------------------------------------------------+
double Profit(int Pr=0){double grpr=0;
   for(int n=0;n<OrdersTotal();n++){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(OrderSymbol()==Symbol()){
         if(Pr>0){if(OrderProfit()>0){grpr=grpr+OrderProfit();}}
         if(Pr<0){if(OrderProfit()<0){grpr=grpr+OrderProfit();}}
       }
     }    
   } 
return(grpr);
}
//+----------------------------------------------------------------------------+
//           +
//-----------------------------------------------------------------------------+
double GrPorfit(){double grpr=0;
if(OrdersTotal()<2){return(0);}
   for(int n=0;n<OrdersTotal();n++){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(OrderSymbol()==Symbol()){grpr=grpr+OrderProfit();}
     }    
   } 
return(grpr);
}
//+----------------------------------------------------------------------------+
//           +
//-----------------------------------------------------------------------------+
double PorfitBuySell(int tip){double grpr=0;
if(OrdersTotal()<1){return(-1);}
   for(int n=OrdersTotal()+1;n>=0;n--){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(IfOrder("0",tip)){grpr=grpr+OrderProfit();}
     }    
   } 
return(grpr);
}
//+----------------------------------------------------------------------------+
//                                   +
//-----------------------------------------------------------------------------+
void CloseAll(){
 //if(IfOrder(0)==true){
   for(int n=OrdersTotal()+1;n>=0;n--){
     if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
       if(IfOrder("0")){del(OrderTicket());}
     }    
   } 
 //}
return;    
}
//+----------------------------------------------------------------------------+
//                                      +  
//-----------------------------------------------------------------------------+
bool TimeOfTrade(){int count=0,distanse=0;double OpPrs=0;
if(OrdersTotal()<1){return(true);}
  for(int n=0;n<OrdersTotal();n++){
    if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
      if(OrderSymbol()==Symbol()){
        if(OrderOpenTime()>count){count=OrderOpenTime();OpPrs=OrderOpenPrice();}
      }
    }    
  } 
if(OpPrs!=0){distanse=(MathAbs(OpPrs-Bid)/Point)/5;}  
if((TimeCurrent()-count)>(MinTradePause*(distanse+1)*60)){return(true);}
return(false);
}
//+----------------------------------------------------------------------------+
//                                                      +  
//-----------------------------------------------------------------------------+
void LastOrdTral(double step){int n,tic,count=0,StPr=0;static int PrewStPr2=0;
  count=0;
  step=step*Point;
  for(n=OrdersTotal()+1;n>=0;n--){
    if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
      if(IfOrder("0")){
        if(OrderOpenTime()>count){
        count=OrderOpenTime();
        tic=OrderTicket();
        }
      }
    }    
  }  
  if(OrderSelect(tic,SELECT_BY_TICKET)){  
    if(OrderCloseTime()==0){
      if((OrderProfit()/(OrderLots()*1000*Bid))>step){
        StPr=(OrderProfit()/(OrderLots()*1000*Bid));
        if(StPr>=PrewStPr2){PrewStPr2=StPr;}else{del(OrderTicket());PrewStPr2=0;return(true);}
      }
    }
  }
return;  
}
//+----------------------------------------------------------------------------+
//                                                         +  
//-----------------------------------------------------------------------------+
bool OneOrdTral(int mag,double step){int n,count=0,StPr=0;static int PrewStPr=0;
//Comment(OrdersTotal());
if(OrdersTotal()<100){return(true);}
//Print(OrdersTotal()," = ",count);
  count=0;
  for(n=OrdersTotal()+1;n>=0;n--){
    if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
      if(IfOrder("0",-1,mag)){count++;}
    }    
  }  
//Print(count);  
if(count>1){return(true);}  
if(count==1){
  for(n=OrdersTotal()+1;n>=0;n--){
    if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){  
      if(IfOrder("0",-1,mag)){
      
        //Comment(OrderProfit());
        if((OrderProfit()*OrderLots()*1000*Bid)>step){
          StPr=(OrderProfit()*OrderLots()*1000*Bid)/step;
          if(StPr>=PrewStPr){PrewStPr=StPr;}
          else{del(OrderTicket());PrewStPr=0;return(true);}
        }
      }
    }    
  }    
}
if(OrderProfit()<0){return(true);}
return(false);   
}
//+------------------------------------------------------------------+
//|                                |
//+------------------------------------------------------------------+
double CalcLotsAuto()
{
double LotOpt,LotNeOpt;int Zalog;
   RefreshRates();
   double Marga=AccountFreeMargin();
   double Balans=AccountBalance();
   double LotMin=MarketInfo(Symbol(),MODE_MINLOT);
   double LotMax=MarketInfo(Symbol(),MODE_MAXLOT);
   double StepLot=MarketInfo(Symbol(),MODE_LOTSTEP);
   double StopLv=AccountStopoutLevel();
   int PrsMinLot=1000*LotMin;
   if(Risk<0)Risk=0;
   if(Risk>100)Risk=100; 
   if(StepLot==0.01){int step=2;}else{step=1;}  
//---------------------------      
   Zalog=((AccountFreeMargin()/(MaxOrd_1))/10)*Risk;
   LotOpt=NormalizeDouble((Zalog/StartDepo),step);
   //if(LotOpt<LotMin);//MaxOrd_1--;//LotOpt=LotMin;
   if(LotOpt>LotMax)LotOpt=LotMax;
   return(LotOpt);
}
//-----------------------------------------------------------------------------+
//                                               |
//-----------------------------------------------------------------------------+
bool NevBar(){

   if (PrevTime==Time[0]) return(false);
   PrevTime=Time[0];
   return(true);} 
//-----------------------------------------------------------------------------+
//                        |
//+----------------------------------------------------------------------------+
void dellot(int ticket,double lot){int err;
int step;
if(MarketInfo(Symbol(),MODE_LOTSTEP)==0.1){step=1;}
if(MarketInfo(Symbol(),MODE_LOTSTEP)==0.01){step=2;}
lot=NormalizeDouble(lot,step);
 for(int i=0;i<1;i++){
   GetLastError();//îáíóëÿåì îøèêó
   OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES);
   string symbol = OrderSymbol();
   if(OrderType()==OP_BUY){RefreshRates();
     double prise = MarketInfo(symbol,MODE_BID);
     if(!OrderClose(ticket,lot,prise,3,Green)){err = GetLastError();}}
   if(OrderType()==OP_SELL){RefreshRates();
     prise = MarketInfo(symbol,MODE_ASK);
     if(!OrderClose(ticket,lot,prise,3,Green)){err = GetLastError();}}
 if(err == 0){PlaySound("expert.wav");break;} 
 if(err != 0){PlaySound("timeout.wav");Print("Error for Close Funtion =",err);} 
 while(!IsTradeAllowed()){Sleep(5000);}// åñëè ðûíîê çàíÿò òî ïîäîæäåì 5 ñåê 
 if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);
 } 
}
//-----------------------------------------------------------------------------+
//                               |
//+----------------------------------------------------------------------------+
void del(int ticket){int err;
 for(int i=0;i<1;i++){
   GetLastError();//îáíóëÿåì îøèêó
   OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES);
   string symbol = OrderSymbol();
   if(OrderType()==OP_BUY){RefreshRates();
     double prise = MarketInfo(symbol,MODE_BID);
     if(!OrderClose(ticket,OrderLots(),prise,3,Green)){err = GetLastError();}}
   if(OrderType()==OP_SELL){RefreshRates();
     prise = MarketInfo(symbol,MODE_ASK);
     if(!OrderClose(ticket,OrderLots(),prise,3,Green)){err = GetLastError();}}
 if(err == 0){PlaySound("expert.wav");break;} 
 if(err != 0){PlaySound("timeout.wav");Print("Error for Close Funtion =",err);} 
 while(!IsTradeAllowed()){Sleep(5000);}// åñëè ðûíîê çàíÿò òî ïîäîæäåì 5 ñåê 
 if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);
 } 
}

//+----------------------------------------------------------------------------+
void Message(string m) {
  //Comment(m);
  if (StringLen(m)>0) Print(m);
}


//+----------------------------------------------------------------------------+
void ModifyOrder(double pp=-1, double sl=0, double tp=0, datetime ex=0) {
  bool   fm;
  color  cl=White;
  double op, pa, pb, os, ot;
  int    dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it;

  if (pp<=0) pp=OrderOpenPrice();
  if (sl<0 ) sl=OrderStopLoss();
  if (tp<0 ) tp=OrderTakeProfit();
  
  pp=NormalizeDouble(pp, dg);
  sl=NormalizeDouble(sl, dg);
  tp=NormalizeDouble(tp, dg);
  op=NormalizeDouble(OrderOpenPrice() , dg);
  os=NormalizeDouble(OrderStopLoss()  , dg);
  ot=NormalizeDouble(OrderTakeProfit(), dg);
  //if(OrderType()==0||OrderType()==2||OrderType()==4){if(Ask-stoplevel<sl||Bid+stoplevel>tp){return;}}
  //if(OrderType()==1||OrderType()==3||OrderType()==5){if(Bid+stoplevel>sl||Ask-stoplevel<tp){return;}}
  //if(MathAbs(sl-Ask)<stoplevel||MathAbs(tp-Ask)<stoplevel){return;}
  if(pp==op&&sl==os&&tp==ot){return;}
  if ((sl==os&&(os!=0||sl!=0))&& (tp==ot&&(ot!=0||tp!=0))) {return;}
    for (it=1; it<=NumberOfTry; it++) {
      //if ((!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      fm=OrderModify(OrderTicket(), pp, sl, tp, ex, cl);
      if (fm) {
        if (UseSound) PlaySound(NameFileSound); break;
      } else {
        er=GetLastError();
        pa=MarketInfo(OrderSymbol(), MODE_ASK);
        pb=MarketInfo(OrderSymbol(), MODE_BID);
        if(print){Print("Error(",er,") modifying order: ",ErrorDescription(er),", try ",it);
                  Print("Ask=",pa,"  Bid=",pb,"  sy=",OrderSymbol(),
                        "  op="+GetNameOP(OrderType()),"  pp=",pp,"  sl=",sl,"  tp=",tp);}
        Sleep(1000*10);
        //if(er==130){del(OrderTicket());}
      }
    }
  //}
}
//+----------------------------------------------------------------------------+
bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) {
  int i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (ot<=OrderOpenTime()) return(True);
            }
          }
        }
      }
    }
  }
  return(False);
}
//+----------------------------------------------------------------------------+
string GetNameOP(int op) {
  switch (op) {
    case OP_BUY      : return("Buy");
    case OP_SELL     : return("Sell");
    case OP_BUYLIMIT : return("BuyLimit");
    case OP_SELLLIMIT: return("SellLimit");
    case OP_BUYSTOP  : return("BuyStop");
    case OP_SELLSTOP : return("SellStop");
    default          : return("Unknown Operation");
  }
}
//+----------------------------------------------------------------------------+
void OpenPosition(string sy, int op, double ll, double Sl=0, double Tp=0, int mn=0) {
  color    clOpen;
  datetime ot;
  double   pp, pa, pb, tp ,sl;
  int      dg, err, it, ticket=0;
  string   lsComm="";
  

  
  if (sy=="" || sy=="0") sy=Symbol();
  int stoplevel=MarketInfo(sy,MODE_STOPLEVEL);
  int spread=MarketInfo(sy,MODE_SPREAD);
  if(Tp!=0&&Tp<stoplevel+spread){Tp=stoplevel;}  
  if (op<1){
   if (Sl>0) {sl=MarketInfo(Symbol(),MODE_ASK)-Sl*Point; }else {sl=0;}
   if (Tp>0) {tp=MarketInfo(Symbol(),MODE_ASK)+Tp*Point; }else{ tp=0;}
  }else{
   if (Sl>0) {sl=MarketInfo(Symbol(),MODE_BID)+Sl*Point; }else{ sl=0;}
   if (Tp>0) {tp=MarketInfo(Symbol(),MODE_BID)-Tp*Point;} else {tp=0;}}  
   
  if (op==OP_BUY) clOpen=clOpenBuy; else clOpen=clOpenSell;
  for (it=1; it<=NumberOfTry; it++) {
    if (IsStopped()) {
      Print("OpenPosition(): Îñòàíîâêà ðàáîòû ôóíêöèè");
      break;}
    while (!IsTradeAllowed()) Sleep(5000);
    RefreshRates();
    dg=MarketInfo(sy, MODE_DIGITS);
    pa=MarketInfo(sy, MODE_ASK);
    pb=MarketInfo(sy, MODE_BID);
    if (op==OP_BUY) pp=pa; else pp=pb;
    pp=NormalizeDouble(pp, dg);
    ot=TimeCurrent();
    if (MarketWatch)
      ticket=OrderSend(sy, op, ll, pp, Slippage, 0, 0, lsComm, mn, 0, clOpen);
    else
      ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, lsComm, mn, 0, clOpen);
    if (ticket>0) {
      if (UseSound) PlaySound(NameFileSound); break;
    } else {
      err=GetLastError();
      if (pa==0 && pb==0) Message(""+sy);
      // Âûâîä ñîîáùåíèÿ îá îøèáêå
      if(print){
      Print("Error(",err,") opening position: ",ErrorDescription(err),", try ",it);
      Print("Ask=",pa," Bid=",pb," sy=",sy," ll=",ll," op=",GetNameOP(op),
            " pp=",pp," sl=",sl," tp=",tp," mn=",mn);}
      // Áëîêèðîâêà ðàáîòû ñîâåòíèêà
      if (err==2 || err==64 || err==65 || err==133) {
        gbDisabled=True; break;
      }
      // Äëèòåëüíàÿ ïàóçà
      if (err==4 || err==131 || err==132) {
        Sleep(1000*300); break;
      }
      if (err==128 || err==142 || err==143) {
        Sleep(1000*66.666);
        if (ExistPositions(sy, op, mn, ot)) {
          if (UseSound) PlaySound(NameFileSound); break;
        }
      }
      if (err==140 || err==148 || err==4110 || err==4111) break;
      if (err==141) Sleep(1000*100);
      if (err==145) Sleep(1000*17);
      if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);
      if (err!=135) Sleep(1000*7.7);
    }
  }
  if (MarketWatch && ticket>0 && (sl>0 || tp>0)) {
    if (OrderSelect(ticket, SELECT_BY_TICKET)) ModifyOrder(-1, sl, tp);
  }
}
//+----------------------------------------------------------------------------+





Sample





Analysis



Market Information Used:

Series array that contains close prices for each bar
Series array that contains open time of each bar


Indicator Curves created:


Indicators Used:

Moving average indicator


Custom Indicators Used:

Order Management characteristics:
Checks for the total of open orders
It Closes Orders by itself
It can change open orders parameters, due to possible stepping strategy
It automatically opens orders when conditions are reached

Other Features:


It plays sound alerts

BackTest : USDJPY on H1

From 2009-11-01 to 2009-11-30 Profit Factor:0.07 Total Net Profit:-3563.08

BackTest : EURUSD on H1

From 2009-12-01 to 2010-01-17 Profit Factor:1.61 Total Net Profit:431.54

BackTest : USDCAD on H1

From 2009-12-01 to 2010-01-01 Profit Factor:1.50 Total Net Profit:143.89

BackTest : EURUSD on H1

From 2009-08-01 to 2009-10-01 Profit Factor:0.80 Total Net Profit:-301.84

BackTest : GBPUSD on H1

From 2010-01-01 to 2010-02-27 Profit Factor:1.13 Total Net Profit:184.30

BackTest : EURUSD on H1

From 2010-04-01 to 2010-04-30 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2010-05-01 to 2010-05-31 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2010-06-01 to 2010-06-30 Profit Factor:0.00 Total Net Profit:0.00

Request Backtest for Lock&&PipsingXRENG


From : (yyyy/mm/dd) To: (yyyy/mm/dd)

Pair: Period: