Skip to content

Latest commit

Β 

History

History
771 lines (631 loc) Β· 17.1 KB

File metadata and controls

771 lines (631 loc) Β· 17.1 KB

StockAlert Pro - Complete Implementation Guide

πŸ“‹ Executive Summary

StockAlert Pro is a production-ready stock market scanning platform built with:

  • Backend: Node.js + Express + PostgreSQL + Redis
  • Frontend: React 18 + TailwindCSS + Recharts
  • Infrastructure: Docker, GitHub Actions, Railway/AWS
  • Features: SMS alerts, derivatives tracking, insider trading, order book analysis

πŸ—‚οΈ Complete Project Structure

stock-alert-pro/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   β”œβ”€β”€ database.js          # Sequelize config
β”‚   β”‚   β”‚   β”œβ”€β”€ redis.js             # Redis client
β”‚   β”‚   β”‚   └── environment.js       # Environment validation
β”‚   β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”‚   β”œβ”€β”€ User.js              # User authentication
β”‚   β”‚   β”‚   β”œβ”€β”€ Strategy.js          # Trading strategies
β”‚   β”‚   β”‚   β”œβ”€β”€ AlertLog.js          # Alert history
β”‚   β”‚   β”‚   β”œβ”€β”€ Derivative.js        # Futures/Options data
β”‚   β”‚   β”‚   β”œβ”€β”€ OptionsBuyer.js      # Options tracking
β”‚   β”‚   β”‚   β”œβ”€β”€ OrderBook.js         # Order book data
β”‚   β”‚   β”‚   β”œβ”€β”€ InsiderTransaction.js # Director trades
β”‚   β”‚   β”‚   └── GeopoliticalEvent.js # News events
β”‚   β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”‚   β”œβ”€β”€ authController.js    # Auth logic
β”‚   β”‚   β”‚   β”œβ”€β”€ strategyController.js# Strategy CRUD
β”‚   β”‚   β”‚   β”œβ”€β”€ alertController.js   # Alert management
β”‚   β”‚   β”‚   β”œβ”€β”€ derivativesController.js
β”‚   β”‚   β”‚   β”œβ”€β”€ insiderController.js
β”‚   β”‚   β”‚   └── newsController.js
β”‚   β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.js
β”‚   β”‚   β”‚   β”œβ”€β”€ strategies.js
β”‚   β”‚   β”‚   β”œβ”€β”€ alerts.js
β”‚   β”‚   β”‚   β”œβ”€β”€ derivatives.js
β”‚   β”‚   β”‚   β”œβ”€β”€ insider.js
β”‚   β”‚   β”‚   β”œβ”€β”€ orderbook.js
β”‚   β”‚   β”‚   └── news.js
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   β”œβ”€β”€ alertService.js      # SMS/Email sending
β”‚   β”‚   β”‚   β”œβ”€β”€ derivativesService.js# Data fetching
β”‚   β”‚   β”‚   β”œβ”€β”€ insiderService.js    # Scraping
β”‚   β”‚   β”‚   β”œβ”€β”€ newsService.js       # News aggregation
β”‚   β”‚   β”‚   └── scanService.js       # Strategy execution
β”‚   β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.js              # JWT verification
β”‚   β”‚   β”‚   β”œβ”€β”€ errorHandler.js      # Error handling
β”‚   β”‚   β”‚   └── rateLimit.js         # Rate limiting
β”‚   β”‚   β”œβ”€β”€ websocket/
β”‚   β”‚   β”‚   └── wsManager.js         # Real-time updates
β”‚   β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”‚   β”œβ”€β”€ logger.js            # Winston logging
β”‚   β”‚   β”‚   β”œβ”€β”€ validators.js        # Input validation
β”‚   β”‚   β”‚   └── helpers.js           # Utility functions
β”‚   β”‚   └── app.js                   # Express app setup
β”‚   β”œβ”€β”€ migrations/
β”‚   β”‚   β”œβ”€β”€ 001_create_users_table.sql
β”‚   β”‚   β”œβ”€β”€ 002_create_strategies_table.sql
β”‚   β”‚   └── ... (up to 009)
β”‚   β”œβ”€β”€ seeds/
β”‚   β”‚   └── seed.js                  # Initial data
β”‚   β”œβ”€β”€ __tests__/
β”‚   β”‚   β”œβ”€β”€ auth.test.js
β”‚   β”‚   β”œβ”€β”€ strategies.test.js
β”‚   β”‚   └── integration.test.js
β”‚   β”œβ”€β”€ package.json
β”‚   β”œβ”€β”€ server.js                    # Entry point
β”‚   └── .env.example                 # Environment template
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ AlertCenter.jsx
β”‚   β”‚   β”‚   β”œβ”€β”€ StrategyStats.jsx
β”‚   β”‚   β”‚   β”œβ”€β”€ Navbar.jsx
β”‚   β”‚   β”‚   β”œβ”€β”€ Sidebar.jsx
β”‚   β”‚   β”‚   └── WebSocketProvider.jsx
β”‚   β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   β”‚   β”œβ”€β”€ Dashboard.jsx
β”‚   β”‚   β”‚   β”œβ”€β”€ StrategyScanBuilder.jsx
β”‚   β”‚   β”‚   β”œβ”€β”€ DerivativesTracker.jsx
β”‚   β”‚   β”‚   β”œβ”€β”€ InsiderTracker.jsx
β”‚   β”‚   β”‚   β”œβ”€β”€ OrderBookMonitor.jsx
β”‚   β”‚   β”‚   └── NewsAndGeopolitical.jsx
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   β”œβ”€β”€ api.js               # Axios instance
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.js              # Auth service
β”‚   β”‚   β”‚   └── websocket.js         # WebSocket client
β”‚   β”‚   β”œβ”€β”€ store/
β”‚   β”‚   β”‚   └── useStore.js          # Zustand store
β”‚   β”‚   β”œβ”€β”€ App.jsx                  # Main component
β”‚   β”‚   β”œβ”€β”€ index.css                # Global styles
β”‚   β”‚   └── main.jsx                 # Entry point
β”‚   β”œβ”€β”€ public/
β”‚   β”‚   └── index.html
β”‚   β”œβ”€β”€ package.json
β”‚   └── vite.config.js
β”œβ”€β”€ docker-compose.yml               # Multi-container setup
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── ci-cd.yml                # GitHub Actions
β”œβ”€β”€ README.md
└── DEPLOYMENT.md                    # Deployment guide


