How to get the "Percentage of Margin" programmatically - page 8

 
Alexey Viktorov:

What a pain in the ass... Check how you are counting.

GOLD at metaquotes (margin percentage - 1, leverage -300), CFD

2017.06.05 21:57:42.015 Script gold_test_vik2 GOLD,H4: removed
2017.06.05 21:57:42.000 gold_test_vik2 GOLD,H4: uninit reason 0
2017.06.05 21:57:42.000 gold_test_vik2 GOLD,H4: ******** AccountMargin = 19188.75 USD
2017.06.05 21:57:42.000 gold_test_vik2 GOLD,H4: ******** Процент маржи 300 Маржа ордера GOLD 0.05 = 19188.75
2017.06.05 21:57:42.000 gold_test_vik2 GOLD,H4: initialized

On crosses and locked positions the calculations are also wrong, but personally I don't care, and I see that your script just doesn't handle it... I don't think it's worth the effort, if all the difficulties so far are in any case related to calculation of margin percentage and collateral for at least one CFD order.

p.s. I also start to think that it's no coincidence that the developers didn't give direct access to margin percentage :D

 

Can you share your experience how to open a demo on MetaQuote-Demo with a leverage of 300? I have a maximum of 100...


GOLD on MetaQuote-Demo

2017.06.06 09:07:32.780 Data Folder: D:\MetaTrader 4\Programming
2017.06.06 09:07:32.780 Windows 7 Home Premium (x64 based PC), IE 11.00, UAC, 4 x AMD FX-4170 Quad-Core Processor , RAM: 10402 / 12255 Mb, HDD: 31535 / 244198 Mb, GMT+03:00
2017.06.06 09:07:32.780 MetaTrader 4 build 1090 started (MetaQuotes Software Corp.)

Printout

2017.06.06 09:09:25.812 test GOLD,H1: ******** AccountMargin = 160.95 USD
2017.06.06 09:09:25.812 test GOLD,H1: ******** Процент маржи 1 Маржа ордера GOLD 0.05 = 160.9525

Screenshots



 
Alexey Viktorov:

Can you share your experience how to open a demo on MetaQuote-Demo with a leverage of 300? I have a maximum of 100...


oops... Got confused in terminals with these tests. This one was insta, otherwise correct, GOLD, margin percentage - 1, leverage 300, screenshots above...

sorry!

 
ir0407:
The margin percentage is not a calculated deposit. It is just one of the components for calculating the margin. The result of this calculation (according to formulas in the table) returns in the margin currency, which must then (if it is different from the deposit currency) be converted into the deposit currency.

And that's something I can't quite put my finger on either. For example, we take a formula:

Lots*Contract_Size/Leverage

Where, Lots - this is the lot in the base currency of the instrument and the contract - also in the base currency, and then, if necessary, multiply the base currency to the quoted currency by the exchange rate. And with all this the result is obtained in the margin currency. How so?

 
K-2SO:

And that's something I can't quite put my finger on either. For example, we take a formula:

Where, Lots - this is the lot in the base currency of the instrument and the contract - also in the base currency, and then, if necessary, multiply the base currency to the quoted currency by the exchange rate. And with all this the result is obtained in the margin currency. How come?

This formula

Lots*Contract_Size/Leverage

is valid for the calculation of the margin for USD*** currencies


First, we determine which price we need to translate into the currency of the deposit.

If the instrument name starts with the deposit currency, in this case USD, then the price is not taken into consideration

If the order is OP_BUY, we need the Bid price

If the order is OP_SELL then Ask

double price = stringFind == 0 ? 1 : type%2 == OP_BUY ? bid : ask;
percentage = NormalizeDouble(
                             margin          // Маржа получена в валюте депозита с учётом плеча
                           /(contractSize    // Размер контракта в базовой валюте
                            *price           // Умножаем на текущую цену и получаем в валюте депозита
                            /100)            // Это для того чтобы коэффициент перевести в проценты
                           *(calcMode == 0 ? leverage : 1) // Это получено методом научно-технического тыка.
                                    // Если способ расчёта 0 - Forex; то надо учесть плечо
                                    //                     1 - CFD; то плечо не учитывается
                                    //                     2 - Futures; 3 - CFD на индексы НЕ проверялись, их у меня нету...
                           , 0);
orderMargin = (orderLots         // правильно, в базовой валюте
              *contractSize      // и это тоже в базовой
              *orderOpenPrice    // а вот тут переводим в валюту депозита
              *percentage/100)   // у меня слов не хватает чтобы объяснить что это такое, но видимо очень нужное.
             /(calcMode == 0 ? leverage : 1);  // Это тоже получено методом научно-технического тыка.

