1 (edited by Riuzk 2019-10-15 21:36:33)

Topic: Risk Percent

Hello friends,

Was wondering if anyone could help me out here.
Trying to makeing some modifications on some of my EA's, right now my objective is to try makeing my EA portifolio risk a certain % on each trade it open.

Normal from EA studio:

/*STRATEGY CODE {"properties":{"entryLots":0.03,"stopLoss":55,"takeProfit":70,"useStopLoss":true,"useTakeProfit":true,"isTrailingStop":false},"openFilters":[{"name":"Bollinger Bands","listIndexes":[2,3,0,0,0],"numValues":[28,1.74,0,0,0,0]},{"name":"Standard Deviation","listIndexes":[7,3,0,0,0],"numValues":[6,0,0,0,0,0]}],"closeFilters":[{"name":"Bollinger Bands","listIndexes":[0,3,0,0,0],"numValues":[34,3.57,0,0,0,0]}]} */
   signalList[i++] = GetExitSignal_00();
   signalList[i++] = GetEntrySignal_00();

   /*STRATEGY CODE {"properties":{"entryLots":0.03,"stopLoss":17,"takeProfit":98,"useStopLoss":true,"useTakeProfit":true,"isTrailingStop":false},"openFilters":[{"name":"Money Flow Index","listIndexes":[5,0,0,0,0],"numValues":[12,56,0,0,0,0]}],"closeFilters":[{"name":"Money Flow Index","listIndexes":[5,0,0,0,0],"numValues":[48,12,0,0,0,0]}]} */
   signalList[i++] = GetExitSignal_01();
   signalList[i++] = GetEntrySignal_01();




What im trying to achieve:

Risk Percent: Example:5%

/*STRATEGY CODE {"properties":{"entryLots":(Calculated based on the risk
5%)
,"stopLoss":5%,"takeProfit":70,"useStopLoss":true,"useTakeProfit":true,"isTrailingStop":false},"openFilters":[{"name":"Bollinger Bands","listIndexes":[2,3,0,0,0],"numValues":[28,1.74,0,0,0,0]},{"name":"Standard Deviation","listIndexes":[7,3,0,0,0],"numValues":[6,0,0,0,0,0]}],"closeFilters":[{"name":"Bollinger Bands","listIndexes":[0,3,0,0,0],"numValues":[34,3.57,0,0,0,0]}]} */
   signalList[i++] = GetExitSignal_00();
   signalList[i++] = GetEntrySignal_00();


   /*STRATEGY CODE {"properties":{"entryLots":(Calculated based on the risk
5%)
,"stopLoss":5%,"takeProfit":98,"useStopLoss":true,"useTakeProfit":true,"isTrailingStop":false},"openFilters":[{"name":"Money Flow Index","listIndexes":[5,0,0,0,0],"numValues":[12,56,0,0,0,0]}],"closeFilters":[{"name":"Money Flow Index","listIndexes":[5,0,0,0,0],"numValues":[48,12,0,0,0,0]}]} */
   signalList[i++] = GetExitSignal_01();
   signalList[i++] = GetEntrySignal_01();


Would really appreciate if anyone could help me out on this one

Thanks guys wink

Re: Risk Percent

you mean open lot size based on risk % on account balance. cause what you show is stop loss in %.

Re: Risk Percent

Yes, Roughey. That is what i meant, sorry for my explanation, abit sleepy atm smile

Re: Risk Percent

input bool                usePercent                        = true;                // Use Risk Percent base on AccountBalance
input double               Entry_Percent              = 2.00;                 // ENTRY PERCENT
Put in OnTick this:
if(usePercent==true)
      int margin=(int) MarketInfo(_Symbol,MODE_MARGINREQUIRED);
         Entry_Amount=(Entry_Percent/100)*AccountEquity()/margin;}

Re: Risk Percent

Thank you Roughey, appreciate your effort helping out members smile

But it seems like i have some issue inserting it to my EA

This i what i did:

I inserted these two lines, almost at the begining

input bool                usePercent          = true;     // Use Risk Percent base on AccountBalance
input double               Entry_Percent        = 2.00;                 // ENTRY PERCENT



//
// EA Studio Portfolio Expert Advisor
//
// Created with: Expert Advisor Studio
// Website: https://eaforexacademy.com/expert-advisor-studio/
//
// Copyright 2019, Forex Software Ltd.
//
// This Portfolio Expert works in MetaTrader 4.
// It opens separate positions for each strategy.
// Every position has an unique magic number,
// which corresponds to the index of the strategy.
//

#property copyright "Forex Software Ltd."
#property version   "2.4"
#property strict

static input double Entry_Amount      = 0.01; // Entry lots
static input int    Base_Magic_Number = 100;  // Base Magic Number

#define TRADE_RETRY_COUNT 4
#define TRADE_RETRY_WAIT  100
#define OP_FLAT           -1

// Session time is set in seconds from 00:00
const int sessionSundayOpen           = 0;     // 00:00
const int sessionSundayClose          = 86400; // 24:00
const int sessionMondayThursdayOpen   = 36000; // 10:00
const int sessionMondayThursdayClose  = 61200; // 17:00
const int sessionFridayOpen           = 36000; // 10:00
const int sessionFridayClose          = 61200; // 17:00
const bool sessionIgnoreSunday        = true;
const bool sessionCloseAtSessionClose = false;
const bool sessionCloseAtFridayClose  = false;

input bool                usePercent                        = true;                // Use Risk Percent base on AccountBalance
input double               Entry_Percent              = 2.00;                 // ENTRY PERCENT


const int    strategiesCount = 10;
const double sigma           = 0.000001;

datetime barTime;
int      digits;
double   stopLevel;
double   pip;
bool     setProtectionSeparately = false;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

