Clearing in the tester - page 5

 
JRandomTrader #:

But! When working on FORTS you should not rely on position data.

My robots keep track of their trades and remember the initial position opening price (not after the last clearing), and use it to calculate profits, SL, ...

By the way, another reason not to rely on position data: FORTS is netting, and several robots can trade on the same symbol plus manual trading. And what is practically useful from this combined position?

So each robot remembers and "leads" its position.

 
JRandomTrader #:

I showed you. Take this last average price and volume of the position, the price of the new trade and its volume. Everything will be calculated correctly.

Yeah, yeah, I got it now... after asking myself - got it :-)
 
JRandomTrader #:

By the way, another reason not to rely on position data: FORTS is netting, and several robots plus manual trading can trade on the same symbol. And what is practically useful from this combined position?

So each robot remembers and "leads" its position.

spc. There are naturally all these market trades and positions there - SONARELY? (IN THE SAME DIRECTION)?
 
Roman Shiredchenko #:
spc. There naturally all these market trades and positions are SONARELY? (IN ONE DIRECTION)?

Robots can have different strategies, trending and counter-trending, and they can work on different timeframes, so the poses can be in either direction. And in MT you can only see the "total".

 
JRandomTrader #:

Robots can have different strategies, trending and counter-trending, and they can work on different timeframes, so the poses can be in either direction. And in MT you can only see the "total".

i.e. you can essentially just keep a dedicated trading record for each direction and that's it... :-)

This is tough of course... all virtual - all the pluses and minuses. There's only one position in common... Netting.

It's certainly a mockery - if you do it all on one instrument...

 
Roman Shiredchenko #:

i.e. you can essentially just keep a dedicated trade record for each line of business and that's it... :-)

It's tough of course... everything is virtual - all the pros and cons. There's only one position in common... Netting.

Of course, it's a mockery - if you do it all on one instrument...

But there aren't many options here. Either one "ideal" robot on the symbol, or diversification - several real ones.

 
JRandomTrader #:

And there aren't many options here. Either one "perfect" robot on the symbol, or diversification - several real ones.

If we can make a general point: apart from the transfer of opening prices at the aggregate position after clearing, what other "hidden" pitfalls are there to pay attention to when trading?

There are essentially commissions, swaps - I think you can see them. And the history of deals and positions can be counted... (it is so that according to the trading algorithm actual position or its parts - were ONLY in the plus!)

What else do you think we should pay attention to when trading?

 
Roman Shiredchenko #:

Can I make a general point: apart from the transfer of opening prices for aggregate positions after clearing, what other "hidden" pitfalls are there to look out for when trading?

There are essentially commissions, swaps - I think you can see them. And the history of deals and positions can be counted... (it is so that according to the trading algorithm actual position or its parts - were ONLY in the plus!)

What else do you think we should pay attention to when trading?

That commission, which is visible in the transaction - is only the commission of the exchange. The broker's commission is not visible in the transaction. At least, it is so for the broker who opens it.

I look deals by OnTrade (or OnTradeTransaction), immediately calculate and write them in State and in log.

I want to add just in case: you should keep in mind that one order may cause several deals with partial volume.

 
JRandomTrader #:

The commission that is visible in the transaction is only the exchange's commission. The broker's commission is not visible in the transaction. At least, it is so with the opener.

I look deals by OnTrade (or OnTradeTransaction), immediately calculate and write them in the state and in the log.

I want to add just in case: you should keep in mind that one order may cause several deals with partial volume.

Thank you!!!
 

There is also an organisational issue, if anyone knows how to solve it in the best way - please write it in words, I will put it in the code:

in general, how to understand that the order cycle, a new position - PROFIT has started - to take into account the average opening price of the position (clearing changes its value):

to be clear, I can both from the terminal via the keys myself and by a robot with magik....

In general, I need a report point - to calculate the average entry price of the position.

Can I use data from here + for example read time when previous position closed in profit and take a difference with the real server time from there, like if I start a cycle from the terminal - without a robot:

I mean something like this:

// --- определение границ требуемой торговой истории
   datetime end=TimeCurrent();                 // текущее серверное время
   datetime start=end-PeriodSeconds(PERIOD_D1);// установим начало на сутки назад
like the past position is in the plus - then the current cycle accounting has already started. and orders - you must already count both the entry price and the volume to calculate the average entry price of the aggregate position...

https://www.mql5.com/ru/articles/211


Получение информации по ордерам из истории

Работа с историческими ордерами почти ничем не отличается от работы с действующими ордерами за одним только исключением. Если количество действующих ордеров в кэше mql5-программе не может быть больше одного, то результат HistoryOrdersTotal() и количество  исторических ордеров в кэше зависит от того, какой объем торговой истории был загружен функцией HistorySelect(start, end), HistorySelectByPosition() или HistoryOrderSelect().
Важно: если торговая история не была загружена в кэш mql5-программы одной из функций  HistorySelect(), HistorySelectByPosition() или HistoryOrderSelect(), то работать с историческими ордерами и сделками невозможно. Обязательно запрашивайте требуемую историю сделок и ордеров перед получением данных по торговой истории.

Для примера приведен скрипт, который ищет последний ордер за последний день и выводит по нему информацию. 

// --- определение границ требуемой торговой истории
   datetime end=TimeCurrent();                 // текущее серверное время
   datetime start=end-PeriodSeconds(PERIOD_D1);// установим начало на сутки назад
//--- запросим в кэш программы торговую историю за день
   HistorySelect(start,end);
//--- получим количество ордеров в истории
   int history_orders=HistoryOrdersTotal();
//--- получим тикет ордера из истории, имеющего последний индекс в списке
   ulong order_ticket=HistoryOrderGetTicket(history_orders-1);
   if(order_ticket>0) // получили в кэш исторический ордер, работаем с ним
     {
      //--- статус ордера
      ENUM_ORDER_STATE state=(ENUM_ORDER_STATE)HistoryOrderGetInteger(order_ticket,ORDER_STATE);
      long order_magic      =HistoryOrderGetInteger(order_ticket,ORDER_MAGIC);
      long pos_ID           =HistoryOrderGetInteger(order_ticket,ORDER_POSITION_ID);
      PrintFormat("Ордер #%d: ORDER_MAGIC=#%d, ORDER_STATE=%d, ORDER_POSITION_ID=%d",
                  order_ticket,order_magic,EnumToString(state),pos_ID);

     }
   else              // неудачная попытка получения ордера

     {
      PrintFormat("Всего в истории %d ордеров, не удалось выбрать ордер"+
                  " с индексом %d. Ошибка %d",history_orders,history_orders-1,GetLastError());
     }

--------------------------------------------------------------

Of course, ideally it should be closed regardless of the outcome of the previous cycle - profit or loss.

The start - the new one was marked for calculation in the code - the average price of the new current cycle of averages, for example, or fills - it doesn't matter...

Ордерa, позиции и сделки в MetaTrader 5
Ордерa, позиции и сделки в MetaTrader 5
  • www.mql5.com
Надежный торговый робот не может быть создан без понимания механизмов работы торговой системы MetaTrader 5. Клиентский терминал получает от торгового сервера информацию о позициях, ордерах и сделках. Чтобы правильно обработать эти данные средствами MQL5 необходимо хорошо представлять как происходит взаимодействие mql5-программы и среды исполнения терминала.