Closing trade before end of candle it entered

 

Hi i am trying to close my trade before the start of the new candle but have been unsuccessful so far , any help/advice is appreciated.


#include <Trade\Trade.mqh>



input double MaximumRisk        = 0.00;    // Maximum Risk in percentage

input double DecreaseFactor     = 0;       // Descrease factor

input int    MovingPeriod       = 8;      // Moving Average period

input int    MovingShift        = 0;       // Moving Average shift

//---

int   ExtHandle=0;

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

//| Calculate optimal lot size                                       |

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

double TradeSizeOptimized(void)

  {

   double price=0.0;

   double margin=0.0;

//--- select lot size

   if(!SymbolInfoDouble(_Symbol,SYMBOL_ASK,price))

      return(0.0);

   if(!OrderCalcMargin(ORDER_TYPE_BUY,_Symbol,1.0,price,margin))

      return(0.0);

   if(margin<=0.0)

      return(0.0);



   double lot=NormalizeDouble(AccountInfoDouble(ACCOUNT_FREEMARGIN)*MaximumRisk/margin,2);

//--- calculate number of losses orders without a break

   if(DecreaseFactor>0)

     {

      //--- select history for access

      HistorySelect(0,TimeCurrent());

      //---

      int    orders=HistoryDealsTotal();  // total history deals

      int    losses=0;                    // number of losses orders without a break



      for(int i=orders-1;i>=0;i--)

        {

         ulong ticket=HistoryDealGetTicket(i);

         if(ticket==0)

           {

            Print("HistoryDealGetTicket failed, no trade history");

            break;

           }

         //--- check symbol

         if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=_Symbol)

            continue;

         //--- check profit

         double profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);

         if(profit>0.0)

            break;

         if(profit<0.0)

            losses++;

        }

      //---

      if(losses>1)

         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);

     }

//--- normalize and check limits

   double stepvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);

   lot=stepvol*NormalizeDouble(lot/stepvol,0);



   double minvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);

   if(lot<minvol)

      lot=minvol;



   double maxvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);

   if(lot>maxvol)

      lot=maxvol;

//--- return trading volume

   return(lot);

  }

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

//| Check for open position conditions                               |

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

void CheckForOpen(void)

  {

   double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   

   MqlRates rt[2];

//--- go trading only for first ticks of new bar

   if(CopyRates(_Symbol,_Period,0,1,rt)!=1)

     {

      Print("CopyRates of ",_Symbol," failed, no history");

      return;

     }

   if(rt[1].tick_volume>1)

      return;

//--- get current Moving Average 

   double   ma[1];

   if(CopyBuffer(ExtHandle,0,0,1,ma)!=1)

     {

      Print("CopyBuffer from iMA failed, no data");

      return;

     }

//--- check signals

   ENUM_ORDER_TYPE signal=WRONG_VALUE;



   if(rt[0].open>ma[0] && currentBid<ma[0])

      signal=ORDER_TYPE_SELL;    // sell conditions

   else

     {

      if(rt[0].open<ma[0] && currentAsk>ma[0])

         signal=ORDER_TYPE_BUY;  // buy conditions

     }

//--- additional checking

   if(signal!=WRONG_VALUE)

      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))

         if(Bars(_Symbol,_Period)>100)

           {

            CTrade trade;

            trade.PositionOpen(_Symbol,signal,TradeSizeOptimized(),

                               SymbolInfoDouble(_Symbol,signal==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK),

                               0,0);

           }

//---

  }

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

//| Check for close position conditions                              |

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

void CheckForClose(void)

  {

   MqlRates rt[2];

   double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

//--- go trading only for first ticks of new bar

   if(CopyRates(_Symbol,_Period,0,2,rt)!=2)

     {

      Print("CopyRates of ",_Symbol," failed, no history");

      return;

     }

   if(rt[1].tick_volume>1)

      return;

//--- get current Moving Average 

   double   ma[1];

   if(CopyBuffer(ExtHandle,0,0,1,ma)!=1)

     {

      Print("CopyBuffer from iMA failed, no data");

      return;

     }

//--- positions already selected before

   bool signal=false;

   long type=PositionGetInteger(POSITION_TYPE);



   if(type==(long)POSITION_TYPE_BUY || currentBid>ma[0] )

      signal=true;

   if(type==(long)POSITION_TYPE_SELL || currentBid<ma[0])

      signal=true;

//--- additional checking

   if(signal)

      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))

         if(Bars(_Symbol,_Period)>100)

           {

            CTrade trade;

            trade.PositionClose(_Symbol,3);

           }

//---

  }

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

//| Expert initialization function                                   |

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

int OnInit(void)

  {

//---

   ExtHandle=iMA(_Symbol,_Period,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE);

   if(ExtHandle==INVALID_HANDLE)

     {

      printf("Error creating MA indicator");

      return(INIT_FAILED);

     }

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert tick function                                             |

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

void OnTick(void)

  {

//---

   if(PositionSelect(_Symbol))

      CheckForClose();

   else

      CheckForOpen();

//---

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

  }

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

通过MQL5社区和服务探索MetaTrader 5的新机遇
通过MQL5社区和服务探索MetaTrader 5的新机遇
  • 2023.02.28
  • www.mql5.com
MQL5:MetaTrader 5客户端内置的交易策略语言。语言允许编写您自己的自动交易系统,技术指标,脚本和函数程序库
 

Please edit your post to use the CODE button (Alt-S)!

Use the CODE button


 
Sergey Golubev #:

Please edit your post to use the CODE button (Alt-S)!





sorry about that im new here

 

The open time of the current bar:

#define  BoB(t) ((t)-((t)%(PeriodSeconds(_Period))))        // Begin of Bar
..
datetime tOpn = BoB(TimeCurrent());

now the time to close:

tLeave = tOpn + PeriodSeconds(_Period) - n; // n= amount of seconds 

so if there are tick coming in:

if (TimeCurrent()>tLeave) closeMyPosition();
 
i am trying to get it to close the trade on the candle it entered in but it seems to only be calling the closing fucntion at the start of the next candle any idea why it is doing this?
 
Carl Schreiber #:

The open time of the current bar:

now the time to close:

so if there are tick coming in:

thanks so much , but it isnt closing on the current candle
 
dhashan naidoo #:
i am trying to get it to close the trade on the candle it entered in but it seems to only be calling the closing fucntion at the start of the next candle any idea why it is doing this?

Because you coded it maybe ?

   if(rt[1].tick_volume>1)

      return;
 
Alain Verleyen #:

Because you coded it maybe ?

i was working off existing code and missed this , thanks
 

The function to close a position is part of ..Trade\Trade.mqh

Open  Trade.mqh in the Editor and look how it is done and how you can use the function.

Reason: