#property indicator_separate_window

#property indicator_buffers 1
#property indicator_color1 Yellow

//---- input parameters
extern int BBPeriod        = 20;
extern int StdDeviation    = 2;

//---- buffers
double BLGBuffer[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init() {
    string short_name;
    
    SetIndexStyle(0,DRAW_LINE);
    SetIndexBuffer(0,BLGBuffer);

    short_name="BBpB("+BBPeriod+","+StdDeviation+")";
    IndicatorShortName(short_name);
    SetIndexLabel(0,short_name);

    return(0);
}


int start() {

    // Figure out how many bars need to be calculated
    // If one or more bars have already been calculated, recalculate
    // last complete bar.
    // This is done incase the indicator was busy and a tick was skipped.
    int iBarsToCalc = Bars - IndicatorCounted() - 1;
    if (iBarsToCalc < Bars - 1)    iBarsToCalc--;
    
    // Iterate over all the bars, from oldest to newest
    for (int i=iBarsToCalc;i>=0;i--) {
    
        // Get values for upper and lower bars
        double dUpperBand = iBands(NULL,0,BBPeriod,StdDeviation,0,PRICE_CLOSE,MODE_UPPER,i);
        double dLowerBand = iBands(NULL,0,BBPeriod,StdDeviation,0,PRICE_CLOSE,MODE_LOWER,i);
        
        // Calculate the difference and place it in the buffer.        
        BLGBuffer[i] = dUpperBand - dLowerBand;
    }

    // All done.    
    return(0);}