Selasa, 29 April 2014

MartingailExpert_v1.0_Stochastic.mq4

//+------------------------------------------------------------------+
//|                             MartingailExpert_v1.0_Stochastic.mq4 |
//|                      Copyright © 2007, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//| Modified by TradingSystemForex http://www.tradingsystemforex.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"

extern string MM="---------------- Money Management";
extern double MinProfit=0; //martingale mm stopped if profit under min profit
extern double Multiplier=2; //martingale multiplier - disabled if 1
extern double LotsBuy=0.01; //initial lots buy
extern double LotsSell=0.01; //initial lots sell
extern bool RiskMM=false; //risk money management
extern double Risk=1; //risk in percentage
extern string OM="---------------- Order Management";
extern double TakeProfit=0; //take profit - if 0 automated take profit is enabled
extern bool UseAutomatedTP=true; //automated take profit
extern double AutomatedTPFactor=10; //automated take profit factor
extern double StopLoss=0; //stop loss - disabled if 0
extern double TrailingStop=0; //trailing stop - disabled if 0
extern double TrailingStopStep=1; //margin allowed to the price before to apply the trailing stop - disabled if 1
extern bool UseMaxSpread=false; //max spread allowed to enter an order
extern int MaxSpread=2; //max spread
extern int Slippage=3; //change in spread
extern bool MaxOpenOrders=false; //max spread allowed to enter an order
extern int MaxBuyOrders=100; //max open buy orders
extern int MaxSellOrders=100; //max open sell orders
extern bool UseEquityTarget=false; //trading stopped if equity target reached
extern int EquityTarget=15000; //equity target
extern bool UseEquityLoss=false; //trading stopped if "equity loss" amount reached
extern int EquityLoss=8000; //equity loss
extern string DBO="---------------- Distance between orders";
extern double Step=25; //distance in pips between each order
extern int StepMode=0; //mode of calculation of the distance
//if stepmode=0 distance=step - if stepmode=1 distance=step+total number of opened orders - 2
//for stepmode=1, there is only a difference if the total number is over 2
extern string SS="---------------- Stochastic Settings";
extern double KPeriod=200; //%k period
extern double DPeriod=20; //%d period
extern double Slowing=20; //slowing
extern double SimpleZoneBuy=50; //zone buy
extern double SimpleZoneSell=50; //zone sell
extern bool ExtendedZone=false; //you have more option for the buy/sell zones
extern double CloseLevelUpBuy=70; //the buy orders are closed when this level is reached
extern double EndZoneBuy=20; //the zone buy starts at this level
extern double StartZoneBuy=0; //the zone buy finishes at this level
extern double CloseLevelDnBuy=0; //the buy orders are closed when this level is reached
//the ea takes buy orders between the two following levels
//the ea takes sell orders between the two following levels
extern double CloseLevelUpSell=100; //the sell orders are closed when this level is reached
extern double EndZoneSell=100; //the zone sell starts at this level
extern double StartZoneSell=70; //the zone sell finishes at this level
extern double CloseLevelDnSell=20; //the sell orders are closed when this level is reached
extern string MAF="---------------- MA Filter Settings";
extern bool MaFilter=false; //if price over ma : up signal is confirmed - if price under ma : down signal is confirmed
extern double MaPeriod=200; //ma period
extern double MaMode=1; //0=sma, 1=ema, 2=smoothed, 3=linear weighted
extern double MaPrice=0; //0=close, 1=open, 2=high, 3=low, 4=median price (hl/2), 5=typical price (hlc/3), 6=weighted close (hlcc/4)
extern string TAF="---------------- Time Filter Settings";
extern bool TimeFilter=false; //the ea trades only if the current time is included in the time filter
extern double StartHour=8; //star hour
extern double EndHour=21; //end hour
extern bool CloseFriday=false; //the orders are closed before the week end
extern double CloseFridayHour=22; //friday end hour
double MagicBuy=555; //buy magic number
double MagicSell=556; //sell magic number

double openpricebuy,openpricesell,LotsBuy2,LotsSell2,lastlotbuy,lastlotsell,tpb,tps,tptb,tpts,sltb,slts,cnt,slbuy,slsell,smbuy,smsell,lotstep,
maxLot,free,balance,lotsell,lotbuy,dig,sig_buy,sig_sell,ask,bid;double Ballance=0.0;int err=0;
int ticketbuy;int ticketsell;

int OrdersTotalMagicBuy(int MagicBuy){
    int j=0;int r;
    for(r=0;r<OrdersTotal();r++){
        if(OrderSelect(r,SELECT_BY_POS,MODE_TRADES)){
           if(OrderMagicNumber()==MagicBuy)j++;
        }
    }  
return(j);
}

int OrdersTotalMagicSell(int MagicSell){
    int d=0;int n;
    for(n=0;n<OrdersTotal();n++){
       if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){
         if(OrderMagicNumber()==MagicSell) d++;
       }
    }   
return(d);
}    

int orderclosebuy(int ticketbuy){
    string symbol = Symbol();double dig2=MarketInfo(symbol,MODE_DIGITS);int cnt;
    for(cnt = OrdersTotal(); cnt >= 0; cnt--){
       OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);      
       if(OrderSymbol() == symbol && OrderMagicNumber()==MagicBuy){
         ticketbuy=OrderTicket();OrderSelect(ticketbuy, SELECT_BY_TICKET, MODE_TRADES);LotsBuy2=OrderLots() ;                        
         double bid = MarketInfo(symbol,MODE_BID);
         RefreshRates();
         OrderClose(ticketbuy,LotsBuy2,NormalizeDouble(bid,dig2),3,Magenta);
       }
    }
    LotsBuy2=LotsBuy;return(0);
}

int orderclosesell(int ticketsell){
    string symbol = Symbol();double dig2=MarketInfo(symbol,MODE_DIGITS);int cnt;  
    for(cnt = OrdersTotal(); cnt >= 0; cnt--){
       OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);      
       if(OrderSymbol() == symbol && OrderMagicNumber()==MagicSell) {
         ticketsell=OrderTicket();OrderSelect(ticketsell, SELECT_BY_TICKET, MODE_TRADES);LotsSell2=OrderLots() ;                        
         double ask = MarketInfo(symbol,MODE_ASK);
         RefreshRates();
         OrderClose(ticketsell,LotsSell2,NormalizeDouble(ask,dig2),3, Lime);
       }
    }
    LotsSell2=LotsSell;return(0);
}

 


int start(){

//----

  if(RiskMM){
     if(Risk<0.1||Risk>100){
        Comment("Invalid Risk Value.");return(0);}
     else{
          LotsBuy=MathFloor((AccountFreeMargin()*AccountLeverage()*Risk*Point*100)/(Ask*MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT)))*MarketInfo(Symbol(),MODE_MINLOT);
          LotsSell=MathFloor((AccountFreeMargin()*AccountLeverage()*Risk*Point*100)/(Ask*MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT)))*MarketInfo(Symbol(),MODE_MINLOT);
     }
  }
  if(RiskMM==false){LotsBuy=LotsBuy;LotsSell=LotsSell;}
  if(Ballance!=0.0&&MinProfit>0){
     if(Ballance<=AccountBalance()&&AccountBalance()<=(Ballance+MinProfit))Multiplier=1;
     else if(AccountBalance()<Ballance)Multiplier=Multiplier;}
  Ballance=AccountBalance();
  double profitbuy=0;double profitsell=0;
  string symbol = OrderSymbol();
  double spread = MarketInfo(symbol,MODE_SPREAD);
  double dig2 = MarketInfo(symbol,MODE_DIGITS);
  double minLot = MarketInfo(symbol,MODE_MINLOT);
  double MA=iMA(Symbol(),0,MaPeriod,0,MaMode,MaPrice,1);
  double STMA=iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MODE_LWMA,1,0,1);
  double STSI=iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MODE_LWMA,1,1,1);
  string SBUY,SSELL;SBUY="false";SSELL="false";
  if(STMA>STSI)SBUY="true";if(STMA<STSI)SSELL="true";
  string ZBUY,ZSELL;ZBUY="false";ZSELL="false";
  if(ExtendedZone==false&&STSI<SimpleZoneBuy)ZBUY="true";
  if(ExtendedZone==false&&STSI>SimpleZoneSell)ZSELL="true";
  if(ExtendedZone==true&&STSI>StartZoneBuy&&STSI<EndZoneBuy)ZBUY="true";
  if(ExtendedZone==true&&STSI>StartZoneSell&&STSI<EndZoneSell)ZSELL="true";
  string CLS,CLB;CLS="false";CLB="false";
  if(ExtendedZone==true&&STSI<=CloseLevelDnSell||STSI>=CloseLevelUpSell)CLS="true";
  if(ExtendedZone==true&&STSI>=CloseLevelUpBuy||STSI<=CloseLevelDnBuy)CLB="true";
  string MAUP,MADN;MAUP="false";MADN="false";
  if(Ask>MA||MaFilter==false)MAUP="true";
  if(Bid<MA||MaFilter==false)MADN="true";
  string MASP;MASP="false";
  if(MaxSpread==MaxSpread||UseMaxSpread==false)MASP="true";
  string MOBO,MOSO;MOBO="false";MOSO="false";
  if(OrdersTotalMagicBuy(MagicBuy)<MaxBuyOrders||MaxOpenOrders==false)MOBO="true";
  if(OrdersTotalMagicSell(MagicSell)<MaxSellOrders||MaxOpenOrders==false)MOSO="true";
  string EQTA;EQTA="false";
  if(AccountEquity()<EquityTarget||UseEquityTarget==false)EQTA="true";
  string EQLO;EQLO="false";
  if(AccountEquity()>EquityLoss||UseEquityLoss==false)EQLO="true";
  if(TimeFilter==true&&(Hour()<StartHour||Hour()>=EndHour))return(0);
  string COFH;COFH="false";
  if(CloseFriday==true&&DayOfWeek()==5&&TimeCurrent()>=StrToTime(CloseFridayHour+":00"))COFH="true";
  if(minLot==0.01){dig=2;maxLot=MarketInfo(symbol,MODE_MAXLOT);}
  if(minLot==0.1){dig=1;maxLot=((AccountBalance()/2)/1000);}
  if(OrdersTotalMagicBuy(MagicBuy)>0){
     double smbuy;
     for(cnt=0;cnt<OrdersTotal();cnt++){
        OrderSelect(cnt,SELECT_BY_POS, MODE_TRADES);
        if(OrderSymbol() == Symbol() && OrderMagicNumber () == MagicBuy){
          ticketbuy = OrderTicket();OrderSelect(ticketbuy,SELECT_BY_TICKET, MODE_TRADES);
          smbuy = smbuy+OrderLots();openpricebuy = OrderOpenPrice();lastlotbuy = OrderLots();
        }
     }{  
     if(smbuy+(NormalizeDouble((lastlotbuy*Multiplier),dig))<maxLot){    
       if(StepMode==0){
         if(Ask<=openpricebuy-Step*Point&&MAUP=="true"&&MASP=="true"&&MOBO=="true"&&EQTA=="true"&&EQLO=="true"&&COFH=="false"&&SBUY=="true"&&ZBUY=="true"){
           LotsBuy2=Multiplier*LotsBuy*OrdersTotalMagicBuy(MagicBuy);
           if(TakeProfit>0)tptb=Ask+TakeProfit*Point;else tptb=0;if(StopLoss>0)sltb=Ask-StopLoss*Point;else sltb=0;
           RefreshRates();ticketbuy=OrderSend(Symbol(),OP_BUY,NormalizeDouble(LotsBuy2,dig),Ask,3,sltb,tptb,"MartingailExpert",MagicBuy,0,Blue);
         }
       }
       if(StepMode==1){
         if(Ask<=openpricebuy-(Step+OrdersTotalMagicBuy(MagicBuy)+OrdersTotalMagicBuy(MagicBuy)-2)*Point&&MAUP=="true"&&MASP=="true"&&MOBO=="true"&&EQTA=="true"&&EQLO=="true"&&COFH=="false"&&SBUY=="true"&&ZBUY=="true"){
           LotsBuy2=Multiplier*LotsBuy*OrdersTotalMagicBuy(MagicBuy);
           if(TakeProfit>0)tptb=Ask+TakeProfit*Point;else tptb=0;if(StopLoss>0)sltb=Ask-StopLoss*Point;else sltb=0;
           RefreshRates();ticketbuy=OrderSend(Symbol(),OP_BUY,NormalizeDouble(LotsBuy2,dig),Ask,3,sltb,tptb,"MartingailExpert",MagicBuy,0,Blue);
         }
       }
     }
     }
  }
  if(OrdersTotalMagicSell(MagicSell)>0){
    double smsell;
    for(cnt=0;cnt<OrdersTotal();cnt++){
       OrderSelect(cnt,SELECT_BY_POS, MODE_TRADES);
       if(OrderSymbol() == Symbol() && OrderMagicNumber () == MagicSell){
         ticketsell = OrderTicket();OrderSelect(ticketsell,SELECT_BY_TICKET, MODE_TRADES);
         smsell = smsell + OrderLots();openpricesell = OrderOpenPrice();lastlotsell = OrderLots();
       }    
    }{
    if(smsell+(NormalizeDouble((lastlotsell*Multiplier),dig))<maxLot){
      if(StepMode==0){
        if(Bid>=openpricesell+Step*Point&&MADN=="true"&&MASP=="true"&&MOSO=="true"&&EQTA=="true"&&EQLO=="true"&&COFH=="false"&&SSELL=="true"&&ZSELL=="true"){
          LotsSell2=Multiplier*LotsSell*OrdersTotalMagicSell(MagicSell);
          if(TakeProfit>0)tpts=Bid-TakeProfit*Point;else tpts=0;if(StopLoss>0)slts=Bid+StopLoss*Point;else slts=0;
          RefreshRates();ticketsell=OrderSend(Symbol(),OP_SELL,NormalizeDouble(LotsSell2,dig),Bid,3,slts,tpts,"MartingailExpert",MagicSell,0,Red);
        }
      }
      if(StepMode==1){
        if(Bid>=openpricesell+(Step+OrdersTotalMagicSell(MagicSell)+OrdersTotalMagicSell(MagicSell)-2)*Point&&MADN=="true"&&MASP=="true"&&MOSO=="true"&&EQTA=="true"&&EQLO=="true"&&COFH=="false"&&SSELL=="true"&&ZSELL=="true"){
          LotsSell2=Multiplier*LotsSell*OrdersTotalMagicSell(MagicSell);
          if(TakeProfit>0)tpts=Bid-TakeProfit*Point;else tpts=0;if(StopLoss>0)slts=Bid+StopLoss*Point;else slts=0;
          RefreshRates();ticketsell=OrderSend(Symbol(),OP_SELL,NormalizeDouble(LotsSell2,dig),Bid,3,slts,tptb,"MartingailExpert",MagicSell,0,Red);
        }
      }
    }
    } 
  }
  if(OrdersTotalMagicBuy(MagicBuy)<1){if(TakeProfit>0)tptb=Ask+TakeProfit*Point;else tptb=0;if(StopLoss>0)sltb=Ask-StopLoss*Point;else sltb=0;
    if(SBUY=="true"&&ZBUY=="true"&&MAUP=="true"&&MASP=="true"&&MOBO=="true"&&EQTA=="true"&&EQLO=="true"&&COFH=="false")
    ticketbuy = OrderSend(Symbol(),OP_BUY,LotsBuy,Ask,3,sltb,tptb,"MartingailExpert",MagicBuy,0,Blue);
  }
  if(OrdersTotalMagicSell(MagicSell)<1){if(TakeProfit>0)tpts=Bid-TakeProfit*Point;else tpts=0;if(StopLoss>0)slts=Bid+StopLoss*Point;else slts=0;
    if(SSELL=="true"&&ZSELL=="true"&&MADN=="true"&&MASP=="true"&&MOSO=="true"&&EQTA=="true"&&EQLO=="true"&&COFH=="false")
    ticketsell = OrderSend(Symbol(),OP_SELL,LotsSell,Bid,3,slts,tpts,"MartingailExpert",MagicSell,0,Red);
  }
 
  for(cnt=0;cnt<OrdersTotal();cnt++){
     OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
     if(OrderSymbol()==Symbol() && OrderMagicNumber () == MagicBuy){
       ticketbuy = OrderTicket();OrderSelect(ticketbuy,SELECT_BY_TICKET, MODE_TRADES);profitbuy = profitbuy+OrderProfit() ;
       openpricebuy = OrderOpenPrice();
     }
  }
  tpb = (OrdersTotalMagicBuy(MagicBuy)*AutomatedTPFactor*Point)+openpricebuy;
  double bid = MarketInfo(Symbol(),MODE_BID);
  if(UseAutomatedTP==true&&profitbuy>0){
    if(Bid>=tpb) orderclosebuy(ticketbuy);
  }
  for(cnt=0;cnt<OrdersTotal();cnt++){  
     OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
     if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicSell){
       ticketsell = OrderTicket();OrderSelect(ticketsell,SELECT_BY_TICKET, MODE_TRADES);profitsell = profitsell+OrderProfit();
       openpricesell = OrderOpenPrice();
     }
  }
  tps = openpricesell-(OrdersTotalMagicSell(MagicSell)*AutomatedTPFactor*Point);
  double ask = MarketInfo(Symbol(),MODE_ASK);   
  if(UseAutomatedTP==true&&profitsell>0){
    if(Ask<=tps)orderclosesell(ticketsell);   
  }
  free = AccountFreeMargin();balance = AccountBalance();   
  for(cnt=0;cnt< OrdersTotal();cnt++){  
     OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
     if(OrderSymbol()==Symbol() && OrderMagicNumber () == MagicBuy)  ticketbuy = OrderTicket();
     if(OrderSymbol()==Symbol() && OrderMagicNumber () == MagicSell) ticketsell = OrderTicket();
  }
  if(EQTA=="false"||EQLO=="false"||COFH=="true"){
    orderclosesell(ticketsell);orderclosebuy(ticketbuy);
  }
  if(CLS=="true"){
    orderclosesell(ticketsell);
  }
  if(CLB=="true"){
    orderclosebuy(ticketbuy);
  }
  if(OrdersTotalMagicBuy(MagicBuy)==0||TakeProfit>0){
    profitbuy=0;ticketbuy=0;tpb=0;
  }
  if(OrdersTotalMagicSell(MagicSell)==0||TakeProfit>0){
    profitsell=0;ticketsell=0;tps=0;
  }
 
