My Autolot Secrets. Dynamic Lot or Autolot.

 My Autolot Secrets. Dynamic Lot or Autolot.

Alert in the indicator. How do you insert Alert and Arrow into your indicator?
Market MQL5. Problem and errors with installing Expert Advisor and solutions
Alert in the indicator. How do you insert Alert and Arrow into your indicator?
Market MQL5. Problem and errors with installing Expert Advisor and solutions

Description

Within the framework of this article, I will try to tell you about my methods for calculating the lot from % (RISK) of Free Margin on different currency pairs and different types of deposits.

And so, let’s start:
 

Basic concepts:

   First, let’s highlight a few concepts used in this calculation:

Free margin  ( AccountFreeMargin() ) – funds that are not used as collateral in open positions. Free margin is calculated according to the formula: free margin = current state of the deposit – required margin in open positions. This indicator is used to determine the number of transactions that can be opened at the current moment.

Ask  is the price at which you buy a certain amount of a financial instrument from the bank. And the bank, accordingly, sells it to you at this price. When trading on the Forex market, you will meet this type of price everywhere: from the trading terminal to stock reports and analytical articles on financial markets. 

   Bid  is the price at which you sell a certain amount of a financial instrument to your bank. And the bank, accordingly, buys it from you at this price. When trading on the Forex market, you will meet this type of price wherever we talk about the international Forex market: from the trading terminal and exchange rates on your broker’s website, to stock reports and analytical articles on international financial markets. 

   Leverage  is the ratio of the amount of collateral to the amount borrowed. During the initial choice of leverage, the size of the leverage is selected, which indicates the amount by which the Client’s deposit will be increased in order to carry out trading operations on the foreign exchange market. The Client can choose the leverage size from 1:1 to 1:500, that is, the Client can only trade with his own funds, or he can request an increase in his deposit up to 500 times in order to enter the market with this amount. Leverage, as the ratio of the amount with which a trader enters the market to the size of his deposit, plays an important role in the trading process, since it is leverage that allows a trader to significantly increase his capital.

   A currency pair  is a designation of two currencies that together form an exchange rate. The currency pair serves as an object for financial transactions. A currency pair is denoted in the form of successive designations of the two currencies that make up this currency pair, which are written either together or through a slash in the following form: base currency / quote currency. The base currency is the first currency that is bought and sold, and the quote currency is used to express the price of the base currency. A currency pair is the basic concept of the foreign exchange market, which is found everywhere, as soon as it comes to this market: from market reports to a trading terminal.

   Lot size  – the volume of the base currency, commodity or the number of shares specified in the contract specification. The lot size depends on the amount of the currency specified in the contract and is a unit of measure in determining the size of the trading contract. A lot has a certain size, which is used to determine the amount of currency used for financial transactions in the Forex market. To carry out a transaction, the Client determines the size of the transaction he makes, which is expressed in the number of lots. The volume of a trade transaction indicates how much currency will make up the transaction. Lot is the size of the contract, which is a fixed amount of currency used in Forex trading.

    The rate of one currency in relation to another is established as a result of the interaction of supply and demand for them at a certain point in time. The process of setting the exchange rate is called currency quotes. Quotes can be direct and reversed. 

 A direct quotation is understood as an expression of the price of a foreign currency in national units. Most exchange rates represent a direct quote of the US dollar against the currencies of various countries. 

For example, USD / RUR – 30.70 – this means that one US dollar is valued or equal to 30.70 Russian rubles; USD/CHF – 1.0850 – in this case, one US dollar is valued at or equivalent to 1.0850 Swiss francs. 

 A reverse quotation is an expression of the value of the national currency in foreign units. The English pound sterling, euro, Australian and New Zealand dollars have historically been reversed. 

For example, the quote EUR / USD – 1.3374 means that 1 euro is worth 1.3374 US dollars, GBP / USD – 1.5970 means that 1 British pound is equal to 1.5970 US dollars, etc.     

There is also such a thing as “to the other exchange rate ” – these are exchange rates in which the dollar is neither the base nor the quote currency, for example, EUR / JPY, GBP / CHF, EUR / GBP, and others.

 Technical side

  1. NormalizeDouble –  Rounds a floating point number to the specified precision.
  2. MODE_LOTSIZE –  Contract size in instrument base currency
  3. MODE_LOTSTEP –  The step of changing the lot size 
  4. AccountCurrency –  Returns the currency name for the current account. 
  5. MathFloor   – The function returns a numeric value representing the largest integer less than or equal to x. 


Essential: In order for all calculations to be correct, activate all symbols in the “Market Watch” panel 

My calculation formula for Account Currency

   My calculation formula looks like this: 

USD deposit 

Deposit USD Direct Quote ()

 Lot= Free Margin*Risk*Leverage/100/Contract Size

Deposit USD Back quote()

 Lot= Free Margin*Risk*Leverage/Ask/100/Contract Size

