Cerrar sólo las operaciones rentables, en el objetivo de beneficio - página 3

 
af1:

Hi GumRai, thanks for your time. I've already tried with your changes, but orders keep closing at 1. In other words, profitable orders are not waiting to reach 25.

¿Incluso utilizando la línea de código suministrada previamente por DeVries y Raptor?

if(CloseAllNow) CloseAll();
    
    if(CloseProfitableTradesOnly && ProfitTarget == 0.0) CloseAllinProfit();
    
    if(BuyProfit+SellProfit >= ProfitTarget && !CloseProfitableTradesOnly) CloseAll(); 

    if(CloseProfitableTradesOnly && BuyProfit+SellProfit >= ProfitTarget) CloseAllinProfit();

    if(ClosePendingOnly) ClosePendingOrdersOnly();

Esperemos que no haya cambiado esta línea, la estaba considerando

if(CloseProfitableTradesOnly && ProfitTarget == 0.0) CloseAllinProfit();

Si lo cambiaste a 25.00, entonces tendrás todas las operaciones rentables de $1+ cerradas

 
GumRai:

¿Incluso utilizando la línea de código suministrada previamente por DeVries y Raptor?

Esperemos que no haya cambiado esta línea, la estaba considerando

Si lo cambiaste a 25.00, entonces tendrás todas las operaciones rentables de $1+ cerradas


He probado todas las sugerencias, pero sigue sin cerrar bien.

 
af1:


He probado todas las sugerencias, pero sigue sin cerrar bien.


Tal vez usted puede mostrar el código completo que está utilizando en este momento
 
GumRai:

Tal vez pueda mostrar el código completo que está utilizando en este momento

//|$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//|              Close 
//|   Last Updated 12-12-2006 10:00pm
//|$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
#define     NL    "\n" 

extern int    ProfitTarget     = 25;             // closes all orders once Float hits this $ amount
extern bool   CloseAllNow      = false;          // closes all orders now
extern bool   CloseProfitableTradesOnly = true; // closes only profitable trades
extern double ProftableTradeAmount      = 1;     // Only trades above this amount close out
extern bool   ClosePendingOnly = false;          // closes pending orders only
extern bool   UseAlerts        = false;

//+-------------+
//| Custom init |
//|-------------+
int init()
  {

  }

//+----------------+
//| Custom DE-init |
//+----------------+
int deinit()
  {

  }

//+------------------------------------------------------------------------+
//| Closes everything
//+------------------------------------------------------------------------+
void CloseAll()
{
   int i;
   bool result = false;

   while(OrdersTotal()>0)
   {
      // Close open positions first to lock in profit/loss
      for(i=OrdersTotal()-1;i>=0;i--)
      {
         if(OrderSelect(i, SELECT_BY_POS)==false) continue;

         result = false;
         if ( OrderType() == OP_BUY)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 15, Red );
         if ( OrderType() == OP_SELL)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 15, Red );
         if (UseAlerts) PlaySound("alert.wav");
      }
      for(i=OrdersTotal()-1;i>=0;i--)
      {
         if(OrderSelect(i, SELECT_BY_POS)==false) continue;

         result = false;
         if ( OrderType()== OP_BUYSTOP)  result = OrderDelete( OrderTicket() );
         if ( OrderType()== OP_SELLSTOP)  result = OrderDelete( OrderTicket() );
         if ( OrderType()== OP_BUYLIMIT)  result = OrderDelete( OrderTicket() );
         if ( OrderType()== OP_SELLLIMIT)  result = OrderDelete( OrderTicket() );
         if (UseAlerts) PlaySound("alert.wav");
      }
      Sleep(1000);
   }
}
   
//+------------------------------------------------------------------------+
//| cancels all orders that are in profit
//+------------------------------------------------------------------------+
void CloseAllinProfit()
{
  for(int i=OrdersTotal()-1;i>=0;i--)
 {
    OrderSelect(i, SELECT_BY_POS);
    bool result = false;
        if ( OrderType() == OP_BUY && OrderProfit()+OrderSwap()>ProftableTradeAmount)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
        if ( OrderType() == OP_SELL && OrderProfit()+OrderSwap()>ProftableTradeAmount)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
        if (UseAlerts) PlaySound("alert.wav");
 }
  return; 
}

//+------------------------------------------------------------------------+
//| cancels all pending orders 
//+------------------------------------------------------------------------+
void ClosePendingOrdersOnly()
{
  for(int i=OrdersTotal()-1;i>=0;i--)
 {
    OrderSelect(i, SELECT_BY_POS);
    bool result = false;
        if ( OrderType()== OP_BUYSTOP)   result = OrderDelete( OrderTicket() );
        if ( OrderType()== OP_SELLSTOP)  result = OrderDelete( OrderTicket() );
  }
  return; 
  }

//+-----------+
//| Main      |
//+-----------+
int start()
  {
   int      OrdersBUY;
   int      OrdersSELL;
   double   BuyLots, SellLots, BuyProfit, SellProfit;

//+------------------------------------------------------------------+
//  Determine last order price                                       |
//-------------------------------------------------------------------+
      for(int i=0;i<OrdersTotal();i++)
      {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue;
         if(OrderType()==OP_BUY)  
         {
            OrdersBUY++;
            BuyLots += OrderLots();
            BuyProfit += OrderProfit() + OrderCommission() + OrderSwap();
         }
         if(OrderType()==OP_SELL) 
         {
            OrdersSELL++;
            SellLots += OrderLots();
            SellProfit += OrderProfit() + OrderCommission() + OrderSwap();
         }
      }               
   
    if(CloseAllNow) CloseAll();
    
    if(CloseProfitableTradesOnly && ProfitTarget == 0.0) CloseAllinProfit();
    
    if(BuyProfit+SellProfit >= ProfitTarget && !CloseProfitableTradesOnly) CloseAll();
    
    if(CloseProfitableTradesOnly && BuyProfit+SellProfit >= ProfitTarget) CloseAllinProfit(); 

    if(ClosePendingOnly) ClosePendingOrdersOnly();
       
   
   Comment("                            Comments Last Update 12-12-2006 10:00pm", NL,
           "                            Buys    ", OrdersBUY, NL,
           "                            BuyLots        ", BuyLots, NL,
           "                            Sells    ", OrdersSELL, NL,
           "                            SellLots        ", SellLots, NL,
           "                            Balance ", AccountBalance(), NL,
           "                            Equity        ", AccountEquity(), NL,
           "                            Margin              ", AccountMargin(), NL,
           "                            MarginPercent        ", MathRound((AccountEquity()/AccountMargin())*100), NL,
           "                            Current Time is  ",TimeHour(CurTime()),":",TimeMinute(CurTime()),".",TimeSeconds(CurTime()));
 } // start()

 


 

Por favor, remítase a mi post

https://forum.mql4.com/56959/page2#822980

No estás sumando sólo las operaciones rentables. Usted está calculando las ganancias o pérdidas netas

 
GumRai:

Por favor, remítase a mi post

https://forum.mql4.com/56959/page2#822980

No estás sumando sólo las operaciones rentables. Usted está calculando las ganancias o pérdidas netas



GumRai, he hecho los cambios de código sugeridos por Raptor y por ti:

https://www.mql5.com/en/forum/146091
https://www.mql5.com/en/forum/146091/page2#822980

Y ahora parece cerrar bien. ¡Gracias por eso!


Sólo una cosa más. Si quiero calcular sólo las operaciones rentables de compra, o sólo las operaciones rentables de venta, en lugar de calcular todas las operaciones rentables, ¿qué debo cambiar?

Estoy pensando en este cambio para calcular sólo las compras, pero no estoy seguro. ¿Es esto correcto?

de esto:

if(OrderType()==OP_SELL) 
         {
            OrdersSELL++;
            SellLots += OrderLots(); 
            ThisTradeProfit=OrderProfit() + OrderCommission() + OrderSwap();
            if(ThisTradeProfit>0)
            BuyProfit += ThisTradeProfit;
         }

a esto:

//if(OrderType()==OP_SELL) 
         {
            //OrdersSELL++;
            //SellLots += OrderLots(); 
            //ThisTradeProfit=OrderProfit() + OrderCommission() + OrderSwap();
            //if(ThisTradeProfit>0)
            //BuyProfit += ThisTradeProfit;
         }
 

Supongo que podría añadir 2 bool externos a los parámetros de entrada, llamados algo así como "BuyTradesOnly" y "SellTradesOnly", ambos establecidos inicialmente en falso

entonces

if(OrderType()==OP_SELL && BuyTradesOnly == false)
         {
            OrdersSELL++;
            SellLots += OrderLots(); 
            ThisTradeProfit=OrderProfit() + OrderCommission() + OrderSwap();
            if(ThisTradeProfit>0)
            BuyProfit += ThisTradeProfit;
         }
 
GumRai:

Supongo que podría añadir 2 bool externos a los parámetros de entrada, llamados algo así como "BuyTradesOnly" y "SellTradesOnly", ambos establecidos inicialmente en falso

entonces


No añadí el bool 2 externo, sólo cambio esto para cerrar "sólo órdenes de compra"

for(int i=0;i<OrdersTotal();i++)
      {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue;
         if(OrderType()==OP_BUY)  
         {
            OrdersBUY++;
            BuyLots += OrderLots();
            double ThisTradeProfit=OrderProfit() + OrderCommission() + OrderSwap();
            if(ThisTradeProfit>0)
            BuyProfit += ThisTradeProfit;
         }

y cambiar esto para cerrar "sólo órdenes de venta"

for(int i=0;i<OrdersTotal();i++)
      {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue;
         if(OrderType()==OP_SELL)  
         {
            OrdersSELL++;
            SellLots += OrderLots();
            double ThisTradeProfit=OrderProfit() + OrderCommission() + OrderSwap();
            if(ThisTradeProfit>0)
            BuyProfit += ThisTradeProfit;
         }

Así que ahora tengo dos EA's. Uno para cerrar las compras, y otro para cerrar las ventas. Eso está bien para mí.


He probado en ambas cuentas, demo y real. En demo funciona bien, pero en la cuenta real, una vez que se alcanza el objetivo de ganancias, comenzará a cerrar posiciones, pero luego dejará de cerrar posiciones cuando las órdenes restantes caigan por debajo del objetivo de ganancias. Esto sucede si el precio está cambiando en el momento del cierre. Así que tiende a dejar abiertas las órdenes rentables, en lugar de cerrarlas todas (órdenes rentables).

He leído este post de RaptorUK https://www.mql5.com/en/forum/139654. Es algo así, pero no sé realmente lo que podría ser la mejor solución para este tema.


 
af1:


He leído este post de RaptorUK https://www.mql5.com/en/forum/139654. Es algo así, pero no sé realmente cuál puede ser la mejor solución para este tema.

La solución se da en el hilo . . por eso lo he creado. Cuenta hacia abajo en el bucle no hacia arriba.
 
RaptorUK:
La solución se da en el hilo... por eso lo he creado. Cuenta hacia abajo en el bucle no hacia arriba.


Ok Raptor, voy a intentar hacer ese bucle, pero antes de hacerlo, que tal si cambio

de esto:
}
      Sleep(1000);
   }
A esto:
}
      Sleep(5000);
      RefreshRates();
      continue;
   }


¿Podría esto hacer el trabajo?