Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trouble with reversing current order

Hello, I am new to Quantopian and am having a little trouble.

I am trying to switch between a long position (of 1) to a short position (of -1) or vice versa.

This is how I created the order pointer (code is run at market open to refresh, I was having trouble with the futures contract being canceled, I think this was caused by that future period ending? But running at market open seems to have solved that issue)

context.future = continuous_future('YM', roll='calendar')  
context.primary = data.current(context.future, 'contract')  

Then every hour I ran some logic and if conditions are met I would reverse the current position.

if context.numOfFutures > 0: # current position is LONG --> switching to SHORT  
                context.numOfFutures = -1  
                context.shortCount += 1  
                order_target(context.primary,-1)  
                print("completed a short")  
        else: # current position is SHORT --> switching to LONG  
                context.numOfFutures = 1  
                context.longCount += 1  
               order_target(context.primary,1)  
                print("completed a long")  

What I think is happening here is that I have a portfolio position of 1, then reverse and I go to a target position of -1, and when reversed again go to a target position of 1 again.

But on the graph instead of seeing my longs and shorts switch from 1 to -1, there are times when there are 0 positions for days or weeks in the middle of the year. This happens multiples and makes me think I am not truly swapping but instead selling out and then buying back in again after a few days.

The graph is created from the context.longCount and context.shortCount counters that are incremented during a long/short trade then recorded with:
def record_vars(context,data): record(long_count=context.longCount, short_count=context.shortCount) context.longCount = 0 context.shortCount = 0 Which is triggered every market close:
schedule_function(func=record_vars, date_rule=date_rules.every_day(), time_rule=time_rules.market_close())

I have read around the forum pages a bit but did not find an exact fix or solution for this that made sense to me.

In conclusion, my goal would be to see on the chart that I am in either a long or short position at all times.
I appreciate any suggestions you guys can throw my way.

P.S
Is there any way to see when an order has been completed?