Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 1130

 
trader781:

Hi all, just continuing to refine what we already have

We have an irregular grid of orders and a horizontal line which can be anywhere

We need to implement this:

if the price is below the line close all orders

The difficulties are as follows

1) if the orders are of non-uniform type and already when setting the line everything is done, and not when we put the marking and set the line (in this case we should also set the on/off flag)

2) Implementation of an inscription on the top right of the line by type (if the order is closed at this price, the result will be the same for the balance, i.e., we have to change the display every tick and also when moving the line; it is generally similar to a trailing stop or sl if the order is placed manually, only floating and with the possibility of erroneous triggers initially)

The robot is there, except for the numerical marker everything is already drawn, the question is in the correct assignment of values and information processing of the whole grid.

Take a look at this one, maybe it will work.
TralingLine
TralingLine
  • votes: 13
  • 2016.09.26
  • Alexey Viktorov
  • www.mql5.com
Виртуальный Stop Loss или Trailing Stop.
 
Alexey Viktorov:
Check this out, maybe it'll fit.
Yeah, that's about all we need, just need to figure out how to modify it for a 4
 
Nauris Zukas:
Hello. I don't understand why iTime sometimes gives wrong time. The opening of a new candle PERIOD_H1 should show the time in the log Print(iTime(NULL,PERIOD_M1,30)). It displays everything correctly in tests, but in reality the time is sometimes different even by several hours. Why is it so?
Vitaly Muzichenko:

UseCopyTime, I also noticed this problem when building graphical objects andCopyTime solved the problem

datetime TM[];
if(CopyTime(Symbol(),Period(),0,1,TM)<0) return;
TIME0=TM[0];
I wondered whether you can set the RefreshRates() function. Maybe it will also help?
 
Nauris Zukas:
I wondered if RefreshRates() could be put in. Maybe it would help too?
Didn't try it, immediately applied the normal universal solution and forgot about the problem.
 
Vitaly Muzichenko:
I didn't try it, applied a normal universal solution at once and forgot about the problem.
Ok, for the sake of interest I will do it with RefreshRates() on one terminal and CopyTime on another.
 
trader781:
Yes, that's roughly what I need, now I just need to figure out how to upgrade to 4.
First just compile for mql4 and test. It should work. If not, here is old mql4 code. And even with error handling.

//*******************************************************************|
//|                                                  TralingLine.mq4 |
//|                                       Copyright © 2010, Viktorov |
//|                                                   v4forex@qip.ru |
//*******************************************************************|
#property copyright "Copyright © 2010, Viktorov"
#property link      "v4forex@qip.ru"

extern int     StopLevel   = 7;
extern color   ColorLine   = IndianRed;
extern bool    comment     =  false;

double prbuys, prsels, TICKVALUE, FixProfitBuy, FixProfitSel;
int Buy, Sel;

//****************expert initialization function*********************|
   bool     run         = True,
            Error       = False;
   int      slip        =  3;
   double   point,
            STOPLEVEL;
int init()
  {
  point  = Point;
  if((Digits == 3 || Digits == 5))
  {
  point  = Point*10;
  slip   *= 10;
  }
  run = True;
  Error = False;
TICKVALUE = MarketInfo(Symbol(), MODE_TICKVALUE);

   return(0);
}//******************************************************************|
double   nd(double v){return(NormalizeDouble(v,Digits));}
string   dts(double v){return(DoubleToStr(v, Digits));}
string   dts2(double v){return(DoubleToStr(v, 2));}
string   ttss(int v){return(TimeToStr(v,TIME_SECONDS));}
//*******************************************************************|
//|                     expert start function                        |
//*******************************************************************|
int start()
  {
     double nprbuys, nprsels;
   CountTrades();
  
   if(Buy > 0 && ObjectFind("StopBuy") == -1) drawline(OP_BUY);
   if(Sel > 0 && ObjectFind("StopSel") == -1) drawline(OP_SELL);
   if(ObjectFind("StopBuy") != -1)
   nprbuys = ObjectGetValueByShift("StopBuy", 0);
   if(ObjectFind("StopSel")!=-1)
   nprsels = ObjectGetValueByShift("StopSel", 0);
  
   if(nprbuys > 0 && Bid <= nprbuys)
   {
    CloseOrder(OP_BUY);
    if(ObjectFind("StopBuy") != -1) ObjectDelete("StopBuy");
   }
   if(nprsels > 0 && Ask >= nprsels)
   {
    CloseOrder(OP_SELL);
    if(ObjectFind("StopSel") != -1) ObjectDelete("StopSel");
   }
      FixProfit();
    if(comment)
   Comment("\n Текущее время  ", ttss(TimeCurrent())
         , "\n Ордера Buy закроются по цене ", dts(nprbuys), ". Фиксированная прибыль ", dts2(FixProfitBuy)
         , "\n Ордера Sell закроются по цене ", dts(nprsels), ". Фиксированная прибыль ", dts2(FixProfitSel)
         );
   return(0);
}//******************************************************************|
  