//----

  for(int ii=0; ii<2; ii+=2){
      ObjectDelete("rect"+ii);
      ObjectCreate("rect"+ii,OBJ_HLINE, 0, 0,tps);
      ObjectSet("rect"+ii, OBJPROP_COLOR, Red);
      ObjectSet("rect"+ii, OBJPROP_WIDTH, 1);
      ObjectSet("rect"+ii, OBJPROP_RAY, False);
  }   
  for(int rr=0; rr<2; rr+=2){
      ObjectDelete("rect1"+rr);
      ObjectCreate("rect1"+rr,OBJ_HLINE, 0, 0,tpb);     
      ObjectSet("rect1"+rr, OBJPROP_COLOR, Blue);
      ObjectSet("rect1"+rr, OBJPROP_WIDTH, 1);
      ObjectSet("rect1"+rr, OBJPROP_RAY, False);    
  }
  if(OrdersTotalMagicBuy(MagicBuy)>1){
    for(cnt=0;cnt<OrdersTotal();cnt++){  
        OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
        if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicBuy){
          ticketbuy = OrderTicket();OrderSelect(ticketbuy,SELECT_BY_TICKET, MODE_TRADES);
          openpricebuy = OrderOpenPrice();slbuy= OrderStopLoss();ticketbuy = OrderTicket();
        }
    }          
    if(Bid-openpricebuy>Point*TrailingStop){
       if((slbuy<Bid-Point*(TrailingStop+TrailingStopStep-1))|| (slbuy==0)){
         if(TrailingStop>0){
            OrderModify(ticketbuy,openpricebuy,NormalizeDouble(Bid-Point*TrailingStop,dig2),0,0,Gold);
            return(0);
         }
       }
    }
  }
  if(OrdersTotalMagicSell(MagicSell)>1){
    for(cnt=0;cnt<OrdersTotal();cnt++){  
        OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
        if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicSell){
          ticketsell = OrderTicket();OrderSelect(ticketsell,SELECT_BY_TICKET, MODE_TRADES);
          openpricesell = OrderOpenPrice(); slsell= OrderStopLoss();
        }
    }               
    if(openpricesell-Ask>Point*TrailingStop){
      if((slsell>Ask+Point*(TrailingStop+TrailingStopStep-1))|| (slsell==0)){
        if(TrailingStop>0){
           OrderModify(ticketsell,openpricesell,NormalizeDouble(Ask+Point*TrailingStop,dig2),0,0,Gold);
           return(0);      
        }
      }
    }      
  }
  Comment("FreeMargin = ",NormalizeDouble(free,0),"  Balance = ",NormalizeDouble(balance,0),"  maxLot = ",NormalizeDouble(maxLot,dig),"\n",
  "Totalbuy = ",OrdersTotalMagicBuy(MagicBuy),"  Lot = ",smbuy,"  Totalsell = ",OrdersTotalMagicSell(MagicSell),"  Lot = ",smsell,"\n",
  "---------------------------------------------------------------","\n","Profitbuy = ",profitbuy,"\n",
  "Profitsell = ",profitsell);
 
  if(ticketbuy<0||ticketsell<0){if(GetLastError()==134){err=1;Print("NOT ENOGUGHT MONEY!!");}return (-1);}
 
  return(0);


//+------------------------------------------------------------------+

Tidak ada komentar:

Posting Komentar