And the other part here

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()

  {
   if(IsForceSessionClose())
     {
      CloseAllPositions();
      return;
     }

   if(Time[0]>barTime)
     {
      barTime=Time[0];
      OnBar();
     }
     
   if(usePercent==true)
      {
      int margin=(int) MarketInfo(_Symbol,MODE_MARGINREQUIRED);
         Entry_Amount =(Entry_Percent/100)*AccountEquity()/margin;
      }
    
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

I got 1 error when im trying to compile it:
'Entry_Amount' - constant cannot be modified

Could you help me out on what i did wrong here or maybe send an EA with the code inserted aldready.

Thanks smile

Re: Risk Percent

Riuzk wrote:

Thank you Roughey, appreciate your effort helping out members smile

But it seems like i have some issue inserting it to my EA

This i what i did:

I inserted these two lines, almost at the begining

input bool                usePercent          = true;     // Use Risk Percent base on AccountBalance
input double               Entry_Percent        = 2.00;                 // ENTRY PERCENT



//
// EA Studio Portfolio Expert Advisor
//
// Created with: Expert Advisor Studio
// Website: https://eaforexacademy.com/expert-advisor-studio/
//
// Copyright 2019, Forex Software Ltd.
//
// This Portfolio Expert works in MetaTrader 4.
// It opens separate positions for each strategy.
// Every position has an unique magic number,
// which corresponds to the index of the strategy.
//

#property copyright "Forex Software Ltd."
#property version   "2.4"
#property strict

static input double Entry_Amount      = 0.01; // Entry lots
static input int    Base_Magic_Number = 100;  // Base Magic Number

#define TRADE_RETRY_COUNT 4
#define TRADE_RETRY_WAIT  100
#define OP_FLAT           -1

// Session time is set in seconds from 00:00
const int sessionSundayOpen           = 0;     // 00:00
const int sessionSundayClose          = 86400; // 24:00
const int sessionMondayThursdayOpen   = 36000; // 10:00
const int sessionMondayThursdayClose  = 61200; // 17:00
const int sessionFridayOpen           = 36000; // 10:00
const int sessionFridayClose          = 61200; // 17:00
const bool sessionIgnoreSunday        = true;
const bool sessionCloseAtSessionClose = false;
const bool sessionCloseAtFridayClose  = false;

input bool                usePercent                        = true;                // Use Risk Percent base on AccountBalance
input double               Entry_Percent              = 2.00;                 // ENTRY PERCENT


const int    strategiesCount = 10;
const double sigma           = 0.000001;

datetime barTime;
int      digits;
double   stopLevel;
double   pip;
bool     setProtectionSeparately = false;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

And the other part here

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()

  {
   if(IsForceSessionClose())
     {
      CloseAllPositions();
      return;
     }

   if(Time[0]>barTime)
     {
      barTime=Time[0];
      OnBar();
     }
     
   if(usePercent==true)
      {
      int margin=(int) MarketInfo(_Symbol,MODE_MARGINREQUIRED);
         Entry_Amount =(Entry_Percent/100)*AccountEquity()/margin;
      }
    
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

I got 1 error when im trying to compile it:
'Entry_Amount' - constant cannot be modified

Could you help me out on what i did wrong here or maybe send an EA with the code inserted aldready.

Thanks smile

I may be wrong but I believe it is because you have Entry amount as a Static Input. Trying removing the word static and compile

7 (edited by Roughey 2019-10-16 22:00:15)

Re: Risk Percent

yes delete the static and than it must work..also you have to check if entry amount is possible to your broker..so you have to normalize it.

      int margin=(int) MarketInfo(_Symbol,MODE_MARGINREQUIRED);
         Entry_Amount=(Entry_Percent/100)*AccountEquity()/margin;}
ADD THIS--->        Entry_Amount = NormalizeEntrySize(Entry_Amount);

add this


and add this outside ontick

double NormalizeEntrySize(double size) {
   double minlot  = MarketInfo(_Symbol, MODE_MINLOT);
   double maxlot  = MarketInfo(_Symbol, MODE_MAXLOT);
   double lotstep = MarketInfo(_Symbol, MODE_LOTSTEP);

   if (size <= minlot)
       return (minlot);

   int steps = (int) MathRound((size - minlot) / lotstep);
   size = minlot + steps * lotstep;

   if (size >= maxlot)
       size = maxlot;
       
   size = NormalizeDouble(size, digits);   

   return (size);
}   

Re: Risk Percent

So i did the change, but it seems like the Entry_Amount error is still the problem.

So i removed the static from the Entry_Amount

//
// EA Studio Portfolio Expert Advisor
//
// Created with: Expert Advisor Studio
// Website: https://eaforexacademy.com/expert-advisor-studio/
//
// Copyright 2019, Forex Software Ltd.
//
// This Portfolio Expert works in MetaTrader 4.
// It opens separate positions for each strategy.
// Every position has an unique magic number,
// which corresponds to the index of the strategy.
//

#property copyright "Forex Software Ltd."
#property version   "2.4"
#property strict

input double Entry_Amount      = 0.01; // Entry lots <<<<<<<<<<<<<<Removed static
static input int    Base_Magic_Number = 100;  // Base Magic Number

#define TRADE_RETRY_COUNT 4
#define TRADE_RETRY_WAIT  100
#define OP_FLAT           -1

// Session time is set in seconds from 00:00
const int sessionSundayOpen           = 0;     // 00:00
const int sessionSundayClose          = 86400; // 24:00
const int sessionMondayThursdayOpen   = 36000; // 10:00
const int sessionMondayThursdayClose  = 61200; // 17:00
const int sessionFridayOpen           = 36000; // 10:00
const int sessionFridayClose          = 61200; // 17:00
const bool sessionIgnoreSunday        = true;
const bool sessionCloseAtSessionClose = false;
const bool sessionCloseAtFridayClose  = false;

input bool                usePercent                        = true;                // Use Risk Percent base on AccountBalance
input double               Entry_Percent              = 2.00;                 // ENTRY PERCENT



const int    strategiesCount = 10;
const double sigma           = 0.000001;

datetime barTime;
int      digits;
double   stopLevel;
double   pip;
bool     setProtectionSeparately = false;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+


Added the normalize in, and the last part outside ontick



//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()

  {
   if(IsForceSessionClose())
     {
      CloseAllPositions();
      return;
     }

   if(Time[0]>barTime)
     {
      barTime=Time[0];
      OnBar();
     }
     
   if(usePercent==true)
      {
      int margin=(int) MarketInfo(_Symbol,MODE_MARGINREQUIRED);
         Entry_Amount =(Entry_Percent/100)*AccountEquity()/margin;
         Entry_Amount = NormalizeEntrySize(Entry_Amount);
      }
    
  }
  
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
  
  
 double NormalizeEntrySize(double size) {
   double minlot  = MarketInfo(_Symbol, MODE_MINLOT);
   double maxlot  = MarketInfo(_Symbol, MODE_MAXLOT);
   double lotstep = MarketInfo(_Symbol, MODE_LOTSTEP);

   if (size <= minlot)
       return (minlot);

   int steps = (int) MathRound((size - minlot) / lotstep);
   size = minlot + steps * lotstep;

   if (size >= maxlot)
       size = maxlot;
       
   size = NormalizeDouble(size, digits);   

   return (size);
}    
  
  
  
  
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

Have i forgot something?

Thanks guys smile

Re: Risk Percent

send error code.

10 (edited by Riuzk 2019-10-17 18:30:19)

Re: Risk Percent

Error: 'Entry_Amount' - constant cannot be modified

Picture of error:
https://imgur.com/a/7Kcipnt

Post's attachments

Error.png
Error.png 8.07 kb, file has never been downloaded. 

You don't have the permssions to download the attachments of this post.

11 (edited by Riuzk 2019-10-17 18:48:53)

Re: Risk Percent

Here is a picture of the whole EA

https://imgur.com/a/zoNr4kh

Post's attachments

EA Error.png 1.81 mb, file has never been downloaded. 

You don't have the permssions to download the attachments of this post.

12 (edited by Roughey 2019-10-17 21:21:42)

Re: Risk Percent

you are using Entry_Amount 2 times.. one time for your calculation and one time here

void OpenPosition(Signal &signal)
  {
   for(int attempt=0; attempt<TRADE_RETRY_COUNT; attempt++)
     {
      int    ticket     = 0;
      int    lastError  = 0;
      bool   modified   = false;
      int    command    = OrderDirectionToCommand(signal.Direction);
      double amount     = Entry_Amount;

So he is taking the 0,01 lots.


So you make it like this

#define OP_FLAT           -1

// Session time is set in seconds from 00:00
const int sessionSundayOpen           = 0;     // 00:00
const int sessionSundayClose          = 86400; // 24:00
const int sessionMondayThursdayOpen   = 36000; // 10:00
const int sessionMondayThursdayClose  = 61200; // 17:00
const int sessionFridayOpen           = 36000; // 10:00
const int sessionFridayClose          = 61200; // 17:00
const bool sessionIgnoreSunday        = true;
const bool sessionCloseAtSessionClose = false;
const bool sessionCloseAtFridayClose  = false;


input bool useFixLot = false; //Use Fix Lot
input double FixLot = 0.01; // Fix Lotsize
input bool                usePercent                        = true;                // Use Risk Percent base on AccountBalance
input double             Entry_Percent              = 2.00;                 // ENTRY PERCENT



const int    strategiesCount = 10;
const double sigma           = 0.000001;

datetime barTime;
int      digits;
double   stopLevel;
double   pip;
bool     setProtectionSeparately = false;
double Entry_Amount;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

AND IN ONTICK ADD THIS

if(usePercent==true)
      {
      int margin=(int) MarketInfo(_Symbol,MODE_MARGINREQUIRED);
         Entry_Amount =(Entry_Percent/100)*AccountEquity()/margin;
         Entry_Amount = NormalizeEntrySize(Entry_Amount);
Comment("Next Lotsize: "+DoubleToString(Entry_Amount));    <---Optional
      }
if(useFixLot == true)
{
Entry_Amount = FixLot;
}

This must working!!!

Re: Risk Percent

Roughey! It finally works!

Did several tests, and it seems like it works perfectly. Will be putting out some EA's next week and see how it goes.

Thank you again for helping me out, really appreciate it Roughey.

Re: Risk Percent

One more thing, if it's not to much to ask.

Is it possible to make the EA only have 1 trade open at once?

So if there is an open position no new trade will be executed before the old position is closed

Thanks.

Re: Risk Percent

Hello Roughey,

So i have been trying out the code for one week now, and it works, but there is still something missing.

When i put 10 in the Entry Percent input, the EA dont risk 10% of the account balance/equity but risk only 2-3%.


Why and do i miss something?


Thanks and happy weekend guys!

Re: Risk Percent

is it not possible to add the percentage risk as a trade option into the expert advisor?

Re: Risk Percent

What will happen if you enter 50% and run 3 experts?

18 (edited by mentosan 2021-04-25 08:35:27)

Re: Risk Percent

Mr. Popov I was thinking to add 5 experts with 1%-2% but anyway, it is ok also to have a code similar to the post from Roughey. Unfortunately, I inserted several times in the last year and it is not working for me. And I have no idea about programming...

Please, if is not such a big work for you, just give us a general code (which works) to be inserted manually..

thanks
Sebastian