A Python wrapper for automated trading operations using the Alpaca trading API. This script provides functionality for position management, order execution, and bracket order trading with built-in risk management.
- Automated Trading: Execute buy orders with automatic stop-loss protection
- Bracket Orders: Create bracket orders with configurable stop-loss percentages
- Future Bracket Orders: Create limit entry bracket orders with automatic quantity calculation
- Portfolio Management: View positions, cash balance, and active orders
- Risk Management: Built-in 7.5% stop-loss protection and configurable portfolio risk
- Quote Retrieval: Get latest market quotes for symbols
- Environment Configuration: Secure API key management via environment variables
- Python 3.6+
- Alpaca trading account (paper or live)
- Required Python packages (see Installation)
- Install required dependencies:
pip3 install alpaca-trade-api python-dotenv matplotlib pytest pytest-cov- Set up environment variables by creating a
.envfile in the project root:
ALPACA_API_KEY=your_api_key_here
ALPACA_SECRET_KEY=your_secret_key_here
ALPACA_BASE_URL=https://paper-api.alpaca.markets # For paper trading
PORTFOLIO_RISK=0.10 # Optional: default is 0.10 (10%)- Set the Python path for module imports:
export PYTHONPATH=/home/wilsonb/dl/github.com/z223i/alpacaNote: This command may be placed in your .bashrc file for permanent setup.
This project includes comprehensive test suites for all components. Two convenient test runners are provided for easy testing.
Using the shell script (recommended for quick testing):
./test.sh # Run all tests
./test.sh verbose # Run tests with verbose output
./test.sh orb # Run only ORB tests
./test.sh coverage # Run tests with coverage report
./test.sh lint # Run linting then testsUsing the Python test runner (more options):
python run_tests.py # Run all tests
python run_tests.py -v # Run tests with verbose output
python run_tests.py -f test_orb.py # Run specific test file
python run_tests.py -c # Run tests with coverage
python run_tests.py -l # Run linting before tests
python run_tests.py -k "test_filter" # Run tests matching patternPytest (recommended):
python -m pytest tests/ # Run all tests
python -m pytest tests/test_orb.py -v # Run ORB tests with verbose output
python -m pytest tests/ --cov code --cov atoms --cov-report html --cov-report term # Run with coverage (HTML + terminal)
python -m pytest tests/ --cov code --cov-report html # Run with HTML coverage only
python -m pytest tests/ --cov code --cov-report term # Run with terminal coverage onlyLegacy unittest:
python -m unittest discover -s test # Run old unittest tests
python test/test_Alpaca.py TestAlpaca.test_order # Run specific test-
tests/test_orb.py: Comprehensive tests for ORB (Opening Range Breakout) functionality- Data filtering and time range validation
- PCA data preparation and validation
- Integration tests with real market data
- Mock testing for external API dependencies
-
test/test_Alpaca.py: Legacy tests for main trading functionality- Order execution and validation
- Portfolio management
- API interaction tests
- Mocked Dependencies: All external API calls are mocked for consistent testing
- Timezone Handling: Proper EST/EDT timezone testing for market hours
- Real Data Integration: Tests use actual market data from
stock_data/directory - Coverage Reports: HTML and terminal coverage reports available
- Linting Integration: Optional code quality checks before testing
python -m pdb test/test_Alpaca.py TestAlpaca.test_order # Debug specific test
python -m pytest tests/test_orb.py::TestORB::test_filter_stock_data_by_time_success --pdb # Debug with pytestView current portfolio status:
python3 code/alpaca.pyGet latest quote for a symbol:
python3 code/alpaca.py --get-latest-quote --symbol AAPLExecute a buy order (dry run):
python3 code/alpaca.py --buy --symbol AAPLExecute a buy order (actual submission):
python3 code/alpaca.py --buy --symbol AAPL --submitExecute a buy order with take profit:
python3 code/alpaca.py --buy --symbol AAPL --submit --take_profit 200.00Create a bracket order:
python3 code/alpaca.py --bracket_order --symbol AAPL --quantity 10 --market_price 150.00 --submitCreate a future bracket order with limit entry:
python3 code/alpaca.py --future_bracket_order --symbol AAPL --quantity 10 --limit_price 145.00 --stop_price 140.00 --take_profit 160.00 --submitCreate a future bracket order with automatic quantity calculation:
python3 code/alpaca.py --future_bracket_order --symbol AAPL --limit_price 145.00 --stop_price 140.00 --take_profit 160.00 --submit--buy: Execute a buy order with automatic position sizing--symbol SYMBOL: Specify the stock symbol to trade--submit: Actually submit orders (without this flag, orders are displayed but not executed)--get_latest_quote: Retrieve the latest quote for a symbol--bracket_order: Create a bracket order with market entry--future_bracket_order: Create a future bracket order with limit entry--quantity N: Number of shares for bracket orders (optional for future bracket orders - will auto-calculate if omitted)--market_price PRICE: Market price for bracket order calculations--limit_price PRICE: Limit price for future bracket order entry--stop_price PRICE: Stop loss price for future bracket orders--take_profit PRICE: Take profit price for bracket orders
- All buy orders automatically include a 7.5% stop-loss order
- Stop-loss percentage is configurable via the
STOP_LOSS_PERCENTclass constant
- First Position: Uses
PORTFOLIO_RISKpercentage of available cash (default: 10%) - Subsequent Positions: Uses all remaining cash for diversification
- Position sizes are automatically calculated based on current market price
- Configurable via
PORTFOLIO_RISKenvironment variable - Default: 10% of available cash for initial positions
- Note: Logic currently optimized for 50% risk - see code comments for updates needed
alpaca_private: Main trading class that handles API interactions and order execution
_buy(): Execute buy orders with automatic bracket order protection_bracketOrder(): Create bracket orders with stop-loss protection_futureBracketOrder(): Create future bracket orders with limit entry and stop-loss protectionExec(): Main execution logic that handles command-line operations
The script uses modular components from the atoms package:
atoms.api.*: API interaction functionsatoms.display.*: Display and printing functionsatoms.utils.*: Utility functions for argument parsing and delays
- Dry Run Mode: Default behavior shows order details without execution
- Environment Variables: Secure API key storage
- Bracket Orders: Automatic stop-loss protection on all positions
- Position Validation: Checks existing positions before sizing new orders
python3 -m pdb code/alpaca.pyThe script is configured for VS Code debugging with F5/Ctrl+F5 shortcuts when using the alpaca conda environment.
- Paper Trading: Use
https://paper-api.alpaca.marketsfor testing - Live Trading: Use
https://api.alpaca.marketsfor live trading (exercise caution) - Order Execution: Always test with paper trading first
- Risk Management: Review and adjust
PORTFOLIO_RISKandSTOP_LOSS_PERCENTbased on your risk tolerance
This project is for educational and personal use. Please ensure compliance with your local financial regulations and Alpaca's terms of service.