Technical Documentation

AlphaVault AI - Technical Documentation

Complete Platform Architecture & Implementation Guide

Version 2.0.0
Production
Admin Access Only

Platform Overview

About AlphaVault AI

AlphaVault AI is a premium financial intelligence platform combining real-time market data analysis, advanced predictive models powered by machine learning, and artificial intelligence to provide professional-grade financial insights for investors, analysts, and financial professionals.

Platform Statistics

65
HTML Pages
49
CSS Files
112
JavaScript Scripts
4
Backend Services
10+
Cloudflare Workers
274,011
Lines of Code
10.53 MB
Total Code Size
4
Pricing Plans

Technology Stack

Firebase
User authentication (Email/Password + Google OAuth), Firestore NoSQL database, real-time session management, and cloud storage for user files.
Cloudflare
Static hosting (Pages), global CDN distribution, serverless Workers for backend logic, KV storage for caching, and real-time analytics.
Stripe
Secure payment processing, subscription management with 14-day trials, webhook event handling, automated invoicing, and promo code system.
Resend
Transactional email delivery with 99.9% uptime, payment confirmations with HTML invoices, welcome emails, and automated newsletter campaigns.

Core Features

Feature Description Plan Required Status
M&A Predictor AI-powered SEC filings analysis (6 factors) to predict mergers & acquisitions probability Platinum Active
Insider Flow Tracker Form 4 insider trading transactions tracking with 14 transaction classes and pattern detection Platinum Active
Trend Prediction ML predictive analysis with 5 models (Linear Regression, Ridge, Lasso, Random Forest, LSTM) Platinum Active
Advanced Analysis 14 Wall Street technical indicators (RSI, MACD, Bollinger, Fibonacci, Ichimoku, Pivot Points, ADX, Stochastic) Pro Active
Monte Carlo Simulation Probabilistic portfolio simulations with 6 models (Normal, Student-t, Log-Normal, Jump Diffusion, Regime Switching, GARCH) Free Active
Risk Parity Portfolio optimization by risk parity allocation with advanced rebalancing algorithms Pro Active
Investment Analytics Multi-allocation portfolio analytics with backtesting, VaR, Sharpe ratio, and scenario analysis Pro Active
Forex Converter 38 currencies with 14 Wall Street indicators, AI recommendations, and historical correlation matrix Pro Active
IPO Intelligence AI IPO scoring with S-1 SEC document parsing and multi-criteria evaluation Platinum Active
Chatbot FinanceGPT AI assistant powered by Gemini 2.5 Flash (8,192 tokens) with 3D robot interface Free Active
Community Hub Social features (posts, comments, likes, messages) with real-time updates Free Active
YouTube Intelligence Market analysis videos with AI categorization and sentiment detection Platinum Active

Performance Metrics

~630ms
Avg API Response Time
70%
Cache Hit Rate
85%
API Cost Reduction
99.9%
Uptime (Cloudflare Edge)

Global Architecture

Distributed Serverless Architecture

AlphaVault AI uses a fully serverless architecture hosted on Cloudflare's global edge network, ensuring ultra-low latency (<50ms) for users worldwide. The platform leverages Firebase for authentication and data storage, Stripe for payment processing, and 10+ Cloudflare Workers for backend logic.

System Architecture Diagram

๐ŸŒ User Layer (Global Access)

Desktop
Chrome, Safari, Edge

Mobile
iOS, Android

Tablet
iPad, Android Tablets
๐ŸŒ CDN & Hosting Layer

Cloudflare Pages
alphavault-ai.pages.dev
TLS 1.3 + Brotli Compression
๐Ÿ’ป Frontend Layer (Client-Side)

HTML Pages
65 pages (10.53 MB)

CSS Styles
49 files (Glassmorphism)

JavaScript
112 files (Vanilla JS)
โš™ Backend Services Layer (Serverless)

Firebase
Auth + Firestore + Storage

CF Workers
10+ Workers (Edge Compute)

Stripe
Payments + Subscriptions

Resend
Transactional Emails
๐Ÿ”Œ External APIs Layer (Data Sources)

Twelve Data
Market Data + Indicators

SEC EDGAR
SEC Filings (Form 4, S-1, 8-K)

Gemini AI
Gemini 2.5 Flash (8,192 tokens)

YouTube API
Market Videos (Quota: 10,000/day)

Communication Flow

Complete Request Flow
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                        ALPHAVAULT AI - REQUEST FLOW                              โ”‚
โ”‚                     (User โ†’ CDN โ†’ Frontend โ†’ Workers โ†’ APIs)                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

1โƒฃ  USER ACTION
    โ””โ”€> User accesses: https://alphavault-ai.com/advanced-analysis
        โ€ข Browser: Chrome 130 (Desktop)
        โ€ข Location: New York, USA
        โ€ข Action: Search for stock symbol "AAPL"

2โƒฃ  DNS RESOLUTION (Cloudflare DNS)
    โ””โ”€> Query: alphavault-ai.com
        โ€ข TTL: 300 seconds
        โ€ข Response: 104.21.x.x (Cloudflare Edge IP)
        โ€ข Latency: ~8ms

3โƒฃ  TLS HANDSHAKE (Cloudflare Edge)
    โ””โ”€> Protocol: TLS 1.3
        โ€ข Cipher: AES-256-GCM
        โ€ข Certificate: Let's Encrypt (Auto-renewed)
        โ€ข Latency: ~12ms

4โƒฃ  CLOUDFLARE PAGES (Static CDN)
    โ””โ”€> Request: GET /advanced-analysis
        โ€ข Cache: HIT (Edge cached for 24h)
        โ€ข Compression: Brotli (78% size reduction)
        โ€ข Response Size: 42 KB (compressed from 190 KB)
        โ€ข Latency: ~18ms
        โ€ข Headers:
          - CF-Cache-Status: HIT
          - CF-Ray: 8d7e2f3a1b2c3d4e-JFK
          - Server: cloudflare

5โƒฃ  BROWSER RENDERING (Client-Side)
    โ””โ”€> Parse HTML (42 KB)
        โ€ข Load CSS: advanced-analysis.css (132 KB)
        โ€ข Load JavaScript: advanced-analysis.js (4,292 lines)
        โ€ข Initialize Firebase SDK
        โ€ข Execute: auth-guard.js (Check authentication)
        โ€ข Execute: access-control.js (Verify plan: Pro โœ…)
        โ€ข Render UI: 14 chart containers + search form
        โ€ข Total Load Time: ~350ms

6โƒฃ  USER SEARCHES SYMBOL "AAPL"
    โ””โ”€> JavaScript Call: analyzeSymbol('AAPL')
        โ€ข Function: advanced-analysis.js (line 1247)
        โ€ข API Client: api-client.js (FinanceAPIClient class)
        โ€ข Parallel Requests: 4

7โƒฃ  CLOUDFLARE WORKER: finance-hub-api
    โ””โ”€> Endpoint: https://finance-hub-api.your-account.workers.dev/api/quote?symbol=AAPL
        โ€ข Method: GET
        โ€ข Headers: Authorization (API Key)
        โ€ข Cache Check: KV Storage ("quote:AAPL")
          - Cache Miss (expired 65 seconds ago)
        โ€ข Proxy to: Twelve Data API
        โ€ข Response: 200 OK (Real-time quote)
        โ€ข Store in KV: TTL 60 seconds
        โ€ข Latency: ~145ms

8โƒฃ  TWELVE DATA API (External)
    โ””โ”€> Request: GET https://api.twelvedata.com/quote?symbol=AAPL&apikey=***
        โ€ข API Key: Valid (Quota: 800/800 requests remaining)
        โ€ข Response: JSON (2.1 KB)
        โ€ข Data:
          {
            symbol: "AAPL",
            name: "Apple Inc",
            exchange: "NASDAQ",
            open: 185.50,
            high: 187.20,
            low: 184.80,
            close: 186.95,
            volume: 52847300,
            previous_close: 184.25,
            change: 2.70,
            percent_change: 1.47
          }
        โ€ข Latency: ~120ms

9โƒฃ  DATA PROCESSING (Frontend)
    โ””โ”€> Function: processAnalysisData()
        โ€ข Calculate 14 technical indicators locally
        โ€ข Generate AI recommendations (3 horizons)
        โ€ข Calculate composite score (0-100)
        โ€ข Prepare Highcharts data structures
        โ€ข Processing Time: ~95ms

๐Ÿ”Ÿ  UI RENDERING (Highcharts)
    โ””โ”€> Render 14 interactive charts:
        โ€ข Candlestick chart (365 data points)
        โ€ข RSI chart (14 periods)
        โ€ข MACD chart (histogram + signal)
        โ€ข Bollinger Bands
        โ€ข Moving Averages (SMA/EMA)
        โ€ข Fibonacci Retracements
        โ€ข Ichimoku Cloud
        โ€ข Pivot Points
        โ€ข ADX + DMI
        โ€ข Stochastic Oscillator
        โ€ข Volume chart
        โ€ข Support/Resistance levels
        โ€ข AI Recommendations (3 cards)
        โ€ข Risk Metrics dashboard
        โ€ข Rendering Time: ~280ms

โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
TOTAL TIME BREAKDOWN:
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

DNS Resolution:        8ms
TLS Handshake:        12ms
CDN Delivery:         18ms
Browser Load:        350ms
API Request:         145ms
External API:        120ms
Data Processing:      95ms
Chart Rendering:     280ms
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
TOTAL:               1,028ms

Cache Hit Next Time:  ~650ms (API cached)

Data Storage Architecture

Storage Type Service Purpose Data Examples
NoSQL Database Firebase Firestore User profiles, posts, messages, analytics /users, /posts, /comments, /conversations, /analytics_visits
Key-Value Store Cloudflare KV API response caching, quota tracking, simulations CACHE, SIMULATIONS_KV, QUOTA_KV namespaces
Object Storage Firebase Storage User uploads (profile pictures, post attachments) /users/{uid}/profile.jpg, /posts/{postId}/image.png
Session Storage Browser LocalStorage JWT tokens, user preferences, theme settings firebaseAuthToken, darkMode, language

Security Layers

TLS 1.3
Encryption Protocol
JWT
Authentication Tokens
Firestore
Security Rules
CORS
Origin Validation

Frontend - Structure & Organization

Modern Frontend Architecture

AlphaVault AI uses a vanilla JavaScript architecture (no frameworks) with a focus on performance, accessibility, and maintainability. All code is written in ES6+ with modular design patterns.

Project Structure

Folder Structure
alphavault-ai/
โ”œโ”€โ”€ assets/
โ”‚   โ”œโ”€โ”€ css/                          (49 files - 1.8 MB)
โ”‚   โ”‚   โ”œโ”€โ”€ common.css                (2,090 lines - Global styles)
โ”‚   โ”‚   โ”œโ”€โ”€ landing.css               (5,886 lines - Homepage)
โ”‚   โ”‚   โ”œโ”€โ”€ community.css             (6,890 lines - Community hub)
โ”‚   โ”‚   โ”œโ”€โ”€ admin-analytics.css       (4,039 lines - Admin dashboard)
โ”‚   โ”‚   โ”œโ”€โ”€ advanced-analysis.css     (5,490 lines - Technical analysis)
โ”‚   โ”‚   โ”œโ”€โ”€ investment-analytics.css  (3,748 lines - Portfolio analytics)
โ”‚   โ”‚   โ”œโ”€โ”€ trend-prediction.css      (2,599 lines - ML predictions)
โ”‚   โ”‚   โ”œโ”€โ”€ sidebar.css               (1,101 lines - Navigation)
โ”‚   โ”‚   โ”œโ”€โ”€ user-menu.css             (538 lines - User dropdown)
โ”‚   โ”‚   โ”œโ”€โ”€ chatbot-futuristic.css    (1,679 lines - AI chatbot)
โ”‚   โ”‚   โ””โ”€โ”€ ... (39 other files)
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ js/                           (112 files - 8.5 MB)
โ”‚   โ”‚   โ”œโ”€โ”€ admin-analytics.js        (7,846 lines - Admin backend)
โ”‚   โ”‚   โ”œโ”€โ”€ investment-analytics.js   (4,869 lines - Portfolio)
โ”‚   โ”‚   โ”œโ”€โ”€ advanced-analysis.js      (4,292 lines - 14 indicators)
โ”‚   โ”‚   โ”œโ”€โ”€ trend-prediction.js       (2,485 lines - ML predictions)
โ”‚   โ”‚   โ”œโ”€โ”€ insider-flow-tracker.js   (2,554 lines - Form 4 analysis)
โ”‚   โ”‚   โ”œโ”€โ”€ ipo-intelligence.js       (2,429 lines - IPO screening)
โ”‚   โ”‚   โ”œโ”€โ”€ ma-predictor.js           (1,066 lines - M&A screening)
โ”‚   โ”‚   โ”œโ”€โ”€ access-control.js         (2,660 lines - Plan-based access)
โ”‚   โ”‚   โ”œโ”€โ”€ api-client.js             (2,237 lines - API client)
โ”‚   โ”‚   โ”œโ”€โ”€ firebase-config.js        (783 lines - Auth & Firestore)
โ”‚   โ”‚   โ”œโ”€โ”€ auth-guard.js             (287 lines - Page protection)
โ”‚   โ”‚   โ”œโ”€โ”€ chatbot-fullpage-ui.js    (1,115 lines - AI chatbot UI)
โ”‚   โ”‚   โ””โ”€โ”€ ... (100 other files)
โ”‚   โ”‚
โ”‚   โ””โ”€โ”€ images/                       (Logos, favicons, illustrations)
โ”‚
โ”œโ”€โ”€ index                        (Homepage - 1,951 lines)
โ”œโ”€โ”€ dashboard-financier          (Budget dashboard - 828 lines)
โ”œโ”€โ”€ advanced-analysis            (14 indicators + AI - 2,906 lines)
โ”œโ”€โ”€ trend-prediction             (ML predictions - 1,565 lines)
โ”œโ”€โ”€ investment-analytics         (Multi-allocation - 1,103 lines)
โ”œโ”€โ”€ community-hub                (Social features - 675 lines)
โ”œโ”€โ”€ admin-analytics              (Admin backend - 2,989 lines)
โ”œโ”€โ”€ chatbot-fullpage             (FinanceGPT - 771 lines)
โ””โ”€โ”€ ... (57 other pages)

HTML Pages Overview (65 pages)

Page Purpose Lines Plan Required Type
index Landing page with 3D elements & hero section 1,951 Public Marketing
auth Login & Registration with Firebase Auth 514 Public Auth
dashboard-financier Budget dashboard with 8 Highcharts graphs 828 Free+ Dashboard
investment-analytics Multi-allocation portfolio analytics & optimization 1,103 Pro+ Analytics
monte-carlo Probabilistic simulations (6 models) 2,160 Free+ Simulation
advanced-analysis 14 Wall Street indicators + AI recommendations 2,906 Pro+ Analysis
trend-prediction ML predictions (5 models) + backtesting + ensemble 1,565 Platinum ML
ipo-intelligence AI IPO scoring + SEC S-1 parsing 847 Platinum Analysis
insider-flow-tracker Form 4 insider trading (14 transaction classes) 703 Platinum Analysis
ma-predictor M&A screening with 6 AI factors 664 Platinum Analysis
forex-converter 38 currencies + 14 Wall Street indicators 1,848 Pro+ Tools
chatbot-fullpage FinanceGPT AI assistant (Gemini 2.5) 771 Free+ AI
community-hub Social features (posts, comments, likes, messages) 675 Free+ Community
admin-analytics Admin dashboard (Stripe + Cloudflare analytics) 2,989 Admin Only Admin
+ 51 additional pages (companies directory, economic data, news terminal, settings, help, etc.)

CSS Architecture (49 files - 1.8 MB)

File Lines Size Purpose
common.css 2,090 47.57 KB Global styles, CSS variables, utility classes, responsive breakpoints
landing.css 5,886 142.24 KB Homepage (hero, features, pricing, testimonials, 3D animations)
community.css 6,890 179.70 KB Social hub (posts, comments, likes, messages, user profiles)
admin-analytics.css 4,039 104.74 KB Admin dashboard (Stripe analytics, Cloudflare metrics, charts)
advanced-analysis.css 5,490 132.89 KB Technical analysis (14 indicators, AI recommendations, charts)
investment-analytics.css 3,748 81.76 KB Portfolio analytics (multi-allocation, backtesting, risk metrics)
trend-prediction.css 2,599 62.22 KB ML predictions (5 models, backtesting, ensemble, accuracy tracking)
sidebar.css 1,101 25.32 KB Navigation sidebar (responsive, glassmorphism, collapsible folders)
chatbot-futuristic.css 1,679 37.60 KB AI chatbot (3D robot, glassmorphism, particles background)
+ 40 additional CSS files (total: 1.8 MB)

CSS Design System

  • Color Palette: Gradient-based (purple/blue theme: #667eea โ†’ #764ba2) with dark mode support
  • Typography: Inter font family, 8-level hierarchy (12px to 48px)
  • Responsive: Mobile-first approach, 4 breakpoints (320px, 480px, 768px, 1024px)
  • Effects: Glassmorphism (backdrop-filter: blur(20px)), neumorphism, 3D transforms, smooth transitions (0.3s ease)
  • Animations: 60fps GPU-accelerated (transform3d, will-change, requestAnimationFrame)
  • Accessibility: WCAG 2.1 Level AA compliant (contrast ratio 4.5:1, keyboard navigation, ARIA labels)

Essential JavaScript Scripts (112 files - 8.5 MB)

Script Lines Purpose Key Functions
admin-analytics.js 7,846 Admin dashboard backend Stripe analytics, Cloudflare metrics, user management, email campaigns, newsletter automation
investment-analytics.js 4,869 Portfolio analytics Multi-allocation system, optimization algorithms, backtesting engine, VaR/Sharpe calculations
advanced-analysis.js 4,292 Technical analysis 14 indicators: RSI, MACD, Bollinger, Fibonacci, Ichimoku, Pivot Points, ADX, Stochastic, SMA/EMA
trend-prediction.js 2,485 ML predictions 5 models (Linear Regression, Ridge, Lasso, Random Forest, LSTM), backtesting, ensemble aggregation
insider-flow-tracker.js 2,554 Insider trading analysis Form 4 parsing, 14 transaction classes, pattern detection (momentum, acceleration, unusual), network graphs
access-control.js 2,660 Plan-based page protection Firebase JWT verification, plan level checks (Free/Basic/Pro/Platinum), upgrade modals, feature gates
ipo-intelligence.js 2,429 IPO screening S-1 document parsing, AI scoring (6 factors), SEC API integration, multi-criteria evaluation
api-client.js 2,237 API client (Twelve Data) getQuote(), getTimeSeries(), getTechnicalIndicator(), getProfile(), getStatistics(), search()
monte-carlo.js 2,086 Probabilistic simulations 6 models: Normal, Student-t, Log-Normal, Jump Diffusion, Regime Switching, GARCH
chatbot-fullpage-ui.js 1,115 AI chatbot UI Firebase conversations, 3D robot animation (Three.js), real-time streaming, export/share/PDF
firebase-config.js 783 Firebase initialization initializeApp(), Auth providers (Email/Password + Google OAuth), Firestore real-time listeners
auth-guard.js 287 Page authentication onAuthStateChanged(), session verification, redirect to login, user data loading
+ 100 additional JavaScript files (total: 8.5 MB)

External Libraries & Integrations

Highcharts
Advanced charting library for stock/candlestick charts, heatmaps, 3D visualizations, and interactive gauges with real-time updates.
Chart.js
Chatbot charts, quick visualizations, responsive graphs for dashboard KPIs and real-time data monitoring.
Three.js
3D robot chatbot animation, landing page 3D elements, WebGL effects, and particle systems for premium visual experience.
Firebase SDK
Authentication (v10.7.1), Firestore database, Cloud Storage, real-time listeners, and serverless functions integration.

Code Statistics

274,011
Total Lines of Code
10.53 MB
Total Size (Uncompressed)
226
Total Files (HTML+CSS+JS)
100%
Vanilla JavaScript (No Frameworks)

Backend - Services & Infrastructure

Serverless Backend Architecture

AlphaVault AI's backend is 100% serverless, leveraging Firebase for authentication and data storage, Cloudflare Workers for edge computing, Stripe for payment processing, and Resend for email delivery. This architecture ensures zero maintenance, infinite scalability, and global low latency.

Firebase Configuration

firebase-config.js (Initialization)
// Firebase Configuration (Production)
const firebaseConfig = {
    apiKey: "YOUR_FIREBASE_API_KEY",
    authDomain: "alphavault-ai.firebaseapp.com",
    projectId: "alphavault-ai",
    storageBucket: "alphavault-ai.appspot.com",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID",
    measurementId: "YOUR_MEASUREMENT_ID"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Initialize Services
const auth = firebase.auth();
const db = firebase.firestore();
const storage = firebase.storage();

// Configure Auth Providers
const googleProvider = new firebase.auth.GoogleAuthProvider();
googleProvider.setCustomParameters({ prompt: 'select_account' });

// Enable Offline Persistence
db.enablePersistence({ synchronizeTabs: true })
    .catch((err) => console.warn('Offline persistence failed:', err));

console.log('๐Ÿ”ฅ Firebase initialized successfully');
Service Purpose Collections/Features
Firebase Authentication User authentication & session management with JWT tokens โ€ข Email/Password authentication
โ€ข Google OAuth 2.0 (one-click login)
โ€ข JWT token-based sessions (1h expiry)
โ€ข Password reset workflows
โ€ข Email verification links
Firestore Database NoSQL real-time database with automatic scaling โ€ข /users - User profiles, plans, subscription status
โ€ข /posts - Community posts with likes/comments
โ€ข /comments - Post comments with threading
โ€ข /conversations - Private messages & group chats
โ€ข /messages - Subcollection for conversation messages
โ€ข /simulations - Monte Carlo simulation data
โ€ข /portfolios - User watchlists & allocations
โ€ข /analytics_visits - Page view tracking
โ€ข /analytics_activity - User activity logs
โ€ข /businessPlans - Business plan documents
โ€ข /referrals - Referral program tracking
โ€ข /email_signatures - Admin email signatures
โ€ข /email_profile_pictures - Admin profile pictures
Firebase Storage File uploads & CDN with automatic image optimization โ€ข User profile pictures (avatars)
โ€ข Post attachments (images, PDFs up to 25MB)
โ€ข Message attachments
โ€ข Export files (JSON, CSV, PDF)
โ€ข Business plan documents

Firestore Security Rules (Production)

firestore.rules (Key Rules)
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    
    // ============================================
    // USERS COLLECTION
    // ============================================
    match /users/{userId} {
      // โœ… Read: Any authenticated user
      allow read: if request.auth != null;

      // โœ… Create: User can create their own document
      allow create: if request.auth != null && request.auth.uid == userId;

      // โœ… Update: User or Admin ([email protected])
      // OR automated updates (followers, posts count, etc.)
      allow update: if request.auth != null && 
                       (request.auth.uid == userId || 
                        request.auth.token.email == '[email protected]' ||
                        (request.resource.data.diff(resource.data).affectedKeys()
                         .hasOnly(['followersCount', 'followingCount', 'reputation', 
                                   'postCount', 'lastLoginAt', 'points', 'postsCount', 
                                   'commentsCount', 'likesReceived', 'updatedAt', 'photoURL'])));

      // โœ… Delete: User only
      allow delete: if request.auth != null && request.auth.uid == userId;
    }
    
    // ============================================
    // POSTS COLLECTION
    // ============================================
    match /posts/{postId} {
      // โœ… Read: Any authenticated user
      allow read: if request.auth != null;
      
      // โœ… Create: User must be author
      allow create: if request.auth != null && 
                       request.resource.data.authorId == request.auth.uid;
      
      // โœ… Update: Author, Admin, or automated counters (views, likes)
      allow update: if request.auth != null && 
                       (request.auth.uid == resource.data.authorId || 
                        request.auth.token.email == '[email protected]' ||
                        (request.resource.data.diff(resource.data).affectedKeys()
                         .hasOnly(['views', 'likes', 'commentsCount', 'updatedAt'])));
      
      // โœ… Delete: Author or Admin
      allow delete: if request.auth != null && 
                       (request.auth.uid == resource.data.authorId || 
                        request.auth.token.email == '[email protected]');
    }
    
    // ============================================
    // CONVERSATIONS (Private Messages + Groups)
    // ============================================
    match /conversations/{conversationId} {
      // โœ… Read: Participants only
      allow read: if request.auth != null && 
                     request.auth.uid in resource.data.participants;

      // โœ… Create: User must be a participant (1-to-1 or group)
      allow create: if request.auth != null && 
                       request.auth.uid in request.resource.data.participants;

      // โœ… Update/Delete: Participants only
      allow update, delete: if request.auth != null && 
                               request.auth.uid in resource.data.participants;

      // Messages subcollection
      match /messages/{messageId} {
        allow read: if request.auth != null && 
                       request.auth.uid in get(/databases/$(database)/documents/conversations/$(conversationId)).data.participants;

        allow create: if request.auth != null && 
                         request.auth.uid == request.resource.data.senderId &&
                         request.auth.uid in get(/databases/$(database)/documents/conversations/$(conversationId)).data.participants;

        allow update, delete: if request.auth != null && 
                                 request.auth.uid in get(/databases/$(database)/documents/conversations/$(conversationId)).data.participants;
      }
    }
    
    // ============================================
    // ADMIN-ONLY COLLECTIONS
    // ============================================
    match /analytics_visits/{document} {
      allow create: if true;  // Public write for tracking
      allow read: if request.auth != null && 
                     request.auth.token.email == '[email protected]';
    }

    match /payments/{document} {
      allow read: if request.auth != null && 
                     request.auth.token.email == '[email protected]';
    }
    
    // ============================================
    // BLOCK ALL OTHER ACCESS
    // ============================================
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

Cloudflare Workers (10+ Serverless APIs)

Worker Name Lines Purpose Key Endpoints & Features
finance-hub-api 2,885 Main backend API (Twelve Data + FinnHub + Stripe + Resend) Twelve Data:
โ€ข /api/quote - Real-time quotes
โ€ข /api/time-series - Historical data
โ€ข /api/technical-indicators - RSI, MACD, etc.
โ€ข /api/profile - Company fundamentals
Stripe:
โ€ข /create-checkout-session - Checkout
โ€ข /webhook - Stripe webhooks
โ€ข /verify-subscription - Plan check
Storage:
โ€ข /api/simulations (CRUD)
โ€ข /api/portfolios (CRUD)
economic-data-worker 656 ECB Forex (XML) + FRED economic data proxy ECB (European Central Bank):
โ€ข /ecb/rates - 30+ currencies (EUR base)
โ€ข /ecb/historical - 6 months historical forex
FRED (Federal Reserve):
โ€ข /series/observations - Time series data
โ€ข /multiple - Batch FRED requests
โ€ข /latest - Latest economic values
gmail-api 2,417 Hybrid email system (Gmail API + Resend API) Read (Gmail API):
โ€ข /gmail-inbox - Inbox messages
โ€ข /gmail-sent - Sent messages
โ€ข /gmail-thread - Message threads
Send (Resend API):
โ€ข /gmail-send - Send emails
โ€ข /gmail-reply - Reply with threading
โ€ข /gmail-forward - Forward with attachments
Management:
โ€ข /gmail-action - Mark read/archive/delete
โ€ข /gmail-labels - Label management
โ€ข Multi-sender support (authorized addresses)
gemini-ai-proxy 175 Secure proxy for Gemini 2.5 Flash API โ€ข POST /api/gemini - AI requests
โ€ข Model: gemini-2.5-flash
โ€ข Max Tokens: 8,192
โ€ข Temperature: 0.9
โ€ข Safety Settings: BLOCK_MEDIUM_AND_ABOVE
โ€ข CORS: alphavault-ai.com only
google-apis-proxy 432 YouTube Data API v3 with quota management โ€ข /youtube/search - Search videos (100 units)
โ€ข /youtube/video - Video details (1 unit)
โ€ข /youtube/channel - Channel info (1 unit)
โ€ข /quotas - Quota status dashboard
โ€ข Daily Limit: 10,000 units (80 searches max)
โ€ข Rate Limits: 60 req/min, 500 req/hour
google-knowledge-api 710 Google Knowledge Graph + Wikidata enrichment โ€ข /company-info?query=Apple - Enriched company data
โ€ข /batch-companies - Batch lookup (max 50)
Data Sources:
โ€ข Google KG (name, description, images, links)
โ€ข Wikidata (16 properties: CEO, headquarters, industry, stock symbol, etc.)
โ€ข Confidence scoring (very_low to very_high)
โ€ข Batch label resolution (50 IDs/request)
+ 4 additional workers (admin-analytics-api, sec-edgar-api, payment-flow-manager, newsletter-automation)

Cloudflare KV Storage (Key-Value Store)

Namespace Purpose TTL (Time To Live)
CACHE API response caching (Twelve Data, FinnHub, SEC EDGAR) 60s (quotes) to 3600s (profiles)
SIMULATIONS_KV User simulations & portfolios storage (Monte Carlo, Risk Parity) Persistent (no expiration)
QUOTA_KV YouTube API quota tracking (daily/hourly request limits) 24h reset (midnight UTC)

Backend Performance Metrics

10+
Cloudflare Workers
~7,500
Lines of Backend Code
30+
API Endpoints
99.9%
Uptime (Cloudflare Edge)
<50ms
Avg Worker Response Time
70%
Cache Hit Rate

Data Flows & Processes

About Data Flows

This section documents the three main data flows in AlphaVault AI: user registration, payment processing, and market data retrieval. Each flow shows the complete journey from user action to final result with detailed technical steps.

1. User Registration Flow

User Registration - Complete Journey (auth โ†’ Firebase โ†’ Firestore โ†’ Resend)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                          USER REGISTRATION FLOW                                  โ”‚
โ”‚                     (Browser โ†’ Firebase Auth โ†’ Firestore โ†’ Email)                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

1โƒฃ  USER SUBMITS REGISTRATION FORM
    โ”œโ”€ Page: auth
    โ”œโ”€ Email: [email protected]
    โ”œโ”€ Password: ************ (min 6 chars)
    โ”œโ”€ Name: John Doe
    โ””โ”€ Function: handleEmailSignup()

2โƒฃ  FIREBASE AUTHENTICATION
    โ”œโ”€ SDK: firebase.auth().createUserWithEmailAndPassword(email, password)
    โ”œโ”€ Validation:
    โ”‚  โœ“ Email format check
    โ”‚  โœ“ Password strength (min 6 chars)
    โ”‚  โœ“ Email not already registered
    โ”œโ”€ Create User:
    โ”‚  โ€ข UID: abc123xyz456 (auto-generated)
    โ”‚  โ€ข JWT Token: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9... (expires in 1h)
    โ””โ”€ Response: { uid, email, emailVerified: false, token }

3โƒฃ  FIRESTORE USER DOCUMENT CREATION
    โ”œโ”€ Collection: /users/{abc123xyz456}
    โ”œโ”€ Function: createUserProfile()
    โ””โ”€ Document Structure:
       {
         uid: "abc123xyz456",
         email: "[email protected]",
         name: "John Doe",
         plan: "basic",                    // Default plan
         subscriptionStatus: "inactive",
         createdAt: "2026-01-07T14:30:00.000Z",
         updatedAt: "2026-01-07T14:30:00.000Z",
         lastLogin: "2026-01-07T14:30:00.000Z",
         photoURL: "https://ui-avatars.com/api/?name=John+Doe",
         emailVerified: false,
         onboardingCompleted: false,
         preferences: {
           theme: "light",
           language: "en",
           notifications: true,
           newsletter: false
         },
         usage: {
           apiCalls: 0,
           chatbotMessages: 0,
           simulationsCreated: 0
         }
       }

4โƒฃ  WELCOME EMAIL (Cloudflare Worker โ†’ Resend API)
    โ”œโ”€ Worker: finance-hub-api
    โ”œโ”€ Function: sendWelcomeEmail()
    โ”œโ”€ Email Service: Resend API
    โ”œโ”€ Sender: AlphaVault AI 
    โ””โ”€ Email Template (HTML + Glassmorphism):
       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
       โ”‚ ๐ŸŽ‰ WELCOME TO ALPHAVAULT AI!                                    โ”‚
       โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚
       โ”‚ [GRADIENT HEADER: Purple โ†’ Blue]                               โ”‚
       โ”‚ [PNG LOGO 192x192]                                             โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ Hi John Doe,                                                    โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ Your account has been created successfully!                    โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ ๐Ÿ‘‘ AlphaVault Basic (9 pages unlocked)                         โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ ๐Ÿ“Š Pages You Can Access:                                       โ”‚
       โ”‚ โœ“ Dashboard Budget                                             โ”‚
       โ”‚ โœ“ Community Hub                                                โ”‚
       โ”‚ โœ“ Monte Carlo Simulations                                      โ”‚
       โ”‚ โœ“ Real Estate Tax Simulator                                    โ”‚
       โ”‚ โœ“ Portfolio Optimizer (Markowitz)                              โ”‚
       โ”‚ โœ“ Economic Dashboard                                           โ”‚
       โ”‚ โœ“ Companies Directory                                          โ”‚
       โ”‚ โœ“ Settings & User Profile                                      โ”‚
       โ”‚ โœ“ Create Posts & Messages                                      โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ [ACCESS YOUR DASHBOARD โ†’] (Gradient Button)                    โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ Need more features? Upgrade to Pro or Platinum!                โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚
       โ”‚ ยฉ 2026 AlphaVault AI | [email protected]                  โ”‚
       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

5โƒฃ  ANALYTICS TRACKING
    โ”œโ”€ Worker: admin-analytics-api
    โ”œโ”€ Collection: /analytics_activity
    โ””โ”€ Event Data:
       {
         eventType: "user_registered",
         userId: "abc123xyz456",
         email: "[email protected]",
         plan: "basic",
         timestamp: "2026-01-07T14:30:00.000Z",
         source: "organic",
         userAgent: "Mozilla/5.0...",
         device: "desktop",
         location: { country: "US", city: "New York" }
       }

6โƒฃ  REDIRECT TO DASHBOARD
    โ”œโ”€ URL: /dashboard-financier
    โ”œโ”€ Session: Active (JWT token stored in localStorage)
    โ”œโ”€ Plan: Basic (9 pages unlocked)
    โ””โ”€ โœ… REGISTRATION COMPLETE

โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
KEY FILES INVOLVED:
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Frontend:
โ€ข auth                           (Registration form UI)
โ€ข assets/js/auth.js                   (Form handling + Firebase calls)
โ€ข assets/js/firebase-config.js        (Firebase initialization)

Backend:
โ€ข Firebase Authentication             (User creation + JWT)
โ€ข Firestore Database                  (/users collection)
โ€ข Cloudflare Worker: finance-hub-api  (Email sending)
โ€ข Resend API                           (Email delivery)

Analytics:
โ€ข Cloudflare Worker: admin-analytics-api
โ€ข Firestore: /analytics_activity

2. Stripe Payment Flow

Stripe Payment - End-to-End Process (Checkout โ†’ Webhook โ†’ Firebase โ†’ Email โ†’ Invoice)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                          STRIPE PAYMENT FLOW                                     โ”‚
โ”‚              (User โ†’ Worker โ†’ Stripe โ†’ Webhook โ†’ Firebase โ†’ Email)              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

1โƒฃ  USER SELECTS PLAN
    โ”œโ”€ Page: checkout
    โ”œโ”€ Plan: Pro ($10/month)
    โ”œโ”€ Promo Code: LAUNCH15 (15% off)
    โ””โ”€ Action: Click "Subscribe"

2โƒฃ  CLOUDFLARE WORKER: finance-hub-api
    โ”œโ”€ Endpoint: POST /create-checkout-session
    โ”œโ”€ Body: { plan: "pro", userId: "abc123", promoCode: "LAUNCH15" }
    โ”œโ”€ Process:
    โ”‚  โœ“ Validate plan (basic/pro/platinum)
    โ”‚  โœ“ Verify promo code: LAUNCH15
    โ”‚    โ†’ Type: percentage (15%)
    โ”‚    โ†’ Duration: forever
    โ”‚  โœ“ Create Stripe Coupon: coupon_launch15_abc123
    โ”‚  โœ“ Get Price ID: env.STRIPE_PRICE_PRO
    โ””โ”€ Stripe API Call:
       POST https://api.stripe.com/v1/checkout/sessions
       {
         mode: "subscription",
         customer_email: "[email protected]",
         client_reference_id: "abc123xyz456",
         line_items: [{ price: "price_pro_id", quantity: 1 }],
         discounts: [{ coupon: "coupon_launch15_abc123" }],
         subscription_data: {
           trial_period_days: 14,
           metadata: { userId: "abc123xyz456", plan: "pro", promoCode: "LAUNCH15" }
         },
         success_url: "https://alphavault-ai.com/success?session_id={CHECKOUT_SESSION_ID}",
         cancel_url: "https://alphavault-ai.com/checkout?cancelled=true"
       }
       Response: { id: "cs_test_abc123", url: "https://checkout.stripe.com/..." }

3โƒฃ  REDIRECT TO STRIPE CHECKOUT
    โ”œโ”€ URL: https://checkout.stripe.com/c/pay/cs_test_abc123
    โ”œโ”€ User enters payment details:
    โ”‚  โ€ข Card: 4242 4242 4242 4242
    โ”‚  โ€ข Expiry: 12/28
    โ”‚  โ€ข CVC: 123
    โ””โ”€ Stripe validates payment method

4โƒฃ  STRIPE PROCESSES PAYMENT
    โ”œโ”€ Create Customer: cus_abc123
    โ”œโ”€ Create Subscription: sub_xyz789
    โ”œโ”€ Apply Discount: 15% off (final: $8.50/month)
    โ”œโ”€ Start Trial: 14 days (no charge until Jan 21, 2026)
    โ”œโ”€ Schedule Invoice: Jan 21, 2026 ($8.50)
    โ””โ”€ Subscription Details:
       {
         id: "sub_xyz789",
         customer: "cus_abc123",
         status: "trialing",
         trial_end: "2026-01-21T00:00:00.000Z",
         plan: { amount: 1000, currency: "usd", interval: "month" },
         discount: { coupon: { percent_off: 15, duration: "forever" } },
         metadata: { userId: "abc123xyz456", plan: "pro", promoCode: "LAUNCH15" }
       }

5โƒฃ  STRIPE WEBHOOK โ†’ WORKER
    โ”œโ”€ Event: checkout.session.completed
    โ”œโ”€ Endpoint: POST /webhook (finance-hub-api)
    โ”œโ”€ Signature Verification: STRIPE_WEBHOOK_SECRET
    โ”œโ”€ Handler: handleCheckoutSessionCompleted()
    โ””โ”€ Actions:
       โ€ข Extract userId from client_reference_id
       โ€ข Update Firebase Firestore (/users/{userId}):
         {
           plan: "pro",
           stripeCustomerId: "cus_abc123",
           stripeSubscriptionId: "sub_xyz789",
           subscriptionStatus: "active",
           promoCode: "LAUNCH15",
           discount: 15,
           trialEnd: "2026-01-21T00:00:00.000Z",
           updatedAt: serverTimestamp()
         }
       โ€ข User now has access to 17 pages (Pro plan)
       โ€ข Trigger confirmation email

6โƒฃ  RESEND API - CONFIRMATION EMAIL
    โ”œโ”€ Service: Resend (https://api.resend.com/emails)
    โ”œโ”€ Sender: AlphaVault AI 
    โ””โ”€ Email Template (Glassmorphism + HTML Invoice):
       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
       โ”‚ โœ… PAYMENT CONFIRMED - ALPHAVAULT AI                            โ”‚
       โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚
       โ”‚ [GRADIENT HEADER: Purple โ†’ Blue]                               โ”‚
       โ”‚ [PNG LOGO 192x192]                                             โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ [โœ“ SUCCESS ICON - Green Circle]                                โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ Hi John Doe,                                                    โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ Your subscription has been successfully processed!             โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ ๐Ÿ‘‘ AlphaVault Pro                                              โ”‚
       โ”‚ โฑ 14-Day Free Trial - No charges until Jan 21, 2026          โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ”‚
       โ”‚ โ•‘ TRANSACTION DETAILS                                       โ•‘ โ”‚
       โ”‚ โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ โ”‚
       โ”‚ โ•‘ Customer:   John Doe                                      โ•‘ โ”‚
       โ”‚ โ•‘ Email:      [email protected]                              โ•‘ โ”‚
       โ”‚ โ•‘ Plan:       AlphaVault Pro                                โ•‘ โ”‚
       โ”‚ โ•‘ Amount:     $8.50/month (15% discount applied)            โ•‘ โ”‚
       โ”‚ โ•‘ Invoice:    #AV-202601-147820                             โ•‘ โ”‚
       โ”‚ โ•‘ Date:       January 07, 2026                              โ•‘ โ”‚
       โ”‚ โ•‘ Status:     โœ“ Active                                      โ•‘ โ”‚
       โ”‚ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ ๐ŸŽ‰ FEATURES UNLOCKED (17 PAGES):                               โ”‚
       โ”‚ โœ“ Everything in Free (9 pages)                                โ”‚
       โ”‚ โœ“ Investment Analytics (Multi-allocation portfolios)          โ”‚
       โ”‚ โœ“ Risk Parity Optimization                                     โ”‚
       โ”‚ โœ“ Scenario Analysis (Bull/Base/Bear)                          โ”‚
       โ”‚ โœ“ Advanced Analysis (14 Wall Street indicators)               โ”‚
       โ”‚ โœ“ Forex Converter (38 currencies + 14 indicators)             โ”‚
       โ”‚ โœ“ Inflation Calculator                                         โ”‚
       โ”‚ โœ“ Interest Rate Tracker                                        โ”‚
       โ”‚ โœ“ News Terminal (Real-time financial news)                    โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ [ACCESS YOUR DASHBOARD โ†’] (Gradient Button)                    โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ Thank you for choosing AlphaVault AI!                          โ”‚
       โ”‚ You can cancel anytime from your account settings.             โ”‚
       โ”‚                                                                 โ”‚
       โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚
       โ”‚ Dashboard | Website | Support                                  โ”‚
       โ”‚ ยฉ 2026 AlphaVault AI | [email protected]                  โ”‚
       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       
       ๐Ÿ“Ž Attachment: AlphaVault_Invoice_AV-202601-147820
          (HTML invoice with SVG logo + transaction details)

7โƒฃ  SUCCESS PAGE
    โ”œโ”€ URL: /success
    โ”œโ”€ Confirmation message displayed
    โ”œโ”€ Email sent notification
    โ””โ”€ โœ… PAYMENT COMPLETE

โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
STRIPE WEBHOOK EVENTS HANDLED:
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

โ€ข checkout.session.completed    โ†’ Update Firebase, send email
โ€ข customer.subscription.updated  โ†’ Sync subscription status
โ€ข customer.subscription.deleted  โ†’ Downgrade to Basic, cancel subscription
โ€ข invoice.payment_succeeded      โ†’ Update payment date, send receipt
โ€ข invoice.payment_failed         โ†’ Set grace period, send notification

3. Market Data Retrieval Flow

Market Data - API Chain (Frontend โ†’ Worker โ†’ External APIs โ†’ Cache โ†’ Response)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                      MARKET DATA RETRIEVAL FLOW                                  โ”‚
โ”‚            (api-client.js โ†’ Cloudflare Worker โ†’ Twelve Data / FinnHub)           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

1โƒฃ  USER SEARCHES SYMBOL "AAPL"
    โ”œโ”€ Page: advanced-analysis
    โ”œโ”€ Input: "AAPL"
    โ”œโ”€ Action: Click "Analyze"
    โ””โ”€ JavaScript: analyzeSymbol('AAPL')

2โƒฃ  API CLIENT (Frontend)
    โ”œโ”€ File: assets/js/api-client.js
    โ”œโ”€ Class: FinanceAPIClient
    โ””โ”€ Parallel Requests (4):
       โ€ข getQuote('AAPL')              โ†’ Real-time price
       โ€ข getTimeSeries('AAPL', '1day', 365) โ†’ Historical data (1 year)
       โ€ข getTechnicalIndicator('AAPL', 'rsi') โ†’ RSI indicator
       โ€ข getProfile('AAPL')            โ†’ Company fundamentals

3โƒฃ  CLOUDFLARE WORKER: finance-hub-api
    โ”œโ”€ Base URL: https://finance-hub-api.your-account.workers.dev
    โ””โ”€ Request 1: GET /api/quote?symbol=AAPL
       โ”œโ”€ Cache Check: KV Storage ("quote:AAPL")
       โ”‚  โ””โ”€ Cache Miss (expired 65s ago)
       โ”œโ”€ Proxy to: Twelve Data API
       โ”‚  โ†’ GET https://api.twelvedata.com/quote?symbol=AAPL&apikey=***
       โ”œโ”€ Response: 200 OK (Real-time quote)
       โ”‚  {
       โ”‚    symbol: "AAPL",
       โ”‚    name: "Apple Inc",
       โ”‚    exchange: "NASDAQ",
       โ”‚    open: 185.50,
       โ”‚    high: 187.20,
       โ”‚    low: 184.80,
       โ”‚    close: 186.95,
       โ”‚    volume: 52847300,
       โ”‚    previous_close: 184.25,
       โ”‚    change: 2.70,
       โ”‚    percent_change: 1.47
       โ”‚  }
       โ”œโ”€ Store in KV: TTL 60 seconds
       โ””โ”€ Latency: ~145ms

    โ””โ”€ Request 2: GET /api/time-series?symbol=AAPL&interval=1day&size=365
       โ”œโ”€ Cache Check: KV Storage ("timeseries:AAPL:1day:365")
       โ”‚  โ””โ”€ Cache Hit! (cached 15 minutes ago)
       โ”œโ”€ Response (from cache):
       โ”‚  {
       โ”‚    symbol: "AAPL",
       โ”‚    interval: "1day",
       โ”‚    data: [
       โ”‚      { datetime: "2025-01-07", open: 185.50, high: 187.20, ... },
       โ”‚      { datetime: "2025-01-06", open: 182.30, high: 184.50, ... },
       โ”‚      ... (365 data points)
       โ”‚    ]
       โ”‚  }
       โ””โ”€ Latency: ~25ms (cache hit)

    โ””โ”€ Request 3: GET /api/technical-indicators?symbol=AAPL&indicator=rsi
       โ”œโ”€ Cache Check: KV Storage ("indicator:AAPL:rsi:1day:14")
       โ”‚  โ””โ”€ Cache Miss
       โ”œโ”€ Proxy to: Twelve Data API
       โ”‚  โ†’ GET https://api.twelvedata.com/rsi?symbol=AAPL&interval=1day...
       โ”œโ”€ Response: 200 OK
       โ”‚  {
       โ”‚    symbol: "AAPL",
       โ”‚    indicator: "RSI",
       โ”‚    values: [
       โ”‚      { datetime: "2025-01-07", rsi: 62.45 },
       โ”‚      { datetime: "2025-01-06", rsi: 58.32 },
       โ”‚      ... (100 data points)
       โ”‚    ]
       โ”‚  }
       โ”œโ”€ Store in KV: TTL 1800 seconds (30 min)
       โ””โ”€ Latency: ~135ms

    โ””โ”€ Request 4: GET /api/profile?symbol=AAPL
       โ”œโ”€ Cache Check: KV Storage ("profile:AAPL")
       โ”‚  โ””โ”€ Cache Hit! (cached 2 hours ago)
       โ”œโ”€ Response (from cache):
       โ”‚  {
       โ”‚    symbol: "AAPL",
       โ”‚    name: "Apple Inc",
       โ”‚    sector: "Technology",
       โ”‚    industry: "Consumer Electronics",
       โ”‚    market_cap: 2800000000000,
       โ”‚    pe_ratio: 28.5,
       โ”‚    eps: 6.55,
       โ”‚    dividend_yield: 0.52,
       โ”‚    beta: 1.24
       โ”‚  }
       โ””โ”€ Latency: ~18ms (cache hit)

4โƒฃ  DATA PROCESSING (Frontend)
    โ”œโ”€ File: assets/js/advanced-analysis.js
    โ”œโ”€ Function: processAnalysisData()
    โ””โ”€ Actions:
       โ€ข Merge all API responses
       โ€ข Calculate 14 technical indicators locally:
         โ†’ RSI, MACD, Bollinger Bands, Fibonacci, Moving Averages,
            Ichimoku Cloud, Pivot Points, ADX, Stochastic, etc.
       โ€ข Generate AI recommendations (3 horizons: Short/Medium/Long)
       โ€ข Calculate composite score (0-100)
       โ€ข Calculate risk metrics (VaR, Sharpe, Beta, Volatility)
       โ€ข Processing Time: ~95ms

5โƒฃ  UI RENDERING (Highcharts)
    โ”œโ”€ Render 14 interactive charts:
    โ”‚  โ€ข Candlestick chart (365 data points)
    โ”‚  โ€ข RSI chart (14 periods)
    โ”‚  โ€ข MACD chart (histogram + signal)
    โ”‚  โ€ข Bollinger Bands
    โ”‚  โ€ข Moving Averages (SMA/EMA)
    โ”‚  โ€ข Fibonacci Retracements
    โ”‚  โ€ข Ichimoku Cloud
    โ”‚  โ€ข Pivot Points
    โ”‚  โ€ข ADX + DMI
    โ”‚  โ€ข Stochastic Oscillator
    โ”‚  โ€ข Volume chart
    โ”‚  โ€ข Support/Resistance levels
    โ”‚  โ€ข AI Recommendations (3 cards)
    โ”‚  โ€ข Risk Metrics dashboard
    โ””โ”€ Rendering Time: ~280ms

6โƒฃ  FINAL RESULT DISPLAYED
    โ”œโ”€ Total Time: ~630ms (fetch + process + render)
    โ”œโ”€ Cache Efficiency: 50% (2/4 requests cached)
    โ””โ”€ โœ… ANALYSIS COMPLETE

โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
CACHE TTL CONFIGURATION:
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

โ€ข quote:                 60s      (1 minute - real-time data)
โ€ข timeSeries:         1,800s      (30 minutes - historical data)
โ€ข indicators:         1,800s      (30 minutes - technical data)
โ€ข profile:           86,400s      (24 hours - company fundamentals)
โ€ข search:            86,400s      (24 hours - symbol search)
โ€ข statistics:         3,600s      (1 hour - company statistics)

Cache Hit Rate Average: 70%
API Cost Reduction: 85% (compared to no caching)

Performance Summary

~630ms
Avg Total Response Time
70%
Cache Hit Rate
85%
API Cost Reduction
4-6
Parallel API Calls per Analysis

Payment System & Subscriptions

Complete Stripe Integration

AlphaVault AI uses Stripe for subscription management with a 14-day free trial, custom promo codes (percentage discounts, free access, trial extensions), and automated email confirmations with professional HTML invoices sent via Resend API.

Pricing Plans & Features

Plan Price Stripe Price ID Pages Key Features
Free $0/month N/A 9 pages Dashboard Budget, Community Hub, Monte Carlo, Real Estate Simulator, Portfolio Optimizer, Economic Dashboard, Companies Directory, Settings, Create Posts
Basic $5/month STRIPE_PRICE_BASIC 9 pages Everything in Free plan (Entry-level subscription)
Pro $10/month STRIPE_PRICE_PRO 17 pages Everything in Basic + Investment Analytics, Risk Parity, Scenario Analysis, Advanced Analysis (14 indicators), Forex Converter (38 currencies), Inflation Calculator, Interest Rate Tracker, News Terminal
Platinum $20/month STRIPE_PRICE_PLATINUM 25 pages Everything in Pro + IPO Intelligence (AI Scoring), Insider Flow Tracker (14 classes), M&A Predictor (6 AI factors), Trend Prediction ML, Market Sentiment, Trending Topics, YouTube Intelligence, Recession Indicators

Promo Codes System

Code Type Value Description Duration
LAUNCH15 Percentage 15% Launch discount (all plans) Forever
WELCOME15 Percentage 15% Welcome discount (all plans) Forever
SAVE15 Percentage 15% General 15% discount Forever
FREEPRO Free Access Lifetime Free lifetime access to Pro plan Permanent
FREEPLATINUM Free Access Lifetime Free lifetime access to Platinum plan Permanent
VIPACCESS Free Access Lifetime VIP access (Pro or Platinum) Permanent
FREE14DAYS Trial 14 days 14-day free trial (no card required) One-time
TRIAL14 Trial 14 days 14-day trial period One-time
TRYITFREE Trial 14 days Try it free for 14 days One-time

Stripe Webhook Events

Event Type Handler Function Actions Performed
checkout.session.completed handleCheckoutSessionCompleted() โ€ข Update Firebase user plan
โ€ข Store Stripe customer ID
โ€ข Store Stripe subscription ID
โ€ข Send confirmation email (Resend)
โ€ข Generate HTML invoice
โ€ข Log analytics event
customer.subscription.updated handleSubscriptionUpdated() โ€ข Sync subscription status
โ€ข Update trial status
โ€ข Update billing period
โ€ข Log subscription change
customer.subscription.deleted handleSubscriptionDeleted() โ€ข Downgrade to Basic plan
โ€ข Set status to 'cancelled'
โ€ข Remove subscription ID
โ€ข Send cancellation notification
โ€ข Log cancellation event
invoice.payment_succeeded handlePaymentSucceeded() โ€ข Update last payment date
โ€ข Send payment receipt
โ€ข Extend subscription period
โ€ข Log successful payment
invoice.payment_failed handlePaymentFailed() โ€ข Set status to 'past_due'
โ€ข Set 7-day grace period
โ€ข Send notification email
โ€ข Attempt Stripe auto-retry

Automated HTML Invoice System

  • Format: Professional HTML invoice with embedded SVG logo (scalable)
  • Filename: AlphaVault_Invoice_AV-{YYMMDD}-{ID}
  • Content: Transaction details, plan summary, payment breakdown, customer info
  • Design: Glassmorphism style matching email template (gradient headers, shadows)
  • Attachment: Base64-encoded HTML file sent via Resend API
  • Storage: Automatically stored in Firestore (/payments collection) for admin access
4
Pricing Plans
9
Promo Codes Active
14 days
Free Trial Period
5
Webhook Events Handled

Security & Access Control

Multi-Layer Security Architecture

AlphaVault AI implements a defense-in-depth security strategy with multiple layers: TLS 1.3 encryption, Firebase JWT authentication, Firestore security rules, plan-based access control, CORS protection, API key rotation, and real-time activity monitoring.

Authentication System

Component Technology Implementation Details
Email/Password Auth Firebase Authentication โ€ข Bcrypt password hashing (cost factor: 10)
โ€ข Min password length: 6 characters
โ€ข Email verification required
โ€ข Password reset via secure links
Google OAuth 2.0 Firebase GoogleAuthProvider โ€ข One-click sign-in/sign-up
โ€ข Automatic account linking
โ€ข Profile data import (name, photo)
โ€ข Custom OAuth scopes
JWT Tokens Firebase Auth Tokens โ€ข RS256 signature algorithm
โ€ข 1-hour expiration (auto-refresh)
โ€ข Secure storage (localStorage)
โ€ข Sent in Authorization header
Session Management Firebase onAuthStateChanged() โ€ข Real-time session monitoring
โ€ข Automatic logout on token expiry
โ€ข Cross-tab synchronization
โ€ข Persistent sessions (remember me)

Plan-Based Access Control

Page/Feature Required Plan Access Control Method Enforcement
Dashboard Budget, Community Hub, Monte Carlo Free+ auth-guard.js only (authentication check) Client-side redirect to login if not authenticated
Investment Analytics, Risk Parity, Advanced Analysis, Forex Converter Pro+ access-control.js + Firebase plan check Upgrade modal + redirect to pricing after 3s if plan insufficient
IPO Intelligence, Insider Flow Tracker, M&A Predictor, Trend Prediction Platinum access-control.js + Firebase plan check Upgrade modal + redirect to pricing after 3s if plan insufficient
Admin Analytics, Admin Documentation Admin Only Email whitelist check ([email protected]) 403 Forbidden + redirect to homepage if not admin

API Key Management

Service Storage Location Access Method Security Measures
Firebase API Key Public (firebaseConfig) Client-side (firebase-config.js) โ€ข Domain restrictions (alphavault-ai.com)
โ€ข Firestore Security Rules
โ€ข Auth required for all operations
Stripe Secret Key Cloudflare Worker Environment Variables Server-side only (finance-hub-api) โ€ข Never exposed to client
โ€ข Webhook signature verification
โ€ข HTTPS-only communication
Resend API Key Cloudflare Worker Secrets Server-side only (finance-hub-api) โ€ข Encrypted at rest
โ€ข Authorized sender addresses only
โ€ข Rate limiting (100 emails/hour)
Twelve Data API Key Cloudflare Worker Environment Proxied through Worker โ€ข Hidden from client
โ€ข Request caching (KV Storage)
โ€ข Quota monitoring
Gemini AI API Key Cloudflare Worker Secrets Proxied through gemini-ai-proxy โ€ข CORS restricted (alphavault-ai.com)
โ€ข Request validation
โ€ข Safety settings enforcement

Firestore Security Rules Summary

Collection Read Access Write Access Special Rules
/users/{userId} Any authenticated user Owner or Admin โ€ข Automated counters allowed (followersCount, postsCount)
โ€ข Admin: [email protected]
/posts/{postId} Any authenticated user Author or Admin โ€ข Author must match authorId on create
โ€ข View/like counters allowed
/comments/{commentId} Any authenticated user Author or Admin โ€ข Author must match authorId on create
โ€ข Like counter updates allowed
/conversations/{convId} Participants only Participants only โ€ข User must be in participants array
โ€ข Supports 1-to-1 and group chats
/messages/{msgId} Conversation participants Sender (participant) โ€ข Sender must match senderId on create
โ€ข Nested under /conversations
/analytics_visits Admin only Public (tracking) โ€ข Create allowed for all (analytics tracking)
โ€ข Read restricted to admin
/payments Admin only Denied โ€ข Read-only for admin
โ€ข Written by Stripe webhook only

Additional Security Measures

TLS 1.3 Encryption
All communication encrypted with TLS 1.3, AES-256-GCM cipher, and automatic HTTP to HTTPS redirection via Cloudflare.
CORS Protection
Strict CORS policies on all Workers (alphavault-ai.com only), preflight request validation, and credential inclusion control.
Rate Limiting
YouTube API: 60 req/min, 500 req/hour. Email sending: 100/hour. Cloudflare Workers: Automatic DDoS protection.
Activity Monitoring
Real-time tracking in /analytics_activity (user actions, failed logins, suspicious patterns, API usage spikes).
TLS 1.3
Encryption Standard
JWT
Token Authentication
99.9%
Security Rule Coverage
0
Security Incidents (Production)

APIs & Cloudflare Workers

Serverless Backend Infrastructure

AlphaVault AI's backend is powered by 10+ Cloudflare Workers deployed on the edge network, providing ultra-low latency (<50ms), infinite scalability, and zero server maintenance. Each worker is optimized for specific tasks (API proxying, payment processing, email delivery, analytics).

Worker 1: Admin Analytics API

admin-analytics-api.your-account.workers.dev
๐Ÿ“Š ADMIN ANALYTICS API
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Base URL: https://admin-analytics-api.raphnardone.workers.dev
Purpose: Aggregate Stripe & Cloudflare analytics for admin dashboard

๐Ÿ”Œ ENDPOINTS:

1. GET /stripe-analytics
   โ”œโ”€ Purpose: Retrieve all Stripe subscription data
   โ”œโ”€ Response: { customers, subscriptions, revenue, plans }
   โ””โ”€ Auth: Stripe Secret Key

2. GET /cloudflare-analytics?days=30
   โ”œโ”€ Purpose: Cloudflare httpRequests1dGroups (up to 365 days)
   โ”œโ”€ Response: { requests, bandwidth, threats, status_codes }
   โ””โ”€ Limitation: Max 365 days

3. GET /cloudflare-geo
   โ”œโ”€ Purpose: Geographic distribution of visitors
   โ””โ”€ Response: { country_code, requests, bandwidth }

4. GET /cloudflare-devices
   โ”œโ”€ Purpose: Device type breakdown (desktop/mobile/tablet)
   โ””โ”€ Response: { deviceType, requests, percentage }

5. GET /cloudflare-pages
   โ”œโ”€ Purpose: Top pages by traffic
   โ””โ”€ Response: { path, requests, unique_visitors }

6. GET /cloudflare-cache
   โ”œโ”€ Purpose: Cache hit/miss statistics
   โ””โ”€ Response: { hit_rate, cached_bytes, requests }

7. GET /cloudflare-referrers
   โ”œโ”€ Purpose: Top referrer sources
   โ”œโ”€ Response: { referrer, requests }
   โ””โ”€ Requirement: Cloudflare Pro plan

8. POST /send-alert-email
   โ”œโ”€ Purpose: Send admin email alerts (Resend API)
   โ”œโ”€ Body: { to, subject, html }
   โ””โ”€ Response: { success, messageId }

9. GET /health
   โ”œโ”€ Purpose: Health check endpoint
   โ””โ”€ Response: { status: "ok", timestamp }

โš  LIMITATIONS:
โ€ข Cloudflare Overview: Up to 365 days
โ€ข Cloudflare Details (httpRequestsAdaptiveGroups): Max 24 hours
โ€ข Referrers: Requires Cloudflare Pro plan

Worker 2: SEC EDGAR API Proxy

sec-edgar-api.your-account.workers.dev
๐Ÿ› SEC EDGAR API PROXY
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Base URL: https://sec-edgar-api.raphnardone.workers.dev
Purpose: Proxy SEC EDGAR API (bypass 403 errors from Cloudflare IPs)

๐Ÿ”Œ ENDPOINTS:

1. GET /filings/form4/recent?count=100
   โ”œโ”€ Purpose: Recent Form 4 insider trading filings
   โ”œโ”€ Response: { filings: [...], count, date_range }
   โ””โ”€ User-Agent: "AlphaVault AI [email protected]"

2. GET /filings/s1/recent?count=50
   โ”œโ”€ Purpose: Recent S-1 IPO registration filings
   โ””โ”€ Response: { filings: [...], count }

3. GET /filings/8k/recent?count=100
   โ”œโ”€ Purpose: Recent 8-K current event reports
   โ””โ”€ Response: { filings: [...], count }

4. GET /company/{cik}/filings
   โ”œโ”€ Purpose: All filings for a specific CIK number
   โ”œโ”€ Example: /company/0000320193/filings (Apple)
   โ””โ”€ Response: { cik, company_name, filings: [...] }

5. GET /search?ticker=AAPL
   โ”œโ”€ Purpose: Search company by ticker symbol
   โ””โ”€ Response: { cik, company_name, tickers }

โš  KNOWN ISSUE:
SEC EDGAR blocks many cloud provider IPs (403 Forbidden).
Alternative: Use direct CIK numbers or pre-cached data.

Worker 3: Payment Flow Manager

payment-flow-manager.your-account.workers.dev
๐Ÿ’ณ PAYMENT FLOW MANAGER
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Base URL: https://payment-flow-manager.raphnardone.workers.dev
Purpose: Handle complete payment flow (Stripe + Firebase + Resend)

๐Ÿ”Œ ENDPOINTS:

1. POST /create-checkout-session
   โ”œโ”€ Body: { plan, userId, email, promoCode? }
   โ”œโ”€ Process:
   โ”‚  โ€ข Validate plan & promo code
   โ”‚  โ€ข Create Stripe Coupon (if discount)
   โ”‚  โ€ข Create Stripe Checkout Session
   โ”‚  โ€ข Apply trial period (14 days)
   โ””โ”€ Response: { sessionId, url }

2. POST /webhook (Stripe Webhooks)
   โ”œโ”€ Events Handled:
   โ”‚  โ€ข checkout.session.completed
   โ”‚  โ€ข customer.subscription.updated
   โ”‚  โ€ข customer.subscription.deleted
   โ”‚  โ€ข invoice.payment_succeeded
   โ”‚  โ€ข invoice.payment_failed
   โ”œโ”€ Actions:
   โ”‚  โ€ข Update Firebase user plan
   โ”‚  โ€ข Send confirmation email (Resend)
   โ”‚  โ€ข Generate HTML invoice
   โ”‚  โ€ข Log analytics event
   โ””โ”€ Security: Signature verification (STRIPE_WEBHOOK_SECRET)

3. POST /create-free-customer
   โ”œโ”€ Body: { userId, email, plan }
   โ”œโ”€ Purpose: Create free access (FREEPRO/FREEPLATINUM codes)
   โ””โ”€ Response: { success, plan }

4. GET /verify-subscription?userId={uid}
   โ”œโ”€ Purpose: Verify active subscription status
   โ””โ”€ Response: { active, plan, trialEnd, status }

5. POST /cancel-subscription
   โ”œโ”€ Body: { userId, subscriptionId }
   โ”œโ”€ Process:
   โ”‚  โ€ข Cancel Stripe subscription
   โ”‚  โ€ข Update Firebase (plan: "basic")
   โ”‚  โ€ข Send cancellation email
   โ””โ”€ Response: { success, message }

๐Ÿ“ง EMAIL TEMPLATES (Resend Integration):
โ€ข Payment Confirmation (with HTML invoice attachment)
โ€ข Trial Activation (14-day countdown)
โ€ข Free Access Granted (lifetime confirmation)
โ€ข Subscription Cancelled (downgrade notification)
โ€ข Payment Failed (grace period warning)

Worker 4: Newsletter Automation

newsletter-automation.your-account.workers.dev
๐Ÿ“ฐ NEWSLETTER AUTOMATION
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Base URL: https://newsletter-automation.raphnardone.workers.dev
Purpose: Automated weekly newsletters based on market events

๐Ÿ”Œ ENDPOINTS:

1. POST /generate-newsletter
   โ”œโ”€ Body: { topics, period }
   โ”œโ”€ Process:
   โ”‚  โ€ข Fetch top market news (FinnHub API)
   โ”‚  โ€ข Analyze major political events (News API)
   โ”‚  โ€ข Generate AI summary (Gemini 2.5 Flash)
   โ”‚  โ€ข Create HTML email template
   โ””โ”€ Response: { html, subject, preview_text }

2. POST /send-newsletter
   โ”œโ”€ Body: { subject, html, subscribers }
   โ”œโ”€ Process:
   โ”‚  โ€ข Fetch subscribers from Firestore (/users with newsletter: true)
   โ”‚  โ€ข Batch send via Resend API (max 100 recipients/email)
   โ”‚  โ€ข Track opens/clicks (UTM parameters)
   โ”‚  โ€ข Log campaign analytics
   โ””โ”€ Response: { sent, failed, campaign_id }

3. GET /subscribers
   โ”œโ”€ Purpose: Get all newsletter subscribers
   โ””โ”€ Response: { count, subscribers: [...] }

4. POST /schedule-newsletter
   โ”œโ”€ Body: { cron, topics }
   โ”œโ”€ Purpose: Schedule recurring newsletters
   โ””โ”€ Response: { scheduled, next_send }

๐Ÿค– AI-POWERED CONTENT:
โ€ข Major market movements (S&P 500, Nasdaq, Dow Jones)
โ€ข Political events impacting markets (Fed decisions, elections, policy changes)
โ€ข Top stock gainers/losers (daily/weekly)
โ€ข Economic calendar highlights (CPI, NFP, GDP releases)
โ€ข Sector rotation analysis
โ€ข Expert commentary synthesis
10+
Cloudflare Workers
30+
API Endpoints
<50ms
Avg Response Time
99.9%
Worker Uptime

Calculations & Financial Algorithms

Advanced Financial Modeling

AlphaVault AI implements professional-grade financial algorithms including machine learning models, Monte Carlo simulations, portfolio optimization (Markowitz, Risk Parity), and 14 Wall Street technical indicators used by institutional investors.

1. Trend Prediction (Machine Learning)

Machine Learning Models (trend-prediction.js)
๐Ÿค– MACHINE LEARNING TREND PREDICTION
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

File: assets/js/trend-prediction.js (2,485 lines)
Purpose: Predict stock price movements using 5 ML models + ensemble

๐Ÿ“Š MODELS IMPLEMENTED:

1โƒฃ  LINEAR REGRESSION
    Formula: y = ฮฒโ‚€ + ฮฒโ‚xโ‚ + ฮฒโ‚‚xโ‚‚ + ... + ฮฒโ‚™xโ‚™
    Features: Price, Volume, MA20, MA50, RSI, MACD
    Training: Least squares optimization
    Prediction Horizon: 1-30 days
    Accuracy: ~65-70% (short-term)

2โƒฃ  RIDGE REGRESSION (L2 Regularization)
    Formula: y = ฮฒโ‚€ + ฮฃ(ฮฒแตขxแตข) + ฮปฮฃ(ฮฒแตขยฒ)
    Purpose: Prevent overfitting in volatile markets
    Lambda (ฮป): Auto-tuned via cross-validation
    Accuracy: ~68-73% (medium-term)

3โƒฃ  LASSO REGRESSION (L1 Regularization)
    Formula: y = ฮฒโ‚€ + ฮฃ(ฮฒแตขxแตข) + ฮปฮฃ|ฮฒแตข|
    Purpose: Feature selection (automatic)
    Best for: Identifying key market drivers
    Accuracy: ~66-71% (long-term)

4โƒฃ  RANDOM FOREST (Ensemble Decision Trees)
    Trees: 100 estimators
    Max Depth: 10 levels
    Features: Technical indicators + volume patterns
    Bootstrap Sampling: 80% of data per tree
    Accuracy: ~72-78% (all horizons)

5โƒฃ  LSTM (Long Short-Term Memory Neural Network)
    Architecture: 3 layers (128, 64, 32 neurons)
    Sequence Length: 60 days (lookback window)
    Activation: Tanh (hidden), Linear (output)
    Training: Adam optimizer, MSE loss
    Epochs: 100 (with early stopping)
    Accuracy: ~75-82% (best for time series)

๐ŸŽฏ ENSEMBLE PREDICTION:
    Final Prediction = Weighted Average of 5 models
    Weights: [0.15, 0.15, 0.15, 0.25, 0.30]
    (LSTM gets highest weight due to superior accuracy)

    Ensemble Accuracy: ~78-85% (production)

๐Ÿ“ˆ BACKTESTING ENGINE:
    โ€ข Walk-forward validation (rolling window)
    โ€ข Out-of-sample testing (20% holdout)
    โ€ข Performance metrics: MAE, RMSE, Rยฒ, Sharpe Ratio
    โ€ข Signal accuracy: Directional hit rate (up/down/neutral)

๐Ÿ’ก FEATURES USED (Total: 18):
    Price Features: Open, High, Low, Close, Volume
    Moving Averages: SMA 20/50/100/200, EMA 20/50
    Momentum: RSI (14), MACD (12,26,9), Stochastic (14,3,3)
    Volatility: Bollinger Bands (20,2), ATR (14)
    Trend: ADX (14), Parabolic SAR

2. Monte Carlo Simulation

Probabilistic Simulations (monte-carlo.js)
๐ŸŽฒ MONTE CARLO PORTFOLIO SIMULATION
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

File: assets/js/monte-carlo.js (2,086 lines)
Purpose: Probabilistic forecasting with 6 statistical models

๐Ÿ”ข MODELS IMPLEMENTED:

1โƒฃ  GEOMETRIC BROWNIAN MOTION (Normal Distribution)
    Formula: S(t) = Sโ‚€ ร— exp((ฮผ - ฯƒยฒ/2)t + ฯƒโˆšt ร— Z)
    Where:
    โ€ข S(t) = Stock price at time t
    โ€ข Sโ‚€ = Initial price
    โ€ข ฮผ = Expected return (drift)
    โ€ข ฯƒ = Volatility (standard deviation)
    โ€ข Z ~ N(0,1) = Random normal variable
    
    Use Case: Standard stock price simulation
    Assumptions: Log-normal returns, constant volatility

2โƒฃ  STUDENT-T DISTRIBUTION
    Formula: S(t) = Sโ‚€ ร— exp((ฮผ - ฯƒยฒ/2)t + ฯƒโˆšt ร— T)
    Where:
    โ€ข T ~ t(df) = Student-t random variable
    โ€ข df = Degrees of freedom (default: 5)
    
    Use Case: Fat-tailed distributions (market crashes)
    Advantage: Captures extreme events better than Normal

3โƒฃ  LOG-NORMAL DISTRIBUTION
    Formula: S(t) = Sโ‚€ ร— exp(ฮผt + ฯƒโˆšt ร— Z)
    Where:
    โ€ข Returns are log-normally distributed
    โ€ข Ensures positive prices (S > 0)
    
    Use Case: Long-term portfolio projections
    Advantage: No negative prices possible

4โƒฃ  JUMP DIFFUSION (Merton Model)
    Formula: S(t) = Sโ‚€ ร— exp((ฮผ - ฯƒยฒ/2)t + ฯƒโˆšt ร— Z + ฮฃ Jumps)
    Where:
    โ€ข Jumps ~ Poisson(ฮป) process
    โ€ข Jump size ~ N(ฮผโฑผ, ฯƒโฑผยฒ)
    โ€ข ฮป = Jump intensity (avg jumps/year)
    
    Use Case: Sudden market shocks (earnings, news)
    Parameters:
    โ€ข ฮป = 2 jumps/year
    โ€ข ฮผโฑผ = -0.05 (avg -5% jump)
    โ€ข ฯƒโฑผ = 0.10 (10% jump volatility)

5โƒฃ  REGIME SWITCHING (Markov Chain)
    States: Bull Market (ฮผโ‚, ฯƒโ‚) โ†” Bear Market (ฮผโ‚‚, ฯƒโ‚‚)
    Transition Matrix:
    P = | 0.90  0.10 |  (90% stay Bull, 10% switch to Bear)
        | 0.20  0.80 |  (20% switch to Bull, 80% stay Bear)
    
    Bull: ฮผ = 12%, ฯƒ = 15%
    Bear: ฮผ = -8%, ฯƒ = 25%
    
    Use Case: Economic cycles, recession modeling

6โƒฃ  GARCH (Generalized Autoregressive Conditional Heteroskedasticity)
    Volatility Equation: ฯƒโ‚œยฒ = ฯ‰ + ฮฑ ร— ฮตโ‚œโ‚‹โ‚ยฒ + ฮฒ ร— ฯƒโ‚œโ‚‹โ‚ยฒ
    Where:
    โ€ข ฯ‰ = Long-term variance baseline
    โ€ข ฮฑ = ARCH effect (reaction to shocks)
    โ€ข ฮฒ = GARCH effect (volatility persistence)
    โ€ข Constraint: ฮฑ + ฮฒ < 1 (stationarity)
    
    Use Case: Time-varying volatility (VIX-like behavior)
    Parameters: ฯ‰=0.000001, ฮฑ=0.15, ฮฒ=0.80

๐ŸŽฏ SIMULATION PARAMETERS:
    โ€ข Number of Simulations: 10,000 paths
    โ€ข Time Horizon: 1 day to 10 years
    โ€ข Time Steps: Daily granularity
    โ€ข Initial Capital: User-defined
    โ€ข Annual Return (ฮผ): Historical or user input
    โ€ข Volatility (ฯƒ): Historical std dev or implied vol

๐Ÿ“Š OUTPUT METRICS:
    โ€ข Percentile Distribution: 5%, 25%, 50%, 75%, 95%
    โ€ข Value at Risk (VaR): 95% confidence level
    โ€ข Conditional VaR (CVaR): Expected loss in worst 5%
    โ€ข Probability of Loss: P(Final Value < Initial)
    โ€ข Maximum Drawdown: Worst peak-to-trough decline
    โ€ข Sharpe Ratio: Risk-adjusted return

3. Portfolio Optimization

Markowitz & Risk Parity (portfolio-optimizer.js, risk-parity.js)
๐Ÿ“Š PORTFOLIO OPTIMIZATION ALGORITHMS
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

๐ŸŽฏ MARKOWITZ MEAN-VARIANCE OPTIMIZATION

Objective: Maximize Sharpe Ratio
Formula: SR = (E[Rโ‚š] - Rีข) / ฯƒโ‚š

Where:
โ€ข E[Rโ‚š] = Portfolio expected return = ฮฃ(wแตข ร— E[Rแตข])
โ€ข Rีข = Risk-free rate (default: 2%)
โ€ข ฯƒโ‚š = Portfolio volatility = โˆš(wแต€ ร— ฮฃ ร— w)
โ€ข w = Asset weights (wโ‚, wโ‚‚, ..., wโ‚™)
โ€ข ฮฃ = Covariance matrix

Constraints:
โ€ข ฮฃwแตข = 1 (fully invested)
โ€ข 0 โ‰ค wแตข โ‰ค 1 (long-only, no short selling)
โ€ข wแตข โ‰ฅ min_weight (optional: 5% minimum per asset)
โ€ข wแตข โ‰ค max_weight (optional: 40% maximum per asset)

Solver: Sequential Quadratic Programming (SQP)
Output: Optimal weights for Maximum Sharpe Ratio

โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

โš– RISK PARITY ALLOCATION

Objective: Equalize Risk Contribution
Formula: RCแตข = wแตข ร— (ฮฃw)แตข / ฯƒโ‚š = 1/N (for all assets)

Where:
โ€ข RCแตข = Risk contribution of asset i
โ€ข (ฮฃw)แตข = Marginal contribution to portfolio risk
โ€ข Target: RCแตข = RC_target = 1/N (equal risk)

Algorithm:
1. Calculate covariance matrix ฮฃ from historical returns
2. Initialize weights: wโ‚€ = (1/N, 1/N, ..., 1/N)
3. Iterate until convergence:
   a. Calculate portfolio volatility: ฯƒโ‚š = โˆš(wแต€ฮฃw)
   b. Calculate marginal risk: MRแตข = (ฮฃw)แตข / ฯƒโ‚š
   c. Calculate risk contributions: RCแตข = wแตข ร— MRแตข
   d. Adjust weights: w_new = w ร— (RC_target / RCแตข)^ฮป
   e. Normalize: w_new = w_new / ฮฃw_new
4. Repeat until |RCแตข - RC_target| < tolerance (ฮต = 0.0001)

Advantage: Better diversification in crisis periods
Use Case: Risk-balanced portfolios (60/40 alternative)

โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

๐Ÿ“ˆ EFFICIENT FRONTIER CONSTRUCTION

1. Minimum Variance Portfolio (leftmost point)
   Minimize: ฯƒโ‚š = โˆš(wแต€ฮฃw)
   Subject to: ฮฃwแตข = 1

2. Maximum Return Portfolio (rightmost point)
   Maximize: E[Rโ‚š] = ฮฃ(wแตข ร— E[Rแตข])
   Subject to: ฮฃwแตข = 1

3. Intermediate Portfolios (100 points on frontier)
   For target return r โˆˆ [min_return, max_return]:
   Minimize: ฯƒโ‚š
   Subject to: E[Rโ‚š] = r, ฮฃwแตข = 1

4. Capital Allocation Line (CAL)
   Tangent line from risk-free rate to efficient frontier
   Slope = Maximum Sharpe Ratio

Output: 100 portfolios (return, risk, weights) + CAL

4. Technical Indicators (14 Indicators)

Wall Street Indicators (advanced-analysis.js)
๐Ÿ“Š 14 WALL STREET TECHNICAL INDICATORS
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

1โƒฃ  RSI (Relative Strength Index)
    Period: 14
    Formula: RSI = 100 - (100 / (1 + RS))
    Where: RS = Average Gain / Average Loss
    Signals:
    โ€ข RSI > 70: Overbought (sell signal)
    โ€ข RSI < 30: Oversold (buy signal)
    โ€ข RSI = 50: Neutral

2โƒฃ  MACD (Moving Average Convergence Divergence)
    Fast EMA: 12 periods
    Slow EMA: 26 periods
    Signal Line: 9-period EMA of MACD
    Formula: MACD = EMA(12) - EMA(26)
    Histogram: MACD - Signal
    Signals:
    โ€ข MACD crosses above Signal: Bullish
    โ€ข MACD crosses below Signal: Bearish

3โƒฃ  BOLLINGER BANDS
    Period: 20
    Standard Deviations: 2
    Formula:
    โ€ข Middle Band = SMA(20)
    โ€ข Upper Band = SMA(20) + 2ร—ฯƒ
    โ€ข Lower Band = SMA(20) - 2ร—ฯƒ
    Signals:
    โ€ข Price touches upper band: Overbought
    โ€ข Price touches lower band: Oversold
    โ€ข Bollinger Squeeze: Low volatility (breakout imminent)

4โƒฃ  FIBONACCI RETRACEMENTS
    Levels: 0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%
    Extensions: 161.8%, 261.8%
    Formula: Level = High - (High - Low) ร— Fib_Ratio
    Use Case: Support/resistance levels

5โƒฃ  MOVING AVERAGES
    โ€ข SMA 20 (Short-term trend)
    โ€ข SMA 50 (Medium-term trend)
    โ€ข SMA 100 (Long-term trend)
    โ€ข SMA 200 (Major trend line)
    โ€ข EMA 20 (Faster response)
    โ€ข EMA 50 (Faster response)
    Signals:
    โ€ข Golden Cross: SMA(50) > SMA(200) โ†’ Bullish
    โ€ข Death Cross: SMA(50) < SMA(200) โ†’ Bearish

6โƒฃ  ICHIMOKU CLOUD
    Components:
    โ€ข Tenkan-sen (9): (Highโ‚‰ + Lowโ‚‰) / 2
    โ€ข Kijun-sen (26): (Highโ‚‚โ‚† + Lowโ‚‚โ‚†) / 2
    โ€ข Senkou A: (Tenkan + Kijun) / 2 (shifted 26 ahead)
    โ€ข Senkou B: (Highโ‚…โ‚‚ + Lowโ‚…โ‚‚) / 2 (shifted 26 ahead)
    โ€ข Chikou: Close (shifted 26 back)
    โ€ข Kumo (Cloud): Area between Senkou A & B
    Signals:
    โ€ข Price above cloud: Bullish
    โ€ข Price below cloud: Bearish

7โƒฃ  PIVOT POINTS (Standard, Fibonacci, Camarilla)
    Standard:
    โ€ข Pivot (P) = (High + Low + Close) / 3
    โ€ข R1 = 2P - Low, S1 = 2P - High
    โ€ข R2 = P + (High - Low), S2 = P - (High - Low)
    โ€ข R3 = High + 2(P - Low), S3 = Low - 2(High - P)
    
    Fibonacci:
    โ€ข R1 = P + 0.382(High - Low)
    โ€ข R2 = P + 0.618(High - Low)
    
    Camarilla:
    โ€ข R4 = Close + (High - Low) ร— 1.1/2
    โ€ข S4 = Close - (High - Low) ร— 1.1/2

8โƒฃ  ADX (Average Directional Index) + DMI
    Period: 14
    Components:
    โ€ข +DI (Positive Directional Indicator)
    โ€ข -DI (Negative Directional Indicator)
    โ€ข ADX (Trend Strength)
    Formula: ADX = SMA(14) of DX
    Where: DX = 100 ร— |+DI - -DI| / (+DI + -DI)
    Signals:
    โ€ข ADX > 25: Strong trend
    โ€ข ADX < 20: Weak trend (range-bound)
    โ€ข +DI > -DI: Uptrend
    โ€ข -DI > +DI: Downtrend

9โƒฃ  STOCHASTIC OSCILLATOR
    %K Period: 14
    %D Period: 3 (SMA of %K)
    Slow Period: 3
    Formula: %K = 100 ร— (Close - Lowโ‚โ‚„) / (Highโ‚โ‚„ - Lowโ‚โ‚„)
    Signals:
    โ€ข %K > 80: Overbought
    โ€ข %K < 20: Oversold
    โ€ข %K crosses above %D: Buy
    โ€ข %K crosses below %D: Sell

๐Ÿ”Ÿ  ATR (Average True Range)
    Period: 14
    Formula: ATR = SMA(14) of True Range
    Where: TR = max(High - Low, |High - Close_prev|, |Low - Close_prev|)
    Use: Volatility measurement (not directional)

1โƒฃ1โƒฃ  PARABOLIC SAR
    Acceleration Factor: 0.02 (increments by 0.02, max 0.20)
    Formula: SAR = SAR_prev + AF ร— (EP - SAR_prev)
    Where: EP = Extreme Point (highest high or lowest low)
    Signals:
    โ€ข SAR below price: Uptrend
    โ€ข SAR above price: Downtrend

1โƒฃ2โƒฃ  OBV (On-Balance Volume)
    Formula: OBV = OBV_prev + Volume (if Close > Close_prev)
             OBV = OBV_prev - Volume (if Close < Close_prev)
    Use: Volume-based momentum indicator

1โƒฃ3โƒฃ  SUPPORT & RESISTANCE LEVELS
    Algorithm:
    1. Identify local peaks (resistance)
    2. Identify local troughs (support)
    3. Cluster similar levels (ยฑ2% tolerance)
    4. Rank by touch count (more touches = stronger level)

1โƒฃ4โƒฃ  VOLUME ANALYSIS
    Metrics:
    โ€ข Volume MA(20): Average daily volume
    โ€ข Relative Volume: Current / MA(20)
    โ€ข Volume Breakout: Volume > 2ร— MA(20)
    Signals:
    โ€ข High volume + price up: Strong bullish
    โ€ข High volume + price down: Strong bearish
    โ€ข Low volume: Weak trend (reversal risk)
5
ML Models (Trend Prediction)
6
Monte Carlo Models
14
Technical Indicators
78-85%
ML Ensemble Accuracy

Architecture Code Extractor

Extract Your Complete Codebase

This tool automatically scans your GitHub repository and generates a comprehensive report including all HTML, CSS, and JavaScript files with detailed analysis of functions, scripts, integrations, and component counts. Perfect for documentation, audits, and architecture reviews.

Configuration

Cloudflare Workers Analyzer

Extract Workers Configuration & Source Code

This tool connects to your Cloudflare account via a temporary worker proxy and extracts all workers scripts, bindings, routes, KV namespaces, and complete source code with detailed analysis. โš  Delete the temporary worker immediately after extraction for security.

Worker Proxy Configuration

๐Ÿ“ Setup Instructions:
1. Deploy the temporary worker "workers-extractor-temp" on your Cloudflare account
2. Copy the worker URL (format: https://workers-extractor-temp.your-account.workers.dev)
3. Paste it below and click "Extract Workers Data"
4. Important: Delete the worker immediately after extraction for security