@erukumk the example you linked demonstrates the correct approach.
htps://forum.amibroker.com/t/correct-use-of-staticvaradd/29697
As was alredy discussed multiple times in the forum, you should use the #pragma sequence(scan, explore)
directive to run a scan followed by an exploration.
Below is a revised version of your original code. It works correctly only if your watchlist contains symbols that were actively traded during the entire date range of your analysis.
It uses your condition C != 0
to filter out stocks that are no longer/no yet trading, preventing them from being included in the count. (Note: if your watchlist doesn’t include all tickers that were active at the beginning of the selected date range, older dates will report fewer stocks than recent ones.)
Alternatively, if you're using Norgate data, I’ve left two commented lines in the code.
You can uncomment them when working with a "Current & Past" type watchlist. In that case, make sure to:
- Enable Pad & Align with a symbol that has a full price history (e.g.,
&SPX
)
- Replace the index symbol (e.g.,
$NDX
) with the one that corresponds to your selected watchlist ($SPX
, $RUA
, etc.)
Here’s the AFL code:
#pragma sequence(scan,explore)
Version( 6.40 );
//#include_once "Formulas\Norgate Data\Norgate Data Functions.afl"
if( Status( "action" ) == actionScan )
{
if( status( "stocknum" ) == 0 )
{
// remove any previous composite values
StaticVarRemove( "~Closeabv20ma" );
StaticVarRemove( "~SymbolCount" );
}
isValid = C != 0; // Check only stocks with a valid price
// isValid = NorgateIndexConstituentTimeSeries( "$NDX" ); // Change the constituency symbol in this line to refer to the used watchlist ($NDX, $SPX, $RUA, etc.)
StaticVarAdd( "~CloseAbv20ma", iif( isValid, Close > MA( Close, 20 ), 0 ) );
StaticVarAdd( "~SymbolCount", isValid );
_exit(); // quick exit in scan mode
}
Filter = 1;
// Retrieve the accumulated values
Closeabv20ma = StaticVarGet( "~Closeabv20ma" );
SymbolCount = StaticVarGet( "~SymbolCount" );
// Calculate the composite percentage
CompositePcClose = Nz( Closeabv20ma / ( SymbolCount ) * 100 );
// Exploration
Filter = Status( "stocknum" ) == 0; // without P&A will work properly only if the first stock in the WL is still traded!
SetOption( "NoDefaultColumns", True );
AddColumn( DateTime(), "Date", formatDateTime );
AddColumn( Closeabv20ma, "Stocks Above 20MA", 1 );
AddColumn( SymbolCount, "Total Stocks", 1 );
// AddColumn( CompositePcClose, "Percent Above 20MA", 1.2 );
AddColumn( CompositePcClose, "%", 1.2, colorWhite, colorLightBlue, 200, CompositePcClose );
if( Status( "action" ) == actionExplore )
SetSortColumns( -1 );