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

 
Mihail Matkovskij #:

Pero no es así. Hay que llevar la cuenta del resultado de

o su nueva función en OnTradeTransaction. Y si no hay puestos, deberías entrar. O escribir la señal en buySignal osellSignal y procesarla en OnTimer como he mostrado en el ejemplo.

ClosePosWithMaxProfitInCurrency

Esta función ya no es relevante. No es adecuado. En su lugar, debemos sustituir la función que cerrará una orden abierta primero, si existe.

No entiendo las variables buySignal ysellSignal escritas en el ámbito global. Pero cuando intento compilarlo, me da el siguiente error

'sellSignal' - some operator expected   

expression has no effect        

'buySignal' - some operator expected    

expression has no effect        



 

Buenas tardes.

Ciertamente he leído todo esto, y puedo escribir cada orden por separado, pero la pregunta era para acortar el código.

 
Buenas tardes, compañeros! Por favor, aconsejad a un novato, cómo obtener el valor actual (en el momento) del indicador, no de la barra anterior? El Asesor Experto sólo se activa cuando la barra anterior termina, y lo necesito antes.
 
makssub #:

Buenas tardes.

Ciertamente he leído todo esto, y puedo escribir cada orden por separado, pero la pregunta era para acortar el código.

¿Qué es exactamente lo que no funciona del acortamiento del código?

 
Shockeir #:
Hola Colegas, ¿podrían aconsejar a un novato cómo obtener el valor actual (en el momento) de un indicador y no el valor de la barra anterior? El EA sólo se dispara cuando termina la barra anterior, y yo lo necesito antes.

Tal vez una descripción más detallada de la situación y de lo que no le funciona sería más útil.

 
Andrey Sokolov #:

Tal vez una descripción más detallada de la situación y de lo que usted no puede hacer dé más resultados.

El indicador es un estocástico estándar. El Asesor Experto debe activarse en la intersección de las líneas K y D. Al cruzar hasta que aparece una nueva barra, no pasa nada. Cuando aparece una nueva barra, si la condición se sigue cumpliendo, se actúa. Por lo que entiendo, es porque el último valor en los buffers del indicador es el valor calculado en la última barra completada. Por lo tanto, me gustaría que la activación se produjera en una barra sin terminar.

 
Shockeir #:

El indicador es un estocástico estándar. El Asesor Experto debe activarse en la intersección de las líneas K y D. En el mismo cruce, hasta que aparece una nueva barra, no pasa nada. En cuanto aparece una nueva barra, si la condición se sigue cumpliendo, se actúa. Por lo que entiendo, es porque el último valor en los buffers del indicador es el valor calculado en la última barra completada. Entonces, me gustaría que la acción se activara en una barra no terminada.

La última vela tiene un índice de 0.

¿Cómo ha intentado resolver este problema? ¿Has leído la ayuda? ¿Qué es exactamente lo que no funciona?

 
Andrey Sokolov #:

¿Puedes poner el código? Por lo menos, aclare qué idioma está utilizando.

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2020, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//--- input parameters
input double   crossDepthOpen=7;    //Глубина пересечения K и D для открытия
input double   crossDepthClose=-2;  //Глубина пересечения K и D для закрытия
input double   closeCoef=5;         //Коэффициент изменения глубины закрытия
input int      k_period=8;          //Период K
input int      d_period=3;          //Период В
input int      slowing=3;           //Сглаживание
input double   tp_1=20;             //Тейк
input double   sl_1=60;             //Лосс
input double   maxPos=2.0;          //Размер лота

int      stoch_handle;
double   k_buffer[1];
double   d_buffer[1];
double   TKP;
double   STL;
double   CDO;
double   CDC;
int      lossCount=0;
int      profitCount=0;
int      EA_magic=12345;


//| Expert initialization function

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   TKP=tp_1;
   STL=sl_1;

   stoch_handle=iStochastic(_Symbol,PERIOD_CURRENT,k_period,d_period,slowing,MODE_EMA,STO_LOWHIGH);
   if(stoch_handle<0)
     {
      Alert("Ошибка при создании индикаторов ",GetLastError());
      return(0);
     }
   return(INIT_SUCCEEDED);
  }

//| Expert tick function

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   CDO=crossDepthOpen;
   CDC=crossDepthClose;
   MqlTick latestPrice;
   MqlTradeResult mResult;
   MqlTradeRequest mRequest;
   ZeroMemory(mRequest);
   SymbolInfoTick(_Symbol,latestPrice);
   ArraySetAsSeries(k_buffer,true);
   ArraySetAsSeries(d_buffer,true);
   if(CopyBuffer(stoch_handle,0,0,1,k_buffer)<0)
     {
      Alert("Не удалось скопировать в буфер K",GetLastError());
      return;
     }
   if(CopyBuffer(stoch_handle,1,0,1,d_buffer)<0)
     {
      Alert("Не удалось скопировать в буфер D",GetLastError());
      return;
     }

   bool buyFullOpened=false;
   bool buyPartOpened=false;
   bool sellFullOpened=false;
   bool sellPartOpened=false;

//Состояние позиций
   if(PositionSelect(_Symbol)==true)
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         if(PositionGetDouble(POSITION_VOLUME)>=maxPos)
           {
            buyFullOpened=true;
           }
         else
           {
            buyPartOpened=true;
           }
        }
      else
         if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
           {

            if(PositionGetDouble(POSITION_VOLUME)>=maxPos)
              {
               sellFullOpened=true;
              }
            else
              {
               sellPartOpened=true;
              }
           }
     }
//состояние позиций конец

//Условия изменения позиций
   bool buyOpenCondition=k_buffer[0]>((d_buffer[0])+CDO);
   bool buyCloseCondition=k_buffer[0]<((d_buffer[0])-CDC);
   bool buyTPCondition=latestPrice.bid>(PositionGetDouble(POSITION_PRICE_OPEN)+TKP*_Point);
   bool buySLCondition=latestPrice.bid<(PositionGetDouble(POSITION_PRICE_OPEN)-STL*_Point);
   bool sellOpenCondition=k_buffer[0]<((d_buffer[0])-CDO);
   bool sellCloseCondition=k_buffer[0]>((d_buffer[0])+CDC);
   bool sellTPCondition=latestPrice.ask<(PositionGetDouble(POSITION_PRICE_OPEN)-TKP*_Point);
   bool sellSLCondition=latestPrice.ask>(PositionGetDouble(POSITION_PRICE_OPEN)+STL*_Point);
//Условия изменения позиций конец

//Проверка и выполнение действий
   if(buyOpenCondition)
     {
      if(!buyFullOpened && !buyPartOpened && !sellPartOpened && !sellFullOpened)
        {
         Print("Покупка по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0; //NormalizeDouble(latestPrice.ask - STL*Point(),_Digits);
         mRequest.tp = 0; //NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = maxPos;
         OrderSend(mRequest,mResult);
         Print("Открыто ",PositionGetDouble(POSITION_VOLUME)," по ", PositionGetDouble(POSITION_PRICE_OPEN));
        }
     }
//Условия покупки
   if(sellTPCondition)
     {
      if(sellFullOpened)
        {
         Print("Тейк-профит шорта");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.ask - STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = MathRound(PositionGetDouble(POSITION_VOLUME)/2);
         OrderSend(mRequest,mResult);
         ++profitCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(sellSLCondition)
     {
      if(sellFullOpened || sellPartOpened)
        {
         Print("Стоп-лосс шорта");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.ask - STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         ++lossCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(sellCloseCondition)
     {
      if(sellFullOpened || sellPartOpened)
        {
         Print("Закрытие шорта по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.ask - STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

//Условия продажи
   if(sellOpenCondition)
     {
      if(!sellFullOpened && !buyPartOpened && !sellPartOpened && !buyFullOpened)
        {
         Print("Продажа по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0; //NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0; //NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = maxPos;
         OrderSend(mRequest,mResult);
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }
   if(buyTPCondition)
     {
      if(buyFullOpened)
        {
         Print("Тейк-профит лонга");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = MathRound(PositionGetDouble(POSITION_VOLUME)/2);
         OrderSend(mRequest,mResult);
         ++profitCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(buySLCondition)
     {
      if(buyFullOpened || buyPartOpened)
        {
         Print("Стоп-лосс лонга");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         ++lossCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(buyCloseCondition)
     {
      if(buyFullOpened || buyPartOpened)
        {
         Print("Закрытие лонга по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }
  }
//+------------------------------------------------------------------+
//| Trade function                                                   |
//+------------------------------------------------------------------+
void OnTrade()
  {
//---

  }
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   IndicatorRelease(stoch_handle);
   Print("loss ",lossCount);
   Print("profit ",profitCount);
  }
//+------------------------------------------------------------------+
Andrey Sokolov #:

¿Puedes poner el código? Al menos aclara en qué idioma lo haces.

 

Foro sobre comercio, sistemas de comercio automatizados y pruebas de estrategias

Cualquier pregunta de los novatos sobre MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos

GlaVredFX, 2022.01.17 22:52

ClosePosWithMaxProfitInCurrency

No debería utilizar más esta función. No es relevante. Si esta función existe, debe ser sustituida por una función que cierre la primera orden abierta.

No entiendo las variables buySignal ysellSignal prescritas a nivel global. Pero cuando intento compilarlo, me da el siguiente error

'sellSignal' - some operator expected   

expression has no effect        

'buySignal' - some operator expected    

expression has no effect        



¿Cómo los ha registrado y dónde interfiere el compilador? No puedo adivinar. Necesitas el código fuente para entenderlo.
 
Shockeir #:
Hola Colegas, ¿podéis aconsejar a un novato cómo obtener el valor actual (en el momento) del indicador, y no el valor de la barra anterior? El EA sólo se dispara cuando termina la barra anterior, y yo lo necesito antes.

Las matrices k_buffer[0] y d_buffer[0] contienen los últimos valores del indicador. ¿Cuál es el problema de emitirlos y verlos usted mismo?

Razón de la queja: