Skip to content

Bhup-GitHUB/sebi-hackathon

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

29 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿš€ SEBI Hackathon - Smart Trading Platform

A modern, secure trading platform built with Hono.js and deployed on Cloudflare Workers for lightning-fast serverless performance. This platform provides comprehensive broker management, fraud detection, and real-time trading capabilities with full KYC compliance.

๐Ÿ“‹ Table of Contents

โœจ Features

  • ๐Ÿ” Secure Authentication - JWT-based login/signup with password hashing
  • ๐Ÿ“‹ KYC Management - Complete Know Your Customer verification system
  • ๐Ÿ’ฐ Balance Management - Real-time balance tracking with minimum balance alerts
  • ๐Ÿ“Š Trading Operations - Buy/sell stocks with real-time portfolio management
  • ๐Ÿšจ Smart Alerts - Low balance notifications and trading alerts
  • ๐Ÿ“ˆ Transaction History - Complete audit trail of all financial transactions
  • ๐Ÿ” Portfolio Tracking - Real-time stock holdings and performance metrics
  • ๐Ÿ›ก๏ธ Fraud Prevention - Built-in security measures and validation

๐Ÿ› ๏ธ Tech Stack

Backend

  • Hono.js - Ultra-fast web framework for edge computing
  • Cloudflare Workers - Serverless deployment platform
  • TypeScript - Type-safe development with full IntelliSense support
  • JWT - Secure token-based authentication

Database & Storage

  • Cloudflare D1 - Serverless SQL database with automatic scaling
  • SQLite - Lightweight, reliable database engine

Development Tools

  • Wrangler CLI - Cloudflare Workers development and deployment tool
  • ESBuild - Fast JavaScript bundler for production builds

๐Ÿ“ Project Structure

sebi-hackathon/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ routes/
โ”‚   โ”‚   โ”œโ”€โ”€ auth.ts          # Authentication endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ kyc.ts           # KYC management
โ”‚   โ”‚   โ”œโ”€โ”€ balance.ts       # Balance and transaction management
โ”‚   โ”‚   โ””โ”€โ”€ trading.ts       # Trading operations
โ”‚   โ””โ”€โ”€ index.ts             # Main application entry point
โ”œโ”€โ”€ schema.sql               # Database schema and initial data
โ”œโ”€โ”€ testcase.md              # Comprehensive API test cases
โ”œโ”€โ”€ wrangler.toml            # Cloudflare Workers configuration
โ”œโ”€โ”€ package.json             # Project dependencies and scripts
โ””โ”€โ”€ README.md               # Project documentation

๐Ÿš€ Quick Start

Prerequisites

  • Node.js 18+
  • npm or yarn
  • Cloudflare account with Workers enabled

Installation

  1. Clone the repository

    git clone https://github.com/Bhup-GitHUB/sebi-hackathon
    cd sebi-hackathon
  2. Install dependencies

    npm install
  3. Set up Cloudflare D1 Database

    # Create D1 database
    npx wrangler d1 create sebi-trading-db
    
    # Apply schema
    npx wrangler d1 execute sebi-trading-db --file=schema.sql
  4. Configure environment

    # Update wrangler.toml with your database ID
    # Add your JWT secret and other environment variables
  5. Run development server

    npm run dev
  6. Deploy to production

    npm run deploy

๐Ÿ“ก API Documentation

Base URL

https://sebi-hackathon.bkumar-be23.workers.dev/

Authentication Endpoints

User Registration

POST /auth/signup
Content-Type: application/json

{
  "username": "user123",
  "email": "[email protected]",
  "phone": "9876543210",
  "password": "SecurePass123!",
  "name": "John Doe"
}

User Login

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

{
  "username": "user123",
  "password": "SecurePass123!"
}

KYC Management

Register KYC

POST /kyc/register
Authorization: Bearer <token>
Content-Type: application/json

{
  "pan": "ABCDE1234F"
}

Validate KYC

POST /kyc/validate
Authorization: Bearer <token>
Content-Type: application/json

{
  "kycId": 1
}

Check KYC Status

GET /kyc/status
Authorization: Bearer <token>

Balance Management

Add Balance

POST /balance/add
Authorization: Bearer <token>
Content-Type: application/json

{
  "addBalance": 1000
}

Check Balance

GET /balance/check
Authorization: Bearer <token>

Check Low Balance Alert

GET /balance/check-low-balance
Authorization: Bearer <token>

Get Transaction History

GET /balance/transactions?limit=50&offset=0
Authorization: Bearer <token>

Trading Operations

Buy Stock

POST /trading/buy
Authorization: Bearer <token>
Content-Type: application/json

{
  "stockName": "RELIANCE",
  "price": 2450.50,
  "quantity": 10
}

Sell Stock

POST /trading/sell
Authorization: Bearer <token>
Content-Type: application/json

{
  "stockName": "RELIANCE",
  "price": 2500.00,
  "quantity": 5
}

Get Portfolio

GET /trading/portfolio
Authorization: Bearer <token>

๐Ÿงช Test Cases

Quick Test Flow

  1. Health Check

    curl -X GET https://sebi-hackathon.bkumar-be23.workers.dev/
  2. Register User

    curl -X POST https://sebi-hackathon.bkumar-be23.workers.dev/auth/signup \
      -H "Content-Type: application/json" \
      -d '{
        "username": "testuser1",
        "email": "[email protected]",
        "phone": "9876543210",
        "password": "TestPassword123!",
        "name": "Test User One"
      }'
  3. Login and Get Token

    curl -X POST https://sebi-hackathon.bkumar-be23.workers.dev/auth/login \
      -H "Content-Type: application/json" \
      -d '{
        "username": "testuser1",
        "password": "TestPassword123!"
      }'
  4. Register KYC

    curl -X POST https://sebi-hackathon.bkumar-be23.workers.dev/kyc/register \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
      -d '{
        "pan": "ABCDE1234F"
      }'
  5. Add Balance

    curl -X POST https://sebi-hackathon.bkumar-be23.workers.dev/balance/add \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
      -d '{
        "addBalance": 1000
      }'
  6. Buy Stock

    curl -X POST https://sebi-hackathon.bkumar-be23.workers.dev/trading/buy \
      -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
      -H "Content-Type: application/json" \
      -d '{
        "stockName": "RELIANCE",
        "price": 2450.50,
        "quantity": 10
      }'

Expected Responses

Successful Registration

{
  "success": true,
  "message": "User created successfully",
  "userId": 1
}

Successful Login

{
  "success": true,
  "message": "Login successful",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": 1,
    "username": "testuser1",
    "email": "[email protected]",
    "name": "Test User One"
  }
}

Successful Stock Purchase

{
  "success": true,
  "message": "Stock purchase successful",
  "order": {
    "orderId": 1,
    "stockName": "RELIANCE",
    "orderType": "buy",
    "quantity": 10,
    "price": 2450.50,
    "totalAmount": 24505.00,
    "status": "executed",
    "executedAt": "2025-08-30T20:30:15.456Z"
  },
  "balance": {
    "previousBalance": 50000,
    "amountSpent": 24505.00,
    "newBalance": 25495.00,
    "currency": "INR"
  },
  "portfolio": {
    "stockName": "RELIANCE",
    "quantity": 10,
    "averagePrice": 2450.50,
    "totalInvestment": 24505.00
  }
}

Error Handling

The API provides comprehensive error handling with detailed error messages:

Authentication Errors

{
  "success": false,
  "error": "Authorization header required"
}

Validation Errors

{
  "success": false,
  "error": "Valid balance amount is required (must be a positive number)"
}

Business Logic Errors

{
  "success": false,
  "error": "Insufficient balance for this purchase",
  "details": {
    "requiredAmount": 24505.00,
    "currentBalance": 1000,
    "shortfall": 23505.00
  }
}

For complete test cases, see testcase.md

๐Ÿ”’ Security Features

  • JWT Authentication - Secure token-based authentication with expiration
  • Password Hashing - Secure password storage using cryptographic hashing
  • Input Validation - Comprehensive validation for all API inputs
  • Rate Limiting - Built-in protection against API abuse
  • CORS Protection - Cross-origin request security
  • SQL Injection Prevention - Parameterized queries for database operations

๐Ÿ“Š Database Schema

The platform uses a well-structured SQLite database with the following tables:

Users Table

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    email TEXT UNIQUE NOT NULL,
    phone TEXT NOT NULL,
    password_hash TEXT NOT NULL,
    name TEXT NOT NULL,
    kyc_status TEXT DEFAULT 'not_registered',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

KYC Table

CREATE TABLE kyc (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    pan TEXT NOT NULL,
    status TEXT DEFAULT 'pending',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    validated_at DATETIME,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

Balance Table

CREATE TABLE balance (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    amount DECIMAL(15,2) DEFAULT 0.00,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

Balance Transactions Table

CREATE TABLE balance_transactions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    type TEXT NOT NULL, -- 'credit' or 'debit'
    amount DECIMAL(15,2) NOT NULL,
    description TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

๐Ÿš€ Deployment

Using Wrangler CLI

# Login to Cloudflare
npx wrangler login

# Deploy to production
npm run deploy

# Deploy to staging
npm run deploy:staging

Environment Configuration

Update your wrangler.toml with the following:

name = "sebi-hackathon"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[[d1_databases]]
binding = "sebi_trading_db"
database_name = "sebi-trading-db"
database_id = "your-database-id"

[vars]
JWT_SECRET = "your-jwt-secret-key"
MINIMUM_BALANCE = "1000"

Available Scripts

# Development
npm run dev              # Start development server

# Deployment
npm run deploy           # Deploy to production
npm run cf-typegen       # Generate TypeScript types

๐Ÿงช Testing

The platform includes comprehensive test cases covering:

  • โœ… User registration and authentication
  • โœ… KYC registration and validation
  • โœ… Balance management and transactions
  • โœ… Stock trading operations
  • โœ… Portfolio management
  • โœ… Error handling and edge cases

Run the test cases using the provided curl commands in the Test Cases section.

๐Ÿ“ˆ Performance

  • Ultra-fast Response Times - Cloudflare Workers edge computing
  • Global CDN - Worldwide content delivery
  • Auto-scaling - Handles traffic spikes automatically
  • 99.9% Uptime - Cloudflare's reliable infrastructure

๐Ÿ”ฎ Future Enhancements

  • Real-time stock price feeds
  • Advanced charting and technical analysis
  • Mobile app development
  • AI-powered trading recommendations
  • Multi-currency support
  • Advanced fraud detection algorithms

๐Ÿ“ž Support

For technical support or questions:

  • Create an issue on GitHub
  • Contact the development team
  • Check the testcase.md for detailed API documentation

๐Ÿ‘ฅ Team -> Yajat , Naman , Bhupesh , Simran , Akshat

https://github.com/YajatPahuja

About

Smart Trading Platform Backend Deployed -> https://sebi-hackathon.bkumar-be23.workers.dev/

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •