Discussion of article "Library for easy and quick development of MetaTrader programs (part XXXIV): Pending trading requests - removing and modifying orders and positions under certain conditions"

 

New article Library for easy and quick development of MetaTrader programs (part XXXIV): Pending trading requests - removing and modifying orders and positions under certain conditions has been published:

In this article, we will complete the description of the pending request trading concept and create the functionality for removing pending orders, as well as modifying orders and positions under certain conditions. Thus, we are going to have the entire functionality enabling us to develop simple custom strategies, or rather EA behavior logic activated upon user-defined conditions.

Compile the EA and launch it in the tester in the visualization mode. To check order removal as well as order and position modification, open two sell positions and place a sell pending order without StopLoss and TakeProfit levels. Next, create pending requests to modify stop levels of orders and positions by price value. Wait for activation of pending requests and placing specified stop levels, and remove orders and positions.

Then open two buy positions and place a buy pending order. After that, create pending requests to remove orders and close positions by time.


As we can see, stop levels were set at the intersection of a given pending request activation price level. The positions were closed after a specified time and the order was removed.

Author: Artyom Trishkin

 

Good afternoon!

Thanks for the series of articles and thanks for the code adapted for MQL4!

Regarding practical examples.

The task is to,

  1. When certain market conditions occur, open several positions in the same direction with the same closing levels for losses and different levels for profits.
  2. When similar conditions occur below/above, open several more positions in the same direction, again with the same closing levels of loss and different levels of profit + change the loss level of open positions to zero.
  3. the aggregate size of the first set of positions should be determined taking into account a 2% loss from the balance sheet
  4. the cumulative size of the second set of positions should be determined taking into account a 2% loss on funds
  5. work with pending orders is not expected.

My MQL4 Expert Advisor has already implemented an algorithm for finding entry points, but there are no trading operations yet.

Attention, question ))

Which of the libraries, classes, methods of the first series would help me to speed up the development?


Рынок - новости, аналитика, прогнозы по рынкам - Блоги трейдеров и аналитика финансовых рынков
Рынок - новости, аналитика, прогнозы по рынкам - Блоги трейдеров и аналитика финансовых рынков
  • www.mql5.com
Рынок — это место, где обычно происходит обмен товара на деньги или товара на товар. Если доступ на рынок свободный, то производители и потребители проводят обмен в условиях конкуренции. Существует
 
Nikolai Karetnikov:

Good afternoon!

Thanks for the series of articles and thanks for the code adapted for MQL4!

Regarding practical examples.

There is a task,

  1. when certain market conditions occur, open several positions in the same direction with the same closing levels for loss and different levels for profit.
  2. When similar conditions occur below/above, open several more positions in the same direction, again with the same closing levels of loss and different levels of profit + change the loss level of open positions to zero.
  3. the aggregate size of the first set of positions should be determined taking into account a 2% loss from the balance sheet
  4. the cumulative size of the second set of positions should be determined taking into account a 2% loss on funds
  5. work with pending orders is not assumed

My MQL4 Expert Advisor has already implemented an algorithm for finding entry points, but there are no trading operations yet.

Attention, question ))

Which of the libraries, classes, methods of the first series would help me to speed up the development?


Not a complete description.

1. We open positions by immediately setting the first group identifier in the magic number to be the same for them. Now the whole first group can be searched by identifier 1.

2. Open positions, immediately setting them to the second group identifier in the magic number that is the same for them. Now the whole second group can be searched by identifier 2.
2.1 After opening the second group of positions, select all positions of group 1 in the list and modify their Stop Loss levels to the calculated Breakeven level for them. The level should be calculated independently. The list of positions of the first group is available - its cumulative profit/loss is easily calculated.

3. is this item the cumulative volume? If yes, then calculate it before opening the first group of positions.

4. Is this item the total volume? If yes, then calculate it before opening the second group of positions. But the funds will depend on the margin occupied for the first group and its profit/loss - floating profit/loss on free funds.

5. Pending requests are convenient to use just for setting all the necessary conditions for opening groups. Plan in advance, and set the expectation. I do not insist - it is a means of planning trading tactics and techniques.

The answer - all this is in the first part to realise what is intended. I don't understand the question - there is no attempt to try something. Accordingly - I can only use words.

 

Artem, good afternoon

Unreal work in terms of capacity, thank you very much

I have one remark: in most cases my MT4 test terminals are connected to a real trading account in investor mode.

The idea is to maximise the trading account conditions in the tester (swaps, commissions, stop levels - anything that is not swapped in the TDS)

However, the library detects that trading in the account is prohibited and refuses to trade. In the tester.

Maybe it makes sense to explicitly relax some of the restrictions for working in the tester?

Apparently, here:

//--- Check trading permission for this account (if there is a connection with the trade server)
   else if(!this.m_account.TradeAllowed() && !::MQLInfoInteger(MQL_TESTER))
     {
      //--- Write the error code to the list and return false - no point in checking further
      this.m_error_reason_flags=TRADE_REQUEST_ERR_FLAG_ERROR_IN_LIST;
      this.AddErrorCodeToList(MSG_LIB_TEXT_ACCOUNT_NOT_TRADE_ENABLED);
      return false;
     }

I have mine added, but this might not be the only check that makes sense to ignore in the tester?

Документация по MQL5: Константы, перечисления и структуры / Состояние окружения / Информация о счете
Документация по MQL5: Константы, перечисления и структуры / Состояние окружения / Информация о счете
  • www.mql5.com
, то позиции по каждому символу разрешается закрывать только в том порядке, в котором они были открыты — сначала самую старую, затем более новую и т.д. При попытке закрыть позиции в ином порядке будет получена ошибка. Уровень залоговых средств, при достижении которого происходит принудительное закрытие самой убыточной позиции (Stop Out). В...
 
Igor Ryabchikov:

Artem, good afternoon

Unreal work in terms of capacity, thank you very much

I have one remark: in most cases my MT4 test terminals are connected to a real trading account in investor mode.

The idea is to maximise the use of trading account conditions in the tester (swaps, commissions, stop levels - anything that is not swapped in the RTD)

However, the library detects that trading in the account is prohibited and refuses to trade. In the tester.

Maybe it makes sense to explicitly relax some of the restrictions for working in the tester?

Apparently, here:

I have mine added, but this might not be the only check that makes sense to ignore in the tester?

Thanks, I'll fix it.

 

Hello @Artyom Trishkin, thank you for this code.

I tried to run modified version in MT4 with no testing buttons to listen to Account/Trade events. but I see wrong result when I opened and closed 3 trades:

01:17:13.849 removed

01:17:13.733 uninit reason 4

01:15:36.860 OnDoEasyEvent: Position closed

01:15:36.860 - Position closed: 2020.08.20 23:45:29.000 -EURUSD Closed Sell #573015195 at price 1.18610, Profit -0.13 USD

01:15:35.489 CEventsCollection::CreateNewEvent, Line 768: This event already in the list

01:15:35.019 OnDoEasyEvent: Position closed

01:15:35.019 - Position closed: 2020.08.20 23:45:27.000 -EURUSD Closed Buy #573015193 at price 1.18623, Profit -0.13 USD

01:15:30.144 OnDoEasyEvent: Position opened

01:15:30.144 - Position opened: 2020.08.20 23:45:29.000 -EURUSD Opened 0.01 Sell #573015195 [0.01 Market-order Sell #573015195] at price 1.18610

01:15:28.724 OnDoEasyEvent: Position opened

01:15:28.724 - Position opened: 2020.08.20 23:45:28.000 -EURUSD Opened 0.01 Buy #573015194 [0.01 Market-order Buy #573015194] at price 1.18623

01:15:28.263 OnDoEasyEvent: Position opened

01:15:28.257 - Position opened: 2020.08.20 23:45:27.000 -EURUSD Opened 0.01 Buy #573015193 [0.01 Market-order Buy #573015193] at price 1.18623

01:14:49.639 initialized

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 Account ****: **** (****) **** USD, 1:100, Hedge, Demo account MetaTrader 4

01:14:20.357 loaded successfully


What is probably wrong in my testing code?

 
Mohammad Bazrkar :

Hello @Artyom Trishkin , thank you for this code.

I tried to run modified version in MT4 with no testing buttons to listen to Account/Trade events. but I see wrong result when I opened and closed 3 trades:

01:17:13.849 removed

01:17:13.733 uninit reason 4

01:15:36.860 OnDoEasyEvent: Position closed

01:15:36.860 - Position closed: 2020.08.20 23:45:29.000 -EURUSD Closed Sell #573015195 at price 1.18610, Profit -0.13 USD

01:15:35.489 CEventsCollection::CreateNewEvent, Line 768: This event already in the list

01:15:35.019 OnDoEasyEvent: Position closed

01:15:35.019 - Position closed: 2020.08.20 23:45:27.000 -EURUSD Closed Buy #573015193 at price 1.18623, Profit -0.13 USD

01:15:30.144 OnDoEasyEvent: Position opened

01:15:30.144 - Position opened: 2020.08.20 23:45:29.000 -EURUSD Opened 0.01 Sell #573015195 [0.01 Market-order Sell #573015195] at price 1.18610

01:15:28.724 OnDoEasyEvent: Position opened

01:15:28.724 - Position opened: 2020.08.20 23:45:28.000 -EURUSD Opened 0.01 Buy #573015194 [0.01 Market-order Buy #573015194] at price 1.18623

01:15:28.263 OnDoEasyEvent: Position opened

01:15:28.257 - Position opened: 2020.08.20 23:45:27.000 -EURUSD Opened 0.01 Buy #573015193 [0.01 Market-order Buy #573015193] at price 1.18623

01:14:49.639 initialized

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 Account ****: **** (****) **** USD, 1:100, Hedge, Demo account MetaTrader 4

01:14:20.357 loaded successfully


What is probably wrong in my testing code?

I don't know what you changed there ...

 

I cut some codes related to buttons, but it is possible to removed some necessary codes. I attach it now.

But, do you agree that error for not capturing SECOND Closing Buy position should not relate to my changes ?

Files:
mhdbzr-34.mq4  46 kb
 
Mohammad Bazrkar :

I cut some codes related to buttons, but it is possible to removed some necessary codes. I attach it now.

But, do you agree that error for not capturing SECOND Closing Buy position should not relate to my changes ?

Does the test advisor work without errors?

 
Artyom Trishkin:

Does the test advisor work without errors?

I run the modified EA to watch my events, then manually place some trades and close them as fast as possible.
I don't use testing EA to open/close position.


those `CAccount` errors appear in default TestDoEasyPart34.ex4

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

 
Mohammad Bazrkar:
I run the modified EA to watch my events, then manually place some trades and close them as fast as possible.
I don't use testing EA to open/close position.


those `CAccount` errors appear in default TestDoEasyPart34.ex4

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

01:14:22.120 CAccount::Load: Could not create object structure from uchar array

Yes, they will. Because there the approach to storing your account data has been changed. This is written at the end of the article as a warning:
-----
For your information:
since we changed the structure of the account object (changed the size of the uchar arrays to store the string properties of the account and added one more integer property), all previously saved files of the account objects will no longer be loaded correctly. If they are in the common folder of terminals in the \Files\DoEasy\Accounts\ directory, then they must all be deleted before starting this test advisor - they will be recreated when switching from one account to another with a new size of the object structure.
-----