bbollinguer funciona!

Comparte y comenta tus estrategias de trading.

Re: bbollinguer funciona!

Notapor rtrader » 21 May 2011, 03:45

Me olvidaba, aquí está el EA con money Management incorporado.
Backtesting tick a tick.
Horario: 22 a 23 GMT+1
Saludos.
Adjuntos
eabanda62223.jpg
eabandaprueba.mq4
(53.26 KiB) 541 veces
Avatar de Usuario
rtrader
 
Mensajes: 279
Registrado: 12 Feb 2008, 14:02
Karma: 0

Re: bbollinguer funciona!

Notapor rtrader » 21 May 2011, 03:48

elchebeto escribió:alguien sabe de algun manual de alfatrader donde expliquen con ejemplos para hacer algun EA?
se los agradeceria

saludos


La gente de http://sistemasinversores.com/ tenían en su web un manual sobre como crear experts con el Alfatrader.

Saludos.

PD. Habrá que hacer el curso :D
Avatar de Usuario
rtrader
 
Mensajes: 279
Registrado: 12 Feb 2008, 14:02
Karma: 0

Re: bbollinguer funciona!

Notapor chaveznqoos » 21 May 2011, 10:41

Hola rtrader;
¿Dónde puedo encontrar la libreria stdlibSIv2.02.mqh ?
Gracias.
chaveznqoos
 
Mensajes: 182
Registrado: 06 Ago 2009, 00:08
Karma: 0

Re: bbollinguer funciona!

Notapor rtrader » 21 May 2011, 15:33

Hola chaveznqoos.

Aclaro que no soy programador... revisando el MetaEditor encontré la v2.02, te pongo el código, espero que sea esto lo que buscas.

Código: Seleccionar todo
//+------------------------------------------------------------------+
//|                                                     stdlibSI.mqh |
//|                                              Sistemas Inversores |
//|                                http://www.sistemasinversores.com |
//+------------------------------------------------------------------+

#property copyright "Sistemas Inversores"
#property link      "http://www.sistemasinversores.com"


int MagicNumber;
int SegundosParaReintentarOperar = 20;

bool comprobarStopLoss(int SL) {
   
   int stopMinimo = MarketInfo(Symbol(),MODE_STOPLEVEL);
   if(SL!=0 && SL < stopMinimo){
      Alert("ERROR: El StopLoss m?nimo en ",Symbol()," es: ",stopMinimo);
      return(false);
   }
   else return(true);
}


bool comprobarTakeProfit(int TP) {
   
   int stopMinimo = MarketInfo(Symbol(),MODE_STOPLEVEL);
   if(TP!=0 && TP < stopMinimo){
      Alert("ERROR: El TakeProfit m?nimo en ",Symbol()," es: ",stopMinimo);
      return(false);
   }
   else return(true);
}

double
getSL(int tipo, int StopLoss, double precio=0)
{
   if(StopLoss == 0) return(0);
   double sl=0;
   
   double stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   stoplevel=stoplevel*Point;
   
   if(tipo == OP_BUY || tipo == OP_BUYLIMIT || tipo == OP_BUYSTOP) // COMPRA
   {
      if (precio==0)
      {
         RefreshRates();
         precio=Ask;
      }
      sl = (precio-StopLoss*Point);
      if (sl>precio-stoplevel)
         sl=precio-stoplevel;
   }
   if(tipo == OP_SELL || tipo == OP_SELLLIMIT || tipo == OP_SELLSTOP) // VENTA
   {
      if (precio==0)
      {
         RefreshRates();
         precio=Bid;
      }
      sl = (precio+StopLoss*Point);
      if (sl<precio+stoplevel)
         sl=precio+stoplevel;
   }
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = sl / Point;
      psl = psl / (ticksize/Point);
      sl = psl * ticksize;
   }
   
   return(sl);
}

double
getTP(int tipo, int TakeProfit, double precio=0)
{
   if(TakeProfit == 0) return(0);
   double tp = 0;
   
   double stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   stoplevel=stoplevel*Point;
   
   if(tipo == OP_BUY || tipo == OP_BUYLIMIT || tipo == OP_BUYSTOP) // COMPRA
   {
      if (precio==0)
      {
         RefreshRates();
         precio=Ask;
      }
      tp=precio+TakeProfit*Point;
      if (tp<precio+stoplevel)
         tp=precio+stoplevel;
   }
   if(tipo == OP_SELL || tipo == OP_SELLLIMIT || tipo == OP_SELLSTOP) // VENTA
   { 
      if (precio==0)
      {
         RefreshRates();
         precio=Bid;
      }
      tp=precio-(TakeProfit*Point);
      if (tp>precio-stoplevel)
         tp=precio-stoplevel;
   }
   
   tp = NormalizeDouble(tp, Digits);
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = tp / Point;
      psl = psl / (ticksize/Point);
      tp = psl * ticksize;
   }
   
   return (tp);
}

bool se?alInversa?(int se?al){
   static int se?al_old = -1;
   
   if(se?al_old == -1){
      se?al_old = se?al;
   }
   
   if(se?al_old != se?al && se?al!=-1){
        se?al_old = se?al;
        return(true);
   }
   else return(false);
}


int
ordenesTotalesEA(int tipo=-1){

   int totalEA = 0;
   int totalMT = OrdersTotal();

   if (tipo==-1 && (IsOptimization() || IsTesting()))
      return (totalMT);
   
   for(int i=0; i<totalMT; i++)
      if(OrderSelect(i,SELECT_BY_POS) && OrderMagicNumber() == MagicNumber) {
         if (tipo==-1 || OrderType()==tipo)
            totalEA++;
      }
     
   return(totalEA);
}

bool
cerrarPosiciones(int tipo = -1){

   int error;
   
   for(int i=OrdersTotal()-1; i>=0; i--){
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderMagicNumber() != MagicNumber) continue;
      if (tipo!=-1 && OrderType()!=tipo) continue;
      bool exito=false;
      while (!exito) {
         RefreshRates();
         while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
         if (OrderType()==OP_BUY || OrderType() == OP_SELL)
            exito=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(OrderClosePrice(), Digits),Slippage,Yellow);
         else
            exito=OrderDelete(OrderTicket());
         if (!exito)
         {
            error = GetLastError(); 
            // Si el error no es recuperable, salimos
            if (error==4108 || error==4106 || error==133)  // 4108=INVALID_TICKET, 4106=UNKNOWN_SYMBOL, 133=ERR_TRADE_DISABLED
               break;
            Sleep(500);
         }
      }
   }
   if (ordenesTotalesEA()==0)
      return(true);
   return (false);
}


int abrirPosicion(string symbol, int se?al, double precio=0, double sl=0, double tp=0, double size=0, string comentario="", datetime expiration=0)
{
   if (comentario=="")
      comentario = NombreDelEA + " " + getPeriodAsString(Period()) + ";";
   double precioApertura;
   color colorFlecha;
   int ticket;
   int error;
   double Stop, Take;
   double digits = MarketInfo(symbol, MODE_DIGITS);
   double point = MarketInfo(symbol, MODE_POINT);
   double stoplevel = (MarketInfo(symbol, MODE_STOPLEVEL)+1)*point;


   int intentos = SegundosParaReintentarOperar*2;
   precio=NormalizeDouble(precio, digits);
   
   double ticksize = MarketInfo(symbol, MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = precio / point;
      psl = psl / (ticksize/point);
      precio = psl * ticksize;
   }
   
   while(intentos>0)
   {       
      // Obtener precio de apertura.
      RefreshRates();
      if(se?al == OP_BUY ||se?al==OP_BUYLIMIT || se?al==OP_BUYSTOP) {precioApertura = NormalizeDouble(MarketInfo(symbol, MODE_ASK),digits); colorFlecha = Green;}
      if(se?al == OP_SELL ||se?al==OP_SELLLIMIT || se?al==OP_SELLSTOP) {precioApertura = NormalizeDouble(MarketInfo(symbol, MODE_BID),digits); colorFlecha = Red;}

      // Precio=0?
      if (precio==0)
      {
         precio=precioApertura;
      }

      // Size=0?
      if (size==0) size=MarketInfo(symbol, MODE_MINLOT);
      else size=NormalizeLots(size,symbol);

      /// Si el precio es menor que el actual, cambiamos stop por limit
      if (se?al!=OP_BUY && se?al!=OP_SELL)
      {
         if (precio<precioApertura && se?al==OP_BUYSTOP)
            se?al=OP_BUYLIMIT;
         if (precio>precioApertura && se?al==OP_BUYLIMIT)
            se?al=OP_BUYSTOP;
   
         if (precio>precioApertura && se?al==OP_SELLSTOP)
            se?al=OP_SELLLIMIT;
         if (precio<precioApertura && se?al==OP_SELLLIMIT)
            se?al=OP_SELLSTOP;


         if (se?al==OP_BUYLIMIT || se?al==OP_BUYSTOP ||se?al==OP_SELLLIMIT ||se?al==OP_SELLSTOP)
         {
            if (MathAbs(precioApertura-precio) > stoplevel)
               precioApertura=precio;
            else
            {
               if (se?al==OP_BUYLIMIT || se?al ==OP_BUYSTOP)
               {
                  //precioApertura=precio+spread;
                  se?al=OP_BUY;
                  expiration=0;
               }
               if (se?al==OP_SELLLIMIT || se?al == OP_SELLSTOP)
               {
                  //precioApertura=precio-spread;
                  se?al=OP_SELL;
                  expiration=0;
               }
            }
         }
      }
   
      // StopLoss y TakeProfit
      if (sl!=0) Stop=sl;
      else Stop=0;
      if (tp!=0) Take=tp;
      else Take=0;
   
      // Comprobamos que SL y TP sean correctos
      if (se?al==OP_BUY || se?al==OP_BUYLIMIT || se?al==OP_BUYSTOP)
      {
         if (Stop!=0 && (precioApertura-Stop)<stoplevel)
         {
            if((precioApertura-Stop)>0) // No hay mucha diferencia
            {
               Stop=NormalizeDouble(precioApertura-stoplevel, digits);
               Print("Cambiando el StopLoss al m?nimo de la plataforma");
            }
            else
            {
               Stop=0;
               Print("Eliminando StopLoss incorrecto.");
            }
         }
         if (Take!=0 && (Take-precioApertura)<stoplevel)
         {
            if((Take-precioApertura)>0) // No hay mucha diferencia
            {
               Take=NormalizeDouble(precioApertura+stoplevel, digits);
               Print("Cambiando el TakeProfit al m?nimo de la plataforma");
            }
            else
            {
               Take=0;
               Print("Eliminando TakeProfit incorrecto");
            }
         }
      }
      if (se?al==OP_SELL || se?al==OP_SELLLIMIT || se?al==OP_SELLSTOP)
      {
         if (Stop!=0 && (Stop-precioApertura)<stoplevel)
         {
            if((Stop-precioApertura)>0) // No hay mucha diferencia
            {
               Stop=NormalizeDouble(precioApertura+stoplevel, digits);
               Print("Cambiando el StopLoss al m?nimo de la plataforma");
            }
            else
            {
               Print("Eliminando StopLoss incorrecto");
               Stop=0;
            }
         }
         if (Take!=0 && (precioApertura-Take)<stoplevel)
         {
            if((precioApertura-Take)>0) // No hay mucha diferencia
            {
               Take=NormalizeDouble(precioApertura-stoplevel, digits);
               Print("Cambiando el TakeProfit al m?nimo de la plataforma");
            }
            else
            {
               Take=0;
               Print("Eliminando TakeProfit incorrecto");
            }
         }
      }
      while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
      ticket = OrderSend(symbol,se?al,size,precioApertura,Slippage,0,0,comentario,MagicNumber,expiration,colorFlecha);
      if(ticket<0){
         error = GetLastError();
         Print("OrderSend fall? con error #",error);
         Print("Orden: ", se?al, " L=",size," pa=",precioApertura," precio="+precio+" sp=",Slippage," sl=",Stop," tp=",Take," c=",comentario," stoplevel=",stoplevel," Bid=",MarketInfo(symbol, MODE_BID));
         intentos--;
         Sleep(500); // Pausa antes de reintentar.
      }
      else
      {
         // Ticket v?lido, modificamos SL y TP para FXCM y MIG entre otros
         modificarSLyTP(ticket, Stop, Take);
         return(ticket); // ticket v?lido.
      }
   } 
   
   Alert("Se intent? operar durante "+SegundosParaReintentarOperar+" segundos. Error #"+error);
   return(-1);
}

