Files

4.0 KiB

In [11]:
import os
from dotenv import load_dotenv
from alpaca.trading.client import TradingClient

load_dotenv()

# Set paper=True for paper trading (sandbox), paper=False for live trading
trading_client = TradingClient(
    api_key=os.getenv("ALPACA_API_KEY"),
    secret_key=os.getenv("ALPACA_SECRET_KEY"),
    paper=True,
)
In [13]:
positions = trading_client.get_all_positions()

if not positions:
    print("No open positions.")
else:
    print("Current Portfolio Positions:")
    for pos in positions:
        print(
            f"Symbol: {pos.symbol:<5} | "
            f"Qty: {pos.qty:<5} | "
            f"Avg Entry Price: ${float(pos.avg_entry_price):.2f} | "
            f"Current Price: ${float(pos.current_price):.2f} | "
            f"Unrealized P/L: ${float(pos.unrealized_pl):.2f}"
        )
No open positions.
In [16]:
account = trading_client.get_account()
print(
    account.cash,
    account.equity
)
99997.95 99997.95
In [17]:
from alpaca.trading.requests import GetOrdersRequest
from alpaca.trading.enums import QueryOrderStatus

# Request only open orders
request_params = GetOrdersRequest(status=QueryOrderStatus.OPEN)
open_orders = trading_client.get_orders(filter=request_params)

if not open_orders:
    print("No open orders found.")
else:
    print(f"Found {len(open_orders)} open order(s):")
    for order in open_orders:
        print(
            f"ID: {order.id} | Symbol: {order.symbol} | "
            f"Side: {order.side} | Qty: {order.qty} | Status: {order.status}"
        )
No open orders found.
In [18]:
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

# Define a market buy order for 10 shares of SPY
market_order_data = MarketOrderRequest(
    symbol="SPY",
    notional=100.0,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY,
)

# Submit the order
order = trading_client.submit_order(order_data=market_order_data)

print(f"Submitted Order ID: {order.id} | Status: {order.status}")
Submitted Order ID: 4838c16d-7a12-4dc3-80cb-7c5d1dbecda3 | Status: OrderStatus.ACCEPTED