Ayuda con mi EA por favor

 

Hola. Tengo un problema con mi EA. El problema es que cuando mi Stop Loss > 0 la opción BreakEven no funciona. La verdad es que no sé qué pasa o qué es lo que se está liando con esto. He comprobado de mil maneras y no encuentro el porqué. Adjunto mi código.


#include <Trade\Trade.mqh>
input int MagicNumber=10000;
input double TakeProfit=15;
input double BreakEven=150;
input double BreakEvenTP=120;
input uchar PeriodoRSI=7;                                          // RSI Periodo
input uchar ValorRSICompra=30;                                    // RSI Valor de Compra
input uchar ValorRSIVenta=70;                                     // RSI Valor de Venta
input ENUM_APPLIED_PRICE RSITipoDePrecio=PRICE_CLOSE;            // RSI Tipo de Precio
//+------------------------------------------------------------------+
//    expert start function
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
ENUM_MA_METHOD MethodMigrate(int method)
  {
   switch(method)
     {
      case 0:
         return(MODE_SMA);
      case 1:
         return(MODE_EMA);
      case 2:
         return(MODE_SMMA);
      case 3:
         return(MODE_LWMA);
      default:
         return(MODE_SMA);
     }
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
ENUM_STO_PRICE StoFieldMigrate(int field)
  {
   switch(field)
     {
      case 0:
         return(STO_LOWHIGH);
      case 1:
         return(STO_CLOSECLOSE);
      default:
         return(STO_LOWHIGH);
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
ENUM_APPLIED_PRICE PriceMigrate(int price)
  {
   switch(price)
     {
      case 1:
         return(PRICE_CLOSE);
      case 2:
         return(PRICE_OPEN);
      case 3:
         return(PRICE_HIGH);
      case 4:
         return(PRICE_LOW);
      case 5:
         return(PRICE_MEDIAN);
      case 6:
         return(PRICE_TYPICAL);
      case 7:
         return(PRICE_WEIGHTED);
      default:
         return(PRICE_CLOSE);
     }
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES TFMigrate(int tf)
  {
   switch(tf)
     {
      case 0:
         return(PERIOD_CURRENT);
      case 1:
         return(PERIOD_M1);
      case 5:
         return(PERIOD_M5);
      case 15:
         return(PERIOD_M15);
      case 30:
         return(PERIOD_M30);
      case 60:
         return(PERIOD_H1);
      case 240:
         return(PERIOD_H4);
      case 1440:
         return(PERIOD_D1);
      case 10080:
         return(PERIOD_W1);
      case 43200:
         return(PERIOD_MN1);

      case 2:
         return(PERIOD_M2);
      case 3:
         return(PERIOD_M3);
      case 4:
         return(PERIOD_M4);
      case 6:
         return(PERIOD_M6);
      case 10:
         return(PERIOD_M10);
      case 12:
         return(PERIOD_M12);
      case 16385:
         return(PERIOD_H1);
      case 16386:
         return(PERIOD_H2);
      case 16387:
         return(PERIOD_H3);
      case 16388:
         return(PERIOD_H4);
      case 16390:
         return(PERIOD_H6);
      case 16392:
         return(PERIOD_H8);
      case 16396:
         return(PERIOD_H12);
      case 16408:
         return(PERIOD_D1);
      case 32769:
         return(PERIOD_W1);
      case 49153:
         return(PERIOD_MN1);
      default:
         return(PERIOD_CURRENT);
     }
  }

#define MODE_MAIN 0
#define MODE_SIGNAL 1
#define MODE_PLUSDI 1
#define MODE_MINUSDI 2
#define MODE_OPEN 0
#define MODE_LOW 1
#define MODE_HIGH 2
#define MODE_CLOSE 3
#define MODE_VOLUME 4
#define MODE_REAL_VOLUME 5


#define OP_BUY 0           //Buy 
#define OP_SELL 1          //Sell 
#define OP_BUYLIMIT 2      //Pending order of BUY LIMIT type 
#define OP_SELLLIMIT 3     //Pending order of SELL LIMIT type 
#define OP_BUYSTOP 4       //Pending order of BUY STOP type 
#define OP_SELLSTOP 5      //Pending order of SELL STOP type 
//---
#define MODE_TRADES 0
#define MODE_HISTORY 1
#define SELECT_BY_POS 0
#define SELECT_BY_TICKET 1
//---
#define DOUBLE_VALUE 0
#define FLOAT_VALUE 1
#define LONG_VALUE INT_VALUE
//---
#define CHART_BAR 0
#define CHART_CANDLE 1
//---
#define MODE_ASCEND 0
#define MODE_DESCEND 1
//---

#define MODE_TIME 5
#define MODE_BID 9
#define MODE_ASK 10
#define MODE_POINT 11
#define MODE_DIGITS 12
#define MODE_SPREAD 13
#define MODE_STOPLEVEL 14
#define MODE_LOTSIZE 15
#define MODE_TICKVALUE 16
#define MODE_TICKSIZE 17
#define MODE_SWAPLONG 18
#define MODE_SWAPSHORT 19
#define MODE_STARTING 20
#define MODE_EXPIRATION 21
#define MODE_TRADEALLOWED 22
#define MODE_MINLOT 23
#define MODE_LOTSTEP 24
#define MODE_MAXLOT 25
#define MODE_SWAPTYPE 26
#define MODE_PROFITCALCMODE 27
#define MODE_MARGINCALCMODE 28
#define MODE_MARGININIT 29
#define MODE_MARGINMAINTENANCE 30
#define MODE_MARGINHEDGED 31
#define MODE_MARGINREQUIRED 32
#define MODE_FREEZELEVEL 33
//---
#define EMPTY -1

int VelaActualParaBuy;
int VelaActualParaSell;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+




//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnInit()
  {
//Reseteamos el valor a cero cada vez que se inicie el EA
   VelaActualParaBuy = 0;
   VelaActualParaSell = 0;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   CTrade trade;
   trade.SetExpertMagicNumber(MagicNumber);

   double PorcentajeLot=0.001;
   double Equity=AccountInfoDouble(ACCOUNT_EQUITY);
   double Balance1=AccountInfoDouble(ACCOUNT_BALANCE);
   double Lots= NormalizeDouble(Equity*PorcentajeLot,2);
   double LoteMinimo= 0.01;


   int MaxSpreadAllowed=10;
   int RiesgoBeneficio=2;

   int Hora_inicio=0;
   int Hora_final=24;

// NormalizeDouble(TakeProfit/RiesgoBeneficio,0)
   double StopLoss= 0;
   double TrailingStop= 0;


   double Ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
   double Bid=SymbolInfoDouble(_Symbol,SYMBOL_BID);

   double MyPoint=_Point;
   if(_Digits==3 || _Digits==5)
      MyPoint=_Point*10;
   double TheStopLoss=0;
   double TheTakeProfit=0;
   if(TotalOrdersCount()==0)

      MqlRates PriceArray();


   double PrecioDeApertura=PositionGetDouble(POSITION_PRICE_OPEN);
   double BreakEvenC= PrecioDeApertura + BreakEvenTP*_Point;
   double BreakEvenV= PrecioDeApertura - BreakEvenTP*_Point;

   if(Lots<LoteMinimo)
     {
      Lots=LoteMinimo;
     }


   int CurrentSpread= SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);

   string SpreadFilter="";

   if(CurrentSpread>MaxSpreadAllowed)
     {
      SpreadFilter="trading is not allowed";
     }

   if(CurrentSpread<MaxSpreadAllowed)
     {
      SpreadFilter="trading is allowed";
     }


     {

      MqlDateTime time_now;

      TimeCurrent(time_now);

      if((time_now.hour>=Hora_inicio) && (time_now.hour<=Hora_final))


        {

         if((iRSIMQL4(NULL,0,PeriodoRSI,RSITipoDePrecio,2)<ValorRSICompra)     &&(iRSIMQL4(NULL,0,PeriodoRSI,RSITipoDePrecio,1)>ValorRSICompra))    // Here is your open buy rule
           {
            if(StopLoss>0)
               TheStopLoss=SymbolInfoDouble(_Symbol,SYMBOL_ASK)-StopLoss*MyPoint;
            if(TakeProfit>0)
               TheTakeProfit=SymbolInfoDouble(_Symbol,SYMBOL_ASK)+TakeProfit*MyPoint;
            if(SpreadFilter!="trading is allowed")
               //Antes de abrir la posición, verificamos que no estemos en la misma vela
               if(VelaActualParaBuy != iBars(Symbol(), PERIOD_CURRENT))
                 {
                  trade.PositionOpen(_Symbol,ORDER_TYPE_BUY,Lots,SymbolInfoDouble(_Symbol,SYMBOL_ASK),TheStopLoss,TheTakeProfit);
                  VelaActualParaBuy = iBars(Symbol(), PERIOD_CURRENT);
                 }
            return;
           }
         if((iRSIMQL4(NULL,0,PeriodoRSI,RSITipoDePrecio,2)>ValorRSIVenta)      &&(iRSIMQL4(NULL,0,PeriodoRSI,RSITipoDePrecio,1)<ValorRSIVenta))    // Here is your open Sell rule
           {
            if(StopLoss>0)
               TheStopLoss=SymbolInfoDouble(_Symbol,SYMBOL_ASK)+StopLoss*MyPoint;
            if(TakeProfit>0)
               TheTakeProfit=SymbolInfoDouble(_Symbol,SYMBOL_ASK)-TakeProfit*MyPoint;
            if(SpreadFilter=="trading is allowed")
               //Antes de abrir la posición, verificamos que no estemos en la misma vela
               if(VelaActualParaSell != iBars(Symbol(), PERIOD_CURRENT))
                 {
                  trade.PositionOpen(_Symbol,ORDER_TYPE_SELL,Lots,SymbolInfoDouble(_Symbol,SYMBOL_BID),TheStopLoss,TheTakeProfit);
                  VelaActualParaSell = iBars(Symbol(), PERIOD_CURRENT);
                 }
            return;
           }

        }

     }

   int posTotal=PositionsTotal();
   for(int posIndex=posTotal-1; posIndex>=0; posIndex--)
     {
      ulong ticket=PositionGetTicket(posIndex);
      if(PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_MAGIC)==MagicNumber)
        {
         if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
           {
            if(Ask > (PrecioDeApertura + BreakEven*_Point))
              {
               trade.PositionModify(ticket,BreakEvenC,PositionGetDouble(POSITION_TP));
               return;
              }
            if(TrailingStop>0)
              {
               if(SymbolInfoDouble(_Symbol,SYMBOL_BID)-PositionGetDouble(POSITION_PRICE_OPEN)>MyPoint*TrailingStop)
                 {
                  if(PositionGetDouble(POSITION_SL)<SymbolInfoDouble(_Symbol,SYMBOL_BID)-MyPoint*TrailingStop)
                    {
                     trade.PositionModify(ticket,SymbolInfoDouble(_Symbol,SYMBOL_BID)-MyPoint*TrailingStop,PositionGetDouble(POSITION_TP));
                     return;
                    }
                 }
              }
           }

         if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
           {
            if(Bid < (PrecioDeApertura - BreakEven*_Point))
              {
               trade.PositionModify(ticket,BreakEvenV,PositionGetDouble(POSITION_TP));
               return;
              }
            if(TrailingStop>0)
              {
               if(PositionGetDouble(POSITION_PRICE_OPEN)-SymbolInfoDouble(_Symbol,SYMBOL_ASK)>MyPoint*TrailingStop)
                 {
                  if(PositionGetDouble(POSITION_SL)>SymbolInfoDouble(_Symbol,SYMBOL_ASK)+MyPoint*TrailingStop)
                    {
                     trade.PositionModify(ticket,SymbolInfoDouble(_Symbol,SYMBOL_ASK)+MyPoint*TrailingStop,PositionGetDouble(POSITION_TP));
                     return;
                    }
                 }
              }
           }
        }
     }
   return;
  }


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int TotalOrdersCount()
  {
   int result=0;
   int posTotal=PositionsTotal();
   for(int posIndex=posTotal-1; posIndex>=0; posIndex--)
     {
      ulong ticket=PositionGetTicket(posIndex);
      if(PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_MAGIC)==MagicNumber)
         result++;
     }
   return (result);
  }


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+


 

LupusLunam:

Hola. Tengo un problema con mi EA. El problema es que cuando mi Stop Loss > 0 la opción BreakEven no funciona. La verdad es que no sé qué pasa o qué es lo que se está liando con esto. He comprobado de mil maneras y no encuentro el porqué. Adjunto mi código.

He traducido su hilo. Tenga en cuenta que cada idioma cuenta con su respectivo foro, y es por ello que está prohibido comunicarse en otro lenguaje que no sea el del foro en cuestión.

 
LupusLunam:

Hola. Tengo un problema con mi EA. El problema es que cuando mi Stop Loss > 0 la opción BreakEven no funciona. La verdad es que no sé qué pasa o qué es lo que se está liando con esto. He comprobado de mil maneras y no encuentro el porqué. Adjunto mi código.Hola Lupus.

Repasando tu código, en principio lo que veo es esto:

      ulong ticket=PositionGetTicket(posIndex); // Con esto no necesitas hacer PositionSelectByTicket.
      if(PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_MAGIC)==MagicNumber) // No hace falta.

En cuanto a lo de StopLoss y Breakeven intenta acotar un poco código con explicaciones sobre lo que debería hacer.

 
David Diez #:

Repasando tu código, en principio lo que veo es esto:

En cuanto a lo de StopLoss y Breakeven intenta acotar un poco código con explicaciones sobre lo que debería hacer.

Hola David. Muchas gracias!! A penas quite 

PositionSelectByTicket(ticket) &&

el código funciono perfectamente con mi Stop Loss y EvenBreak. De verdad muchas gracias!

 
LupusLunam #:

Hola David. Muchas gracias!! A penas quite 

el código funciono perfectamente con mi Stop Loss y EvenBreak. De verdad muchas gracias!

Genial, encantado de poder ayudarte.
Razón de la queja: