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
844
73%
Arbitrage
15
53% / 13%
En retard
193
23%
Gratuit
Commandes similaires
Am looking for am experience Programmer who can Edit and compile 2 Ea"s that i built with the help of CHATGPT. I need the job to be done within one day and I will prove the source code
I am looking for an experienced MQL5 developer to build a professional, fully automated Expert Advisor (EA) for MetaTrader 5 . This project is focused on risk-controlled, long-term consistency , not unrealistic promises. 🧑‍💻 Developer Requirements (Very Important) Please apply only if you meet these criteria : ✅ Rating 4.7+ ✅ 50+ completed jobs (more is better) ✅ 3+ years experience with MQL5 ✅ Strong understanding
1. Trading Idea & Project Goal This is a Market Filter Scanner , not a trading robot. Its sole purpose is to automate the identification of high-probability price action setups across multiple symbols. The tool must scan markets, apply a strict set of objective rules to closed candles only , and alert me with a sound when a setup is found. This MVP (Minimal Viable Product) version is deliberately simplified to
## Project Summary I am hiring an experienced *MQL5 developer* to convert an existing *Heikin Ashi–based scalping strategy (currently written in Pine Script)* into a fully automated Expert Advisor for *MetaTrader 5*. The trading logic already exists. Your role is implementation, execution reliability, and engineering improvements — particularly eliminating trades during consolidation/ranging markets. This is a custom
Hi, I want to develop an EA that replicates the logic of a bot I’m currently watching on a live account. The bot has grown an account from $500 to $60k in 3 weeks using a specific 'Buy Stop/Sell Stop' strategy with 0.03 lots. I have the Investor Password and Trade History. Can you analyze the execution patterns and build a replica for me? Let me know your experience with this kind of task. message me for account
Good day to you all i need an mt5 version of the attached Indicators currently i have its mt4 source code but the indicator has the following problem it give signal after the finished bar in some case this signal disappear if the signal is false i want to know if you have its mt5 version then we can discuss the possibility of modify it so that instead of deleting the false signal it will regenerate another reversed
I need a AI signal generating bot for forex trading that use the latest ai technology to track real time forex market, analyse and give signals. The bot should operate such that when i put it in a chart it will analyse the market, after several minutes it will display whether the trade is buying or selling. It should display the one minute, five minute,15minute, 30 minute, one hour, 4 hours and daily time frame
1. Objective A fully automated trading bot that: • Trades USD-quoted assets (forex pairs like EUR/USD, GBP/USD, crypto markets with USD trading pairs, and USD-denominated stocks/ETFs). • Uses real-time data to detect trends and place entries/exits based on multiple strategies. • Maximizes profit while maintaining robust risk controls and drawdown limits. 2. High-Level Architecture Components Component Purpose Data
I am looking for an experienced developer that can design an EA that detects impulse in the market and trade in the direction. The EA will have good risk management with trailing drawdown. The developer should have an idea of what instrument the EA will use to detect the impulse and trade in that direction
Hello I want to convert my tradingview indicators into Ninja trader can anyone help me with it it is urgent and I will like to discuss more about it to you if you can help me Kindly do well to bid on it

Informations sur le projet

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