This very simple script generates Buy/Sell signals for the very last bar only. It is designed to run on live charts.
How do I backtest this type of scripts?
The backtester runs it only once and reports the signals of the last bar only even if I set range to "All quotes". I need to make backtester iterate through all bars, and evaluate this script as if each of these bars was the last one. Is there a way to do this?
The script loads all essentials variables in static vars and continues on the next cycle.
It makes a BUY if the last bar is bullish. Holds the trade for 4 bars and then sells. It keeps only one position open. (Of course this is only an example. Please do not try to optimise this and make it into a formula. this is not the point.)
You can run it with bar replay to see it working.
SetBarsRequired( sbrAll, sbrAll );
bi = BarCount - 1;
Buy = Nz( StaticVarGet( "buy" ) );
Sell = Nz( StaticVarGet( "sell" ) );
long_bar = Nz( StaticVarGet( "long_bar" ) );
prev_barcount = Nz( StaticVarGet( "prev_barcount" ) );
// make it more elegant
if( long_bar > prev_barcount ) // we have garbage from a previous run. We need to reset the static vars
{
StaticVarRemove( "*" );
Buy = Nz( StaticVarGet( "buy" ) );
Sell = Nz( StaticVarGet( "sell" ) );
long_bar = Nz( StaticVarGet( "long_bar" ) );
prev_barcount = Nz( StaticVarGet( "prev_barcount" ) );
}
if( prev_barcount != Barcount ) // we have a new bar
{
// The new bars of the static arrays are not blank. They have the same values like the previous bar.
// So we have to detect when new bars appear, and initiallize them.
Buy[bi] = false;
sell[bi] = false;
printf( "We have a new bar !!! \n" );
}
if( long_bar == 0 ) // no open position
{
// Now set the signal of the last bar, based on our rules (every BULL bar is a BUY signal)
if( O[bi] < C[bi] )
{
Buy[bi] = True;
Long_bar = bi; // always the last bar
}
}
else // we have open position
if( long_bar < ( BarCount - 4 ) ) // hold for 4 bars
{
sell[bi] = True;
long_bar = 0;
}
/* Plot Buy/Sell Signal Arrows */
shape = Buy * shapeUpArrow;
PlotShapes( shape, colorGreen, 0, Low );
shape = Sell * shapeDownArrow;
PlotShapes( shape, colorRed, 0, High );
StaticVarSet( "buy", buy );
StaticVarSet( "sell", sell );
StaticVarSet( "long_bar", long_bar );
StaticVarSet( "prev_barcount", BarCount );
SetChartOptions( 0, chartShowArrows | chartShowDates );
_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) );
Plot( C, "Close", ParamColor( "Color", colorDefault ), styleNoTitle | ParamStyle( "Style" ) | GetPriceStyle() );