MQL4: полезные функции пишем сюда

Тема в разделе "Индикаторы, скрипты и эксперты для МТ4", создана пользователем RickD, 5 июн 2006.

Метки:
  1. RickD

    RickD MQL4 developer

    Очень полезная функция split и примеры ее использования.

    split - разделяет элементы строки и возвращает их в виде массива.

    Параметры:
    Код:
    [OUT] string& arr[] - возвращаемый массив строк.
    [IN] string str - входная строка.
    [IN] string sym - разделитель.
    Пример:
    Код:
      string text = "1; 2; 3; 4; 5";
      string dig[];
      split(dig, text, ";");
    
    //Теперь массив dig будет содержать 5 элементов:  "1", "2", "3", "4", "5".

    Код:
    void split(string& arr[], string str, string sym) 
    {
      ArrayResize(arr, 0);
    
      string item;
      int pos, size;
      
      int len = StringLen(str);
      for (int i=0; i < len;) {
    	pos = StringFind(str, sym, i);
    	if (pos == -1) pos = len;
    	
    	item = StringSubstr(str, i, pos-i);
    	item = StringTrimLeft(item);
    	item = StringTrimRight(item);
    	
    	size = ArraySize(arr);
    	ArrayResize(arr, size+1);
    	arr[size] = item;
    	
    	i = pos+1;
      }
    }
     
  2. RickD

    RickD MQL4 developer

    Теперь более полезный пример.
    Предположим советник должен открывать позицию в указанный промежуток времени. Этот промежуток удобно записать в следующем виде: "12:00-12:03".
    Далее - таких временных интервалов может быть несколько. Удобно будет записать их в виде одной строки-параметра: "12:00-12:03; 13:00-13:05; 15:20-15:21".
    Это дает нам возможность как указывать неограниченное количество временных интервалов, так и ни одного.
    Код для постановки позиции будем следующим:

    Код:
      extern string OpenTime = "10:00-10:05; 12:20-12:31; 13:40-13:55";
    
      string OTA[];
      string OTI[];
      split(OTA, OpenTime, ";");
      
      datetime tm0 = CurTime();
      datetime tm1, tm2;
      
      bool cond = false;
      
      int cnt = ArraySize(OTA);
      for (int i=0; i < cnt; i++) {
    	split(OTI, OTA[i], "-");
    	if (ArraySize(OTI) != 2) continue;
    	
    	tm1 = StrToTime(TimeToStr(CurTime(), TIME_DATE) + " " + OTI[0]);
    	tm2 = StrToTime(TimeToStr(CurTime(), TIME_DATE) + " " + OTI[1]);
    	
    //	Print (OTI[0], " *** " ,OTI[1]);
    	
    	cond = cond || (tm1 <= tm0 && tm0 < tm2);
      }
      
    		
      if (cond)
      {
    	//Открываем позицию либо выполняем иные действия.
      }
     
  3. artindent

    artindent Троянский лось™

    А через маркетинфо функцию стандартную нельзя чтоли ;)
     
  4. artindent

    artindent Троянский лось™

    ;) Более стандартные фцнкци есть, например
    Код:
       iBarShift(Symbol(), 0, "2006.09.01 00:00");
     
  5. RickD

    RickD MQL4 developer

    Код:
      int orders = 0;
      
      int cnt = HistoryTotal();
      for (int i=0; i < cnt; i++) {
    	if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
    	
    	//if (OrderSymbol() != Symbol()) continue;
    	//if (OrderMagicNumber() != Magic) continue;
    	
    	if (CurTime() - OrderCloseTime() > 24*60*60) continue;
    	
    	int type = OrderType();
    	if (type == OP_BUY || type == OP_SELL) 
    	{
    	  if (OrderProfit() < 0) orders++;  
    	}
      }
      
      if (orders > 2) return;
    Т.е. смотрим ордера за последние 24 часа с отрицательным профитом.
     
  6. leonid553

    leonid553 Активный пользователь

    Уважаемые специалисты.
    Напишите пож. iCustom для индикатора ДиНаполи:

    double DIN= iCustom(NULL, 0, " DinapoliTargets" ... ... ... );

    Никак не получается!
    Индикатор - в закачке.
     

    Вложения:

  7. kharko

    kharko Активный пользователь

    Код:
    double DIN= iCustom(Symbol(),0,"DinapoliTargets",barn,Length,0,shift);
     
  8. leonid553

    leonid553 Активный пользователь

    Добрый день всем!
    В моем советнике прописано условие, например, на покупку. Oткрыта позиция двумя лотами:

    ticket = OrderSend(Symbol(), OP_BUY, lots*2, Ask, 3, Bid - sl * Point, 0,
    "F1", MagicNumber, 0, Blue);

    Мне необходимо частично закрыть позицию - один лот, - когда цена достигнет профита , задаваемого внешним параметром "тейкпрофит" . Второй же лот не должен реагировать на этот параметр!
    Пож. подскажите кусочек такого кода?
    И для длинной и для короткой позиции... Либо общий - для обеих сразу.
     
  9. RickD

    RickD MQL4 developer

    Добрый вечер.

    Примерно так будет:
    Код:
     
      OrderSelect(ticket);
    
      if (Bid-OrderOpenPrice() > TakeProfit1*Point && OrderLots() == 2*lots) {
    	OrderClose(ticket, lots, Bid, 3);
      }
     
  10. leonid553

    leonid553 Активный пользователь

    Благодарю, RickD !
     
  11. RickD

    RickD MQL4 developer

    1. Загоняете все тикеты в массив.
    2. Сортируете - как душе угодно.

    Вот например функции сортировки и сравнения:
    Код:
    void Sort(int& Tickets[]) 
    {
      int cnt = ArraySize(Tickets);
      for (int i=0; i < cnt; i++) {
    	for (int j=i+1; j < cnt; j++) {
    	  int res = Compare(Tickets[i], Tickets[j]);
    
    	  if (res == -1) {
    		int ticket = Tickets[i];
    		Tickets[i] = Tickets[j];
    		Tickets[j] = ticket;		
    	  }
    	}
      }  
    }
    
    int Compare(int ticket1, int ticket2) 
    {
      if (!OrderSelect(ticket1, SELECT_BY_TICKET, MODE_HISTORY)) return (0);
      datetime tm1 = OrderCloseTime();
      
      if (!OrderSelect(ticket2, SELECT_BY_TICKET, MODE_HISTORY)) return (0);
      datetime tm2 = OrderCloseTime();
      
      if (tm1 < tm2) return (1);
      if (tm1 > tm2) return (-1);
    
      return (0);
    }
     
  12. finger

    finger Alex

    от KimIV

    Возвращает флаг закрытия последней позиции по стопу.

    isCloseLastPosByStop
    isCloseLastPosByTake


    ;)

    Код:
    //+----------------------------------------------------------------------------+
    //|  Возвращает флаг закрытия последней позиции по стопу.		  
    //|  Параметры:																			 
    //|	sym - наименование инструмента  ("" - текущий символ)		  
    //|	op  - операция				  (-1 - любая позиция)					 
    //|	mn  - MagicNumber			   (-1 - любой магик)					  
    //+----------------------------------------------------------------------------+
    bool isCloseLastPosByStop(string sym="", int op=-1, int mn=-1) {
      datetime t;
      double   ocp, osl;
      int	  dg, i, j=-1, k=OrdersHistoryTotal();
     
      if (sym=="") sym=Symbol();
      for (i=0; i<k; i++) {
    	if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
    	  if (OrderSymbol()==sym) {
    		if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
    		  if (op<0 || OrderType()==op) {
    			if (mn<0 || OrderMagicNumber()==mn) {
    			  if (t<OrderCloseTime()) {
    				t=OrderCloseTime();
    				j=i;
    			  }
    			}
    		  }
    		}
    	  }
    	}
      }
      if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
    	dg=MarketInfo(sym, MODE_DIGITS);
    	if (dg==0) if (StringFind(sym, "JPY")<0) dg=4; else dg=2;
    	ocp=NormalizeDouble(OrderClosePrice(), dg);
    	osl=NormalizeDouble(OrderStopLoss(), dg);
    	if (ocp==osl) return(True);
      }
      return(False);
    }
     
    
    
    
    //+----------------------------------------------------------------------------+
    //|  Возвращает флаг закрытия последней позиции по тейку.					  
    //|  Параметры:																
    //|	sym - наименование инструмента  ("" - текущий символ)				   
    //|	op  - операция				  (-1 - любая позиция)					
    //|	mn  - MagicNumber			   (-1 - любой магик)					  
    //+----------------------------------------------------------------------------+
    bool isCloseLastPosByTake(string sym="", int op=-1, int mn=-1) {
      datetime t;
      double   ocp, otp;
      int	  dg, i, j=-1, k=OrdersHistoryTotal();
     
      if (sym=="") sym=Symbol();
      for (i=0; i<k; i++) {
    	if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
    	  if (OrderSymbol()==sym) {
    		if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
    		  if (op<0 || OrderType()==op) {
    			if (mn<0 || OrderMagicNumber()==mn) {
    			  if (t<OrderCloseTime()) {
    				t=OrderCloseTime();
    				j=i;
    			  }
    			}
    		  }
    		}
    	  }
    	}
      }
      if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
    	dg=MarketInfo(sym, MODE_DIGITS);
    	if (dg==0) if (StringFind(sym, "JPY")<0) dg=4; else dg=2;
    	ocp=NormalizeDouble(OrderClosePrice(), dg);
    	otp=NormalizeDouble(OrderTakeProfit(), dg);
    	if (ocp==otp) return(True);
      }
      return(False);
    }
     
  13. RickD

    RickD MQL4 developer

    Код:
    extern int Profit = 9;
    extern int Slippage = 3;
    
    if (AccountProfit() >= Profit) CloseOrders();
    
    void CloseOrders() 
    {
      int cnt = OrdersTotal();
      for (int i=cnt-1; i>=0; i--) {
    	if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
    
    	if (OrderType() == OP_BUY) OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), Slippage);
    	if (OrderType() == OP_SELL) OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), Slippage);
      }
    }
     
  14. RickD

    RickD MQL4 developer

    Код:
    extern double Profit = 1;
    extern int Slippage = 3;
    
    if (AccountProfit() > Profit) 
    {
    	CloseOrders(OP_BUY);
    	//or CloseOrders(OP_SELL);
    }
    
    void CloseOrders(int type) 
    {
      int cnt = OrdersTotal();
      for (int i=cnt-1; i>=0; i--) 
      {
    	if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
     
    	//if (OrderSymbol() != Symbol()) continue;
    	//if (OrderMagicNumber() != Magic) continue;
    	
    	if (OrderType() != type) continue;
    	
    	if (type == OP_BUY) 
    	{
    	  RefreshRates();
    	  OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), Slippage);
    	  continue;
    	}
    
    	if (type == OP_SELL)
    	{
    	   RefreshRates();
    	   OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), Slippage);
    	   continue;
    	}
      }
    }
     
  15. RickD

    RickD MQL4 developer

    Код:
    datetime Time0 = 0;
    
    void start()
    {
      if (iTime(NULL, PERIOD_H4, 0) != Time0)
      {
    	Time0 = iTime(NULL, PERIOD_H4, 0);
    	Close(...
      }
    }
     
  16. alf

    alf Старый опытный камикадзе

    Постановка вопроса изменилась ;)
    Вопрос: на графике имеются 2 объекта (левая и правая ценовые метки), есть ли возможность получить их параметр (цену) для двух переменных скрипта?
     
  17. finger

    finger Alex

    Stamp
    Печать функции часть данных относительно диаграммы, используя размер шрифта, напечатайте и покрасите Вас, хотят. Вы можете установить x и y текста.


    Parameters:
    message: The piece of data you want to print on the chart - Type: string.
    Font_Size: The size of the font - Type: integer.
    Font_Name: The name of the font - Type: string.
    Font_Color: The color of the font - Type: color,
    x: The x coordinate of the print.
    y: The y coordinate of the print.

    Код:
    void Stamp(string message , int Font_Size , string Font_Name , color Font_Color , int x , int y)
    {
       string Obj="Stamp_" + message;
       int objs = ObjectsTotal();
       string name;
     
       for(int i=0;i<objs;i++)
    	 { 
    		 int res = ObjectFind(Obj);
    		 if (res != -1){
    		 ObjectSet(Obj,OBJPROP_XDISTANCE,x);
    		 ObjectSet(Obj,OBJPROP_YDISTANCE,y);
    		 WindowRedraw();
    
    		 }
    	 
    	 
    	  else
    	  {
    		 ObjectCreate(Obj,OBJ_LABEL,0,0,0);
    		 ObjectSetText(Obj,message,Font_Size,Font_Name,Font_Color);
    		 ObjectSet(Obj,OBJPROP_XDISTANCE,x);
    		 ObjectSet(Obj,OBJPROP_YDISTANCE,y);
    		 WindowRedraw();
    
    	  }
       }
       if (ObjectsTotal() == 0)
       {
    		 ObjectCreate(Obj,OBJ_LABEL,0,0,0);
    		 ObjectSetText(Obj,message,Font_Size,Font_Name,Font_Color);
    		 ObjectSet(Obj,OBJPROP_XDISTANCE,x);
    		 ObjectSet(Obj,OBJPROP_YDISTANCE,y);
    		 WindowRedraw();
    
    
       }
       
       return(0);
    }

    Example:

    Код:
    Stamp("Hi World,8,"arial",Red,5,20);
     
  18. finger

    finger Alex

    использование Многократными парами времени
    IsInTradingTime()

    Код:
    bool IsInTradingTime(string TRADE_TIME)
    {
      int i;
      string s;
      
      int ipc;
      datetime dtStart[100];  datetime dtEnd[100];
      string strLocalDate;
      
      bool bRet;
      
      //========
      
      // First, we eliminate each invalid character from the time string.
      s="";
      for (i=0;i<StringLen(TRADE_TIME);i++)
    	if (((StringGetChar(TRADE_TIME,i)>='0') && (StringGetChar(TRADE_TIME,i)<='9')) ||
    		(StringSubstr(TRADE_TIME,i,1)=="-") ||
    		(StringSubstr(TRADE_TIME,i,1)==":") ||
    		(StringSubstr(TRADE_TIME,i,1)==";"))
    	  s=s+StringSubstr(TRADE_TIME,i,1);
      
      TRADE_TIME=s;
      
      // The trading time string contains always a pair of times, 
      // separated with "-". Multiple time pairs can be entered by
      // separating each pair with ";".
      //
      // Example: "00:00-06:59;22:00-23:59"
    
      // First, get the current local date.
      strLocalDate=TimeToStr(LocalTime(),TIME_DATE);
      
      // Parse the string.
      i=0;
      ipc=0;
      while (true)
      {
    	// Get start time.
    	s="";
    	while ((StringSubstr(TRADE_TIME,i,1)!="-") && (i<StringLen(TRADE_TIME)))
    	{
    	  s=s+StringSubstr(TRADE_TIME,i,1);
    	  i++;
    	}
    	// Create the full date/time and add it to the start time list.
    	dtStart[ipc]=StrToTime(strLocalDate+" "+s);
    	
    	i++;
    
    	// Get end time.
    	s="";
    	while ((StringSubstr(TRADE_TIME,i,1)!=";") && (i<StringLen(TRADE_TIME)))
    	{
    	  s=s+StringSubstr(TRADE_TIME,i,1);
    	  i++;
    	}
    	// Create the full date/time and add it to the end time list.
    	dtEnd[ipc]=StrToTime(strLocalDate+" "+s);
    	
    	i++;
    
    	// Next pair.
    	ipc++;  
    
    	if (i>=StringLen(TRADE_TIME))
    	  break;
      }
    
      // Now, compare the current time against our list and return
      // result.
      bRet=true;
      for (i=0;i<ipc;i++)
      {
    	if ((LocalTime()>=dtStart[i]) && (LocalTime()<=dtEnd[i]))
    	  bRet=false;
    
    	/*  
    	Alert("Start=",TimeToStr(dtStart[i]));
    	Alert("End  =",TimeToStr(dtEnd[i]));
    	Alert("Local=",TimeToStr(LocalTime()));
    	Alert("Result=",bRet);
    	*/
      }
      
      return (bRet);
    }

    Beispiel
    Код:
    extern string DONT_TRADE_TIME="00:00-06:59;22:00-23:59";
    
    int start()
    {
    if (IsInTradingTime(DONT_TRADE_TIME) ) return(0);
    }

    ;)
     
  19. finger

    finger Alex

    close all open Orders 120 seconds before the Next BAR coming
    is possible ?

    закройте все открытые Заказы за 120 секунд до того, как Следующее прибытие БРУСКА возможно?

    :bs:
     
  20. RickD

    RickD MQL4 developer

    It is impossible. The close time of a bar is unknown.
     

Поделиться этой страницей