How can I get Close [0]? - page 2

 
Daniel Cioca #:

I don't understand different.

Probably void function is not available 

 
Daniel Cioca #:

On Tick function is available but I want to do it in the void function

 
Close[0] is the bid price, easy
 
amando #:
Close[0] is the bid price, easy

Yes,it's easy to get in the On Tick function, But Close[0] and Bid can't get close price of the current bar in the void function.

 
Kosei S #: Yes,it's easy to get in the On Tick function, But Close[0] and Bid can't get close price of the current bar in the void function.

The close price of the current chart (Close[0]) equals Bid, always.

You can read any bar in any function; void function is irrelevant.

 
William Roeder #:

The close price of the current chart (Close[0]) equals Bid, always.

You can read any bar in any function; void function is irrelevant.

#11 and #12 are same code, but got different price. Why are the same code but different results?

 
//+------------------------------------------------------------------+
//|                                                      EA Test.mq4 |
//|                        Copyright 2022, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#define MAGICMA  0001
//--- Inputs
input double Lots          =0.1;
input double MaximumRisk   =0.02;
input double DecreaseFactor=3;
input int    MovingPeriod  =12;
input int    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);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma;
   int res;
   int handle = FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";");
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);

//Pips
   double a = MathAbs(Close[0]-Open[0]);
   string b = DoubleToStr( NormalizeDouble( ( a/( 1*Point ) ),3 ),3 );
   double p = StrToDouble(b);//現在足の実体のPips
   //Print(a);
   
//Average Pips
   double candle = 0;
   double sum_candle =0;
   double count =0;
   double average =0;
   
   for(int j=1;j<=21;j++)
    { 
      double a1 = MathAbs(Close[j]-Open[j]);
      string b1 = DoubleToStr( NormalizeDouble( a1/ (1*Point  ),3 ),3 );
      double e1 = StrToDouble(b1);
      
      candle = e1;
      sum_candle += candle;
      count++;
    }
    
   if(count == 21 )
    {
     average = sum_candle/count;
    }
//--- sell conditions
   if(a*3.0>average)
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
//--- buy conditions
   if(a*3.0>average)
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
     }
//---
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma;
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//---
   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(OrderType()==OP_BUY)
        {
         if(Open[1]>ma && Close[1]<ma)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(Open[1]<ma && Close[0]>ma)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//---
  }
//+------------------------------------------------------------------+

Here is the entire code.

Since Close [0] in the if statement of Order send does not get the price of Bid, a becomes 0 and entry is not possible in the first place.


double a = MathAbs(Close[0]-Open[0]);← I don’t understand (Close[0] = Open[0])

so ↑a=0 that's why a*3.0>average = 0

 

Fernando explained already that you code only runs for first Tick at every bar.


When new Tick comes to your code, it means new price is coming.  During a period of time ( Timeframe) many ticks will come, and High Low Open Close will be defined for the current Bar. High, means the Highest price during that particular Bar, Low means the Lowest price, Open is the Opening price of the Bar, and Close is the closing price ( as explained above, if the Bar is not yet closed, Close[0] == Bid ). So we will use Bid instead of Close[0].

No we go back again to the example above. You are on 1Hr Timeframe, and it is 13:00 and new Bar is starting:

First Tick of the new Bar arrived ( Tick == new price). So for the current Bar we only have one price. Lets say first price of the new bar is 0.12345. 

Now we analize : 

What is Opening Price ?  is very first price arrived for the current Bar = 0.12345

What is High : as stated above High is Highest price received for this Bar. But for our Bar we only received one price ( first Tick) so High it will be also 0.12345

What is Low :  as stated above Low is Lowest price received for this Bar. But for our Bar we only received one price ( first Tick) so Low it will be also 0.12345

And what is Bid  : Bid is last price received, which is also 0.12345 and since bar is not yet closed, we said that Close[0] == Bid.

So you see, as Fernando said, at very first tick all price calculation for the Bar are equal. Close[0] == Open[0] == High[0] == Low[0]; because it is only one price available.


You Code only runs only for the first Tick of every bar, so always Open[0] == Close[0].

That is why in your code, if you want to test if price crossed over MA, you should compare Close[2] with Close[1]

if(Close[2]<ma && Close[1]>ma) 
        { Print " Crossed Up";}
 
Daniel Cioca #:

Fernando explained already that you code only runs for first Tick at every bar.


When new Tick comes to your code, it means new price is coming.  During a period of time ( Timeframe) many ticks will come, and High Low Open Close will be defined for the current Bar. High, means the Highest price during that particular Bar, Low means the Lowest price, Open is the Opening price of the Bar, and Close is the closing price ( as explained above, if the Bar is not yet closed, Close[0] == Bid ). So we will use Bid instead of Close[0].

No we go back again to the example above. You are on 1Hr Timeframe, and it is 13:00 and new Bar is starting:

First Tick of the new Bar arrived ( Tick == new price). So for the current Bar we only have one price. Lets say first price of the new bar is 0.12345. 

Now we analize : 

What is Opening Price ?  is very first price arrived for the current Bar = 0.12345

What is High : as stated above High is Highest price received for this Bar. But for our Bar we only received one price ( first Tick) so High it will be also 0.12345

What is Low :  as stated above Low is Lowest price received for this Bar. But for our Bar we only received one price ( first Tick) so Low it will be also 0.12345

And what is Bid  : Bid is last price received, which is also 0.12345 and since bar is not yet closed, we said that Close[0] == Bid.

So you see, as Fernando said, at very first tick all price calculation for the Bar are equal. Close[0] == Open[0] == High[0] == Low[0]; because it is only one price available.


You Code only runs only for the first Tick of every bar, so always Open[0] == Close[0].

That is why in your code, if you want to test if price crossed over MA, you should compare Close[2] with Close[1]

//Pips
   double a = MathAbs(Close[0]-Open[0]);
   string b = DoubleToStr( NormalizeDouble( ( a/( 1*Point ) ),3 ),3 );
   double p = StrToDouble(b);//現在足の実体のPips
   //Print(a);
   
//Average Pips
   double candle = 0;
   double sum_candle =0;
   double count =0;
   double average =0;
   
   for(int j=1;j<=21;j++)
    { 
      double a1 = MathAbs(Close[j]-Open[j]);
      string b1 = DoubleToStr( NormalizeDouble( a1/ (1*Point  ),3 ),3 );
      double e1 = StrToDouble(b1);
      
      candle = e1;
      sum_candle += candle;
      count++;
    }
    
   if(count == 21 )
    {
     average = sum_candle/count;
    }
//--- sell conditions
   if(a*3.0>average)
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
//--- buy conditions
   if(a*3.0>average)
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
     }

Ok, Thank you. So does this code mean that BId (Close [0]) only get the first tick?

How can I get the last tick?

I want to get the last Tick (ex100, not closed) of the Bar with the Order Send above and complete it.

 
Kosei S #:

Ok, Thank you. So does this code mean that BId (Close [0]) only get the first tick?

How can I get the last tick?

You can't know when a candle closes. Only when a new tick arrives that starts a new bar is the old bar closed.

For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
          MT4: New candle - MQL4 programming forum #3 (2014)
          MT5: Accessing variables - MQL4 programming forum #3 (2022)

I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
          Running EA once at the start of each bar - MQL4 programming forum (2011)

Reason: