Warm tip: This article is reproduced from serverfault.com, please click

Variables keep resetting to initial declared values

发布于 2021-03-04 19:52:29

wondering whether someone may be able to point out what I'm doing wrong here.

Just for background I am very new to MQL4 (or coding at all)

I wrote the following code to act as a virtual trailing stop loss.

I am trying to lock in HH (Hihest High) and LL (Lowest Low) based on the below loop. However when I print, it looks like both HH and LL are resetting to both Bid and Ask on every tick, and not "locking".

I had three questions:

  1. What am I doing wrong?!
  2. Does HH and LL just reset to zero continuously because of where the variables have been declared?
  3. Will HH and LL be unique for every order? If not, is there a way of setting that?

(The ~are just placeholders for now - can be ignored, I will correct that)

Thanks a lot!

double      HH = 0;
double      LL = 0;
int orderstotal = OrdersTotal();
int orders = 0;
int ordticket[90][2];
for (int i = 0; i < orderstotal; i++)
{
     if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
     if (OrderSymbol() != Symbol() || OrderMagicNumber() != ~OrderId~)
     {
         continue;
     }
     ordticket[orders][0] = OrderOpenTime();
     ordticket[orders][1] = OrderTicket();
     orders++;
}
if (orders > 1)
{
    ArrayResize(ordticket,orders);
    ArraySort(ordticket);
}
for (i = 0; i < orders; i++)
{
    if (OrderSelect(ordticket[i][1], SELECT_BY_TICKET) == true)
    {
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == ~OrderId~)
        {
            if (Ask > HH)
            {
                HH = Ask;
                Print("Print(HH)=",HH);
            }
            if (Bid < LL)
            {
                LL = Bid;
                Print("Print(LL)=",LL);
            }
            if ((OrderType() == OP_BUY && HH - OrderOpenPrice() > ~TrailingStartGap~*PipValue*Point) ||
                (OrderType() == OP_SELL && OrderOpenPrice() - LL > ~TrailingStartGap~*PipValue*Point))
            {
                if ((OrderType() == OP_BUY && HH - Ask > ~TrailingStop~*PipValue*Point) ||
                    (OrderType() == OP_SELL && Bid - LL > ~TrailingStop~*PipValue*Point))
                {
                   bool ret = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), ~Slippage~, ~Color~);

                   if (ret == true)
                   {
                        int error = GetLastError();
                        if (ret == false && error > 0)
                        Print("OrderClose() error - ", ErrorDescription(error));
                   }
                }
            }
        }
    }
}

Questioner
Intelis
Viewed
0
tomgny 2021-03-18 21:10:38

Declare the HH and LL as a global variables, outside OnTick() function to avoid reinitialization them on every tick.