TradePro Documentation

Explore the technical architecture and implementation details of a high-performance trading engine.

System Architecture

TradePro System Architecture

The system follows a microservices architecture with three core components communicating through Redis streams. Real-time price data flows from external exchanges through WebSocket connections, gets processed by the trading engine, and triggers automatic liquidations based on leverage and risk parameters.

Core Components & Implementation

Trading Engine

Order Processing Logic

The trading engine processes orders through Redis streams with real-time price validation:

• Validates user balance against required margin
• Calculates opening price based on bid/ask spread
• Deducts margin: (price × qty) / leverage
• Stores order in memory for real-time monitoring

Liquidation Mechanism

Automatic liquidation system runs on every price update:

• Take Profit: buy orders when price ≥ target
• Stop Loss: sell orders when price ≤ target
• Margin Call: when remaining margin ≤ 5% of initial
• PnL calculation: (closing - opening) × qty × side

Redis Stream Communication

engine-stream (Input)
price-update: Real-time price data
create-order: New order requests
close-order: Manual order closures
callback-queue (Output)
created: Order successfully created
closed: Order liquidated/closed
insufficient_balance: Margin not met

Price Poller & WebSocket Integration

WebSocket Connection

Connects to Backpack Exchange for real-time BTC_USDC price feeds:

const subscribeMessage = { method: "SUBSCRIBE", params: ["bookTicker.BTC_USDC"], id: 1 };

Streams bid/ask prices directly to the trading engine via Redis.

Price Processing

Every price update triggers immediate liquidation checks:

• Bid price: Used for sell order executions
• Ask price: Used for buy order executions
• Mid price: (bid + ask) / 2 for display
• Spread: Difference between bid and ask

Web Server & API Layer

Authentication & Middleware

JWT-based authentication with middleware protection:

• Token generation on login
• Middleware validates JWT on protected routes
• User context injection for order association
• Session management for persistent auth

Order Lifecycle Management

Complete order management with async communication:

• Creates order in pending state
• Sends to engine via Redis stream
• Waits for callback confirmation
• Updates database with final status

API Routes

Base URL: http://localhost:4000/api/v1

/auth

POST/auth/signup
GET/auth/signin/verify
Protected routes:
GET /auth/protected-route-test

/trade

POST/trade/create-order
POST/trade/close-order
GET/trade/get-open-orders
GET/trade/get-close-orders
All routes protected:
Requires authMiddleware

/balance

GET/balance/me
Protected route:
Returns user balance

Route Structure & File Organization

📁 Main Router
apps/api/src/routes/index.ts
• Mounts: /auth, /trade, /balance
📁 Auth Router
apps/api/src/routes/auth.routes.ts
• POST /signup → signupHandler
• GET /signin/verify → signInVerify
• GET /protected-route-test → authMiddleware
📁 Trade Router
apps/api/src/routes/trade.routes.ts
• POST /create-order → authMiddleware + createOrder
• POST /close-order → authMiddleware + closeOrder
• GET /get-open-orders → authMiddleware + fetchOpenOrders
• GET /get-close-orders → authMiddleware + fetchCloseOrders
📁 Balance Router
apps/api/src/routes/balance.route.ts
• GET /me → authMiddleware + getUserBalance
Middleware Chain:
authMiddleware → Controller → Response

Database Schema

PostgreSQL with Prisma ORM • Schema: packages/db/prisma/schema.prisma

model User

Prisma Schema Definition
idString@id@default(uuid())
emailString@unique
lastLoggedInDateTime
balanceInt
existingTradesExistingTrade[]

model ExistingTrade

Prisma Schema Definition
idString@id@default(uuid())
openPriceFloat
closePriceFloat
leverageFloat
pnlFloat
slippageFloat
quantityFloat
sideString
assetString
liquidatedBoolean
userIdString
reasonString?
createdAtDateTime@default(now())
userUser@relation(fields: [userId], references: [id])
DB

Database

Provider: PostgreSQL
Connection: env("DATABASE_URL")
P

ORM

Framework: Prisma
Client: @prisma/client
📁

Schema

Location:
packages/db/prisma/schema.prisma

Entity Relationship

User
id (PK)
email
balance
1
ExistingTrade
id (PK)
userId (FK)
openPrice
closePrice
pnl

Technical Deep Dive

Real-time Data Flow

Price Update Sequence

Backpack Exchange
WebSocket price feed
Price Poller
Parse & validate data
Redis Stream
Queue price updates
Trading Engine
Process liquidations

Order Creation Sequence

Web UI
User places order
API Server
Validate & auth
Redis Stream
Queue order request
Trading Engine
Process & execute
Callback
Confirm to API

Risk Management & Liquidation Engine

Margin Calculation

// Required margin calculation const requiredMargin = (openingPrice * qty) / leverage; // Remaining margin after PnL const currentPnl = side === 'buy' ? (currentPrice - openingPrice) * qty : (openingPrice - currentPrice) * qty; const remainingMargin = initialMargin + currentPnl;

Liquidation Triggers

Automatic Liquidation When:
• Remaining margin ≤ 5% of initial margin
• Take profit price is reached
• Stop loss price is triggered
• Manual closure by user

Performance & Scalability

In-Memory Processing

• Open orders stored in memory for instant access
• Price updates trigger immediate calculations
• Periodic database snapshots every 10 seconds
• Recovery from database on restart

Async Communication

• Redis streams for decoupled services
• Non-blocking order processing
• Promise-based callback system
• Timeout handling for failed operations

Error Handling

• Graceful WebSocket reconnection
• Database transaction rollbacks
• Redis connection recovery
• Comprehensive logging system

Docker Setup

Production Services

# docker-compose.deployment.yml services: api: build: ./docker/api.dockerfile ports: ["4000:4000"] environment: [DATABASE_URL, JWT_SECRET, ...] ws: build: ./docker/ws.dockerfile ports: ["8080:8080"] environment: [REDIS_URL, WS_PORT] engine: build: ./docker/engine.dockerfile environment: [DATABASE_URL, REDIS_URL] poller: build: ./docker/poller.dockerfile environment: [REDIS_URL] redis: image: redis ports: ["6379:6379"] healthcheck: redis-cli ping

Service Architecture

API Server (Port 4000)
• Express.js REST API with auth middleware
• Handles user auth, order creation, balance queries
• Routes: /auth, /trade, /balance
WebSocket Server (Port 8080)
• Real-time price feeds and order updates
• Connects to Redis streams for live data
Trading Engine
• Processes orders and liquidations
• Monitors price updates for risk management
Price Poller
• Fetches market data from exchanges
• Streams to Redis for engine consumption
Redis
• Message streams between services
• Health checks and persistent data

Ready to get started?

Set up your development environment and start building with MarketSim. Join the world of limitless trading opportunities.

Built by @jaspreetbawa_