Deposit USD Cross rate:()

       Option 1, if there is a current price of the base currency + USD (for example, if the settlement pair is AUDCAD, then the current price of the base currency = AUDUSD)

          Lot= Free Margin*Risk*Leverage/( Current Base Currency Price+USD )/100/Contract Size

       Option 2, if there is no current price of the base currency + USD (for example, CADJPY)

          Lot= Free Margin*Risk*Leverage/ 100/Contract Size

EUR Deposit

Deposit EUR Direct Quote

 Lot= Free Margin*Risk*Leverage/100/Contract Size

Deposit  EUR  Cross rate:

       Current price  EUR +  quote currency (for example, if the settlement pair is AUDCAD, then the current price is  quote currency  = EURAUD)   

          Lot= Free margin*Risk*Leverage/( current price  EUR   quote currency )/100/Contract size

UAH deposit and other

Deposit UAH Back quote (for example, USDUAH )

 Lot=  MathFloor ( Free Margin*Risk*Leverage/100/Current Price/Contract Size/Lot Step/20)* Lot Step

Deposit UAH Cross (e.g. EURGBP)

  current price  =MarketInfo(StringSubstr(Symbol(),0,3)+”UAH“+StringSubstr(Symbol(),6),MODE_BID);     

if(pr!=0)Lot2=MathFloor( Free Margin  * Risk  * Leverage  / Current Price  /100/ Contract Size  / Lot Step  )* Lot Step  ; 

else  Lot  =MathFloor( Free Margin *Risk *Leverage  /100/ Contract Size  / Lot Step  )* Lot Step  ; 

The order of these functions was obtained in the course of calculating the parameters on different deposits. If YOU have an opinion about these calculations, please offer your autolot functions when ordering programming.  

External variables Autolot calculation function:

LotsFixed lot for opening a position. 
DynamicLot
(RiskLotTypetype)
A dynamic lot, Autolot, for an open position.
You can turn ON dynamic lot calculation in percent of free margin and other factors.
Calculation of our autolot.

Autolot calculation type:
BALANCE (Risk from Balance) – Autolot is calculated from the current balance. Lot calculation from account balance! If there are open positions on the account, then the next lot will be approximately the same because the balance does not decrease from the number of current open positions!
FREEMARGIN (Risk from FreeMargin) – The standard lot calculation from the current free margin is that the more open positions on the account, the smaller the lot calculated for the next position. Because when opening a position, the free margin decreases, respectively, each new open position has a smaller lot when calculating the autolot

Risk from SL – Calculate the automatic lot, taking into account Stop Loss.
The maximum loss in percentage of the balance when closing a deal at StopLoss.
When calculating the lot, our Expert Advisor will take into account the stop loss (at the moment of opening the deal).
If the deal closes at the stop loss, the loss of this deal will be = % of the balance (at the time of opening the deal).
Important! If your stop loss was changed after the deal was opened, the lot of the deal could not be changed. At closing the deal, the loss can be more or less.
Important! If you use a Trailing Stop, the deal Stoploss changes with each tick. But the lot cannot be changed.

Type of risk calculation for the RiskLot option.
Three modes are available:
RiskLotType = 0, // Risk from FreeMargin
RiskLotType = 1, // Risk from Balance
RiskLotType = 2, // Risk from SL
LotBalancePcnt (RiskLot)Percent for autolot.
The percentage for the dynamic lot (Autolot) function.

If RiskLot  = 0, then the deal LOT(Volume) will be counted according to the parameter Lot.


If RiskLot is not equal to 0, then a deal at the client terminal will be opened with a lot in % from the client’s free margin (Autolot).
RiskRateThe rate of your currency against the dollar (Or your account currency). 

By default, RiskRate = 0, which means that the Expert Advisor will try to find the correct rate in the Market Review. 
For Autolot to work well with all currency pairs, you need to turn ON the “Show all currency pairs” in the Market Watch.
MaxLotThe maximum lot that an Expert Advisor can open when calculating an autolot and martingale for the first main position.
MartinMartingale. The standard multiplication of the lot of the last closed position at a loss.


If Martin = 1, then the martingale does not turn on (Fixed lots (Volumes)).
If Martin = 0, then the Expert Advisor can not open the next position.
If Martin = 2, then the first lot = 0.1, the second lot = 0.2, and so on, 0.4 – 0.8 – 1.6 – 3.2 – 6.4…..
If Martin = 0.5, then the first lot = 1, the second lot = 0.5, and so on, 0.25 – 0.125.

Do you need a code? 


Autolot calculation code function :

