Code for Risk Management

 

Hi,

I'm looking for a code to calculate the lot size based on stop loss, but the stop loss is not fixed at a specific value. For example, stoploss will be placed at a MA value.

Thanks for spending your time.

Best regards.

 
//+------------------------------------------------------------------+
//|                                  Viet EA No Limit Martingale.mq4 |
//|                                                       Viet Hoang |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Viet Hoang"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict


//=========Default Parameters is for EURUSD H1 chart=================//
//Optimize it with the pair and timeframe that you like to test.

//-----------Trade Parameters
extern double StopLoss   = 650;
extern double TakeProfit = 650;
extern double LS         = 0.1;
input int     Slippage=3;
input int     MagicNumber=1234;
//-----------Martingale Parameter
extern double Multiplier=2;

//-----------Indicator & Entry Analysis Parameters
//=================================================
//Put here the parameters of your own analysis
//--- indicator inputs

//=================================================
//--- global variables
double MyPoint;
int    MySlippage;
//-----------Variables
double Lot         = 0.1;
double AcctBalance = 0.0;
bool   Go          = true;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
   AcctBalance=AccountBalance();
   return(0);
   MyPoint = MyPoint();
   MySlippage = MySlippage();
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   if(OrdersTotal()==0 && AcctBalance!=AccountBalance())
     {
      if(AcctBalance>AccountBalance())
        {
         Lot=Multiplier*Lot;
         Go = true;
        }
      else if(AcctBalance<AccountBalance())
        {
         Lot=LS;
         Go = true;
        }
     }
   //else if(OrdersTotal()==0 && AcctBalance==AccountBalance())
   //  {
   //   Go=true;
   //  }

   if(OrdersTotal()==0 && Go)
     {
      int order;
      
      //=================Change this with your own entry analysis=============================
      double Indicator()
      //======================================================================================

      if ( Buy condition )
      )
        {
         order=OrderSend(Symbol(),OP_BUY,Lot,Ask,MySlippage,Bid-StopLoss*MyPoint,Ask+TakeProfit*MyPoint,"Viet EA BUY",MagicNumber);
         Go=false;
        }
      else if( Sell condition )
      )
        {
         order=OrderSend(Symbol(),OP_SELL,Lot,Bid,MySlippage,Ask+StopLoss*MyPoint,Bid-TakeProfit*MyPoint,"Viet EA SELL",MagicNumber);
         Go=false;
        }
     }

//----
   return(0);
  }
//+------------------------------------------------------------------+
   
// Get My Points   
double MyPoint()
{
   double CalcPoint = 0;
   
   if(_Digits == 2 || _Digits == 3) CalcPoint = 0.01;
   else if(_Digits == 4 || _Digits == 5) CalcPoint = 0.0001;
   
   return(CalcPoint);
}


// Get My Slippage
int MySlippage()
{
   int CalcSlippage = 0;
   
   if(_Digits == 2 || _Digits == 4) CalcSlippage = Slippage;
   else if(_Digits == 3 || _Digits == 5) CalcSlippage = Slippage * 10;
   
   return(CalcSlippage);
}

Currently I have already had an Martingale version of it, but unfortunately it can only open 1 trade at a time. I want to use Money Management instead of Martingale.

 

you have to calculate the lot like this:

double risk_percent= 2;
Lot =  (AccountBalance() * risk_percent/100 ) /  StopLoss;
 
Khuman Bakhramirad:

you have to calculate the lot like this:

Thank you for your reply,

Well I'm kind of a newbie with all these mq4 things. I wonder where do I put the calculation for StopLoss? Right after int start()??
And how can I divided stoploss into 2 orders buy and sell? Each order will have different stoploss.

Thank you for your help.

Wish you all the best.

 
Tran Nguyen Viet Hoang: I'm looking for a code to calculate the lot size based on stop loss, but the stop loss is not fixed at a specific value. For example, stoploss will be placed at a MA value.

Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk. Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

  1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce the stop goes below the support.

  2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/pip but it takes account of the exchange rates of the pair vs. your account currency.)

  3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
              MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum 2017.10.10
              Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum 2018.02.11
              Lot value calculation off by a factor of 100 - MQL5 programming forum 2019.07.19

  4. You must normalize lots properly and check against min and max.

  5. You must also check FreeMargin to avoid stop out

Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

 
William Roeder:

Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk. Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

  1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce the stop goes below the support.

  2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/pip but it takes account of the exchange rates of the pair vs. your account currency.)

  3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
              MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum 2017.10.10
              Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum 2018.02.11
              Lot value calculation off by a factor of 100 - MQL5 programming forum 2019.07.19

  4. You must normalize lots properly and check against min and max.

  5. You must also check FreeMargin to avoid stop out

Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

Yes, what I am trying to figure out is how to make a money management code since StopLosses of each order are not equal. Buy and sell orders will have different kinds of stop loss. I have searched many topics, and their stoploss was a fixed value.

Reason: