Traverse through all the stock in watchlist for count

Hi All,

I am trying to go through given watchlist, calculate 50 days SMA for today and have a count if todays price is greater the sma calculated and print it.

Code which I tried:

_SECTION_BEGIN("Count Stocks Above 50 SMA");

watchlist="MasterList";
// Define the period for the SMA
smaPeriod = 50;

// Calculate the 50-period SMA for each stock
sma = MA(C, smaPeriod);

// Initialize a counter
aboveSmaCount = 0;
belowSmaCount = 0;
if(InWatchListName(watchlist)){
// Loop through all the symbols
for (i = 0; i < BarCount; i++) {
    // Check if the closing price is above the 50-period SMA for the current bar
    if (C[i] >= sma[i] ){
        aboveSmaCount = aboveSmaCount + 1;
        }else{
        belowSmaCount=belowSmaCount+1;
        }
}
}


// Display the count of stocks above the 50-period SMA
noOfStocks = "Stocks Above 50 SMA: " + aboveSmaCount+" Below "+belowSmaCount;
printf(noOfStocks);

_SECTION_END();

And is it possible to print only count in exploration.
I am able to print all stocks name but not only count.

_SECTION_BEGIN("Print SMA in Analysis");

// Define the period for the SMA
smaPeriod = 50;

// Calculate the 50-period SMA
sma = MA(C, smaPeriod);

Filter= C>=sma;
AddRankColumn();
// Plot the SMA on the chart
AddColumn(sma,"SMA 50");
AddColumn(C,"Price");

// Use printf to display the SMA values in the Analysis commentary
printf("SMA Values: %g", sma);

_SECTION_END();

This is gravely wrong, whatever you are trying to do.

instead search this function CategoryGetSymbols( categoryWatchlist, <number here> )
then use FOR loop to fetch each symbol and work on it

cgs = CategoryGetSymbols( categoryWatchlist, <find WL #>);
count = StrCount( cgs, ",") +1;   // count of all symbols
ctr = 0;                                        // counter for C > MA

for( i=0; ( cgss = StrExtract( cgs, i ) ) != ""; i++ ) {
    if( LastValue( C ) > LastValue( MA( Foreign( cgss, "C"), smaPeriod)) ){
        ctr += 1;
    }
}
// and count-ctr will give you C <= MA

If you run Exploration on N symbols, you will get N output * number of bars, assuming only last bar, you will get N rows.
so either choose current symbol OR run exploration on a fixed single symbol,
and use Foreign() to access other symbols like in previous post.