RiskAdvisor

Download script
Author: Copyright � 2006, Arunas Pranckevicius (T-1000), Lithuania
RiskAdvisor

This script is designed as a smart risk management assistant for traders. Its primary goal is to analyze your current account status and provide precise recommendations on how much "Lot Size" (the volume of your trade) you should use, based on a specific percentage of risk you are willing to take.

Instead of letting you guess the trade size, the logic follows these professional steps:

1. Current Exposure Analysis

The tool first looks at all your currently open trades. It calculates how much "margin" or capital is already tied up in active positions. It specifically identifies trades that have a valid Stop Loss and determines how much potential capital is being "reserved" by your existing market commitments.

2. Available Capital Calculation

By subtracting your current margin (money locked in active trades) and the reserved margin from your total account balance, the script determines exactly how much "Free Money" you actually have left to work with. This ensures that the advice it gives you is based on your actual buying power, not just your total balance.

3. Dynamic Lot Sizing

Using the risk percentage you provide (e.g., 5%), the script performs a multi-step calculation:

  • Base Calculation: It calculates the maximum number of lots you can afford for a one-pip move based on your available free money.
  • Stop Loss Adjustment: It then scales that lot size down according to your specific Stop Lossピips. For example, if you have a wide stop loss, it will recommend a larger lot size; if you have a tight stop loss, it will recommend a smaller one.
  • Broker Constraints: The script automatically checks with your broker's rules to ensure the recommended lot size meets their minimum and maximum requirements (e.g., ensuring it doesn't suggest 0.05 lots on an account that only allows 0.10).

4. Safety Checks and Auto-Corrections

The logic includes "safety nets" to prevent over-leveraging:

  • Insufficient Funds: If your account balance is too low to open a trade with the requested parameters, it will notify you immediately.
  • Margin Starvation: If the calculated lot size would exceed your remaining margin requirements, the script automatically shrinks the lot size until it fits perfectly within your available funds.
  • Adjustment Logic: If the suggested lot size is smaller than the broker's minimum, the script attempts to intelligently recalculate a viable Stop Loss and Take Profit distance to make the trade possible.

5. Real-Time Reporting

Finally, the tool provides a clear summary on your trading screen. It displays your recommended Risk Percentage, the exact Lot Size you should use, and your target Take Profit and Stop Loss distances in pips. It also shows your "Reserved Margin" so you can see exactly how much of your capital is currently committed to the market.

Orders Execution
Checks for the total of open orders
Miscellaneous
It issuies visual alerts to the screen
9 Views
0 Downloads
0 Favorites
RiskAdvisor
//+------------------------------------------------------------------+
//|                                                  RiskAdvisor.mq4 |
//|       Copyright © 2006, Arunas Pranckevicius (T-1000), Lithuania |
//|                                            irc://irc.omnitel.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, Arunas Pranckevicius (T-1000), Lithuania"
#property link      "irc://irc.omnitel.net/forex"
#property show_inputs
#include <stderror.mqh>
extern int BalanceRiskPercent = 5;
extern int OrdersStopLossPips = 100;
extern int ProfitLossFactor = 3;
extern int OrdersLots = 1;


//+------------------------------------------------------------------------------+
//| script "Advise Lots Size and Stop Loss for orders on given Risk Percent"     |
//+------------------------------------------------------------------------------+
int start()
  {
   double TakeProfit = OrdersStopLossPips * ProfitLossFactor;
   double MaxLots;
   int FreeMoney;
   int StopLoss = OrdersStopLossPips;
   double Lots = OrdersLots;
   double LotSize=MarketInfo(Symbol(),MODE_LOTSIZE) / AccountLeverage();
   double MinLots=MarketInfo(Symbol(),MODE_MINLOT);
   double MaxLot=MarketInfo(Symbol(),MODE_MAXLOT);
   double LotStep=MarketInfo(Symbol(),MODE_LOTSTEP);
   double PipSize=MarketInfo(Symbol(),MODE_TICKVALUE);
   int TradeAllowed=MarketInfo(Symbol(),MODE_TRADEALLOWED);
   double Slippage=MarketInfo(Symbol(),MODE_SPREAD);
   double RequiredMargin=MarketInfo(Symbol(),MODE_MARGINREQUIRED);
   double Margin,ReservedMargin=0;
   int MinTakeProfit=TakeProfit / 2;
   int MinStopLoss=OrdersStopLossPips / 2;
   int    cmd,total;

//----
   total=OrdersTotal();
//----
   for(int i=0; i<total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         cmd=OrderType();
         //---- open working orders only are considered
         if(cmd==OP_BUY || cmd==OP_SELL)
           {
            //---- print selected order
            OrderPrint();
            PipSize=MarketInfo(OrderSymbol(),MODE_TICKVALUE);
            if(cmd==OP_BUY) 
            {
            if ((OrderOpenPrice() - OrderStopLoss()) / Point * PipSize * OrderLots() + OrderSwap() - OrderCommission() > AccountBalance() * 0.18 && OrderStopLoss() > Point)
               ReservedMargin += ((OrderOpenPrice() - OrderStopLoss()) / Point * PipSize * OrderLots() - OrderSwap() - OrderCommission());
            else Print ("Skipping out of Money Management order.");   
            }
            if(cmd==OP_SELL) 
            {
            if ((OrderStopLoss() - OrderOpenPrice()) / Point * PipSize * OrderLots() + OrderSwap() - OrderCommission() > AccountBalance() * 0.18 && OrderStopLoss() > Point)
               ReservedMargin += ((OrderStopLoss() - OrderOpenPrice()) / Point * PipSize * OrderLots() - OrderSwap() - OrderCommission());
            else Print ("Skipping out of Money Management order.");   
            }
           }
        }
      else { Print( "Error when order select ", GetLastError()); break; }
     }
