I need some help with my function please!

 

Hello everybody,

I am designing a function that will close a position the moment the current price crosses over a MA. the problem is that I am not able to properly define whether the price is above the MA or below the MA at the time that the position is open. I tried by matching the time the position was open to the current time in order to define the location of the price to the MA, but it was no success.

Could anybody please help me out on a way to define the position of the price relative to the MA?

Thank you in advance!

#include <Trade\Trade.mqh>
CTrade trade;
//+-------------------------------------+
void OnInit() {ChartSetInteger(0,CHART_SHOW_GRID,false);}
//+-------------------------------------+
void OnTick() {
        
   double ASK = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK), _Digits);
   if(PositionsTotal() < 1) {
      trade.Buy(0.10,_Symbol,ASK,ASK-400*_Point,ASK+400*_Point);
   }
   if(PositionsTotal() > 0) {
      for(int i=PositionsTotal(); i >= 0; i--) {
         //+-------------------------------------------+
         int MA_Defin = 0;
         double MA_Holder = EMPTY_VALUE;
         MA_Defin = iMA(_Symbol,PERIOD_CURRENT,50,0,MODE_EMA,PRICE_CLOSE);
         double MA_Array[];
         ArraySetAsSeries(MA_Array,true);
         CopyBuffer(MA_Defin,0,0,3,MA_Array);
         MA_Holder = MA_Array[1];
         //+-------------------------------------------+
         ulong position_ticket = PositionGetTicket(i);
         double price_current = PositionGetDouble(POSITION_PRICE_CURRENT);
         long position_time_open = PositionGetInteger(POSITION_TIME);
         bool above_price = false, below_price = false;
         if(position_time_open == TimeCurrent()) {
            if(price_current > MA_Holder)      above_price = true;
            else if(price_current < MA_Holder) below_price = true;
         }
         if(above_price == true) {
            if(price_current < MA_Holder) {
               trade.PositionClose(position_ticket);
               above_price = false;
            }
         }
         if(below_price == true) {
            if(price_current > MA_Holder) {
               trade.PositionClose(position_ticket);
               below_price = false;
            }
         }
         Comment(
                  "Ask price: ",ASK,"\n"
                  "Current Price: ",price_current,"\n"
                  "MA Price: ",MA_Holder,"\n"
                  "time current",TimeCurrent(),"\n"
                  "above price: ",above_price,"\n"
                  "below price: ",below_price
                );   
      }
   }
}



 

If you want to find the location of MA you have to find first the moment when trade was opened: so get the open time of the trade you analyzing. Then use iBarShift to get the index of the bar on which trade was opened and then calculate the MA for this bar. Then you can compare if price on this found bar was below or above MA. But remember that you will get values of price and MA at the close of this bar – so it might be a bit different that the values at the very moment of opening the trade. You can always add +1 to the index to find the values on the last closed bar before opening – so you will check if MA was above or below before opening this trade. It depends on what is the strategy really for opening those trades. 

Besides that – it’s better to create handles for indicators on the INit function – so you won’t create them multiple times during every tick – it’s not optimal method. 
 
  1.       trade.Buy(0.10,_Symbol,ASK,ASK-400*_Point,ASK+400*_Point);
    

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close to a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  2.          MA_Defin = iMA(_Symbol,PERIOD_CURRENT,50,0,MODE_EMA,PRICE_CLOSE);
             double MA_Array[];
             ArraySetAsSeries(MA_Array,true);
             CopyBuffer(MA_Defin,0,0,3,MA_Array);
    

    Perhaps you should read the manual, especially the examples.
       How To Ask Questions The Smart Way. (2004)
          How To Interpret Answers.
             RTFM and STFW: How To Tell You've Seriously Screwed Up.

    They all (including iCustom) return a handle (an int). You get that in OnInit. In OnTick/OnCalculate (after the indicator has updated its buffers), you use the handle, shift and count to get the data.
              Technical Indicators - Reference on algorithmic/automated trading language for MetaTrader 5
              Timeseries and Indicators Access / CopyBuffer - Reference on algorithmic/automated trading language for MetaTrader 5
              How to start with MQL5 - General - MQL5 programming forum - Page 3 #22 (2020)
              How to start with MQL5 - MetaTrader 5 - General - MQL5 programming forum - Page 7 #61 (2020)
              MQL5 for Newbies: Guide to Using Technical Indicators in Expert Advisors - MQL5 Articles (2010)
              How to call indicators in MQL5 - MQL5 Articles (2010)

  3. Andrey Spassov: I am not able to properly define whether the price is above the MA or below the MA at the time that the position is open. 

    When you open, read the MA, save the MA and the Ask in a global or static variable for later use.