An example for calculating the lot value with a fixed margin level. That is, if you specify 10%, a position with the margin equal to 10% of free margin will be opened.
The following loop is implemented to simulate trading:
Initial value count=-21 is set to "warm up" the strategy tester. Then the remainder after devision of count by 980 (this number was chosen randomly) is calculated. It means that every 980 ticks lot calculation cycle is started, in which lot is calculated taking into account the risks per trade.
The lot calculation cycle depending on risk per trade (calculation for the Buy position):
The following parameters are printed to the Experts journal: StopLoss, calculated lot value in accordance with the risk per trade, trade account balance at the time of calculation, margin at the moment of calculation.
If the calculation returns "0.0", exit:
Then we receive the lot value of the Buy position for which we have sufficient funds; the value is received to the chek_volime_lot variable using the CheckVolume method of the CTrade class. The following parameters are passed here: m_symbol.Name() — symbol name, check_open_long_lot — position volume we want to open (this parameter was calculated earlier):
If the CheckVolume method returns a value other than "0.0", then we check the condition: do we have enough money to open a position with the lot calculated in accordance with the risk.
If we have enough money, open the position, if not — the lot value calculated in accordance with the risk per trade (DoubleToString(check_open_long_lot,2)) and the lot value for wich we have enough funds (DoubleToString(chek_volime_lot,2)) are printed to the Experts journal.
AN example of opening a Buy position with 10% of free margin:
The following was printed to journal:
Note that when calculating the lot depending on the risk of free margin, StopLoss does not matter.
Translated from Russian by MetaQuotes Software Corp.
Original code: https://www.mql5.com/ru/code/17282
The Expert Advisor places two pending orders at a certain time.Lucky
A tick Expert Advisor. It compares the price on the previous tick and the current price.