Update Watchlist from AFL Parameter

I am trying to update a watchlist from param. I am clearly missing something, it works, but you need to run exlpore twice or add foreign twice. Can someone point me in a direction to resolve this, currently it does what I want, but I know it must not be correct if I need to have two foreign statements and I would like to better understand this, thank you.

Stocks = CategoryFind("Test Stock",categorywatchlist);

stocklist      =ParamStr("Symbols","IBM,GE");

if ( Status( "stocknum" ) == 0 )
{
    CurrentStkList=GetCategorySymbols(categoryWatchlist,stocks);
     for ( i = 0; ( symbol = StrExtract( Currentstklist, i ) )  != "";  i++ )
    {
		CategoryRemoveSymbol(symbol,categoryWatchlist,Stocks);
	}		
	for ( i = 0; ( symbol = StrExtract( Stocklist, i ) )  != "";  i++ )
    {
		CategoryaddSymbol(symbol,categoryWatchlist,Stocks);
	}		
	 for ( i = 0; ( symbol = StrExtract( stocklist, i ) )  != "";  i++ )
    {
       
       t= Foreign( symbol,"C" );
       t= Foreign( symbol,"C" ); 
     }
}

Clarity is required even in asking questions. You don’t say what you expect and what you are getting instead.

Please follow this advice step by step:

"I am trying to update a watchlist from param."

this works, however to get result you must either run explore twice or include foreign statement twice. On the first call of Foreign the "t" is Null on the second call of Foreign, "t" equals the close of symbol.

I think the answer is to add

StockList=GetCategorySymbols(categoryWatchlist,stocks);

just before calling extract so information is not coming from paramstr.

No. Most frequent source of problems is that you assume something that is not th case in reality.

Adding random lines to your code is not the solution.

The solution is to debug your code so you see what is happening and start to understand.

To get better understanding of what is happening in your code and how functions work, use advice given here: How do I debug my formula?

True reasons of problems are typically (wrong) assumptions. Don't assume. Debug. Trace.

Many operations are asynchronous and multi threaded, they happen in parallel asynchronously in separate threads. You just can't assume serial single threaded op. Foreign is non blocking call. If data are not present in the database and require backfill then obviously data will arrive later when data source responds finally with the data. Proper settings like large enough in memory cache are essential, to keep data in RAM and not re-request them from disk or from remote source.

When the formula loads, does it load the watchlists also? Can I not update the watchlist in the afl? Should I update watchlist outside of the afl and then open afl?

If you change the watchlist that is being used in filter, how do I get it to refresh the data?

The "Apply To" list is evaluated BEFORE FORMULA is run.

Any changes that you make from the formula will be applied to the NEXT RUN (next scan/ exploration, whatever).