I hope I have explained things clearly...

 
Alexey Viktorov:

I hope I've made myself clear...

Um... I think we're talking about different things again. I just decided to try to clarify not the method of margin calculation (not the calculations), but how it turns out that at the output of margin calculation formula, where we practically do not work with margin currency, we get the result exactly in the margin currency. At least that's how I understood it fromir0407 message. And that's why I gave the simplest calculation formula, where there is no quotes accounting yet...

For the rest (the gut feeling method), I also tried it all, but noted that a single solution has not yet been found. I mixed up the brokers, but the results-no, i.e. on insta your last option with the above parameters, still produces cosmic numbers as well: https://www.mql5.com/ru/forum/193833/page8#comment_5243991

p.s. But thanks for the comments! Anyway I understand the way of thinking, the calculations described by you)

 
K-2SO:

Erm... I think we're talking about different things again. I just decided to try to clarify not the method of margin calculation (not the calculations), but how it is that the output of margin calculation formula, where we practically do not work with margin currency, we get the result in the currency of margin. At least that's how I understood it fromir0407 message. And that's why I gave the simplest calculation formula, where there is no quotes accounting yet...

For the rest (the gut feeling method), I also tried it all, but noted that a single solution has not yet been found. I mixed up the brokers, but the results-no, i.e. on insta your last option with the above parameters, still produces cosmic numbers as well: https://www.mql5.com/ru/forum/193833/page8#comment_5243991

p.s. But thanks for the comments! Anyway, I understand the way of thinking, the calculations you described)

I do not even want to open a demo on insta. If it is not difficult, in the debugger can show what intermediate values are obtained. As on my screenshot


 
Alexey Viktorov:

I don't even want to open a demo on insta. If you don't mind, in the debugger you can show what intermediate values you get. Like on my screenshot



Again, my bad luck! Apparently when parsing your code, I must have changed something in it (I forgot to return it) and that's why it threw up such an error. Now (just in case) re-copied the original - correctly and on insta counts. I'll test it with other brokers then.
 

Hats off to you, you almost got it right! At all three brokers previously reviewed with different margin percentages, the calculation for gold (for orders in one direction) is correct.

But the script still fails with exotics. I have stopped at fxcm broker. The percentage margin for gold is 70000, for conventional currency pairs is 130, the currency of margin seems to be USD. And nothing is counting correctly anywhere! (. I myself have been looking for the key to it for two days, and in fact as a result of this I am now looking for an answer to the question, how come that as a result of calculations of base currencies and their rates with quotes currencies, we get a margin currency... Maybe it's this, or maybe it's the fact that this broker takes into account the percentage of margin even for normal currency pairs.

Here you can download the terminal ru.files.fm/u/xfezz883#_ , unzip it, run it using the exe file, make a demo...

 
K-2SO:

Hats off to you, you almost got it right! At all three brokers previously reviewed with different margin percentages, the calculation for gold (for orders in one direction) is correct.

But the script still fails with exotics. I have stopped at fxcm broker. The percentage margin for gold is 70000, for conventional currency pairs is 130, the currency of margin seems to be USD. And nothing is counting correctly anywhere! (. I myself have been looking for the key to it for two days, and in fact as a result of this I am now looking for an answer to the question, how come that as a result of calculations of base currencies and their rates with quotes currencies, we get margin currency... Maybe it's this, or maybe it's the fact that this broker takes into account the percentage of margin even for normal currency pairs.

You can download terminal here ru.files.fm/u/xfezz883#_ , unzip it, run it using the exe file, start the demo...

It is not a problem to calculate the crosses. You just need to take a quote, that translates from margin currency to deposit currency.

For example EURJPY price

double price = stringFind == 0 ? 1 : type%2 == OP_BUY ? bid : ask;

If your deposit is in USD, you should use EURUSD. If you calculate CADJPY, you should use USDCAD. Here we should see how to add the deposit currency to the margin currency, we shouldn't just enter it in the list.

The counter ones are not so difficult having MarketInfo(symbol, MODE_MARGINHEDGED). The only problem is to find counter currency first, and then to decompose part of it by counter currency, and the rest by full...

In general, I see the only benefit of this article is that the trader knows in advance what margin will be taken when the pending order is activated and can delete the pending order if it is not enough in time to avoid errors. I once struggled with this when placing an EA in the market.