https://github.com/lugondev/trade-perps-api
Multi-Exchange Perpetual Futures Trading Platform
https://github.com/lugondev/trade-perps-api
exchange-api exchange-server perps-dex perps-trading vibe-coding vibecoding
Last synced: 2 months ago
JSON representation
Multi-Exchange Perpetual Futures Trading Platform
- Host: GitHub
- URL: https://github.com/lugondev/trade-perps-api
- Owner: lugondev
- Created: 2025-11-02T15:11:09.000Z (5 months ago)
- Default Branch: main
- Last Pushed: 2025-11-02T15:14:09.000Z (5 months ago)
- Last Synced: 2025-11-02T17:20:44.088Z (5 months ago)
- Topics: exchange-api, exchange-server, perps-dex, perps-trading, vibe-coding, vibecoding
- Language: TypeScript
- Homepage:
- Size: 309 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Perps Vibe AI - Multi-Exchange Perpetual Futures Trading Platform
A sophisticated NestJS-based trading platform with **Unified API Architecture** supporting multiple perpetual futures exchanges including Aster DEX, Hyperliquid, Binance Futures, and OKX Perpetuals.
## ๐ฏ Architecture Highlights
- โ
**Unified API**: Single set of endpoints serving all exchanges
- โ
**Factory Pattern**: Dynamic service resolution at runtime via Exchange Factory
- โ
**Interface-Driven**: Clean separation between interfaces and implementations
- โ
**Type-Safe**: Full TypeScript with strict mode enabled
- โ
**Modular Design**: Each exchange is a self-contained module
- โ
**Plug & Play**: Add new exchanges by implementing standard interfaces
## ๐ข Supported Exchanges
- โ
**Aster DEX**: Decentralized perpetual futures (with WebSocket support)
- โ
**Hyperliquid**: On-chain perpetual futures (with WebSocket support)
- โ
**Binance Futures**: Centralized perpetual futures
- โ
**OKX Perpetuals**: Centralized perpetual futures
## ๐ก Core Features
- โ
**Trading Operations**: Market/limit orders, position management, leverage control
- โ
**Risk Management**: Stop-loss, take-profit, margin management
- โ
**Balance & Portfolio**: Real-time balance tracking, P&L calculation, portfolio value
- โ
**Market Data**: Real-time prices, orderbook depth, historical candles, funding rates
- โ
**Symbol Normalization**: Automatic symbol format conversion across exchanges
## ๐ง Technical Features
- โ
**REST API**: Comprehensive Swagger documentation at `/api`
- โ
**WebSocket Support**: Real-time market data and account updates
- โ
**Authentication**: API Key guard for secure access
- โ
**Error Handling**: Standardized error responses
- โ
**Clean Architecture**: Modular, testable, maintainable codebase
## ๐ฆ Quick Start
### 1. Installation
```bash
# Install dependencies
pnpm install
```
### 2. Configuration
Create a `.env` file in the root directory with your exchange API credentials:
```env
# Application Settings
NODE_ENV=development
PORT=3000
LOG_LEVEL=debug
# API Access Control (REQUIRED!)
# This key protects all endpoints
API_KEY_ACCESS=your_secure_api_key_here
# Aster DEX Configuration
ASTER_API_KEY=your_aster_api_key
ASTER_API_SECRET=your_aster_api_secret
ASTER_USER_ADDRESS=your_wallet_address
ASTER_SIGNER_ADDRESS=your_signer_address
ASTER_PRIVATE_KEY=your_private_key
ASTER_REST_URL=https://fapi.asterdex.com
ASTER_WS_URL=wss://fstream.asterdex.com
# Hyperliquid Configuration
HYPERLIQUID_REST_URL=https://api.hyperliquid.xyz
HYPERLIQUID_WS_URL=wss://api.hyperliquid.xyz/ws
HYPERLIQUID_WALLET_ADDRESS=your_wallet_address
HYPERLIQUID_PRIVATE_KEY=your_private_key
HYPERLIQUID_TESTNET=false
# Binance Futures Configuration (Optional)
BINANCE_API_KEY=your_binance_api_key
BINANCE_API_SECRET=your_binance_api_secret
BINANCE_REST_URL=https://fapi.binance.com
BINANCE_TESTNET=false
# OKX Perpetuals Configuration (Optional)
OKX_API_KEY=your_okx_api_key
OKX_API_SECRET=your_okx_api_secret
OKX_PASSPHRASE=your_okx_passphrase
OKX_REST_URL=https://www.okx.com
OKX_TESTNET=false
```
**Security Note:** The `API_KEY_ACCESS` is required in the `X-API-Key` header for all requests to protected endpoints.
### 3. Start the Application
```bash
# Development mode with hot reload
pnpm start:dev
# Production mode
pnpm build
pnpm start:prod
```
The application will be available at:
- **API**:
- **Swagger Documentation**:
## ๐ API Authentication
All trading endpoints require API key authentication using the `X-API-Key` header.
**Required Header:**
```http
X-API-Key: your_api_key_access_here
```
### Using Swagger UI
1. Open
2. Click the **"Authorize"** button (lock icon) at the top
3. Enter your `API_KEY_ACCESS` from `.env` file
4. Click **"Authorize"** and **"Close"**
5. Now you can test all endpoints directly in the browser
### Using curl
```bash
curl -H "X-API-Key: your_api_key_access_here" \
http://localhost:3000/balance?exchange=aster
```
## ๐ก Unified API Endpoints
All endpoints follow a unified pattern: `/{resource}?exchange={exchange_name}`
### Balance Endpoints
- `GET /balance?exchange={exchange}` - Get account balance and positions
- `GET /balance/portfolio?exchange={exchange}` - Get portfolio summary
- `GET /balance/positions?exchange={exchange}` - Get all open positions
- `GET /balance/position?exchange={exchange}&symbol={symbol}` - Get specific position
**Example:**
```bash
# Get Aster balance
curl -H "X-API-Key: your_key" \
"http://localhost:3000/balance?exchange=aster"
# Get Hyperliquid positions
curl -H "X-API-Key: your_key" \
"http://localhost:3000/balance/positions?exchange=hyperliquid"
```
### Market Data Endpoints
- `GET /market/symbols?exchange={exchange}` - Get all tradable symbols
- `GET /market/ticker?exchange={exchange}&symbol={symbol}` - Get 24hr ticker
- `GET /market/orderbook?exchange={exchange}&symbol={symbol}` - Get order book
- `GET /market/trades?exchange={exchange}&symbol={symbol}` - Get recent trades
- `GET /market/candles?exchange={exchange}&symbol={symbol}&interval={interval}` - Get klines/candles
- `GET /market/funding?exchange={exchange}&symbol={symbol}` - Get funding rate history
**Example:**
```bash
# Get BTC ticker from Binance
curl -H "X-API-Key: your_key" \
"http://localhost:3000/market/ticker?exchange=binance&symbol=BTC-USDT"
# Get ETH orderbook from Hyperliquid
curl -H "X-API-Key: your_key" \
"http://localhost:3000/market/orderbook?exchange=hyperliquid&symbol=ETH-USD"
```
### Trading Endpoints
- `POST /trading/order/market` - Place market order
- `POST /trading/order/limit` - Place limit order
- `POST /trading/order/cancel` - Cancel order
- `POST /trading/order/cancel-all` - Cancel all orders
- `GET /trading/orders?exchange={exchange}` - Get open orders
- `POST /trading/leverage` - Set leverage
- `POST /trading/position/close` - Close position
**Market Order Example:**
```bash
curl -X POST -H "X-API-Key: your_key" \
-H "Content-Type: application/json" \
"http://localhost:3000/trading/order/market" \
-d '{
"exchange": "aster",
"symbol": "BTC-USDT",
"side": "BUY",
"quantity": 0.001
}'
```
**Limit Order Example:**
```bash
curl -X POST -H "X-API-Key: your_key" \
-H "Content-Type: application/json" \
"http://localhost:3000/trading/order/limit" \
-d '{
"exchange": "hyperliquid",
"symbol": "ETH-USD",
"side": "SELL",
"quantity": 0.1,
"price": 3500
}'
```
**Close Position Example:**
```bash
curl -X POST -H "X-API-Key: your_key" \
-H "Content-Type: application/json" \
"http://localhost:3000/trading/position/close" \
-d '{
"exchange": "binance",
"symbol": "BTC-USDT"
}'
```
## ๐๏ธ Project Structure
```text
src/
โโโ api/ # Unified API Layer
โ โโโ controllers/ # REST API Controllers
โ โ โโโ balance.controller.ts # Balance & portfolio endpoints
โ โ โโโ market.controller.ts # Market data endpoints
โ โ โโโ trading.controller.ts # Trading endpoints
โ โโโ api.module.ts # API module configuration
โ
โโโ common/ # Shared Utilities
โ โโโ decorators/ # Custom decorators
โ โ โโโ api-key.decorator.ts # API key extraction
โ โ โโโ public.decorator.ts # Public endpoint marker
โ โโโ dto/ # Data Transfer Objects
โ โ โโโ exchange.dto.ts # Exchange selection DTOs
โ โ โโโ trading.dto.ts # Trading operation DTOs
โ โโโ factory/ # Factory Pattern
โ โ โโโ exchange.factory.ts # Dynamic service resolution
โ โโโ guards/ # Authentication Guards
โ โ โโโ api-key.guard.ts # API key validation
โ โโโ interfaces/ # Standard Interfaces
โ โ โโโ balance.interface.ts # Balance operations
โ โ โโโ market.interface.ts # Market data operations
โ โ โโโ trading.interface.ts # Trading operations
โ โโโ middleware/ # HTTP Middleware
โ โ โโโ symbol-normalizer.middleware.ts # Symbol format conversion
โ โโโ services/ # Common Services
โ โ โโโ symbol-normalizer.service.ts # Symbol normalization logic
โ โโโ types/ # Type Definitions
โ โโโ exchange.types.ts # Exchange enums and types
โ
โโโ exchanges/ # Exchange Integrations
โ โโโ aster/ # Aster DEX
โ โ โโโ perpetual/
โ โ โ โโโ services/
โ โ โ โ โโโ perpetual-balance.service.ts
โ โ โ โ โโโ perpetual-market.service.ts
โ โ โ โ โโโ perpetual-trading.service.ts
โ โ โ โโโ perpetual.module.ts
โ โ โโโ shared/
โ โ โ โโโ aster-api.service.ts # REST API client
โ โ โ โโโ aster-websocket.service.ts # WebSocket client
โ โ โโโ types/ # Type definitions
โ โ โโโ aster.module.ts
โ โ
โ โโโ hyperliquid/ # Hyperliquid
โ โ โโโ perp/
โ โ โ โโโ services/
โ โ โ โ โโโ balance.service.ts
โ โ โ โ โโโ market-data.service.ts
โ โ โ โ โโโ order-management.service.ts
โ โ โ โ โโโ order-placement.service.ts
โ โ โ โโโ perp.module.ts
โ โ โโโ shared/
โ โ โ โโโ hyperliquid-api.service.ts # REST API client
โ โ โ โโโ signing.service.ts # Signature generation
โ โ โโโ types/
โ โ โโโ hyperliquid.module.ts
โ โ
โ โโโ binance/ # Binance Futures
โ โ โโโ perpetual/
โ โ โ โโโ services/
โ โ โ โ โโโ perpetual-balance.service.ts
โ โ โ โ โโโ perpetual-market.service.ts
โ โ โ โ โโโ perpetual-trading.service.ts
โ โ โ โโโ perpetual.module.ts
โ โ โโโ shared/
โ โ โ โโโ binance-api.service.ts
โ โ โโโ types/
โ โ โโโ binance.module.ts
โ โ
โ โโโ okx/ # OKX Perpetuals
โ โ โโโ perpetual/
โ โ โ โโโ services/
โ โ โ โ โโโ perpetual-balance.service.ts
โ โ โ โ โโโ perpetual-market.service.ts
โ โ โ โ โโโ perpetual-trading.service.ts
โ โ โ โโโ perpetual.module.ts
โ โ โโโ shared/
โ โ โ โโโ okx-api.service.ts
โ โ โโโ types/
โ โ โโโ okx.module.ts
โ โ
โ โโโ exchanges.module.ts # Exchanges module aggregator
โ
โโโ config/ # Configuration Files
โ โโโ app.config.ts # App settings
โ โโโ aster.config.ts # Aster configuration
โ โโโ binance.config.ts # Binance configuration
โ โโโ hyperliquid.config.ts # Hyperliquid configuration
โ โโโ okx.config.ts # OKX configuration
โ โโโ trading.config.ts # Trading settings
โ
โโโ app.module.ts # Root module
โโโ main.ts # Application entry point
```
## ๐ Architecture Overview
### Unified API Pattern
Instead of separate endpoints per exchange, we use a unified pattern:
```text
Traditional Approach (Bad):
- /aster/balance
- /hyperliquid/balance
- /binance/balance
- /okx/balance
โ 4 exchanges ร 50 operations = 200 endpoints!
Unified Approach (Good):
- /balance?exchange=aster
- /balance?exchange=hyperliquid
- /balance?exchange=binance
- /balance?exchange=okx
โ 50 endpoints serving all exchanges
```
### Exchange Factory Pattern
The `ExchangeFactory` dynamically resolves the correct service based on the exchange parameter:
```typescript
// Client request
GET /balance?exchange=aster
// Factory resolves
ExchangeFactory โ AsterPerpetualBalanceService โ Execute
// Client request
GET /balance?exchange=hyperliquid
// Factory resolves
ExchangeFactory โ HyperliquidBalanceService โ Execute
```
### Interface-Driven Design
All exchange implementations follow standard interfaces:
- `IBalanceService`: Balance and portfolio operations
- `IMarketDataService`: Market data operations
- `ITradingService`: Trading operations
This ensures:
- **Consistency**: All exchanges work the same way
- **Testability**: Easy to mock and test
- **Maintainability**: Changes in one place affect all exchanges
- **Extensibility**: New exchanges just implement interfaces
### Symbol Normalization
Each exchange uses different symbol formats:
- Aster: `BTCUSDT`
- Hyperliquid: `BTC`
- Binance: `BTCUSDT`
- OKX: `BTC-USDT-SWAP`
The `SymbolNormalizerMiddleware` automatically converts symbols:
```text
Client โ "BTC-USDT" โ Middleware โ "BTCUSDT" (Aster)
Client โ "BTC-USDT" โ Middleware โ "BTC" (Hyperliquid)
Client โ "BTC-USDT" โ Middleware โ "BTC-USDT-SWAP" (OKX)
```
## โ๏ธ Configuration
### Environment Variables
| Variable | Description | Required | Default |
| ---------------- | ----------------------------------- | -------- | ------------- |
| `API_KEY_ACCESS` | API key for endpoint authentication | Yes | - |
| `PORT` | Application port | No | `3000` |
| `NODE_ENV` | Environment mode | No | `development` |
| `LOG_LEVEL` | Logging level | No | `debug` |
**Aster DEX:**
| Variable | Description | Required |
| ---------------------- | ---------------- | -------- |
| `ASTER_API_KEY` | Aster API key | Yes |
| `ASTER_API_SECRET` | Aster API secret | Yes |
| `ASTER_USER_ADDRESS` | Wallet address | Yes |
| `ASTER_SIGNER_ADDRESS` | Signer address | Yes |
| `ASTER_PRIVATE_KEY` | Private key | Yes |
| `ASTER_REST_URL` | REST API URL | No |
| `ASTER_WS_URL` | WebSocket URL | No |
**Hyperliquid:**
| Variable | Description | Required |
| ---------------------------- | -------------- | -------- |
| `HYPERLIQUID_WALLET_ADDRESS` | Wallet address | Yes |
| `HYPERLIQUID_PRIVATE_KEY` | Private key | Yes |
| `HYPERLIQUID_REST_URL` | REST API URL | No |
| `HYPERLIQUID_WS_URL` | WebSocket URL | No |
| `HYPERLIQUID_TESTNET` | Use testnet | No |
**Binance Futures:**
| Variable | Description | Required |
| -------------------- | ------------------ | -------- |
| `BINANCE_API_KEY` | Binance API key | Yes |
| `BINANCE_API_SECRET` | Binance API secret | Yes |
| `BINANCE_REST_URL` | REST API URL | No |
| `BINANCE_TESTNET` | Use testnet | No |
**OKX Perpetuals:**
| Variable | Description | Required |
| ---------------- | -------------- | -------- |
| `OKX_API_KEY` | OKX API key | Yes |
| `OKX_API_SECRET` | OKX API secret | Yes |
| `OKX_PASSPHRASE` | OKX passphrase | Yes |
| `OKX_REST_URL` | REST API URL | No |
| `OKX_TESTNET` | Use testnet | No |
## ๐งช Development
### Available Scripts
```bash
# Development
pnpm start:dev # Start with hot reload
pnpm build # Build for production
pnpm start:prod # Start production build
# Testing
pnpm test # Run unit tests
pnpm test:watch # Run tests in watch mode
pnpm test:cov # Generate coverage report
pnpm test:e2e # Run end-to-end tests
# Code Quality
pnpm lint # Run ESLint
pnpm format # Format code with Prettier
```
### Adding a New Exchange
To add support for a new exchange:
1. **Create exchange module structure:**
```bash
mkdir -p src/exchanges/newexchange/perpetual/services
mkdir -p src/exchanges/newexchange/shared
mkdir -p src/exchanges/newexchange/types
```
2. **Implement standard interfaces:**
Create services implementing:
- `IBalanceService` (balance operations)
- `IMarketDataService` (market data)
- `ITradingService` (trading operations)
3. **Create API service:**
Implement REST API client in `shared/newexchange-api.service.ts`
4. **Define types:**
Add exchange-specific types in `types/index.ts`
5. **Create configuration:**
Add config in `src/config/newexchange.config.ts`
6. **Register in factory:**
Add exchange to `ExchangeFactory` resolution logic
7. **Update exchange enum:**
Add to `ExchangeName` enum in `common/types/exchange.types.ts`
8. **Test thoroughly:**
Create unit tests for all services
## ๐ Security Features
- **Environment Variables**: Sensitive data stored securely in `.env`
- **API Key Authentication**: All endpoints protected with API key guard
- **HMAC Signatures**: Secure API authentication for supported exchanges
- **Input Validation**: Comprehensive validation using class-validator
- **Rate Limiting**: Built-in protection against API rate limits
- **Error Sanitization**: Sensitive information removed from logs
## ๐ Monitoring & Logging
The application uses structured logging with contextual information:
- **Error**: System errors and critical failures
- **Warn**: Non-critical issues and warnings
- **Info**: General application information
- **Debug**: Detailed debugging information (set `LOG_LEVEL=debug`)
Logs include request IDs, exchange names, and operation metadata for easy troubleshooting.
## ๐ Troubleshooting
### Common Issues
**Connection Failed:**
- Verify API credentials in `.env` file
- Check network connectivity
- Ensure exchange API is accessible
**Invalid Signature:**
- Verify API secret is correct
- Check system time synchronization
- Ensure timestamp is within acceptable range
**Rate Limited:**
- Reduce request frequency
- Implement exponential backoff
- Check exchange rate limit documentation
**Symbol Not Found:**
- Verify symbol format for the specific exchange
- Check if symbol is supported by the exchange
- Use `/market/symbols` endpoint to list available symbols
### Debug Mode
Enable detailed logging:
```bash
LOG_LEVEL=debug pnpm start:dev
```
## ๐ API Response Format
All API responses follow a standardized format:
**Success Response:**
```json
{
"success": true,
"data": {
// Response data here
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
**Error Response:**
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Error description",
"details": {}
},
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
## ๐ Deployment
### Docker Deployment
```bash
# Build image
docker build -t perps-vibe-ai .
# Run container
docker run -d \
--name perps-vibe-ai \
-p 3000:3000 \
--env-file .env \
perps-vibe-ai
```
### Cloud Run Deployment
```bash
# Deploy to Google Cloud Run
./scripts/deploy-cloudrun.sh
```
## ๐ Documentation
For detailed documentation, see the `.docs` folder:
- Architecture guides
- API authentication details
- Exchange-specific documentation
- Trading strategies
- WebSocket integration guides
## ๐ค Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Implement your changes
4. Add tests for new features
5. Submit a pull request
## ๐ License
MIT License - see LICENSE file for details.
## โ ๏ธ Disclaimer
**Important:** This is a trading platform that can place real orders and spend real money. Always:
- Test thoroughly in testnet/sandbox environments
- Start with small amounts
- Implement proper risk management
- Monitor positions actively
- Use at your own risk
The developers are not responsible for any financial losses incurred while using this platform.