Skip to content

An automated stock trading application built with Python and the Alpaca API. Adjustable trading strategies are used to buy/sell stocks when the market is right, all without any user interaction. Just add a list of stocks in the Stock-Universe, and turn on automatic trading, to make money on stocks while doing other things. More improvements coming.

Notifications You must be signed in to change notification settings

aingram702/StockTraderAuto

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AI Trading Platform - Enhanced Edition

🚀 Professional algorithmic trading platform with automated workflows, real-time monitoring, and comprehensive analytics.

✨ New Features (v2.0)

🔄 Auto-Refresh System

  • No manual refreshing needed - Data updates every 60 seconds automatically
  • Smart market scanning - Auto-scans during market hours (9:30 AM - 4:00 PM EST)
  • Real-time market status - Shows OPEN/CLOSED and time until next event
  • 3 background threads - Data, scanning, and dashboard updates

📊 Transaction History Viewer

  • Complete trade history with P&L tracking
  • Filter by symbol and date range
  • Win rate calculator and statistics
  • CSV export for external analysis
  • Press Ctrl+H to open

⌨️ Keyboard Shortcuts

Shortcut Action
Ctrl + R Refresh Data
Ctrl + H Transaction History
Ctrl + Q Quit Application
F1 Show Help

🕐 Market Hours Detection

  • Timezone-aware (Eastern Time)
  • Pre-market and after-hours support
  • Shows time until market open/close
  • Auto-pauses scanning when market closed

🎯 Core Features

Trading Capabilities

  • ✅ Manual order execution (market, limit, stop)
  • ✅ Automated trading with technical analysis
  • ✅ Bracket orders with TP/SL
  • ✅ Risk management (daily loss limits, position sizing)
  • ✅ Real-time market data

Security & Safety

  • ✅ Encrypted credential storage (Fernet)
  • ✅ Input validation on all trades
  • ✅ Rate limiting (200 calls/min)
  • ✅ Comprehensive audit logging
  • ✅ Emergency stop button

Performance

  • ✅ Smart caching (80% fewer API calls)
  • ✅ Retry logic with exponential backoff
  • ✅ Connection pooling
  • ✅ Optimized data fetching

Monitoring

  • ✅ Structured logging system
  • ✅ Real-time notifications
  • ✅ Complete trade history
  • ✅ Portfolio snapshots
  • ✅ Performance analytics

🚀 Quick Start

Installation

cd /home/taj702/Software/StockTrader

# Install dependencies (if needed)
pip install --user pytz pystray

# Run the platform
./run.sh

First-Time Setup

  1. Launch the application
  2. Go to Settings tab
  3. Enter Alpaca API credentials
  4. Enable Paper Trading (recommended)
  5. Click Connect to Alpaca

📖 Usage Guide

Auto-Refresh Operation

The platform automatically:

  • Refreshes account data every 60 seconds
  • Scans markets every 60 seconds (during market hours only)
  • Updates dashboard every 5 seconds
  • Saves portfolio snapshots to database

Market Status Indicators:

  • 🟢 OPEN - Market is currently trading
  • CLOSED - Market is closed
  • 🟡 PRE-MARKET - Before market open
  • 🟠 AFTER-HOURS - After market close

Transaction History

Access via:

  • Press Ctrl+H
  • Or add menu item (Tools → Transaction History)

Features:

  • View all trades with timestamps
  • Filter by symbol or date range
  • See win rate and total P&L
  • Export to CSV for analysis
  • Color-coded profits/losses

Manual Trading

  1. Navigate to Trading tab
  2. Enter symbol and quantity
  3. Select order type (Market/Limit)
  4. Review quote
  5. Click BUY or SELL

Automated Trading

  1. Navigate to Auto Trading tab
  2. Configure strategy parameters
  3. Click "Start Auto Trading"
  4. Monitor in activity log
  5. Stop anytime with "Stop Auto Trading"

Risk Controls

All trades validated against:

  • ✓ Daily loss limits (default: 5%)
  • ✓ Position size limits (max: 50%)
  • ✓ Symbol concentration (max: 30%)
  • ✓ Maximum positions (default: 3)

Customize in config.py:

MAX_DAILY_LOSS = 0.05
MAX_POSITION_SIZE = 0.50
MAX_POSITION_CONCENTRATION = 0.30
DEFAULT_MAX_POSITIONS = 3

📁 Project Structure

StockTrader/
├── trading_platform.py      # Main GUI application
├── config.py                 # Configuration settings
├── security.py               # Encryption & validation
├── logger.py                 # Logging system
├── database.py               # SQLite trade history
├── risk_manager.py           # Risk controls
├── notification_system.py    # Alerts
├── market_hours.py           # NEW - Market detection
├── transaction_viewer.py     # NEW - History viewer
├── data_manager.py           # Market data (enhanced)
├── alpaca_trader.py          # Broker API (enhanced)
├── strategy_engine.py        # Trading strategies
├── requirements.txt          # Dependencies
├── run.sh                    # Launcher script
└── logs/                     # Log files

🔧 Configuration

Auto-Refresh Settings

Edit config.py:

# Auto-Refresh
AUTO_REFRESH_ENABLED = True          # Enable/disable
AUTO_REFRESH_INTERVAL = 60           # Data refresh (seconds)
AUTO_SCAN_INTERVAL = 60              # Market scanning (seconds)
DASHBOARD_UPDATE_INTERVAL = 5        # Dashboard (seconds)

# Market Hours
MARKET_TIMEZONE = "America/New_York"
MARKET_HOURS_START = "09:30"
MARKET_HOURS_END = "16:00"

Risk Limits

MAX_DAILY_LOSS = 0.05               # 5% max daily loss
MAX_POSITION_SIZE = 0.50            # 50% max per position
MAX_POSITION_CONCENTRATION = 0.30   # 30% max per symbol

Trading Defaults

DEFAULT_MAX_POSITIONS = 3
DEFAULT_POSITION_SIZE = 0.10        # 10% of portfolio
DEFAULT_STOP_LOSS = 0.08            # 8%
DEFAULT_TAKE_PROFIT = 0.15          # 15%

📊 Database

Location: trading_database.db

Tables:

  • trades - Complete trade history
  • portfolio_snapshots - Historical portfolio states
  • positions - Position tracking
  • activity_log - System events
  • strategy_performance - Strategy metrics

Query Examples:

from database import DatabaseManager

db = DatabaseManager()
trades = db.get_trades(symbol='NVDA', limit=50)
stats = db.get_trading_statistics()

📝 Logs

Location: logs/ directory

File Content
trading_platform.log System events
trading.log Trade executions
security.log Security events
performance.log Performance metrics

Log Rotation:

  • 10MB per file
  • 5 backup files kept
  • Automatic rotation

🔐 Security

Credential Storage

  • Encrypted with Fernet (symmetric encryption)
  • PBKDF2 key derivation (100,000 iterations)
  • Salt stored separately
  • Never committed to git

Input Validation

  • Symbols: 1-5 uppercase letters
  • Quantities: 1-10,000 range
  • Prices: Positive, reasonable values

Rate Limiting

  • 200 API calls per minute enforced
  • Automatic request throttling
  • Prevents API abuse

⚠️ Disclaimers

Trading Risk: This software is for educational purposes. Trading involves substantial risk of loss. Always use paper trading before live trading.

Not Financial Advice: This tool does not provide financial advice. You are responsible for your trading decisions.

API Limits: Respect Alpaca's API rate limits and terms of service.


🐛 Troubleshooting

Application Won't Start

# Check Python version
python3 --version  # Need 3.8+

# Reinstall dependencies
pip install --user -r requirements.txt

# Use launcher script
./run.sh

Auto-Refresh Not Working

  • Check config.pyAUTO_REFRESH_ENABLED = True
  • Look for errors in logs/trading_platform.log
  • Verify API connection in Settings tab

Transaction History Empty

  • Ensure trades have been executed
  • Check trading_database.db exists
  • Verify database permissions

Market Status Shows "UNKNOWN"

  • Check internet connection
  • Verify pytz is installed
  • Check logs for timezone errors

📚 Additional Resources

  • Alpaca API Docs: https://alpaca.markets/docs
  • QUICKSTART.md: Launch troubleshooting
  • Implementation Plan: See artifacts directory
  • Walkthrough: Complete feature documentation

🎓 Tips for Success

  1. Start with Paper Trading - Test strategies risk-free
  2. Monitor Logs - Watch logs/trading.log for activity
  3. Set Conservative Limits - Start with low position sizes
  4. Use Auto-Refresh - Let the platform monitor for you
  5. Review Transaction History - Learn from past trades
  6. Backup Database - Export trades regularly

💡 Features Coming Soon

  • ⏳ Enhanced candlestick charts
  • ⏳ Portfolio equity curve visualization
  • ⏳ Stock browser with search
  • ⏳ System tray / background mode
  • ⏳ Multi-timeframe analysis
  • ⏳ Advanced backtesting

📞 Support

For issues or questions:

  1. Check logs/ for error details
  2. Review QUICKSTART.md
  3. Verify all dependencies installed
  4. Ensure API credentials are correct

Version: 2.0.0
Last Updated: 2025-12-02
License: MIT

About

An automated stock trading application built with Python and the Alpaca API. Adjustable trading strategies are used to buy/sell stocks when the market is right, all without any user interaction. Just add a list of stocks in the Stock-Universe, and turn on automatic trading, to make money on stocks while doing other things. More improvements coming.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published