0
# Trading Client
1
2
The Trading Client provides comprehensive functionality for managing orders, positions, account information, and trading-related activities in both paper and live trading environments.
3
4
## Core Client
5
6
### TradingClient
7
8
```python { .api }
9
from alpaca.trading import TradingClient
10
11
class TradingClient(RESTClient):
12
def __init__(
13
self,
14
api_key: Optional[str] = None,
15
secret_key: Optional[str] = None,
16
oauth_token: Optional[str] = None,
17
paper: bool = True,
18
raw_data: bool = False,
19
url_override: Optional[str] = None,
20
) -> None:
21
"""
22
Initialize trading client for paper or live trading.
23
24
Args:
25
api_key: API key for authentication
26
secret_key: Secret key for authentication
27
oauth_token: OAuth token for user-on-behalf trading
28
paper: True for paper trading, False for live trading
29
raw_data: Return raw API responses instead of models
30
url_override: Override base URL for testing/proxy
31
"""
32
```
33
34
#### Basic Setup
35
36
```python { .api }
37
# Paper trading client
38
trading_client = TradingClient(
39
api_key="your-paper-api-key",
40
secret_key="your-paper-secret-key",
41
paper=True
42
)
43
44
# Live trading client
45
trading_client = TradingClient(
46
api_key="your-live-api-key",
47
secret_key="your-live-secret-key",
48
paper=False
49
)
50
51
# OAuth-based client for user-on-behalf trading
52
trading_client = TradingClient(
53
oauth_token="user-oauth-token",
54
paper=True
55
)
56
```
57
58
## Order Management
59
60
### Order Submission
61
62
#### submit_order()
63
64
```python { .api }
65
def submit_order(self, order_data: OrderRequest) -> Union[Order, RawData]:
66
"""
67
Submit a new order for execution.
68
69
Args:
70
order_data: Order request with order details
71
72
Returns:
73
Order: The submitted order with server-assigned ID and status
74
"""
75
```
76
77
#### Order Request Types
78
79
##### MarketOrderRequest
80
81
```python { .api }
82
from alpaca.trading.requests import MarketOrderRequest
83
from alpaca.trading.enums import OrderSide, TimeInForce
84
85
class MarketOrderRequest(OrderRequest):
86
"""Market order that executes immediately at current market price."""
87
88
def __init__(
89
self,
90
symbol: str,
91
qty: Optional[float] = None,
92
notional: Optional[float] = None, # Dollar amount for stocks
93
side: OrderSide,
94
time_in_force: TimeInForce,
95
extended_hours: Optional[bool] = None,
96
client_order_id: Optional[str] = None,
97
order_class: Optional[OrderClass] = None,
98
take_profit: Optional[TakeProfitRequest] = None,
99
stop_loss: Optional[StopLossRequest] = None,
100
position_intent: Optional[PositionIntent] = None # For options: BTO, BTC, STO, STC
101
):
102
```
103
104
**Usage Examples:**
105
106
```python { .api }
107
# Basic market buy order
108
market_buy = MarketOrderRequest(
109
symbol="AAPL",
110
qty=100,
111
side=OrderSide.BUY,
112
time_in_force=TimeInForce.DAY
113
)
114
order = trading_client.submit_order(market_buy)
115
116
# Notional market order (buy $1000 worth)
117
dollar_buy = MarketOrderRequest(
118
symbol="TSLA",
119
notional=1000.00,
120
side=OrderSide.BUY,
121
time_in_force=TimeInForce.GTC
122
)
123
order = trading_client.submit_order(dollar_buy)
124
125
# Market order with bracket (take profit + stop loss)
126
bracket_order = MarketOrderRequest(
127
symbol="MSFT",
128
qty=50,
129
side=OrderSide.BUY,
130
time_in_force=TimeInForce.DAY,
131
order_class=OrderClass.BRACKET,
132
take_profit=TakeProfitRequest(limit_price=200.00),
133
stop_loss=StopLossRequest(stop_price=180.00)
134
)
135
order = trading_client.submit_order(bracket_order)
136
```
137
138
##### LimitOrderRequest
139
140
```python { .api }
141
from alpaca.trading.requests import LimitOrderRequest
142
143
class LimitOrderRequest(OrderRequest):
144
"""Limit order that executes only at specified price or better."""
145
146
def __init__(
147
self,
148
symbol: str,
149
qty: Optional[float] = None,
150
notional: Optional[float] = None,
151
side: OrderSide,
152
time_in_force: TimeInForce,
153
limit_price: float, # Maximum buy price or minimum sell price
154
extended_hours: Optional[bool] = None,
155
client_order_id: Optional[str] = None,
156
order_class: Optional[OrderClass] = None,
157
take_profit: Optional[TakeProfitRequest] = None,
158
stop_loss: Optional[StopLossRequest] = None,
159
position_intent: Optional[PositionIntent] = None
160
):
161
```
162
163
**Usage Examples:**
164
165
```python { .api }
166
# Limit buy order
167
limit_buy = LimitOrderRequest(
168
symbol="NVDA",
169
qty=25,
170
side=OrderSide.BUY,
171
time_in_force=TimeInForce.GTC,
172
limit_price=450.00
173
)
174
order = trading_client.submit_order(limit_buy)
175
176
# Limit sell order
177
limit_sell = LimitOrderRequest(
178
symbol="AMZN",
179
qty=10,
180
side=OrderSide.SELL,
181
time_in_force=TimeInForce.DAY,
182
limit_price=155.00
183
)
184
order = trading_client.submit_order(limit_sell)
185
```
186
187
##### StopOrderRequest
188
189
```python { .api }
190
from alpaca.trading.requests import StopOrderRequest
191
192
class StopOrderRequest(OrderRequest):
193
"""Stop order that becomes market order when stop price is reached."""
194
195
def __init__(
196
self,
197
symbol: str,
198
qty: Optional[float] = None,
199
notional: Optional[float] = None,
200
side: OrderSide,
201
time_in_force: TimeInForce,
202
stop_price: float, # Price that triggers the order
203
extended_hours: Optional[bool] = None,
204
client_order_id: Optional[str] = None,
205
order_class: Optional[OrderClass] = None,
206
take_profit: Optional[TakeProfitRequest] = None,
207
stop_loss: Optional[StopLossRequest] = None,
208
position_intent: Optional[PositionIntent] = None
209
):
210
```
211
212
**Usage Examples:**
213
214
```python { .api }
215
# Stop loss order
216
stop_loss = StopOrderRequest(
217
symbol="GOOG",
218
qty=15,
219
side=OrderSide.SELL,
220
time_in_force=TimeInForce.GTC,
221
stop_price=2800.00
222
)
223
order = trading_client.submit_order(stop_loss)
224
```
225
226
##### StopLimitOrderRequest
227
228
```python { .api }
229
from alpaca.trading.requests import StopLimitOrderRequest
230
231
class StopLimitOrderRequest(OrderRequest):
232
"""Stop-limit order: becomes limit order when stop price is reached."""
233
234
def __init__(
235
self,
236
symbol: str,
237
qty: Optional[float] = None,
238
notional: Optional[float] = None,
239
side: OrderSide,
240
time_in_force: TimeInForce,
241
stop_price: float, # Price that triggers the order
242
limit_price: float, # Limit price after trigger
243
extended_hours: Optional[bool] = None,
244
client_order_id: Optional[str] = None,
245
order_class: Optional[OrderClass] = None,
246
take_profit: Optional[TakeProfitRequest] = None,
247
stop_loss: Optional[StopLossRequest] = None,
248
position_intent: Optional[PositionIntent] = None
249
):
250
```
251
252
**Usage Examples:**
253
254
```python { .api }
255
# Stop-limit sell order
256
stop_limit_sell = StopLimitOrderRequest(
257
symbol="META",
258
qty=20,
259
side=OrderSide.SELL,
260
time_in_force=TimeInForce.DAY,
261
stop_price=320.00, # Trigger price
262
limit_price=315.00 # Minimum sell price after trigger
263
)
264
order = trading_client.submit_order(stop_limit_sell)
265
```
266
267
##### TrailingStopOrderRequest
268
269
```python { .api }
270
from alpaca.trading.requests import TrailingStopOrderRequest
271
272
class TrailingStopOrderRequest(OrderRequest):
273
"""Trailing stop order that adjusts stop price as stock moves favorably."""
274
275
def __init__(
276
self,
277
symbol: str,
278
qty: Optional[float] = None,
279
notional: Optional[float] = None,
280
side: OrderSide,
281
time_in_force: TimeInForce,
282
trail_price: Optional[float] = None, # Fixed dollar trail amount
283
trail_percent: Optional[float] = None, # Percentage trail amount
284
extended_hours: Optional[bool] = None,
285
client_order_id: Optional[str] = None,
286
order_class: Optional[OrderClass] = None,
287
take_profit: Optional[TakeProfitRequest] = None,
288
stop_loss: Optional[StopLossRequest] = None,
289
position_intent: Optional[PositionIntent] = None
290
):
291
```
292
293
**Usage Examples:**
294
295
```python { .api }
296
# Trailing stop with dollar amount
297
trailing_stop_dollar = TrailingStopOrderRequest(
298
symbol="AAPL",
299
qty=100,
300
side=OrderSide.SELL,
301
time_in_force=TimeInForce.GTC,
302
trail_price=5.00 # Trail by $5
303
)
304
order = trading_client.submit_order(trailing_stop_dollar)
305
306
# Trailing stop with percentage
307
trailing_stop_percent = TrailingStopOrderRequest(
308
symbol="TSLA",
309
qty=50,
310
side=OrderSide.SELL,
311
time_in_force=TimeInForce.GTC,
312
trail_percent=0.02 # Trail by 2%
313
)
314
order = trading_client.submit_order(trailing_stop_percent)
315
```
316
317
### Order Querying
318
319
#### get_orders()
320
321
```python { .api }
322
def get_orders(
323
self,
324
filter: Optional[GetOrdersRequest] = None
325
) -> Union[List[Order], RawData]:
326
"""
327
Retrieve orders with optional filtering.
328
329
Args:
330
filter: Optional filtering parameters
331
332
Returns:
333
List[Order]: List of orders matching filter criteria
334
"""
335
```
336
337
#### GetOrdersRequest
338
339
```python { .api }
340
from alpaca.trading.requests import GetOrdersRequest
341
from alpaca.trading.enums import OrderStatus, OrderSide
342
from datetime import datetime
343
344
class GetOrdersRequest(NonEmptyRequest):
345
def __init__(
346
self,
347
status: Optional[QueryOrderStatus] = None, # NEW, OPEN, CLOSED, ALL
348
limit: Optional[int] = None, # Max 500
349
after: Optional[datetime] = None, # Orders after timestamp
350
until: Optional[datetime] = None, # Orders before timestamp
351
direction: Optional[Sort] = None, # ASC, DESC
352
nested: Optional[bool] = None, # Include nested orders
353
symbols: Optional[Union[str, List[str]]] = None, # Filter by symbols
354
side: Optional[OrderSide] = None, # BUY, SELL
355
asof: Optional[datetime] = None # Point-in-time query
356
):
357
```
358
359
**Usage Examples:**
360
361
```python { .api }
362
# Get all orders
363
all_orders = trading_client.get_orders()
364
365
# Get open orders only
366
open_orders = trading_client.get_orders(
367
GetOrdersRequest(status=QueryOrderStatus.OPEN)
368
)
369
370
# Get recent orders for specific symbols
371
recent_orders = trading_client.get_orders(GetOrdersRequest(
372
symbols=["AAPL", "TSLA", "MSFT"],
373
after=datetime.now() - timedelta(days=7),
374
limit=100
375
))
376
377
# Get buy orders from last month
378
buy_orders = trading_client.get_orders(GetOrdersRequest(
379
side=OrderSide.BUY,
380
after=datetime.now() - timedelta(days=30),
381
status=QueryOrderStatus.ALL
382
))
383
```
384
385
#### get_order_by_id()
386
387
```python { .api }
388
def get_order_by_id(
389
self,
390
order_id: Union[UUID, str],
391
filter: Optional[GetOrderByIdRequest] = None
392
) -> Union[Order, RawData]:
393
"""
394
Get specific order by ID.
395
396
Args:
397
order_id: UUID of the order
398
filter: Optional nested order inclusion
399
400
Returns:
401
Order: The specified order
402
"""
403
```
404
405
#### get_order_by_client_id()
406
407
```python { .api }
408
def get_order_by_client_id(self, client_id: str) -> Union[Order, RawData]:
409
"""
410
Get order by client-assigned ID.
411
412
Args:
413
client_id: Client order identifier
414
415
Returns:
416
Order: The order with specified client ID
417
"""
418
```
419
420
**Usage Examples:**
421
422
```python { .api }
423
# Get order by server ID
424
order = trading_client.get_order_by_id("f47ac10b-58cc-4372-a567-0e02b2c3d479")
425
426
# Get order by client ID
427
order = trading_client.get_order_by_client_id("my-order-123")
428
429
# Get order with nested details
430
order = trading_client.get_order_by_id(
431
"f47ac10b-58cc-4372-a567-0e02b2c3d479",
432
GetOrderByIdRequest(nested=True)
433
)
434
```
435
436
### Order Modification
437
438
#### replace_order_by_id()
439
440
```python { .api }
441
def replace_order_by_id(
442
self,
443
order_id: Union[UUID, str],
444
order_data: Optional[ReplaceOrderRequest] = None,
445
) -> Union[Order, RawData]:
446
"""
447
Update an existing order with new parameters.
448
449
Args:
450
order_id: ID of order to replace
451
order_data: New order parameters
452
453
Returns:
454
Order: Updated order
455
"""
456
```
457
458
#### ReplaceOrderRequest
459
460
```python { .api }
461
from alpaca.trading.requests import ReplaceOrderRequest
462
463
class ReplaceOrderRequest(NonEmptyRequest):
464
def __init__(
465
self,
466
qty: Optional[float] = None,
467
time_in_force: Optional[TimeInForce] = None,
468
limit_price: Optional[float] = None,
469
stop_price: Optional[float] = None,
470
trail_price: Optional[float] = None,
471
trail_percent: Optional[float] = None,
472
client_order_id: Optional[str] = None
473
):
474
```
475
476
**Usage Examples:**
477
478
```python { .api }
479
# Update order quantity
480
updated_order = trading_client.replace_order_by_id(
481
"order-id-123",
482
ReplaceOrderRequest(qty=150)
483
)
484
485
# Update limit price
486
updated_order = trading_client.replace_order_by_id(
487
"order-id-456",
488
ReplaceOrderRequest(limit_price=105.50)
489
)
490
491
# Update multiple parameters
492
updated_order = trading_client.replace_order_by_id(
493
"order-id-789",
494
ReplaceOrderRequest(
495
qty=200,
496
limit_price=99.99,
497
time_in_force=TimeInForce.GTC
498
)
499
)
500
```
501
502
### Order Cancellation
503
504
#### cancel_orders()
505
506
```python { .api }
507
def cancel_orders(self) -> Union[List[CancelOrderResponse], RawData]:
508
"""
509
Cancel all open orders.
510
511
Returns:
512
List[CancelOrderResponse]: Status of each cancellation attempt
513
"""
514
```
515
516
#### cancel_order_by_id()
517
518
```python { .api }
519
def cancel_order_by_id(self, order_id: Union[UUID, str]) -> None:
520
"""
521
Cancel specific order.
522
523
Args:
524
order_id: ID of order to cancel
525
"""
526
```
527
528
**Usage Examples:**
529
530
```python { .api }
531
# Cancel all orders
532
cancel_responses = trading_client.cancel_orders()
533
for response in cancel_responses:
534
print(f"Order {response.id}: Status {response.status}")
535
536
# Cancel specific order
537
trading_client.cancel_order_by_id("f47ac10b-58cc-4372-a567-0e02b2c3d479")
538
```
539
540
## Position Management
541
542
### Position Querying
543
544
#### get_all_positions()
545
546
```python { .api }
547
def get_all_positions(self) -> Union[List[Position], RawData]:
548
"""
549
Get all open positions.
550
551
Returns:
552
List[Position]: All current positions
553
"""
554
```
555
556
#### get_open_position()
557
558
```python { .api }
559
def get_open_position(
560
self,
561
symbol_or_asset_id: Union[str, UUID]
562
) -> Union[Position, RawData]:
563
"""
564
Get specific open position.
565
566
Args:
567
symbol_or_asset_id: Symbol or UUID of the asset
568
569
Returns:
570
Position: The position for specified asset
571
"""
572
```
573
574
**Usage Examples:**
575
576
```python { .api }
577
# Get all positions
578
positions = trading_client.get_all_positions()
579
for position in positions:
580
print(f"{position.symbol}: {position.qty} shares, ${position.market_value}")
581
582
# Get specific position
583
aapl_position = trading_client.get_open_position("AAPL")
584
print(f"AAPL P&L: ${aapl_position.unrealized_pl}")
585
```
586
587
### Position Closing
588
589
#### close_all_positions()
590
591
```python { .api }
592
def close_all_positions(
593
self,
594
cancel_orders: Optional[bool] = None
595
) -> Union[List[ClosePositionResponse], RawData]:
596
"""
597
Liquidate all open positions.
598
599
Args:
600
cancel_orders: Whether to cancel existing orders first
601
602
Returns:
603
List[ClosePositionResponse]: Results of position closures
604
"""
605
```
606
607
#### close_position()
608
609
```python { .api }
610
def close_position(
611
self,
612
symbol_or_asset_id: Union[str, UUID],
613
close_options: Optional[ClosePositionRequest] = None,
614
) -> Union[Order, RawData]:
615
"""
616
Close specific position.
617
618
Args:
619
symbol_or_asset_id: Symbol or UUID of asset to close
620
close_options: Partial close options
621
622
Returns:
623
Order: The liquidation order
624
"""
625
```
626
627
#### ClosePositionRequest
628
629
```python { .api }
630
from alpaca.trading.requests import ClosePositionRequest
631
632
class ClosePositionRequest(NonEmptyRequest):
633
def __init__(
634
self,
635
qty: Optional[str] = None, # Shares to close
636
percentage: Optional[str] = None # Percentage to close
637
):
638
# Must specify either qty OR percentage, not both
639
```
640
641
**Usage Examples:**
642
643
```python { .api }
644
# Close all positions
645
close_responses = trading_client.close_all_positions(cancel_orders=True)
646
647
# Close entire position
648
close_order = trading_client.close_position("AAPL")
649
650
# Partial close by quantity
651
close_order = trading_client.close_position(
652
"TSLA",
653
ClosePositionRequest(qty="50")
654
)
655
656
# Partial close by percentage
657
close_order = trading_client.close_position(
658
"MSFT",
659
ClosePositionRequest(percentage="25") # Close 25% of position
660
)
661
```
662
663
### Options Exercise
664
665
#### exercise_options_position()
666
667
```python { .api }
668
def exercise_options_position(
669
self,
670
symbol_or_contract_id: Union[str, UUID]
671
) -> None:
672
"""
673
Exercise options contracts.
674
675
Args:
676
symbol_or_contract_id: Option symbol or contract ID
677
"""
678
```
679
680
**Usage Examples:**
681
682
```python { .api }
683
# Exercise option by symbol
684
trading_client.exercise_options_position("AAPL230317C00150000")
685
686
# Exercise option by contract ID
687
trading_client.exercise_options_position("contract-uuid-here")
688
```
689
690
## Account Information
691
692
### Account Details
693
694
#### get_account()
695
696
```python { .api }
697
def get_account(self) -> Union[TradeAccount, RawData]:
698
"""
699
Get current account information.
700
701
Returns:
702
TradeAccount: Account details and balances
703
"""
704
```
705
706
#### TradeAccount Model
707
708
```python { .api }
709
class TradeAccount:
710
"""Account information and balances."""
711
712
id: UUID
713
account_number: str
714
status: AccountStatus
715
currency: str
716
cash: float # Available cash
717
buying_power: float # Total buying power
718
regt_buying_power: float # Regulation T buying power
719
daytrading_buying_power: float # Day trading buying power
720
equity: float # Total equity
721
last_equity: float # Previous day equity
722
multiplier: float # Buying power multiplier
723
portfolio_value: float # Total portfolio value
724
initial_margin: float # Initial margin requirement
725
maintenance_margin: float # Maintenance margin requirement
726
long_market_value: float # Long positions market value
727
short_market_value: float # Short positions market value
728
position_market_value: float # Total positions market value
729
last_maintenance_margin: float
730
sma: float # Special Memorandum Account
731
daytrade_count: int # PDT rule day trades count
732
balance_asof: datetime # Balance as-of timestamp
733
crypto_status: Optional[AccountStatus]
734
```
735
736
**Usage Examples:**
737
738
```python { .api }
739
# Get account information
740
account = trading_client.get_account()
741
print(f"Account: {account.account_number}")
742
print(f"Status: {account.status}")
743
print(f"Buying Power: ${account.buying_power:,.2f}")
744
print(f"Cash: ${account.cash:,.2f}")
745
print(f"Portfolio Value: ${account.portfolio_value:,.2f}")
746
print(f"Day Trade Count: {account.daytrade_count}")
747
748
# Check if account can day trade
749
if account.daytrade_count >= 3 and account.equity < 25000:
750
print("Warning: Approaching PDT limit")
751
```
752
753
### Account Configuration
754
755
#### get_account_configurations()
756
757
```python { .api }
758
def get_account_configurations(self) -> Union[AccountConfiguration, RawData]:
759
"""
760
Get account configuration settings.
761
762
Returns:
763
AccountConfiguration: Current account settings
764
"""
765
```
766
767
#### set_account_configurations()
768
769
```python { .api }
770
def set_account_configurations(
771
self,
772
account_configurations: AccountConfiguration
773
) -> Union[AccountConfiguration, RawData]:
774
"""
775
Update account configuration settings.
776
777
Args:
778
account_configurations: New configuration settings
779
780
Returns:
781
AccountConfiguration: Updated configuration
782
"""
783
```
784
785
#### AccountConfiguration Model
786
787
```python { .api }
788
from alpaca.trading.enums import DTBPCheck, TradeConfirmationEmail
789
790
class AccountConfiguration:
791
"""Account configuration and preferences."""
792
793
dtbp_check: DTBPCheck # Day trade buying power check
794
fractional_trading: bool # Allow fractional shares
795
max_margin_multiplier: float # Maximum margin multiplier
796
no_shorting: bool # Disable short selling
797
pdt_check: PDTCheck # Pattern day trader check
798
suspend_trade: bool # Suspend trading capability
799
trade_confirm_email: TradeConfirmationEmail # Email confirmation setting
800
```
801
802
**Usage Examples:**
803
804
```python { .api }
805
# Get current configuration
806
config = trading_client.get_account_configurations()
807
print(f"Fractional Trading: {config.fractional_trading}")
808
print(f"Max Margin: {config.max_margin_multiplier}")
809
810
# Update configuration
811
from alpaca.trading.models import AccountConfiguration
812
813
# Get current configuration and modify it
814
config = trading_client.get_account_configurations()
815
config.fractional_trading = True
816
config.dtbp_check = DTBPCheck.BOTH
817
config.trade_confirm_email = TradeConfirmationEmail.ALL
818
updated_config = trading_client.set_account_configurations(config)
819
```
820
821
## Portfolio Analysis
822
823
### Portfolio History
824
825
#### get_portfolio_history()
826
827
```python { .api }
828
def get_portfolio_history(
829
self,
830
history_filter: Optional[GetPortfolioHistoryRequest] = None
831
) -> Union[PortfolioHistory, RawData]:
832
"""
833
Get historical portfolio performance.
834
835
Args:
836
history_filter: Time range and resolution parameters
837
838
Returns:
839
PortfolioHistory: Portfolio performance data
840
"""
841
```
842
843
#### GetPortfolioHistoryRequest
844
845
```python { .api }
846
from alpaca.trading.requests import GetPortfolioHistoryRequest
847
from datetime import datetime, date
848
849
class GetPortfolioHistoryRequest(NonEmptyRequest):
850
def __init__(
851
self,
852
period: Optional[str] = None, # 1D, 1W, 1M, 3M, 1A, etc.
853
timeframe: Optional[str] = None, # 1Min, 5Min, 15Min, 1H, 1D
854
intraday_reporting: Optional[str] = None, # continuous, end_of_day
855
start: Optional[datetime] = None, # Start timestamp
856
end: Optional[datetime] = None, # End timestamp
857
date_end: Optional[date] = None, # End date
858
extended_hours: Optional[bool] = None, # Include extended hours
859
pnl_reset: Optional[str] = None, # per_day, per_position
860
cashflow_types: Optional[str] = None # Cashflow activities to include
861
):
862
```
863
864
#### PortfolioHistory Model
865
866
```python { .api }
867
class PortfolioHistory:
868
"""Historical portfolio performance data."""
869
870
timestamp: List[datetime] # Timestamps for data points
871
equity: List[float] # Portfolio equity values
872
profit_loss: List[float] # Profit/loss values
873
profit_loss_pct: List[float] # Profit/loss percentages
874
base_value: float # Starting portfolio value
875
timeframe: str # Data timeframe resolution
876
```
877
878
**Usage Examples:**
879
880
```python { .api }
881
# Get 1 month portfolio history
882
history = trading_client.get_portfolio_history(
883
GetPortfolioHistoryRequest(period="1M", timeframe="1D")
884
)
885
886
print(f"Base Value: ${history.base_value:,.2f}")
887
print(f"Current Value: ${history.equity[-1]:,.2f}")
888
print(f"Total Return: {history.profit_loss_pct[-1]:.2%}")
889
890
# Get detailed intraday history
891
detailed_history = trading_client.get_portfolio_history(
892
GetPortfolioHistoryRequest(
893
period="1W",
894
timeframe="15Min",
895
extended_hours=True,
896
intraday_reporting="continuous"
897
)
898
)
899
900
# Calculate daily returns
901
import pandas as pd
902
df = pd.DataFrame({
903
'timestamp': history.timestamp,
904
'equity': history.equity,
905
'pnl_pct': history.profit_loss_pct
906
})
907
print(df.tail())
908
```
909
910
## Asset Information
911
912
### Asset Querying
913
914
#### get_all_assets()
915
916
```python { .api }
917
def get_all_assets(
918
self,
919
filter: Optional[GetAssetsRequest] = None
920
) -> Union[List[Asset], RawData]:
921
"""
922
Get tradeable assets with optional filtering.
923
924
Args:
925
filter: Asset filtering parameters
926
927
Returns:
928
List[Asset]: Available assets
929
"""
930
```
931
932
#### get_asset()
933
934
```python { .api }
935
def get_asset(
936
self,
937
symbol_or_asset_id: Union[str, UUID]
938
) -> Union[Asset, RawData]:
939
"""
940
Get specific asset details.
941
942
Args:
943
symbol_or_asset_id: Asset symbol or UUID
944
945
Returns:
946
Asset: Asset information
947
"""
948
```
949
950
#### GetAssetsRequest
951
952
```python { .api }
953
from alpaca.trading.requests import GetAssetsRequest
954
from alpaca.trading.enums import AssetStatus, AssetClass
955
956
class GetAssetsRequest(NonEmptyRequest):
957
def __init__(
958
self,
959
status: Optional[AssetStatus] = None, # ACTIVE, INACTIVE
960
asset_class: Optional[AssetClass] = None, # US_EQUITY, CRYPTO, US_OPTION
961
exchange: Optional[AssetExchange] = None, # NYSE, NASDAQ, etc.
962
attributes: Optional[str] = None # ptp_no_exception, etc.
963
):
964
```
965
966
#### Asset Model
967
968
```python { .api }
969
class Asset:
970
"""Tradeable asset information."""
971
972
id: UUID
973
asset_class: AssetClass # US_EQUITY, CRYPTO, US_OPTION
974
exchange: AssetExchange # NYSE, NASDAQ, ARCA, etc.
975
symbol: str # Trading symbol
976
name: str # Asset name
977
status: AssetStatus # ACTIVE, INACTIVE, DELISTED
978
tradable: bool # Can be traded
979
marginable: bool # Can be bought on margin
980
shortable: bool # Can be sold short
981
easy_to_borrow: bool # Easy to borrow for shorting
982
fractionable: bool # Supports fractional shares
983
min_order_size: Optional[float] # Minimum order size
984
min_trade_increment: Optional[float] # Minimum price increment
985
price_increment: Optional[float] # Tick size
986
```
987
988
**Usage Examples:**
989
990
```python { .api }
991
# Get all active US equities
992
active_stocks = trading_client.get_all_assets(
993
GetAssetsRequest(
994
status=AssetStatus.ACTIVE,
995
asset_class=AssetClass.US_EQUITY
996
)
997
)
998
999
# Get specific asset details
1000
aapl = trading_client.get_asset("AAPL")
1001
print(f"Name: {aapl.name}")
1002
print(f"Exchange: {aapl.exchange}")
1003
print(f"Fractionable: {aapl.fractionable}")
1004
print(f"Marginable: {aapl.marginable}")
1005
print(f"Shortable: {aapl.shortable}")
1006
1007
# Get crypto assets
1008
crypto_assets = trading_client.get_all_assets(
1009
GetAssetsRequest(asset_class=AssetClass.CRYPTO)
1010
)
1011
for asset in crypto_assets[:5]:
1012
print(f"{asset.symbol}: {asset.name}")
1013
```
1014
1015
## Market Information
1016
1017
### Market Clock
1018
1019
#### get_clock()
1020
1021
```python { .api }
1022
def get_clock(self) -> Union[Clock, RawData]:
1023
"""
1024
Get market status and trading hours.
1025
1026
Returns:
1027
Clock: Current market status and times
1028
"""
1029
```
1030
1031
#### Clock Model
1032
1033
```python { .api }
1034
class Clock:
1035
"""Market status and trading hours."""
1036
1037
timestamp: datetime # Current timestamp
1038
is_open: bool # Whether market is currently open
1039
next_open: datetime # Next market open time
1040
next_close: datetime # Next market close time
1041
```
1042
1043
**Usage Examples:**
1044
1045
```python { .api }
1046
# Check market status
1047
clock = trading_client.get_clock()
1048
print(f"Market is {'open' if clock.is_open else 'closed'}")
1049
print(f"Next open: {clock.next_open}")
1050
print(f"Next close: {clock.next_close}")
1051
1052
# Wait for market open
1053
if not clock.is_open:
1054
import time
1055
wait_seconds = (clock.next_open - clock.timestamp).total_seconds()
1056
print(f"Market opens in {wait_seconds/3600:.1f} hours")
1057
```
1058
1059
### Market Calendar
1060
1061
#### get_calendar()
1062
1063
```python { .api }
1064
def get_calendar(
1065
self,
1066
filters: Optional[GetCalendarRequest] = None
1067
) -> Union[List[Calendar], RawData]:
1068
"""
1069
Get market calendar with trading days and hours.
1070
1071
Args:
1072
filters: Date range for calendar
1073
1074
Returns:
1075
List[Calendar]: Market calendar entries
1076
"""
1077
```
1078
1079
#### GetCalendarRequest
1080
1081
```python { .api }
1082
from alpaca.trading.requests import GetCalendarRequest
1083
from datetime import date
1084
1085
class GetCalendarRequest(NonEmptyRequest):
1086
def __init__(
1087
self,
1088
start: Optional[date] = None, # Start date
1089
end: Optional[date] = None # End date
1090
):
1091
```
1092
1093
#### Calendar Model
1094
1095
```python { .api }
1096
class Calendar:
1097
"""Market trading day information."""
1098
1099
date: date # Trading date
1100
open: datetime # Market open time
1101
close: datetime # Market close time
1102
session_open: Optional[datetime] # Extended session open
1103
session_close: Optional[datetime] # Extended session close
1104
```
1105
1106
**Usage Examples:**
1107
1108
```python { .api }
1109
from datetime import date, timedelta
1110
1111
# Get next 30 days of market calendar
1112
calendar = trading_client.get_calendar(
1113
GetCalendarRequest(
1114
start=date.today(),
1115
end=date.today() + timedelta(days=30)
1116
)
1117
)
1118
1119
print("Upcoming trading days:")
1120
for day in calendar[:5]:
1121
print(f"{day.date}: {day.open.time()} - {day.close.time()}")
1122
1123
# Check if today is a trading day
1124
today = date.today()
1125
is_trading_day = any(day.date == today for day in calendar)
1126
print(f"Today is {'a' if is_trading_day else 'not a'} trading day")
1127
```
1128
1129
## Watchlist Management
1130
1131
### Watchlist Operations
1132
1133
#### get_watchlists()
1134
1135
```python { .api }
1136
def get_watchlists(self) -> Union[List[Watchlist], RawData]:
1137
"""
1138
Get all watchlists.
1139
1140
Returns:
1141
List[Watchlist]: All user watchlists
1142
"""
1143
```
1144
1145
#### get_watchlist_by_id()
1146
1147
```python { .api }
1148
def get_watchlist_by_id(
1149
self,
1150
watchlist_id: Union[UUID, str]
1151
) -> Union[Watchlist, RawData]:
1152
"""
1153
Get specific watchlist.
1154
1155
Args:
1156
watchlist_id: Watchlist UUID
1157
1158
Returns:
1159
Watchlist: The specified watchlist
1160
"""
1161
```
1162
1163
#### create_watchlist()
1164
1165
```python { .api }
1166
def create_watchlist(
1167
self,
1168
watchlist_data: CreateWatchlistRequest
1169
) -> Union[Watchlist, RawData]:
1170
"""
1171
Create new watchlist.
1172
1173
Args:
1174
watchlist_data: Watchlist creation parameters
1175
1176
Returns:
1177
Watchlist: Created watchlist
1178
"""
1179
```
1180
1181
#### update_watchlist_by_id()
1182
1183
```python { .api }
1184
def update_watchlist_by_id(
1185
self,
1186
watchlist_id: Union[UUID, str],
1187
watchlist_data: UpdateWatchlistRequest,
1188
) -> Union[Watchlist, RawData]:
1189
"""
1190
Update watchlist details.
1191
1192
Args:
1193
watchlist_id: Watchlist UUID
1194
watchlist_data: New watchlist parameters
1195
1196
Returns:
1197
Watchlist: Updated watchlist
1198
"""
1199
```
1200
1201
#### add_asset_to_watchlist_by_id()
1202
1203
```python { .api }
1204
def add_asset_to_watchlist_by_id(
1205
self,
1206
watchlist_id: Union[UUID, str],
1207
symbol: str,
1208
) -> Union[Watchlist, RawData]:
1209
"""
1210
Add asset to watchlist.
1211
1212
Args:
1213
watchlist_id: Watchlist UUID
1214
symbol: Asset symbol to add
1215
1216
Returns:
1217
Watchlist: Updated watchlist
1218
"""
1219
```
1220
1221
#### remove_asset_from_watchlist_by_id()
1222
1223
```python { .api }
1224
def remove_asset_from_watchlist_by_id(
1225
self,
1226
watchlist_id: Union[UUID, str],
1227
symbol: str,
1228
) -> Union[Watchlist, RawData]:
1229
"""
1230
Remove asset from watchlist.
1231
1232
Args:
1233
watchlist_id: Watchlist UUID
1234
symbol: Asset symbol to remove
1235
1236
Returns:
1237
Watchlist: Updated watchlist
1238
"""
1239
```
1240
1241
#### delete_watchlist_by_id()
1242
1243
```python { .api }
1244
def delete_watchlist_by_id(self, watchlist_id: Union[UUID, str]) -> None:
1245
"""
1246
Delete watchlist.
1247
1248
Args:
1249
watchlist_id: Watchlist UUID to delete
1250
"""
1251
```
1252
1253
#### Watchlist Request Classes
1254
1255
```python { .api }
1256
from alpaca.trading.requests import CreateWatchlistRequest, UpdateWatchlistRequest
1257
1258
class CreateWatchlistRequest(NonEmptyRequest):
1259
def __init__(
1260
self,
1261
name: str, # Watchlist name
1262
symbols: Optional[List[str]] = None # Initial symbols
1263
):
1264
1265
class UpdateWatchlistRequest(NonEmptyRequest):
1266
def __init__(
1267
self,
1268
name: Optional[str] = None, # New name
1269
symbols: Optional[List[str]] = None # Replace symbols
1270
):
1271
```
1272
1273
#### Watchlist Model
1274
1275
```python { .api }
1276
class Watchlist:
1277
"""User-created watchlist of assets."""
1278
1279
id: UUID # Watchlist UUID
1280
name: str # Watchlist name
1281
assets: List[Asset] # Assets in watchlist
1282
created_at: datetime # Creation timestamp
1283
updated_at: datetime # Last update timestamp
1284
account_id: UUID # Owner account ID
1285
```
1286
1287
**Usage Examples:**
1288
1289
```python { .api }
1290
# Create new watchlist
1291
tech_watchlist = trading_client.create_watchlist(
1292
CreateWatchlistRequest(
1293
name="Tech Stocks",
1294
symbols=["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]
1295
)
1296
)
1297
print(f"Created watchlist: {tech_watchlist.id}")
1298
1299
# Get all watchlists
1300
watchlists = trading_client.get_watchlists()
1301
for wl in watchlists:
1302
print(f"{wl.name}: {len(wl.assets)} assets")
1303
1304
# Add stock to watchlist
1305
updated_watchlist = trading_client.add_asset_to_watchlist_by_id(
1306
tech_watchlist.id, "NVDA"
1307
)
1308
1309
# Remove stock from watchlist
1310
updated_watchlist = trading_client.remove_asset_from_watchlist_by_id(
1311
tech_watchlist.id, "AMZN"
1312
)
1313
1314
# Update watchlist name
1315
updated_watchlist = trading_client.update_watchlist_by_id(
1316
tech_watchlist.id,
1317
UpdateWatchlistRequest(name="FAANG+ Stocks")
1318
)
1319
1320
# Delete watchlist
1321
trading_client.delete_watchlist_by_id(tech_watchlist.id)
1322
```
1323
1324
## Options Trading
1325
1326
### Option Contracts
1327
1328
#### get_option_contracts()
1329
1330
```python { .api }
1331
def get_option_contracts(
1332
self,
1333
request: GetOptionContractsRequest
1334
) -> Union[OptionContractsResponse, RawData]:
1335
"""
1336
Get available option contracts.
1337
1338
Args:
1339
request: Option contract query parameters
1340
1341
Returns:
1342
OptionContractsResponse: Available contracts and pagination
1343
"""
1344
```
1345
1346
#### get_option_contract()
1347
1348
```python { .api }
1349
def get_option_contract(
1350
self,
1351
symbol_or_id: Union[str, UUID]
1352
) -> Union[OptionContract, RawData]:
1353
"""
1354
Get specific option contract details.
1355
1356
Args:
1357
symbol_or_id: Option symbol or contract UUID
1358
1359
Returns:
1360
OptionContract: Contract details
1361
"""
1362
```
1363
1364
#### GetOptionContractsRequest
1365
1366
```python { .api }
1367
from alpaca.trading.requests import GetOptionContractsRequest
1368
from alpaca.trading.enums import ContractType, ExerciseStyle
1369
from datetime import date
1370
1371
class GetOptionContractsRequest(NonEmptyRequest):
1372
def __init__(
1373
self,
1374
underlying_symbols: Optional[Union[str, List[str]]] = None, # Underlying stocks
1375
underlying_asset_ids: Optional[Union[str, List[str]]] = None, # Underlying UUIDs
1376
type: Optional[ContractType] = None, # CALL, PUT
1377
strike_price_gte: Optional[float] = None, # Min strike price
1378
strike_price_lte: Optional[float] = None, # Max strike price
1379
expiration_date: Optional[date] = None, # Specific expiry
1380
expiration_date_gte: Optional[date] = None, # Min expiry
1381
expiration_date_lte: Optional[date] = None, # Max expiry
1382
root_symbol: Optional[str] = None, # Option root
1383
limit: Optional[int] = None, # Max contracts returned
1384
page_token: Optional[str] = None, # Pagination token
1385
exercise_style: Optional[ExerciseStyle] = None, # AMERICAN, EUROPEAN
1386
style: Optional[ExerciseStyle] = None, # Deprecated alias
1387
):
1388
```
1389
1390
#### OptionContract Model
1391
1392
```python { .api }
1393
class OptionContract:
1394
"""Option contract details."""
1395
1396
id: UUID # Contract UUID
1397
symbol: str # Option symbol (OCC format)
1398
name: str # Contract name
1399
status: AssetStatus # Contract status
1400
tradable: bool # Can be traded
1401
underlying_asset_id: UUID # Underlying stock UUID
1402
underlying_symbol: str # Underlying stock symbol
1403
type: ContractType # CALL or PUT
1404
exercise_style: ExerciseStyle # AMERICAN or EUROPEAN
1405
strike_price: float # Strike price
1406
expiration_date: date # Expiration date
1407
size: int # Contract size (usually 100)
1408
open_interest: Optional[int] # Current open interest
1409
close_price: Optional[float] # Last close price
1410
close_price_date: Optional[date] # Last close price date
1411
```
1412
1413
**Usage Examples:**
1414
1415
```python { .api }
1416
# Get AAPL call options expiring next month
1417
from datetime import date, timedelta
1418
1419
next_month = date.today() + timedelta(days=30)
1420
aapl_calls = trading_client.get_option_contracts(
1421
GetOptionContractsRequest(
1422
underlying_symbols="AAPL",
1423
type=ContractType.CALL,
1424
expiration_date_gte=date.today(),
1425
expiration_date_lte=next_month,
1426
limit=50
1427
)
1428
)
1429
1430
print(f"Found {len(aapl_calls.option_contracts)} AAPL call contracts")
1431
for contract in aapl_calls.option_contracts[:5]:
1432
print(f"{contract.symbol}: Strike ${contract.strike_price}, Expires {contract.expiration_date}")
1433
1434
# Get specific option contract
1435
contract = trading_client.get_option_contract("AAPL230317C00150000")
1436
print(f"Contract: {contract.name}")
1437
print(f"Strike: ${contract.strike_price}")
1438
print(f"Expiry: {contract.expiration_date}")
1439
print(f"Open Interest: {contract.open_interest}")
1440
1441
# Find at-the-money puts
1442
current_price = 150.00 # Assume current AAPL price
1443
atm_puts = trading_client.get_option_contracts(
1444
GetOptionContractsRequest(
1445
underlying_symbols="AAPL",
1446
type=ContractType.PUT,
1447
strike_price_gte=current_price - 5,
1448
strike_price_lte=current_price + 5,
1449
expiration_date_gte=date.today() + timedelta(days=7)
1450
)
1451
)
1452
```
1453
1454
### Option Order Examples
1455
1456
```python { .api }
1457
# Buy call option
1458
call_buy = MarketOrderRequest(
1459
symbol="AAPL230317C00150000", # OCC option symbol
1460
qty=1, # 1 contract = 100 shares
1461
side=OrderSide.BUY,
1462
time_in_force=TimeInForce.DAY,
1463
position_intent=PositionIntent.BTO # Buy to Open
1464
)
1465
option_order = trading_client.submit_order(call_buy)
1466
1467
# Sell put option (cash-secured)
1468
put_sell = LimitOrderRequest(
1469
symbol="AAPL230317P00140000",
1470
qty=2,
1471
side=OrderSide.SELL,
1472
time_in_force=TimeInForce.GTC,
1473
limit_price=3.50, # Premium per share ($350 per contract)
1474
position_intent=PositionIntent.STO # Sell to Open
1475
)
1476
option_order = trading_client.submit_order(put_sell)
1477
1478
# Close option position
1479
option_close = MarketOrderRequest(
1480
symbol="AAPL230317C00150000",
1481
qty=1,
1482
side=OrderSide.SELL,
1483
time_in_force=TimeInForce.DAY,
1484
position_intent=PositionIntent.BTC # Buy to Close (for short position)
1485
)
1486
close_order = trading_client.submit_order(option_close)
1487
```
1488
1489
## Corporate Actions
1490
1491
### Corporate Action Information
1492
1493
#### get_corporate_announcements()
1494
1495
```python { .api }
1496
def get_corporate_announcements(
1497
self,
1498
filter: GetCorporateAnnouncementsRequest
1499
) -> Union[List[CorporateActionAnnouncement], RawData]:
1500
"""
1501
Get corporate action announcements.
1502
1503
Args:
1504
filter: Corporate action query parameters
1505
1506
Returns:
1507
List[CorporateActionAnnouncement]: Corporate actions
1508
"""
1509
```
1510
1511
#### get_corporate_announcement_by_id()
1512
1513
```python { .api }
1514
def get_corporate_announcement_by_id(
1515
self,
1516
corporate_announcement_id: Union[str, UUID]
1517
) -> Union[CorporateActionAnnouncement, RawData]:
1518
"""
1519
Get specific corporate action by ID.
1520
1521
Args:
1522
corporate_announcement_id: Corporate action UUID
1523
1524
Returns:
1525
CorporateActionAnnouncement: Corporate action details
1526
"""
1527
```
1528
1529
#### GetCorporateAnnouncementsRequest
1530
1531
```python { .api }
1532
from alpaca.trading.requests import GetCorporateAnnouncementsRequest
1533
from alpaca.trading.enums import CorporateActionType, CorporateActionDateType
1534
1535
class GetCorporateAnnouncementsRequest(NonEmptyRequest):
1536
def __init__(
1537
self,
1538
ca_types: Union[CorporateActionType, List[CorporateActionType]], # Required
1539
since: datetime, # Required
1540
until: datetime, # Required
1541
symbol: Optional[str] = None, # Specific symbol
1542
cusip: Optional[str] = None, # CUSIP filter
1543
date_type: Optional[CorporateActionDateType] = None, # ex_date, record_date, etc.
1544
):
1545
```
1546
1547
**Usage Examples:**
1548
1549
```python { .api }
1550
from alpaca.trading.enums import CorporateActionType
1551
from datetime import datetime, timedelta
1552
1553
# Get recent dividend announcements
1554
recent_dividends = trading_client.get_corporate_announcements(
1555
GetCorporateAnnouncementsRequest(
1556
ca_types=CorporateActionType.DIVIDEND,
1557
since=datetime.now() - timedelta(days=30),
1558
until=datetime.now()
1559
)
1560
)
1561
1562
# Get stock split announcements for AAPL
1563
aapl_splits = trading_client.get_corporate_announcements(
1564
GetCorporateAnnouncementsRequest(
1565
ca_types=CorporateActionType.SPLIT,
1566
symbol="AAPL",
1567
since=datetime.now() - timedelta(days=365),
1568
until=datetime.now()
1569
)
1570
)
1571
```
1572
1573
## Real-time Trading Updates
1574
1575
### Trading Stream
1576
1577
```python { .api }
1578
from alpaca.trading.stream import TradingStream
1579
1580
class TradingStream:
1581
def __init__(
1582
self,
1583
api_key: Optional[str] = None,
1584
secret_key: Optional[str] = None,
1585
paper: bool = True,
1586
raw_data: bool = False,
1587
url_override: Optional[str] = None,
1588
websocket_params: Optional[dict] = None
1589
):
1590
"""
1591
Initialize trading stream for real-time trade updates.
1592
1593
Args:
1594
api_key: API key for authentication
1595
secret_key: Secret key for authentication
1596
paper: True for paper trading, False for live
1597
raw_data: Return raw data instead of models
1598
url_override: Override WebSocket URL
1599
websocket_params: Additional WebSocket configuration
1600
"""
1601
1602
def subscribe_trade_updates(self, handler: Callable) -> None:
1603
"""
1604
Subscribe to trade execution updates.
1605
1606
Args:
1607
handler: Async callback function for trade updates
1608
"""
1609
1610
async def run(self) -> None:
1611
"""Start the WebSocket connection and begin streaming."""
1612
```
1613
1614
#### Trade Update Handler
1615
1616
```python { .api }
1617
# Trade update streaming example
1618
from alpaca.trading.stream import TradingStream
1619
1620
stream = TradingStream(
1621
api_key="your-api-key",
1622
secret_key="your-secret-key",
1623
paper=True
1624
)
1625
1626
async def trade_update_handler(data):
1627
"""Handle trade update events."""
1628
print(f"Trade Update: {data.event}")
1629
print(f"Order ID: {data.order.id}")
1630
print(f"Symbol: {data.order.symbol}")
1631
print(f"Status: {data.order.status}")
1632
1633
if data.event == "filled":
1634
print(f"Filled: {data.order.filled_qty} @ ${data.order.filled_avg_price}")
1635
elif data.event == "canceled":
1636
print(f"Order canceled: {data.order.cancel_requested_at}")
1637
1638
# Subscribe to trade updates
1639
stream.subscribe_trade_updates(trade_update_handler)
1640
1641
# Start streaming (async)
1642
import asyncio
1643
asyncio.run(stream.run())
1644
```
1645
1646
## Enums and Constants
1647
1648
### Order Enums
1649
1650
```python { .api }
1651
from alpaca.trading.enums import (
1652
OrderSide, OrderType, OrderClass, OrderStatus, TimeInForce,
1653
PositionSide, PositionIntent, QueryOrderStatus
1654
)
1655
1656
class OrderSide(str, Enum):
1657
BUY = "buy"
1658
SELL = "sell"
1659
1660
class OrderType(str, Enum):
1661
MARKET = "market"
1662
LIMIT = "limit"
1663
STOP = "stop"
1664
STOP_LIMIT = "stop_limit"
1665
TRAILING_STOP = "trailing_stop"
1666
1667
class OrderClass(str, Enum):
1668
SIMPLE = "simple"
1669
BRACKET = "bracket"
1670
OCO = "oco" # One-Cancels-Other
1671
OTO = "oto" # One-Triggers-Other
1672
MLEG = "multileg" # Multi-leg options
1673
1674
class TimeInForce(str, Enum):
1675
DAY = "day" # Good for day
1676
GTC = "gtc" # Good till canceled
1677
OPG = "opg" # Market on open
1678
CLS = "cls" # Market on close
1679
IOC = "ioc" # Immediate or cancel
1680
FOK = "fok" # Fill or kill
1681
1682
class OrderStatus(str, Enum):
1683
NEW = "new"
1684
PARTIALLY_FILLED = "partially_filled"
1685
FILLED = "filled"
1686
DONE_FOR_DAY = "done_for_day"
1687
CANCELED = "canceled"
1688
EXPIRED = "expired"
1689
REPLACED = "replaced"
1690
PENDING_CANCEL = "pending_cancel"
1691
PENDING_REPLACE = "pending_replace"
1692
PENDING_REVIEW = "pending_review"
1693
ACCEPTED = "accepted"
1694
PENDING_NEW = "pending_new"
1695
ACCEPTED_FOR_BIDDING = "accepted_for_bidding"
1696
STOPPED = "stopped"
1697
REJECTED = "rejected"
1698
SUSPENDED = "suspended"
1699
CALCULATED = "calculated"
1700
1701
class PositionIntent(str, Enum):
1702
BTO = "buy_to_open" # Buy to open position
1703
BTC = "buy_to_close" # Buy to close short position
1704
STO = "sell_to_open" # Sell to open short position
1705
STC = "sell_to_close" # Sell to close long position
1706
```
1707
1708
### Asset Enums
1709
1710
```python { .api }
1711
from alpaca.trading.enums import AssetClass, AssetStatus, AssetExchange
1712
1713
class AssetClass(str, Enum):
1714
US_EQUITY = "us_equity"
1715
CRYPTO = "crypto"
1716
US_OPTION = "us_option"
1717
1718
class AssetStatus(str, Enum):
1719
ACTIVE = "active"
1720
INACTIVE = "inactive"
1721
DELISTED = "delisted"
1722
1723
class AssetExchange(str, Enum):
1724
NASDAQ = "NASDAQ"
1725
NYSE = "NYSE"
1726
ARCA = "ARCA"
1727
BATS = "BATS"
1728
# ... many more exchanges
1729
```
1730
1731
### Configuration Enums
1732
1733
```python { .api }
1734
from alpaca.trading.enums import DTBPCheck, TradeConfirmationEmail
1735
1736
class DTBPCheck(str, Enum):
1737
NONE = "none" # No day trading buying power check
1738
BOTH = "both" # Check on entry and exit
1739
ENTRY = "entry" # Check on position entry only
1740
EXIT = "exit" # Check on position exit only
1741
1742
class TradeConfirmationEmail(str, Enum):
1743
NONE = "none" # No email confirmations
1744
ALL = "all" # Email for all trades
1745
```
1746
1747
## Error Handling
1748
1749
```python { .api }
1750
from alpaca.common.exceptions import APIError
1751
1752
try:
1753
# Submit order that might fail
1754
order = trading_client.submit_order(order_data)
1755
except APIError as e:
1756
print(f"Order failed: {e.message}")
1757
print(f"HTTP Status: {e.status_code}")
1758
print(f"Request ID: {e.request_id}")
1759
1760
# Handle specific error cases
1761
if e.status_code == 403:
1762
print("Insufficient buying power or permissions")
1763
elif e.status_code == 422:
1764
print("Invalid order parameters")
1765
elif e.status_code == 429:
1766
print("Rate limit exceeded")
1767
except Exception as e:
1768
print(f"Unexpected error: {e}")
1769
```
1770
1771
## Complete Trading Example
1772
1773
```python { .api }
1774
import asyncio
1775
from datetime import datetime, timedelta
1776
from alpaca.trading import TradingClient
1777
from alpaca.trading.stream import TradingStream
1778
from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest
1779
from alpaca.trading.enums import OrderSide, TimeInForce, QueryOrderStatus
1780
1781
class TradingBot:
1782
def __init__(self, api_key: str, secret_key: str, paper: bool = True):
1783
self.trading_client = TradingClient(api_key, secret_key, paper=paper)
1784
self.stream = TradingStream(api_key, secret_key, paper=paper)
1785
self.stream.subscribe_trade_updates(self.on_trade_update)
1786
1787
def check_account(self):
1788
"""Check account status and buying power."""
1789
account = self.trading_client.get_account()
1790
print(f"Account: {account.account_number}")
1791
print(f"Buying Power: ${account.buying_power:,.2f}")
1792
print(f"Portfolio Value: ${account.portfolio_value:,.2f}")
1793
return account
1794
1795
def get_positions(self):
1796
"""Get current positions."""
1797
positions = self.trading_client.get_positions()
1798
print(f"\nCurrent Positions ({len(positions)}):")
1799
for pos in positions:
1800
pnl_pct = (float(pos.unrealized_pl) / float(pos.cost_basis)) * 100
1801
print(f"{pos.symbol}: {pos.qty} shares, P&L: ${pos.unrealized_pl} ({pnl_pct:.1f}%)")
1802
return positions
1803
1804
def place_bracket_order(self, symbol: str, qty: float, take_profit_pct: float = 0.05, stop_loss_pct: float = 0.03):
1805
"""Place bracket order with take profit and stop loss."""
1806
try:
1807
# Get current price for bracket calculations
1808
asset = self.trading_client.get_asset(symbol)
1809
1810
bracket_order = MarketOrderRequest(
1811
symbol=symbol,
1812
qty=qty,
1813
side=OrderSide.BUY,
1814
time_in_force=TimeInForce.DAY,
1815
order_class=OrderClass.BRACKET,
1816
take_profit=TakeProfitRequest(
1817
limit_price=None # Will be calculated by server based on percentage
1818
),
1819
stop_loss=StopLossRequest(
1820
stop_price=None # Will be calculated by server
1821
)
1822
)
1823
1824
order = self.trading_client.submit_order(bracket_order)
1825
print(f"Bracket order placed: {order.id}")
1826
return order
1827
1828
except APIError as e:
1829
print(f"Order failed: {e.message}")
1830
return None
1831
1832
def cancel_all_orders(self):
1833
"""Cancel all open orders."""
1834
cancel_responses = self.trading_client.cancel_orders()
1835
print(f"Attempted to cancel {len(cancel_responses)} orders")
1836
1837
async def on_trade_update(self, data):
1838
"""Handle real-time trade updates."""
1839
print(f"\n[{datetime.now()}] Trade Update: {data.event.upper()}")
1840
print(f"Order: {data.order.symbol} {data.order.side} {data.order.qty}")
1841
1842
if data.event == "filled":
1843
print(f"โ FILLED: {data.order.filled_qty} @ ${data.order.filled_avg_price}")
1844
elif data.event == "canceled":
1845
print(f"โ CANCELED")
1846
elif data.event == "rejected":
1847
print(f"๐ซ REJECTED")
1848
1849
async def run_strategy(self):
1850
"""Main trading strategy loop."""
1851
print("๐ Starting trading bot...")
1852
1853
# Check initial account state
1854
account = self.check_account()
1855
if account.buying_power < 1000:
1856
print("โ ๏ธ Insufficient buying power")
1857
return
1858
1859
# Get current positions
1860
self.get_positions()
1861
1862
# Start stream for real-time updates
1863
stream_task = asyncio.create_task(self.stream.run())
1864
1865
# Example strategy: Buy some stocks if we have buying power
1866
if account.buying_power > 5000:
1867
print("\n๐ Executing sample trades...")
1868
1869
# Place some orders
1870
self.place_bracket_order("AAPL", 10)
1871
await asyncio.sleep(2)
1872
1873
self.place_bracket_order("TSLA", 5)
1874
await asyncio.sleep(2)
1875
1876
# Monitor for 60 seconds, then cleanup
1877
await asyncio.sleep(60)
1878
1879
print("\n๐งน Cleaning up...")
1880
self.cancel_all_orders()
1881
1882
# Close positions if desired
1883
positions = self.trading_client.get_all_positions()
1884
if positions:
1885
print("Closing all positions...")
1886
self.trading_client.close_all_positions(cancel_orders=True)
1887
1888
stream_task.cancel()
1889
print("โ Trading session complete")
1890
1891
# Run the trading bot
1892
if __name__ == "__main__":
1893
bot = TradingBot(
1894
api_key="your-paper-api-key",
1895
secret_key="your-paper-secret-key",
1896
paper=True
1897
)
1898
1899
asyncio.run(bot.run_strategy())
1900
```