This is a backend service for stock trading operations built with NestJS, TypeScript, PostgreSQL, and Redis.
- List available stocks from vendor API with caching and pagination
- Get user portfolios with aggregated holding data
- Execute stock purchase transactions with price validation (±2%)
- Generate and send daily reports by email with transaction statistics
- Implements resilient external API communication
- Uses token-based to offset-based pagination translation
- Comprehensive error handling with standardized error codes
- Docker-based development and deployment environment
- Node.js v20 or higher
- Docker and Docker Compose
- (Optional) SMTP server or Mailgun account for email sending
- Clone the repository:
git clone https://github.com/yourusername/fuse-trading-backend.git
cd fuse-trading-backend- Create a
.envfile based on.env.example:
cp .env.example .env-
Update the environment variables in the
.envfile as needed. -
Start the development environment using one of the following options:
docker compose -f docker-compose.dev.yml up# Start development environment
npm run docker:dev
# Start development environment and rebuild containers
npm run docker:dev:build
# Stop development environment
npm run docker:dev:down
# Start production environment
npm run docker:prod
# Start production environment and rebuild containers
npm run docker:prod:build
# Stop production environment
npm run docker:prod:downThis project uses Mailhog for email testing in development environments. Important: Mailhog is designed for development purposes only and does not actually deliver emails to real recipients by default.
When running the application with Docker Compose:
- Report emails and other system emails are sent to Mailhog
- You can view all captured emails at http://localhost:8025
- From the web interface, you can inspect email content, headers, and attachments
- If needed, you can manually release emails for actual delivery through the Mailhog UI
To test the report generation:
- Use the report endpoints (
POST /reports/generateorGET /reports/generate-sync) - Check the Mailhog UI at http://localhost:8025 to see the generated report emails
- View the HTML content of the report by clicking on the email
In production environments, the application is configured to use Mailgun for reliable email delivery of reports and notifications. To enable Mailgun:
- Set
ENABLE_MAILGUN=truein your environment variables - Configure
MAILGUN_API_KEYandMAILGUN_DOMAINwith your Mailgun account credentials - Set appropriate
EMAIL_FROMandEMAIL_RECIPIENTSvalues for production use
If Mailgun is not enabled, the system will fall back to standard SMTP configuration.
This project includes services that may require architecture emulation:
-
ARM hosts (Apple Silicon M1/M2/M3): Docker Desktop on Mac should automatically handle emulation for any x86_64/amd64 images. You may see warnings about platform mismatches, but services should work properly.
-
x86/AMD64 hosts: If running on non-ARM platforms and encountering issues with ARM images, you might need to enable emulation:
# For Linux hosts docker run --privileged --rm tonistiigi/binfmt --install all # Then run docker-compose with: DOCKER_DEFAULT_PLATFORM=linux/amd64 docker compose -f docker-compose.dev.yml up
Note: The application will wait for the database and Redis to be healthy before starting. Health checks are configured to ensure all services are properly initialized.
Database Initialization: The PostgreSQL database is automatically initialized with the required schema when the container starts for the first time. The initialization script is located in
docker/init-scripts/init-db.sh.
The API will be available at http://localhost:3000/api
Swagger documentation at http://localhost:3000/api/docs
Email testing UI at http://localhost:8025 (MailHog)
- Install dependencies:
npm install-
Create and configure a
.envfile as described above. -
Make sure PostgreSQL and Redis are running and accessible with the credentials specified in your
.envfile. -
Start the development server:
npm run start:devThis project includes infrastructure configuration for deploying to AWS App Runner with RDS (PostgreSQL) and ElastiCache (Redis). The deployment is automated through GitHub Actions and Terraform.
- App Runner: Hosts the containerized application
- RDS: Provides PostgreSQL database
- ElastiCache: Provides Redis cache
- ECR: Stores Docker images
- GitHub Actions: Handles CI/CD pipeline
For detailed deployment instructions, see the Deployment Guide.
Quick start:
- Set up AWS credentials
- Configure GitHub repository secrets
- Apply Terraform configuration
- Push to main branch to trigger the CI/CD pipeline
To quickly populate a user's portfolio with test data, the project includes a seed script that automatically purchases random stocks:
# Make sure the application is running first
npm run seed-portfolioBy default, the script will:
- Use the user ID "user123"
- Attempt to purchase up to 20 different stocks
- Generate random quantities (1-10 shares per stock)
- Set purchase prices within the allowed ±2% range to ensure successful transactions
You can modify the script settings by editing scripts/seed-portfolio.ts:
USER_ID: Change the target userNUM_STOCKS_TO_BUY: Adjust the number of stocks to purchase
The script provides detailed logging of each purchase attempt, showing successes and failures, and will add the purchased stocks to the specified user's portfolio.
Interactive API documentation is available via Swagger UI at http://localhost:3000/api/docs when the application is running.
The following documentation is available in the docs directory:
- Architecture Report - Detailed explanation of system architecture and design decisions
- Implementation Roadmap - Step-by-step implementation plan
- Deployment Guide - Instructions for AWS App Runner deployment
For a high-level overview of the system architecture, please see the High Level Architecture document.
For detailed information about the implementation of each module, please see the Low Level Architecture document.
GET /api/stocks- List available stocks with pagination
GET /api/portfolio/:userId- Get user portfolio
POST /api/stocks/:symbol/buy- Execute stock purchase
POST /reports/generate- Trigger asynchronous generation of a daily report (optionaldaysquery param, default: 0 = today)GET /reports/generate-sync- Generate and send a daily report synchronously (optionaldaysquery param, default: 0 = today)
Note: In development, report emails are sent to Mailhog and can be viewed at http://localhost:8025. In production, reports are delivered via Mailgun to actual recipients when the
ENABLE_MAILGUNfeature flag is set totrue; otherwise, standard SMTP is used.
Run unit tests:
npm run testRun end-to-end tests:
npm run test:e2eSee .env.example for a complete list of environment variables.
src/stocks/- Stock listing and data fetchingsrc/portfolio/- User portfolio managementsrc/trades/- Trade executionsrc/reports/- Report generation and emailingsrc/common/- Shared utilities, filters, and interceptorssrc/config/- Configuration handlingterraform/- AWS infrastructure as code.github/workflows/- CI/CD pipeline configuration
ISC