Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

npx tsc node dist/index.js

docker stop $(docker ps -aq) docker rm $(docker ps -aq)

docker run --name redis-server
-p 6379:6379
-d redis

docker run --name exchange-db
-e POSTGRES_USER=postgres
-e POSTGRES_PASSWORD=postgres
-e POSTGRES_DB=exchange
-p 5432:5432
-d postgres

in /api docker-compose -f prometheus-grafana.yml down docker-compose -f prometheus-grafana.yml up

Trading App with Order Management System

This is a comprehensive trading application that allows users to buy and sell assets with real-time price updates, margin monitoring, and automatic liquidation.

Features

πŸš€ Order Management

  • Buy/Sell Orders: Users can place BUY or SELL orders for any supported asset
  • Real-time Pricing: Live price updates via WebSocket connection
  • Order Tracking: View all open orders with current P&L calculations
  • Manual Closure: Close orders manually at any time

πŸ’° Account Management

  • User Authentication: Secure signup/login system with JWT tokens
  • Balance Tracking: Real-time account balance updates
  • Margin Requirements: 10% margin requirement for all positions
  • Automatic Liquidation: Orders are automatically closed when margin requirements are not met

πŸ“Š Real-time Data

  • Live Price Feeds: WebSocket connection to real-time trading data
  • Margin Monitoring: Continuous monitoring of position margins
  • Automatic Updates: Real-time order updates and balance changes

Architecture

Backend (API Server - Port 3003)

  • Express.js server with TypeScript
  • Prisma ORM with PostgreSQL database
  • Redis for pub/sub messaging
  • JWT authentication
  • Margin monitoring service for automatic liquidation

Frontend (Web App - Port 3000)

  • Next.js with TypeScript
  • Real-time WebSocket connections
  • Responsive trading interface with buy/sell forms
  • Order management dashboard

Real-time Services

  • WebSocket Server (Port 3002) for live price feeds
  • Redis Pub/Sub for margin monitoring and price updates

Database Schema

model User {
  id        String   @unique @default(uuid())
  name      String
  email     String   @unique
  password  String
  balance   Float    @default(5000)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  orders    Order[]
}

model Order {
  id           String      @unique @default(uuid())
  userId       String      @map("user_id")
  symbol       String
  side         OrderSide   // BUY or SELL
  quantity     Float
  entryPrice   Float       @map("entry_price")
  currentPrice Float       @map("current_price")
  status       OrderStatus @default(OPEN) // OPEN or CLOSED
  createdAt    DateTime    @default(now()) @map("created_at")
  closedAt     DateTime?   @map("closed_at")
  
  user User @relation(fields: [userId], references: [id])
}

enum OrderSide {
  BUY
  SELL
}

enum OrderStatus {
  OPEN
  CLOSED
}

API Endpoints

Authentication

  • POST /api/v1/user/signup - User registration
  • POST /api/v1/user/login - User login

Orders

  • POST /api/v1/orders - Create new order
  • GET /api/v1/orders - Get user's orders
  • PUT /api/v1/orders/:orderId/close - Close an order
  • GET /api/v1/orders/balance - Get user balance

Price Updates

  • POST /api/v1/price-update - Publish price update for margin monitoring

Getting Started

Prerequisites

  • Node.js 18+
  • PostgreSQL database
  • Redis server
  • WebSocket server running on port 3002

Installation

  1. Clone the repository

    git clone <repository-url>
    cd exness
  2. Install dependencies

    # API Server
    cd api
    npm install
    
    # Web App
    cd ../web
    npm install
  3. Environment Setup

    # In api/ directory
    cp .env.example .env
    # Update DATABASE_URL and REDIS_URL in .env
  4. Database Setup

    cd api
    npx prisma generate
    npx prisma db push
  5. Start Services

    # Terminal 1: Start API server
    cd api
    npm run dev
    
    # Terminal 2: Start WebSocket server
    cd realtime-ws
    npm run dev
    
    # Terminal 3: Start web app
    cd web
    npm run dev

Usage

1. User Registration/Login

  • Navigate to /signup to create an account
  • Use /signin to log in with existing credentials
  • Each user starts with $5,000 balance

2. Trading Interface

  • Select an asset from the dropdown (BTC, ETH, SOL)
  • Choose BUY or SELL side
  • Enter quantity
  • Review the total value and click to place order

3. Order Management

  • View all open orders in the trading interface
  • Monitor real-time P&L for each position
  • Close orders manually when desired
  • Automatic liquidation occurs when margin requirements are not met

4. Margin Monitoring

  • System continuously monitors all open positions
  • 10% margin requirement for all positions
  • Automatic liquidation when margin falls below requirement
  • Real-time balance updates

Margin Calculation

Margin Requirement = Position Value Γ— 10%
Available Margin = User Balance + Unrealized P&L

If Available Margin < Margin Requirement:
  β†’ Position is automatically liquidated

Security Features

  • JWT Authentication: Secure token-based authentication
  • Input Validation: Server-side validation of all inputs
  • Balance Checks: Prevents orders exceeding available balance
  • User Isolation: Users can only access their own orders and data

Real-time Features

  • Live Price Updates: WebSocket connection for real-time pricing
  • Margin Monitoring: Continuous monitoring via Redis pub/sub
  • Order Updates: Real-time order status and P&L updates
  • Balance Updates: Instant balance changes after trades

Error Handling

  • Insufficient Balance: Clear error messages for insufficient funds
  • Invalid Inputs: Validation errors for malformed requests
  • Network Issues: Graceful handling of connection problems
  • Database Errors: Proper error logging and user feedback

Monitoring and Logging

  • Margin Calls: Logged when positions approach liquidation
  • Order Lifecycle: Complete tracking of order creation, updates, and closure
  • User Activity: Authentication and trading activity logging
  • System Health: Connection status and service health monitoring

Future Enhancements

  • Advanced Order Types: Stop-loss, take-profit, limit orders
  • Portfolio Analytics: Performance metrics and risk analysis
  • Multi-asset Support: Support for more trading pairs
  • Advanced Risk Management: Configurable margin requirements
  • Mobile App: React Native mobile application
  • API Rate Limiting: Protection against abuse
  • Webhook Notifications: Real-time alerts for important events

Troubleshooting

Common Issues

  1. WebSocket Connection Failed

    • Ensure realtime-ws server is running on port 3002
    • Check firewall settings
  2. Database Connection Error

    • Verify PostgreSQL is running
    • Check DATABASE_URL in .env file
  3. Redis Connection Failed

    • Ensure Redis server is running
    • Check REDIS_URL in .env file
  4. Orders Not Creating

    • Verify user is authenticated
    • Check user balance
    • Ensure all required fields are provided

Debug Mode

Enable debug logging by setting environment variables:

DEBUG=* npm run dev

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

This project is licensed under the MIT License.

Support

For support and questions:

  • Create an issue in the repository
  • Check the troubleshooting section
  • Review the API documentation

Note: This is a demo application. For production use, implement additional security measures, proper error handling, and comprehensive testing.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages