TRUE Forex

Просмотр кода форекс советника ZZ_H1v2.1.mq4

//+------------------------------------------------------------------+
//|                                                 e+robot123_2.mq4 |
//+------------------------------------------------------------------+
//|                                                   e+robot123.mq4 |
//+------------------------------------------------------------------+
//|                                                      robot123.mq4|
//+------------------------------------------------------------------+
extern string    zz="----- ПАРАМЕТРЫ ZigZag -------";
extern int       ExtDepth         =      12;
extern int       ExtDeviation     =       5;
extern int       ExtBackstep      =       3;
extern string    par="----- ПАРАМЕТРЫ ТОРГОВЛИ -------";
extern int       Otstup_point_b     =       5; // отступ ордеров от экстремумов зигзага
extern int       Otstup_point_s     =       5; 
extern int       TP_buy           =      50; // тейкпрофит для покупок в пунктах 0 - выкл
extern int       SL_buy           =      50; // стоплосс для покупок в пунктах 0 - выкл.
extern int       TP_sell          =      50; // тейкпрофит для продаж в пунктах 0 - выкл
extern int       SL_sell          =      50; // стоплосс для продаж в пунктах 0 - выкл.
extern string    TRAL = " -- ПАРАМЕТРЫ ТРЕЙЛИНГ СТОПА -- ";
extern int       Start_BU         =       0; // уровень перевода в безубыток(пунктов) 0-выкл.
extern int       Level_BU         =       0; // уровень безубытока (пунктов) 
extern int       TrailingStop     =      25; // дистация трейлинга 0- выкл.  
extern int       TrailingStep     =       5; // шаг трейлинга 
extern string    fr_tr="----- ТРЕЙЛИНГ СТОП ПО ФРАКТАЛАМ -------";
extern bool      TrailingStopFr   =    false; //если= false, то трейлинг по фракталам отключен
extern string    mm="----- УПРАВЛЕНИЕ КАПИТАЛОМ -------";
extern double    Lots             =    0.01; // рабочий лот
extern bool      USE_MM           =    true; // MM 
extern double    Risk             =     1.5; // risk (Lots=Balance*0.0001*Risk)
extern string    cl=" --- ЗАКРЫТИЕ И УДАЛЕНИЕ ОРДЕРОВ В ПЯТНИЦУ ----";
extern bool      Закрытие_в_пятницу        =     true; 
extern bool      Удалить_отложки           =     true; 
extern bool      Закрыть_рыночные_ордера   =     true; 
extern int       Время    = 23; 
extern int       Время_мин = 1;
extern int       slippage =  2;
extern string    m=" --- МАГИЧЕСКИЙ НОМЕР ОРДЕРОВ ----";
extern int       MAGIC =  7575;
extern bool      Auto_4_digits   =   true; // включить автоперевод пунктов на 4 знак


double _lastExtremum=0.0,_price;
double _currentExtremum=0.0;
double _previousExtremum=0.0;
int _extType=-1,mp,prevtime,LastTimeUP,LastTimeDN,TimeLastUP,TimeLastDN;
double _workLots=0.0;
//--------------------------------------------------------------------
int STOPLEVEL,orders_buy,orders_sell,orders_buystop,orders_sellstop;
int minstop,i, k, STATUS,start_buystop,start_sellstop;
double open_price,sl,tp,price,lots;
double maxlot,minlot,lotstep,op,Eq,_op,_sl;
int spread,ticket,magic;
double LastOpenPriseOpenBuy, LastOpenBuySL, LastOpenPriseOpenSell, LastOpenSellSL,LastOpenBuyTP, LastOpenSellTP; 
int  LastOpenBuyMagic,LastOpenSellMagic,LastOpenBuyTicket,LastOpenSellTicket;
datetime OpenBuyTime,OpenSellTime;
double LastOpenPrise_SS, LastOpenPrise_BS,LastOpenBuyLots,LastOpenSellLots;
int OpenBuyStopTime, LastBuyStopMagic, OpenSellStopTime,LastSellStopMagic;   
string comm,gl_timeseria,upname,dnname; double Last_BS_SL,Last_SS_SL;
double LastLotsBS,LastLotsSS,CurProfit; int Last_BS_ticket,Last_SS_ticket;
double Op_BL, Op_SL,BuyLots,SellLots,minlots; int orders_BL,orders_SL;
double  LastLots;
//--------------------------------------------------------------------
double NL(double lots){
   double MaxLots=MarketInfo(Symbol(),MODE_MAXLOT);
   double MinLots=MarketInfo(Symbol(),MODE_MINLOT);
   double StepLots=MarketInfo(Symbol(),MODE_LOTSTEP);
   double lot=NormalizeDouble(lots/StepLots,0)*StepLots;
   //if (lot>MaxLots) lot=MaxLots; 
   if (lot>100) lot=100; 
   if (lot<MinLots) lot=MinLots; 
   return (lot); 
}
//--------------------------------------------------------------------
double Lots(){
double lots =Lots; 
if(USE_MM )lots=AccountBalance()*0.0001*Risk; 
return(NL(lots));}
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---- авто пятизнак-----
   mp=1; 
   if(Auto_4_digits)if(Digits==3 || Digits==5)mp=10;
   Otstup_point_b *=mp; Otstup_point_s *=mp;
   TP_buy*= mp; SL_buy*= mp; TP_sell*=mp;SL_sell*=mp;
   prevtime=Time[0];
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
  if(!IsTradeAllowed())return(0);
  if(Закрытие_в_пятницу   ==    true)
   if(DayOfWeek( )>=5 && TimeHour(TimeCurrent()) >= Время
                      && TimeMinute(TimeCurrent()) >= Время_мин){Закрыть_всё();return(0);}
 
  if(TrailingStopFr) TrailingStop();
   
  if(Start_BU+TrailingStop>0) Tral();

//----
   if(prevtime==Time[0])return(0); prevtime=Time[0];
   
   _lastExtremum=GetExtremumZZPrice(1);
   Comment (_lastExtremum);
   ORDERS_SCANER();
   if (Close[0]<_lastExtremum){
      if(LastTimeUP>TimeLastUP){
      //if (_extType!=OP_BUYSTOP){
        // DeleteOrder(OP_BUYSTOP);
         _price=NormalizeDouble((_lastExtremum+Otstup_point_b*Point),Digits);
        // _extType=OP_BUYSTOP;
        if(MathAbs(_price-LastOpenPrise_BS)>=2*Point*mp) 
         if(SetStopOrder(MAGIC,1,Lots(),_price,SL_buy,TP_buy, "")>0){TimeLastUP=LastTimeUP;return(0);}
          else {prevtime=Time[1]; _extType=-1;}
      }
   }
   if (Close[0]>_lastExtremum){
      if(LastTimeDN>TimeLastDN){
    //  if (_extType!=OP_SELLSTOP){
    //     DeleteOrder(OP_SELLSTOP);
         _price=NormalizeDouble((_lastExtremum-Otstup_point_s*Point),Digits);
    //      _extType=OP_SELLSTOP;
         if(MathAbs(_price-LastOpenPrise_SS)>=2*Point*mp) 
          if(SetStopOrder(MAGIC,-1,Lots(),_price,SL_sell,TP_sell, "")>0){TimeLastDN=LastTimeDN;return(0);}
          else {prevtime=Time[1]; _extType=-1;}
      }
   }
   
//----
   return(0);
  }
//--------------------------------------------------------------------
//+------------------------------------------------------------------+
int ORDERS_SCANER(){
//------------------счетчик ордеров ----------------------------------      
   orders_buystop=0;orders_sellstop=0; orders_buy=0;orders_sell=0;
   LastOpenPriseOpenBuy=0;LastOpenPriseOpenSell=0;
   LastOpenBuySL=0;  LastOpenSellSL=0;
   LastOpenBuyLots=0; LastOpenSellLots = 0;  
   OpenBuyTime=0;OpenSellTime=0;
   OpenBuyStopTime=0; LastOpenPrise_SS=0; LastOpenPrise_BS=0;
   OpenSellStopTime=0;Last_BS_SL=0;Last_SS_SL=0; CurProfit=0;
   Last_BS_ticket=0; Last_SS_ticket=0; LastLotsBS=0;LastLotsSS=0; 
   start_buystop=0;start_sellstop=0; BuyLots=0; SellLots=0;
//----   
   for (int i=OrdersTotal();i>=1;i--){
         if(OrderSelect(i-1, SELECT_BY_POS, MODE_TRADES))
         if(OrderSymbol ()!= Symbol())continue;
         if (MAGIC>0)if (OrderMagicNumber()!=MAGIC)continue;
         if(OrderType() == OP_BUY ){
              if(OpenBuyTime < OrderOpenTime()){
                    OpenBuyTime=OrderOpenTime();
                    LastOpenPriseOpenBuy=OrderOpenPrice();
                    LastOpenBuySL = OrderStopLoss();                    
                    LastOpenBuyLots = OrderLots();   
                    }
             BuyLots += OrderLots();   
             orders_buy++;CurProfit+=OrderProfit()+OrderSwap();
             }
            if(OrderType() == OP_SELL)
             {
              if(OpenSellTime < OrderOpenTime()){
                    OpenSellTime=OrderOpenTime();
                    LastOpenPriseOpenSell=OrderOpenPrice();
                    LastOpenSellSL = OrderStopLoss();
                    LastOpenSellLots = OrderLots();  
                    }
              SellLots += OrderLots();
              orders_sell++;CurProfit+=OrderProfit()+OrderSwap();
             } 
             if(OrderType() == OP_BUYSTOP){  
                 if(OpenBuyStopTime < OrderOpenTime()){
                    OpenBuyStopTime=OrderOpenTime();
                    Last_BS_SL=OrderStopLoss();
                    LastOpenPrise_BS=OrderOpenPrice();
                    LastLotsBS = OrderLots();  
                    }
                    Last_BS_ticket=OrderTicket();
                    orders_buystop++;
                    }
             if(OrderType() == OP_SELLSTOP){  
                 if(OpenSellStopTime < OrderOpenTime()){
                    OpenSellStopTime=OrderOpenTime();
                    Last_SS_SL=OrderStopLoss();
                    LastOpenPrise_SS=OrderOpenPrice();
                    LastLotsSS = OrderLots(); 
                    }      
                    Last_SS_ticket=OrderTicket();
                    orders_sellstop++;
                    }     
              }
if(LastOpenBuyLots>LastOpenSellLots)LastLots=LastOpenBuyLots;
if(LastOpenSellLots>LastOpenBuyLots)LastLots=LastOpenSellLots;
return(orders_buy+orders_sell+orders_buystop+orders_sellstop);
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
int SetStopOrder(int Magic, int ord, double lots ,double price,int SL,int TP, string comm)
{
   int ticket=0;
   double  sl,tp,minlot=MarketInfo(Symbol(),MODE_MINLOT), maxlot=MarketInfo(Symbol(),MODE_MAXLOT);
   int STOPLEVEL=MarketInfo(Symbol(),MODE_STOPLEVEL);
   while (IsTradeContextBusy())  Sleep(500); RefreshRates();
   if(lots<minlot)lots=minlot;
   if(lots>=maxlot)lots=maxlot;
    if(AccountFreeMarginCheck(Symbol(), OP_SELL, lots) <= 0 || GetLastError() == 134)/* NOT_ENOUGH_MONEY */
     {
       Print("Нет или не хватает для открытия  свободных средств");return(0);}    
   if (ord==-1 && Bid >= NormalizeDouble(price-STOPLEVEL*Point,Digits)) 
      {
         if (SL!=0) sl = NormalizeDouble(price+SL*Point,Digits); else sl = 0;
         if (TP!=0) tp = NormalizeDouble(price-TP*Point,Digits); else tp = 0;
         ticket=OrderSend(Symbol(),OP_SELLSTOP,lots,price,1,sl,tp,comm,Magic,0,Red);
         if(ticket>0)return(ticket);
          else  Print("ОШИБКА УСТАНОВКИ  ОРДЕРА СЕЛЛСТОП ",GetLastError());
      }
      if (ord== 1 && Ask <= NormalizeDouble(price+STOPLEVEL*Point,Digits)) 
      {
         if (SL!=0) sl = NormalizeDouble(price-SL*Point,Digits); else sl = 0;
         if (TP!=0) tp = NormalizeDouble(price+TP*Point,Digits); else tp = 0;
         ticket=OrderSend(Symbol(),OP_BUYSTOP, lots,price,1,sl,tp,comm,Magic,0,Blue);
         if(ticket>0)return(ticket);
          else  Print("ОШИБКА УСТАНОВКИ  ОРДЕРА БАЙСТОП ",GetLastError());
      }
return(ticket);   
}
//--------------------------------------------------------------------
//+------------------------------------------------------------------+
double GetExtremumZZPrice(int ne=0) {
   double zz;   
   int    i, k=iBars(Symbol(), 0), ke=0;
   for (i=1; i<k; i++) {
      zz=iCustom(Symbol(),0, "ZigZag", ExtDepth,ExtDeviation,ExtBackstep,0,i);
      if (zz!=0) {
         ke++;
         if (ke>ne) { if(Close[1]<zz)LastTimeUP=Time[i];
                      if(Close[1]>zz)LastTimeDN=Time[i];
                       return(zz);break;}     
      }   
   }   
   return(0); 
} 
//+------------------------------------------------------------------+
int DeleteOrder(){
   int i;
   if (OrdersTotal()>0){
      for (i=OrdersTotal()-1; i>=0; i--){
         if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
            if (OrderType()>1 && OrderMagicNumber()==MAGIC){
                while (IsTradeContextBusy()) Sleep(1000);
                OrderDelete(OrderTicket());}
         }
      }
   }
   return(0);
}
//+------------------------------------------------------------------+
//----------------------------------------------------------------
void Tral(){
  int minstop= MarketInfo(Symbol(),MODE_STOPLEVEL),k_8=mp;
  if(minstop==0)minstop+=1;
  int Orders = OrdersTotal(); double stop,op,bid,ask,new_stop;
  for (int i=0; i<=Orders; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
    if (OrderSymbol() != Symbol()) continue; 
    if (OrderMagicNumber()!=MAGIC) continue; 
    //---
    if (OrderType() == OP_BUY) {
      while (IsTradeContextBusy()) Sleep(1000); RefreshRates();
      bid=Bid; stop=OrderStopLoss(); op=OrderOpenPrice();
      new_stop=stop;
      if(Start_BU >0 &&  stop<op)
        if(bid-op > Start_BU*k_8*Point)
          if(bid-(op+Level_BU*k_8*Point) > minstop*Point)new_stop=op+Level_BU*k_8*Point;
      
      if(TrailingStop>0)
      if((Start_BU >0 &&  stop>op) ||Start_BU ==0)
        if(stop < bid-(TrailingStop+TrailingStep-1)*k_8*Point || stop == 0) new_stop= bid-TrailingStop*k_8*Point;
      
      
      if(new_stop<=stop || new_stop==0)continue;   
       if(new_stop!=0 && new_stop > minstop*Point){ 
          if(!OrderModify(OrderTicket(),op,NormalizeDouble(new_stop,Digits),OrderTakeProfit(), 0, Aqua))
            {Print(" Повторить операцию трейлинг-стопа, ошибка - ", GetLastError()); Sleep (1000);} 
           
       }}
    if (OrderType() == OP_SELL) {
      while (IsTradeContextBusy()) Sleep(1000); RefreshRates();
      ask=Ask;stop=OrderStopLoss(); op=OrderOpenPrice();
      new_stop=stop;
      if(Start_BU >0 && ( stop>op|| stop == 0))
        if(op-ask > Start_BU*k_8*Point)
         if((op-Level_BU*k_8*Point)-ask > minstop*Point) new_stop=op-Level_BU*k_8*Point;
     
      if(TrailingStop>0) 
       if((Start_BU >0  &&  stop!=0 &&  stop<op) || Start_BU ==0)
        if(stop > ask+(TrailingStop+TrailingStep-1)*k_8*Point || stop == 0)
             new_stop=ask+TrailingStop*k_8*Point;
      
      
         if(new_stop!=stop && new_stop-ask > minstop*Point){
         if(!OrderModify(OrderTicket(),op,NormalizeDouble(new_stop,Digits),OrderTakeProfit(), 0, Lime))
            {Print(" Повторить операцию трейлинг-стопа, ошибка - ",GetLastError()); Sleep (1000); } 
            
         }}
       }
   }
}
//---------------------------------------------------------------------------
//+------------------------------------------------------------------------------+
//|                                                                 TrailingStop |
//|                                           Copyright © 2010, Хлыстов Владимир |
//|                                                            cmillion@narod.ru |
//+------------------------------------------------------------------------------+
void TrailingStop()
{
   int tip,Ticket;
   bool error;
   double StLo,OSL,OOP;
   for (int i=0; i<OrdersTotal(); i++) 
   {  if (OrderSelect(i, SELECT_BY_POS)==true)
      {  tip = OrderType();
         if (tip<2 && OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC)
         {
            OSL   = OrderStopLoss();
            OOP   = OrderOpenPrice();
            Ticket = OrderTicket();
            if (tip==OP_BUY)             
            {
               StLo = NormalizeDouble(SlLastBar(1,Bid),Digits);        
               if (StLo==0) continue;        
               if (StLo < OOP) continue;
               if (StLo > OSL)
               {  error=OrderModify(Ticket,OOP,StLo,OrderTakeProfit(),0,DeepPink);
                  if (!error) Print("Error order ",Ticket," TrailingStop ",GetLastError(),"   ",Symbol(),"   SL ",StLo);
                  else Print("TrailingStopFR ",Ticket," ",TimeToStr(TimeCurrent(),TIME_MINUTES));
               }
            }                                         
            if (tip==OP_SELL)        
            {
               StLo = NormalizeDouble(SlLastBar(-1,Ask),Digits);  
               if (StLo==0) continue;        
               if (StLo > OOP) continue;
               if (StLo < OSL || OSL==0 )
               {  error=OrderModify(Ticket,OOP,StLo,OrderTakeProfit(),0,DeepPink);
                  if (!error) Print("Error order ",Ticket," TrailingStop ",GetLastError(),"   ",Symbol(),"   SL ",StLo);
                   else Print("TrailingStopFR "+Ticket," ",TimeToStr(TimeCurrent(),TIME_MINUTES));
               }
            } 
         }
      }
   }
}
//--------------------------------------------------------------------
double SlLastBar(int tip,double price)
{
   double fr;
   int i;
   int    STOPLEVEL=MarketInfo(Symbol(),MODE_STOPLEVEL);
   if (tip== 1)
   {
      for (i=2; i<100; i++) 
      {
         fr = iFractals(NULL,0,MODE_LOWER,i);
         if (fr!=0) {if (price-STOPLEVEL*Point > fr) return(fr);}
         else return(0);
      }
   }
   if (tip==-1)
   {
      for (i=2; i<100; i++) 
      {
         fr = iFractals(NULL,0,MODE_UPPER,i);
         if (fr!=0) {if (price+STOPLEVEL*Point < fr) return(fr);}
         else return(0);
      }
   }
}
//--------------------------------------------------------------------
//+------------------------------------------------------------------+ 
void CloseAll() {
int mp=1; if(Digits==3 || Digits==5)mp=10; 
bool   CurSymbolOnly   = True;            // Только текущий символ
bool   UseSound        = False;           // Использовать звуковой сигнал
string NameFileSound   = "expert.wav";    // Наименование звукового файла
int    Slippage        = 5*mp;               // Проскальзывание цены
int    NumberOfTry     = 3;               // Количество попыток
int    PauseAfterError = 3;              // Пауза после ошибки в секундах
color clCloseBuy  = Blue;         // Цвет значка закрытия покупки
color clCloseSell = Red;          // Цвет значка закрытия продажи
//---
  bool   fc;
  double pp;
  int    err, i, it, k=OrdersTotal();
//---- 
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber()!=MAGIC) continue;
      if (!CurSymbolOnly || OrderSymbol()==Symbol()) {
        fc=False;
        for (it=1; it<=NumberOfTry; it++) {
          while (!IsTradeAllowed()) Sleep(500);
          RefreshRates();
          if (OrderType()==OP_BUY ) {
            pp=MarketInfo(OrderSymbol(), MODE_BID);
            fc=OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseBuy);
            if (fc) {
              if (UseSound) PlaySound(NameFileSound); break;
            } else {
              err=GetLastError();
              Print("Error",err);
              Sleep(1000*PauseAfterError);
            }
          }
          if (OrderType()==OP_SELL) {
            pp=MarketInfo(OrderSymbol(), MODE_ASK);
            fc=OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseSell);
            if (fc) {
              if (UseSound) PlaySound(NameFileSound); break;
            } else {
              err=GetLastError();
              Print("Error",err);
              Sleep(1000*PauseAfterError);
            }
          }
        }
      }
    }
  }
//Sleep(1000*Period()+100);
}
/////////////////////////////////////////////////////////////////////////
void Закрыть_всё()
   {
    CloseAll();
    DeleteOrder();
   }

Комментарии к исходному коду форекс советника ZZ_H1v2.1.mq4
В целях безопасности и борьбы со спамом в тексте комментариев запрещено размещать html-теги и ссылки. Благодарим за понимание.

  • X
  • 0% загружено
« советник ZZElse.mq4
советник ZaharovAndrey_25.mq4 »