py_alpaca_api.trading.positions =============================== .. py:module:: py_alpaca_api.trading.positions Classes ------- .. autoapisummary:: py_alpaca_api.trading.positions.Requests py_alpaca_api.trading.positions.PositionModel py_alpaca_api.trading.positions.Account py_alpaca_api.trading.positions.Positions Functions --------- .. autoapisummary:: py_alpaca_api.trading.positions.position_class_from_dict Module Contents --------------- .. py:class:: Requests .. py:method:: 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) Execute HTTP request with retry logic. :param method: A string representing the HTTP method to be used in the request. :param url: A string representing the URL to send the request to. :param headers: An optional dictionary containing the headers for the request. :param params: An optional dictionary containing the query parameters for the request. :param json: An optional dictionary containing the JSON payload for the request. :param 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. .. py:class:: PositionModel .. py:attribute:: asset_id :type: str .. py:attribute:: symbol :type: str .. py:attribute:: exchange :type: str .. py:attribute:: asset_class :type: str .. py:attribute:: avg_entry_price :type: float .. py:attribute:: qty :type: float .. py:attribute:: qty_available :type: float .. py:attribute:: side :type: str .. py:attribute:: market_value :type: float .. py:attribute:: cost_basis :type: float .. py:attribute:: profit_dol :type: float .. py:attribute:: profit_pct :type: float .. py:attribute:: intraday_profit_dol :type: float .. py:attribute:: intraday_profit_pct :type: float .. py:attribute:: portfolio_pct :type: float .. py:attribute:: current_price :type: float .. py:attribute:: lastday_price :type: float .. py:attribute:: change_today :type: float .. py:attribute:: asset_marginable :type: bool .. py:function:: position_class_from_dict(data_dict: dict) -> PositionModel Returns a PositionModel object created from a given data dictionary. :param data_dict: A dictionary containing the data for creating a PositionModel object. :returns: A PositionModel object created using the data from the dictionary. :rtype: PositionModel .. py:class:: Account(headers: dict[str, str], base_url: str) .. py:method:: get() -> py_alpaca_api.models.account_model.AccountModel Retrieves the user's account information. :returns: The user's account model. :rtype: AccountModel .. py:method:: activities(activity_type: str, date: str | None = None, until_date: str | None = None) -> list[py_alpaca_api.models.account_activity_model.AccountActivityModel] Retrieves the account activities for the specified activity type. Optionally filtered by date or until date. :param activity_type: The type of account activity to retrieve. :type activity_type: str :param date: The date to filter the activities by. If provided, only activities on this date will be returned. :type date: str, optional :param until_date: The date to filter the activities up to. If provided, only activities up to and including this date will be returned. :type until_date: str, optional :returns: A list of account activity models representing the retrieved activities. :rtype: List[AccountActivityModel] :raises ValueError: If the activity type is not provided, or if both date and until_date are provided. .. py:method:: portfolio_history(period: str = '1W', timeframe: str = '1D', intraday_reporting: str = 'market_hours') -> pandas.DataFrame Retrieves portfolio history data. :param period: The period of time for which the portfolio history is requested. Defaults to "1W" (1 week). :type period: str :param timeframe: The timeframe for the intervals of the portfolio history. Defaults to "1D" (1 day). :type timeframe: str :param intraday_reporting: The type of intraday reporting to be used. Defaults to "market_hours". :type intraday_reporting: str :returns: A pandas DataFrame containing the portfolio history data. :rtype: pd.DataFrame :raises Exception: If the request to the Alpaca API fails. .. py:method:: get_configuration() -> py_alpaca_api.models.account_config_model.AccountConfigModel Retrieves the current account configuration settings. :returns: The current account configuration. :rtype: AccountConfigModel :raises APIRequestError: If the request to retrieve configuration fails. .. py:method:: 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 Updates the account configuration settings. :param dtbp_check: Day trade buying power check ("entry", "exit", "both") :param fractional_trading: Whether to enable fractional trading :param max_margin_multiplier: Maximum margin multiplier ("1", "2", "4") :param no_shorting: Whether to disable short selling :param pdt_check: Pattern day trader check ("entry", "exit", "both") :param ptp_no_exception_entry: Whether to enable PTP no exception entry :param suspend_trade: Whether to suspend trading :param trade_confirm_email: Trade confirmation emails ("all", "none") :returns: The updated account configuration. :rtype: AccountConfigModel :raises APIRequestError: If the request to update configuration fails. :raises ValueError: If invalid parameter values are provided. .. py:class:: Positions(base_url: str, headers: dict[str, str], account: py_alpaca_api.trading.account.Account) .. py:method:: close_all(cancel_orders: bool = False) -> str Close all positions. :param cancel_orders: Whether to cancel open orders associated with the positions. Defaults to False. :type cancel_orders: bool, optional :returns: A message indicating the number of positions that have been closed. :rtype: str :raises Exception: If the request to close positions is not successful, an exception is raised with the error message from the API response. .. py:method:: close(symbol_or_id: str, qty: float | None = None, percentage: int | None = None) -> str Closes a position for a given symbol or asset ID. :param symbol_or_id: The symbol or asset ID of the position to be closed. :type symbol_or_id: str :param qty: The quantity of the position to be closed. Defaults to None. :type qty: float, optional :param percentage: The percentage of the position to be closed. Defaults to None. :type percentage: int, optional :returns: A message indicating the success or failure of closing the position. :rtype: str :raises ValueError: If neither quantity nor percentage is provided. :raises ValueError: If both quantity and percentage are provided. :raises ValueError: If the percentage is not between 0 and 100. :raises ValueError: If symbol_or_id is not provided. :raises Exception: If the request to close the position fails. .. py:method:: get(symbol: str) -> py_alpaca_api.models.position_model.PositionModel Retrieves the position for the specified symbol. :param symbol: The symbol of the asset for which to retrieve the position. :type symbol: str :returns: The position for the specified symbol. :rtype: PositionModel :raises ValueError: If the symbol is not provided or if a position for the specified symbol is not found. .. py:method:: get_all(order_by: str = 'profit_pct', order_asc: bool = False) -> pandas.DataFrame 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. .. py:method:: modify_position_df(positions_df: pandas.DataFrame) -> pandas.DataFrame :staticmethod: Modifies the given positions DataFrame by renaming columns, converting data types, and rounding values. :param positions_df: The positions DataFrame to be modified. :type positions_df: pd.DataFrame :returns: The modified positions DataFrame. :rtype: pd.DataFrame .. py:method:: cash_position_df() Retrieves the user's cash position data as a DataFrame. :returns: A DataFrame containing the user's cash position data. :rtype: pd.DataFrame .. py:method:: exercise(symbol_or_contract_id: str) -> dict 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. :param symbol_or_contract_id: The symbol or contract ID of the option position to exercise. :returns: Response from the API confirming the exercise request. :rtype: dict :raises APIRequestError: If the exercise request fails. :raises ValueError: If symbol_or_contract_id is not provided. .. 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.