Cualquier pregunta de los recién llegados sobre MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos - página 324

 

¿Es esto correcto?

for(int i=1; i<=TotalPedidos(); i++) // Bucle de pedidos

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // si lo siguiente

{

int OT=Total de órdenes; //el número de órdenes abiertas en la terminal

double Price=OrderOpenPrice(); // Precio de la orden seleccionada

double Mas [Precio][OT]; //array para ordenar todos los pedidos

o

for(int i=1; i<=Total de pedidos(); i++) /bucle de pedidos

{

if (OrderSelect(i-1,SELECT_BY_POS)==true) // si hay un

{

double Price=OrderOpenPrice(); // Precio de la orden seleccionada

double Mas [Precio]; //¿Matriz para ordenar todos los pedidos por precio?

 
vikzip:

¿Es esto correcto?

for(int i=1; i<=TotalPedidos(); i++) // Bucle de pedidos

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // si lo siguiente

{

int OT=Total de órdenes; //el número de órdenes abiertas en la terminal

double Price=OrderOpenPrice(); // Precio de la orden seleccionada

double Mas [Precio][OT]; //array para ordenar todos los pedidos

o

for(int i=1; i<=Total de pedidos(); i++) /bucle de pedidos

{

if (OrderSelect(i-1,SELECT_BY_POS)==true) // si hay un

{

double Price=OrderOpenPrice(); // Precio de la orden seleccionada

double Mas [Precio]; //¿Matriz para ordenar todos los pedidos por precio?

1. OrdersTotal devuelve la cantidad total de pedidos, pero se numeran empezando por cero. Por eso el bucle debe ser i < OrdersTotal()

2. La matriz debe ser declarada doble Mas[];. Si el pedido se selecciona con éxito, el tamaño del array debe aumentar, porque no sabemos cuántos pedidos hay en total.

3. El índice de la cadena del array debe estar entre corchetes. Mas[i] = Precio;

En consecuencia, ambos están equivocados.

 
Alexey Viktorov:

1. OrdersTotal devuelve el número total de pedidos, pero se numeran empezando por cero. Por eso el bucle debe ser i < OrdersTotal()

2. La matriz debe ser declarada doble Mas[];. Si se elige una orden con éxito, el tamaño del array debe aumentar, porque no sabemos cuántas hay...

3. El índice de la cadena del array debe estar entre corchetes. Mas[i] = Precio;

En consecuencia, ambos están equivocados.


¡Muchas gracias!

 
Alexey Viktorov:

1. OrdersTotal devuelve el número total de pedidos, pero se numeran empezando por cero. Por lo tanto, el bucle debe ser i < OrdersTotal()

2. La matriz debe ser declarada doble Mas[];. Si se elige una orden con éxito, el tamaño del array debe aumentar, porque no sabemos cuántas hay...

3. El índice de la cadena del array debe estar entre corchetes. Mas[i] = Precio;

En consecuencia, ambos están equivocados.


¿Obtendremos una matriz unidimensional de precios de pedidos en este caso?

double Price=OrderOpenPrice(); // Precio de la orden seleccionada

double Mas[i] = Precio; //array para poner en orden todas las órdenes

for(int i=1; i<OrdersTotal();) // Bucle de pedidos

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // si hay un siguiente

i++;

}

 
vikzip:

¿Y en este caso, será una matriz unidimensional de precios de pedidos?

double Price=OrderOpenPrice(); // Precio de la orden seleccionada

double Mas[i] = Precio; //array para poner en orden todas las órdenes

for(int i=1; i<OrdersTotal();) // Bucle de pedidos

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // si hay un siguiente

i++;

}

No. Es más o menos así.
  double Price;               // Цена выбранного ордера
  double Mas[];                      //массив для упорядочивания всех ордеров
  for(int i=0; i<OrdersTotal(); i++;)          // Цикл перебора ордер
   {
    if(OrderSelect(i,SELECT_BY_POS)==true) // Если есть следующий
     {
      ArrayResize(Mas, ArraySyze()+1);
      Mas[i] = OrderOpenPrice();
// или 
//    Price=OrderOpenPrice();
//    Mas[i] = Price;
     }
   }

La selección ==true no puede ser escrita.

 
Alexey Viktorov:
No. Es más o menos así.

El resaltado ==true no puede ser escrito.


¡Muchas gracias!

 
Por la tarde, hay una línea para seleccionar el beneficio en moneda. Quiero 1) tener una opción en la configuración del EA de un beneficio fijo ( como ya es) o una parte del depósito como porcentaje. Por favor, aconséjeme cómo hacerlo.
La cadena original es esta:

Beneficio doble externo =10;

2) hacer que se habilite el autoconteo de la ganancia, deshabilitado por el dígito seleccionado del saldo de la cuenta.

El resultado final:
Beneficio: fijar/autocontar.
Arreglar - cantidad.
Autorizar - porcentaje de saldo.
Activar la ejecución automática - beneficio %.
Desactivar la ejecución automática - beneficio/pérdida en %.
Seleccione el valor a partir del cual se contabilizarán las ganancias/pérdidas de la cuenta automática
 

Hola. ¿Pueden decirme cómo eliminar el cierre y la apertura de una orden pendiente en cada barra? Necesito que se abra y esperar a que se abra la orden correspondiente.

//+------------------------------------------------------------------+
//|                                                e-News-Lucky$.mq4 |
//|                                                   Lucky$ & KimIV |
//|                                              http://www.kimiv.ru |
//|                                                                  |
//|   24.10.2005                                                     |
//| Выставление ордеров в определённое время на пробой диапазона.    |
//| Если ни один ордер не сработал, то модификация на каждом баре.   |
//+------------------------------------------------------------------+
#property copyright "Lucky$ & KimIV"
#property link      "http://www.kimiv.ru"
#define    MAGIC     123

//------- Внешние параметры советника --------------------------------
extern string _Parameters_Trade = "----- Параметры торговли";
extern double Lots           = 0.01;     // Размер торгуемого лота
extern int    StopLoss       = 0;      // Размер фиксированного стопа
extern int    TakeProfit     = 0;       // Размер фиксированного тэйка
extern string TimeSetOrders  = "10:30"; // Время установки ордеров
extern string TimeDelOrders  = "22:30"; // Время удаления ордеров
extern string TimeClosePos   = "22:30"; // Время закрытия позиций
extern int    DistanceSet    = 200;      // Расстояние от рынка
extern bool   UseTrailing    = True;    // Использовать трал
extern bool   ProfitTrailing = True;    // Тралить только профит
extern int    TrailingStop   = 25;      // Фиксированный размер трала
extern int    TrailingStep   = 5;       // Шаг трала
extern int    Slippage       = 3;       // Проскальзывание цены

extern string _Parameters_Expert = "----- Параметры советника";
extern string Name_Expert   = "e-News-Lucky$";
extern bool   UseSound      = True;         // Использовать звуковой сигнал
extern string NameFileSound = "expert.wav"; // Наименование звукового файла
extern color  clOpenBuy     = LightBlue;    // Цвет открытия покупки
extern color  clOpenSell    = LightCoral;   // Цвет открытия продажи
extern color  clModifyBuy   = Aqua;         // Цвет модификации покупки
extern color  clModifySell  = Tomato;       // Цвет модификации продажи
extern color  clCloseBuy    = Blue;         // Цвет закрытия покупки
extern color  clCloseSell   = Red;          // Цвет закрытия продажи

//---- Глобальные переменные советника -------------------------------
int prevBar;

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
void deinit() {
  Comment("");
}

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
void start() {
  if (TimeToStr(CurTime(), TIME_MINUTES)==TimeSetOrders) SetOrders();
  if (prevBar!=Bars && ExistOrder(1) && ExistOrder(2)) ModifyOrders();
  DeleteOppositeOrders();
  TrailingPositions();
  if (TimeToStr(CurTime(), TIME_DATE)==TimeDelOrders) DeleteAllOrders();
  if (TimeToStr(CurTime(), TIME_MINUTES)==TimeClosePos) CloseAllPositions();
  prevBar=Bars;
}

//+------------------------------------------------------------------+
//| Установка ордеров                                                |
//+------------------------------------------------------------------+
void SetOrders() {
  double ldStop=0, ldTake=0;
  int    spr=MarketInfo(Symbol(), MODE_SPREAD);
  double pAsk=Ask+(DistanceSet+spr)*Point;
  double pBid=Bid-DistanceSet*Point;

  if (!ExistOrder(1)) {
    if (StopLoss!=0) ldStop=pAsk-StopLoss*Point;
    if (TakeProfit!=0) ldTake=pAsk+TakeProfit*Point;
    SetOrder(OP_BUYSTOP, pAsk, ldStop, ldTake, 1);
  }
  if (!ExistOrder(2)) {
    if (StopLoss!=0) ldStop=pBid+StopLoss*Point;
    if (TakeProfit!=0) ldTake=pBid-TakeProfit*Point;
    SetOrder(OP_SELLSTOP, pBid, ldStop, ldTake, 2);
  }
}

//+------------------------------------------------------------------+
//| Модификация ордеров                                              |
//+------------------------------------------------------------------+
void ModifyOrders() {
bool ret;
  double ldStop=0, ldTake=0;
  int    spr=MarketInfo(Symbol(), MODE_SPREAD);
  double pAsk=Ask+(DistanceSet+spr)*Point;
  double pBid=Bid-DistanceSet*Point;

  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+1) {
        if (StopLoss!=0) ldStop=pAsk-StopLoss*Point;
        if (TakeProfit!=0) ldTake=pAsk+TakeProfit*Point;
        ret=OrderModify(OrderTicket(), pAsk, ldStop, ldTake, 0, clModifyBuy);
      }
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+2) {
        if (StopLoss!=0) ldStop=pBid+StopLoss*Point;
        if (TakeProfit!=0) ldTake=pBid-TakeProfit*Point;
        ret=OrderModify(OrderTicket(), pBid, ldStop, ldTake, 0, clModifySell);
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Возвращает флаг существования ордера или позиции по номеру       |
//+------------------------------------------------------------------+
bool ExistOrder(int mn) {
  bool Exist=False;
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+mn) {
        Exist=True; break;
      }
    }
  }
  return(Exist);
}

//+------------------------------------------------------------------+
//| Возвращает флаг существования позиции по номеру                  |
//+------------------------------------------------------------------+
bool ExistPosition(int mn) {
  bool Exist=False;
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+mn) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          Exist=True; break;
        }
      }
    }
  }
  return(Exist);
}

//+------------------------------------------------------------------+
//| Установка ордера                                                 |
//| Параметры:                                                       |
//|   op     - операция                                              |
//|   pp     - цена                                                  |
//|   ldStop - уровень стоп                                          |
//|   ldTake - уровень тейк                                          |
//|   mn     - добавить к MAGIC                                      |
//+------------------------------------------------------------------+
void SetOrder(int op, double pp, double ldStop, double ldTake, int mn) {
  bool ret;
  color  clOpen;
  string lsComm=GetCommentForOrder();

  if (op==OP_BUYSTOP) clOpen=clOpenBuy;
  else clOpen=clOpenSell;
  ret=OrderSend(Symbol(),op,Lots,pp,Slippage,ldStop,ldTake,lsComm,MAGIC+mn,0,clOpen);
  if (UseSound) PlaySound(NameFileSound);
}

//+------------------------------------------------------------------+
//| Генерирует и возвращает строку коментария для ордера или позиции |
//+------------------------------------------------------------------+
string GetCommentForOrder() {
  return(Name_Expert);
}

//+------------------------------------------------------------------+
//| Удаление всех ордеров                                            |
//+------------------------------------------------------------------+
void DeleteAllOrders() {
  bool fd;
  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2) {
        if (OrderSymbol()==Symbol()) {
          if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP) {
            fd=OrderDelete(OrderTicket());
            if (fd && UseSound) PlaySound(NameFileSound);
          }
        }
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Закрытие всех позиций по рыночной цене                           |
//+------------------------------------------------------------------+
void CloseAllPositions() {
  bool fc;
  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2) {
        if (OrderSymbol()==Symbol()) {
          fc=False;
          if (OrderType()==OP_BUY) {
            fc=OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, clCloseBuy);
          }
          if (OrderType()==OP_SELL) {
            fc=OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, clCloseSell);
          }
          if (fc && UseSound) PlaySound(NameFileSound);
        }
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Удаление противоположных ордеров                                 |
//+------------------------------------------------------------------+
void DeleteOppositeOrders() {
  bool fd, fep1, fep2;

  fep1=ExistPosition(1);
  fep2=ExistPosition(2);

  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol()) {
        fd=False;
        if (OrderType()==OP_BUYSTOP && OrderMagicNumber()==MAGIC+1) {
          if (fep2) fd=OrderDelete(OrderTicket());
        }
        if (OrderType()==OP_SELLSTOP && OrderMagicNumber()==MAGIC+2) {
          if (fep1) fd=OrderDelete(OrderTicket());
        }
        if (fd && UseSound) PlaySound(NameFileSound);
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Сопровождение позиции простым тралом                             |
//+------------------------------------------------------------------+
void TrailingPositions() {
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2) {
        if (OrderSymbol()==Symbol()) {
          if (OrderType()==OP_BUY) {
            if (!ProfitTrailing || (Bid-OrderOpenPrice())>TrailingStop*Point) {
              if (OrderStopLoss()<Bid-(TrailingStop+TrailingStep-1)*Point) {
                ModifyStopLoss(Bid-TrailingStop*Point, clModifyBuy);
              }
            }
          }
          if (OrderType()==OP_SELL) {
            if (!ProfitTrailing || OrderOpenPrice()-Ask>TrailingStop*Point) {
              if (OrderStopLoss()>Ask+(TrailingStop+TrailingStep-1)*Point || OrderStopLoss()==0) {
                ModifyStopLoss(Ask+TrailingStop*Point, clModifySell);
              }
            }
          }
        }
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Перенос уровня StopLoss                                          |
//| Параметры:                                                       |
//|   ldStopLoss - уровень StopLoss                                  |
//|   clModify   - цвет модификации                                  |
//+------------------------------------------------------------------+
void ModifyStopLoss(double ldStop, color clModify) {
  bool   fm;
  double ldOpen=OrderOpenPrice();
  double ldTake=OrderTakeProfit();

  fm=OrderModify(OrderTicket(), ldOpen, ldStop, ldTake, 0, clModify);
  if (fm && UseSound) PlaySound(NameFileSound);
}
//+------------------------------------------------------------------+

 

Hola. ¿Alguien aquí utiliza indicadores de ClasterDelta en su trabajo? Tengo una pregunta sobre el uso automático de los datos del indicador VolumeProfile. El caso es que este indicador no devuelve nada sino que sólo dibuja un histograma de líneas de tendencia. Pero al poner el cursor sobre esta línea, aparecerá el valor del volumen negociado en ese tick. Cómo sacar esta información del indicador

¿Alguna idea?

 

Como he encontrado antes de estudiar las clases, de nuevo hay matices que no se describen en los artículos o en algún lugar tan oculto que no es posible encontrar a través de un motor de búsqueda. Todo un día en vano buscando explicaciones. Por ejemplo, qué significa este símbolo y cómo afecta si no. Como se ve a continuación en el ejemplo de stati, primero está y luego no: &

   // Для int. Проверка существования в массиве элемента с заданным значением
   int Find(int & aArray[],int aValue)
     {
      for(int i=0; i<ArraySize(aArray); i++) 
        {
         if(aArray[i]==aValue) 
           {
            return(i); // Элемент существует, возвращаем индекс элемента
           }
        }
      return(-1); // Нет такого элемента, возвращаем -1
     }

También este símbolo no está claro lo que significa: ~

   // Конструктор
                     CName() { Alert("Конструктор"); }
   // Деструктор
                    ~ CName() { Alert("Деструктор"); }

*

CInfo * returnInfo()
  {
   CInfo * i = new CInfo();
   i.symbol=_Symbol;

   return i;
  }
Razón de la queja: