py_alpaca_api.trading.orders

Exceptions

ValidationError

Raised when input validation fails.

Classes

Requests

OrderModel

Orders

Functions

order_class_from_dict(→ OrderModel)

Creates an instance of OrderModel using the provided dictionary data.

Module Contents

exception py_alpaca_api.trading.orders.ValidationError[source]

Bases: PyAlpacaAPIError

Raised when input validation fails.

class py_alpaca_api.trading.orders.Requests[source]
request(method: str, url: str, headers: dict[str, str] | None = None, params: dict[str, str | bool | float | int] | None = None, json: dict[str, Any] | None = None, raw_response: bool = False)[source]

Execute HTTP request with retry logic.

Parameters:
  • method – A string representing the HTTP method to be used in the request.

  • url – A string representing the URL to send the request to.

  • headers – An optional dictionary containing the headers for the request.

  • params – An optional dictionary containing the query parameters for the request.

  • json – An optional dictionary containing the JSON payload for the request.

  • raw_response – If True, return the raw response object without status checks. Defaults to False.

Returns:

The response object returned by the server.

Raises:

APIRequestError – If the response status code is not one of the acceptable statuses (200, 204, 207) and raw_response is False.

class py_alpaca_api.trading.orders.OrderModel[source]
id: str
client_order_id: str
created_at: datetime.datetime
updated_at: datetime.datetime
submitted_at: datetime.datetime
filled_at: datetime.datetime
expired_at: datetime.datetime
canceled_at: datetime.datetime
failed_at: datetime.datetime
replaced_at: datetime.datetime
replaced_by: str
replaces: str
asset_id: str
symbol: str
asset_class: str
notional: float
qty: float
filled_qty: float
filled_avg_price: float
order_class: str
order_type: str
type: str
side: str
time_in_force: str
limit_price: float
stop_price: float
status: str
extended_hours: bool
legs: list[object]
trail_percent: float
trail_price: float
hwm: float
subtag: str
source: str
py_alpaca_api.trading.orders.order_class_from_dict(data_dict: dict) OrderModel[source]

Creates an instance of OrderModel using the provided dictionary data.

Parameters:

data_dict (Dict) – A dictionary containing the data used to create the OrderModel instance.

Returns:

An instance of OrderModel created using the provided data.

Return type:

OrderModel

Raises:

None

class py_alpaca_api.trading.orders.Orders(base_url: str, headers: dict[str, str])[source]
get_all_orders(status: str = 'open', limit: int = 50, after: str | None = None, until: str | None = None, direction: str = 'desc', nested: bool = False, symbols: str | None = None) list[py_alpaca_api.models.order_model.OrderModel][source]

Retrieves a list of orders for the account, filtered by the supplied parameters.

Parameters:
  • status – Order status to be queried. Options are ‘open’, ‘closed’, or ‘all’. Defaults to ‘open’.

  • limit – Maximum number of orders to return. Max is 500. Defaults to 50.

  • after – Filter for orders submitted after this timestamp (ISO 8601 format).

  • until – Filter for orders submitted until this timestamp (ISO 8601 format).

  • direction – Chronological order of response based on submission time. Options are ‘asc’ or ‘desc’. Defaults to ‘desc’.

  • nested – If True, multi-leg orders will be rolled up under the legs field of primary order. Defaults to False.

  • symbols – Comma-separated list of symbols to filter by (e.g., “AAPL,TSLA,MSFT”).

Returns:

List of OrderModel objects matching the query parameters.

Raises:
get_by_id(order_id: str, nested: bool = False) py_alpaca_api.models.order_model.OrderModel[source]

Retrieves order information by its ID.

Parameters:
  • order_id (str) – The ID of the order to retrieve.

  • nested (bool, optional) – Whether to include nested objects in the response. Defaults to False.

Returns:

An object representing the order information.

Return type:

OrderModel

Raises:

ValueError – If the request to retrieve order information fails.

cancel_by_id(order_id: str) str[source]

Cancel an order by its ID.

Parameters:

order_id (str) – The ID of the order to be cancelled.

Returns:

A message indicating the status of the cancellation.

Return type:

str

Raises:

Exception – If the cancellation request fails, an exception is raised with the error message.

cancel_all() str[source]

Cancels all open orders.

Returns:

A message indicating the number of orders that have been cancelled.

Return type:

str

Raises:

Exception – If the request to cancel orders is not successful, an exception is raised with the error message.

replace_order(order_id: str, qty: float | None = None, limit_price: float | None = None, stop_price: float | None = None, trail: float | None = None, time_in_force: str | None = None, client_order_id: str | None = None) py_alpaca_api.models.order_model.OrderModel[source]

Replace an existing order with updated parameters.

Parameters:
  • order_id – The ID of the order to replace.

  • qty – The new quantity for the order.

  • limit_price – The new limit price for limit orders.

  • stop_price – The new stop price for stop orders.

  • trail – The new trail amount for trailing stop orders (percent or price).

  • time_in_force – The new time in force for the order.

  • client_order_id – Optional client-assigned ID for the replacement order.

Returns:

The replaced order.

Return type:

OrderModel

Raises:
get_by_client_order_id(client_order_id: str) py_alpaca_api.models.order_model.OrderModel[source]

Retrieves order information by client order ID.

Note: This queries all orders and filters by client_order_id. The Alpaca API doesn’t have a direct endpoint for this.

Parameters:

client_order_id – The client-assigned ID of the order to retrieve.

Returns:

An object representing the order information.

Return type:

OrderModel

Raises:
cancel_by_client_order_id(client_order_id: str) str[source]

Cancel an order by its client order ID.

Note: This first retrieves the order by client_order_id, then cancels by ID.

Parameters:

client_order_id – The client-assigned ID of the order to be cancelled.

Returns:

A message indicating the status of the cancellation.

Return type:

str

Raises:
static check_for_order_errors(symbol: str, qty: float | None = None, notional: float | None = None, take_profit: float | None = None, stop_loss: float | None = None) None[source]

Checks for order errors based on the given parameters.

Parameters:
  • symbol (str) – The symbol for trading.

  • qty (float, optional) – The quantity of the order. Defaults to None.

  • notional (float, optional) – The notional value of the order. Defaults to None.

  • take_profit (float, optional) – The take profit value for the order. Defaults to None.

  • stop_loss (float, optional) – The stop loss value for the order. Defaults to None.

Raises:
  • ValueError – If symbol is not provided.

  • ValueError – If both qty and notional are provided or if neither is provided.

  • ValueError – If either take_profit or stop_loss is not provided.

  • ValueError – If both take_profit and stop_loss are not provided.

  • ValueError – If notional is provided or if qty is not an integer when both take_profit and

  • stop_loss are provided.

Returns:

None

market(symbol: str, qty: float | None = None, notional: float | None = None, take_profit: float | None = None, stop_loss: float | None = None, side: str = 'buy', time_in_force: str = 'day', extended_hours: bool = False, client_order_id: str | None = None, order_class: str | None = None) py_alpaca_api.models.order_model.OrderModel[source]

Submits a market order for a specified symbol.

Parameters:
  • symbol (str) – The symbol of the asset to trade.

  • qty (float, optional) – The quantity of the asset to trade. Either qty or notional must be provided, but not both. Defaults to None.

  • notional (float, optional) – The notional value of the asset to trade. Either qty or notional must be provided, but not both. Defaults to None.

  • take_profit (float, optional) – The take profit price for the order. Defaults to None.

  • stop_loss (float, optional) – The stop loss price for the order. Defaults to None.

  • side (str, optional) – The side of the order (buy/sell). Defaults to “buy”.

  • time_in_force (str, optional) – The time in force for the order (day/gtc/opg/ioc/fok). Defaults to “day”.

  • extended_hours (bool, optional) – Whether to trade during extended hours. Defaults to False.

  • client_order_id (str, optional) – Client-assigned ID for the order. Defaults to None.

  • order_class (str, optional) – Order class (simple/bracket/oco/oto). Defaults to None.

Returns:

An instance of the OrderModel representing the submitted order.

Return type:

OrderModel

limit(symbol: str, limit_price: float, qty: float | None = None, notional: float | None = None, take_profit: float | None = None, stop_loss: float | None = None, side: str = 'buy', time_in_force: str = 'day', extended_hours: bool = False, client_order_id: str | None = None, order_class: str | None = None) py_alpaca_api.models.order_model.OrderModel[source]

Limit order function that submits an order to buy or sell a specified symbol at a specified limit price.

Parameters:
  • symbol (str) – The symbol of the asset to trade.

  • limit_price (float) – The limit price at which to execute the order.

  • qty (float, optional) – The quantity of the asset to trade. Default is None.

  • notional (float, optional) – The amount of money to spend on the asset. Default is None.

  • take_profit (float, optional) – The price at which to set a take profit order. Default is None.

  • stop_loss (float, optional) – The price at which to set a stop loss order. Default is None.

  • side (str, optional) – The side of the order. Must be either “buy” or “sell”. Default is “buy”.

  • time_in_force (str, optional) – The duration of the order. Must be either “day” or “gtc” (good till canceled). Default is “day”.

  • extended_hours (bool, optional) – Whether to allow trading during extended hours. Default is False.

  • client_order_id (str, optional) – Client-assigned ID for the order. Defaults to None.

  • order_class (str, optional) – Order class (simple/bracket/oco/oto). Defaults to None.

Returns:

The submitted order.

Return type:

OrderModel

stop(symbol: str, stop_price: float, qty: float, side: str = 'buy', take_profit: float | None = None, stop_loss: float | None = None, time_in_force: str = 'day', extended_hours: bool = False, client_order_id: str | None = None, order_class: str | None = None) py_alpaca_api.models.order_model.OrderModel[source]
Parameters:
  • symbol – The symbol of the security to trade.

  • stop_price – The stop price at which the trade should be triggered.

  • qty – The quantity of shares to trade.

  • side – The side of the trade. Defaults to ‘buy’.

  • take_profit – The price at which to take profit on the trade. Defaults to None.

  • stop_loss – The price at which to set the stop loss on the trade. Defaults to None.

  • time_in_force – The duration for which the order will be in effect. Defaults to ‘day’.

  • extended_hours – A boolean value indicating whether to place the order during extended hours. Defaults to False.

  • client_order_id – Client-assigned ID for the order. Defaults to None.

  • order_class – Order class (simple/bracket/oco/oto). Defaults to None.

Returns:

An instance of the OrderModel representing the submitted order.

Raises:

OrderError – If there are any errors with the order parameters.

stop_limit(symbol: str, stop_price: float, limit_price: float, qty: float, side: str = 'buy', time_in_force: str = 'day', extended_hours: bool = False, client_order_id: str | None = None, order_class: str | None = None) py_alpaca_api.models.order_model.OrderModel[source]

Submits a stop-limit order for trading.

Parameters:
  • symbol (str) – The symbol of the security to trade.

  • stop_price (float) – The stop price for the order.

  • limit_price (float) – The limit price for the order.

  • qty (float) – The quantity of shares to trade.

  • side (str, optional) – The side of the order, either ‘buy’ or ‘sell’. Defaults to ‘buy’.

  • time_in_force (str, optional) – The time in force for the order. Defaults to ‘day’.

  • extended_hours (bool, optional) – Whether to allow trading during extended hours. Defaults to False.

  • client_order_id (str, optional) – Client-assigned ID for the order. Defaults to None.

  • order_class (str, optional) – Order class (simple/bracket/oco/oto). Defaults to None.

Returns:

The submitted stop-limit order.

Return type:

OrderModel

Raises:
trailing_stop(symbol: str, qty: float, trail_percent: float | None = None, trail_price: float | None = None, side: str = 'buy', time_in_force: str = 'day', extended_hours: bool = False, client_order_id: str | None = None, order_class: str | None = None) py_alpaca_api.models.order_model.OrderModel[source]

Submits a trailing stop order for the specified symbol.

Parameters:
  • symbol (str) – The symbol of the security to trade.

  • qty (float) – The quantity of shares to trade.

  • trail_percent (float, optional) – The trailing stop percentage. Either trail_percent or trail_price must be provided, not both. Defaults to None.

  • trail_price (float, optional) – The trailing stop price. Either trail_percent or trail_price must be provided, not both. Defaults to None.

  • side (str, optional) – The side of the order, either ‘buy’ or ‘sell’. Defaults to ‘buy’.

  • time_in_force (str, optional) – The time in force for the order. Defaults to ‘day’.

  • extended_hours (bool, optional) – Whether to allow trading during extended hours. Defaults to False.

  • client_order_id (str, optional) – Client-assigned ID for the order. Defaults to None.

  • order_class (str, optional) – Order class (simple/bracket/oco/oto). Defaults to None.

Returns:

The submitted trailing stop order.

Return type:

OrderModel

Raises:
  • ValueError – If symbol is not provided.

  • ValueError – If qty is not provided.

  • ValueError – If both trail_percent and trail_price are provided, or if neither is provided.

  • ValueError – If trail_percent is less than 0.