pls help me to Calculate Position Size with Balance.

 

Hello Guys , i want to  Create a personal panel for trading buy but I have a problem... im new in Programming and The problem I have now is that : i want Calculate Position Size with My account Balance and my risk buy i dont know how to do that ...

My stoploss is not fixed and I consider it according to the length of the previous candle(candleback)

//+------------------------------------------------------------------+
//|                                                   TradePanel.mq4 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                          https://www.cafemql.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link      "https://www.cafemql.com"
#property version   "1.00"
#property strict

#include <stderror.mqh>
#include <stdlib.mqh>

#include "Include/Components.mqh"

int pointopip=1;
double pips;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
 
//--- Determine what a pip is.
   pips=Point; //.00001 or .0001. .001 .01.
   
   if(Digits==3 || Digits==5 || (_Symbol=="XAUUSD" && Digits==2))
      pips *= 10;    
      pointopip=10;
//---
  MyPanel();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
    TradePanel.Destroy(reason);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
    
    
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---
   TradePanel.OnEvent(id,lparam,dparam,sparam);
   

//--- Place Noticable for Buy Position
   if(id==CHARTEVENT_OBJECT_CLICK && sparam=="Buy Button")
   {
        int ans = MessageBox("Are you sure to place a BUY order?","Place Order",MB_YESNO | MB_ICONQUESTION);
        
        if(ans == IDYES)
           PlaceOrder(OP_BUY);
   }  

//--- Place Noticable for Sell Position
   if(id==CHARTEVENT_OBJECT_CLICK && sparam=="Sell Button")
   {
        int ans = MessageBox("Are you sure to place a SELL order?","Place Order",MB_YESNO | MB_ICONQUESTION);
        
        if(ans == IDYES)
           PlaceOrder(OP_SELL);
   }  
   
//--- Place Noticable for Buy Position
   if(id==CHARTEVENT_OBJECT_CLICK && sparam=="Buy limit Button")
   {
        int ans = MessageBox("Are you sure to place a BUY order?","Place Order",MB_YESNO | MB_ICONQUESTION);
        
        if(ans == IDYES)
           PlaceOrder(OP_BUYLIMIT);
   }  

//--- Place Noticable for Sell Position
   if(id==CHARTEVENT_OBJECT_CLICK && sparam=="Sell limit Button")
   {
        int ans = MessageBox("Are you sure to place a SELL order?","Place Order",MB_YESNO | MB_ICONQUESTION);
        
        if(ans == IDYES)
           PlaceOrder(OP_SELLLIMIT);
   }   
   
      
   
   
  }
//+------------------------------------------------------------------+
//|  Place Order  Market                                                   |
//+------------------------------------------------------------------+
void PlaceOrder(int type)
{
      
   //--- Initialize Variables (openprice, stoploss, takeprofit)
   double openprice  = 0  ;
   double stoploss   = 0  ;  
   double takeprofit = 0 ; 
   
      double lotsize = StrToDouble( lotedit.Text() );
   double Padamount = StrToDouble( padamount.Text() );
   double Rewardprofit = StrToDouble( Rewardprofit.Text() );
   double Candleback = StrToDouble( Candleback.Text() );
   //--- Trade Volume
   double lot=LotSizeCalc();
   lot=NormalizeDouble(lot,2);

   //---BUY Position Checking...
  if(type == OP_BUY)
   {
   //---openprice, stoploss, takeprofit for Buy Position
       openprice   = Ask;
       double lowPrev = iLow(NULL, 0, Candleback);
       double highPrev = iHigh(NULL, 0, Candleback);
       double stoppos=highPrev - lowPrev;
       double PadPercent=Padamount*(stoppos/100);
      stoploss    = NormalizeDouble(openprice - (stoppos)-PadPercent,_Digits);  
      takeprofit  = NormalizeDouble(openprice + (stoppos*Rewardprofit),_Digits);
       
   }
 
   //---SELL Position Checking...
   if(type == OP_SELL)
   {
    //---openprice, stoploss, takeprofit for Sell Position
      openprice = Bid;
      double lowPrev = iLow(NULL, 0, Candleback);
      double highPrev = iHigh(NULL, 0, Candleback);
      double stoppos=highPrev - lowPrev;
      double PadPercent=Padamount*(stoppos/100);
      stoploss    = NormalizeDouble(openprice + (stoppos)+PadPercent,_Digits);  
      takeprofit  = NormalizeDouble(openprice - (stoppos*Rewardprofit),_Digits);       
   }
   
//+------------------------------------------------------------------+
//|  Place Order  limit                                                |
//+------------------------------------------------------------------+   
   if(type == OP_BUYLIMIT)
   {
   //---openprice, stoploss, takeprofit for Buy Position
      openprice   = iLow(NULL, 0, Candleback);
       double lowPrev = iLow(NULL, 0, Candleback);
       double highPrev = iHigh(NULL, 0, Candleback);
       double stoppos=highPrev - lowPrev;
       double PadPercent=Padamount*(stoppos/100);
      stoploss    = NormalizeDouble(openprice - (stoppos)-PadPercent,_Digits);  
      takeprofit  = NormalizeDouble(openprice + (stoppos*Rewardprofit),_Digits);  
   }
 
   //---SELL Position Checking...
   if(type == OP_SELLLIMIT)
   {
    //---openprice, stoploss, takeprofit for Sell Position
      openprice = iHigh(NULL, 0, Candleback);
      double lowPrev = iLow(NULL, 0, Candleback);
      double highPrev = iHigh(NULL, 0, Candleback);
      double stoppos=highPrev - lowPrev;
      double PadPercent=Padamount*(stoppos/100);
      stoploss    = NormalizeDouble(openprice + (stoppos)+PadPercent,_Digits);  
      takeprofit  = NormalizeDouble(openprice - (stoppos*Rewardprofit),_Digits);       
   }
   
   //--- send order to the server
   if( OrderSend(_Symbol,type,lot,openprice,30,stoploss,takeprofit) == -1)
        Print("unable to place order due to \"",ErrorDescription(GetLastError()),"\"");
   
}


//+------------------------------------------------------------------+
//|  Place Order  Limit                                                   |
//+------------------------------------------------------------------+
double LotSizeCalc()
{
   double lotsize = StrToDouble( lotedit.Text() );
   double Padamount = StrToDouble(padamount.Text() );
   double Candleback = StrToDouble( Candleback.Text() );
       double openprice  = 0  ;
       double stoploss   = 0  ;
       openprice   = Ask;
       double lowPrev = iLow(NULL, 0, 1);
       double highPrev = iHigh(NULL, 0, 1);
       double stoppos=(highPrev - lowPrev);
       double PadPercent=(Padamount*(stoppos/100));
       stoploss    = openprice - (stoppos-PadPercent);

      
   double lotsizebalance=0;
   
   double Tick_valuee = MarketInfo(Symbol(), MODE_TICKVALUE);
   // If the digits are 3 or 5, we normalize multiplying by 10.
   if ((Digits == 3) || (Digits == 5)){
      Tick_valuee = Tick_valuee * 10;
   }
   
   double balanceac = AccountBalance();
   double riskPercent=lotsize;
   lotsizebalance=(riskPercent/(stoploss*1.0)/Tick_valuee);
   lotsizebalance=NormalizeDouble(lotsizebalance,2);
   
   double minlot=MarketInfo(_Symbol,MODE_MINLOT);
   double maxlot=MarketInfo(_Symbol,MODE_MAXLOT);
   
   if(lotsizebalance <=0)
      lotsizebalance=minlot;
   else if(lotsizebalance >= maxlot)
      lotsizebalance=maxlot;
   Print("Position size in lotsss? ", stoploss);
   
   return lotsizebalance;
}

 

Your question is very common and has been asked many times. Please do a search in the Forum, CodeBase and Articles.

Here is one post of mine ... https://www.mql5.com/en/forum/390589#comment_28231377

But there are many other posts with different approaches and there are even articles dedicated to the subject. So, please do a search and study them

 
aliasgari524:

Hello Guys , i want to  Create a personal panel for trading buy but I have a problem... im new in Programming and The problem I have now is that : i want Calculate Position Size with My account Balance and my risk buy i dont know how to do that ...

My stoploss is not fixed and I consider it according to the length of the previous candle(candleback)


What do you mean here ? 

 
Lorentzos Roussos #:

What do you mean here ? 
For example, the stoploss is determined according to the distance of the price from the low to the high of the previous candle(candle[1] or [2] or ....
 
Lorentzos Roussos #:


What do you mean here ? 

For example, in the candleback variable, I enter the number 3, so the stop loss should be determined according to the length of the low to high of the previous 3 candles.
 
i see so essentially you are using one of the previous candles's size and you are calculating the lot so as to "would-be" losing this % of your balance within that size or something
 
aliasgari524 #:
For example, in the candleback variable, I enter the number 3, so the stop loss should be determined according to the length of the low to high of the previous 3 candles.
Yes, I want the risk that is taken for the trade to be according to the size of the previous candles. That is, if I enter 1% risk, I will risk 1% of my account balance for the size of this candle. I don't know how to do this...
 
aliasgari524 #:
Yes, I want the risk that is taken for the trade to be according to the size of the previous candles. That is, if I enter 1% risk, I will risk 1% of my account balance for the size of this candle. I don't know how to do this...

I see , try this function , if it returns 0.0 it means there is an error 

#property copyright "forum thread"
#property link      "https://www.mql5.com/en/forum/448801"
#property version   "1.00"
#property strict
input int bar_offset=1;//bar offset to acquire size 
input double risk=1;//risk %

double get_lot_by_bar_size_and_risk(int _bar,double _risk){
//reset the error 
  ResetLastError();
//error collector
  int errors=0;
//get tick value for one lot for asset
  double tvol=(double)SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
  //collect errors 
    if(GetLastError()!=0){errors+=GetLastError();ResetLastError();}
//get min and max lot
  double minlot=(double)SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
  //collect errors 
    if(GetLastError()!=0){errors+=GetLastError();ResetLastError();}
  double maxlot=(double)SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
  //collect errors 
    if(GetLastError()!=0){errors+=GetLastError();ResetLastError();}
//lot step
  double lotstep=(double)SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
  //collect errors
    if(GetLastError()!=0){errors+=GetLastError();ResetLastError();}
//if no errors 
  if(errors==0){
  //get size of bar 
    if(_bar<Bars){
    double size_in_ticks=(High[_bar]-Low[_bar])/_Point;
    double amount_to_lose=(AccountBalance()/100.0)*_risk;
    //so you are intending to lose the above amount in the above ticks
    //   you can calculate the target value per tick based on the above 
    double tick_value_target=amount_to_lose/size_in_ticks;
    //we know the value of 1 tick if we had a trade of 1 lot
      //so if we divide the target tick value by the one lot tick value we get the lots
    double lot=tick_value_target/tvol;
    //check if within limits 
      if(lotstep>0.0){
      int steps=(int)MathFloor(lot/lotstep);
      lot=((double)steps)*lotstep;
      }
    if(lot<minlot){lot=minlot;}
    if(lot>maxlot){lot=maxlot;}
    return(lot);
    }
  }
return(0.0);
}
int OnInit()
  {
//---
  //don't call oninit 
    while(!EventSetMillisecondTimer(44)){
    Print("Setting timer please wait");
    Sleep(44);
    } 
//---
   return(INIT_SUCCEEDED);
  }

void OnTimer(){
EventKillTimer();
double lot=get_lot_by_bar_size_and_risk(bar_offset,risk);
Print("Lot to use ("+DoubleToString(lot,2)+")");
ExpertRemove();
}
void OnDeinit(const int reason)
  {  
  }
void OnTick()
  {
  }
 
    if(GetLastError()!=0){errors+=GetLastError();ResetLastError();}
You read last error, set it to zero, checked if it was non-zero, added zero, and set it to zero again.
After the function call, the contents of _LastError are reset.
          GetLastError - Checkup - MQL4 Reference

Check your return codes, and report your errors (including market prices and your variables). Don't look at GLE/LE unless you have an error.

 
William Roeder #:
You read last error, set it to zero, checked if it was non-zero, added zero, and set it to zero again.

Check your return codes, and report your errors (including market prices and your variables). Don't look at GLE/LE unless you have an error.

Thank you 

It says in the docs (of mql5) that calling the GetLastError() does not reset it .

Its not the same in mql4 ?

 
Lorentzos Roussos #: Its not the same in mql4 ?

I quoted the documentation and provided a link.