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
(564)
Projets
845
73%
Arbitrage
15
53% / 13%
En retard
193
23%
Gratuit
Commandes similaires
I need fully automatic scalping robots for XAUUSD Gold the robot should work on M1 and M5 timeframe and open trades based on the scalping logic using EMA and RSI confirmation it should analyze the market on its own and only take high probability trades
I am looking for an experienced MQL5 / MetaTrader 5 developer to help me add alert notifications to an existing MT5 indicator. What I Have I have an indicator that I am currently using on MetaTrader 5 , but I do not have the source code (.mq5) . I only have the compiled indicator file, or I can provide the indicator file that I currently have. What I Need I want to add alerts when the indicator generates its specific
I need best scalping bot 150 - 300 USD
I have attached the video of the EA I want to reproduce in MQL5. Please study the video carefully and build an EA that follows the same trading behavior shown in it. The EA is for XAUUSD (Gold) and appears to use an automated scalping/grid-style strategy with multiple positions opened around the market price. I want the entry sequence, spacing between positions, lot progression, direction of trades, and
New EA for Moj1367 50 - 100 USD
//@version=6 strategy("Ultimate + 11 Filters Bot [M1 - 0.5 pip TP]", overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_bars_back=5000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.04) // ═══════════════════════════════════════════════════════════ // 1. تنظیمات ورودی (Inputs)
I need an MT5 EA (MQL5) specifically for XAUUSD, trading price gaps when the market opens/reopens. The EA needs 2 independent strategies: 1. Weekend/Monday Gap: Record the last price before the market closes for the weekend and the first price when XAUUSD reopens at the beginning of the week. Calculate the gap size. When the gap meets the required conditions, the EA trades in the direction of the Gap Fill. Gap Up →
Best performing EA MT5 30 - 1000 USD
I am looking for a reliable MQL4/MQL5 EA that creates orders automatically. If anyone has a good-performing EA available for sale, please share it with verified live trading results or a genuine live track record . I am ready to purchase, but live performance proof is mandatory . Please share the live account results, trading history, and EA details before discussing the purchase
Hi In my current EA, you must edit this robot in an Instagram-based mode to construct robots. My old Robot Pending Order is designed to put merely in order, making it easy to update. I've included a link to the rar file, which is plainly referenced in the video. The strategy behind this work is detailed, as are the Instagram videos that are linked to the chart. As shown in this Instagram video link, we need a robot
I’m looking for an experienced MQL5 / MT5 developer to build an EA that acts as a connector between a user’s MT5 trading account and our own web-based performance tracking platform. The concept is similar to platforms like Myfxbook or ShowMyTrades , where users can connect their trading account and automatically track their trading performance, including trade history, profit/loss, win rate, drawdown, account
Account size 50$ to 100$ or 5000USC to 10000USC ( Account $ Size may not matter ) Max Leverage 1000-2000 Min Lot 0.01 [ if averaging possible ] Averaging + Shift TP Faster Required if Trend Direction is Clear Account Protection Maxx Profit Max Loss Key Based Activation News Filter Need Expert to handle this to avoid false entry [ Developer can suggest extra additional filters inputs here ] as i mentioned I have no
Build a Forex Multi-Basket Trading Bot for OANDA (Python v20 REST API Only) MANDATORY DEVELOPER REQUIREMENTS (PLEASE READ BEFORE APPLYING): Do not apply for this project unless you meet the following strict professional criteria: 1. Deep Mathematical & Quantitative Background: You must thoroughly understand statistical distributions, rolling standard deviations (σ), calculating matrix medians, and dynamic Z-score

Informations sur le projet

Budget
10 - 20 USD
Délais
de 1 à 2 jour(s)