bool cerrarPosicion(int ticket)
{
   int error=-1;
   
   // Compruebo que el ticket exista
   if (ticket<1) return (false);
   
   int nerrores=0;

   while(true) // Intentamos cerrar hasta que no haya error.
   {
      // Obtener precio de cierre.
      if (OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
      {
         RefreshRates();
         bool result;
         while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
         if (OrderType() ==OP_BUY || OrderType() == OP_SELL)
            result = OrderClose(ticket,OrderLots(),NormalizeDouble(OrderClosePrice(), Digits),Slippage,Yellow);
         else
            result = OrderDelete(ticket);
         if (!result) {
            error = GetLastError();
            if (OrderType() ==OP_BUY || OrderType() == OP_SELL)
               Print("OrderClose fall? con error #",error);
            else
               Print("OrderDelete fall? con error #",error);
            // Si el error no es recuperable, salimos
            if (error==4108 || error==4106 || error==133)  // 4108=INVALID_TICKET, 4106=UNKNOWN_SYMBOL, 133=ERR_TRADE_DISABLED
               return (false);
            Sleep(500); // Pausa antes de reintentar.
         }
         else
            return(true);
       }
       else { nerrores++; if (nerrores>10) break; }
   }
}

int
getMagicNumber(bool recuperarOrdenes = false)
{
   int MagicNumber;
   
   // Magic Number Autom?tico.
   if(!IsTesting()) MagicNumber = WindowHandle(Symbol(),0);
   else if(!IsVisualMode()) MagicNumber = 23;
   
   if (recuperarOrdenes)
   {
      // Si hay operaciones abiertas, de un EA que se ha cerrado antes, tomamos su MagicNumber
      for (int i=OrdersTotal()-1; i>=0; i--)
      {
         OrderSelect(i, SELECT_BY_POS);
         if (OrderSymbol()!=Symbol()) continue;
         // Coincide el nombre del EA, y coindice el periodo, o no hay periodo
         if (StringSubstr(OrderComment(),0, StringLen(NombreDelEA)) == NombreDelEA
            && (StringFind(OrderComment(), " ", StringLen(NombreDelEA)+1)==-1 ||
               StringSubstr(OrderComment(),StringLen(NombreDelEA)+1,StringLen(getPeriodAsString(Period())))==getPeriodAsString(Period())))
         {
            Print("Retomando orden "+OrderTicket());
            MagicNumber=OrderMagicNumber();
            // Modificamos la se?al inversa para detectar pr?ximos cambios de se?al
            se?alInversa?(OrderType());
            break;
         }
      }
   }
   
   return (MagicNumber);
}

void
ajustarTrailingStopTodas(int TrailingTrigger, int TrailingDistancia, int Step=0)
{
   for (int i=0; i<OrdersTotal(); i++)
   {
      if (!(OrderSelect(i, SELECT_BY_POS) && OrderMagicNumber()==MagicNumber)) continue;
   
      ajustarTrailingStop(OrderTicket(), TrailingTrigger, TrailingDistancia, Step);
   }
   
   return;
}


bool
ajustarTrailingStop(int ticket, int TrailingTrigger, int TrailingDistancia, int Step=0)
{
   int total;
   int beneficio;
   double nuevoStop, stopstep;
   
   if (!OrderSelect(ticket,SELECT_BY_TICKET))
      return (false);
 
   // Si la distancia es menor que el stoplevel, salimos
   if (TrailingDistancia < MarketInfo(OrderSymbol(), MODE_STOPLEVEL))
   {
      Print("No se puede modificar el SL, la distancia m?nima requerida es " + DoubleToStr(MarketInfo(OrderSymbol(), MODE_STOPLEVEL),0) + " y se ha calculado "+DoubleToStr(TrailingDistancia,0));
      return (false);
   }
   
    // Obtener beneficio de la orden
    if(OrderType() == OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
      beneficio = (OrderClosePrice()-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT);         
    else if(OrderType() == OP_SELL ||OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
      beneficio = (OrderOpenPrice()-OrderClosePrice())/MarketInfo(OrderSymbol(),MODE_POINT); 
   
    // Si no hay beneficio la dejamos
    if(beneficio <= 0) return(false);
   
    // Si hay beneficio y hay que ajustar
    if(beneficio > TrailingTrigger){
      if(OrderType() == OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP){
         nuevoStop = OrderOpenPrice() + (beneficio - TrailingDistancia) * Point; 
         nuevoStop=NormalizeDouble(nuevoStop, Digits);
         stopstep = nuevoStop-(Step*Point);
         if(NormalizeDouble(OrderStopLoss(),Digits) < NormalizeDouble(stopstep, Digits) || OrderStopLoss() == 0)
         {
            modificarStopLoss(OrderTicket(), nuevoStop);
         }
      }
      if(OrderType() == OP_SELL ||OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP){
         nuevoStop = OrderOpenPrice() - (beneficio - TrailingDistancia) * Point;
         nuevoStop = NormalizeDouble(nuevoStop, Digits);
         stopstep = nuevoStop+(Step*Point);
         if(NormalizeDouble(OrderStopLoss(),Digits) > NormalizeDouble(stopstep, Digits) || OrderStopLoss() == 0)
         {
            modificarStopLoss(OrderTicket(), nuevoStop);
         }
      }
     }
     
     // No se ajust? nada.
     return(false);   
}

void
ajustarBreakEvenTodas(int BreakEven)
{
   if (BreakEven==0) return;

   for (int i=0; i<OrdersTotal(); i++)
   {
      if (!(OrderSelect(i, SELECT_BY_POS) && OrderMagicNumber()==MagicNumber)) continue;
   
      ajustarBreakEven(OrderTicket(), BreakEven);
   }
   
   return;
}

bool
ajustarBreakEven(int ticket, int BreakEven)
{
   if (BreakEven==0) return;

   if (OrderProfitPoints(ticket)>=BreakEven)
      modificarStopLoss(ticket, OrderOpenPrice());
}

void
cerrarPendientesEA()
{
   int total = OrdersTotal();
   for (int i=total-1; i>=0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS) && OrderMagicNumber()==MagicNumber)
      {
         if (OrderType()!=OP_BUY && OrderType()!=OP_SELL)
         {
            cerrarPosicion(OrderTicket());
         }
      }
   }
}

double getFixedFractional (double precio, double sl, double porcentaje)
{
   double pips = 0;
   if (precio==0)
   {
      pips = sl;
   }
   else
   {
      pips = (precio-sl)/Point;
      pips = NormalizeDouble(MathAbs(pips), 1);
   }
   
   // Compruebo que es al menos el minimo de la plataforma
   if (pips<MarketInfo(Symbol(), MODE_STOPLEVEL))
      pips=MarketInfo(Symbol(), MODE_STOPLEVEL);
   
   double maximoriesgo = AccountEquity()*porcentaje;
   
   double perdidaporlote = pips * MarketInfo(Symbol(), MODE_TICKVALUE);
   
   double value;
   value  = NormalizeDouble((maximoriesgo/perdidaporlote),1);
   
   return (NormalizeLots(value));
}

double
getFixedRatio(double capitalInicial, double delta, double Lots) {
  double equity = AccountEquity();

  int i = 1;
  double deltaAnterior = capitalInicial;
  while(equity>((delta*i)+deltaAnterior))
  {
     deltaAnterior += delta*i;
     i++;
  }
  return(NormalizeLots(i*Lots));
}

double
getFixedLot(double lots){
   return (NormalizeLots(lots));
}

double
getLotsPerBalance(double balance){
   double equity = AccountEquity();

   double lots = NormalizeDouble((equity/balance),1);

   if( lots < 0.1 ){
      lots = 0.1;
   }
   
   return (NormalizeLots(lots));
}

// si el nuevo numero de lotes es superior a maximumLots, volvemos a empezar.
double getMartingala( double lots, double multiplier, double maximumLots){
   
   return (0.0);
}

// si el nuevo numero de lotes es superior a maximumLots, volvemos a empezar.
double getAntiMartingala( double lots, double multiplier, double maximumLots){
   
return (0.0);
}

string
getPeriodAsString(int period = 0)
{
   if (period==0) period=Period();
   switch(period)
   {
      case PERIOD_M1:
         return ("M1");
      case PERIOD_M5:
         return ("M5");
      case PERIOD_M15:
         return ("M15");
      case PERIOD_M30:
         return ("M30");
      case PERIOD_H1:
         return ("H1");
      case PERIOD_H4:
         return ("H4");
      case PERIOD_D1:
         return ("D1");
      case PERIOD_W1:
         return ("W1");
      case PERIOD_MN1:
         return ("MN1");
      default:
         return ("");       
   }

   return ("");       
}

double NormalizeLots(double l, string symbol = "")
{
   if (symbol == "") symbol = Symbol();
  // double ret = NormalizeDouble(l, 2);
  double ret = l;
   double min = MarketInfo(symbol, MODE_MINLOT);
   if (ret<min) return (0);
   
   double max = MarketInfo(symbol, MODE_MAXLOT);
   if (ret>max) return (max);

   // Compruebo que sea m?ltiplo de LOTSTEP
   double lotstep = MarketInfo(symbol, MODE_LOTSTEP);
   int total = MathRound(ret/lotstep);
   ret = lotstep*total;

   return (NormalizeDouble(ret,2));
}

bool modificarStopLoss(int ticket, double precioStopLoss)
{
   precioStopLoss=NormalizeDouble(precioStopLoss, Digits);

   // controlo el stoplevel
   double stoplevel=MarketInfo(Symbol(), MODE_STOPLEVEL)*Point;
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = precioStopLoss / Point;
      psl = psl / (ticksize/Point);
      precioStopLoss = psl * ticksize;
   }
   
   // Orden
   OrderSelect(ticket, SELECT_BY_TICKET);

   if (NormalizeDouble(precioStopLoss, Digits)==NormalizeDouble(OrderStopLoss(),Digits)) return;

   // Controlo que el nuevo SL sea mayor o menor que el precio
   if (OrderType()==OP_BUY)
      if (precioStopLoss>(OrderClosePrice()-stoplevel)) return (false);
   if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
      if (precioStopLoss>OrderOpenPrice()) return (false);
   if (OrderType()==OP_SELL)
      if (precioStopLoss<(OrderClosePrice()-stoplevel)) return (false);
   if (OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
      if (precioStopLoss<OrderOpenPrice()) return (false);

         
   if(OrderStopLoss()==0 ||
      (OrderStopLoss() < precioStopLoss && OrderType() == OP_BUY)
         || (OrderStopLoss() > precioStopLoss && OrderType() == OP_SELL)){
      int intentos = SegundosParaReintentarOperar*2;
      while(intentos>0){
         while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
         bool resultado = OrderModify(OrderTicket(),OrderOpenPrice(),precioStopLoss,OrderTakeProfit(),0,Yellow);
         if(!resultado)
         {
            Print("Error al modificar StopLoss. SL actual:"+ OrderStopLoss()+" Nuevo SL:"+precioStopLoss+". Error "+ GetLastError());
            intentos--;
            Sleep(500);
         }
         else return (true);
      }
   }
   return (false);
}

bool modificarPendiente(int ticket, double nuevoPrecio)
{
   nuevoPrecio=NormalizeDouble(nuevoPrecio, Digits);

   // Orden
   if (!OrderSelect(ticket, SELECT_BY_TICKET)) return (false);

   if (OrderType()==OP_BUY || OrderType()==OP_SELL) return (false);

   if (NormalizeDouble(nuevoPrecio, Digits)==NormalizeDouble(OrderOpenPrice(),Digits)) return;
         
   int intentos = SegundosParaReintentarOperar*2;
   while(intentos>0){
      while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
      bool resultado = OrderModify(ticket,nuevoPrecio,OrderStopLoss(),OrderTakeProfit(),0,Yellow);
      if(!resultado)
      {
         Print("Error al modificar el precio. Precio actual:"+ OrderOpenPrice()+" Nuevo precio:"+nuevoPrecio+". Error "+ GetLastError());
         intentos--;
         Sleep(500);
      }
      else return (true);
   }
   return (false);
}

bool modificarSLyTP(int ticket, double precioStopLoss, double precioTakeProfit)
{
   if (precioStopLoss==0 && precioTakeProfit==0) return (false);

   // controlo el stoplevel
   double stoplevel=MarketInfo(Symbol(), MODE_STOPLEVEL)*Point;
   
   // Orden
   OrderSelect(ticket, SELECT_BY_TICKET);

   // STOPLOSS
   precioStopLoss=NormalizeDouble(precioStopLoss, Digits);
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = precioStopLoss / Point;
      psl = psl / (ticksize/Point);
      precioStopLoss = psl * ticksize;
   }

   if (precioStopLoss > 0)
   {
      // Controlo que el nuevo SL sea mayor o menor que el precio
      if (OrderType()==OP_BUY)
         if (precioStopLoss>(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
         if (precioStopLoss>OrderOpenPrice()) return (false);
      if (OrderType()==OP_SELL)
         if (precioStopLoss<(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
         if (precioStopLoss<OrderOpenPrice()) return (false);
   }

   // TAKEPROFIT
   precioTakeProfit=NormalizeDouble(precioTakeProfit, Digits);

   if(ticksize!=0)
   {
      // Redondeo a ticksize
      psl = precioTakeProfit / Point;
      psl = psl / (ticksize/Point);
      precioTakeProfit = psl * ticksize;
   }

   if (precioTakeProfit>0)
   {
      if (NormalizeDouble(precioStopLoss, Digits)==NormalizeDouble(OrderStopLoss(),Digits)
         && NormalizeDouble(precioTakeProfit, Digits)==NormalizeDouble(OrderTakeProfit(),Digits)) return;

      // Controlo que el nuevo TP sea mayor o menor que el precio
      if (OrderType()==OP_BUY)
         if (precioTakeProfit<(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
         if (precioTakeProfit<OrderOpenPrice()) return (false);
      if (OrderType()==OP_SELL)
         if (precioTakeProfit>(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
         if (precioTakeProfit>OrderOpenPrice()) return (false);
   }

   if(OrderStopLoss()==0 ||
      (OrderStopLoss() < precioStopLoss && OrderType() == OP_BUY)
         || (OrderStopLoss() > precioStopLoss && OrderType() == OP_SELL))
   {
      if((OrderTakeProfit()==0 ||
         (OrderTakeProfit() > precioTakeProfit && OrderType() == OP_BUY)
            || (OrderTakeProfit() < precioTakeProfit && OrderType() == OP_SELL)
             && MathAbs(OrderClosePrice()-precioTakeProfit)>stoplevel))
      {
         int intentos = SegundosParaReintentarOperar*2;
         while(intentos>0){
            while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
            bool resultado = OrderModify(OrderTicket(),OrderOpenPrice(),precioStopLoss,precioTakeProfit,0,Yellow);
            if(!resultado)
            {
               Print("Error al modificar StopLoss. SL actual:"+ OrderStopLoss()+" Nuevo SL:"+precioStopLoss+". Error "+ GetLastError());
               intentos--;
               Sleep(500);
            }
            else return (true);
         }
      }
   }
   return (false);
}

int
OrderProfitPoints(int ticket){
   if (!OrderSelect(ticket,SELECT_BY_TICKET)) return (0);
   
   if(OrderType() == OP_BUY)
    return(NormalizeDouble((OrderClosePrice()-OrderOpenPrice())/Point,0));
   else if(OrderType() == OP_SELL)
    return(NormalizeDouble((OrderOpenPrice()-OrderClosePrice())/Point,0));
}

void infoVline(int info, string motivo="", int col=-1){
   static int numse?al = 0;
   string NombreLinea;
     
   if (IsTesting() && !IsVisualMode()) return;
   
   if (numse?al==0)
   {
      // Es la primera vez que se carga el EA, borramos todas las l?neas verticales anteriores
      for (int i=ObjectsTotal()-1; i>=0; i--)
      {
         string name = ObjectName(i);
         if (StringSubstr(name, 0, 4)=="INFO" && ObjectType(name)==OBJ_VLINE)
            ObjectDelete(name);
      }
      numse?al++;
   }
   
   color LColor = Lime;

   if (col==0) LColor=Blue;
   if (col==1) LColor=Red;

   if (info<0)
   {
      if (info==-1 || col!=-1) LColor=Yellow;
      else LColor = Red;
   }
   
   // Modificar colores e informaci?n.
   switch(info)
   {
     case -1: // Fall? alguno de los trades que se enviaron.
         NombreLinea = "SE?AL #"+numse?al+" Fallo al operar"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;
     case -2:
         NombreLinea = "SE?AL #"+numse?al+" Fuera de ventana"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;   
     case -3:
         NombreLinea = "SE?AL #"+numse?al+" StopLoss incorrecto"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;   
     case -100:
         NombreLinea = "SE?AL #"+numse?al+" "+motivo; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;   
     default:
         NombreLinea = "SE?AL #"+numse?al+" OK"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;
   }
}


Saludos.
Adjuntos
stdlibSIv2.02.mqh
(27.25 KiB) 560 veces
Avatar de Usuario
rtrader
 
Mensajes: 279
Registrado: 12 Feb 2008, 14:02
Karma: 0

Re: bbollinguer funciona!

Notapor elchebeto » 22 May 2011, 02:06

rtrader escribió:Hola chaveznqoos.

Aclaro que no soy programador... revisando el MetaEditor encontré la v2.02, te pongo el código, espero que sea esto lo que buscas.

Código: Seleccionar todo
//+------------------------------------------------------------------+
//|                                                     stdlibSI.mqh |
//|                                              Sistemas Inversores |
//|                                http://www.sistemasinversores.com |
//+------------------------------------------------------------------+

#property copyright "Sistemas Inversores"
#property link      "http://www.sistemasinversores.com"


int MagicNumber;
int SegundosParaReintentarOperar = 20;

bool comprobarStopLoss(int SL) {
   
   int stopMinimo = MarketInfo(Symbol(),MODE_STOPLEVEL);
   if(SL!=0 && SL < stopMinimo){
      Alert("ERROR: El StopLoss m?nimo en ",Symbol()," es: ",stopMinimo);
      return(false);
   }
   else return(true);
}


bool comprobarTakeProfit(int TP) {
   
   int stopMinimo = MarketInfo(Symbol(),MODE_STOPLEVEL);
   if(TP!=0 && TP < stopMinimo){
      Alert("ERROR: El TakeProfit m?nimo en ",Symbol()," es: ",stopMinimo);
      return(false);
   }
   else return(true);
}

double
getSL(int tipo, int StopLoss, double precio=0)
{
   if(StopLoss == 0) return(0);
   double sl=0;
   
   double stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   stoplevel=stoplevel*Point;
   
   if(tipo == OP_BUY || tipo == OP_BUYLIMIT || tipo == OP_BUYSTOP) // COMPRA
   {
      if (precio==0)
      {
         RefreshRates();
         precio=Ask;
      }
      sl = (precio-StopLoss*Point);
      if (sl>precio-stoplevel)
         sl=precio-stoplevel;
   }
   if(tipo == OP_SELL || tipo == OP_SELLLIMIT || tipo == OP_SELLSTOP) // VENTA
   {
      if (precio==0)
      {
         RefreshRates();
         precio=Bid;
      }
      sl = (precio+StopLoss*Point);
      if (sl<precio+stoplevel)
         sl=precio+stoplevel;
   }
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = sl / Point;
      psl = psl / (ticksize/Point);
      sl = psl * ticksize;
   }
   
   return(sl);
}

double
getTP(int tipo, int TakeProfit, double precio=0)
{
   if(TakeProfit == 0) return(0);
   double tp = 0;
   
   double stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   stoplevel=stoplevel*Point;
   
   if(tipo == OP_BUY || tipo == OP_BUYLIMIT || tipo == OP_BUYSTOP) // COMPRA
   {
      if (precio==0)
      {
         RefreshRates();
         precio=Ask;
      }
      tp=precio+TakeProfit*Point;
      if (tp<precio+stoplevel)
         tp=precio+stoplevel;
   }
   if(tipo == OP_SELL || tipo == OP_SELLLIMIT || tipo == OP_SELLSTOP) // VENTA
   { 
      if (precio==0)
      {
         RefreshRates();
         precio=Bid;
      }
      tp=precio-(TakeProfit*Point);
      if (tp>precio-stoplevel)
         tp=precio-stoplevel;
   }
   
   tp = NormalizeDouble(tp, Digits);
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = tp / Point;
      psl = psl / (ticksize/Point);
      tp = psl * ticksize;
   }
   
   return (tp);
}

bool se?alInversa?(int se?al){
   static int se?al_old = -1;
   
   if(se?al_old == -1){
      se?al_old = se?al;
   }
   
   if(se?al_old != se?al && se?al!=-1){
        se?al_old = se?al;
        return(true);
   }
   else return(false);
}


int
ordenesTotalesEA(int tipo=-1){

   int totalEA = 0;
   int totalMT = OrdersTotal();

   if (tipo==-1 && (IsOptimization() || IsTesting()))
      return (totalMT);
   
   for(int i=0; i<totalMT; i++)
      if(OrderSelect(i,SELECT_BY_POS) && OrderMagicNumber() == MagicNumber) {
         if (tipo==-1 || OrderType()==tipo)
            totalEA++;
      }
     
   return(totalEA);
}

bool
cerrarPosiciones(int tipo = -1){

   int error;
   
   for(int i=OrdersTotal()-1; i>=0; i--){
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderMagicNumber() != MagicNumber) continue;
      if (tipo!=-1 && OrderType()!=tipo) continue;
      bool exito=false;
      while (!exito) {
         RefreshRates();
         while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
         if (OrderType()==OP_BUY || OrderType() == OP_SELL)
            exito=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(OrderClosePrice(), Digits),Slippage,Yellow);
         else
            exito=OrderDelete(OrderTicket());
         if (!exito)
         {
            error = GetLastError(); 
            // Si el error no es recuperable, salimos
            if (error==4108 || error==4106 || error==133)  // 4108=INVALID_TICKET, 4106=UNKNOWN_SYMBOL, 133=ERR_TRADE_DISABLED
               break;
            Sleep(500);
         }
      }
   }
   if (ordenesTotalesEA()==0)
      return(true);
   return (false);
}


int abrirPosicion(string symbol, int se?al, double precio=0, double sl=0, double tp=0, double size=0, string comentario="", datetime expiration=0)
{
   if (comentario=="")
      comentario = NombreDelEA + " " + getPeriodAsString(Period()) + ";";
   double precioApertura;
   color colorFlecha;
   int ticket;
   int error;
   double Stop, Take;
   double digits = MarketInfo(symbol, MODE_DIGITS);
   double point = MarketInfo(symbol, MODE_POINT);
   double stoplevel = (MarketInfo(symbol, MODE_STOPLEVEL)+1)*point;


   int intentos = SegundosParaReintentarOperar*2;
   precio=NormalizeDouble(precio, digits);
   
   double ticksize = MarketInfo(symbol, MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = precio / point;
      psl = psl / (ticksize/point);
      precio = psl * ticksize;
   }
   
   while(intentos>0)
   {       
      // Obtener precio de apertura.
      RefreshRates();
      if(se?al == OP_BUY ||se?al==OP_BUYLIMIT || se?al==OP_BUYSTOP) {precioApertura = NormalizeDouble(MarketInfo(symbol, MODE_ASK),digits); colorFlecha = Green;}
      if(se?al == OP_SELL ||se?al==OP_SELLLIMIT || se?al==OP_SELLSTOP) {precioApertura = NormalizeDouble(MarketInfo(symbol, MODE_BID),digits); colorFlecha = Red;}

      // Precio=0?
      if (precio==0)
      {
         precio=precioApertura;
      }

      // Size=0?
      if (size==0) size=MarketInfo(symbol, MODE_MINLOT);
      else size=NormalizeLots(size,symbol);

      /// Si el precio es menor que el actual, cambiamos stop por limit
      if (se?al!=OP_BUY && se?al!=OP_SELL)
      {
         if (precio<precioApertura && se?al==OP_BUYSTOP)
            se?al=OP_BUYLIMIT;
         if (precio>precioApertura && se?al==OP_BUYLIMIT)
            se?al=OP_BUYSTOP;
   
         if (precio>precioApertura && se?al==OP_SELLSTOP)
            se?al=OP_SELLLIMIT;
         if (precio<precioApertura && se?al==OP_SELLLIMIT)
            se?al=OP_SELLSTOP;


         if (se?al==OP_BUYLIMIT || se?al==OP_BUYSTOP ||se?al==OP_SELLLIMIT ||se?al==OP_SELLSTOP)
         {
            if (MathAbs(precioApertura-precio) > stoplevel)
               precioApertura=precio;
            else
            {
               if (se?al==OP_BUYLIMIT || se?al ==OP_BUYSTOP)
               {
                  //precioApertura=precio+spread;
                  se?al=OP_BUY;
                  expiration=0;
               }
               if (se?al==OP_SELLLIMIT || se?al == OP_SELLSTOP)
               {
                  //precioApertura=precio-spread;
                  se?al=OP_SELL;
                  expiration=0;
               }
            }
         }
      }
   
      // StopLoss y TakeProfit
      if (sl!=0) Stop=sl;
      else Stop=0;
      if (tp!=0) Take=tp;
      else Take=0;
   
      // Comprobamos que SL y TP sean correctos
      if (se?al==OP_BUY || se?al==OP_BUYLIMIT || se?al==OP_BUYSTOP)
      {
         if (Stop!=0 && (precioApertura-Stop)<stoplevel)
         {
            if((precioApertura-Stop)>0) // No hay mucha diferencia
            {
               Stop=NormalizeDouble(precioApertura-stoplevel, digits);
               Print("Cambiando el StopLoss al m?nimo de la plataforma");
            }
            else
            {
               Stop=0;
               Print("Eliminando StopLoss incorrecto.");
            }
         }
         if (Take!=0 && (Take-precioApertura)<stoplevel)
         {
            if((Take-precioApertura)>0) // No hay mucha diferencia
            {
               Take=NormalizeDouble(precioApertura+stoplevel, digits);
               Print("Cambiando el TakeProfit al m?nimo de la plataforma");
            }
            else
            {
               Take=0;
               Print("Eliminando TakeProfit incorrecto");
            }
         }
      }
      if (se?al==OP_SELL || se?al==OP_SELLLIMIT || se?al==OP_SELLSTOP)
      {
         if (Stop!=0 && (Stop-precioApertura)<stoplevel)
         {
            if((Stop-precioApertura)>0) // No hay mucha diferencia
            {
               Stop=NormalizeDouble(precioApertura+stoplevel, digits);
               Print("Cambiando el StopLoss al m?nimo de la plataforma");
            }
            else
            {
               Print("Eliminando StopLoss incorrecto");
               Stop=0;
            }
         }
         if (Take!=0 && (precioApertura-Take)<stoplevel)
         {
            if((precioApertura-Take)>0) // No hay mucha diferencia
            {
               Take=NormalizeDouble(precioApertura-stoplevel, digits);
               Print("Cambiando el TakeProfit al m?nimo de la plataforma");
            }
            else
            {
               Take=0;
               Print("Eliminando TakeProfit incorrecto");
            }
         }
      }
      while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
      ticket = OrderSend(symbol,se?al,size,precioApertura,Slippage,0,0,comentario,MagicNumber,expiration,colorFlecha);
      if(ticket<0){
         error = GetLastError();
         Print("OrderSend fall? con error #",error);
         Print("Orden: ", se?al, " L=",size," pa=",precioApertura," precio="+precio+" sp=",Slippage," sl=",Stop," tp=",Take," c=",comentario," stoplevel=",stoplevel," Bid=",MarketInfo(symbol, MODE_BID));
         intentos--;
         Sleep(500); // Pausa antes de reintentar.
      }
      else
      {
         // Ticket v?lido, modificamos SL y TP para FXCM y MIG entre otros
         modificarSLyTP(ticket, Stop, Take);
         return(ticket); // ticket v?lido.
      }
   } 
   
   Alert("Se intent? operar durante "+SegundosParaReintentarOperar+" segundos. Error #"+error);
   return(-1);
}

bool cerrarPosicion(int ticket)
{
   int error=-1;
   
   // Compruebo que el ticket exista
   if (ticket<1) return (false);
   
   int nerrores=0;

   while(true) // Intentamos cerrar hasta que no haya error.
   {
      // Obtener precio de cierre.
      if (OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
      {
         RefreshRates();
         bool result;
         while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
         if (OrderType() ==OP_BUY || OrderType() == OP_SELL)
            result = OrderClose(ticket,OrderLots(),NormalizeDouble(OrderClosePrice(), Digits),Slippage,Yellow);
         else
            result = OrderDelete(ticket);
         if (!result) {
            error = GetLastError();
            if (OrderType() ==OP_BUY || OrderType() == OP_SELL)
               Print("OrderClose fall? con error #",error);
            else
               Print("OrderDelete fall? con error #",error);
            // Si el error no es recuperable, salimos
            if (error==4108 || error==4106 || error==133)  // 4108=INVALID_TICKET, 4106=UNKNOWN_SYMBOL, 133=ERR_TRADE_DISABLED
               return (false);
            Sleep(500); // Pausa antes de reintentar.
         }
         else
            return(true);
       }
       else { nerrores++; if (nerrores>10) break; }
   }
}

int
getMagicNumber(bool recuperarOrdenes = false)
{
   int MagicNumber;
   
   // Magic Number Autom?tico.
   if(!IsTesting()) MagicNumber = WindowHandle(Symbol(),0);
   else if(!IsVisualMode()) MagicNumber = 23;
   
   if (recuperarOrdenes)
   {
      // Si hay operaciones abiertas, de un EA que se ha cerrado antes, tomamos su MagicNumber
      for (int i=OrdersTotal()-1; i>=0; i--)
      {
         OrderSelect(i, SELECT_BY_POS);
         if (OrderSymbol()!=Symbol()) continue;
         // Coincide el nombre del EA, y coindice el periodo, o no hay periodo
         if (StringSubstr(OrderComment(),0, StringLen(NombreDelEA)) == NombreDelEA
            && (StringFind(OrderComment(), " ", StringLen(NombreDelEA)+1)==-1 ||
               StringSubstr(OrderComment(),StringLen(NombreDelEA)+1,StringLen(getPeriodAsString(Period())))==getPeriodAsString(Period())))
         {
            Print("Retomando orden "+OrderTicket());
            MagicNumber=OrderMagicNumber();
            // Modificamos la se?al inversa para detectar pr?ximos cambios de se?al
            se?alInversa?(OrderType());
            break;
         }
      }
   }
   
   return (MagicNumber);
}

void
ajustarTrailingStopTodas(int TrailingTrigger, int TrailingDistancia, int Step=0)
{
   for (int i=0; i<OrdersTotal(); i++)
   {
      if (!(OrderSelect(i, SELECT_BY_POS) && OrderMagicNumber()==MagicNumber)) continue;
   
      ajustarTrailingStop(OrderTicket(), TrailingTrigger, TrailingDistancia, Step);
   }
   
   return;
}


bool
ajustarTrailingStop(int ticket, int TrailingTrigger, int TrailingDistancia, int Step=0)
{
   int total;
   int beneficio;
   double nuevoStop, stopstep;
   
   if (!OrderSelect(ticket,SELECT_BY_TICKET))
      return (false);
 
   // Si la distancia es menor que el stoplevel, salimos
   if (TrailingDistancia < MarketInfo(OrderSymbol(), MODE_STOPLEVEL))
   {
      Print("No se puede modificar el SL, la distancia m?nima requerida es " + DoubleToStr(MarketInfo(OrderSymbol(), MODE_STOPLEVEL),0) + " y se ha calculado "+DoubleToStr(TrailingDistancia,0));
      return (false);
   }
   
    // Obtener beneficio de la orden
    if(OrderType() == OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
      beneficio = (OrderClosePrice()-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT);         
    else if(OrderType() == OP_SELL ||OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
      beneficio = (OrderOpenPrice()-OrderClosePrice())/MarketInfo(OrderSymbol(),MODE_POINT); 
   
    // Si no hay beneficio la dejamos
    if(beneficio <= 0) return(false);
   
    // Si hay beneficio y hay que ajustar
    if(beneficio > TrailingTrigger){
      if(OrderType() == OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP){
         nuevoStop = OrderOpenPrice() + (beneficio - TrailingDistancia) * Point; 
         nuevoStop=NormalizeDouble(nuevoStop, Digits);
         stopstep = nuevoStop-(Step*Point);
         if(NormalizeDouble(OrderStopLoss(),Digits) < NormalizeDouble(stopstep, Digits) || OrderStopLoss() == 0)
         {
            modificarStopLoss(OrderTicket(), nuevoStop);
         }
      }
      if(OrderType() == OP_SELL ||OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP){
         nuevoStop = OrderOpenPrice() - (beneficio - TrailingDistancia) * Point;
         nuevoStop = NormalizeDouble(nuevoStop, Digits);
         stopstep = nuevoStop+(Step*Point);
         if(NormalizeDouble(OrderStopLoss(),Digits) > NormalizeDouble(stopstep, Digits) || OrderStopLoss() == 0)
         {
            modificarStopLoss(OrderTicket(), nuevoStop);
         }
      }
     }
     
     // No se ajust? nada.
     return(false);   
}

void
ajustarBreakEvenTodas(int BreakEven)
{
   if (BreakEven==0) return;

   for (int i=0; i<OrdersTotal(); i++)
   {
      if (!(OrderSelect(i, SELECT_BY_POS) && OrderMagicNumber()==MagicNumber)) continue;
   
      ajustarBreakEven(OrderTicket(), BreakEven);
   }
   
   return;
}

bool
ajustarBreakEven(int ticket, int BreakEven)
{
   if (BreakEven==0) return;

   if (OrderProfitPoints(ticket)>=BreakEven)
      modificarStopLoss(ticket, OrderOpenPrice());
}

void
cerrarPendientesEA()
{
   int total = OrdersTotal();
   for (int i=total-1; i>=0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS) && OrderMagicNumber()==MagicNumber)
      {
         if (OrderType()!=OP_BUY && OrderType()!=OP_SELL)
         {
            cerrarPosicion(OrderTicket());
         }
      }
   }
}

double getFixedFractional (double precio, double sl, double porcentaje)
{
   double pips = 0;
   if (precio==0)
   {
      pips = sl;
   }
   else
   {
      pips = (precio-sl)/Point;
      pips = NormalizeDouble(MathAbs(pips), 1);
   }
   
   // Compruebo que es al menos el minimo de la plataforma
   if (pips<MarketInfo(Symbol(), MODE_STOPLEVEL))
      pips=MarketInfo(Symbol(), MODE_STOPLEVEL);
   
   double maximoriesgo = AccountEquity()*porcentaje;
   
   double perdidaporlote = pips * MarketInfo(Symbol(), MODE_TICKVALUE);
   
   double value;
   value  = NormalizeDouble((maximoriesgo/perdidaporlote),1);
   
   return (NormalizeLots(value));
}

double
getFixedRatio(double capitalInicial, double delta, double Lots) {
  double equity = AccountEquity();

  int i = 1;
  double deltaAnterior = capitalInicial;
  while(equity>((delta*i)+deltaAnterior))
  {
     deltaAnterior += delta*i;
     i++;
  }
  return(NormalizeLots(i*Lots));
}

double
getFixedLot(double lots){
   return (NormalizeLots(lots));
}

double
getLotsPerBalance(double balance){
   double equity = AccountEquity();

   double lots = NormalizeDouble((equity/balance),1);

   if( lots < 0.1 ){
      lots = 0.1;
   }
   
   return (NormalizeLots(lots));
}

// si el nuevo numero de lotes es superior a maximumLots, volvemos a empezar.
double getMartingala( double lots, double multiplier, double maximumLots){
   
   return (0.0);
}

// si el nuevo numero de lotes es superior a maximumLots, volvemos a empezar.
double getAntiMartingala( double lots, double multiplier, double maximumLots){
   
return (0.0);
}

string
getPeriodAsString(int period = 0)
{
   if (period==0) period=Period();
   switch(period)
   {
      case PERIOD_M1:
         return ("M1");
      case PERIOD_M5:
         return ("M5");
      case PERIOD_M15:
         return ("M15");
      case PERIOD_M30:
         return ("M30");
      case PERIOD_H1:
         return ("H1");
      case PERIOD_H4:
         return ("H4");
      case PERIOD_D1:
         return ("D1");
      case PERIOD_W1:
         return ("W1");
      case PERIOD_MN1:
         return ("MN1");
      default:
         return ("");       
   }

   return ("");       
}

double NormalizeLots(double l, string symbol = "")
{
   if (symbol == "") symbol = Symbol();
  // double ret = NormalizeDouble(l, 2);
  double ret = l;
   double min = MarketInfo(symbol, MODE_MINLOT);
   if (ret<min) return (0);
   
   double max = MarketInfo(symbol, MODE_MAXLOT);
   if (ret>max) return (max);

   // Compruebo que sea m?ltiplo de LOTSTEP
   double lotstep = MarketInfo(symbol, MODE_LOTSTEP);
   int total = MathRound(ret/lotstep);
   ret = lotstep*total;

   return (NormalizeDouble(ret,2));
}

bool modificarStopLoss(int ticket, double precioStopLoss)
{
   precioStopLoss=NormalizeDouble(precioStopLoss, Digits);

   // controlo el stoplevel
   double stoplevel=MarketInfo(Symbol(), MODE_STOPLEVEL)*Point;
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = precioStopLoss / Point;
      psl = psl / (ticksize/Point);
      precioStopLoss = psl * ticksize;
   }
   
   // Orden
   OrderSelect(ticket, SELECT_BY_TICKET);

   if (NormalizeDouble(precioStopLoss, Digits)==NormalizeDouble(OrderStopLoss(),Digits)) return;

   // Controlo que el nuevo SL sea mayor o menor que el precio
   if (OrderType()==OP_BUY)
      if (precioStopLoss>(OrderClosePrice()-stoplevel)) return (false);
   if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
      if (precioStopLoss>OrderOpenPrice()) return (false);
   if (OrderType()==OP_SELL)
      if (precioStopLoss<(OrderClosePrice()-stoplevel)) return (false);
   if (OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
      if (precioStopLoss<OrderOpenPrice()) return (false);

         
   if(OrderStopLoss()==0 ||
      (OrderStopLoss() < precioStopLoss && OrderType() == OP_BUY)
         || (OrderStopLoss() > precioStopLoss && OrderType() == OP_SELL)){
      int intentos = SegundosParaReintentarOperar*2;
      while(intentos>0){
         while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
         bool resultado = OrderModify(OrderTicket(),OrderOpenPrice(),precioStopLoss,OrderTakeProfit(),0,Yellow);
         if(!resultado)
         {
            Print("Error al modificar StopLoss. SL actual:"+ OrderStopLoss()+" Nuevo SL:"+precioStopLoss+". Error "+ GetLastError());
            intentos--;
            Sleep(500);
         }
         else return (true);
      }
   }
   return (false);
}

bool modificarPendiente(int ticket, double nuevoPrecio)
{
   nuevoPrecio=NormalizeDouble(nuevoPrecio, Digits);

   // Orden
   if (!OrderSelect(ticket, SELECT_BY_TICKET)) return (false);

   if (OrderType()==OP_BUY || OrderType()==OP_SELL) return (false);

   if (NormalizeDouble(nuevoPrecio, Digits)==NormalizeDouble(OrderOpenPrice(),Digits)) return;
         
   int intentos = SegundosParaReintentarOperar*2;
   while(intentos>0){
      while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
      bool resultado = OrderModify(ticket,nuevoPrecio,OrderStopLoss(),OrderTakeProfit(),0,Yellow);
      if(!resultado)
      {
         Print("Error al modificar el precio. Precio actual:"+ OrderOpenPrice()+" Nuevo precio:"+nuevoPrecio+". Error "+ GetLastError());
         intentos--;
         Sleep(500);
      }
      else return (true);
   }
   return (false);
}

bool modificarSLyTP(int ticket, double precioStopLoss, double precioTakeProfit)
{
   if (precioStopLoss==0 && precioTakeProfit==0) return (false);

   // controlo el stoplevel
   double stoplevel=MarketInfo(Symbol(), MODE_STOPLEVEL)*Point;
   
   // Orden
   OrderSelect(ticket, SELECT_BY_TICKET);

   // STOPLOSS
   precioStopLoss=NormalizeDouble(precioStopLoss, Digits);
   
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if(ticksize!=0)
   {
      // Redondeo a ticksize
      int psl = precioStopLoss / Point;
      psl = psl / (ticksize/Point);
      precioStopLoss = psl * ticksize;
   }

   if (precioStopLoss > 0)
   {
      // Controlo que el nuevo SL sea mayor o menor que el precio
      if (OrderType()==OP_BUY)
         if (precioStopLoss>(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
         if (precioStopLoss>OrderOpenPrice()) return (false);
      if (OrderType()==OP_SELL)
         if (precioStopLoss<(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
         if (precioStopLoss<OrderOpenPrice()) return (false);
   }

   // TAKEPROFIT
   precioTakeProfit=NormalizeDouble(precioTakeProfit, Digits);

   if(ticksize!=0)
   {
      // Redondeo a ticksize
      psl = precioTakeProfit / Point;
      psl = psl / (ticksize/Point);
      precioTakeProfit = psl * ticksize;
   }

   if (precioTakeProfit>0)
   {
      if (NormalizeDouble(precioStopLoss, Digits)==NormalizeDouble(OrderStopLoss(),Digits)
         && NormalizeDouble(precioTakeProfit, Digits)==NormalizeDouble(OrderTakeProfit(),Digits)) return;

      // Controlo que el nuevo TP sea mayor o menor que el precio
      if (OrderType()==OP_BUY)
         if (precioTakeProfit<(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
         if (precioTakeProfit<OrderOpenPrice()) return (false);
      if (OrderType()==OP_SELL)
         if (precioTakeProfit>(OrderClosePrice()-stoplevel)) return (false);
      if (OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
         if (precioTakeProfit>OrderOpenPrice()) return (false);
   }

   if(OrderStopLoss()==0 ||
      (OrderStopLoss() < precioStopLoss && OrderType() == OP_BUY)
         || (OrderStopLoss() > precioStopLoss && OrderType() == OP_SELL))
   {
      if((OrderTakeProfit()==0 ||
         (OrderTakeProfit() > precioTakeProfit && OrderType() == OP_BUY)
            || (OrderTakeProfit() < precioTakeProfit && OrderType() == OP_SELL)
             && MathAbs(OrderClosePrice()-precioTakeProfit)>stoplevel))
      {
         int intentos = SegundosParaReintentarOperar*2;
         while(intentos>0){
            while (!IsTradeAllowed() || IsTradeContextBusy()) Sleep(1000);
            bool resultado = OrderModify(OrderTicket(),OrderOpenPrice(),precioStopLoss,precioTakeProfit,0,Yellow);
            if(!resultado)
            {
               Print("Error al modificar StopLoss. SL actual:"+ OrderStopLoss()+" Nuevo SL:"+precioStopLoss+". Error "+ GetLastError());
               intentos--;
               Sleep(500);
            }
            else return (true);
         }
      }
   }
   return (false);
}

int
OrderProfitPoints(int ticket){
   if (!OrderSelect(ticket,SELECT_BY_TICKET)) return (0);
   
   if(OrderType() == OP_BUY)
    return(NormalizeDouble((OrderClosePrice()-OrderOpenPrice())/Point,0));
   else if(OrderType() == OP_SELL)
    return(NormalizeDouble((OrderOpenPrice()-OrderClosePrice())/Point,0));
}

void infoVline(int info, string motivo="", int col=-1){
   static int numse?al = 0;
   string NombreLinea;
     
   if (IsTesting() && !IsVisualMode()) return;
   
   if (numse?al==0)
   {
      // Es la primera vez que se carga el EA, borramos todas las l?neas verticales anteriores
      for (int i=ObjectsTotal()-1; i>=0; i--)
      {
         string name = ObjectName(i);
         if (StringSubstr(name, 0, 4)=="INFO" && ObjectType(name)==OBJ_VLINE)
            ObjectDelete(name);
      }
      numse?al++;
   }
   
   color LColor = Lime;

   if (col==0) LColor=Blue;
   if (col==1) LColor=Red;

   if (info<0)
   {
      if (info==-1 || col!=-1) LColor=Yellow;
      else LColor = Red;
   }
   
   // Modificar colores e informaci?n.
   switch(info)
   {
     case -1: // Fall? alguno de los trades que se enviaron.
         NombreLinea = "SE?AL #"+numse?al+" Fallo al operar"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;
     case -2:
         NombreLinea = "SE?AL #"+numse?al+" Fuera de ventana"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;   
     case -3:
         NombreLinea = "SE?AL #"+numse?al+" StopLoss incorrecto"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;   
     case -100:
         NombreLinea = "SE?AL #"+numse?al+" "+motivo; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;   
     default:
         NombreLinea = "SE?AL #"+numse?al+" OK"; numse?al++;
         ObjectCreate(NombreLinea,OBJ_VLINE,0,Time[0],Bid);     
         ObjectSet(NombreLinea,OBJPROP_COLOR,LColor);
         break;
   }
}


Saludos.



Gracias Rtrader con compartir, bueno no no se a alguien mas le a pasado que tiene una configuracion de un ea, en una semana hace backtesting y le da unos resultados muy buenos, y aveces no funciona ni siquiera el programa, si alguien sabe algo acerca de esto seria bueno que lo comentara, me ah pasado varias veces, a veces se arregla como por arte de magia y a veces no
Avatar de Usuario
elchebeto
 
Mensajes: 113
Registrado: 11 Ene 2011, 19:47
Karma: 0

Re: bbollinguer funciona!

Notapor cortex » 22 May 2011, 17:57

Eso a mi me pasa los fines de semana por el spread tan alto que se guarda en el mt4 ahora mismo tengo 5.4 en eurusd y cualquier sistema que ponga usa ese spread y falla
cortex
 
Mensajes: 32
Registrado: 08 Jul 2009, 01:15
Karma: 0

Re: bbollinguer funciona!

Notapor elchebeto » 22 May 2011, 20:00

mmm tiene logica, mira en esta imagen que esta cobrando casi 17 pips, en Alpari UK Eur-Usd, y en el Gbp-Jpy 21 pips

Imagen


Es decir que el backtesting utiliza el spread que hay actual, entonces es mejor realizarlo en el horario en el que se esta programado el ea, y observar el spread promedio en ese horario, para poder ajustar mejor la tecnica
Avatar de Usuario
elchebeto
 
Mensajes: 113
Registrado: 11 Ene 2011, 19:47
Karma: 0

Re: bbollinguer funciona!

Notapor atreyu » 22 May 2011, 23:08

hola a todos

no puedo compilar los archivos por que me dan errlores en los dos
atreyu
 
Mensajes: 13
Registrado: 05 May 2011, 23:52
Karma: 0

AnteriorSiguiente

Volver a Estrategias de Trading

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 0 invitados

cron