How to buy on beginning and sell at the end?

 

Hi,

I´m trying to write a simple EA that put a buy order at the beginning of the bar and sell at the end of the bar.

I´m trying to develop these with a daily chart but I intent that it work’s on every timeframe.

The first part of the problem is easy because we can use the expression: “if(Volume[0]>1) return;” and a enter condition.

But I don´t have any ideas how can I close the position at the end of the bar (before the next day/bar).

Any idea?

Thanks,

 

since it is never known, which price tick will be the last one in a bar, so your option is to close on the next bar open (first tick of new bar)

the other solution is to write a script with eternal loop cycle and 1 second pause (Sleep(1000)) and close order at the last second of bar (or few seconds before), but either way this does not guarantee you execution at exact bar's close price (and also is not backtestable).

 

datetime lastT=NULL;

void start()

{

if (lastT == NULL) lastT = Time[0];

if ((lastT -Time[0]) == ( Period()*60))

{

CloseOrder(.....);

SendOrder(....);

lastT = Time[0];

}

return (0);

}

 

DxdCn

I've noticed that often the use of datetime builtins is not accurate - the terminal just never realises Xseconds and may get X[+-]1,2,3...

(ummm, when say accurate, I mean if I have a simple Comment(currentSecond); test program, it can be way out)

Could this mean that terminal might q up i/o or schedule it in some way that 'visually' it appears inaccurate but at EA code level - IS accurate ?

Have you experienced this?

If you have...?

Thanx

 
SpaceTrader:

Hi,

I´m trying to write a simple EA that put a buy order at the beginning of the bar and sell at the end of the bar.

I´m trying to develop these with a daily chart but I intent that it work’s on every timeframe.

The first part of the problem is easy because we can use the expression: “if(Volume[0]>1) return;” and a enter condition.

But I don´t have any ideas how can I close the position at the end of the bar (before the next day/bar).

Any idea?

Thanks,

Hi SpaceTrader,

the easiest way for me it is to open and close at the beggining of a new bar, wich is particulary useful with backtesting since the history for some reason doesn´t shows every move.

if(high[0] == low[0]) do whatever you want. This will consider the new bar everytime it is created.

The orde to close the previous opened order must be inside this conditioning and before sending the new order, otherwise it will close the order as soon as it is open, and we don't want that, right?

So it will look like this:

if (High{0} == Low[0]

{

CloseOpenedOrders();

send your order.........

}

Cheers

 

Hi,

Thank you very much for all responses!

The idea of close on the next bar is impossible because on Fridays I ´d be positioned until Monday…

I try to evaluate DxdCn solution so I create a very simple EA based on Moving Average EA but it is not working with EURUSD Daily.

I even try to use the Breakpoint solution ('Breakpoints in Tester: It's Possible!') to find the error but I have no clue…

I don´t believe MQL4 doesn´t have a way to close the deal at the end of the bar/day even a simple auto-trade system I used have this option (close negotiation at the end of the day). So there must be someway to code this on MQL4.

Maybe MetaQuotes can help us? Do you know how to contact them to read this question?

Here is my code:

#define MAGICMA  123123

static datetime lastT=NULL;

extern double Lots               = 0.1;
extern int    Slippage           = 3;
extern double MaximumRisk        = 0.02;
extern double DecreaseFactor     = 3;
extern double MovingPeriod       = 20;
extern double MovingShift        = 6;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+

int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }

//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma;
   int    res;
//---- go trading only for first tiks of new bar
   //if(Volume[0]>1) return;
//---- get Moving Average 
   ma=iMA(Symbol(),0,MovingPeriod,0,MODE_SMA,PRICE_CLOSE,0);
   
   //BreakPoint(ma, Close[1],Hour(), Minute());
//---- sell conditions
   if(Close[1]<ma)  
     {
      res=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"Cyber1",MAGICMA,0,Red);
      return;
     }
//---- buy conditions
   if(Close[1]>ma)  
     {
      res=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"Cyber1",MAGICMA,0,Blue);
      return;
     }
//----
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {

//---- go trading only for first tiks of new bar
  // if(Volume[0]>1) return;
//---- get Moving Average 
   
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //---- check order type 
      
      if (lastT == NULL) lastT = Time[0];
      if ((lastT -Time[0]) == ( Period()*60))
        {
          if(OrderType()==OP_BUY)
            {
              OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,White);
              break;
            }
          if(OrderType()==OP_SELL)
            {
             OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,White);
             break;
            }

          lastT = Time[0];
        }
      

     }
//----
  }
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+



void start()
  {
//---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol

   if(CalculateCurrentOrders(Symbol())==0)
     {
       CheckForOpen();
     }
   else
     {
       CheckForClose();
     }
//----
  }
//+------------------------------------------------------------------+

Any ideas??

Thanks

 

IS accurate ? on terminal, and MQL4 language, MT only allow you work on Period() timebase. for current time during one period, you can work but the results not sure.

Reason: