Skip to content

HexLab-Software/Stock-Market-App

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“ˆ Stock Market Portfolio Tracker

A Laravel-based stock portfolio tracking application with Telegram bot integration, automated daily reports, and real-time stock price updates via AlphaVantage API.

πŸš€ Features

  • Telegram Bot Integration: Search stocks, add to portfolio, get instant recaps
  • Real-time Stock Prices: Powered by AlphaVantage API
  • Automated Reports: Daily email and Telegram notifications with P/L analysis
  • Performance Tracking: Daily, MTD, and YTD performance metrics
  • RESTful API: Full CRUD operations for portfolio management
  • Cloud-Ready: Optimized for Google Cloud Run deployment
  • Type-Safe: Strict PHP 8.4 typing with declare(strict_types=1)
  • Tested: Comprehensive Pest test suite

οΏ½ Documentation

For detailed information on configuration and deployment, please refer to the following guides:

οΏ½πŸ“‹ Requirements

  • Docker & Docker Compose
  • PHP 8.4+
  • PostgreSQL (via Supabase)
  • AlphaVantage API Key
  • Telegram Bot Token (optional)

πŸ› οΈ Local Development

Quick Start

  1. Clone and setup:

    git clone <repository-url>
    cd stock-market-app
  2. Configure environment:

    Note: The files .env, .env.staging, and .env.production are committed to the repository with dummy values to prevent exposing sensitive credentials on GitHub.

    Edit .env (or .env.staging / .env.production based on your target) and set your real credentials:

    • DB_HOST, DB_USERNAME, DB_PASSWORD (Supabase credentials)
    • ALPHA_VANTAGE_API_KEY
    • TELEGRAM_BOT_TOKEN (optional)
    • CRON_SECRET (generate a random string)
  3. Start the application:

    ./run staging
  4. Run migrations:

    ./sail artisan migrate
  5. Access the app:

  6. Start Queue Worker (Required for pricing & reports):

    ./sail artisan queue:work

Available Commands

# Start staging environment
./run staging

# Start production environment
./run production

# Run artisan commands
./sail artisan <command>

# Run tests
./test

# Manual stock fetch
./sail artisan stocks:fetch

# Generate daily report
./sail artisan report:daily

# Seed test data (Safe for staging/local)
./sail artisan db:seed-test

πŸ€– Telegram Bot Commands

  • /start - Welcome message and command list
  • /search <symbol> - Search for stock symbols (e.g., /search AAPL)
  • /add <symbol> <quantity> - Add stocks to portfolio (e.g., /add AAPL 10)
  • /recap - Get current portfolio summary with P/L

Setting up Telegram Webhook

# Webhook now uses your bot token as a secret path for security
curl "https://api.telegram.org/bot<YOUR_TOKEN>/setWebhook?url=https://your-domain.com/api/telegram/webhook/<YOUR_TOKEN>"

πŸ“Š API Endpoints

Portfolio Management (Authenticated)

GET    /api/portfolio          # List all holdings
POST   /api/portfolio          # Add transaction
DELETE /api/portfolio/{id}     # Remove transaction

Cron Jobs (Protected)

GET /api/cron/fetch-stocks     # Trigger stock price update
GET /api/cron/daily-report     # Trigger daily report generation

☁️ Google Cloud Run Deployment

Prerequisites

  1. Install Google Cloud SDK
  2. Authenticate: gcloud auth login
  3. Create a GCP project
  4. Enable APIs:
    gcloud services enable run.googleapis.com
    gcloud services enable cloudscheduler.googleapis.com
    gcloud services enable containerregistry.googleapis.com

Deploy

  1. Update configuration: Edit deploy.sh and set PROJECT_ID

  2. Configure production environment: The .env.production file contains dummy values. Edit it with your real production credentials.

  3. Deploy to Cloud Run:

    ./deploy.sh production
  4. Setup Cloud Scheduler (replaces cron):

    ./scheduler-setup.sh production

Cost Estimation (Free Tier)

  • Cloud Run: 2M requests/month FREE

    • Expected usage: ~3,000 requests/month
    • Cost: $0/month
  • Cloud Scheduler: 3 jobs/month FREE

    • We use 2 jobs
    • Cost: $0/month
  • Supabase: 500MB database FREE

    • Expected usage: <100MB
    • Cost: $0/month

Total estimated cost: $0/month βœ…

πŸ§ͺ Testing

# Run all tests
./test

# Run specific test file
./test tests/Feature/StockServiceTest.php

# Run with coverage
./sail artisan test --coverage

πŸ› οΈ Test Data Seeding

To get up and running quickly with a consistent environment, you can use the built-in test data seeder.

Warning

This command will TRUNCATE all data in the following tables: users, tickers, transactions, daily_metrics, settings, and personal_access_tokens. Use it only in development or staging environments.

./sail artisan db:seed-test

The seeder provides:

  • Admin User: admin@example.com / password
  • Sample Users: 5 additional random users
  • Tickers: 10 active stock symbols
  • Daily Metrics: 30 days of historical data per ticker
  • Transactions: 15 transactions per user
  • Default Settings: Pre-configured application settings

πŸ”— Linking Telegram ID (Testing only)

For testing purposes, you can link your Telegram account to any existing user ID from the database using the /start command. This allows you to "impersonate" a specific user and view their portfolio.

  1. Find the UUID of the user you want to link (e.g., from the users table or seeder output).
  2. In Telegram, send: /start <user_uuid>

Note

If the Telegram ID is already linked to another user, it will be automatically moved to the specified UUID to maintain the uniqueness of the telegram_id field.

Test Coverage

  • βœ… Stock Service (API integration, error handling)
  • βœ… Report Service (daily/MTD/YTD calculations)
  • βœ… Transaction Service (CRUD, holdings calculation)
  • βœ… Market Hours Service (timezone handling)

πŸ“ Project Structure

app/
β”œβ”€β”€ Console/Commands/      # Artisan commands
β”‚   β”œβ”€β”€ FetchStockData.php
β”‚   └── GenerateDailyReport.php
β”œβ”€β”€ Http/
β”‚   β”œβ”€β”€ Controllers/       # API & Telegram controllers
β”‚   └── Middleware/        # Cron authentication
β”œβ”€β”€ Models/                # Eloquent models
β”‚   β”œβ”€β”€ User.php
β”‚   β”œβ”€β”€ Ticker.php
β”‚   β”œβ”€β”€ Transaction.php
β”‚   └── DailyMetric.php
β”œβ”€β”€ Services/              # Business logic
β”‚   β”œβ”€β”€ AlphaVantageService.php
β”‚   β”œβ”€β”€ TelegramService.php
β”‚   β”œβ”€β”€ StockService.php
β”‚   β”œβ”€β”€ ReportService.php
β”‚   β”œβ”€β”€ TransactionService.php
β”‚   β”œβ”€β”€ MetricService.php
β”‚   └── MarketHoursService.php
└── Mail/
    └── DailyPortfolioReport.php

database/
β”œβ”€β”€ migrations/            # Database schema
└── factories/             # Model factories for testing

tests/
β”œβ”€β”€ Feature/               # Integration tests
└── Unit/                  # Unit tests

πŸ”’ Security

  • Cron endpoints protected by bearer token or OIDC (Cloud Run)
  • API endpoints protected by Laravel Sanctum
  • Database connections use SSL in production
  • Passwords hashed with bcrypt
  • CSRF protection on web routes

πŸ“§ Email Reports

Daily reports are sent via email with:

  • Portfolio summary
  • Daily P/L per ticker
  • Month-to-Date performance
  • Year-to-Date performance
  • CSV attachment with detailed data

Configure SMTP in .env:

MAIL_MAILER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=your-api-key

πŸ› Troubleshooting

Database connection fails

  • Verify Supabase credentials in .env
  • Check if Supabase project is active (not paused)
  • Ensure SSL mode is correct (prefer for staging, require for production)

Stock fetch returns no data

  • Verify ALPHA_VANTAGE_API_KEY is valid
  • Check API rate limits (5 requests/minute for free tier)
  • Ensure market hours check is working

Telegram bot not responding

  • Verify webhook is set correctly
  • Check TELEGRAM_BOT_TOKEN in .env
  • Review logs: ./sail artisan log:tail

πŸ“ License

This project is open-source and available under the MIT License.

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new features
  4. Submit a pull request

πŸ“ž Support

For issues and questions, please open a GitHub issue.


Built with ❀️ using Laravel 12, PHP 8.4, and modern senior best practices.

About

A Laravel-based stock portfolio tracking application with Telegram bot integration, automated daily reports, and real-time stock price updates via AlphaVantage API

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors