py_alpaca_api.trading

Submodules

Classes

Account

CorporateActions

Market

News

Orders

Positions

Recommendations

Watchlist

Trading

Package Contents

class py_alpaca_api.trading.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.CorporateActions(headers: dict[str, str], base_url: str)[source]
get_announcements(since: str, until: str, ca_types: list[str], symbol: str | None = None, cusip: str | None = None, date_type: Literal['declaration_date', 'ex_date', 'record_date', 'payable_date'] | None = None, page_limit: int = 100, page_token: str | None = None) list[py_alpaca_api.models.corporate_action_model.CorporateActionModel][source]

Retrieve corporate action announcements.

Parameters:
  • since – The start (inclusive) of the date range in YYYY-MM-DD format. Date range is limited to 90 days.

  • until – The end (inclusive) of the date range in YYYY-MM-DD format. Date range is limited to 90 days.

  • ca_types – List of corporate action types to return. Valid types: dividend, merger, spinoff, split

  • symbol – Optional filter by symbol

  • cusip – Optional filter by CUSIP

  • date_type – Optional date type for filtering (declaration_date, ex_date, record_date, payable_date)

  • page_limit – Number of results per page (Note: API may return all results regardless)

  • page_token – Token for pagination (currently not used by API)

Returns:

List of CorporateActionModel objects

Raises:
get_announcement_by_id(announcement_id: str) py_alpaca_api.models.corporate_action_model.CorporateActionModel[source]

Retrieve a specific corporate action announcement by ID.

Parameters:

announcement_id – The unique ID of the announcement

Returns:

CorporateActionModel object

Raises:

APIRequestError – If the API request fails or announcement not found

get_all_announcements(since: str, until: str, ca_types: list[str], symbol: str | None = None, cusip: str | None = None, date_type: Literal['declaration_date', 'ex_date', 'record_date', 'payable_date'] | None = None) list[py_alpaca_api.models.corporate_action_model.CorporateActionModel][source]

Retrieve all corporate action announcements.

Note: The API currently returns all results within the date range without pagination, so this method simply calls get_announcements.

Parameters:
  • since – The start (inclusive) of the date range in YYYY-MM-DD format.

  • until – The end (inclusive) of the date range in YYYY-MM-DD format.

  • ca_types – List of corporate action types to return.

  • symbol – Optional filter by symbol

  • cusip – Optional filter by CUSIP

  • date_type – Optional date type for filtering

Returns:

List of all CorporateActionModel objects

Raises:
class py_alpaca_api.trading.Market(base_url: str, headers: dict[str, str])[source]
clock() py_alpaca_api.models.clock_model.ClockModel[source]

Retrieves the current market clock.

Returns:

A model containing the current market clock data.

Return type:

ClockModel

calendar(start_date: str, end_date: str) pandas.DataFrame[source]

Retrieves the market calendar for the specified date range.

Parameters:
  • start_date (str) – The start date of the calendar range in the format “YYYY-MM-DD”.

  • end_date (str) – The end date of the calendar range in the format “YYYY-MM-DD”.

Returns:

A DataFrame containing the market calendar data, with columns for the date, settlement date, open time, and close time.

Return type:

pd.DataFrame

class py_alpaca_api.trading.News(headers: dict[str, str])[source]
static strip_html(content: str)[source]

Removes HTML tags and returns the stripped content.

Parameters:

content (str) – The HTML content to be stripped.

Returns:

The stripped content without HTML tags.

Return type:

str

static scrape_article(url: str) str | None[source]

Scrapes the article text from the given URL.

Parameters:

url (str) – The URL of the article.

Returns:

The text content of the article, or None if the article body is not found.

Return type:

str | None

static truncate(text: str, length: int) str[source]

Truncates a given text to a specified length.

Parameters:
  • text (str) – The text to be truncated.

  • length (int) – The maximum length of the truncated text.

Returns:

The truncated text.

Return type:

str

get_news(symbol: str, limit: int = 6) list[dict[str, str]][source]

Retrieves news articles related to a given symbol from Benzinga and Yahoo Finance.

Note: Yahoo Finance has implemented anti-scraping measures that prevent fetching full article content. Yahoo news will include title, URL, publish date, and summary/description when available, but not full article text.

Parameters:
  • symbol (str) – The symbol for which to retrieve news articles.

  • limit (int, optional) – The maximum number of news articles to retrieve. Defaults to 6.

Returns:

A list of news articles, sorted by publish date in descending order.

Return type:

list

class py_alpaca_api.trading.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.

class py_alpaca_api.trading.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.

class py_alpaca_api.trading.Recommendations[source]
static get_recommendations(symbol: str) dict[Any, Any] | pandas.DataFrame[source]

Retrieves the latest recommendations for a given stock symbol.

Parameters:

symbol (str) – The stock symbol for which to retrieve recommendations.

Returns:

A dictionary or DataFrame containing the latest recommendations for the stock symbol.

Return type:

Union[dict, pd.DataFrame]

get_sentiment(symbol: str) str[source]

Retrieves the sentiment for a given stock symbol based on the latest recommendations.

Parameters:

symbol (str) – The stock symbol for which to retrieve the sentiment.

Returns:

The sentiment for the stock symbol, either “BULLISH”, “BEARISH”, or “NEUTRAL”.

Return type:

str

class py_alpaca_api.trading.Watchlist(base_url: str, headers: dict[str, str])[source]
get(watchlist_id: str | None = None, watchlist_name: str | None = None) py_alpaca_api.models.watchlist_model.WatchlistModel | str[source]

Retrieves a watchlist based on the provided watchlist ID or name.

Parameters:
  • watchlist_id (str, optional) – The ID of the watchlist to retrieve.

  • watchlist_name (str, optional) – The name of the watchlist to retrieve.

Returns:

The retrieved watchlist.

Return type:

WatchlistModel

Raises:

ValueError – If both watchlist_id and watchlist_name are provided, or if neither is provided.

get_all() list[py_alpaca_api.models.watchlist_model.WatchlistModel | str][source]

Retrieves all watchlists.

Returns:

A list of WatchlistModel objects representing all the watchlists.

Raises:

Exception – If the API request fails.

create(name: str, symbols: list | str | None = None) py_alpaca_api.models.watchlist_model.WatchlistModel | str[source]

Creates a new watchlist with the given name and symbols.

Parameters:
  • name (str) – The name of the watchlist.

  • symbols (str, optional) – A comma-separated string of symbols to add to the watchlist. Defaults to “”.

Returns:

The created watchlist.

Return type:

WatchlistModel

Raises:

SomeException – An exception that may occur during the request.

update(watchlist_id: str | None = None, watchlist_name: str | None = None, name: str = '', symbols: list | str | None = None) py_alpaca_api.models.watchlist_model.WatchlistModel | str[source]

Update a watchlist with the specified parameters.

Parameters:
  • watchlist_id (str, optional) – The ID of the watchlist to update. Either watchlist_id or watchlist_name

  • provided. (watchlist_name must be)

  • watchlist_name (str, optional) – The name of the watchlist to update. Either watchlist_id or

  • provided.

  • name (str, optional) – The new name for the watchlist. If not provided, the existing name will be used.

  • symbols (str, optional) – A comma-separated string of symbols to update the watchlist with. If not provided, the existing symbols

  • used. (will be)

Returns:

The updated watchlist.

Return type:

WatchlistModel

Raises:
  • ValueError – If both watchlist_id and watchlist_name are provided, or if neither watchlist_id nor

  • watchlist_name

delete(watchlist_id: str | None = None, watchlist_name: str | None = None) str[source]

Deletes a watchlist.

Parameters:
  • watchlist_id (str, optional) – The ID of the watchlist to delete.

  • watchlist_name (str, optional) – The name of the watchlist to delete.

Returns:

A message indicating the successful deletion of the watchlist.

Return type:

str

Raises:

ValueError – If both watchlist_id and watchlist_name are provided or if neither is provided.

add_asset(watchlist_id: str | None = None, watchlist_name: str | None = None, symbol: str = '') py_alpaca_api.models.watchlist_model.WatchlistModel | str[source]

Adds an asset to a watchlist.

Parameters:
  • watchlist_id (str) – The ID of the watchlist to add the asset to. If watchlist_id is provided,

  • None. (watchlist_id should be)

  • watchlist_name (str) – The name of the watchlist to add the asset to. If watchlist_name is provided,

  • None.

  • symbol (str) – The symbol of the asset to add to the watchlist.

Returns:

The updated watchlist after adding the asset.

Return type:

WatchlistModel

Raises:
  • ValueError – If both watchlist_id and watchlist_name are provided or neither is provided.

  • ValueError – If symbol is not provided.

remove_asset(watchlist_id: str | None = None, watchlist_name: str | None = None, symbol: str = '') py_alpaca_api.models.watchlist_model.WatchlistModel | str[source]

Removes an asset from a watchlist.

Parameters:
  • watchlist_id (str, optional) – The ID of the watchlist. If not provided, the watchlist_name parameter

  • to (will be used)

  • None. (retrieve the ID. Defaults to)

  • watchlist_name (str, optional) – The name of the watchlist. If not provided, thewatchlist_id parameter will be used to

  • None.

  • symbol (str) – The symbol of the asset to be removed from the watchlist.

Returns:

The updated watchlist object.

Return type:

WatchlistModel

Raises:

ValueError – If both watchlist_id and watchlist_name are provided, or if symbol is not provided.

get_assets(watchlist_id: str | None = None, watchlist_name: str | None = None) list[source]

Retrieves the symbols of assets in a watchlist.

Parameters:
  • watchlist_id (str, optional) – The ID of the watchlist. Either watchlist_id or watchlist_name should be provided,

  • None. (not both. Defaults to)

  • watchlist_name (str, optional) – The name of the watchlist. Either watchlist_id or watchlist_name should be

  • provided

  • None.

Returns:

A list of symbols of assets in the watchlist.

Return type:

list

Raises:
  • ValueError – If both watchlist_id and watchlist_name are provided, or if neither watchlist_id nor

  • watchlist_name

class py_alpaca_api.trading.Trading(api_key: str, api_secret: str, api_paper: bool)[source]