[mql5] How to plot positions profit in % of the margin ?

 

Hello!

While developing an expert advisor that is becoming quite complex, I thought it was a good idea to plot the profit of the positions in percent of the free margin.

This indicator would help to understand visually what's happening in specific cases. It is intended to work in indicator_separate_window mode.

For now, my OnCalculate function looks like this:

    if(IsStopped()) return (0); 
    
    double profit = 0.0;
    int    start;
    
    if(prev_calculated == 0)
        start = 10; //rates_total - 1000;
    else
      start = prev_calculated - 1;
      
    for(int i = start; i < rates_total && !IsStopped(); i++) {
    
        for(int p = 0; p < PositionsTotal(); p++) {
        
            BufferLongProfit[p]    = EMPTY_VALUE;
            BufferShortProfit[p]   = EMPTY_VALUE;
            BufferOverallProfit[p] = EMPTY_VALUE;
            
            if(PositionInfo.SelectByIndex(i)) {
            
                if(InputMagic == 0 || PositionInfo.Magic() == InputMagic) {
                    
                    profit = PositionInfo.Profit();

                    if(PositionInfo.Type() == POSITION_TYPE_BUY)  BufferLongProfit[p]  += profit;
                    if(PositionInfo.Type() == POSITION_TYPE_SELL) BufferShortProfit[p] += profit;
                    BufferOverallProfit[i] += profit;
                }
            }
        }
    }
    return(rates_total);

Here is the OnInit function:

    IndicatorSetInteger(INDICATOR_DIGITS, Digits());
    
    SetIndexBuffer(0, BufferLongProfit   , INDICATOR_DATA);
    SetIndexBuffer(1, BufferShortProfit  , INDICATOR_DATA);
    SetIndexBuffer(2, BufferOverallProfit, INDICATOR_DATA);
    
    PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, 0);
    PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, 0);
    PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, 0);

    
    return(INIT_SUCCEEDED);

I get no errors, but nothing is displayed when used in a ea.


Any ideas on what I'm doing wrong?

Documentation on MQL5: Language Basics / Functions / Event Handling Functions
Documentation on MQL5: Language Basics / Functions / Event Handling Functions
  • www.mql5.com
Event Handling Functions - Functions - Language Basics - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5