Moonshot Closing Limit Orders with Strategy File and Limit Order Best Practices

We are planning to implement limit orders with Alpaca within our moonshot strategy file. We have some working logic already that will place limit orders. The issue we ran into previously was the limit orders would stay open if they were not filled. We are trading on minute candles every minute.

I have considered writing a job that will cancel limit orders every other minute, to avoid accidently closing the limit order I just placed. I was wondering a few things:

  1. Is there a way to close limit orders within the strategy file besides kicking off a subprocess to execute a bash command? It would be neat if I could set a global within the moonshot class to let it tell blotter to close unfilled orders after so much time.
  2. Are there any best practices I should be aware of for placing limit orders using moonshot with alpaca?
  3. Are there any "gotchas" I should be aware of for placing limit orders using moonshot with alpaca?

Thanks!

With IBKR, you can set an expiration time on the order itself, but Alpaca doesn’t support this. So you would want to schedule a custom script to query and cancel orders according to whatever logic you want.

Not much to add on best practices or gotchas for limit orders.

Hey Brian,

I am writing a custom script to place stop orders on my positions. Is there a way to cancel orders based on type? I would love a one liner that could close all my limit orders.

I see that cancel_orders will cancel based on ref, sid, and account but that is all.

As always, thank you for your help!

The general approach you can use to get a one-liner is:

  1. write a custom script that does what you want;
  2. Create a .bashrc file. In it, define an alias that calls your script:
alias cancel_limit_orders="quantrocket satellite exec codeload.myscripts.my_cancel_limit_orders_function" 

That will allow you to call your function by typing

cancel_limit_orders

in a terminal.

Thank you for that info. I am currently writing the script and am curious if there is built in functionality for canceling just limit orders using python.

Just looking at the documentation, it looks like I would need to get the order ref's for the orders I would like to cancel as it doesn't appear to be a way to cancel orders based on OrderType.

Thanks!

You can query open orders (download_order_statuses(..., open_orders=True), filter the DataFrame by OrderType=="LMT", and cancel the resulting dataframe of limit orders by order ID (cancel_orders(order_ids=limit_orders.OrderId.tolist()).

API reference: download_order_statuses