//********************Подсчёт профита всех ордеров*******************|
void FixProfit()
{  double LineB, LineS, Profit, tv;
   LineB = nd(ObjectGetValueByShift("StopBuy", 0));
   LineS = nd(ObjectGetValueByShift("StopSel", 0));
    tv = TICKVALUE; FixProfitBuy = 0; FixProfitSel = 0;
     int Total = OrdersTotal();
  
   for(int i = Total-1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
     {
     if(OrderSymbol() == Symbol())
       {
        if(OrderType() == OP_BUY && LineB > 0)
         {
          if(StringSubstr(Symbol(),0,3) == "USD") tv = TICKVALUE*Bid/LineB;
          FixProfitBuy += (OrderCommission() + OrderSwap() + (LineB - OrderOpenPrice())*tv*OrderLots()/Point);
         }
        if(OrderType() == OP_SELL && LineS > 0)
         {
          if(StringSubstr(Symbol(),0,3) == "USD") tv = TICKVALUE*Bid/LineS;
          FixProfitSel += (OrderCommission() + OrderSwap() + (OrderOpenPrice() - LineS)*tv*OrderLots()/Point);
         }
       }
     Profit += OrderProfit();
     }
    }
}//******************************************************************|

//*******Подсчёт открытых ордеров OP_BUY & OP_BUYSTOP****************|
        void CountTrades()
           {   Buy = 0; Sel = 0;
            int Total = OrdersTotal();
            for(int i = 0; i < Total; i++)
             {
              if(OrderSelect(i, SELECT_BY_POS))
              {
              if(OrderSymbol() == Symbol())
               {
               if(OrderType() == OP_BUY) Buy++;
                  if(OrderType() ==  OP_SELL) Sel++;
               }
              }
             }//for
           }//*******************************************************|

//**********************рисование линий******************************|
void drawline(int sig)
{
   double   Otstup_ = StopLevel*point;
    if(sig == OP_BUY)
     {
      prbuys = nd(iLow(NULL, 0, 1)-Otstup_);
       ObjectCreate("StopBuy", OBJ_TREND, 0, Time[0]+2*Period()*60, prbuys, Time[0]+4*Period()*60, prbuys);
       ObjectSet("StopBuy", OBJPROP_COLOR, ColorLine);
       ObjectSet("StopBuy", OBJPROP_STYLE, STYLE_DOT);
     }
    if(sig == OP_SELL)
     {
      prsels = nd(iHigh(NULL, 0, 1)+Otstup_);
       ObjectCreate("StopSel", OBJ_TREND, 0, Time[0]+2*Period()*60, prsels, Time[0]+4*Period()*60, prsels);  
       ObjectSet("StopSel", OBJPROP_COLOR, ColorLine);
       ObjectSet("StopSel", OBJPROP_STYLE, STYLE_DOT);
     }
   return;
}//******************************************************************|

//********************Закрытие ордеров*******************************|
void CloseOrder(int sig)
{     double GH, FE, c = 0; bool OrdClose; int Total = OrdersTotal();

            for(int i = 0; i < Total; i++)
              {
               OrdClose = False;
   if(OrderSelect(i, SELECT_BY_POS,MODE_TRADES) && OrderSymbol() == Symbol())
      {
      if(OrderType() == sig)
       {
      while(!OrdClose) // Цикл закрытия ордера 8 попыток
            {
      RefreshRates();
        if(OrderType() == OP_BUY)  GH = Bid;
   else if(OrderType() == OP_SELL) GH = Ask;
      OrdClose =  OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(GH, Digits), slip, CLR_NONE);
               if(OrdClose) i--;
         if(!OrdClose)
         {
      FE = Fun_Error(GetLastError());
            if(FE == 1) {  continue;   } // Повторная попытка
       else if(FE == 0) { Print("Неудачная попытка CloseOrder Error = ", GetLastError()); return;}
       else {  Print("Неудачная попытка CloseOrder"); return;   }
         }
            } // Цикл while(c < 8)
       }
      }
              }//for
   return;
}//******************************************************************|

//*********************Ф-ия обработки ошибок*************************|
int Fun_Error(int error)
{
      switch(error)
   { // Преодолимые ошибки
   case 0: return(1);
   case 4: //Print("Торговый сервер занят. Пробуем ещё раз...");
   Sleep(500); // Простое решение
   return(1); // Выход из функции
   case 128:   //Истек срок ожидания совершения сделки
   return(1);
   case 6: //Print("Нет связи с торговым сервером. Пробуем ещё раз...");
   Sleep(10000); // Простое решение
   return(1); // Выход из функции
   case 129: //Print("Цена изменилась. Пробуем ещё раз...");
   return(1); // Выход из функции
   case 132: //Print("Рынок закрыт. Пробуем ещё раз...");
   Sleep(123000); // Простое решение
   return(1); // Выход из функции
   case 135: //Print("Цена изменилась. Пробуем ещё раз...");
   RefreshRates(); // Обновим данные
   return(1); // Выход из функции
   case 136: //Print("Нет цен. Ждём новый тик...");
   while(RefreshRates()==false) // До нового тика
   Sleep(1); // Задержка в цикле
   return(1); // Выход из функции
   case 137: //Print("Брокер занят. Пробуем ещё раз...");
   Sleep(500); // Простое решение
   return(1); // Выход из функции
   case 138: //Print("Новые цены. Пробуем ещё раз...");
   Sleep(1); // Задержка в цикле
   return(1); // Выход из функции
   case 146: //Print("Подсистема торговли занята. Пробуем ещё...");
   Sleep(500); // Простое решение
   return(1); // Выход из функции
   case 4107: //Print("Неправильный параметр цены для торговой функции. Пробуем ещё...");
   Sleep(50); // Простое решение
   return(1); // Выход из функции
// Критические ошибки
   case 1:
   return(0);
   case 2: Alert("Общая ошибка. Перегрузите терминал и\или компьютер.");
   return(0); // Выход из функции
   case 5: Alert("Старая версия терминала.");
   //Work=false; // Больше не работать
   return(0); // Выход из функции
   case 64: Alert("Счет заблокирован.");
   //Work=false; // Больше не работать
   return(0); // Выход из функции
   case 130: //Alert("Неправильные стопы.");
   return(0); // Выход из функции
   case 133: Alert("Торговля запрещена.");
   return(0); // Выход из функции
   case 134: Alert("Недостаточно денег для совершения операции.");
   return(0); // Выход из функции
   case 4051: Alert("Недопустимое значение параметра функции.");
   return(0); // Выход из функции
   case 4108: Alert("Неверный номер тикета.");
   return(0); // Выход из функции
   default: //Print("Возникла ошибка ",Error); // Другие варианты
   return(0); // Выход из функции
   }
}//******************************************************************|

//****************expert deinitialization function*******************|
int deinit()
  {
  ObjectDelete("StopBuy");
  ObjectDelete("StopSel");
   return(0);
}//******************************************************************|

 
Nauris Zukas:
OK, for the sake of interest I will do on one terminal with RefreshRates() and on the other with CopyTime.
The time shift problem was showing up well in the tester, so RefreshRates may not help.
 
Vitaly Muzichenko:
The time offset problem showed up well in the tester, so RefreshRates might not help.
I see, then doing with CopyTime.
 

1. Is there any handy tool for synchronizing Expert Advisors, indicators and scripts between terminals? (for example, I program on one terminal, then I need to send the Expert Advisor to the terminals I trade on)

2. Is there an example of automatic updating (loading a new version) of an EA on a working chart?

 
How to make a bid line in a custom indicator?

I prescribe it like this

      ObjectCreate("line",OBJ_HLINE,windowIndex,0,Bid);
              
      ObjectSet("line",OBJPROP_COLOR,Red);
      ObjectSet("line",OBJPROP_WIDTH,1);

      WindowRedraw();  

But it's built once and it's already there. it's static.
I need it to change with every tick, like a bid line on a price chart.
Reason: