CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-alpaca-trade-api

Python client library for Alpaca's commission-free trading API with support for both REST and streaming data interfaces

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

trading-operations.mddocs/

Trading Operations

Core trading functionality for account management, order execution, position management, and portfolio analytics. These operations provide the foundation for algorithmic trading strategies and portfolio management systems.

Capabilities

Account Management

Access and manage account information including equity, buying power, account configurations, and trading permissions.

def get_account() -> Account:
    """Get current account information."""

def get_account_configurations() -> AccountConfigurations:
    """Get account configuration settings."""

def update_account_configurations(
    no_shorting: bool = None,
    dtbp_check: str = None, 
    trade_confirm_email: str = None,
    suspend_trade: bool = None
) -> AccountConfigurations:
    """Update account configuration settings."""

Usage Example:

api = tradeapi.REST('key', 'secret')

# Get account details
account = api.get_account()
print(f"Equity: ${account.equity}")
print(f"Buying Power: ${account.buying_power}")
print(f"Day Trading Buying Power: ${account.daytrading_buying_power}")

# Update account settings
config = api.update_account_configurations(
    trade_confirm_email='all'
)

Order Management

Submit, manage, and track trading orders with support for various order types, time-in-force options, and advanced order strategies.

def submit_order(
    symbol: str,
    qty: float = None,
    side: str = "buy",
    type: str = "market",
    time_in_force: str = "day",
    limit_price: str = None,
    stop_price: str = None,
    client_order_id: str = None,
    extended_hours: bool = None,
    order_class: str = None,
    take_profit: dict = None,
    stop_loss: dict = None,
    trail_price: str = None,
    trail_percent: str = None,
    notional: float = None
) -> Order:
    """Submit a new order."""

def list_orders(
    status: str = None,
    limit: int = None,
    after: str = None,
    until: str = None,
    direction: str = None,
    nested: bool = None,
    symbols: List[str] = None,
    side: str = None
) -> List[Order]:
    """List orders with optional filtering."""

def get_order(order_id: str, nested: bool = None) -> Order:
    """Get a specific order by ID."""

def get_order_by_client_order_id(client_order_id: str) -> Order:
    """Get an order by client order ID."""

def replace_order(
    order_id: str,
    qty: str = None,
    limit_price: str = None,
    stop_price: str = None,
    trail_price: str = None,
    trail_percent: str = None,
    time_in_force: str = None,
    client_order_id: str = None
) -> Order:
    """Replace an existing order."""

def cancel_order(order_id: str) -> None:
    """Cancel a specific order."""

def cancel_all_orders() -> None:
    """Cancel all open orders."""

Usage Examples:

# Submit a market order
order = api.submit_order(
    symbol='AAPL',
    qty=100,
    side='buy',
    type='market',
    time_in_force='day'
)

# Submit a limit order with stop loss
order = api.submit_order(
    symbol='TSLA',
    qty=50,
    side='buy', 
    type='limit',
    time_in_force='gtc',
    limit_price=250.00,
    order_class='bracket',
    stop_loss={'stop_price': 230.00},
    take_profit={'limit_price': 270.00}
)

# List all open orders
orders = api.list_orders(status='open')
for order in orders:
    print(f"Order {order.id}: {order.symbol} {order.side} {order.qty} @ {order.limit_price}")

# Cancel all orders
api.cancel_all_orders()

Position Management

Monitor and manage trading positions including position sizes, market values, and position closing operations.

def list_positions() -> List[Position]:
    """List all current positions."""

def get_position(symbol: str) -> Position:
    """Get a specific position by symbol."""

def close_position(symbol: str, qty: float = None) -> Position:
    """Close a position (full or partial)."""

def close_all_positions() -> List[Position]:
    """Close all open positions."""

Usage Examples:

# List all positions
positions = api.list_positions()
for position in positions:
    print(f"{position.symbol}: {position.qty} shares, P&L: ${position.unrealized_pl}")

# Get specific position
try:
    position = api.get_position('AAPL')
    print(f"AAPL position: {position.qty} shares at ${position.avg_entry_price}")
except tradeapi.rest.APIError as e:
    print("No AAPL position found")

# Close half of a position
api.close_position('AAPL', qty=50)

# Close all positions
api.close_all_positions()

Asset Information

Access information about tradeable assets including asset classes, exchange details, and trading status.

def list_assets(status: str = None, asset_class: str = None) -> List[Asset]:
    """List available assets with optional filtering."""

def get_asset(symbol: str) -> Asset:
    """Get information about a specific asset."""

Usage Examples:

# List all active US equity assets
assets = api.list_assets(status='active', asset_class='us_equity')
print(f"Found {len(assets)} active stocks")

# Get asset information
asset = api.get_asset('AAPL')
print(f"Asset: {asset.name}, Exchange: {asset.exchange}, Tradable: {asset.tradable}")

Account Activities

Retrieve account activity history including trade executions, dividends, and other account events.

def get_activities(
    activity_types: str = None,
    until: str = None,
    after: str = None,
    direction: str = None,
    date: str = None,
    page_size: int = None,
    page_token: str = None
) -> List[AccountActivity]:
    """Get account activities with optional filtering."""

Usage Example:

# Get recent trade activities
activities = api.get_activities(activity_types='FILL')
for activity in activities:
    print(f"{activity.transaction_time}: {activity.symbol} {activity.side} {activity.qty} @ ${activity.price}")

Watchlists

Create and manage watchlists for tracking symbols of interest.

def get_watchlists() -> List[Watchlist]:
    """Get all watchlists."""

def get_watchlist(watchlist_id: str) -> Watchlist:
    """Get a specific watchlist by ID."""

def get_watchlist_by_name(watchlist_name: str) -> Watchlist:
    """Get a watchlist by name."""

def create_watchlist(watchlist_name: str, symbols: List[str] = None) -> Watchlist:
    """Create a new watchlist."""

def add_to_watchlist(watchlist_id: str, symbol: str) -> Watchlist:
    """Add a symbol to a watchlist."""

def update_watchlist(watchlist_id: str, name: str = None, symbols: List[str] = None) -> Watchlist:
    """Update a watchlist."""

def delete_watchlist(watchlist_id: str) -> None:
    """Delete a watchlist."""

def delete_from_watchlist(watchlist_id: str, symbol: str) -> None:
    """Remove a symbol from a watchlist."""

Portfolio History

Access historical portfolio performance data for analysis and reporting.

def get_portfolio_history(
    date_start: str = None,
    date_end: str = None,
    period: str = None,
    timeframe: str = None,
    extended_hours: bool = None
) -> PortfolioHistory:
    """Get portfolio history data."""

Types

class Account:
    @property
    def id(self) -> str: ...
    @property
    def equity(self) -> float: ...
    @property
    def cash(self) -> float: ...
    @property
    def buying_power(self) -> float: ...
    @property
    def daytrading_buying_power(self) -> float: ...
    @property
    def status(self) -> str: ...

class Order:
    @property
    def id(self) -> str: ...
    @property
    def client_order_id(self) -> str: ...
    @property
    def symbol(self) -> str: ...
    @property
    def qty(self) -> float: ...
    @property
    def side(self) -> str: ...
    @property
    def order_type(self) -> str: ...
    @property
    def status(self) -> str: ...
    @property
    def filled_qty(self) -> float: ...
    @property
    def legs(self) -> List[Order]: ...

class Position:
    @property
    def symbol(self) -> str: ...
    @property
    def qty(self) -> float: ...
    @property
    def side(self) -> str: ...
    @property
    def market_value(self) -> float: ...
    @property
    def avg_entry_price(self) -> float: ...
    @property
    def unrealized_pl(self) -> float: ...
    @property
    def unrealized_plpc(self) -> float: ...

class Asset:
    @property
    def id(self) -> str: ...
    @property
    def symbol(self) -> str: ...
    @property
    def name(self) -> str: ...
    @property
    def exchange(self) -> str: ...
    @property
    def asset_class(self) -> str: ...
    @property
    def status(self) -> str: ...
    @property
    def tradable(self) -> bool: ...

class AccountActivity:
    @property
    def id(self) -> str: ...
    @property
    def activity_type(self) -> str: ...
    @property
    def transaction_time(self) -> pd.Timestamp: ...
    @property
    def symbol(self) -> str: ...
    @property
    def qty(self) -> float: ...
    @property
    def price(self) -> float: ...
    @property
    def side(self) -> str: ...

class AccountConfigurations:
    @property
    def dtbp_check(self) -> str: ...
    @property
    def no_shorting(self) -> bool: ...
    @property
    def suspend_trade(self) -> bool: ...
    @property
    def trade_confirm_email(self) -> str: ...

class Watchlist:
    @property
    def id(self) -> str: ...
    @property
    def name(self) -> str: ...
    @property
    def assets(self) -> List[Asset]: ...
    @property
    def created_at(self) -> pd.Timestamp: ...
    @property
    def updated_at(self) -> pd.Timestamp: ...

class PortfolioHistory:
    @property
    def df(self) -> pd.DataFrame: ...
    @property
    def equity(self) -> List[float]: ...
    @property
    def profit_loss(self) -> List[float]: ...
    @property
    def profit_loss_pct(self) -> List[float]: ...
    @property
    def base_value(self) -> float: ...
    @property
    def timeframe(self) -> str: ...

Install with Tessl CLI

npx tessl i tessl/pypi-alpaca-trade-api

docs

async-operations.md

cryptocurrency.md

index.md

market-data.md

streaming.md

trading-operations.md

tile.json