Python client library for Alpaca's commission-free trading API with support for both REST and streaming data interfaces
npx @tessl/cli install tessl/pypi-alpaca-trade-api@3.2.0A comprehensive Python client library for Alpaca's commission-free trading API with support for both REST and streaming data interfaces. The library enables rapid development of trading algorithms, portfolio management systems, and market analysis tools with access to real-time and historical market data, account management, and order execution capabilities.
pip install alpaca-trade-apifrom alpaca_trade_api import REST, Stream, TimeFrame, TimeFrameUnit, AsyncRest
from alpaca_trade_api.rest import APIError, SortFor async operations:
from alpaca_trade_api import AsyncRestimport alpaca_trade_api as tradeapi
# Initialize REST client
api = tradeapi.REST('your-key-id', 'your-secret-key')
# Get account information
account = api.get_account()
print(f"Account equity: ${account.equity}")
# Submit a market order
order = api.submit_order(
symbol='AAPL',
qty=10,
side='buy',
type='market',
time_in_force='day'
)
print(f"Order ID: {order.id}")
# Get historical bars
bars = api.get_bars('AAPL', tradeapi.TimeFrame.Day, '2023-01-01', '2023-01-31')
for bar in bars:
print(f"{bar.timestamp}: Open=${bar.open}, Close=${bar.close}")The library follows a modular architecture:
This design provides comprehensive access to Alpaca's trading platform while maintaining clean separation between synchronous trading operations, asynchronous data operations, and real-time streaming functionality.
Core trading functionality including account management, order execution, position management, and portfolio analytics. These operations form the foundation of algorithmic trading strategies and portfolio management systems.
def get_account() -> Account: ...
def submit_order(symbol: str, qty: float = None, side: str = "buy", type: str = "market", time_in_force: str = "day", **kwargs) -> Order: ...
def list_orders(status: str = None, limit: int = None, symbols: List[str] = None, **kwargs) -> List[Order]: ...
def replace_order(order_id: str, qty: str = None, limit_price: str = None, **kwargs) -> Order: ...
def get_position(symbol: str) -> Position: ...
def list_positions() -> List[Position]: ...
def close_position(symbol: str, qty: float = None) -> Position: ...
def close_all_positions() -> List[Position]: ...Historical and real-time market data for stocks and cryptocurrencies including bars, trades, quotes, snapshots, and news. Supports multiple data feeds and provides pandas DataFrame integration for analysis workflows.
def get_bars(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> BarsV2: ...
def get_bars_iter(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> Iterator[BarV2]: ...
def get_trades(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> TradesV2: ...
def get_trades_iter(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> Iterator[TradeV2]: ...
def get_quotes(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> QuotesV2: ...
def get_quotes_iter(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> Iterator[QuoteV2]: ...
def get_latest_bar(symbol: str, feed: str = None) -> BarV2: ...
def get_snapshot(symbol: str, feed: str = None) -> SnapshotV2: ...
def get_news(symbol: Union[str, List[str]] = None, start: str = None, end: str = None, **kwargs) -> NewsListV2: ...
def get_news_iter(symbol: Union[str, List[str]] = None, start: str = None, end: str = None, **kwargs) -> Iterator[NewsV2]: ...WebSocket streaming for real-time market data feeds and trading account updates. Supports subscription-based data streams with handler functions and decorator patterns for event processing.
def subscribe_trades(handler: Callable, *symbols: str) -> None: ...
def subscribe_quotes(handler: Callable, *symbols: str) -> None: ...
def subscribe_bars(handler: Callable, *symbols: str) -> None: ...
def subscribe_trade_updates(handler: Callable) -> None: ...
def run() -> None: ...
def stop() -> None: ...Specialized market data operations for cryptocurrency trading pairs including trades, quotes, bars, and orderbook data. Supports multiple crypto exchanges with location-based data access.
def get_crypto_bars(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> BarsV2: ...
def get_crypto_bars_iter(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> Iterator[BarV2]: ...
def get_crypto_trades(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> TradesV2: ...
def get_crypto_trades_iter(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> Iterator[TradeV2]: ...
def get_latest_crypto_orderbook(symbol: str, loc: str = None) -> OrderbookV2: ...
def subscribe_crypto_trades(handler: Callable, *symbols: str) -> None: ...Asynchronous market data operations optimized for high-performance data retrieval with pandas DataFrame outputs. Designed for concurrent data fetching and analysis workflows.
async def get_bars_async(symbol: str, start: str, end: str, timeframe: TimeFrame, **kwargs) -> Tuple[str, pd.DataFrame]: ...
async def get_trades_async(symbol: str, start: str, end: str, **kwargs) -> Tuple[str, pd.DataFrame]: ...
async def get_quotes_async(symbol: str, start: str, end: str, **kwargs) -> Tuple[str, pd.DataFrame]: ...
async def get_latest_trade_async(symbol: str) -> Tuple[str, TradeV2]: ...
async def get_latest_quote_async(symbol: str) -> Tuple[str, QuoteV2]: ...class TimeFrame:
def __init__(self, amount: int, unit: TimeFrameUnit): ...
@property
def amount(self) -> int: ...
@property
def unit(self) -> TimeFrameUnit: ...
class TimeFrameUnit(Enum):
Minute = "Min"
Hour = "Hour"
Day = "Day"
Week = "Week"
Month = "Month"
class Sort(Enum):
Asc = "asc"
Desc = "desc"
class APIError(Exception):
@property
def code(self) -> str: ...
@property
def status_code(self) -> int: ...
@property
def request(self): ...
@property
def response(self): ...