πŸš€ Installation & Setup

Prerequisites

  • Docker & Docker Compose (or Node.js 18+ + PostgreSQL 15+ + Redis 7+)
  • Git
  • GitHub account (for CI/CD)
  • API Keys: Twilio, NSE, Finnhub, NewsAPI

Step 1: Clone Repository

git clone https://github.com/yourusername/stock-alert-pro.git
cd stock-alert-pro

Step 2: Configure Environment Variables

Backend (backend/.env):

# Server
PORT=5000
NODE_ENV=development

# Database
DB_HOST=postgres
DB_PORT=5432
DB_NAME=stockalert_db
DB_USER=postgres
DB_PASSWORD=postgres_password_123

# Redis
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=redis_password_123

# JWT
JWT_SECRET=your_super_secret_jwt_key_change_in_production
JWT_EXPIRE=7d

# Twilio SMS
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_PHONE_NUMBER=+1234567890

# NSE API
NSE_API_KEY=your_nse_api_key
NSE_API_BASE_URL=https://www.nseindia.com/api

# News APIs
FINNHUB_API_KEY=your_finnhub_api_key
NEWSAPI_KEY=your_newsapi_key

# Email (SMTP)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_app_password

# Logging
LOG_LEVEL=debug

Frontend (frontend/.env):

VITE_API_URL=http://localhost:5000/api
VITE_WS_URL=ws://localhost:5000
VITE_APP_NAME=StockAlert Pro

Step 3: Start with Docker Compose

# Build and start all services
docker-compose up -d

# Check status
docker-compose ps

# View logs
docker-compose logs -f backend
docker-compose logs -f frontend

Step 4: Database Setup

# Run migrations
docker exec stockalert_backend npm run migrate

# Seed initial data
docker exec stockalert_backend npm run seed

# Verify database
docker exec -it stockalert_postgres psql -U postgres -d stockalert_db -c "\dt"

Step 5: Access Application


πŸ“Š API Documentation

Authentication Endpoints

Register User

POST /api/auth/register
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePassword123!",
  "firstName": "John",
  "lastName": "Doe",
  "phoneNumber": "+919876543210"
}

Response (201):
{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "subscriptionTier": "free",
    "createdAt": "2026-01-06T17:30:00Z"
  }
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePassword123!"
}

Response (200):
{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": { ... }
}

Strategy Endpoints

Create Strategy

POST /api/strategies
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "EMA 20/50 Crossover",
  "description": "Buy when EMA 20 crosses above EMA 50",
  "clause": "close > ema(20) and ema(20) > ema(50)",
  "timeframe": "daily",
  "alertSettings": {
    "sms": true,
    "email": true,
    "webhook": null
  }
}

Response (201):
{
  "id": "550e8400-e29b-41d4-a716-446655440001",
  "name": "EMA 20/50 Crossover",
  "isActive": true,
  "createdAt": "2026-01-06T17:30:00Z"
}

List Strategies

GET /api/strategies
Authorization: Bearer <token>

Response (200):
[
  { id: "...", name: "EMA 20/50 Crossover", isActive: true, executionCount: 5 },
  { id: "...", name: "RSI Oversold", isActive: true, executionCount: 12 },
  ...
]

Execute Strategy

POST /api/strategies/:id/execute
Authorization: Bearer <token>

Response (200):
{
  "success": true,
  "matchedStocks": ["INFY", "TCS", "WIPRO"],
  "alertsSent": 3,
  "executedAt": "2026-01-06T17:30:00Z"
}

Alert Endpoints

Get Alert Logs

GET /api/alerts/logs?limit=20&status=sent
Authorization: Bearer <token>

Response (200):
[
  {
    "id": "...",
    "message": "INFY crossed EMA 20/50",
    "status": "sent",
    "alertType": "sms",
    "recipient": "+919876543210",
    "sentAt": "2026-01-06T17:30:00Z"
  },
  ...
]

Send Test SMS

POST /api/alerts/test-sms
Authorization: Bearer <token>
Content-Type: application/json

{
  "phoneNumber": "+919876543210",
  "message": "Test SMS from StockAlert Pro"
}

Response (200):
{
  "success": true,
  "messageId": "SM1234567890abcdef",
  "sentAt": "2026-01-06T17:30:00Z"
}

Derivatives Endpoints

Get Top 20 Contracts

GET /api/derivatives/top-20-contracts

Response (200):
[
  {
    "symbol": "NIFTY50",
    "contractType": "future",
    "volume": 2500000000,
    "openInterest": 1850000000,
    "lastPrice": 25180.50,
    "changePercent": 1.25
  },
  ...
]

Get Options Chain

GET /api/derivatives/NIFTY50/chain?expiryDate=2026-01-16

Response (200):
{
  "symbol": "NIFTY50",
  "expiryDate": "2026-01-16",
  "callBuyers": [
    { strike: 25000, volume: 450000, oi: 380000, lastPrice: 250.50 },
    ...
  ],
  "putBuyers": [
    { strike: 25000, volume: 320000, oi: 290000, lastPrice: 45.25 },
    ...
  ]
}

Get Put-Call Ratio

GET /api/derivatives/NIFTY50/put-call-ratio

Response (200):
{
  "symbol": "NIFTY50",
  "putCallRatio": 0.78,
  "sentiment": "bullish",
  "callVolume": 2500000000,
  "putVolume": 1950000000,
  "timestamp": "2026-01-06T17:30:00Z"
}

Insider Trading Endpoints

Get Director Holdings

GET /api/insider/directors/TCS?limit=10

Response (200):
[
  {
    "directorName": "Ajay Singh",
    "companyName": "TCS",
    "transactionType": "buy",
    "quantity": 10000,
    "price": 3500,
    "transactionDate": "2026-01-05",
    "shareholdingPercent": 0.05
  },
  ...
]

Order Book Endpoints

Get Large Orders

GET /api/orderbook/large-orders?minQuantity=1000000

Response (200):
[
  {
    "companyName": "Reliance Industries",
    "symbol": "RELIANCE",
    "buyQuantity": 5000000,
    "buyPrice": 2850.00,
    "sellQuantity": 3500000,
    "sellPrice": 2851.50,
    "timestamp": "2026-01-06T17:30:00Z"
  },
  ...
]

News Endpoints

Get News Feed

GET /api/news/feed?symbol=INFY&limit=10

Response (200):
[
  {
    "title": "Infosys Q3 Results Beat Expectations",
    "description": "IT major reports strong quarterly earnings...",
    "source": "Reuters",
    "publishedAt": "2026-01-06T10:00:00Z",
    "url": "https://reuters.com/...",
    "sentiment": "positive"
  },
  ...
]

πŸ§ͺ Testing

Run All Tests

cd backend
npm install
npm test

With Coverage Report

npm test -- --coverage

Watch Mode (Development)

npm test -- --watch

Specific Test File

npm test -- __tests__/auth.test.js

Expected Output

 PASS  __tests__/auth.test.js
  Authentication Tests
    βœ“ should register new user (234ms)
    βœ“ should login user (145ms)
    βœ“ should fail with invalid password (98ms)

 PASS  __tests__/strategies.test.js
  Strategies API Tests
    βœ“ should return user strategies (167ms)
    βœ“ should create new strategy (156ms)
    βœ“ should delete strategy (123ms)

Test Suites: 2 passed, 2 total
Tests:       6 passed, 6 total
Coverage: 82%

πŸ”„ CI/CD Pipeline

GitHub Actions Workflow

The .github/workflows/ci-cd.yml file automatically:

  1. Runs on Push/PR to main/develop branches
  2. Tests: Jest with coverage
  3. Lint: Code quality checks
  4. Build: Docker images
  5. Deploy: To Railway on main branch

Required GitHub Secrets

DOCKER_USERNAME = your_docker_hub_username
DOCKER_PASSWORD = your_docker_hub_password
RAILWAY_TOKEN = your_railway_api_token

Add Secrets to GitHub

# Via GitHub CLI
gh secret set DOCKER_USERNAME --body "your_username"
gh secret set DOCKER_PASSWORD --body "your_password"
gh secret set RAILWAY_TOKEN --body "your_token"

# Or via GitHub Web UI:
# Settings β†’ Secrets and variables β†’ Actions β†’ New repository secret

πŸ“ˆ Deployment Options

Option 1: Railway (Recommended for Beginners)

  1. Create Railway Account: https://railway.app
  2. Connect GitHub: Link your repository
  3. Create Services:
    • Backend (Node.js)
    • Frontend (Static)
    • PostgreSQL
    • Redis
  4. Set Environment Variables in Railway dashboard
  5. Deploy: Automatic on git push

Railway Pricing: Free tier available, pay-as-you-go

Option 2: AWS Deployment

Infrastructure Setup:

# 1. RDS PostgreSQL
aws rds create-db-instance \
  --db-instance-identifier stockalert-db \
  --db-instance-class db.t3.micro \
  --engine postgres \
  --master-username postgres \
  --master-user-password YourPassword123

# 2. ElastiCache Redis
aws elasticache create-cache-cluster \
  --cache-cluster-id stockalert-redis \
  --cache-node-type cache.t3.micro \
  --engine redis

# 3. ECS Fargate
aws ecs create-cluster --cluster-name stockalert

# 4. Load Balancer
aws elbv2 create-load-balancer \
  --name stockalert-lb \
  --subnets subnet-xxx subnet-yyy

Option 3: DigitalOcean

  1. Create Droplet (2GB RAM, $12/month)
  2. Install Docker:
    curl -fsSL https://get.docker.com -o get-docker.sh
    sudo sh get-docker.sh
  3. Upload docker-compose.yml
  4. Deploy:
    docker-compose up -d
  5. Setup Nginx as reverse proxy
  6. SSL Certificate: Let's Encrypt

πŸ” Security Best Practices

Environment Variables

  • Never commit .env to Git
  • Use .env.example for templates
  • Rotate secrets regularly

Database Security

-- Create dedicated user
CREATE USER stockalert_user WITH PASSWORD 'strong_password_123';
GRANT CONNECT ON DATABASE stockalert_db TO stockalert_user;
GRANT USAGE ON SCHEMA public TO stockalert_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO stockalert_user;

-- Enable SSL
ALTER SYSTEM SET ssl = on;

API Security

  • JWT tokens expire in 15 minutes
  • Refresh token rotation
  • Rate limiting (100 req/min)
  • CORS whitelist only trusted domains
  • Helmet security headers
  • Request validation with Joi

SMS Security

  • Hash phone numbers
  • Encrypt sensitive data
  • Log all alerts
  • Monitor failed attempts

Code Security

  • Dependabot for dependency updates
  • SAST scanning (SonarQube)
  • Container scanning (Trivy)
  • Supply chain security (SBOM)

🚨 Troubleshooting

Docker Issues

Containers won't start:

# Check logs
docker-compose logs backend

# Rebuild images
docker-compose build --no-cache

# Full reset
docker-compose down -v
docker-compose up -d

Port already in use:

# Find process using port
sudo lsof -i :5000

# Kill process
sudo kill -9 <PID>

# Or use different port
PORT=5001 docker-compose up

Database Issues

Migration failed:

# Connect to database
docker exec -it stockalert_postgres psql -U postgres -d stockalert_db

# Check tables
\dt

# Reset database
docker exec stockalert_backend npm run migrate:reset

Connection refused:

# Check PostgreSQL is running
docker exec stockalert_postgres pg_isready

# Check Redis is running
docker exec stockalert_redis redis-cli ping

Backend Issues

Module not found:

docker exec stockalert_backend npm install
docker-compose restart backend

Memory leak:

# Check memory usage
docker stats stockalert_backend

# Increase memory limit in docker-compose.yml
# mem_limit: 2g

Frontend Issues

CORS errors:

# Check Backend URL in frontend .env
VITE_API_URL=http://localhost:5000/api

# Check CORS in backend
cors({ origin: ['http://localhost:3000'] })

WebSocket connection failed:

# Check WebSocket URL
VITE_WS_URL=ws://localhost:5000

# Verify backend serves WebSocket
netstat -an | grep 5000

πŸ“š Additional Resources


πŸ“ License

MIT License - See LICENSE file for details


Last Updated: January 6, 2026 Version: 1.0.0 Maintainer: Your Team