Codigo proporcional lotaje MQL5

 

Hola buenas, llevo creando algoritmos bastante tiempo en MT4 con un código proporcional de lotaje de riesgo para cada algoritmo. Mide el % de riesgo con el que entra a mercado según el capital actual. Esto lo modifico cambiando su código en mql4, pero me gustaría cambiarme a mql5 ya que su plataforma es muchísimo más potente y los productos que ofrecen los brókers son más amplias normalmente. El problema es que no sé realizar ese cambio de código proporcional de lotaje ni tampoco he encontrado ninguna fuente que lo proporcione.

No sé si hay alguien aquí en el foro que tenga ese código hecho. Me sería de gran ayuda la verdad. 


Muchas gracias y un saludo.

 
Peron Giig:

Buenas! Tienes cientos de ejemplos en el apartado CodeBase.

 

Hola Miguel Angel. Exactamente podrías indicarme donde? No sé donde está ese apartado, siento que sea tan noob pero estoy recién comenzando con MT5.


Gracias y un saludo.

Miguel Angel Vico Alba #:

Buenas! Tienes cientos de ejemplos en el apartado CodeBase.

 
MQL5 Code Base: Asesores Expertos
MQL5 Code Base: Asesores Expertos
  • www.mql5.com
Asesores Expertos para MetaTrader 5 con los códigos fuente
 

Gracias Miguel Ángel, si encuentro el código proporcional de lotaje lo anclaré por aquí por si le sirve a alguien.


Un saludo.

 
Peron Giig:

Hola buenas, llevo creando algoritmos bastante tiempo en MT4 con un código proporcional de lotaje de riesgo para cada algoritmo. Mide el % de riesgo con el que entra a mercado según el capital actual. Esto lo modifico cambiando su código en mql4, pero me gustaría cambiarme a mql5 ya que su plataforma es muchísimo más potente y los productos que ofrecen los brókers son más amplias normalmente. El problema es que no sé realizar ese cambio de código proporcional de lotaje ni tampoco he encontrado ninguna fuente que lo proporcione.

No sé si hay alguien aquí en el foro que tenga ese código hecho. Me sería de gran ayuda la verdad. 


Muchas gracias y un saludo.

¿Por qué no pruebas a poner tu código MQL4 aquí y te ayudamos a traducirlo?

 
David Diez #:

¿Por qué no pruebas a poner tu código MQL4 aquí y te ayudamos a traducirlo?

Hola David,

Perdona pero no he estado muy pendiente del foro.

¡Claro! Aquí mismo pongo un ejemplo de los muchos algoritmos que me saca el EAS junto con la corrección que he hecho al código.

También adjunto el pdf con el que copio y pego el código, junto con un EA sin el código.

static input string _Properties_ = "------"; // --- Expert Properties ---

double Entry_Amount;

input double MaxRiskPerTrade = 1;

input int Maximum_Lots = 5;

input double Minimum_Lots = 0.01;

       input int    Stop_Loss    =      106; // Stop Loss   (pips)

       input int    Take_Profit  =        0; // Take Profit (pips)



static input string ___0______   = "------"; // --- Entry Time ---

       input int    Ind0Param0   =        2; // From hour

       input int    Ind0Param1   =        0; // From minute

       input int    Ind0Param2   =       23; // Until hour

       input int    Ind0Param3   =       59; // Until minute



static input string ___1______   = "------"; // --- Bollinger Bands ---

       input int    Ind1Param0   =       30; // Period

       input double Ind1Param1   =     2.35; // Deviation



static input string ___2______   = "------"; // --- Envelopes ---

       input int    Ind2Param0   =       15; // Period

       input double Ind2Param1   =     0.74; // Deviation %



static input string _Settings___ = "------"; // --- Expert Settings ---

static input int    Magic_Number = 86916976; // Magic Number



#define TRADE_RETRY_COUNT   4

#define TRADE_RETRY_WAIT  100

#define OP_FLAT            -1



// Session time is set in seconds from 00:00

int  sessionSundayOpen          =     0; // 00:00

int  sessionSundayClose         = 86400; // 24:00

int  sessionMondayThursdayOpen  =     0; // 00:00

int  sessionMondayThursdayClose = 86400; // 24:00

int  sessionFridayOpen          =     0; // 00:00

int  sessionFridayClose         = 86400; // 24:00

bool sessionIgnoreSunday        = true;

bool sessionCloseAtSessionClose = false;

bool sessionCloseAtFridayClose  = false;



const double sigma        = 0.000001;

const int    requiredBars = 33;



double posType       = OP_FLAT;

int    posTicket     = 0;

double posLots       = 0;

double posStopLoss   = 0;

double posTakeProfit = 0;



datetime barTime;

double   pip;

double   stopLevel;

bool     isTrailingStop          = false;

bool     setProtectionSeparately = false;

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int OnInit()

  {

   barTime        = Time[0];

   stopLevel      = MarketInfo(_Symbol, MODE_STOPLEVEL);

   pip            = GetPipValue();

   isTrailingStop = isTrailingStop && Stop_Loss > 0;



   return ValidateInit();

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void OnTick()

{

int margin=(int) MarketInfo(_Symbol,MODE_MARGINREQUIRED);

Entry_Amount=(AccountBalance()*MaxRiskPerTrade/1000)/(Stop_Loss);

Entry_Amount = NormalizeEntrySize(Entry_Amount);

if(Time[0]>barTime)

{

barTime=Time[0];

OnBar();

}

}

double NormalizeEntrySize(double size) {

double minlot = MarketInfo(_Symbol, MODE_MINLOT);

double maxlot = MarketInfo(_Symbol, MODE_MAXLOT);

double lotstep = MarketInfo(_Symbol, MODE_LOTSTEP);

if (size <= minlot)

size = minlot;

if (size <=Minimum_Lots)

size = Minimum_Lots;

if (size >= maxlot)

size = maxlot;

if (size >=Maximum_Lots)

size = Maximum_Lots;

size = NormalizeDouble(size, _Digits);

return (size);

}

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void OnBar()

  {

   UpdatePosition();



   if (posType != OP_FLAT && IsForceSessionClose())

     {

      ClosePosition();

      return;

     }



   if ( IsOutOfSession() )

      return;



   if (posType != OP_FLAT)

     {

      ManageClose();

      UpdatePosition();

     }



   if (posType != OP_FLAT && isTrailingStop)

     {

      double trailingStop = GetTrailingStopPrice();

      ManageTrailingStop(trailingStop);

      UpdatePosition();

     }



   int entrySignal = GetEntrySignal();



   if (posType == OP_FLAT && entrySignal != OP_FLAT)

     {

      OpenPosition(entrySignal);

      UpdatePosition();

     }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void UpdatePosition()

  {

   posType   = OP_FLAT;

   posTicket = 0;

   posLots   = 0;

   int total = OrdersTotal();



   for (int pos = total - 1; pos >= 0; pos--)

     {

      if (OrderSelect(pos, SELECT_BY_POS) &&

          OrderSymbol()      == _Symbol   &&

          OrderMagicNumber() == Magic_Number)

        {

         posType       = OrderType();

         posLots       = OrderLots();

         posTicket     = OrderTicket();

         posStopLoss   = OrderStopLoss();

         posTakeProfit = OrderTakeProfit();

         break;

        }

     }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int GetEntrySignal()

  {

   // Entry Time (2, 0, 23, 59)



   int fromTime0  = Ind0Param0 * 3600 + Ind0Param1 * 60;

   int untilTime0 = Ind0Param2 * 3600 + Ind0Param3 * 60;



   MqlDateTime mqlTime0;

   TimeToStruct(Time(0), mqlTime0);

   int barMinutes0 = mqlTime0.hour * 3600 + mqlTime0.min * 60;



   bool isOnTime0 = fromTime0 < untilTime0

      ? barMinutes0 >= fromTime0 && barMinutes0 <= untilTime0

      : barMinutes0 >= fromTime0 || barMinutes0 <= untilTime0;



   bool ind0long  = isOnTime0;

   bool ind0short = isOnTime0;





   // Bollinger Bands (Close, 30, 2.35)

   double ind1upBand1 = iBands(NULL, 0, Ind1Param0, Ind1Param1, 0, PRICE_CLOSE, MODE_UPPER, 1);

   double ind1dnBand1 = iBands(NULL, 0, Ind1Param0, Ind1Param1, 0, PRICE_CLOSE, MODE_LOWER, 1);

   double ind1upBand2 = iBands(NULL, 0, Ind1Param0, Ind1Param1, 0, PRICE_CLOSE, MODE_UPPER, 2);

   double ind1dnBand2 = iBands(NULL, 0, Ind1Param0, Ind1Param1, 0, PRICE_CLOSE, MODE_LOWER, 2);

   bool   ind1long    = Open(0) < ind1dnBand1 - sigma && Open(1) > ind1dnBand2 + sigma;

   bool   ind1short   = Open(0) > ind1upBand1 + sigma && Open(1) < ind1upBand2 - sigma;



   bool canOpenLong  = ind0long && ind1long;

   bool canOpenShort = ind0short && ind1short;



   return canOpenLong  && !canOpenShort ? OP_BUY

        : canOpenShort && !canOpenLong  ? OP_SELL

        : OP_FLAT;

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void ManageClose()

  {

   // Envelopes (Close, Simple, 15, 0.74)

   double ind2upBand1 = iEnvelopes(NULL, 0, Ind2Param0, MODE_SMA, 0, PRICE_CLOSE, Ind2Param1, MODE_UPPER, 1);

   double ind2dnBand1 = iEnvelopes(NULL, 0, Ind2Param0, MODE_SMA, 0, PRICE_CLOSE, Ind2Param1, MODE_LOWER, 1);

   double ind2upBand2 = iEnvelopes(NULL, 0, Ind2Param0, MODE_SMA, 0, PRICE_CLOSE, Ind2Param1, MODE_UPPER, 2);

   double ind2dnBand2 = iEnvelopes(NULL, 0, Ind2Param0, MODE_SMA, 0, PRICE_CLOSE, Ind2Param1, MODE_LOWER, 2);

   bool   ind2long    = Open(0) > ind2dnBand1 + sigma && Open(1) < ind2dnBand2 - sigma;

   bool   ind2short   = Open(0) < ind2upBand1 - sigma && Open(1) > ind2upBand2 + sigma;



   if ( (posType == OP_BUY  && ind2long) ||

        (posType == OP_SELL && ind2short) )

      ClosePosition();

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void OpenPosition(int command)

  {

   for (int attempt = 0; attempt < TRADE_RETRY_COUNT; attempt++)

     {

      int    ticket     = 0;

      int    lastError  = 0;

      bool   modified   = false;

      string comment    = IntegerToString(Magic_Number);

      color  arrowColor = command == OP_BUY ? clrGreen : clrRed;



      if (IsTradeContextFree())

        {

         double price      = command == OP_BUY ? Ask() : Bid();

         double stopLoss   = GetStopLossPrice(command);

         double takeProfit = GetTakeProfitPrice(command);



         if (setProtectionSeparately)

           {

            // Send an entry order without SL and TP

            ticket = OrderSend(_Symbol, command, Entry_Amount, price, 10, 0, 0, comment, Magic_Number, 0, arrowColor);



            // If the order is successful, modify the position with the corresponding SL and TP

            if (ticket > 0 && (Stop_Loss > 0 || Take_Profit > 0))

               modified = OrderModify(ticket, 0, stopLoss, takeProfit, 0, clrBlue);

           }

         else

           {

            // Send an entry order with SL and TP

            ticket    = OrderSend(_Symbol, command, Entry_Amount, price, 10, stopLoss, takeProfit, comment, Magic_Number, 0, arrowColor);

            lastError = GetLastError();



            // If order fails, check if it is because inability to set SL or TP

            if (ticket <= 0 && lastError == 130)

              {

               // Send an entry order without SL and TP

               ticket = OrderSend(_Symbol, command, Entry_Amount, price, 10, 0, 0, comment, Magic_Number, 0, arrowColor);



               // Try setting SL and TP

               if (ticket > 0 && (Stop_Loss > 0 || Take_Profit > 0))

                  modified = OrderModify(ticket, 0, stopLoss, takeProfit, 0, clrBlue);



               // Mark the expert to set SL and TP with a separate order

               if (ticket > 0 && modified)

                 {

                  setProtectionSeparately = true;

                  Print("Detected ECN type position protection.");

                 }

              }

           }

        }



      if (ticket > 0)

         break;



      lastError = GetLastError();

      if (lastError != 135 && lastError != 136 && lastError != 137 && lastError != 138)

         break;



      Sleep(TRADE_RETRY_WAIT);

      Print("Open Position retry no: " + IntegerToString(attempt + 2));

     }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void ClosePosition()

  {

   for(int attempt = 0; attempt < TRADE_RETRY_COUNT; attempt++)

     {

      bool closed;

      int lastError = 0;



      if ( IsTradeContextFree() )

        {

         double price = posType == OP_BUY ? Bid() : Ask();

         closed    = OrderClose(posTicket, posLots, price, 10, clrYellow);

         lastError = GetLastError();

        }



      if (closed)

         break;



      if (lastError == 4108)

         break;



      Sleep(TRADE_RETRY_WAIT);

      Print("Close Position retry no: " + IntegerToString(attempt + 2));

     }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void ModifyPosition()

  {

   for (int attempt = 0; attempt < TRADE_RETRY_COUNT; attempt++)

     {

      bool modified;

      int lastError = 0;



      if ( IsTradeContextFree() )

        {

         modified  = OrderModify(posTicket, 0, posStopLoss, posTakeProfit, 0, clrBlue);

         lastError = GetLastError();

        }



      if (modified)

         break;



      if (lastError == 4108)

         break;



      Sleep(TRADE_RETRY_WAIT);

      Print("Modify Position retry no: " + IntegerToString(attempt + 2));

     }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double GetStopLossPrice(int command)

  {

   if (Stop_Loss == 0)

      return 0;



   double delta    = MathMax(pip * Stop_Loss, _Point * stopLevel);

   double stopLoss = command == OP_BUY ? Bid() - delta : Ask() + delta;



   return NormalizeDouble(stopLoss, _Digits);

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double GetTakeProfitPrice(int command)

  {

   if (Take_Profit == 0)

      return 0;



   double delta      = MathMax(pip * Take_Profit, _Point * stopLevel);

   double takeProfit = command == OP_BUY ? Bid() + delta : Ask() - delta;



   return NormalizeDouble(takeProfit, _Digits);

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double GetTrailingStopPrice()

  {

   double bid = Bid();

   double ask = Ask();

   double stopLevelPoints = _Point * stopLevel;

   double stopLossPoints  = pip * Stop_Loss;



   if (posType == OP_BUY)

     {

      double stopLossPrice = High(1) - stopLossPoints;

      if (posStopLoss < stopLossPrice - pip)

         return stopLossPrice < bid

                 ? stopLossPrice >= bid - stopLevelPoints

                    ? bid - stopLevelPoints

                    : stopLossPrice

                 : bid;

     }



   if (posType == OP_SELL)

     {

      double stopLossPrice = Low(1) + stopLossPoints;

      if (posStopLoss > stopLossPrice + pip)

         return stopLossPrice > ask

                 ? stopLossPrice <= ask + stopLevelPoints

                    ? ask + stopLevelPoints

                    : stopLossPrice

                 : ask;

     }



   return posStopLoss;

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void ManageTrailingStop(double trailingStop)

  {

   if ( (posType == OP_BUY  && MathAbs(trailingStop - Bid()) < _Point) ||

        (posType == OP_SELL && MathAbs(trailingStop - Ask()) < _Point) )

     {

      ClosePosition();

      return;

     }



   if ( MathAbs(trailingStop - posStopLoss) > _Point )

     {

      posStopLoss = NormalizeDouble(trailingStop, _Digits);

      ModifyPosition();

     }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double Bid()

  {

   return MarketInfo(_Symbol, MODE_BID);

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double Ask()

  {

   return MarketInfo(_Symbol, MODE_ASK);

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

datetime Time(int bar)

  {

   return Time[bar];

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double Open(int bar)

  {

   return Open[bar];

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double High(int bar)

  {

   return High[bar];

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double Low(int bar)

  {

   return Low[bar];

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double Close(int bar)

  {

   return Close[bar];

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

double GetPipValue()

  {

   return _Digits == 4 || _Digits == 5 ? 0.0001

        : _Digits == 2 || _Digits == 3 ? 0.01

                        : _Digits == 1 ? 0.1 : 1;

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

bool IsTradeContextFree()

  {

   if ( IsTradeAllowed() )

      return true;



   uint startWait = GetTickCount();

   Print("Trade context is busy! Waiting...");



   while (true)

     {

      if (IsStopped())

         return false;



      uint diff = GetTickCount() - startWait;

      if (diff > 30 * 1000)

        {

         Print("The waiting limit exceeded!");

         return false;

        }



      if ( IsTradeAllowed() )

        {

         RefreshRates();

         return true;

        }



      Sleep(TRADE_RETRY_WAIT);

     }



   return true;

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

bool IsOutOfSession()

  {

   int dayOfWeek    = DayOfWeek();

   int periodStart  = int(Time(0) % 86400);

   int periodLength = PeriodSeconds(_Period);

   int periodFix    = periodStart + (sessionCloseAtSessionClose ? periodLength : 0);

   int friBarFix    = periodStart + (sessionCloseAtFridayClose || sessionCloseAtSessionClose ? periodLength : 0);



   return dayOfWeek == 0 && sessionIgnoreSunday ? true

        : dayOfWeek == 0 ? periodStart < sessionSundayOpen         || periodFix > sessionSundayClose

        : dayOfWeek  < 5 ? periodStart < sessionMondayThursdayOpen || periodFix > sessionMondayThursdayClose

                         : periodStart < sessionFridayOpen         || friBarFix > sessionFridayClose;

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

bool IsForceSessionClose()

  {

   if (!sessionCloseAtFridayClose && !sessionCloseAtSessionClose)

      return false;



   int dayOfWeek = DayOfWeek();

   int periodEnd = int(Time(0) % 86400) + PeriodSeconds(_Period);



   return dayOfWeek == 0 && sessionCloseAtSessionClose ? periodEnd > sessionSundayClose

        : dayOfWeek  < 5 && sessionCloseAtSessionClose ? periodEnd > sessionMondayThursdayClose

        : dayOfWeek == 5 ? periodEnd > sessionFridayClose : false;

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

ENUM_INIT_RETCODE ValidateInit()

  {

   return INIT_SUCCEEDED;

  }

//+------------------------------------------------------------------+

/*STRATEGY MARKET PepperstoneUK-Live; NZDCAD; H4 */

/*STRATEGY CODE {"properties":{"entryLots":0.1,"tradeDirectionMode":0,"oppositeEntrySignal":0,"stopLoss":106,"takeProfit":0,"useStopLoss":true,"useTakeProfit":false,"isTrailingStop":false},"openFilters":[{"name":"Entry Time","listIndexes":[0,0,0,0,0],"numValues":[2,0,23,59,0,0]},{"name":"Bollinger Bands","listIndexes":[4,3,0,0,0],"numValues":[30,2.35,0,0,0,0]}],"closeFilters":[{"name":"Envelopes","listIndexes":[5,3,0,0,0],"numValues":[15,0.74,0,0,0,0]}]} */















 
Peron Giig #:

Hola David,

Perdona pero no he estado muy pendiente del foro.

¡Claro! Aquí mismo pongo un ejemplo de los muchos algoritmos que me saca el EAS junto con la corrección que he hecho al código.

También adjunto el pdf con el que copio y pego el código, junto con un EA sin el código.

Hola Amigo que tal, disculpa esto como funciona, si quiero que mis operaciones se abran con 0.01 ni más ni menos, y si quiero que ejemplo se abrán maximo 5 posiciones o 3 no lo se, donde le doy, como lo pongo a trabajar? etc, muchas gracias