P
PipsGrowth
← Back to Libraries

Alpaca for Live Trading

Commission-free trading API for stocks and crypto. Features paper trading, real-time market data, and easy integration with Python trading systems.

Difficulty: Beginner
Category: Live Trading
💰 Commission-Free

Installation

Install the official Alpaca Python SDK for trading and market data access.

# Install Alpaca SDK
$ pip install alpaca-py
# Or with all dependencies
$ pip install alpaca-py pandas numpy

Key Features

Commission-Free Trading

Trade stocks and crypto with zero commission. No hidden fees or payment for order flow.

Fast Execution

Direct market access with low latency execution for both paper and live trading.

Free Market Data

Access to real-time and historical market data for stocks and cryptocurrencies.

Paper Trading

Full-featured paper trading environment to test strategies without risking real money.

Code Examples

Setup and Authentication

Connect to Alpaca API with credentials

Python
from alpaca.trading.client import TradingClient
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
import os
# API credentials (use environment variables in production)
API_KEY = os.environ.get('ALPACA_API_KEY')
API_SECRET = os.environ.get('ALPACA_SECRET_KEY')
# Initialize clients
trading_client = TradingClient(API_KEY, API_SECRET, paper=True)
data_client = StockHistoricalDataClient(API_KEY, API_SECRET)
# Get account info
account = trading_client.get_account()
print(f"Account Status: {account.status}")
print(f"Buying Power: {float(account.buying_power):,.2f} USD")
print(f"Portfolio Value: {float(account.portfolio_value):,.2f} USD")
print(f"Cash: {float(account.cash):,.2f} USD")

Get Historical Market Data

Download stock and crypto price data

Python
from alpaca.data.historical import StockHistoricalDataClient, CryptoHistoricalDataClient
from alpaca.data.requests import StockBarsRequest, CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime
# Initialize data client
data_client = StockHistoricalDataClient(API_KEY, API_SECRET)
# Get stock bars
request = StockBarsRequest(
symbol_or_symbols = ["AAPL", "MSFT", "GOOGL"],
timeframe = TimeFrame.Day,
start = datetime(2024, 1, 1),
end = datetime(2024, 6, 1)
)
bars = data_client.get_stock_bars(request)
# Convert to DataFrame
df = bars.df
print(df.head())
# Get crypto data
crypto_client = CryptoHistoricalDataClient()
crypto_request = CryptoBarsRequest(
symbol_or_symbols = ["BTC/USD", "ETH/USD"],
timeframe = TimeFrame.Hour,
start = datetime(2024, 1, 1),
end = datetime(2024, 1, 7)
)
crypto_bars = crypto_client.get_crypto_bars(crypto_request)

Place Orders

Submit market and limit orders

Python
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
trading_client = TradingClient(API_KEY, API_SECRET, paper = True)
# Market Order - Buy 10 shares of AAPL
market_order = MarketOrderRequest(
symbol = "AAPL",
qty = 10,
side = OrderSide.BUY,
time_in_force = TimeInForce.DAY
)
order = trading_client.submit_order(market_order)
print(f"Market Order ID: {order.id}")
# Limit Order - Buy at specific price
limit_order = LimitOrderRequest(
symbol = "MSFT",
qty = 5,
side = OrderSide.BUY,
time_in_force = TimeInForce.GTC,
limit_price = 350.00
)
limit_result = trading_client.submit_order(limit_order)
# Sell Order
sell_order = MarketOrderRequest(
symbol = "AAPL",
qty = 5,
side = OrderSide.SELL,
time_in_force = TimeInForce.DAY
)
trading_client.submit_order(sell_order)

Bracket Orders with Stop Loss

Create orders with automatic stop loss and take profit

Python
from alpaca.trading.requests import MarketOrderRequest, TakeProfitRequest, StopLossRequest
from alpaca.trading.enums import OrderSide, TimeInForce, OrderClass
# Bracket Order: Entry + Take Profit + Stop Loss
bracket_order = MarketOrderRequest(
symbol = "AAPL",
qty = 10,
side = OrderSide.BUY,
time_in_force = TimeInForce.GTC,
order_class = OrderClass.BRACKET,
take_profit = TakeProfitRequest(limit_price = 200.00),
stop_loss = StopLossRequest(stop_price = 170.00, limit_price = 169.00)
)
order = trading_client.submit_order(bracket_order)
print(f"Bracket Order: {order.id}")
print(f" Take Profit: {order.legs[0].id}")
print(f" Stop Loss: {order.legs[1].id}")
# OCO Order: One Cancels Other
from alpaca.trading.requests import LimitOrderRequest
oco_order = LimitOrderRequest(
symbol = "MSFT",
qty = 5,
side = OrderSide.SELL,
time_in_force = TimeInForce.GTC,
order_class = OrderClass.OCO,
take_profit = TakeProfitRequest(limit_price = 420.00),
stop_loss = StopLossRequest(stop_price = 380.00)
)
trading_client.submit_order(oco_order)

Manage Positions

View and close positions

Python
# Get all positions
positions = trading_client.get_all_positions()
for pos in positions:
print(f"{pos.symbol}: {pos.qty} shares @ " + str(pos.avg_entry_price))
print(f" Market Value: " + str(pos.market_value))
print(f" P/L: {pos.unrealized_pl} ({pos.unrealized_plpc}%)")
# Get specific position
try:
aapl = trading_client.get_open_position("AAPL")
print(f"AAPL Position: {aapl.qty} shares")
except Exception as e:
print("No AAPL position")
# Close a position
trading_client.close_position("AAPL")
# Close all positions
trading_client.close_all_positions()
# Get recent orders
orders = trading_client.get_orders()
for order in orders[:5]:
print(f"{order.symbol}: {order.side} {order.qty} - {order.status}")

Real-Time Streaming

Stream live market data and trade updates

Python
from alpaca.data.live import StockDataStream
from alpaca.trading.stream import TradingStream
import asyncio
# Market Data Stream
data_stream = StockDataStream(API_KEY, API_SECRET)
async def handle_bar(bar):
print(f"Bar: {bar.symbol} - Close: {bar.close}")
async def handle_trade(trade):
print(f"Trade: {trade.symbol} - Price: {trade.price}")
# Subscribe to data
data_stream.subscribe_bars(handle_bar, "AAPL", "MSFT")
data_stream.subscribe_trades(handle_trade, "AAPL")
# Trading Updates Stream
trade_stream = TradingStream(API_KEY, API_SECRET, paper = True)
async def handle_trade_update(update):
print(f"Order Update: {update.order.symbol} - {update.event}")
if update.event == 'fill':
print(f" Filled at: " + str(update.order.filled_avg_price))
trade_stream.subscribe_trade_updates(handle_trade_update)
# Run streams(in production, run in background)
# data_stream.run()
# trade_stream.run()

Common Use Cases

Algorithmic trading bots
Portfolio automation
Paper trading systems
Market data analysis
Backtesting validation
Real-time monitoring
Position management
Order execution
Crypto trading
Strategy deployment

Best Practices & Common Pitfalls

Use Paper Trading First

Always test your strategies in paper trading mode before going live with real money.

Environment Variables

Store API keys in environment variables, never hardcode them in your scripts.

Handle Rate Limits

Implement proper rate limiting and error handling for API calls.

Market Hours

Alpaca only allows trading during market hours (9:30 AM - 4:00 PM ET) for regular stocks.

PDT Rule

Pattern Day Trader rules apply to accounts under $25,000. Limit day trades to 3 per 5 days.

Order Validation

Always validate orders before submission and handle rejection gracefully.

Additional Resources

Related Libraries

  • pandas - Data analysis
  • bt/backtrader - Strategy backtesting
  • pandas-ta - Technical indicators

Next Steps

Build a complete trading system by combining Alpaca with backtesting frameworks: