Backtest Watchlist Ranked In Order of Original Symbol Entry

I am struggling to control the ranking of buy orders based on the original stored watchlist symbol order. When there are more buy signals than the max positions permits, I want the system to select the buy signals from the watchlist based on the order in which they were stored. Not the default alphabetical(?) sort. Here is the code I have tried:

wlnumber = CategoryFind("Top 22 + SPY + QQQ", categoryWatchlist );
symbolIndex = StaticVarGet("WLIndex_" + Name());

if (Status("stocknum") == 0)
{
    StaticVarRemove("WLIndex_*");
    list = CategoryGetSymbols(categoryWatchlist, wlnumber);
    for (i = 0; (symbol = StrExtract(list, i)) != ""; i++)
        StaticVarSet("WLIndex_" + symbol, i + 1); // +1 to avoid zero
}

PositionScore = 10000 - symbolIndex;

Thanks in advance for your help

I don't believe I've ever seen any documentation that guarantees the order of the symbols returned by CategoryGetSymbols. I agree that it seems to be sorted alphabetically, but it's risky to write code that assumes any particular order.

As an alternative, you could read the watchlist file yourself, as .tls files are simply text files with one symbol per line. First symbol in the file would have position score 10000, next is 9999, etc.

1 Like

Symbols from watchlists ARE returned in original order. This can be easily verified using code like this:

_N(symbols = GetCategorySymbols(categoryWatchlist, 1));

printf("%s", symbols );

Note that only watchlists have "their order". Other categories (groups, markets, etc) don't have "ordering" - they use alphabetical order.

This of course assumes that you added symbols in NON-alpha order (you can run exploration, sort say by close then add symbols to new watch list using right click menu).

Your code is using static variables for no reason. You don't need to use static variables at all. You don't need Status() calls. All you need is to find index of symbol on the list.

function WhichOneOnTheWatchlist( num )
{
   symbols = GetCategorySymbols( categoryWatchlist, num );
   
   result = -1;
   
   n = Name();
   
   for( i = 0; ( sym = StrExtract( symbols, i ) ) != ""; i++ )
   {
       if( sym == n ) { result = i; break; };
   }

   return result;
} 

_N(symbols = GetCategorySymbols(categoryWatchlist, 1));

which = WhichOneOnTheWatchlist( 1 );

printf( "Watchlist content: %s\n\n", symbols );
printf( "Current symbol %s is %g on the watch list (zero-based index)\n", Name(), which );

// You can use that for position score if you wish
PositionScore = 10000 - which; // 

Now you can use value returned by WhichOneOnTheWatchList() function for your position score.

3 Likes

Thank you Tomasz!