//Print("Reserved Margin:",ReservedMargin);
PipSize=MarketInfo(Symbol(),MODE_TICKVALUE);
if (ReservedMargin <= AccountFreeMargin()) FreeMoney=AccountBalance() - AccountMargin() - ReservedMargin;
else FreeMoney=AccountBalance() - AccountMargin();
MaxLots=FreeMoney / 100 * BalanceRiskPercent / LotSize * PipSize ; //Max Lots for 1 pip market change
if (GetLastError() == ERR_ZERO_DIVIDE) {Print("Err: division by zero: FreeMoney:",FreeMoney," BalanceRiskPercent:",BalanceRiskPercent," LotSize:",LotSize);return(-1);}

Lots = MaxLots / StopLoss * PipSize; 
if (GetLastError() == ERR_ZERO_DIVIDE) {Print("Err: division by zero: MaxLots:",MaxLots," StopLoss:",StopLoss," Lots:",Lots," PipSize:",PipSize);return(-1);}
//Print("DEBUG: MaxLots=",MaxLots," PipSize=",PipSize," Lots=",Lots);

// Normalize Lots
if (MinLots == 1) Lots=MathAbs(Lots);
if (MinLots == 0.1) Lots=MathAbs(Lots * 10) / 10;
if (MinLots == 0.01) Lots=MathAbs(Lots * 100) / 100;
if (Lots == 0)
{
Alert(Symbol(),": There is not enough money for new trade!");
return(1);
}
if (Lots < MinLots) 
   //We have not much money left?! try to arrange new deposit stop loss/take profit
   {  
    StopLoss=MathAbs(StopLoss / (MinLots/Lots));
    if (GetLastError() == ERR_ZERO_DIVIDE) {Print("Err: division by zero: StopLoss:",StopLoss," Minlots:",MinLots," Lots:",Lots);return(-1);}
    if (StopLoss < Slippage * 2) StopLoss = Slippage * 2;
    TakeProfit= StopLoss * ProfitLossFactor;
    Lots=MinLots;
   }  

   if (AccountFreeMargin() < Lots * StopLoss * PipSize + Lots * RequiredMargin)
   //We have starving FREE MARGIN!
   {
      Margin=AccountFreeMargin() / (Lots * StopLoss * PipSize + Lots * RequiredMargin);
     if (GetLastError() == ERR_ZERO_DIVIDE) {Print("Err: division by zero: StopLoss:",StopLoss," Margin:",Margin," Lots:",Lots);return(-1);}
      Lots = Lots * Margin; // Recalculate lots size to fit margin requirements
   }   
   if (Lots > MaxLots) Lots = MaxLot; //We reached maximum size of order

   if (Lots > 1) Lots = NormalizeDouble(Lots,1); 
   if (Lots > 0.1 && Lots < 1) Lots = NormalizeDouble(Lots,1);
   if (Lots < 0.1) Lots = NormalizeDouble(Lots,2);
 //----
   if (ReservedMargin > AccountFreeMargin()) Comment("\n\n\nRecommended Orders Risk Info:\nRisk:",BalanceRiskPercent,"%\n","Lots:",Lots,"\nTake Profit in Pips:",TakeProfit,"\nStop Loss in Pips:",StopLoss,"\nReserved Margin: n/a due incorrect S/L in orders");
   else Comment("\n\n\nRecommended Orders Risk Info:\nRisk:",BalanceRiskPercent,"%\n","Lots:",Lots,"\nTake Profit in Pips:",TakeProfit,"\nStop Loss in Pips:",StopLoss,"\nReserved Margin:",ReservedMargin+AccountMargin()," ",AccountCurrency());
   return(0);
  }
//+------------------------------------------------------------------+

Comments