You covered quite a lot of ground with your question so let’s break it down into pieces. I won’t provide any code here, because most of what I have to say is completely theoretical. I just want to describe the framework. It’s up to you to determine the details.
First section: Scan all stocks, enter position in first stock that met your strategy criteria
Since you did not give any criteria I will manufacture my own. In regards to the part about entering a position on first stock that met the criteria. Well how do you pick one from the list of scan results? How do you sort them? You have to sort them before you can pick the “first”. So for our example we’ll say that condition one is the 50 ma above the 200 ma. Condition 2 is the 21 ema above the 50 ma. The trigger is when the 8 ema crosses above the 21 ema. So we have two conditions and one trigger. We set the scan up to find stocks the meet conditions 1 and 2. Let’s say the scan returns 500 stocks. How do you sort the list of results to “pick the first one”? You can create a ranking. Perhaps you take the distance between the 21 ema and the 5o ma and convert that to a percentage of the current close. You place that code in a custom column in the results screen. Then you sort your results by that custom column. Then you enter a conditional order for the one at the top of the list. The conditional order filters for conditions 1 and 2 and also contains the trigger. The end.
Second section: This section deals with the suggestion of using the API
This is an extremely advanced proposition. Someone would need to build the entire structure from the ground up. It would be either a web based application or a multi-platform application that would run locally on your computer. It would be completely independent of Thinkorswim. The cost to construct and maintain it would be enormous.
Conclusion:
For those interested in pursuing a truly Automated Trading System I recommend you move to a platform that already supports this. Such as NinjaTrader or TradeStation.
this is the video I’m referring to: https://www.youtube.com/watch?v=YW8ruMckbEw&t=831s