0
# alpaca-py Python SDK
1
2
alpaca-py is the official Python SDK for Alpaca's commission-free trading API. It provides a comprehensive set of tools for algorithmic trading, market data access, and brokerage account management across stocks, options, and cryptocurrencies.
3
4
## Package Information
5
6
- **Package Name**: alpaca-py
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install alpaca-py`
10
11
## Core Imports
12
13
```python { .api }
14
# Trading API - Orders, positions, account management
15
from alpaca.trading import TradingClient
16
from alpaca.trading.stream import TradingStream
17
18
# Market Data API - Historical clients
19
from alpaca.data.historical import (
20
StockHistoricalDataClient, CryptoHistoricalDataClient,
21
OptionHistoricalDataClient, NewsClient, ScreenerClient
22
)
23
24
# Market Data API - Live streaming clients
25
from alpaca.data.live import (
26
StockDataStream, CryptoDataStream,
27
OptionDataStream, NewsDataStream
28
)
29
30
# Broker API - Account creation, funding, portfolio management
31
from alpaca.broker import BrokerClient
32
33
# Import all classes from specific modules
34
from alpaca.trading import * # All trading classes
35
from alpaca.data import * # All data classes
36
from alpaca.broker import * # All broker classes
37
```
38
39
## Basic Usage
40
41
### Authentication & Client Setup
42
43
```python { .api }
44
# Trading client for paper or live trading
45
trading_client = TradingClient(
46
api_key="your-api-key",
47
secret_key="your-secret-key",
48
paper=True # Set to False for live trading
49
)
50
51
# Historical data client
52
data_client = StockHistoricalDataClient(
53
api_key="your-api-key",
54
secret_key="your-secret-key"
55
)
56
57
# Broker client for account management
58
broker_client = BrokerClient(
59
api_key="your-api-key",
60
secret_key="your-secret-key",
61
sandbox=True # Set to False for production
62
)
63
```
64
65
### Simple Trading Example
66
67
```python { .api }
68
from alpaca.trading import TradingClient
69
from alpaca.trading.requests import MarketOrderRequest
70
from alpaca.trading.enums import OrderSide, TimeInForce
71
72
# Create trading client
73
trading_client = TradingClient(api_key="key", secret_key="secret", paper=True)
74
75
# Submit a market buy order
76
market_order_data = MarketOrderRequest(
77
symbol="AAPL",
78
qty=10,
79
side=OrderSide.BUY,
80
time_in_force=TimeInForce.DAY
81
)
82
83
order = trading_client.submit_order(order_data=market_order_data)
84
print(f"Order submitted: {order.id}")
85
```
86
87
### Market Data Example
88
89
```python { .api }
90
from alpaca.data.historical import StockHistoricalDataClient
91
from alpaca.data.requests import StockBarsRequest
92
from alpaca.data.timeframe import TimeFrame, TimeFrameUnit
93
from datetime import datetime
94
95
# Create data client
96
data_client = StockHistoricalDataClient(api_key="key", secret_key="secret")
97
98
# Get historical bars
99
request_params = StockBarsRequest(
100
symbol_or_symbols=["AAPL", "TSLA"],
101
timeframe=TimeFrame.Hour,
102
start=datetime(2023, 1, 1),
103
end=datetime(2023, 12, 31)
104
)
105
106
bars = data_client.get_stock_bars(request_params)
107
print(f"Retrieved {len(bars)} bars")
108
```
109
110
## Architecture
111
112
alpaca-py is organized into three main modules that can be used independently or together:
113
114
### 1. Trading Module (`alpaca.trading`)
115
**Purpose**: Execute trades, manage positions, and monitor account status
116
**Key Components**: TradingClient, TradingStream
117
**Use Cases**: Algorithmic trading, portfolio management, order execution
118
119
### 2. Data Module (`alpaca.data`)
120
**Purpose**: Access historical and real-time market data
121
**Key Components**: Historical clients for stocks/crypto/options, live streaming clients
122
**Use Cases**: Market analysis, backtesting, real-time data feeds
123
124
### 3. Broker Module (`alpaca.broker`)
125
**Purpose**: Manage customer accounts, funding, and regulatory compliance
126
**Key Components**: BrokerClient for account lifecycle management
127
**Use Cases**: Account opening, KYC/AML compliance, cash management
128
129
## Capabilities
130
131
### Order Management
132
Complete order lifecycle management across multiple order types:
133
134
```python { .api }
135
from alpaca.trading.requests import (
136
MarketOrderRequest, LimitOrderRequest, StopOrderRequest,
137
StopLimitOrderRequest, TrailingStopOrderRequest
138
)
139
from alpaca.trading.enums import OrderSide, TimeInForce, OrderType
140
141
# Market Order
142
market_order = MarketOrderRequest(
143
symbol="AAPL",
144
qty=100,
145
side=OrderSide.BUY,
146
time_in_force=TimeInForce.DAY
147
)
148
149
# Limit Order
150
limit_order = LimitOrderRequest(
151
symbol="TSLA",
152
qty=50,
153
side=OrderSide.SELL,
154
time_in_force=TimeInForce.GTC,
155
limit_price=200.00
156
)
157
158
# Stop Loss Order
159
stop_order = StopOrderRequest(
160
symbol="MSFT",
161
qty=25,
162
side=OrderSide.SELL,
163
time_in_force=TimeInForce.DAY,
164
stop_price=300.00
165
)
166
167
# Submit orders
168
order1 = trading_client.submit_order(market_order)
169
order2 = trading_client.submit_order(limit_order)
170
order3 = trading_client.submit_order(stop_order)
171
```
172
173
**See**: [Trading Client](./trading-client.md) for comprehensive order management
174
175
### Position Management
176
Track and manage open positions with real-time P&L:
177
178
```python { .api }
179
# Get all positions
180
positions = trading_client.get_all_positions()
181
182
# Get specific position
183
position = trading_client.get_open_position("AAPL")
184
print(f"Qty: {position.qty}, Market Value: {position.market_value}")
185
186
# Close all positions
187
trading_client.close_all_positions(cancel_orders=True)
188
189
# Close specific position
190
trading_client.close_position("AAPL")
191
```
192
193
**See**: [Trading Client](./trading-client.md) for position management details
194
195
### Market Data Access
196
Multi-asset class data retrieval and streaming:
197
198
```python { .api }
199
from alpaca.data.requests import StockBarsRequest, CryptoBarsRequest
200
from alpaca.data.timeframe import TimeFrame
201
202
# Stock data
203
stock_bars = data_client.get_stock_bars(StockBarsRequest(
204
symbol_or_symbols="AAPL",
205
timeframe=TimeFrame.Minute,
206
start=datetime.now() - timedelta(days=1)
207
))
208
209
# Crypto data
210
crypto_client = CryptoHistoricalDataClient(api_key="key", secret_key="secret")
211
crypto_bars = crypto_client.get_crypto_bars(CryptoBarsRequest(
212
symbol_or_symbols="BTC/USD",
213
timeframe=TimeFrame.Hour,
214
start=datetime.now() - timedelta(days=7)
215
))
216
```
217
218
**See**: [Data Client](./data-client.md) for comprehensive market data access
219
220
### Real-time Streaming
221
WebSocket-based live data feeds:
222
223
```python { .api }
224
from alpaca.data.live import StockDataStream
225
226
# Create stream
227
stream = StockDataStream(api_key="key", secret_key="secret")
228
229
# Define handlers
230
async def trade_handler(data):
231
print(f"Trade: {data.symbol} - {data.price} @ {data.size}")
232
233
async def quote_handler(data):
234
print(f"Quote: {data.symbol} - Bid: {data.bid_price} Ask: {data.ask_price}")
235
236
# Subscribe to data
237
stream.subscribe_trades(trade_handler, "AAPL", "TSLA")
238
stream.subscribe_quotes(quote_handler, "AAPL", "TSLA")
239
240
# Start streaming
241
stream.run()
242
```
243
244
**See**: [Data Client](./data-client.md) for streaming setup and usage
245
246
### Account Management
247
Comprehensive account information and configuration:
248
249
```python { .api }
250
# Get account details
251
account = trading_client.get_account()
252
print(f"Buying Power: ${account.buying_power}")
253
print(f"Portfolio Value: ${account.portfolio_value}")
254
255
# Get account configuration
256
config = trading_client.get_account_configurations()
257
258
# Update account settings
259
from alpaca.trading.models import AccountConfiguration
260
from alpaca.trading.enums import DTBPCheck
261
262
# Get current configuration and modify it
263
config = trading_client.get_account_configurations()
264
config.dtbp_check = DTBPCheck.BOTH
265
config.fractional_trading = True
266
trading_client.set_account_configurations(config)
267
```
268
269
**See**: [Trading Client](./trading-client.md) for account management features
270
271
### Broker Services
272
Customer account lifecycle and funding management:
273
274
```python { .api }
275
from alpaca.broker.requests import CreateAccountRequest
276
from alpaca.broker.models import Contact, Identity
277
278
# Create customer account
279
account_data = CreateAccountRequest(
280
contact=Contact(
281
email_address="customer@example.com",
282
phone_number="555-123-4567"
283
),
284
identity=Identity(
285
given_name="John",
286
family_name="Doe",
287
date_of_birth=date(1990, 1, 1),
288
tax_id="123456789"
289
)
290
)
291
292
account = broker_client.create_account(account_data)
293
print(f"Created account: {account.id}")
294
```
295
296
**See**: [Broker Client](./broker-client.md) for full broker functionality
297
298
## Error Handling
299
300
```python { .api }
301
from alpaca.common.exceptions import APIError
302
303
try:
304
order = trading_client.submit_order(order_data)
305
except APIError as e:
306
print(f"API Error: {e.message}")
307
print(f"Status Code: {e.status_code}")
308
print(f"Request ID: {e.request_id}")
309
```
310
311
## Documentation Structure
312
313
This Knowledge Tile is organized into focused sub-documents:
314
315
- **[Trading Client](./trading-client.md)** - Orders, positions, account management, streaming trades
316
- **[Data Client](./data-client.md)** - Historical data, live streaming, market snapshots, news
317
- **[Broker Client](./broker-client.md)** - Account creation, funding, KYC/AML compliance, portfolios
318
319
Each sub-document provides comprehensive API coverage with complete function signatures, parameters, return types, and practical usage examples.