[ARCHIVE!] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Can't go anywhere without you - 4. - page 118

 
For closed STOP Orders, OrderOpenTime() returns the time the position was opened.
Is it possible to find out from the code the time when the STOP-Order was set?
Thank you!
 
chief2000:
For closed stop orders, OrderOpenTime() returns the time when the position was opened.
Is it possible to find out from the code the time when the STOP-Order was set?
Thank you!


There's no such thing as a closed stop, there's a remote one...

Doesn't OrderOpenTime() - for set and not triggered stops - return its setting time?

 
Roman.:

There's no such thing as a closed stop, there's a remote one...

Doesn't OrderOpenTime() - for a set and not triggered stop return the time of its setting?

You are right, I was not accurate.
I meant that we set a STOP-order which triggered and a position was opened on it.
But the position may be opened on the same bar where the STOP-order was set, or it may be opened some time later.

The OrderOpenTime() shows the time when the position was opened, my question is, how do we know when the stop order was set?
The MT4 report has this time, but is it possible to find it out from the code?

 
If your broker provides this information, then look for an order with a given type, price and magician closed at the time of triggering (going to market)
 

I get the following error at compilation

'&&' - condition cannot be a string \00.mq4 (225, 27)

'&&' - condition can't be a string

how to fix it ?

 
Lians:

Dear Professionals, I found a useful Expert Advisor for setting virtual take and stop and trailing stops (attached). But virtual stop loss does not work correctly. Please help me to correct it. Or maybe someone has a good analogue?

I would like to give my thanks.

Here's a similar SCRIPT.

Description in code.
Files:
 

was compiled by an advisor

//+------------------------------------------------------------------+
//|                                                           00.mq4 |
//|                        Copyright 2012, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"
//+------------------------------------------------------------------+

color clModifyBuy;
color clCloseBuy;

// Внешние переменные:
extern double ll =1;
extern int tp = 0;
extern int sl = 0;
extern int mn = 777;
extern int Slippage = 3; 
extern int    NumberOfTry = 5;  
//-------------------------------------------------------------------+
//|  Описание : Установка ордера. Версия функции для тестов на истории.
//|  Выставления отложенных ордеров на покупку    |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    op - операция                                                           |
//|    ll - лот                                                                |
//|    pp - цена                                                               |
//|    sl - уровень стоп                                                       |
//|    tp - уровень тейк                                                       |
//|    mn - Magic Number                                                       |
//|    ex - Срок истечения                                                     |
//+----------------------------------------------------------------------------+
void SetOrder(string sy, int op, double ll, double pp,
              double sl=0, double tp=0, int mn=0, datetime ex=0) {
  color clOpen;
  int   err, ticket;
 
  if (sy=="" || sy=="0") sy=Symbol();
  if (op==OP_BUYLIMIT || op==OP_BUYSTOP) clOpen=clOpenBuy;
  ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, "", mn, ex, clOpen);
  if (ticket<0) {
    err=GetLastError();
    Print("Error(",err,") set ",GetNameOP(op),": ",ErrorDescription(err));
    Print("Ask=",Ask," sy=",sy," ll=",ll,
          " pp=",pp," sl=",sl," tp=",tp," mn=",mn);
  }
}
//+----------------------------------------------------------------------------+
//|  Описание: Закрытие одной предварительно выбранной позиции     
//|  Закрывает отложенный ордера на покупку.         |
//+----------------------------------------------------------------------------+
void ClosePosBySelect() {
  double pp;

  if (OrderType()==2) {
    pp=MarketInfo(OrderSymbol(), MODE_BID);
    OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseBuy);
  }
  if (OrderType()==4) {
    pp=MarketInfo(OrderSymbol(), MODE_BID);
    OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseBuy);
     
  }
}


//|  Описание : Возвращает количество ордеров.                                 |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любой ордер)                    |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
int NumberOfOrders(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), ko=0, ot;

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if (ot>1 && ot<6) {
        if ((OrderSymbol()==sy || sy=="") && (op<0 || ot==op)) {
          if (mn<0 || OrderMagicNumber()==mn) ko++;
        }
      }
    }
  }
  return(ko);
}
//|  Описание : Возвращает цену TakeProfit последней открытой позиций или -1.  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double TakeProfitLastPos(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   r=-1;
  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 (t<OrderOpenTime()) {
                t=OrderOpenTime();
                r=OrderTakeProfit();
              }
            }
          }
        }
      }
    }
  }
  return(r);
}
 
//|  Описание : Возвращает цену TakeProfit последней закрытой позиций или -1.  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double TakeProfitLastClosePos(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   r=-1;
  int      i, k=OrdersHistoryTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (t<OrderCloseTime()) {
                t=OrderCloseTime();
                r=OrderTakeProfit();
              }
            }
          }
        }
      }
    }
  }
  return(r);
}
//|  Описание : Открытие позиции. Версия функции для тестов на истории.        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ("" - текущий символ)                   |
//|    op - операция                                                           |
//|    ll - лот                                                                |
//|    sl - уровень стоп                                                       |
//|    tp - уровень тейк                                                       |
//|    mn - MagicNumber                                                        |
//+----------------------------------------------------------------------------+
void OpenPosition(string sy, int op, double ll, double sl=0, double tp=0, int mn=0) {
  color  clOpen;
  double pp;
  int    err, ticket;
 
  if (sy=="") sy=Symbol();
  if (op==OP_BUY) {
    pp=MarketInfo(sy, MODE_ASK); clOpen=clOpenBuy;
  } 
  ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, "", mn, 0, clOpen);
  if (ticket<0) {
    err=GetLastError();
    Print("Error(",err,") open ",GetNameOP(op),": ",ErrorDescription(err));
    Print("Ask=",Ask," sy=",sy," ll=",ll,
          " pp=",pp," sl=",sl," tp=",tp," mn=",mn);
  }
}
//|  Описание : Модификация одного предварительно выбранного ордера.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    pp - цена установки ордера                                              |
//|    sl - ценовой уровень стопа                                              |
//|    tp - ценовой уровень тейка                                              |
//|    ex - дата истечения                                                     |
//+----------------------------------------------------------------------------+
void ModifyOrder(double pp=-1, double sl=0, double tp=0, datetime ex=0) {
  bool   fm;
  color  cl=IIFc(OrderType()==OP_BUY
              || OrderType()==OP_BUYLIMIT
              || OrderType()==OP_BUYSTOP, clModifyBuy);
  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 (pp!=op || sl!=os || tp!=ot) {
    for (it=1; it<=NumberOfTry; it++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      fm=OrderModify(OrderTicket(), pp, sl, tp, ex, cl);
      if (fm)  else {
        er=GetLastError();
        
        pa=MarketInfo(OrderSymbol(), MODE_ASK);
        pb=MarketInfo(OrderSymbol(), MODE_BID);
        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);
      }
    }
  }
}
//|  Описание : Рассчитывает количество ордеров по типам.                      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    mo - массив количества ордеров по типам                                 |
//|    mn - MagicNumber                          (-1 - любой магик)            |
//+----------------------------------------------------------------------------+
void CountOrders(int& mo[], int mn=-1) {
  int i, k=OrdersTotal();

  if (ArraySize(mo)!=6) ArrayResize(mo, 6);
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (mn<0 || OrderMagicNumber()==mn) mo[OrderType()]++;
    }
  }
}
//+----------------------------------------------------------------------------+
// Удаление ордеров. Версия функции для тестов на истории.  

//| Параметры:                                                                 |
//| sy - наименование инструмента   (NULL - текущий символ)                    |
//| op - операция                   ( -1  - любой ордер)                       |
//| mn - MagicNumber                ( -1  - любой магик)                       |
//+----------------------------------------------------------------------------+
void DeleteOrders(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), ot;
 
  if (sy=="" || sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if (ot==OP_BUYLIMIT || ot==OP_BUYSTOP ) {
        if (OrderSymbol()==sy && (op<0 || ot==op)) {
          if (mn<0 || OrderMagicNumber()==mn) {
            OrderDelete(OrderTicket());
          }
        }
      }
    }
  }
}
//==============================================================================
// --------------------------- Графические функции ----------------------------+
//==============================================================================
void SetHLine(color cl, string nm="", double p1=0, int st=0, int wd=1) {
  if (ObjectFind(nm)<0) ObjectCreate(nm, OBJ_HLINE, 0, 0,0);
  ObjectSet(nm, OBJPROP_PRICE1, p1);
  ObjectSet(nm, OBJPROP_COLOR , cl);
  ObjectSet(nm, OBJPROP_STYLE , st);
  ObjectSet(nm, OBJPROP_WIDTH , wd);
}
 

Outputs 2 errors

'clOpenBuy' - variable not defined .mq4 (40, 49)

clOpenBuy - variable not defined

I rewrote the code again and again - these 2 errors can't be fixed.

 
alex12:

Outputs 2 errors

'clOpenBuy' - variable not defined .mq4 (40, 49)

clOpenBuy - variable not defined

I rewrote the code again and again - these 2 errors can't be fixed.



// Внешние переменные:
extern double ll =1;
extern int tp = 0;
extern int sl = 0;
extern int mn = 777;
extern int Slippage = 3; 
extern int    NumberOfTry = 5;  

color clOpenBuy=Red;
You could do this for example
Reason: