How to create the Bollinger Bands using the Close price

How to create the bollinger band just use the last bar Close price written as a StyleThick and only shown the length of the last 10 bars?

Pls find attached the file for your easy to know what I mean.
ami%20bb%20resize

September 29, 2018 3:33 AM

@graceleung it is not very difficult.

This KB article will show you how to draw an indicator only for some selected bars (in your case the last 10), leaving the remaining chart space unaffected.

Re the Bollinger Bands, please, see these examples.
To plot horizontal lines instead of the curves, the only change you have to do is to use the LastValue() of the arrays.

So, using some variables names from the cited examples, your code will probably have something like this:

// custom function definition
function LastNBars( array, bars )
{
    bi = BarIndex();
    lvbi = LastValue( bi );

    // use Null value for bars other than last N
    return IIf( bi > lvbi - bars, array, Null );
}

Plot( LastNBars( LastValue( BBandTop( P, Periods1, Width1 ) ), 10 ), "upperBB1", ColorUpper, Style1 );
1 Like

Hi Giueseppe,

Copied your code in. shown below error :

Error 30

Syntax error, identifier 'LastNBars' is undefined.

My code as below:

//_SECTION_BEGIN("Bollinger Bands1");
P = ParamField("Price field",-1) ;
Periods = Param("Periods", 60, 2, 600, 1 );
Width = Param("Width", 0.8, 0, 10, 0.05 );
Color = ParamColor("Color", colorOrange );
Style = ParamStyle("Style", StyleThick);
//Plot( BBandTop( P, Periods, Width ), "BBTop1", colorPink, styleLine  ); 
//Plot( BBandBot( P, Periods, Width ), "BBBot1" , colorYellow, styleLine  ); 
Plot( LastNBars( LastValue( BBandTop( P, Periods1, Width1 ) ), 10 ), "upperBB1", ColorUpper, Style1 );
_SECTION_END();

Many Thank You for Your Assis.

Solved, Thank you so much!

1 Like

The missing function is given in the Knowledge Base article

// comes from Knowledge Base article: http://www.amibroker.com/kb/2014/12/31/drawing-indicators-on-a-subset-of-visible-bars/
// custom function definition
function LastNBars( array, bars )
{
    bi = BarIndex();
    lvbi = LastValue( bi );

    // use Null value for bars other than last N
    return IIf( bi > lvbi - bars, array, Null );
}
1 Like