npx tsc node dist/index.js
docker stop
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
This is a comprehensive trading application that allows users to buy and sell assets with real-time price updates, margin monitoring, and automatic liquidation.
- 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
- 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
- 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
- Express.js server with TypeScript
- Prisma ORM with PostgreSQL database
- Redis for pub/sub messaging
- JWT authentication
- Margin monitoring service for automatic liquidation
- Next.js with TypeScript
- Real-time WebSocket connections
- Responsive trading interface with buy/sell forms
- Order management dashboard
- WebSocket Server (Port 3002) for live price feeds
- Redis Pub/Sub for margin monitoring and price updates
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
}POST /api/v1/user/signup- User registrationPOST /api/v1/user/login- User login
POST /api/v1/orders- Create new orderGET /api/v1/orders- Get user's ordersPUT /api/v1/orders/:orderId/close- Close an orderGET /api/v1/orders/balance- Get user balance
POST /api/v1/price-update- Publish price update for margin monitoring
- Node.js 18+
- PostgreSQL database
- Redis server
- WebSocket server running on port 3002
-
Clone the repository
git clone <repository-url> cd exness
-
Install dependencies
# API Server cd api npm install # Web App cd ../web npm install
-
Environment Setup
# In api/ directory cp .env.example .env # Update DATABASE_URL and REDIS_URL in .env
-
Database Setup
cd api npx prisma generate npx prisma db push -
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
- Navigate to
/signupto create an account - Use
/signinto log in with existing credentials - Each user starts with $5,000 balance
- 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
- 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
- System continuously monitors all open positions
- 10% margin requirement for all positions
- Automatic liquidation when margin falls below requirement
- Real-time balance updates
Margin Requirement = Position Value Γ 10%
Available Margin = User Balance + Unrealized P&L
If Available Margin < Margin Requirement:
β Position is automatically liquidated
- 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
- 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
- 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
- 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
- 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
-
WebSocket Connection Failed
- Ensure realtime-ws server is running on port 3002
- Check firewall settings
-
Database Connection Error
- Verify PostgreSQL is running
- Check DATABASE_URL in .env file
-
Redis Connection Failed
- Ensure Redis server is running
- Check REDIS_URL in .env file
-
Orders Not Creating
- Verify user is authenticated
- Check user balance
- Ensure all required fields are provided
Enable debug logging by setting environment variables:
DEBUG=* npm run dev- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License.
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.