Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
order in the future

Hi, is there a simple way to place an order in the future, say N days/minutes after the actual handle_data(...) execution?

4 responses

You can just use a counter. Add SPY to your universe, and handle_data will be called every minute. Then, you can order when N = dt. There are fancier ways, but if you just want to try something quickly, this will work.

Or you could use a priority queue of scheduled orders, with each entry of the form (scheduled_datetime, security, nshares). Every call to handle_data should run a loop to pop and submit the first order as long as the queue is not empty and the scheduled_datetime of that order is <=now. Make sure you have the timezones straight. See https://docs.python.org/2/library/heapq.html .

thnx, I'll keep it simple. A counter incremented every loop and deadlines in a dictionary where keys are the name of security to sell.

If I say you can do it, I can do it. I implemented a scheduled orders time-based priority queue, using the standard Python heapq package. To use it, one line must be placed in initialize, one in handle_data or scheduled with schedule_function, three import lines at the beginning; the rest of the code may be pasted at the end.

The following functions are available:

  • schedule_order(when, security, nshares) schedules an order to be submitted at or after the specified datetime; when may be a datetime or a string containing a date with or without time;
  • scheduled_orders(context) returns a time-sorted list of scheduled orders, may also be used in conditions to find out if there are any;
  • submit_scheduled_orders(context, data), placed in handle_data or scheduled with schedule_function, calls order to submit all the orders scheduled for "now" or before "now";
  • list_scheduled_orders(context, data) lists the scheduled orders with log.info;
  • cancel_scheduled_orders(context, data).

The latter two may be called from anywhere (after the queue is initialized) or scheduled with schedule_function to run at the end of each day, week, etc.

Some use cases:

  • schedule orders from anywhere: initialize, before_trading_start, handle_data, or your rebalance
  • don't worry whether the scheduled time falls within trading hours
  • schedule single or multiple orders for a single or multiple times:
    • a buy order to run in 3 days (when your cash is settled)
    • a sequence of identical orders every minute or 5 (to break up a large trade), or every week, or every 365 days
    • a sequence of small orders, of identical or random sizes, at random intervals that hopefully HFT traders won't predict
    • a flurry of small orders now, to reduce volume slippage.