// see-the-arrays.afl
// Part 8 - The Array Model
//
// Purpose:  make the array model visible. Every line below produces a whole
//           column of numbers - one value for every bar - and the title
//           reads those columns back at whichever bar you select.
// Assumes:  any symbol, any interval. A deliberately short average period is
//           used so the empty warm-up bars are easy to find.
// Apply:    Formula Editor -> Apply indicator, then click along the chart and
//           watch every number in the title change together.

_SECTION_BEGIN( "See The Arrays" );

// ---------------------------------------------------------------------------
// Settings
// ---------------------------------------------------------------------------

AvgPeriod = 3;   // small on purpose: the warm-up is then only two bars long

// ---------------------------------------------------------------------------
// Four arrays, built one from another
// ---------------------------------------------------------------------------

// High and Low are built-in arrays. Adding them produces a temporary array of
// the same length; dividing that by 2 produces another. One line, two whole
// array operations, no loop anywhere.
MidPrice = ( High + Low ) / 2;

// MA() reads one array and returns another of exactly the same length.
Average = MA( Close, AvgPeriod );

// Element-wise subtraction: bar 0 minus bar 0, bar 1 minus bar 1, and so on.
// Where Average is empty the difference is empty too - that is Null spreading.
Gap = Close - Average;

// ---------------------------------------------------------------------------
// Drawing
// ---------------------------------------------------------------------------

Plot( Close,    "Close",                    colorDefault, styleCandle );
Plot( MidPrice, "(High+Low)/2",             colorOrange,  styleLine );
Plot( Average,  "MA(Close," + AvgPeriod + ")", colorBlue, styleLine | styleThick );

// Gap is drawn on its own scale so that a small difference in price does not
// have to share an axis with the price itself.
Plot( Gap, "Close - MA", colorGrey40, styleHistogram | styleOwnScale | styleNoLabel );

// ---------------------------------------------------------------------------
// Reading the arrays back
// ---------------------------------------------------------------------------

// BarCount is a single number: how many bars the arrays hold.
// BarIndex() is an array: the zero-based number of each bar.
// SelectedValue() collapses an array to the one value at the selected bar.
Title = StrFormat(
    "{{NAME}} {{DATE}}   bar %g of %g   Close %g   (H+L)/2 %g   MA %g   Close-MA %g",
    SelectedValue( BarIndex() ), BarCount, Close, MidPrice, Average, Gap );

_SECTION_END();
