Day trading: Close all open positions towards the end of a trading session

In day trading, it is common to close all open positions towards the end of the trading day.

Is there a good "Quantopian" way to do that?

And if there is not, what is the best way to get the minutes-until-session-end for a given asset and a given stock exchange?

4 responses

Hi Ralph,

In backtesting, it may not be possible in a robust fashion. The reason (I think) is that for an order to be filled, an historical trade ("event") must be encountered, to determine the fill price. There is no guarantee, for a given stock, that there will be trades between the point when you submit the closing order, and the end of the trading day.

For real-money trading with Interactive Brokers, it should be a different situation, since a market will develop if you are willing to unload your positions at a steep enough loss.

Hi Ralph, something like this should work:

def initialize(context):
schedule_function(
func=close_all,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_close(minutes=25)
)

def close_all(context, data):
for equity in context.portfolio.positions:
order_percent(equity, 0)


is there a way to check if profit first? then close all?

Regards

This function returns PnL, can also be made a single line:
https://www.quantopian.com/posts/pnl

This, related, uses the same:
https://www.quantopian.com/posts/record-pnl-per-stock