Risk percentage lot size calculation

MQL5 Experts

Tâche terminée

Temps d'exécution 1 jour
Commentaires du client
Great Developer! Code works like a charm and was delivered very quickly with useful complementary information!
Commentaires de l'employé
Excellent customer. Wishing you success in learning MQL.

Spécifications

Hi All,

I would like to add to an existing and working MQL5 EA the ability to calculate the lot size based on a risk percentage. Or in other words how many percent of the account I'm willing to lose for each deal.

Here are some key elements of my EA setup:

The base currency is EUR

Trading pair is EURJPY

Leverage is 1/100

SL is fixed at 50 pips

Target risk percentage per deal should be a variable set by default on 5%  

 

The below formula seem to be the one needed to achieve my lot size calculation but I'm not sure. 

Lot Size = Amount Risked / Number of Pips x Pip Value 

 

I tried the created the code myself and here is where I stopped: 

Basically I need help to compete the "//Calculating Lot Size based on SL and Risk Percentage" part of the code. 

 

Let me know if you have any questions.  

 

Different Variables for the lot size calculation: 

input int      StopLoss=50;               // Stop Loss
input double   RiskPercentage=5;          // Lots to Trade

int STP, TKP; 
double LotSize;
double Pips;



//--- Let us handle currency pairs with 5 or 3 digit prices instead of 4
   STP = StopLoss;
   TKP = TakeProfit;
   if(_Digits==5 || _Digits==3)
     {
      STP = STP*10;
      TKP = TKP*10;
     }
   return(0);
  }

 My Buying Script

if(Buy_Condition_1 && Buy_Condition_2)
     {
         // any opened position?
         if((Buy_opened)||(Sell_opened))
           {
            //Alert("We already have an open Position. Oportuinity passed.");
            return;    // Don't open a new Buy Position
           }
           
         // Calculating Lot size based on SL and Risk Percentage
         
         MqlTick latest_price;
         SymbolInfoTick(_Symbol,latest_price);
         
         Pips = (latest_price.bid - STP)/_Point;          
         
         double AccountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
         double TickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
         LotSize = (AccountBalance * (RiskPercentage/100))/(Pips * TickValue);  
         
         Print("Pips ", Pips, " Acc Bal: ", AccountBalance," Tick Val ", TickValue," Lot Size ", LotSize);      
         
         //Executing the Trade 
         ZeroMemory(mrequest);
         mrequest.action = TRADE_ACTION_DEAL;                                    // immediate order execution
         mrequest.price = NormalizeDouble(latest_price.ask,_Digits);             // latest ask price
         mrequest.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits);   // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.ask + TKP*_Point,_Digits);   // Take Profit
         mrequest.symbol = _Symbol;                                              // currency pair
         mrequest.volume = LotSize;                                                  // number of lots to trade
         mrequest.magic = EA_Magic;                                              // Order Magic Number
         mrequest.type = ORDER_TYPE_BUY;                                         // Buy Order
         mrequest.type_filling = ORDER_FILLING_FOK;                              // Order execution type
         mrequest.deviation=100;                                                 // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
            SendNotification("BBWP added a new Buy order!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError());
            ResetLastError();           
            return;
           }
        
     }

 

 

Répondu

1
Développeur 1
Évaluation
(182)
Projets
342
42%
Arbitrage
118
12% / 73%
En retard
104
30%
Gratuit
Publié : 4 codes
2
Développeur 2
Évaluation
(560)
Projets
840
73%
Arbitrage
15
53% / 13%
En retard
193
23%
Gratuit
Commandes similaires
I’m looking for a custom MT4 or MT5 server setup that looks and feels exactly like a live trading account but gives me full control over the environment. What I need: • A private MT4/MT5 server that connects to the official MT4/MT5 desktop terminal • Live market price feed (real-time quotes for realism) • Ability to: • Create and manage accounts • Set or change balance, equity, margin • Manually add/edit/close trades
Create a ZigZag indicator, which is constructed based on extreme values determined using oscillators. It can use any classical normalized oscillator, which has overbought and oversold zones. The algorithm should first be executed with the WPR indicator, then similarly add the possibility to draw a zigzag using the following indicators
I'm looking for a developer to create a trading bot based on order blocks. Entry: on OB via the indicator CODE Exit and Money Management copied from: https://www.mql5.com/en/market/product/55393?source=Site +Market+MT4+Search+Rating006%3adark+venus CODE Goal so I can do multiple iframes But otherwise EURUSD in M1
Hello I’m looking for a custom MT4 or MT5 server setup that looks and feels exactly like a live trading account but gives me full control over the environment. What I need: • A private MT4/MT5 server that connects to the official MT4/MT5 desktop terminal • Live market price feed (real-time quotes for realism) • Ability to: • Create and manage accounts • Set or change balance, equity, margin • Manually add/edit/close
What I Need I'm looking for solid MQL4/5 and Pine Script developers for ongoing projects. No agencies, no middlemen - just skilled devs who know their stuff. The Deal ~5 projects per month to start Fair pay - I don't lowball good work Per-project rates - we'll agree on price upfront You Should Know MQL4/5 programming (EAs, indicators, scripts) Pine Script for TradingView How trading actually works How to write clean
Sierrachart 30+ USD
Hello, I am new to sierra chart, but very familiar with trading space. I dont want to spend time learning through online videos and want to get to what i want quickly. I need help from someone who knows sierra chart inside and out to help me get setup futures NQ market, chart, footprint, order flow, DOM etc. I will provide you my userid password and you can set it up for me and also let me know exactly what needs
Hallo, ich suche einen erfahrenen MT5-Programmierer, der mir einen Key Structure Range Indikator auf Basis von 3er-Fractals erstellt, inkl. Buffers für spätere EA-Nutzung. Pflichtenheft - Key Structure Range Indikator für MT5 (EA-ready): Projektbezeichnung: "Key Structure Range Indikator für MT5 (EA-ready)" 1. Plattform - MetaTrader 5 (MT5) - Unterstützte Timeframes: M1 bis H12 2. Kerneigenschaften (unbedingt
I'm looking for a developer to maintain and improve an existing trading system based on MT4 (MQL4) and Python . 📌 Communication must be in Polish (written or spoken). The developer doesn’t need to be based in Poland. ✅ What’s already working: A fully functional MT4 Expert Advisor : opens trades based on signals, shifts Stop Loss at TP1, TP2, TP3, reacts to Break Even (BE) signals, A Python script : listens to
Strategy Purpose: Place a trade immediately at the close of a Renko candle or wait for close of 1 st, 2nd or 3rd renko candle (user defined) when color changes (trend reversal) for placing entry, with a confirmation that previous trend had at least 1, 2 (user defined) number of continues same-color bricks. User Inputs (Customizable Parameters): 1. EntryOnCandlenumber = 1 o Enter on 1st, 2nd, 3rd or same-color candle
Hi, I’m looking for a custom MT4 or MT5 server setup that looks and feels exactly like a live trading account but gives me full control over the environment. What I need: • A private MT4/MT5 server that connects to the official MT4/MT5 desktop terminal • Live market price feed (real-time quotes for realism) • Ability to: • Create and manage accounts • Set or change balance, equity, margin • Manually add/edit/close

Informations sur le projet

Budget
10 - 20 USD
Pour le développeur
9 - 18 USD
Délais
de 1 à 2 jour(s)