Utilities

This section describes miscellaneous utility methods provided by tda-api. All utilities are presented under the Utils class:

class tda.utils.Utils(client, account_id)

Helper for placing orders on equities. Provides easy-to-use implementations for common tasks such as market and limit orders.

__init__(client, account_id)

Creates a new Utils instance. For convenience, this object assumes the user wants to work with a single account ID at a time.

set_account_id(account_id)

Set the account ID used by this Utils instance.

Get the Most Recent Order

For successfully placed orders, tda.client.Client.place_order() returns the ID of the newly created order, encoded in the headers. This method inspects the response and extracts the order ID from the contents, if it’s there. This order ID can then be used to monitor or modify the order as described in the Client documentation. Example usage:

# Assume client and order already exist and are valid
account_id = 123456
r = client.place_order(account_id, order)
assert r.ok, raise_for_status()
order_id = Utils(account_id, client).extract_order_id(r)
assert order_id is not None
Utils.extract_order_id(place_order_response)

Attempts to extract the order ID from a response object returned by Client.place_order(). Return None if the order location is not contained in the response.

Parameters:place_order_response – Order response as returned by Client.place_order(). Note this method requires that the order was successful.
Raises:ValueError – if the order was not succesful or if the order’s account ID is not equal to the account ID set in this Utils object.

For orders that were rejected or whose order responses for whatever other reason might not contain the order ID, we can do a best-effort lookup using this method:

Utils.find_most_recent_order(*, symbol=None, quantity=None, instruction=None, order_type=None, lookback_window=datetime.timedelta(days=1))

When placing orders, the TDA API does not always return the order ID of the newly placed order, especially when the order was rejected. This means if we want to make extra sure of its status, we have to take a guess as to which order we just placed. This method simplifies things by returning the most recently-placed order with the given order signature.

Note: This method cannot guarantee that the calling process was the one which placed an order. This means that if there are multiple sources of orders, this method may return an order which was placed by another process.

Parameters:
  • symbol – Limit search to orders for this symbol.
  • quantity – Limit search to orders of this quantity.
  • instruction – Limit search to orders with this instruction. See tda.orders.EquityOrderBuilder.Instruction
  • order_type – Limit search to orders with this order type. See tda.orders.EquityOrderBuilder.OrderType
  • lookback_window – Limit search to orders entered less than this long ago. Note the TDA API does not provide orders older than 60 days.