Skip to content

Latest commit

 

History

59 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PulseTrade — Full-Stack Paper-Trading Platform

Enterprise-grade full-stack paper-trading platform for simulated equity trading, real-time market data streaming, atomic financial ledgers, and portfolio management.


Tech Stack & Badges

License: ISC React 19 Vite Node.js Express 5 MongoDB Atlas Socket.io JWT HttpOnly Razorpay Sandbox Docker Compose GitHub Actions CI Jest & Supertest Swagger OpenAPI


Live Production Deployments

Component Production URL Description
Trading Terminal https://dashboard-lilac-nu-83.vercel.app React 19 / Vite SPA trading terminal for simulated portfolio management
Marketing Portal https://pulsetrade-ten.vercel.app Landing page, feature walkthroughs, and onboarding portal
Backend API https://pulsetrade-zygv.onrender.com Express 5 REST API & Socket.IO real-time price streaming engine
Swagger UI Docs https://pulsetrade-zygv.onrender.com/api-docs Interactive OpenAPI 3.0 API documentation & test runner
Health Diagnostics https://pulsetrade-zygv.onrender.com/health Live service status, database connectivity & memory metrics

Visual Showcase & Application Walkthrough

Explore the core user workflows, real-time trading interfaces, and financial management capabilities across the PulseTrade ecosystem:

1. Marketing & Onboarding Portal

The marketing landing page introduces PulseTrade's educational paper-trading simulator and portfolio analytics suite, offering seamless entry points to launch the trading terminal or authenticate into trader workspaces.

PulseTrade Marketing Landing Page

  • Modern Responsive Design: Built with React 19 and Vite with dark-mode aesthetic.
  • Direct Workspace Launch: Fast routing between the public marketing portal and the authenticated trading terminal SPA.
  • Zero-Risk Simulation: Clarifies educational sandbox scope for practicing equity trading.

2. Secure Trader Authentication (Sign In & Registration)

PulseTrade implements enterprise-grade authentication utilizing Bcrypt password hashing (Salt factor 12) and HttpOnly, SameSite, Secure JWT cookies, ensuring complete defense against client-side script token theft (XSS).

User Sign-In Portal

User Registration Portal

  • Anti-Enumeration Security: Returns unified "Incorrect email address or password" error messages to prevent username/email scraping.
  • Sliding-Window Rate Limiting: Dedicated auth rate limiter enforcing 10 requests per 15-minute window against brute-force attacks.
  • Automatic Identity Provisioning: New sign-ups automatically receive a unique exchange Client Code (e.g. PT-6A92C6) and initialize isolated ledgers.

3. Live Trading Terminal & Real-Time Market Streaming

The central command center provides real-time market data streaming, margin calculations, and instant portfolio telemetry.

PulseTrade Live Trading Terminal

  • Real-Time Index Ticker: Live streaming benchmark indices (NIFTY 50 at 24,716.34, SENSEX at 80,425.79) with live percentage movements.
  • 50-Stock Watchlist Stream: Paginated multi-stock watchlist streaming real-time micro-ticks via Socket.IO for top equities (INFY, ONGC, TCS, KPITTECH, QUICKHEAL, WIPRO, M&M, RELIANCE, HUL, HDFCBANK).
  • Live Margin Telemetry: Synchronous margin computation showing Available Margin (₹29,578.45), Margins Used (₹20,421.55), and Initial Opening Balance (₹50,000.00).
  • Holdings Telemetry Card: Live P&L performance overview (+₹7,147.74 / +35.00%), current asset valuation (₹27,569.29), and total invested capital (₹20,421.55).

4. Comprehensive Portfolio Holdings Ledger (12 Active Equities)

The holdings engine tracks multi-stock portfolios with automated weighted average purchase price recalculation and Mark-to-Market (MTM) P&L updates.

Portfolio Holdings Ledger

  • 12-Stock Portfolio Ledger: Granular records for BHARTIARTL, HDFCBANK, HINDUNILVR, INFY, ITC, KPITTECH, M&M, RELIANCE, SBIN, TATAPOWER, TCS, and WIPRO.
  • Weighted Average Cost Basis: Server-side arithmetic calculates exact weighted average purchase costs on every BUY fill.
  • Live Performance Badges: Color-coded badges for Day Change % and Net Change % alongside real-time LTP changes.
  • Aggregated Financial Telemetry: Total Investment: ₹20,421.55 | Current Value: ₹27,600.09 | Net P&L: +₹7,178.54 (+35.15%).

5. Open Positions & Intraday Trading

Dynamic monitoring of active open intraday trades and short-term delivery positions.

Open Positions

  • Real-Time Position Tracking: Dynamic view of active open positions (EVEREADY, JUBLFOOD) with quantity, average execution price, and live LTP.
  • Unrealized MTM Tracking: Live Mark-to-Market P&L calculations (-₹14.02, -₹27.32) synchronized with WebSocket price streams.
  • Product Type Isolation: Clean separation between long-term CNC delivery holdings and intraday positions.

6. Funds & Capital Management Hub

Centralized wallet and margin management interface with double-entry balance verification.

Funds and Capital Management

  • Capital Telemetry Cards: Instant visibility into Total Funds Added (₹50,000.00), Available Cash to Buy (₹29,578.45), Capital Spent on Stocks (₹20,421.55), Current Portfolio Valuation (₹27,642.73), and Net Gains (+₹7,221.18 / +35.36%).
  • Direct Capital Operations: Quick action triggers for simulated deposits and margin withdrawals.
  • Immutable Transaction Ledger: Comprehensive audit trail capturing deposits, withdrawals, order debits, and credits with pre-trade and post-trade balance snapshots.

7. Razorpay Sandbox Payment Gateway Checkout

Simulated instant funds deposit flow powered by the official Razorpay Sandbox payment gateway.

Razorpay Sandbox Checkout

  • Multi-Rail Sandbox Checkout: Embedded checkout modal supporting simulated Netbanking (SBI, HDFC, Bank of Baroda, Canara Bank, PNB, IDBI, Airtel Payments Bank), UPI, Cards, and Wallets.
  • Pre-Order Validation Guarantee: Verification requires a pre-created server PENDING order with matching amount and authorized userId.
  • HMAC-SHA256 Cryptographic Verification: Signature verification utilizing constant-time comparison (crypto.timingSafeEqual) to eliminate timing attacks.
  • Atomic Balance Settlement: Updates wallet margin balances and inserts immutable transaction records within single ACID database sessions.

8. User Profile & Exchange Trader Identity

Trader profile management with personalized client code assignment and security settings.

User Profile Details

  • Unique Client Code: Auto-generated exchange client identifier (e.g. PT-6A92C6) for individual trader identity.
  • Account Metadata Management: Displays display name, verified email (sekharsekhar1919@gmail.com), membership date, mobile phone, and trading bio.
  • Declarative Sanitization: Server-side validation and sanitization preventing injection attacks on profile mutations.

9. Account Analytics, Quick Actions & Multi-Device Session Invalidation

Account analytics overview with one-click navigation and multi-device session revocation.

Account Analytics & Quick Actions

  • Trader Activity Scorecard: Highlights Available Cash (₹29,578.45), Active Holdings count (12 stocks, valuation ₹27,611.45), Executed Orders count, and Total Outcome (+₹7,189.90).
  • Quick Action Hub: Direct one-click shortcuts to Deposit Funds, inspect Holdings (12), and review Orders.
  • Multi-Device Session Invalidation: Secure Sign Out leveraging tokenVersion increments in MongoDB to instantly revoke active JWT sessions across all browsers and devices.

Note

Product Disclaimer & Scope: PulseTrade is an educational paper-trading simulator and portfolio management application. It allows users to practice simulated equity delivery (CNC) trading and track virtual portfolios using market data feeds. It does not route live trades to real financial exchanges (such as NSE/BSE) and has no affiliation with Zerodha Broking Ltd. or any registered stock broker.


System Architecture

PulseTrade is designed with a decoupled multi-tier architecture ensuring fail-closed operations, financial consistency, and sub-millisecond local latency:

flowchart TB
    subgraph ClientLayer ["1. Client Presentation Layer"]
        FE["Marketing Portal<br/>(React 19, Vite)"]
        DASH["Trading Terminal SPA<br/>(React 19, Vite, Chart.js)"]
    end

    subgraph IngressLayer ["2. Ingress & Security Middleware"]
        CORS["CORS Allowlist & Security Headers<br/>(Helmet, Credentials)"]
        RL["Rate Limiters<br/>(Auth, Orders, Wallet, Global)"]
        LOG["Structured JSON Logger<br/>(X-Request-Id Correlation)"]
        VAL["Centralized Declarative Validator<br/>(Input Sanitization)"]
        AUTH["JWT HttpOnly Cookie Auth Middleware<br/>(Token Revocation & Verification)"]
    end

    subgraph ControllerLayer ["3. API Routing & Controllers"]
        AUTH_CTRL["AuthController<br/>(/api/v1/auth)"]
        ORDER_CTRL["OrderController<br/>(/api/v1/orders)"]
        HOLD_CTRL["HoldingController<br/>(/api/v1/holdings)"]
        WALL_CTRL["WalletController<br/>(/api/v1/wallet)"]
    end

    subgraph ServiceLayer ["4. Domain Services Layer"]
        AUTH_SVC["AuthService<br/>- Bcrypt Hashing (Salt 12)<br/>- Multi-Device Session Revocation"]
        ORDER_SVC["OrderService<br/>- Concurrency-Safe BUY / SELL<br/>- Weighted Cost-Basis Recalculation<br/>- Honest LIMIT / MARKET Execution"]
        HOLD_SVC["HoldingService<br/>- Portfolio Aggregation & Positions<br/>- Demo Data Seeding"]
        WALL_SVC["WalletService<br/>- Cash Margins & Net Worth<br/>- Immutable Audit Ledger<br/>- Razorpay Signature Verification"]
        TICKER_SVC["MarketTickerService<br/>- Real-Time Live Feed Polling<br/>- Micro-Tick Simulation Engine"]
    end

    subgraph TransactionLayer ["5. ACID Multi-Document Transaction Engine"]
        TX_MGR["Mongoose Client Sessions<br/>(startSession -> withTransaction -> commit/abort)"]
    end

    subgraph StorageLayer ["6. Storage & External Integrations"]
        MONGO[("MongoDB Atlas Replica Set<br/>(Users, Holdings, Positions, Orders, Transactions)")]
        SOCKET[["Socket.IO Engine<br/>(Real-Time Price Broadcasts)"]]
        RZP["Razorpay Sandbox Gateway<br/>(HMAC-SHA256 Verification)"]
        YAHOO["Market Data Feeds<br/>(NSE Live Feeds)"]
    end

    %% Client Traffic
    FE -->|REST API Requests| CORS
    DASH -->|Axios HTTP Requests| CORS
    DASH <-->|WebSocket Connection| SOCKET

    %% Middleware Pipeline
    CORS --> RL --> LOG --> VAL --> AUTH

    %% Routing
    AUTH --> AUTH_CTRL
    AUTH --> ORDER_CTRL
    AUTH --> HOLD_CTRL
    AUTH --> WALL_CTRL

    %% Service Delegation
    AUTH_CTRL --> AUTH_SVC
    ORDER_CTRL --> ORDER_SVC
    HOLD_CTRL --> HOLD_SVC
    WALL_CTRL --> WALL_SVC

    %% Persistence & Transactions
    ORDER_SVC --> TX_MGR
    WALL_SVC --> TX_MGR
    HOLD_SVC --> MONGO
    AUTH_SVC --> MONGO

    TX_MGR -->|Atomic Multi-Doc Session Operations| MONGO
    WALL_SVC -->|Payment Verification| RZP
    TICKER_SVC -->|Market LTP Polling| YAHOO
    TICKER_SVC -->|Broadcast Price Ticks| SOCKET
Loading

Quick Demo & Getting Started

Experience PulseTrade with instant registration and demo portfolio seeding:

1. Instant Demo Portfolio Seeding

  1. Register or Log in to the Trading Terminal (or http://localhost:5173 locally).
  2. Navigate to Holdings and click "Load Demo Portfolio".
  3. Instantly loads a ₹50,000 simulated balance and 12 active NSE equity holdings with real-time price tickers.

2. Simulated Razorpay Sandbox Deposit

  1. Go to the Funds tab and click "+ Add Funds".
  2. Enter any deposit amount (e.g. ₹10,000).
  3. In the Razorpay Checkout popup, select Netbanking (SBI / HDFC) or UPI to simulate verified deposits without real money.

Core Engineering & Business Logic Architecture

1. Fail-Closed ACID MongoDB Transactions

  • Multi-Document Session Transactions: BUY and SELL operations run in strict MongoDB session transactions (mongoose.startSession()), guaranteeing all-or-nothing consistency across UserModel (funds), HoldingModel (portfolio), OrderModel (audit trail), and TransactionModel (financial ledger).
  • Strict Fail-Closed Architecture: If a database session cannot be acquired or if any document write fails, operations fail closed immediately with zero silent downgrade to non-transactional execution.
  • BUY Validation: The backend independently validates available balance >= (qty * executedPrice). If insufficient, a REJECTED order is recorded in the audit trail without touching funds or holdings.
  • SELL Validation: The backend validates shares owned >= requested quantity. If unowned or oversold, a REJECTED order is recorded immediately.

2. Concurrency Safety & Multi-Document Atomicity

  • Prevents double-spending and overselling under concurrent requests (e.g. concurrent BUY orders or parallel withdrawals) via atomic conditional writes ({ _id: userId, funds: { $gte: totalCost } } and { userId, name, qty: { $gte: qty } }) executed within database transactions.

3. Server-Authoritative Market Pricing & Honest Limit Orders

  • Authoritative Market Pricing: Execution prices are strictly calculated server-side from live market feeds and predefined tradable instruments (TRADABLE_SYMBOLS), never trusting client-supplied execution prices.
  • Tradable Symbols Whitelist: Unregistered instruments or unsupported symbols are rejected immediately without fallback to client requested prices.
  • Price Model Fields: Distinguishes requestedPrice (client target price), marketPrice (server LTP), and executedPrice (actual simulated fill price).
  • Honest LIMIT Order Semantics:
    • MARKET: Fills immediately at current server market price.
    • LIMIT BUY: Only fills if serverMarketPrice <= requestedPrice; otherwise rejected with clear price feedback.
    • LIMIT SELL: Only fills if serverMarketPrice >= requestedPrice; otherwise rejected with clear price feedback.

4. Hardened Payment Gateway & Strict Pending Validation

  • Pre-Created Pending Order Guarantee: Payment verification strictly requires a pre-existing server-created record with status PENDING belonging to req.userId with exact matching amount and valid HMAC-SHA256 signature.
  • Production Fail-Closed Configuration: In production, missing RAZORPAY_KEY_ID or RAZORPAY_KEY_SECRET immediately fails closed with a 500 error rather than entering simulation mode.
  • Atomic Credit & Ledger: Wallet balance increments and ledger write occur within a single database transaction, preventing balance/ledger divergence.
  • Idempotency: Prevents double-crediting on network retries or replay attacks.

5. Multi-Device Session Invalidation & Rate Limiting Architecture

  • Token Versioning: UserModel maintains tokenVersion, embedded in signed JWT payloads.
  • Session Revocation: Calling POST /api/v1/auth/logout-all increments tokenVersion, instantly invalidating all existing JWT sessions across all devices.
  • Zero-Token Exposure: Strict HttpOnly: true cookies with zero JWT tokens exposed in JSON payloads.
  • Brute-Force & Flood Protection: Dedicated sliding-window rate limiters for auth (10 req / 15m), orders (30 req / 1m), wallet operations (15 req / 1m), and global API (300 req / 15m).
  • Generic Auth Errors: Both unknown users and bad passwords return "Incorrect email address or password" to prevent user enumeration.

6. Clean Architectural Separation

  • Strict separation of concerns across every domain: Route -> Middleware -> Controller -> Service -> Model
  • Controllers handle HTTP transport, while AuthService, OrderService, HoldingService, and WalletService encapsulate business logic.

7. Strict User Isolation & Access Control

  • All authenticated endpoints (/allOrders, /allHoldings, /allPositions, /user/funds, /user/transactions, /verify-razorpay-payment) are strictly scoped to the authenticated req.userId.
  • Rigorously verified through integration tests ensuring User A can never read or mutate User B's portfolio or order records.

8. Financial Arithmetic & Monetary Precision

  • Dedicated currency utility (util/currency.js) provides standard 2-decimal rounded currency arithmetic and integer-paise conversion functions.
  • All wallet balances, order costs, and ledger records maintain exact mathematical consistency without race conditions.

9. Real-Time Market Data & WebSocket Subscriptions

  • MarketTickerService streams live prices for 12 NSE stocks via Socket.IO.
  • Authenticated websocket handshake with user-specific notification rooms (user_${userId}).
  • Dynamic symbol subscription (subscribe / unsubscribe events) and resilient polling with synthetic micro-tick simulation outside market hours.

Database Entity-Relationship (ER) Diagram

erDiagram
    USER ||--o{ HOLDING : owns
    USER ||--o{ POSITION : maintains
    USER ||--o{ ORDER : executes
    USER ||--o{ TRANSACTION : records
    USER ||--o{ PAYMENT_RECORD : verifies

    USER {
        ObjectId _id PK
        string email UK "Unique, Indexed"
        string username
        string password "Bcrypt Hashed (Salt factor 12)"
        number funds "Trading Wallet Balance"
        number tokenVersion "Session Revocation Counter"
        string phone
        string bio
        date createdAt
    }

    HOLDING {
        ObjectId _id PK
        ObjectId userId FK "Compound Unique Index (userId + name)"
        string name "Stock Symbol"
        number qty "Quantity Owned"
        number avg "Weighted Average Purchase Cost Basis"
        number price "Live Market Price (LTP)"
        string net "Net Percentage Change"
        string day "Day Percentage Change"
        boolean isLoss
        date updatedAt
    }

    POSITION {
        ObjectId _id PK
        ObjectId userId FK "Indexed"
        string product "CNC"
        string name "Stock Symbol"
        number qty "Position Quantity"
        number avg "Cost Basis"
        number price "Live Market Price"
        string net
        string day
        boolean isLoss
    }

    ORDER {
        ObjectId _id PK
        ObjectId userId FK "Compound Indexes (userId + createdAt, userId + status)"
        string name "Stock Symbol"
        number qty "Order Quantity"
        number price "Execution Fill Price"
        number requestedPrice "Requested / Limit Price"
        number executedPrice "Simulated Fill Price"
        number marketPrice "Market LTP"
        string mode "BUY or SELL"
        string productType "CNC"
        string orderType "MARKET or LIMIT"
        string status "EXECUTED, FILLED, REJECTED, PENDING, CANCELLED"
        string failureReason "Error details if rejected"
        number totalCost "Total Cost Value"
        date createdAt "Indexed"
    }

    TRANSACTION {
        ObjectId _id PK
        ObjectId userId FK "Indexed"
        string type "DEPOSIT, WITHDRAWAL, ORDER_BUY, ORDER_SELL"
        number amount "Transaction Amount"
        number balanceBefore "Pre-trade Wallet Balance"
        number balanceAfter "Post-trade Wallet Balance"
        string status "SUCCESS, FAILED"
        string referenceId "Order/Payment Reference"
        string description "Audit log details"
        date createdAt "Indexed"
    }

    PAYMENT_RECORD {
        ObjectId _id PK
        ObjectId userId FK "Indexed"
        string razorpay_payment_id UK "Unique Idempotency Key"
        string razorpay_order_id "Razorpay Order ID"
        string razorpay_signature "HMAC-SHA256 Signature"
        number amount "Deposit Amount"
        string status "SUCCESS"
        date createdAt
    }
Loading

API Reference (/api/v1)

Access the interactive Swagger UI documentation at https://pulsetrade-zygv.onrender.com/api-docs (or http://localhost:3000/api-docs locally).

HTTP Method Endpoint Path Description Auth Required Rate Limited
GET /api/v1/health System diagnostics, uptime & DB ping latency No No
GET /api-docs Interactive OpenAPI 3.0 Swagger UI No No
POST /api/v1/auth/signup User account registration (sets HttpOnly cookie) No Yes (10 / 15m)
POST /api/v1/auth/login User login & HttpOnly session cookie issuance No Yes (10 / 15m)
POST /api/v1/auth/logout User logout & cookie clearance No No
POST /api/v1/auth/logout-all Revoke all active sessions across all devices Yes No
POST /api/v1/auth/updateProfile Update user profile bio & phone Yes No
GET /api/v1/orders/allOrders Retrieve user orders with pagination, filtering & sorting Yes No
POST /api/v1/orders/newOrders Submit transaction-safe BUY / SELL stock order Yes Yes (30 / 1m)
GET /api/v1/holdings/allHoldings Retrieve user stock holdings & cost basis Yes No
GET /api/v1/holdings/allPositions Retrieve user active positions Yes No
POST /api/v1/holdings/seedDemoData Seed ₹50,000 demo portfolio with 12 stocks (Dev only) Yes No
DELETE /api/v1/holdings/resetPortfolio Reset portfolio, orders & wallet to clean state (Dev only) Yes No
GET /api/v1/wallet/user/funds Fetch available cash margins & wallet balance Yes No
POST /api/v1/wallet/user/funds Deposit or withdraw funds from wallet Yes Yes (15 / 1m)
POST /api/v1/wallet/create-razorpay-order Create Razorpay Sandbox test order Yes Yes (15 / 1m)
POST /api/v1/wallet/verify-razorpay-payment Verify HMAC-SHA256 signature with idempotency Yes Yes (15 / 1m)
GET /api/v1/wallet/user/transactions Retrieve wallet audit transaction ledger Yes No

Test Coverage & Verification

PulseTrade features a dual-layer automated test suite (API integration + Service-level unit/transaction rollback tests) with Jest and Supertest running against MongoDB:

cd Backend
npm test

Automated Test Breakdown (13 Domain-Driven Test Suites)

Layer Test Suite File Critical Business Logic & Invariants Verified Status
API Integration Backend/tests/integration/health.api.test.js Health diagnostics (/health, /api/v1/health), MongoDB connectivity, memory telemetry, Swagger UI, X-Request-Id correlation tracking Passed
API Integration Backend/tests/integration/auth.api.test.js Signup validation, duplicate email rejection, HttpOnly cookies, zero-token JSON, generic 401 login errors, profile update, multi-device logout-all session revocation Passed
API Integration Backend/tests/integration/orders.api.test.js BUY/SELL validation, insufficient balance rejection, honest LIMIT orders, MARKET executions, weighted cost basis, pagination, sorting & user isolation Passed
API Integration Backend/tests/integration/holdings.api.test.js Portfolio holdings, intraday positions, user isolation, root backward-compatibility aliases Passed
API Integration Backend/tests/integration/wallet.api.test.js Deposit credit, available cash calculation, excessive withdrawal rejection, Razorpay order creation, HMAC signature checks, idempotent replay protection Passed
API Integration Backend/tests/integration/acid.rollback.test.js Simulated database crash failure-injection verifying 100% ACID transaction abort & zero financial ledger leaks Passed
Domain Services Backend/tests/services/auth.service.test.js Password hashing (Bcrypt Salt 12), email format regex, password strength guardrails, token version increments Passed
Domain Services Backend/tests/services/order.service.test.js Input guardrails, tradable symbol whitelist, CNC validation, market price comparisons, weighted average price recalculation, holding cleanup Passed
Domain Services Backend/tests/services/wallet.service.test.js Financial summary arithmetic (availableCash, spentOnHoldings, totalNetWorth), constant-time HMAC comparison (timingSafeEqual), cross-user order rejection Passed
Domain Services Backend/tests/services/holding.service.test.js Demo data seeding (12 stocks, 2 positions, ₹50,000 cash margin), portfolio reset cleanup Passed
Domain Services Backend/tests/services/ticker.service.test.js Socket.IO handshake auth, price cache snapshot, dynamic symbol subscription engine (subscribe/unsubscribe) Passed
Middlewares Backend/tests/middlewares/rateLimiter.test.js Sliding-window request tracking, 429 Too Many Requests enforcement, Retry-After headers, test mode bypass Passed
Middlewares Backend/tests/middlewares/authMiddleware.test.js Cookie vs Bearer extraction, signature verification, revoked tokenVersion blocking, user verification payload Passed

CI/CD Pipeline (GitHub Actions)

PulseTrade includes a continuous integration workflow (.github/workflows/ci.yml) executing on every push and pull request to main:

flowchart LR
    PUSH[Push / PR to main] --> BE[1. Backend Tests & DB Integration]
    PUSH --> DASH[2. Build Trading Dashboard SPA]
    PUSH --> FE[3. Build Marketing Portal SPA]

    subgraph BackendJob [Backend Test Job]
        MONGO_RUN["Start MongoDB 6.0 Replica Set (Docker)"]
        MONGO_INIT["Initiate Replica Set (rs0)"]
        BE_INSTALL["Install Dependencies (npm ci)"]
        BE_TEST["Run Test Suite (npm test)"]
        MONGO_RUN --> MONGO_INIT --> BE_INSTALL --> BE_TEST
    end

    subgraph DashboardJob [Dashboard Build Job]
        DASH_INSTALL["npm ci"] --> DASH_BUILD["npm run build (Vite)"]
    end

    subgraph FrontendJob [Frontend Build Job]
        FE_INSTALL["npm ci"] --> FE_BUILD["npm run build (Vite)"]
    end

    BE --> BackendJob
    DASH --> DashboardJob
    FE --> FrontendJob
Loading

Production Docker Deployment

PulseTrade includes a production-hardened multi-stage Docker containerization setup:

  • Backend: Lightweight Node 20 LTS runtime installing only production dependencies (npm ci --omit=dev), executing under a non-root user (USER node).
  • Dashboard & Frontend: Multi-stage builds compiling static production bundles via Vite (npm run build), served through high-performance nginx:alpine containers with SPA routing fallbacks, gzip compression, and caching headers.

Start with Docker Compose:

docker-compose up --build -d
  • Backend API: http://localhost:3000
  • Dashboard Terminal: http://localhost:5173
  • Marketing Frontend: http://localhost:5174

Local Development Setup

1. Prerequisites

  • Node.js (v20+ LTS)
  • Git
  • MongoDB Database: Either MongoDB Atlas (Recommended — Replica Sets are enabled by default) OR a Local MongoDB Replica Set (Required for multi-document ACID transactions).

Important

MongoDB Replica Set Requirement: PulseTrade uses MongoDB multi-document ACID transactions (session.startTransaction()) in OrderService and WalletService to guarantee strict balance and inventory consistency without race conditions.

Transactions require a Replica Set. If running MongoDB locally on a standalone instance (mongod), transactions will fail with Transaction numbers are only allowed on a replica set member or mongos.

Quick Local Replica Set Setup (Choose one):

  1. MongoDB Atlas (Easiest): Create a free tier M0 cluster on MongoDB Atlas — it runs as a 3-node replica set automatically.
  2. Docker One-Liner:
    docker run -d --name pulsetrade-mongo -p 27017:27017 mongo:7.0 --replSet rs0
    docker exec -it pulsetrade-mongo mongosh --eval "rs.initiate({_id:'rs0',members:[{_id:0,host:'localhost:27017'}]})"
    Connection URL: mongodb://localhost:27017/pulsetrade?replicaSet=rs0&directConnection=true
  3. Native Local mongod: Start mongod with --replSet rs0 and run rs.initiate() in mongosh.

2. Clone the Repository

git clone https://github.com/Sekhar01807/Trading-platform.git
cd Trading-platform

3. Configure Environment Variables

A. Backend (Backend/.env)

PORT=3000
NODE_ENV=development
# Atlas URI or Local Replica Set URI:
ATLASDB_URL=mongodb+srv://<user>:<password>@cluster.mongodb.net/pulsetrade
# Or Local: mongodb://localhost:27017/pulsetrade?replicaSet=rs0&directConnection=true
DB_NAME=pulsetrade
TOKEN_KEY=your_secure_jwt_secret_key_here
RAZORPAY_KEY_ID=rzp_test_your_key_id
RAZORPAY_KEY_SECRET=your_razorpay_secret
FRONTEND_URL=http://localhost:5174
DASHBOARD_URL=http://localhost:5173
ALLOWED_ORIGINS=http://localhost:5174,http://localhost:5173

B. Trading Dashboard (dashboard/.env)

VITE_API_URL=http://localhost:3000
VITE_LANDING_URL=http://localhost:5174

C. Marketing Portal (frontend/.env)

VITE_API_URL=http://localhost:3000
VITE_DASHBOARD_URL=http://localhost:5173

4. Run Services Locally

Start Backend API & WebSocket Server:

cd Backend
npm ci
npm run dev
  • API Health Check: http://localhost:3000/api/v1/health
  • Interactive Swagger UI: http://localhost:3000/api-docs

Start Dashboard Trading Terminal:

cd dashboard
npm ci
npm run dev
  • Accessible at http://localhost:5173

Start Marketing Portal:

cd frontend
npm ci
npm run dev
  • Accessible at http://localhost:5174

5. Run Test Suite

Run the full 13-suite automated test matrix across API integration, domain services, security middlewares, and ACID rollback tests:

cd Backend
npm test

See the Test Coverage & Verification section above for the full architectural breakdown of all 13 test suites.

6. Database Management & Seeding Utilities

PulseTrade includes dedicated scripts to reset, clean, and initialize a fresh database with pre-configured demo test accounts:

A. Clean & Reset Database:

Wipes all collections (users, holdings, positions, orders, transactions, payment_records), purges legacy orphan tables, and synchronizes all schema indexes:

cd Backend
npm run db:clean

B. Initialize Fresh Database with Demo Account:

Wipes existing records, synchronizes indexes, and provisions a verified demo user account with ₹50,000 margin balance and 12 NSE equity holdings:

cd Backend
npm run db:fresh

Default Demo Account Credentials:

  • Email: demo@pulsetrade.com
  • Password: DemoPassword123!
  • Initial Cash Margin: ₹50,000.00
  • Seeded Holdings: 12 active NSE equities (BHARTIARTL, HDFCBANK, HINDUNILVR, INFY, ITC, KPITTECH, M&M, RELIANCE, SBIN, TATAPOWER, TCS, WIPRO) + 2 intraday positions

License

This project is licensed under the ISC License.

About

Full-stack paper-trading platform with transactional order workflows, real-time market data, portfolios, payments, and automated testing.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages