Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 1144

 
Маргарита Королёва:

So... A catch is a catch... I'm feeling all torn up again :(


...and the more you dig MT5, the more they'll get messed up)
start with MT4
 
Маргарита Королёва:

My broker's official response (extract):

"Our regulatory documents stipulate that we provide only the MT4 trading terminal for trading with hedge accounting and multi-directional trades."

Tell me please, why do you need hedging? The netting system is easy to trade with, especially for scalping. There is a market for that as well. If price goes up, I buy 0.01 lot. I also increase the lot up to 0.02. When the price goes down I sell 0.02. Purchase is automatically closed, remaining 0.01 lot to be sold. In one movement the transaction is reversed. There is no need to close the position. And so on. It is quick and convenient. At any moment there is one total position, which is convenient to manage. Open as many orders as you want, and the position is the averaged one. While traders will experience problems with closing a great deal of oppositely directed positions. For trading, MT5 is more suitable, while for the initial study of the language MQL4 is more suitable. This is what the wolf from Rostov with years of experience in trading and programming is telling you.

Let's simulate hedging in our city bazaar.

You can sell potatoes to a trader for 50 (BID) and buy from her for 100 (ASK). We come and buy a bucket of potatoes for 100 rubles. And we agree that we will return it in an hour at the market price (for 50). After all, in forex, an open position must be closed sooner or later with a reverse transaction. We assume that they will come for potatoes from the canteen. And the price will increase threefold. Then they sell for 150 and an extra 50 stays in the pocket. But then the collective farmers arrive with a truckload of potatoes and the price goes down (40 and 80) - the trend has changed. Smart would be to sell our bucket for 40 (to sell the deposit) and forget about Forex. But we will hedge. We sell our potato to another trader for 40 and agree that in half an hour we will buy the potato at market price (apparently for 80) to return the first trader. Is there a mistake in the description of the hedge somewhere? Then correct it, or give another example to prove hedging.

 
I will remember my first paycheck for the rest of my life. I lived in a hostel and was free as a bird.
I still avoid alcohol, and even then I was averse to it. I decided to give myself something to eat with my paycheck, so I went to the market.
I met a guy, nicknamed 'Indicator', from our backyard. We say hello, and he tells me:
- Take a tool from me. I'll give it to you for 100. And in two weeks, spring will finally arrive, the men will come out of the garages,
you'll give them the tool for 130. You'll have it for beer.
I liked the indicator's reasoning. I took one tool from him for 100.
Next week, I went to the market again to check my profit.
Where the last time was the Indicator, now there was a man called the Mediator. He says:
- "We beat up the Indicator. He's been knocking the price down. Take another tool, I'll give it to you for 80.
You got 180 for the two, that's 90 for each. You'll get a tenner right back.
You move the take profit from 130 to 120, you'll sell faster, too. That'll buy you two beers.
I liked the Oddsmaker's reasoning, too. Took the second tool from him for 80.
Next week, I run to the market to find out about the profit. Orediator says:
- Take two more tools, I'll give them to you for 70. It turns out you gave 320 for four, i.e. 80 for each.
You move take-profit from 120 to 110 - you'll sell faster too. You'll have enough for four beers.
I thought - it turns out, as if I get twenty right back, and the profit will be faster. Took the tools.
Just as soon as I put them in my pockets, Mihalych comes up and says to the mediator:
- Here's five more, will you take 50 each?
The mediator takes the tools, Mikhalych puts the money in his pocket and walks away. I catch up with him and say:
- Wait, Mikhalych. Some people here are averaging, in order to get higher profits later. And what are you doing?
And I told him everything as it is. He looked at me angrily, even spat at me angrily, and said:
- So it was you who was buying the tools, raising the price? Only you bought 4 grand, and I brought 15. That's the price going down!!!
Where'd you get it? I borrowed it from my garage neighbours. They're not likely to buy them, they're hoping I'll pay them back.
It turns out there's a surplus of tools at the bazaar, so the price is going down. When it gets to 20 or at least 30,
I'll buy them back and give them back to my friends. And the difference is mine. Of course the price will go up to 60.
But it's unlikely to go back to 100.
What happened next? New technology came in, so I kept the tools as a souvenir. I'm fed up with averaging for life.
 
Taras Slobodyanik:...and the more you dig into MT5, the more they will be disheveled) start with MT4

For trading, MT5 with a netting account is better. For mastering programming, MQL4 is better. Then in a week you switch to MQL5. So put both

 

I want to set a pending order so that after the time equal to the TF period the order is cancelled (on the next candle). I am doing so:

ulong time = TimeCurrent () + GetSecCountFromTF (PERIOD_CURRENT);
G_LastTicket = SendOrder (Symbol (),
                          lot,
                          type,
                          ORDER_TIME_SPECIFIED, // ORDER_TIME_GTC,
                          (datetime)time,
                          NormalizeDouble (priceOpen, Digits ()),
                          NormalizeDouble (priceSL,   Digits ()),
                          NormalizeDouble (priceTP,   Digits ()),
                          Magic_P,
                          comment,
                          FillReturn_P);

//——————————————————————————————————————————————————————————————————————————————
// Установить отложенный ордер, усех: номер тикета, неудача: -1,
// функция НЕ делает нормализацию значений цены и уровней стопов
ulong SendOrder (string                  symbol,     //символ
                 double                  volume,     //объем
                 ENUM_ORDER_TYPE         type,       //тип ордера, ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT
                 ENUM_ORDER_TYPE_TIME    typeTime,   //ORDER_TIME_GTC           - Ордер будет находится в очереди до тех пор, пока не будет снят
                                                     //ORDER_TIME_DAY           - Ордер будет действовать только в течение текущего торгового дня
                                                     //ORDER_TIME_SPECIFIED     - Ордер будет действовать до даты истечения
                                                     //ORDER_TIME_SPECIFIED_DAY - Ордер будет действовать до 23:59:59 указанного дня. Если это время не попадает на торговую сессию, истечение наступит в ближайшее торговое время.
                 datetime                expTime,    // дата истечения
                 double                  priceOpen,  // уровень цены установки ордера
                 double                  priceSL      = 0.0,  // уровень цены SL
                 double                  priceTP      = 0.0,  // уровень цены TP
                 long                    magic_number = 0,    // уникальный идентификатор
                 string                  comment      = "",   // комментарий
                 ENUM_ORDER_TYPE_FILLING filling = ORDER_FILLING_RETURN) //ORDER_FILLING_FOK - всё или ничего
                                                                         //ORDER_FILLING_IOC - разрешен неполный объем
                                                                         //ORDER_FILLING_RETURN - частичное до полного заполнения
{
  //--- готовим запрос
  MqlTradeRequest request = { 0 }; //торговый запрос
  MqlTradeResult  result  = { 0 }; //результат торгового запроса

  request.symbol       = symbol;               // инструмент
  request.volume       = volume;               // объем
  request.action       = TRADE_ACTION_PENDING; // установка отложенного ордера
  request.type         = type;                 // тип ордера
  request.type_time    = typeTime;             // тип времени истечения ордера
  request.expiration   = expTime;
  request.price        = priceOpen;            // цена для открытия
  request.sl           = priceSL;              // уровень Stop Loss
  request.tp           = priceTP;              // уровень Take Profit
  request.magic        = magic_number;         // уникальный идентификатор
  request.comment      = comment;              // комментарий
  request.type_filling = filling;              // тип заливки ордера

  //--- отправим торговый приказ
  bool success = OrderSend (request, result);
  if(success)
  {
    return ((int)result.order);
  }

  //--- выведем в лог ответ сервера
  Print ("Failed send pending order, comment from server: " + result.comment + ", Retcode: " + (string)result.retcode);

  return (-1);
}
//——————————————————————————————————————————————————————————————————————————————

//——————————————————————————————————————————————————————————————————————————————
// Возвращает количество секунд в указанном ТФ
int GetSecCountFromTF (ENUM_TIMEFRAMES period)
{
  switch(period)
  {
  case PERIOD_M1:
    return (60);
  case PERIOD_M2:
    return (120);
  case PERIOD_M3:
    return (180);
  case PERIOD_M4:
    return (240);
  case PERIOD_M5:
    return (300);
  case PERIOD_M6:
    return (360);
  case PERIOD_M10:
    return (600);
  case PERIOD_M12:
    return (720);
  case PERIOD_M15:
    return (900);
  case PERIOD_M20:
    return (1200);
  case PERIOD_M30:
    return (1800);
  case PERIOD_H1:
    return (3600);
  case PERIOD_H2:
    return (7200);
  case PERIOD_H3:
    return (10800);
  case PERIOD_H4:
    return (14400);
  case PERIOD_H6:
    return (21600);
  case PERIOD_H8:
    return (28800);
  case PERIOD_H12:
    return (43200);
  case PERIOD_D1:
    return (86400);
  case PERIOD_W1:
    return (604800);
  case PERIOD_MN1:
    return (2592000);
  default:
    return (60);
  }
}
//——————————————————————————————————————————————————————————————————————————————

But the server returns an error:

2017.04.16 09:48:49.732 Core 1 2017.02.10 05:25:00 Failed to send pending order, comment from server: Invalid expiration, Retcode: 10022

What am I doing wrong? I am checking in the tester.

 
Andrey Dik:

I want to set a pending order so that after the time equal to the TF period the order is cancelled (on the next candle). I am doing so:

But the server returns an error:

2017.04.16 09:48:49.732 Core 1 2017.02.10 05:25:00 Failed to send pending order, comment from server: Invalid expiration, Retcode: 10022

What am I doing wrong? I am checking in the tester.

When I was doing the cancellation of orders for the fifth guy, I got the same error. Maybe, the expiration time is not used. I just execute the order by myself after expiry time - if the current time is more or equal to the time of order placement plus PeriodSeconds(NEEDED_PERIOD_WEEK)*number of candlesticks.
 
Andrey Dik:

I want to set a pending order so that after the time equal to the TF period the order is cancelled (on the next candle). I am doing so:

But the server returns an error:

2017.04.16 09:48:49.732 Core 1 2017.02.10 05:25:00 Failed to send pending order, comment from server: Invalid expiration, Retcode: 10022

What am I doing wrong? I am checking in the tester.

The nearest expiry date +10 minutes was in mql4. I don't know how it is now, I should check it in mql5.
 
Artyom Trishkin:
I have also faced such an error when I have been dealing with order cancellation for a fifth order. Maybe, the order expiration time is not used. I just removed the order by myself after expiry time - if the current time is more or equal to the time of order placement plus PeriodSeconds(NEEDED_PERIOD_WEEK)*number of candlesticks.

Thanks for PeriodSeconds (), I forgot about this function.

Alexey Viktorov:
In mql4 the nearest expiry date was +10 minutes. I don't know how it is now, I should check it with mql5.

I don't want to change it with mql5.


I see. I will have to check the order date and delete it myself, I really do not want to do that.

 
Please advise! How to write code with this condition, if before the close of 0 candle left 1 sec then open an order in one direction or the other! I would be sincerely grateful for help.
 

@Andrey Dik

// Возвращает количество секунд в указанном ТФ
PeriodSeconds(_Period);
Reason: