Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How do I check if I have already placed an order on a specific stock today?

I want to place a limit order that will be active for 5 minutes, then it kills the order if not filled in 5 minutes. I can do this without a problem but once I kill the order, I am no longer registering that I have any orders, and so when myfunc() runs again checking for open orders it doesn't detect any and places another trade. myfunc() runs every minute for the first 1hr of trading because that is my Target entry. The problem is I can't halt the entire function because I am running the same logic for all of my universe to determine buying and selling.

def myfunc(context, data):
for stock in context.security_list:
if has_orders(stock):
print('has open orders - doing nothing!')
elif (currentHigh>meanPrice) & (currentLow<meanPrice):
order(stock, sharesToShort,limit_price=entryLimit)#, style=LimitOrder(entryLimit))

10 responses

one idea is to use the context to store the current shares that you own in the context and to look for that changing to know if you filled the order or not

The only problem, I want to trade only the first sma cross of the day IF it occurs in the first hour. I place a limit order and give it 5 minutes to fill before cancelling the order. Regardless of whether I have shares or not, I do not want to place another order on a second cross in the first hour.

Examples..

1) Price crosses sma at 9:45am, I place a limit order and get a partial fill, if it crosses again before 10:30am and I have shares already, it does not buy more.

2) Price crossess sma at 9:45am, I place a limit order and NONE are filled, if it crosses again before 10:30am, I still don't want to place another order but I don't know how to do this.

Basically, I want to buy ONLY at the first sma cross of the day if it occurs before 10:30am.

Thanks for the response! Hopefully this will clear up my question a bit

At the beginning of the day, set a boolean value to false:

context.did_trade = False  

When you cross the first time, set a boolean value in the context.

if not context.did_trade:  
    context.did_trade = True  
    do_order(...)  

Here, longs() corresponds to your myfunc(). Stocks are stored in a dictionary with an integer representing the number of days, counter. Those are increased each day until waits_max reached when they are removed. (You would want waits_max to be 1 instead of 3). Best way to check this out would be to click in the margin on line numbers to set breakpoint(s) to see what's happening. Type variables in the debugger console prompt that appears and hit [Enter] and/or enter them in the watch window.

def initialize(context):  
    context.waits     = {}  
    context.waits_max = 3          # trading days

def longs(context, data):  
    value = context.portfolio.cash / len(context.longs)

    for s in context.longs:  # s for stock or security  
        if not data.can_trade(s): continue  
        if get_open_orders(s):    continue  
        if s in context.waits:    continue      # Was ordered, now waiting  
        if s in context.portfolio.positions: continue  
        order_value(s, value)  
        wait(context, s, 1)         # start waiting

def before_trading_start(context, data):  
    wait(context)    # Increment any that are present

def wait(c, sec=None, action=None):  
    if sec and action:  
        if action == 1:  
            c.waits[sec] = 1        # start wait  
        elif action == 0:  
            del c.waits[sec]        # end wait  
    else:  
        for sec in c.waits.copy():  
            if c.waits[sec] > c.waits_max:  
                del c.waits[sec]  
            else:  
                c.waits[sec] += 1   # increment  

since you are probably monitoring multiple stocks, you can use a dictionary to keep track

This is just pseudo code to illustrate the point.

context.did_trade = {}  
if not context.did_trade.get(symbol):  
   if crosses(symbol, data):  
       context.did_trade[symbol] = True  
       do_order(symbol)  

My context is set to a securities list,

for stock in context.securities_list: blah blah blah logic ... make the trade

Could I send just the specific stock?

If I set the context.did_trade as you said would that stop all other stocks from being traded as well? Or would that specify the specific stock that was in my securities_list?

I can post some code if this doesn't make much since.

Appreciate the help!!

The continuation of your answers just appeared to me, so ignore the previous post ^^

Thank you, I believe I get the idea now!

haha ok cool I was typing on my phone so the follow up reply was a little slow

No worries, I really appreciate the help, I definitely need it!

If you don't mind me asking.. how long have you been using Quantopian? / Is it your full time gig?

I haven't been programming very long but haven't left my computer in about 4 months and have learned a ton. My original focus was on creating loops with mixes of variables to find the best weighted differences, then I recently found Quantopian and think I might change my approach.

Any tips for a newbie? :)

I just do this as a side hobby and hardly have time for it. Professionally, I'm a Python expert.

Don't really have any tips other than be careful with low volume stocks; the buy/sell prices tend to be optimistic because you will piggyback transactions of a shrewd trader. If you have unfilled orders in the logs when you back test then it basically means you cannot trust the results. Also make sure the leverage stays below one. I put an assert in my code that will error if my cash goes below zero.