¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io

Get and close all positions at a specific time


 

Hi,

I want to retrieve all open positions for a contract and then close them if the time is close to market closure (like 3:45 pm). Is there a way to do that in tws python api?


 

Take a look at the of the API Reference Guide.

When you place orders, you can also use to attach a condition for when the order should become active. One such condition is the TimeCondition which allows you to place an order sometime throughout the day but that does not become active until 3:45pm (or any other time).

´³¨¹°ù²µ±ð²Ô


Nick
 

¿ªÔÆÌåÓý

You could have the exit orders in an OCA group and add one more to buy/sell at market with a "good after" time of 3:45.


On 10/20/2021 3:38 PM, movais996@... wrote:

Hi,

I want to retrieve all open positions for a contract and then close them if the time is close to market closure (like 3:45 pm). Is there a way to do that in tws python api?



 

Thanks Jurgen!
I saw your approach and it's a really good one. However my use-case turned out to be really straight forward (cancel all api and tws orders and close all positions at 3:45). So I ended up using reqGlobalCancel() for cancelling orders and reqAccountUpdated() alongwith updatePortfolio() to get positions on each entity and place orders opposite to positions.??


 

Your approach will work most of the time, but things do go wrong and you exposure yourself to some degree of risk that your orders and positions do not get closed and will stay open past the end of the trading session:
  • Your power goes out or your application crashes
  • Your TWS locks up or loses connection with IBKR
  • Your network or your ISP is down around 3:45pm
  • ...
The combination of OCA groups and conditional orders allows you to define the exit condition for each position so that it is executed by IBKR without you(r application) having to be around,
´³¨¹°ù²µ±ð²Ô