double GetSizeLot(double ll=1) //The function returns the value of lots,
  {
   string Autor=" Author of function for template : www.expforex.com";
   string lotcalc;
   double pr;
   string Valdepo=AccountCurrency();
//if MM is enabled then the value of lots,
   double Lot2,MinLots,MaxLots;
   int lotdig;
   if(MarketInfo(Symbol(),MODE_LOTSTEP)==0.01)lotdig=2; else lotdig=1;
   if(Valdepo=="USD")
     {
      if(StringSubstr(Symbol(),0,3)=="USD")Lot2=NormalizeDouble(AccountFreeMargin()*LotBalancePcnt*
         AccountLeverage()/100/MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
      else if(StringSubstr(Symbol(),3,3)=="USD")Lot2=NormalizeDouble(AccountFreeMargin()*LotBalancePcnt*
         AccountLeverage()/Ask/100/MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
      else
        {
         pr=MarketInfo(StringSubstr(Symbol(),0,3)+"USD",MODE_ASK);
         if(pr!=0)Lot2=NormalizeDouble(AccountFreeMargin()*LotBalancePcnt*AccountLeverage()/pr/100/
            MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
         else Lot2=NormalizeDouble(AccountFreeMargin()*LotBalancePcnt*AccountLeverage()/100/
            MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
        }
     }
   if(Valdepo=="EUR")
     {
      if(StringSubstr(Symbol(),0,3)=="EUR")Lot2=NormalizeDouble(AccountFreeMargin()*LotBalancePcnt*
         AccountLeverage()/100/MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
      else
        {
         pr=MarketInfo("EUR"+StringSubstr(Symbol(),0,3),MODE_BID);
         if(pr!=0)Lot2=NormalizeDouble(AccountFreeMargin()*LotBalancePcnt*AccountLeverage()*pr/100/
            MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
         else Lot2=NormalizeDouble(AccountFreeMargin()*LotBalancePcnt*AccountLeverage()/100/
            MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
        }
     }

   if(Valdepo=="UAH" || Valdepo=="UAH")
     {
      if(StringSubstr(Symbol(),0,3)=="USD")Lot2=NormalizeDouble(AccountFreeMargin()/40*
         LotBalancePcnt*AccountLeverage()/100/MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
      else if(StringSubstr(Symbol(),3,3)=="USD")Lot2=NormalizeDouble(AccountFreeMargin()/40*
         LotBalancePcnt*AccountLeverage()/Ask/100/MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
      else
        {
         pr=MarketInfo(StringSubstr(Symbol(),0,3)+"USD",MODE_ASK);
         if(pr!=0)Lot2=NormalizeDouble(AccountFreeMargin()/40*LotBalancePcnt*AccountLeverage()/pr/100/
            MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
         else Lot2=NormalizeDouble(AccountFreeMargin()/40*LotBalancePcnt*AccountLeverage()/100/
            MarketInfo(Symbol(),MODE_LOTSIZE),lotdig);
        }
     }

   MinLots=MarketInfo(Symbol(),MODE_MINLOT);
   MaxLots=MaxLot;
   lotcalc=" Autolot="+Lot2;
   if(!DynamicLot)Lot2=Lots;

   if(Lot2 < MinLots) Lot2 = MinLots;
   if(Lot2 > MaxLots) Lot2 = MaxLots;
   lotcalc=lotcalc+" MinLots="+MinLots+" LOT="+NormalizeDouble(Lot2,lotdig);
   Print(lotcalc);
   return(NormalizeDouble(Lot2,lotdig));
  }

Stoploss autolot calculation function :

If you want to add stop loss autolot functionality to your EA, you can download our code: 

StopLosssd = stoploss in points

External variables:

extern double Lots =0.1; // Fixed lot 

DynamicLot (RiskLotTypetype)
extern double LotBalancePcnt(RiskLot) =20; // % of deposit
 

Function:

double GetSizeLotStopLoss(double StopLosssd=1) //The function returns the value of lots,
 {
 string Autor=" Author of function for template : www.expforex.com";
 string Valdepo=AccountCurrency();
//if MM is enabled then the value of lots,
 double MinLots;
 int lotdig;
 if(MarketInfo(Symbol(),MODE_LOTSTEP)==0.01)lotdig=2; else lotdig=1;
 double Free=AccountFreeMargin();
 double LotVal=MarketInfo(Symbol(),MODE_TICKVALUE);//cost of 1 pip for 1 lot
 double Min_Lot =MarketInfo(Symbol(),MODE_MINLOT);
 double Max_Lot =MarketInfo(Symbol(),MODE_MAXLOT);
 double Step=MarketInfo(Symbol(),MODE_LOTSTEP);
 double Lot =MathFloor((Free*LotBalancePcnt/100)/(StopLosssd*LotVal)/Step)*Step;
 MinLots=MarketInfo(Symbol(),MODE_MINLOT);

 if(Lot<MinLots) Lot=MinLots;

 return(NormalizeDouble(Lot,lotdig));
 }

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This website uses cookies to improve your experience. By using this website you agree to our Data Protection Policy.
Read more