Configuration
Learn how to configure the ProjectX Python SDK for your trading application development needs.
Overview
project-x-py can be configured in several ways:
Environment variables (recommended for credentials)
Configuration objects (for application settings)
Constructor parameters (for one-off settings)
Default Configuration
The package comes with sensible defaults:
from project_x_py import ProjectXConfig
# View default configuration
config = ProjectXConfig()
print(config)
Configuration Options
Core Settings
Setting |
Type |
Default |
Description |
---|---|---|---|
|
str |
|
API base URL |
|
int |
|
Request timeout in seconds |
|
int |
|
Number of retry attempts for failed requests |
|
int |
|
Rate limit for API requests |
WebSocket Settings
Setting |
Type |
Default |
Description |
---|---|---|---|
|
str |
|
WebSocket base URL |
|
int |
|
WebSocket ping interval (seconds) |
Timezone Settings
Setting |
Type |
Default |
Description |
---|---|---|---|
|
str |
|
Default timezone for timestamps |
Configuration Methods
Environment Variables
Set configuration via environment variables:
# Required credentials
export PROJECT_X_API_KEY='your_api_key'
export PROJECT_X_USERNAME='your_username'
# Optional configuration
export PROJECTX_API_URL='https://api.topstepx.com/api'
export PROJECT_X_TIMEOUT='60'
export PROJECT_X_TIMEZONE='America/New_York'
Configuration Object
Create a custom configuration:
import asyncio
from project_x_py import ProjectXConfig, ProjectX
async def custom_config():
# Custom configuration
config = ProjectXConfig(
api_url="https://api.topstepx.com/api",
websocket_url="wss://api.topstepx.com",
timeout_seconds=60,
retry_attempts=5,
timezone="America/New_York"
)
# Use with client
async with ProjectX(
username='your_username',
api_key='your_api_key',
config=config
) as client:
await client.authenticate()
# Use client for operations
asyncio.run(custom_config())
Configuration File
Create a JSON configuration file at ~/.config/projectx/config.json
:
{
"api_key": "your_api_key",
"username": "your_username",
"api_url": "https://api.topstepx.com/api",
"websocket_url": "wss://api.topstepx.com",
"timezone": "US/Central"
}
Then use it:
async def use_config_file():
# Automatically loads from config file
async with ProjectX.from_env() as client:
await client.authenticate()
# Use client
asyncio.run(use_config_file())
Advanced Configuration
Custom Endpoints
For testing or custom deployments:
config = ProjectXConfig(
api_url="https://sandbox-api.topstepx.com/api",
websocket_url="wss://sandbox-api.topstepx.com"
)
Rate Limiting
Adjust rate limiting for your usage pattern:
config = ProjectXConfig(
requests_per_minute=60, # Lower rate for batch processing
timeout_seconds=120 # Longer timeout for slow connections
)
Multiple Accounts
Handle multiple accounts:
async def multi_account():
# List all accounts after authentication
async with ProjectX.from_env() as client:
await client.authenticate()
accounts = await client.list_accounts()
for account in accounts:
print(f"Account: {account['name']} (ID: {account['id']})")
asyncio.run(multi_account())
Environment-Specific Configs
import os
from project_x_py import ProjectXConfig
# Load different configs based on environment
if os.getenv('ENVIRONMENT') == 'production':
config = ProjectXConfig(
api_url="https://api.topstepx.com/api",
websocket_url="wss://api.topstepx.com",
timeout_seconds=30,
retry_attempts=3
)
else:
config = ProjectXConfig(
api_url="https://sandbox-api.topstepx.com/api",
websocket_url="wss://sandbox-api.topstepx.com",
timeout_seconds=60,
retry_attempts=5
)
Logging Configuration
Configure logging for debugging and monitoring:
from project_x_py import setup_logging
# Basic logging
setup_logging(level='INFO')
# Detailed logging for debugging
setup_logging(level='DEBUG', format='detailed')
# Custom logging configuration
setup_logging(
level='WARNING',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='trading.log'
)
Configuration Validation
Validate your configuration:
from project_x_py import check_setup
async def validate_config():
# Check overall setup
status = check_setup()
if status['status'] != 'Ready to use':
print("Configuration issues found:")
for issue in status['issues']:
print(f" - {issue}")
# Test client connection
try:
async with ProjectX.from_env() as client:
await client.authenticate()
print(f"✅ Configuration valid: {client.account_info.name}")
except Exception as e:
print(f"❌ Configuration error: {e}")
asyncio.run(validate_config())
Best Practices
Security
Never hardcode credentials in source code
Use environment variables for sensitive data
Rotate API keys regularly
Use different keys for different environments
Performance
Adjust timeouts based on your network
Set appropriate rate limits for your usage
Use connection pooling for high-frequency trading
Enable compression for large data transfers
Monitoring
Enable logging appropriate for your environment
Monitor API usage to avoid rate limits
Set up alerts for connection failures
Track performance metrics
Example Configurations
High-Frequency Trading
config = ProjectXConfig(
timeout_seconds=10, # Fast timeouts
retry_attempts=1, # Minimal retries
timezone="US/Central" # Exchange timezone
)
Batch Processing
config = ProjectXConfig(
timeout_seconds=300, # Long timeouts
retry_attempts=10, # More retries
timezone="UTC" # UTC for consistency
)
Development/Testing
config = ProjectXConfig(
api_url="https://sandbox-api.topstepx.com/api",
websocket_url="wss://sandbox-api.topstepx.com",
timeout_seconds=60,
retry_attempts=5,
timezone="UTC" # Consistent timezone for testing
)
Troubleshooting
Common Configuration Issues
Invalid timezone:
ValueError: Invalid timezone: 'Invalid/Timezone'
Use a valid timezone from the pytz library:
import pytz
print(pytz.all_timezones) # List all valid timezones
Connection timeouts:
ProjectXConnectionError: Request timeout
Increase the timeout or check your network:
config = ProjectXConfig(timeout_seconds=120)
Rate limit errors:
ProjectXRateLimitError: Rate limit exceeded
The SDK handles rate limiting automatically with exponential backoff and retry logic.
Getting Help
If you’re having configuration issues:
Check the troubleshooting guide
Validate your setup with
check_setup()
Enable debug logging to see detailed errors
Review the authentication guide
Next Steps
Once your configuration is working:
Explore trading features
Set up real-time data