or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdcryptocurrency.mdindex.mdmarket-data.mdstreaming.mdtrading-operations.md

index.mddocs/

0

# Alpaca Trade API

1

2

A 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.

3

4

## Package Information

5

6

- **Package Name**: alpaca-trade-api

7

- **Language**: Python

8

- **Installation**: `pip install alpaca-trade-api`

9

10

## Core Imports

11

12

```python

13

from alpaca_trade_api import REST, Stream, TimeFrame, TimeFrameUnit, AsyncRest

14

from alpaca_trade_api.rest import APIError, Sort

15

```

16

17

For async operations:

18

19

```python

20

from alpaca_trade_api import AsyncRest

21

```

22

23

## Basic Usage

24

25

```python

26

import alpaca_trade_api as tradeapi

27

28

# Initialize REST client

29

api = tradeapi.REST('your-key-id', 'your-secret-key')

30

31

# Get account information

32

account = api.get_account()

33

print(f"Account equity: ${account.equity}")

34

35

# Submit a market order

36

order = api.submit_order(

37

symbol='AAPL',

38

qty=10,

39

side='buy',

40

type='market',

41

time_in_force='day'

42

)

43

print(f"Order ID: {order.id}")

44

45

# Get historical bars

46

bars = api.get_bars('AAPL', tradeapi.TimeFrame.Day, '2023-01-01', '2023-01-31')

47

for bar in bars:

48

print(f"{bar.timestamp}: Open=${bar.open}, Close=${bar.close}")

49

```

50

51

## Architecture

52

53

The library follows a modular architecture:

54

55

- **REST Client**: Synchronous HTTP client for account management, trading, and market data

56

- **AsyncRest Client**: Asynchronous client optimized for market data operations

57

- **Stream Client**: WebSocket client for real-time data feeds and trading updates

58

- **Entity System**: Object representations of all API responses with pandas integration

59

- **Configuration Layer**: Environment-based configuration for flexible deployment

60

61

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.

62

63

## Capabilities

64

65

### Trading Operations

66

67

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.

68

69

```python { .api }

70

def get_account() -> Account: ...

71

def submit_order(symbol: str, qty: float = None, side: str = "buy", type: str = "market", time_in_force: str = "day", **kwargs) -> Order: ...

72

def list_orders(status: str = None, limit: int = None, symbols: List[str] = None, **kwargs) -> List[Order]: ...

73

def replace_order(order_id: str, qty: str = None, limit_price: str = None, **kwargs) -> Order: ...

74

def get_position(symbol: str) -> Position: ...

75

def list_positions() -> List[Position]: ...

76

def close_position(symbol: str, qty: float = None) -> Position: ...

77

def close_all_positions() -> List[Position]: ...

78

```

79

80

[Trading Operations](./trading-operations.md)

81

82

### Market Data Access

83

84

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.

85

86

```python { .api }

87

def get_bars(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> BarsV2: ...

88

def get_bars_iter(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> Iterator[BarV2]: ...

89

def get_trades(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> TradesV2: ...

90

def get_trades_iter(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> Iterator[TradeV2]: ...

91

def get_quotes(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> QuotesV2: ...

92

def get_quotes_iter(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> Iterator[QuoteV2]: ...

93

def get_latest_bar(symbol: str, feed: str = None) -> BarV2: ...

94

def get_snapshot(symbol: str, feed: str = None) -> SnapshotV2: ...

95

def get_news(symbol: Union[str, List[str]] = None, start: str = None, end: str = None, **kwargs) -> NewsListV2: ...

96

def get_news_iter(symbol: Union[str, List[str]] = None, start: str = None, end: str = None, **kwargs) -> Iterator[NewsV2]: ...

97

```

98

99

[Market Data](./market-data.md)

100

101

### Real-time Streaming

102

103

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.

104

105

```python { .api }

106

def subscribe_trades(handler: Callable, *symbols: str) -> None: ...

107

def subscribe_quotes(handler: Callable, *symbols: str) -> None: ...

108

def subscribe_bars(handler: Callable, *symbols: str) -> None: ...

109

def subscribe_trade_updates(handler: Callable) -> None: ...

110

def run() -> None: ...

111

def stop() -> None: ...

112

```

113

114

[Streaming](./streaming.md)

115

116

### Cryptocurrency Data

117

118

Specialized market data operations for cryptocurrency trading pairs including trades, quotes, bars, and orderbook data. Supports multiple crypto exchanges with location-based data access.

119

120

```python { .api }

121

def get_crypto_bars(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> BarsV2: ...

122

def get_crypto_bars_iter(symbol: Union[str, List[str]], timeframe: TimeFrame, start: str, end: str, **kwargs) -> Iterator[BarV2]: ...

123

def get_crypto_trades(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> TradesV2: ...

124

def get_crypto_trades_iter(symbol: Union[str, List[str]], start: str, end: str, **kwargs) -> Iterator[TradeV2]: ...

125

def get_latest_crypto_orderbook(symbol: str, loc: str = None) -> OrderbookV2: ...

126

def subscribe_crypto_trades(handler: Callable, *symbols: str) -> None: ...

127

```

128

129

[Cryptocurrency](./cryptocurrency.md)

130

131

### Async Market Data

132

133

Asynchronous market data operations optimized for high-performance data retrieval with pandas DataFrame outputs. Designed for concurrent data fetching and analysis workflows.

134

135

```python { .api }

136

async def get_bars_async(symbol: str, start: str, end: str, timeframe: TimeFrame, **kwargs) -> Tuple[str, pd.DataFrame]: ...

137

async def get_trades_async(symbol: str, start: str, end: str, **kwargs) -> Tuple[str, pd.DataFrame]: ...

138

async def get_quotes_async(symbol: str, start: str, end: str, **kwargs) -> Tuple[str, pd.DataFrame]: ...

139

async def get_latest_trade_async(symbol: str) -> Tuple[str, TradeV2]: ...

140

async def get_latest_quote_async(symbol: str) -> Tuple[str, QuoteV2]: ...

141

```

142

143

[Async Operations](./async-operations.md)

144

145

## Types

146

147

```python { .api }

148

class TimeFrame:

149

def __init__(self, amount: int, unit: TimeFrameUnit): ...

150

@property

151

def amount(self) -> int: ...

152

@property

153

def unit(self) -> TimeFrameUnit: ...

154

155

class TimeFrameUnit(Enum):

156

Minute = "Min"

157

Hour = "Hour"

158

Day = "Day"

159

Week = "Week"

160

Month = "Month"

161

162

class Sort(Enum):

163

Asc = "asc"

164

Desc = "desc"

165

166

class APIError(Exception):

167

@property

168

def code(self) -> str: ...

169

@property

170

def status_code(self) -> int: ...

171

@property

172

def request(self): ...

173

@property

174

def response(self): ...

175

```