A blazing-fast, production-ready cryptocurrency exchange matching engine built in Go with real-time trade event streaming, persistent storage, and comprehensive risk management.
⚡ Features • 🚀 Quick Start • 📚 Documentation • 🧪 Testing
- Price-Time Priority Matching: Industry-standard FIFO algorithm for fair order execution
- Limit & Market Orders: Support for both order types with instant execution
- Real-time Matching: Sub-millisecond order processing latency
- Thread-Safe Order Book: Concurrent access with fine-grained locking
- REST API: Clean HTTP endpoints for order management
- WebSocket Feed: Live order book updates and trade notifications
- Web Dashboard: Built-in trading interface with real-time visualization
- NATS Streaming: Event-driven architecture for downstream consumers
- Redis Storage: Durable order book persistence with automatic recovery
- State Restoration: Automatic order book reconstruction on startup
- Atomic Operations: Consistent state management across all operations
- Position Limits: Configurable maximum position size per user
- Self-Trade Prevention: Blocks orders that would trade against user's own orders
- Price Collars: Rejects orders outside configured price bounds
- Pre-Trade Validation: Comprehensive order validation before acceptance
┌─────────────────────────────────────────────────────────────────┐
│ Cryptex Exchange │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ REST API │ │ WebSocket │ │ Dashboard │ │
│ │ (Gin) │ │ (Gorilla) │ │ (HTML/JS) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └───────────────────┼───────────────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ API Router │ │
│ │ (Order mgmt) │ │
│ └────────┬────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ Matching Engine │ │
│ │ (Price-Time) │ │
│ └────────┬────────┘ │
│ │ │
│ ┌───────────────────┼───────────────────┐ │
│ │ │ │ │
│ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ │
│ │ Order Book │ │Risk Checker │ │ NATS Pub. │ │
│ │ (Bids/Asks) │ │ (Limits) │ │ (Events) │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ ┌──────▼──────┐ ┌──────▼──────┐ │ │
│ │ Redis Store │ │ │ │ │
│ │ (Persistence│ │ │ │ │
│ └─────────────┘ │ │ │ │
│ │ │ │ │
└─────────────────────┴─────────────┴───────────────────┘ │
│
└─────────────────────────────────────────────────────────────────┘
- Go: 1.26 or higher
- Redis: 6.0+ (for persistence)
- NATS: 2.9+ (optional, for event streaming)
# Clone the repository
git clone https://github.com/jellyfishing2346/cryptex.git
cd cryptex
# Install dependencies
go mod download
# Build the binary
go build -o cryptex ./cmd/serverThe easiest way to get started:
# Start Redis and NATS
docker-compose -f docker/docker-compose.yml up -d
# Run the server
docker-compose up# Start Redis
redis-server
# Start NATS (optional)
nats-server -js
# Configure environment
export TRADING_PAIR="BTC-USD"
export REDIS_ADDR="localhost:6379"
export NATS_URL="nats://localhost:4222" # Optional
export PORT="8080"
# Run the server
./cryptexOpen your browser to: http://localhost:8080
| Variable | Description | Default |
|---|---|---|
TRADING_PAIR |
Trading pair to match | BTC-USD |
REDIS_ADDR |
Redis server address | localhost:6379 |
REDIS_PASSWORD |
Redis password (optional) | - |
REDIS_DB |
Redis database number | 0 |
NATS_URL |
NATS server URL (optional) | - |
PORT |
HTTP server port | 8080 |
MAX_POSITION_SIZE |
Max position per user | 1000.0 |
MIN_PRICE |
Minimum allowed price | 0.01 |
MAX_PRICE |
Maximum allowed price | 1000000.0 |
POST /orders
Content-Type: application/json
{
"trading_pair": "BTC-USD",
"side": "buy",
"type": "limit",
"price": 50000.0,
"quantity": 1.5,
"user_id": "uuid-here"
}DELETE /orders/:idGET /orderbook?depth=10GET /healthzWS /wsWhen NATS_URL is configured, Cryptex publishes trade events to NATS subjects:
trades.<trading_pair>- Raw trade datatrade-events.<trading_pair>- Structured trade events with metadataorders.<trading_pair>- Order lifecycle events
{
"trade": {
"id": "uuid",
"trading_pair": "BTC-USD",
"buy_order_id": "uuid",
"sell_order_id": "uuid",
"price": 50000.0,
"quantity": 1.5,
"executed_at": "2024-06-22T20:00:00Z"
},
"timestamp": "2024-06-22T20:00:00Z",
"event_type": "trade.executed"
}nc, _ := nats.Connect("nats://localhost:4222")
sub, _ := nc.Subscribe("trades.BTC-USD", func(msg *nats.Msg) {
var trade models.Trade
json.Unmarshal(msg.Data, &trade)
// Process trade
})go test ./...go test -cover ./...go test ./internal/matching/...
go test ./internal/orderbook/...
go test ./internal/risk/...go test -bench=. ./internal/orderbook/cryptex/
├── cmd/server/ # Main application entry point
├── internal/
│ ├── api/ # HTTP handlers and routing
│ ├── matching/ # Order matching engine
│ ├── models/ # Data models (Order, Trade, etc.)
│ ├── nats/ # NATS publisher for trade events
│ ├── orderbook/ # Order book data structure
│ ├── persistence/ # Redis storage layer
│ ├── risk/ # Risk management checks
│ └── ws/ # WebSocket real-time feed
├── web/ # Web dashboard
├── docker/ # Docker Compose configuration
├── docs/ # Documentation
└── deploy/ # Kubernetes deployment files
- 📖 Documentation Index - Complete documentation overview and navigation
- 🚀 Quick Start Guide - Get up and running in 5 minutes
- 🏗️ Architecture Documentation - Deep dive into system design and components
- 📡 API Documentation - Complete API reference with examples
- 🛠️ Development Guide - Development setup and contribution guidelines
- 🚀 Deployment Guide - Production deployment instructions
We follow standard Go conventions:
- Effective Go guidelines
- Standard project layout
- Comprehensive testing
- Clear documentation
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
# Build for Linux
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o cryptex ./cmd/server
# Build Docker image
docker build -t cryptex:latest .- Week 1: ✅ Order book data structure
- Week 2: ✅ Matching engine with price-time priority
- Week 3: ✅ REST API for order management
- Week 4: ✅ Redis persistence
- Week 5: ✅ WebSocket real-time feed
- Week 6: ✅ NATS trade event streaming
- Week 7: ✅ Risk management system
- Week 8: ✅ Web dashboard
Contributions are welcome! Please read our development guide first.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with Gin web framework
- Powered by Redis for persistence
- Event streaming with NATS
- WebSocket support via Gorilla WebSocket
Built with ❤️ for the crypto community