A comprehensive, production-ready backend for a decentralized peer-to-peer trading platform. Built with NestJS, TypeScript, and PostgreSQL, featuring real-time WebSocket support, GraphQL API, intelligent caching, and advanced trading analytics.
- Overview
- Key Features
- Tech Stack
- Project Structure
- Prerequisites
- Installation & Setup
- Configuration
- Running the Application
- Testing
- Database Migrations
- API Documentation
- Deployment
- Monitoring & Troubleshooting
- Contributing
- License
SwapTrade Backend is the core engine of a modern trading platform that enables peer-to-peer asset swaps with insurance protection, real-time order matching, and comprehensive risk management. The system is designed for high performance, scalability, and reliability.
To provide a secure, efficient, and user-centric trading experience with built-in safeguards against liquidation cascades and market manipulation.
- Real-time order matching engine
- Support for multiple asset types (fiat, crypto, commodities)
- Leveraged trading with risk management
- Position tracking and portfolio analytics
- Historical trade analysis and reporting
- Multi-layered insurance fund for liquidation protection
- Automated cascade liquidation prevention
- Dynamic coverage decisions under market stress
- Real-time fund health monitoring
- Comprehensive audit trail for all transactions
- JWT-based authentication with refresh tokens
- Two-factor authentication (2FA) via OTP
- Role-based access control (RBAC)
- QR code generation for secure setup
- Rate limiting and DDoS protection
- Request throttling
- WebSocket support via Socket.IO for live updates
- GraphQL subscriptions for real-time data streaming
- Instant notifications for trade executions and alerts
- Event-driven architecture with Bull job queues
- Redis-based caching layer
- Intelligent cache invalidation
- Distributed caching for horizontal scaling
- Cache warming strategies
- TensorFlow integration for predictive analytics
- Trade statistics and performance metrics
- Risk analytics and volatility calculations
- User behavior analysis
- CSV/XLSX export capabilities
- Stellar network support for blockchain transactions
- USDC stablecoin integration
- On-chain settlement verification
- Ethereum compatibility (ERC-20 tokens)
- Email notifications via Nodemailer
- SMS alerts via Twilio
- i18n support for multi-language messages
- Configurable notification preferences
- Automatic database migrations with TypeORM
- Job queue management with Bull
- Event emission and handling
- Scheduled cron jobs for maintenance tasks
- Comprehensive logging and monitoring
| Category | Technology | Version |
|---|---|---|
| Framework | NestJS | ^11.0.1 |
| Language | TypeScript | ^5.7.3 |
| Database | PostgreSQL / SQLite | Latest |
| ORM | TypeORM | ^0.3.27 |
| API | GraphQL & REST | Apollo & Express |
| Real-time | WebSocket & Socket.IO | ^4.8.1 |
| Caching | Redis & IORedis | Latest |
| Job Queue | Bull | ^4.16.5 |
| Authentication | JWT & OTP | jsonwebtoken, otplib |
| Validation | Joi & Class Validator | ^17.13.3 |
| Testing | Jest | ^30.0.0 |
| Security | Helmet | ^7.0.0 |
| Analytics | TensorFlow.js | ^4.20.0 |
| Blockchain | Stellar SDK & Ethers | Latest |
| File Handling | XLSX & CSV Writer | Latest |
src/
βββ app.module.ts # Root application module
βββ main.ts # Application entry point
β
βββ auth/ # Authentication module
β βββ strategies/ # JWT, Local, etc.
β βββ guards/ # Auth guards
β βββ entities/ # Auth entities
β βββ services/ # Auth logic
β βββ controllers/ # Auth endpoints
β βββ auth.module.ts
β
βββ users/ # User management
β βββ entities/
β βββ services/
β βββ controllers/
β βββ dto/
β βββ users.module.ts
β
βββ trading/ # Core trading functionality
β βββ entities/ # Trade, Position, Order entities
β βββ services/ # Trading logic
β βββ controllers/ # Trading endpoints
β βββ dto/ # Data transfer objects
β βββ resolvers/ # GraphQL resolvers
β βββ trading.module.ts
β
βββ orders/ # Order management
β βββ entities/
β βββ services/
β βββ controllers/
β βββ orders.module.ts
β
βββ insurance/ # Insurance fund system
β βββ entities/
β βββ services/
β βββ controllers/
β βββ dto/
β βββ tests/
β βββ insurance.module.ts
β
βββ blockchain/ # Blockchain integration
β βββ services/ # Stellar, Ethereum services
β βββ entities/
β βββ blockchain.module.ts
β
βββ notifications/ # Email, SMS, Push notifications
β βββ services/
β βββ templates/
β βββ notifications.module.ts
β
βββ jobs/ # Background job definitions
β βββ services/
β βββ jobs.module.ts
β
βββ events/ # Event handling
β βββ listeners/
β βββ events.module.ts
β
βββ analytics/ # Analytics & reporting
β βββ services/
β βββ dto/
β βββ analytics.module.ts
β
βββ cache/ # Caching layer
β βββ services/
β βββ cache.module.ts
β
βββ common/ # Shared utilities
β βββ constants/
β βββ filters/
β βββ interceptors/
β βββ decorators/
β βββ exceptions/
β βββ guards/
β βββ pipes/
β βββ utils/
β
βββ database/ # Database configuration
β βββ migrations/
β βββ seeds/
β βββ data-source.ts
β
βββ config/ # Configuration management
β βββ env.validation.ts
β βββ config.service.ts
β βββ configuration.ts
β
βββ graphql/ # GraphQL setup
βββ schema.gql
βββ graphql.config.ts
test/ # E2E tests
βββ jest-e2e.json
βββ app.e2e-spec.ts
Before you begin, ensure you have the following installed:
- Node.js - v18.0.0 or higher
- npm - v9.0.0 or higher
- PostgreSQL - v12.0 or higher (for production)
- Redis - v6.0 or higher
- Git - for version control
- Docker & Docker Compose - for containerized development
- Stellar CLI - for blockchain testing
git clone https://github.com/StelTade/SwapTrade-Backend.git
cd SwapTrade-Backendnpm installdocker compose up -d redisRedis will be available at:
- Host:
localhost - Port:
6379
# macOS
brew install redis
# Linux
sudo apt-get install redis-server
# Start Redis
redis-serverSQLite database will be created automatically at first run.
# Create database
createdb swaptrade_db
# Set connection string in .env
DATABASE_URL=postgresql://user:password@localhost:5432/swaptrade_dbCreate a .env file in the root directory:
# Copy from template
cp .env.example .env# Application
NODE_ENV=development
PORT=3000
LOG_LEVEL=debug
# Database
DB_TYPE=postgres
DB_HOST=localhost
DB_PORT=5432
DB_NAME=swaptrade_db
DB_USERNAME=postgres
DB_PASSWORD=your_password
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# JWT
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRATION=3600
JWT_REFRESH_EXPIRATION=604800
# Blockchain
STELLAR_HORIZON_URL=https://horizon-testnet.stellar.org
STELLAR_USDC_ISSUER=GBDT5...
STELLAR_NETWORK_PASSPHRASE=Test SDF Network ; September 2015
# External Services
EXCHANGE_RATE_URL=https://api.exchangerate-api.com/v4/latest
TWILIO_ACCOUNT_SID=your_sid
TWILIO_AUTH_TOKEN=your_token
TWILIO_PHONE_NUMBER=+1234567890
# Email
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_app_password
# GraphQL
GRAPHQL_PLAYGROUND=true
GRAPHQL_INTROSPECTION=true
# Cache
CACHE_TTL=300
CACHE_ENABLED=true# Feature Flags
FEATURE_2FA_ENABLED=true
FEATURE_TRADING_ENABLED=true
FEATURE_INSURANCE_ENABLED=true
# Performance
CACHE_MAX_SIZE=1000
JOB_QUEUE_CONCURRENCY=5
DB_CONNECTION_POOL_SIZE=20
# Monitoring
SENTRY_DSN=https://your-sentry-dsn@sentry.io/project
DATADOG_API_KEY=your_datadog_keynpm run start:devApplication will start on http://localhost:3000
npm run start:watchnpm run start:debugDebugger will listen on port 9229
# Build
npm run build
# Start
npm run start:prodnpm run testnpm run test -- insurance-fund.service.spec
npm run test -- auth.service.specnpm run test:covGenerates coverage report in coverage/ directory
npm run test:e2enpm run test:watchnpm run test:security
npm run audit:depsnpm run migration:generate -- CreateUsersTablenpm run migration:runnpm run migration:revert- Swagger UI:
http://localhost:3000/api/docs - OpenAPI Spec:
http://localhost:3000/api/docs-json
- GraphQL Playground:
http://localhost:3000/graphql - GraphQL Endpoint:
POST http://localhost:3000/graphql
query GetTrades {
trades(limit: 10) {
id
symbol
price
volume
status
createdAt
}
}mutation CreateTrade {
createTrade(input: {
symbol: "BTC/USD"
quantity: 1.5
price: 45000
}) {
id
status
message
}
}const io = require('socket.io-client');
const socket = io('http://localhost:3000', {
auth: {
token: 'your-jwt-token'
}
});
socket.on('trade:created', (data) => {
console.log('New trade:', data);
});
socket.on('price:updated', (data) => {
console.log('Price update:', data);
});# Build image
docker build -t swaptrade-backend:latest .
# Run container
docker run -p 3000:3000 \
-e NODE_ENV=production \
-e DATABASE_URL=postgresql://... \
swaptrade-backend:latestdocker compose -f docker-compose.prod.yml up -dheroku login
heroku create swaptrade-backend
heroku config:set NODE_ENV=production
git push heroku mainSee DEPLOYMENT.md for detailed AWS setup instructions.
curl http://localhost:3000/healthExpected Response:
{
"status": "ok",
"timestamp": "2024-01-15T10:30:00Z",
"database": "connected",
"redis": "connected"
}Error: connect ECONNREFUSED 127.0.0.1:5432
Solution: Ensure PostgreSQL is running and DATABASE_URL is correct
Error: connect ECONNREFUSED 127.0.0.1:6379
Solution: Start Redis: redis-server or docker compose up -d redis
# Find process using port 3000
lsof -i :3000
# Kill process
kill -9 <PID># Increase Node.js heap size
node --max-old-space-size=4096 dist/main.jsLogs are configured with different levels:
- ERROR: Critical errors requiring immediate attention
- WARN: Warning messages for potential issues
- INFO: General application information
- DEBUG: Detailed debugging information
Change log level in .env:
LOG_LEVEL=debugWe welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow ESLint rules:
npm run lint - Format code:
npm run format - Write tests for new features
- Update documentation
| Command | Purpose |
|---|---|
npm run build |
Build TypeScript to JavaScript |
npm run start |
Start production server |
npm run start:dev |
Start development server with hot-reload |
npm run start:debug |
Start with debugger |
npm run start:prod |
Start production build |
npm run lint |
Run ESLint |
npm run format |
Format code with Prettier |
npm test |
Run unit tests |
npm run test:watch |
Run tests in watch mode |
npm run test:cov |
Run tests with coverage |
npm run test:e2e |
Run E2E tests |
npm run migration:generate |
Generate new migration |
npm run migration:run |
Run pending migrations |
npm run migration:revert |
Revert last migration |
npm run audit:deps |
Audit dependencies for vulnerabilities |
This project is licensed under the UNLICENSED license. See the LICENSE file for details.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: Full Docs
- Email: support@swaptrade.io
- β Core trading functionality
- β Insurance fund system
- β Real-time WebSocket updates
- β GraphQL API
- π² Mobile app integration
- π² Advanced order types
- π² Margin trading enhancements
- π² Cross-chain support
- π² AI-powered trading assistant
- π² Decentralized governance
- π² Multi-chain liquidity pools
- π² Advanced analytics dashboard
Made with β€οΈ by the SwapTrade Team
Last Updated: June 2024 | Version: 1.0.0