py_alpaca_api.trading.positions

Classes

Requests

PositionModel

Account

Positions

Functions

position_class_from_dict(→ PositionModel)

Returns a PositionModel object created from a given data dictionary.

Module Contents

class py_alpaca_api.trading.positions.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.positions.PositionModel[source]
asset_id: str
symbol: str
exchange: str
asset_class: str
avg_entry_price: float
qty: float
qty_available: float
side: str
market_value: float
cost_basis: float
profit_dol: float
profit_pct: float
intraday_profit_dol: float
intraday_profit_pct: float
portfolio_pct: float
current_price: float
lastday_price: float
change_today: float
asset_marginable: bool
py_alpaca_api.trading.positions.position_class_from_dict(data_dict: dict) PositionModel[source]

Returns a PositionModel object created from a given data dictionary.

Parameters:

data_dict – A dictionary containing the data for creating a PositionModel object.

Returns:

A PositionModel object created using the data from the dictionary.

Return type:

PositionModel

class py_alpaca_api.trading.positions.Account(headers: dict[str, str], base_url: str)[source]
get() py_alpaca_api.models.account_model.AccountModel[source]

Retrieves the user’s account information.

Returns:

The user’s account model.

Return type:

AccountModel

activities(activity_type: str, date: str | None = None, until_date: str | None = None) list[py_alpaca_api.models.account_activity_model.AccountActivityModel][source]

Retrieves the account activities for the specified activity type.

Optionally filtered by date or until date.

Parameters:
  • activity_type (str) – The type of account activity to retrieve.

  • date (str, optional) – The date to filter the activities by. If provided, only activities on this date will be returned.

  • until_date (str, optional) – The date to filter the activities up to. If provided, only activities up to and including this date will be returned.

Returns:

A list of account activity models

representing the retrieved activities.

Return type:

List[AccountActivityModel]

Raises:

ValueError – If the activity type is not provided, or if both date and until_date are provided.

portfolio_history(period: str = '1W', timeframe: str = '1D', intraday_reporting: str = 'market_hours') pandas.DataFrame[source]

Retrieves portfolio history data.

Parameters:
  • period (str) – The period of time for which the portfolio history is requested. Defaults to “1W” (1 week).

  • timeframe (str) – The timeframe for the intervals of the portfolio history. Defaults to “1D” (1 day).

  • intraday_reporting (str) – The type of intraday reporting to be used. Defaults to “market_hours”.

Returns:

A pandas DataFrame containing the portfolio history data.

Return type:

pd.DataFrame

Raises:

Exception – If the request to the Alpaca API fails.

get_configuration() py_alpaca_api.models.account_config_model.AccountConfigModel[source]

Retrieves the current account configuration settings.

Returns:

The current account configuration.

Return type:

AccountConfigModel

Raises:

APIRequestError – If the request to retrieve configuration fails.

update_configuration(dtbp_check: str | None = None, fractional_trading: bool | None = None, max_margin_multiplier: str | None = None, no_shorting: bool | None = None, pdt_check: str | None = None, ptp_no_exception_entry: bool | None = None, suspend_trade: bool | None = None, trade_confirm_email: str | None = None) py_alpaca_api.models.account_config_model.AccountConfigModel[source]

Updates the account configuration settings.

Parameters:
  • dtbp_check – Day trade buying power check (“entry”, “exit”, “both”)

  • fractional_trading – Whether to enable fractional trading

  • max_margin_multiplier – Maximum margin multiplier (“1”, “2”, “4”)

  • no_shorting – Whether to disable short selling

  • pdt_check – Pattern day trader check (“entry”, “exit”, “both”)

  • ptp_no_exception_entry – Whether to enable PTP no exception entry

  • suspend_trade – Whether to suspend trading

  • trade_confirm_email – Trade confirmation emails (“all”, “none”)

Returns:

The updated account configuration.

Return type:

AccountConfigModel

Raises:
class py_alpaca_api.trading.positions.Positions(base_url: str, headers: dict[str, str], account: py_alpaca_api.trading.account.Account)[source]
close_all(cancel_orders: bool = False) str[source]

Close all positions.

Parameters:

cancel_orders (bool, optional) – Whether to cancel open orders associated with the positions. Defaults to False.

Returns:

A message indicating the number of positions that have been closed.

Return type:

str

Raises:

Exception – If the request to close positions is not successful, an exception is raised with the error message from the API response.

close(symbol_or_id: str, qty: float | None = None, percentage: int | None = None) str[source]

Closes a position for a given symbol or asset ID.

Parameters:
  • symbol_or_id (str) – The symbol or asset ID of the position to be closed.

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

  • percentage (int, optional) – The percentage of the position to be closed. Defaults to None.

Returns:

A message indicating the success or failure of closing the position.

Return type:

str

Raises:
  • ValueError – If neither quantity nor percentage is provided.

  • ValueError – If both quantity and percentage are provided.

  • ValueError – If the percentage is not between 0 and 100.

  • ValueError – If symbol_or_id is not provided.

  • Exception – If the request to close the position fails.

get(symbol: str) py_alpaca_api.models.position_model.PositionModel[source]

Retrieves the position for the specified symbol.

Parameters:

symbol (str) – The symbol of the asset for which to retrieve the position.

Returns:

The position for the specified symbol.

Return type:

PositionModel

Raises:

ValueError – If the symbol is not provided or if a position for the specified symbol is not found.

get_all(order_by: str = 'profit_pct', order_asc: bool = False) pandas.DataFrame[source]

Retrieves all positions for the user’s Alpaca account, including cash positions.

The positions are returned as a pandas DataFrame, with the following columns: - asset_id: The unique identifier for the asset - symbol: The symbol for the asset - exchange: The exchange the asset is traded on - asset_class: The class of the asset (e.g. ‘stock’, ‘crypto’) - avg_entry_price: The average price at which the position was entered - qty: The quantity of the asset held in the position - qty_available: The quantity of the asset that is available to trade - side: The side of the position (either ‘long’ or ‘short’) - market_value: The current market value of the position - cost_basis: The total cost basis of the position - profit_dol: The unrealized profit/loss in dollars - profit_pct: The unrealized profit/loss as a percentage - intraday_profit_dol: The unrealized intraday profit/loss in dollars - intraday_profit_pct: The unrealized intraday profit/loss as a percentage - portfolio_pct: The percentage of the total portfolio value that this position represents - current_price: The current price of the asset - lastday_price: The price of the asset at the end of the previous trading day - change_today: The percent change in the asset’s price from the previous trading day - asset_marginable: Whether the asset is marginable or not

The positions are sorted based on the provided order_by parameter, in ascending or descending order based on the order_asc parameter.

static modify_position_df(positions_df: pandas.DataFrame) pandas.DataFrame[source]

Modifies the given positions DataFrame by renaming columns, converting data types, and rounding values.

Parameters:

positions_df (pd.DataFrame) – The positions DataFrame to be modified.

Returns:

The modified positions DataFrame.

Return type:

pd.DataFrame

cash_position_df()[source]

Retrieves the user’s cash position data as a DataFrame.

Returns:

A DataFrame containing the user’s cash position data.

Return type:

pd.DataFrame

exercise(symbol_or_contract_id: str) dict[source]

Exercise a held option contract.

All available held shares of this option contract will be exercised. By default, Alpaca will automatically exercise in-the-money (ITM) contracts at expiry.

Parameters:

symbol_or_contract_id – The symbol or contract ID of the option position to exercise.

Returns:

Response from the API confirming the exercise request.

Return type:

dict

Raises:

Note

  • Exercise requests will be processed immediately once received.

  • Exercise requests submitted between market close and midnight will be rejected.

  • To cancel an exercise request or submit a Do-not-exercise (DNE) instruction, contact Alpaca support.