Of 50 shares, transmit only the first 5 to TWS

Good day to all,

can please help me here in the group. I have developed a strategy which buys the best five stocks from a list of stocks. I have managed the ranking in the backtest with "PositionScore".

I have the following questions for the group:

  1. how do I create a ranking for the explorer.
  2. how can I specify that I only want to submit the top five stocks from the list to TWS.

Thanks in advance for your help!
Michael

Here is my current code:

if( LastValue( Buy ) )
{
  ibc = GetTradingInterface("IB");

  // check if we are connected OK
  if( ibc.IsConnected() )
  {
     // check if we do not have already open position on this stock
     if( ibc.GetPositionSize( Name() ) == 0)
	{
		// transmit order
		ibc.PlaceOrder( Name(), "Buy", Percent_Equity, "MKT", 0, 0, "Day", True );
		
     }
  }
}


if( LastValue( Sell ) )
{
  ibc = GetTradingInterface("IB");

  // check if we are connected OK
  if( ibc.IsConnected() )
  {
     // check if we do not have already open position on this stock
     if( ibc.GetPositionSize( Name() ) > 0 )
     {
        // transmit order
        ibc.PlaceOrder( Name(), "Sell" , ibc.GetPositionSize( Name() ), "MKT", 0, 0, "Day", True );
     }
  }
}

First of all don't use your "current code" on real account. It is incorrect. GetPositionSize() reports data from TWS "Account" page. These data are DELAYED (in TWS itself, it has nothing to do with AmiBroker), therefore you should track positions YOURSELF and not trust TWS to provide immediate data, otherwise you would get repeated orders.

Use STATIC variables to store state. There are plenty of examples AmiBroker Users' Knowledge Base

Secondly you can and should keep track on number of positions, sent orders ALSO using Static variables. Again, check the examples AmiBroker Users' Knowledge Base

Ranking can be done using Static variables as well. Again, it is all described in the docs Ranking features

Hello Tomasz,

thank you very much for your message and helpful hints. I won't have used the current code version on a real account.

Further, I will definitely follow your recommendation to use STATIC variables to store state and track positions as well as orders sent. It is good to know that this is a better way to handle the data reliably and avoid repeated orders.

However, I must admit that as a non-programmer, I have difficulties in implementing all the commands correctly. The world of programming is still quite new to me, and I appreciate any further support and help.

I will check the resources you recommended: the AmiBroker Users' Knowledge Base and the Ranking documentation. I hope this will deepen my understanding and improve my implementation.

Thank you again for your time and kind assistance. If I have any further questions, I will be happy to contact you.

Yours sincerely,
Michael