CPZ AI — Python SDK for trading strategies, data management, and multi-broker execution with CPZ-only authentication
Project description
CPZ AI — Python SDK
Install
pip install cpz-ai
60-second Quickstart (Sync)
⚠️ IMPORTANT: All trading operations are now routed through CPZ AI. You do not need to provide broker credentials directly. Broker credentials are securely managed in your CPZ AI account.
Trading
import cpz
from cpz.execution.models import OrderSubmitRequest
from cpz.execution.enums import OrderSide, OrderType, TimeInForce
# Only CPZ AI credentials needed
client = cpz.clients.sync.CPZClient()
# Single account setup
client.execution.use_broker("alpaca", environment="paper")
# Multi-account setup (if you have multiple accounts with same broker/environment)
# client.execution.use_broker("alpaca", environment="paper", account_id="your-account-id")
order = client.execution.submit_order(OrderSubmitRequest(
symbol="AAPL",
side=OrderSide.BUY,
qty=10,
type=OrderType.MARKET,
time_in_force=TimeInForce.DAY,
strategy_id="your-strategy-uuid-here", # REQUIRED
))
print(order.id, order.status)
Execution Architecture
CPZClient.execution --> BrokerRouter --> CPZ AI API --> Trading Credentials --> AlpacaAdapter
| | | ^
| v v |
| Orders Table Broker Execution +---- future brokers (IBKR, Tradier, ...)
| | |
| v v
| Audit Trail Order Updates
Flow
- Order Creation: All orders are first written to CPZ AI's
orderstable with full audit trail - Credential Resolution: Trading credentials are fetched securely from CPZ AI (never from environment)
- Broker Execution: Orders are placed at the broker using resolved credentials
- Status Updates: Order status and broker responses are updated in CPZ AI
Configuration (.env)
⚠️ Authentication Change: Only CPZ AI credentials are needed. Do not set broker credentials (ALPACA_* etc.) - they are managed in your CPZ AI account.
Required Settings
| Key | Description | Example |
|---|---|---|
| CPZ_AI_API_KEY | Your CPZ AI API Key | cpz_... |
| CPZ_AI_API_SECRET | Your CPZ AI API Secret | cpz_secret_... |
Optional Settings
| Key | Description | Default | When to Change |
|---|---|---|---|
| CPZ_AI_URL | CPZ AI API Endpoint | https://api-ai.cpz-lab.com/cpz | Custom deployments only |
| CPZ_ENV | SDK environment | production | Development/debugging |
| CPZ_LOG_LEVEL | Log level | INFO | Debugging issues |
| CPZ_REQUEST_TIMEOUT_SECONDS | Default request timeout | 30 | Slow connections |
Getting Your CPZ AI Keys
- Get API Keys: https://ai.cpz-lab.com/profile-settings?tab=api-keys
- Add Trading Accounts: https://ai.cpz-lab.com/profile-settings?tab=trading-accounts
- Generate your
CPZ_AI_API_KEYandCPZ_AI_API_SECRET - Add your broker credentials (Alpaca, etc.) to enable trading
Usage
Selecting a broker
# Single account (most common)
client.execution.use_broker("alpaca", environment="paper")
client.execution.use_broker("alpaca", environment="live")
# Multi-account: Use account_id when you have multiple accounts
# with the same broker and environment
client.execution.use_broker("alpaca", environment="paper", account_id="account-1")
client.execution.use_broker("alpaca", environment="paper", account_id="account-2")
client.execution.use_broker("alpaca", environment="live", account_id="main-live-account")
When to use account_id:
- You have multiple accounts with the same broker (e.g., Alpaca)
- Same environment (paper or live)
- Need to specify which account to trade with
- Without
account_id, the SDK uses your default/primary account
Submit / cancel / replace order (sync)
from cpz.execution.models import OrderSubmitRequest, OrderReplaceRequest
from cpz.execution.enums import OrderSide, OrderType, TimeInForce
req = OrderSubmitRequest(
symbol="AAPL",
side=OrderSide.BUY,
qty=1,
type=OrderType.MARKET,
time_in_force=TimeInForce.DAY,
strategy_id="your-strategy-uuid-here" # REQUIRED
)
order = client.execution.submit_order(req)
client.execution.cancel_order(order.id)
client.execution.replace_order(order.id, OrderReplaceRequest(qty=2))
Async + Streaming
import asyncio
from cpz.clients.async_ import AsyncCPZClient
async def main():
client = AsyncCPZClient()
await client.execution.use_broker("alpaca", environment="paper")
async for q in client.execution.stream_quotes(["AAPL", "MSFT"]):
print(q.symbol, q.bid, q.ask)
break
asyncio.run(main())
Get account / positions
acct = client.execution.get_account()
positions = client.execution.get_positions()
CPZ AI - Strategies & Files
Access your CPZ AI platform data including strategies and files:
from cpz.common.cpz_ai import CPZAIClient
# Connect to CPZ AI
client = CPZAIClient.from_env()
# Get your strategies (user-specific by default)
strategies = client.get_strategies()
print(f"Your strategies: {[s.get('title', 'Unknown') for s in strategies]}")
# Create a new strategy (automatically assigned to your user_id)
new_strategy = client.create_strategy({
"title": "My Trading Bot",
"description": "Automated trading strategy",
"strategy_type": "momentum",
"status": "active"
})
User-Specific Access Control
The CPZ AI client automatically handles user isolation:
- Regular Users: Only see and manage their own strategies, files, orders, and trading data
- Admins: Can access all strategies, files, orders, and trading data across all users
API Permissions & Data Access
Your CPZ AI credentials provide access to:
✅ Strategies - Read/write your trading strategies
✅ Data Files - Upload/download files and datasets
✅ Storage - File storage and management
✅ Orders - Read/write order history and execution data
✅ Trading Credentials - Access to your configured broker accounts
✅ Metadata - Strategy metadata, performance metrics, and analytics
# Recommended: Use environment variables (automatic user resolution)
client = CPZAIClient.from_env() # User-specific access based on your CPZ AI credentials
# Manual instantiation (if needed for special cases)
client = CPZAIClient(
url="https://api-ai.cpz-lab.com/cpz",
api_key="your_api_key",
secret_key="your_secret_key"
# User identity and permissions are auto-resolved from your credentials
)
# Environment variables (in .env file):
# CPZ_AI_API_KEY=your_api_key
# CPZ_AI_API_SECRET=your_secret_key
# User ID and admin permissions are auto-resolved from your CPZ AI account
File Operations & DataFrames
Upload, download, and manage files with pandas DataFrame support:
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'symbol': ['AAPL', 'GOOGL', 'MSFT'],
'price': [150.25, 2750.80, 310.45],
'volume': [1000000, 500000, 800000]
})
# Upload DataFrame as CSV
client.upload_dataframe("data-bucket", "stocks.csv", df, format="csv")
# Upload DataFrame as JSON
client.upload_dataframe("data-bucket", "stocks.json", df, format="json")
# Upload DataFrame as Parquet
client.upload_dataframe("data-bucket", "stocks.parquet", df, format="parquet")
# Download CSV and load to DataFrame
downloaded_df = client.download_csv_to_dataframe("data-bucket", "stocks.csv")
# Download JSON and load to DataFrame
downloaded_df = client.download_json_to_dataframe("data-bucket", "stocks.json")
# Download Parquet and load to DataFrame
downloaded_df = client.download_parquet_to_dataframe("data-bucket", "stocks.parquet")
# List files in a bucket
files = client.list_files_in_bucket("data-bucket", prefix="stocks")
# Delete files
client.delete_file("data-bucket", "stocks.csv")
Load User Strategies to DataFrame
from cpz.common.cpz_ai import CPZAIClient
import pandas as pd
# Load your strategies (user-specific, auto-resolved from CPZ AI credentials)
client = CPZAIClient.from_env() # Uses CPZ_AI_API_KEY and CPZ_AI_API_SECRET from .env
# Get your strategies as DataFrame
strategies_df = pd.DataFrame(client.get_strategies())
print(f"Found {len(strategies_df)} strategies")
print(strategies_df.head())
Note: The CPZ AI client connects to your API endpoint at api-ai.cpz-lab.com/cpz. Users only need to provide their CPZ AI API keys.
🚨 Breaking Changes & Migration
Version 2.0+ Updates
Authentication:
- ✅ Only CPZ AI keys (
CPZ_AI_API_KEY,CPZ_AI_API_SECRET) - ❌ No broker keys (ALPACA_, IBKR_, etc.)
Order Submission:
- ✅
strategy_idrequired for all orders - ✅ Client-side idempotency with
client_order_id - ✅ Full audit trail through CPZ AI
Broker Configuration:
- ✅
use_broker("alpaca", environment="paper", account_id="optional") - ❌
use_broker("alpaca", env="paper")(old style)
Migration Steps:
- Remove all
ALPACA_*environment variables - Set
CPZ_AI_API_KEYandCPZ_AI_API_SECRET - Add broker credentials to your CPZ AI account (Settings → Trading Accounts)
- Add
strategy_idto allOrderSubmitRequestcalls - Update
use_broker()calls to useenvironmentparameter
CLI
⚠️ Authentication: The CLI uses your CPZ AI credentials from environment variables or
.envfile. No broker credentials needed.
# List available brokers
cpz broker list
# Configure broker (credentials auto-resolved from CPZ AI)
cpz broker use alpaca --env paper
cpz broker use alpaca --env live --account-id "your-account-id" # Multi-account
# Submit orders (strategy-id is required)
cpz order submit --symbol AAPL --side buy --qty 10 --type market --tif day --strategy-id "your-uuid"
# Manage orders
cpz order get --id <order-id>
cpz order cancel --id <order-id>
cpz order replace --id <order-id> --qty 20
# Get account info
cpz positions
cpz-ai positions
cpz-ai stream quotes --symbols AAPL,MSFT
Error handling
Catch cpz.common.errors.CPZBrokerError. Broker errors are mapped to CPZ errors.
Logging & Redaction
Structured JSON logging via structlog, with redaction of Authorization, ALPACA_API_SECRET_KEY, and similar.
Configure level via CPZ_LOG_LEVEL.
Testing & Quality
make test(coverage goal ≥ 85%)mypy --strict
Python Compatibility
This package is tested and compatible with:
- Python 3.9 ✅
- Python 3.10 ✅
- Python 3.11 ✅
- Python 3.12 ✅
Compatibility Features
- Uses
from __future__ import annotationsfor forward-compatible type hints - Compatible type annotation syntax across all supported versions
- No version-specific syntax that would break older Python versions
- Continuous integration testing on all supported Python versions
Contributing
Style: ruff/black/isort, pre-commit, branch naming. See CONTRIBUTING.md.
Versioning & Release
Bump version in pyproject.toml, build, and publish to PyPI.
Roadmap
Next brokers: IBKR, Tradier, …
Security
See SECURITY.md. No LICENSE file is included intentionally.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cpz_ai-1.1.8.tar.gz.
File metadata
- Download URL: cpz_ai-1.1.8.tar.gz
- Upload date:
- Size: 29.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a75b9bf31ecad89f4045ea594af9f177fc245de13ac8f807c242eafd1cb30e4c
|
|
| MD5 |
927ed8f73de0703b82547c26e7eafd11
|
|
| BLAKE2b-256 |
d2a0b4c995f1a17017e99aa4d7f959620fe6d8809e833bf3e81923ce953b86cd
|
File details
Details for the file cpz_ai-1.1.8-py3-none-any.whl.
File metadata
- Download URL: cpz_ai-1.1.8-py3-none-any.whl
- Upload date:
- Size: 30.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
809b57742e86123156be370e6d88c42e12330e94cff85975977c6295465ccec0
|
|
| MD5 |
734429103f1a795e3bb67c28669a4b5f
|
|
| BLAKE2b-256 |
4c5146fc26ac4e25644c13470427c97e5f0b5b48fee4aaf89e4c5de7c532ac91
|