Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Setting a Stop Loss and Sell Limit at the same time?

Hi all,

Looping through multiple stocks, I'm having trouble understanding how context variables are set for each stock in order to use variables to set a stop loss AND sell limit.

Does anyone have a better suggestion then the code below for accomplishing my intent when purchasing a stock?

for stock in context.stock:

   if test:

                # need to calculate how many shares to buy  
                number_of_shares = int(cash/current_price)

                # place the buy order (positive = buy, negative = sell)  
                order(stock, +number_of_shares)

                # place stop loss order  
                order(stock, 0, style=StopOrder(stop_loss))

                # place sell limit order  
                order(stock, 0, style=LimitOrder(upper))  
6 responses

(Rainy Saturday afternoon). Here's some broad philosophies regarding stops (profit and loss).

[Ascend soapbox...]

Using stops for non-auto-algorithmic swing trading is a best practice. You pick your prices and place your orders and let the broker/exchange deal with the details. You come back every day or two and check to see what has transpired, reassess, readjust and repeat.

Using stops for auto-algorithmic trading is less clear as a best practice. If you trade in fear of being disconnected from the market and having a trade punch through your logical stops (usually for futures/FX trading) then maintaining loss stops can keep your sane. Maintaining stops mind you, you don't just plop in a stop and walk away. You need to adjust over time per the market's activity.

But if your auto-trading system retains a high quality connection rate, stops become less useful and more problematic. If your strategy is actively watching the market, watching your position, and watching your risk, then it itself can determine when it's time to exit. Minute granularity seems rather gross with regards to most people's ideas of "real time" trading. But for equities, minutely volatility is well with most strategies' risk parameters. Meaning that your algorithm can just watch the market and "stop out" with market orders when it deems fit to do so.

That said, normally you would wait for acknowledgement of a position before you submit protective stops and profit limits. I'd be curious as to Quantopian's plans regarding IB's ability to deal with bracket orders (OCO, OCA) style. There must be some discussion on this topi in the forum somewhere.

Are you performing a volatility arb by precalculating your stop loss and stop profit? (Narrow loss and profit levels?) Otherwise your stop loss would probably be wide enough to wait or calculate dynamically once a minute. Profit limits show up in the market's orderbook and can be hunted... If you intend to periodically shift your profit limits up then you may want to also dynamically calculate these and issue market orders on profit events.

[Descend soapbox...]

I see thanks for the information.

Would anyone know would I approach setting the price based on the purchased price to sell a bought security? (AKA saving variables with the purchase price and a saved calculated sale price) I'm confused about using context to accomplish this and have not been able to find a solution while reading the documentation/searching. Thanks!

You would use the cost_basis on the position to determine the purchase price. (See Help & API docs)

If position and no open orders for security: submit stop based on cost_basis

Q, can you set a filled_price in the order object for us?

Hello,

What you are asking for is a bracket order basically, as most have aptly pointed out. I've been working for the past few weeks to build a bracket order system. There are a lot of intricacies and quirks associated with this, and ideally it should be allowable as a order-type for live trading. But as of now, we have to implement ourselves. Several challenges:

1) You only want your stoploss and limit orders to become active (ie be put in as orders) IF your initial order executes. Problem with this is that sometimes you only get a partial fill and have to wait another bar or even more to get a full fill. This is less of an issue if you trade very liquid issues with lower volume fills. Nevertheless, you have to monitor this issue proactively to make sure your initial order fills before your bracket orders become active.

2) Once your bracket orders become active, you have to continue monitoring the stoploss and limit orders. If one of them executes, you want to automatically cancel the other. This is also something you have to proactively monitor.

Right now, I have a bracket object that takes in a order_entry (for the initial order fill), a stop price, a limit price, and empty variables for stop_order and limit_order id's. I keep a dict of bracket orders keyed by stock in context. I monitor this with a Update/Manage function at every bar. If my initial order is filled, I put in the orders for the stop and limit orders. If either the stop or limit order is filled, I cancel the other one. It's tough to do but possible.

I have not overcome the problem of getting only partially filled. I'm just ignoring it for now and using small size and liquid issues.