[ARCHIVE !] Toute question de débutant, pour ne pas encombrer le forum. Professionnels, ne passez pas à côté. Nulle part sans toi - 4. - page 117

 
chief2000:
Pour les ordres stop fermés, OrderOpenTime() renvoie l'heure à laquelle la position a été ouverte.
Est-il possible de savoir, à partir du code, à quel moment l'ordre d'arrêt a été activé ?
Merci !


Il n'y a pas d'arrêt fermé, il y a un arrêt à distance...

La fonction OrderOpenTime() ne renvoie-t-elle pas son heure de déclenchement - pour les arrêts fixés et non déclenchés ?

 
Roman.:

Il n'y a pas d'arrêt fermé, il y a un arrêt à distance...

OrderOpenTime() ne renvoie-t-il pas l'heure de la mise en place d'un arrêt non déclenché ?

Vous avez raison, je n'étais pas précis.
Je voulais dire que nous avons placé un ordre STOP qui s'est déclenché et une position a été ouverte sur cet ordre.
Mais la position peut être ouverte sur la même barre où l'ordre STOP a été fixé, ou bien elle peut être ouverte un peu plus tard.

L'OrderOpenTime() indique l'heure à laquelle la position a été ouverte, ma question est la suivante : comment savoir quand l'ordre stop a été fixé ?
Le rapport MT4 indique cette heure, mais est-il possible de la découvrir à partir du code ?

 
Si votre courtier fournit ces informations, recherchez un ordre avec un type, un prix et un magicien fermé au moment du déclenchement (passage au marché).
 

J'obtiens l'erreur suivante à la compilation

'&&' - la condition ne peut pas être une chaîne de caractères \00.mq4 (225, 27)

'&&' - la condition ne peut pas être une chaîne de caractères

comment le réparer ?

 
Lians:

Chers professionnels, j'ai trouvé un Expert Advisor utile pour définir des take and stop et des trailing stops virtuels (ci-joint). Mais le stop loss virtuel ne fonctionne pas correctement. Veuillez m'aider à le corriger. Ou peut-être que quelqu'un a un bon analogue ?

Je tiens à vous remercier.

Voici un SCRIPT similaire .

Description en code.
Dossiers :
 

a été compilé par un conseiller

//+------------------------------------------------------------------+
//|                                                           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);
}
 

Sort 2 erreurs

clOpenBuy' - variable non définie .mq4 (40, 49)

clOpenBuy - variable non définie

J'ai réécrit le code encore et encore - ces 2 erreurs ne peuvent être corrigées.

 
alex12:

Sort 2 erreurs

clOpenBuy' - variable non définie .mq4 (40, 49)

clOpenBuy - variable non définie

J'ai réécrit le code encore et encore - ces 2 erreurs ne peuvent être corrigées.



// Внешние переменные:
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;
Vous pourriez par exemple faire ceci
 
alex12:

Sortie de 2 erreurs

clOpenBuy' - variable non définie .mq4 (40, 49)

clOpenBuy - variable non définie

J'ai réécrit le code et il ne corrige pas ces 2 erreurs.

alex12, je ne te comprends pas. Vous avez quelques emplois dans kodobase et vous posez de telles questions. Vous avez déjà couvert plusieurs fils avec eux.

La variable clOpenBuy n'est pas définie. Elle doit donc être définie. A en juger par le code, il s'agit de quelque chose de similaire à la couleur associée à l'ouverture d'un ordre d'achat.

Vous devez savoir exactement comment la variable est définie. Comme il est utilisé dans plusieurs fonctions différentes, il devrait probablement être global. Définissez-le donc comme global. Et d'autant plus que

color clCloseBuy;

Vous l'avez défini.

Raison: