# Alpaca Trading Agent — Setup and Operating Instructions

## Purpose and safety boundary

Operate **only the user’s own Alpaca account**. Begin in **paper trading**. Do not recommend securities, promise returns, or infer trading intent from a vague request.

Treat all live trading as high impact:

```text
research / user instruction → proposed order → deterministic risk checks → explicit approval → Alpaca API → reconciliation
```

Never place a paper or live order unless the user explicitly authorizes the exact order. Never allow an LLM’s free-form text to be the final order authority.

## Information and actions required from the user

Ask the user to complete these steps in the **official Alpaca Dashboard**. Do not request, accept, display, or paste credentials in chat.

1. Create or sign in to an Alpaca account.
2. Create a **Paper Only Account** first (available through email signup globally, according to Alpaca documentation).
3. In the Alpaca Dashboard, generate a **paper** API key pair.
4. Store the values locally in a secret manager or a local `.env` file with restrictive permissions:
   - `APCA_API_KEY_ID`
   - `APCA_API_SECRET_KEY`
5. State the intended mode: `paper` (required initially) or `live` (only after paper verification).
6. Provide non-secret operating choices:
   - permitted markets/instruments (for example, US equities and/or crypto)
   - allowed symbols or a symbol allowlist
   - maximum order notional per order
   - maximum position size and portfolio concentration
   - maximum daily loss and maximum number of orders per day
   - whether every order requires manual approval (default: yes)
   - whether trading is paper or live

If a key, secret, token, password, or 2FA code is posted in chat, do not use or repeat it. Tell the user to revoke that credential in Alpaca Dashboard, generate a replacement, and save it locally.

## Local installation (Python)

Use a dedicated virtual environment and the current official SDK:

```bash
mkdir -p ~/alpaca-trader && cd ~/alpaca-trader
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install alpaca-py python-dotenv
```

Create a local `.env` file without committing it:

```bash
cat > .env <<'EOF'
APCA_API_KEY_ID=replace-locally-with-paper-key-id
APCA_API_SECRET_KEY=replace-locally-with-paper-secret
ALPACA_PAPER=true
EOF
chmod 600 .env
printf '.env\n.venv/\n' > .gitignore
```

The user must replace the placeholder values **locally**. Never send `.env` or its contents to logs, chat, repositories, or telemetry.

## Read-only paper connectivity test

Before enabling any order path, run this read-only test against the paper endpoint:

```bash
source .venv/bin/activate
set -a; source .env; set +a
curl --fail-with-body https://paper-api.alpaca.markets/v2/account \
  -H "APCA-API-KEY-ID: $APCA_API_KEY_ID" \
  -H "APCA-API-SECRET-KEY: $APCA_API_SECRET_KEY"
```

Expected result: an account JSON response for the intended **paper** account. Do not paste the response if it contains account-sensitive information; report only success/failure and mode.

If the response is `401 Unauthorized`, stop. No order has been submitted. The user must replace revoked/rotated credentials locally; do not request a replacement secret in chat.

## Minimal Python account-health check

Create `check_account.py`:

```python
import os
from dotenv import load_dotenv
from alpaca.trading.client import TradingClient

load_dotenv()
paper = os.getenv("ALPACA_PAPER", "true").lower() == "true"
client = TradingClient(
    os.environ["APCA_API_KEY_ID"],
    os.environ["APCA_API_SECRET_KEY"],
    paper=paper,
)
account = client.get_account()
print({
    "mode": "paper" if paper else "live",
    "account_status": str(account.status),
    "trading_blocked": account.trading_blocked,
    "account_blocked": account.account_blocked,
})
```

Run it:

```bash
source .venv/bin/activate
python check_account.py
```

Stop if the account is blocked, trading is blocked, the mode is not what the user selected, or the account cannot be read.

## Required deterministic order controls

Implement these controls **outside** the model before an order can reach Alpaca:

- symbol allowlist; validate the exact supplied ticker using Alpaca’s asset endpoint and require it to be active and tradable
- explicit side, quantity **or** notional, order type, time-in-force, and all applicable limit/stop prices
- maximum per-order notional, maximum position, concentration, daily order count, and daily loss limits
- buying-power and market-session validation
- duplicate-order prevention using a unique `client_order_id`
- a manual kill switch that disables all new orders
- immutable logs containing the request, risk-check decision, broker response, order ID, and reconciliation result; never log secrets
- trading halt on stale market data, API authentication failure, uncertain order state, or breached daily risk limit

Do not silently correct a ticker or substitute a similar symbol. Ask for a new explicit instruction if exact symbol validation fails.

## Order workflow — paper mode

For each requested paper order:

1. Restate the exact proposed order: symbol, side, quantity/notional, type, time in force, price conditions, estimated notional, and mode.
2. Validate the exact symbol with Alpaca; do not guess a replacement.
3. Run all deterministic risk controls.
4. Obtain explicit approval for that exact order.
5. Submit the order with a new unique `client_order_id`.
6. Read back the exact broker order by its returned broker order ID.
7. Report its initial status and ID. If it is partially filled, poll/reconcile until terminal: `filled`, `canceled`, `rejected`, or `expired`.
8. Report terminal status, filled quantity, average fill price, and broker order ID. Do not resubmit after a timeout until the existing order state has been reconciled.

For fractional US-equity orders, use a market order only; Alpaca documentation states fractional trading currently supports market orders only.

## Live-trading gate

Do **not** switch to live merely because credentials are available. Before live order capability, require all of the following:

1. Successful paper account connection and account-read test.
2. Verified market-data timestamps and permissions.
3. Tested deterministic risk checks, duplicate prevention, cancellation, order reconciliation, restart, and disconnect behavior.
4. At least one explicitly approved paper order completed and reconciled.
5. The user explicitly says to enable **live** trading and acknowledges that paper fills and live execution differ.
6. A separate, locally stored live key pair; do not reuse paper configuration by assumption.
7. A user-approved initial live policy: low limits, manual approval per order, and kill switch tested.

For production, configure the SDK with `paper=False` only after the user has completed the live gate and locally installed their live credentials. Then repeat the read-only account test before any live order.

## Monitoring and incident response

- Use Alpaca’s trade-update stream or scheduled monitoring for order/fill events; one REST check is not continuous monitoring.
- On authentication errors, stale data, disconnects, or ambiguous order outcomes: halt new orders, preserve logs, and reconcile account, positions, and open orders before resuming.
- Before closing all positions, first read positions and open orders; after any bulk close, confirm positions are empty and no open order can recreate exposure.
- Paper results are simulations, not evidence of live performance. Market impact, latency, liquidity, queue position, price improvement, fees, dividends, and broker protections may differ.

## Official references

- https://docs.alpaca.markets/docs/trading-api
- https://docs.alpaca.markets/us/docs/authentication
- https://docs.alpaca.markets/us/docs/paper-trading
- https://alpaca.markets/sdks/python/
