Risk percentage lot size calculation

MQL5 Эксперты

Работа завершена

Время выполнения 1 день
Отзыв от заказчика
Great Developer! Code works like a charm and was delivered very quickly with useful complementary information!
Отзыв от исполнителя
Excellent customer. Wishing you success in learning MQL.

Техническое задание

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;
           }
        
     }

 

 

Откликнулись

1
Разработчик 1
Оценка
(182)
Проекты
342
42%
Арбитраж
118
12% / 73%
Просрочено
104
30%
Свободен
2
Разработчик 2
Оценка
(549)
Проекты
826
73%
Арбитраж
15
53% / 13%
Просрочено
193
23%
Работает
Похожие заказы
Hi guys I would like to k ow if someone has experience with machine learning models? I would like to train a model to identify if there is a range market or trendy market based on several parameters like EMA and ATR for example. If we use for example a 20 and 50 EMA and we measure the distance between both lines the algo should oearn if the trend is strong or weak. If it‘s steong it keeps trending and if it‘s weak
Hello The EA will work on particular zone choose by the user and can mark it on any TF and with some rules can open trades and mange the trade by some unique rules. the EA need to check the difference by RSI as well and with some extra rules . developer should have good attitude and good communication (englsih) with high performence and knowledge with coding EA
we want to build a dashboard ea that would display on another chart key metrics : i will foward screeshot of what i want to dashboard to look like : the function i would need to get display are the following: 1. classified past performance ea by magic number ( with classic : total trade , total profit , return/dd , max dd (base on history) , ) 2. equity chart of performance if we click on a magic number we should
the task will be actually quiet simple , i need an active develloper to devellope out of 3 updates an ea STEP 1 (this job): make a classical pair trading ea , that can calculate correlation between assets and trade when the correlation diverge above a specified % the develloper that will postulate for the job will need : 1- to be ok to do the full project this job and the update following 2- very low arbitration , i
Hello, I want to create an EA that can be able to take and optimise trade bids using the trend tracker concept I have developed. The tracker will monitor the 2 lines in the below pictures and then start to activate bids once they cross each other and then be able to manage all bids afterwards towards the direction of the market by opening and closing them intermittently and profitably until the position at the other
Hi man, How are u? I have an EA and I need to check few aspects of the code, if It works fine? I am looking for an expert coder, who can understand mt4 language and help us to solve this out. This job will hardly take about 3-4 hours max for an experienced coder, when explained detail. Also, I would like to give this to someone, who can understand and speak English well. Also, the coder should be able to come via
Hello The EA will work on particular zone choose by the user and can mark it on any TF and with some rules can open trades and mange the trade by some unique rules. the EA need to check the difference by RSI as well and with some extra rules . developer should have good attitude and good communication (englsih) with high performence and knowledge with coding EA. THREE TYPES OF ENTRIES 1: AGGRESSIVE 2: DIVERGENCE 3
Indicator in use: Bollinger Bands Mechanism (See diagrams provided for help) Sells: 1. Trigger candle: When candle low is above the top Bollinger band - accurate to the lowest point scale (e.g. On EURUSD if candle low is 1.07915 and the value of top bollinger is 1.07914 - this is a sell signal; or if on Futures if the increment is .25 or .10 then this is used) 2. Enter sell ONLY on the next candle if price breaks
Indicator in use: Bollinger Bands Mechanism: (See diagrams provided for help) Sells: 1. Trigger candle: When candle low is above the top Bollinger band - accurate to the point scale (e.g. On EURUSD if candle low is 1.07915 and the value of top bollinger is 1.07914 - this is a sell signal) 2. Enter sell ONLY on the next candle if price breaks below the trigger candle LOW (using the e.g. above- if next candle price
hey guys, im looking for an auto mt5 license system through a web app i have already, i simply want it so a unique license key is generated for memebers, they input this onto the EA input and then it checks if its valid. active license per user capped at 5. i already have an mt5 coder and dec team for the app so i dont know if youd prefer to intergrate onto the webapp yourself or simply provide the code and doc so my

Информация о проекте

Бюджет
10 - 20 USD
Исполнителю
9 - 18 USD
Сроки выполнения
от 1 до 2 дн.