Skip to main content
NeuraTrade’s service architecture follows a domain-driven design with clear service boundaries and explicit communication contracts.

Service Overview

backend-api

Go 1.26+Core trading engine, API, domain logic, persistence, and AI orchestration

ccxt-service

Bun + CCXTExchange bridge for unified access to 100+ exchanges

telegram-service

Bun + grammYTelegram bot and notification delivery

backend-api (Go)

The primary runtime service containing all trading logic, arbitrage engines, AI agents, and API endpoints.

Structure

services/backend-api/
├── cmd/server/           # Process entrypoint + startup wiring
├── internal/api/         # Routes + HTTP handlers
├── internal/services/    # Trading, signal, collector, orchestration
├── internal/ai/          # LLM providers, registry, reasoning
├── internal/skill/       # Skill loader and prompt building
├── internal/database/    # DB connection + repositories
├── database/             # Migrations + migration tooling
└── scripts/              # Startup, health, env, webhook ops

Core Services

ServiceFileResponsibility
CollectorServicecollector_service.goMarket data ingestion from exchanges
SignalProcessorsignal_processor.goSignal pipeline coordination
ArbitrageServicearbitrage_service.goSpot arbitrage opportunity detection
FuturesArbitrageServicefutures_arbitrage_service.goFunding rate arbitrage engine
QuestEnginequest_engine.goAutonomous quest scheduling
AnalystAgentanalyst_agent.goMarket analysis AI agent
TraderAgenttrader_agent.goTrading decision AI agent
RiskManagerAgentrisk/risk_manager_agent.goRisk assessment AI agent
NotificationServicenotification.goTelegram notification dispatch
See services/backend-api/AGENTS.md for detailed service documentation.

Startup Flow

The backend wiring is explicit constructor injection in cmd/server/main.go:
// Simplified startup flow
func run() error {
    // 1. Load config
    cfg := config.Load()
    
    // 2. Initialize infrastructure
    db := database.Connect(cfg.DatabaseURL)
    redis := redis.NewClient(cfg.RedisURL)
    
    // 3. Initialize services (order matters!)
    ccxtClient := ccxt.NewClient(cfg.CCXTServiceURL)
    collector := services.NewCollectorService(db, ccxtClient, cfg, redis)
    signalProcessor := services.NewSignalProcessor(db, collector, ...)
    arbitrageService := services.NewArbitrageService(db, signalProcessor, ...)
    questEngine := services.NewQuestEngine(db, redis, ...)
    
    // 4. Initialize AI agents
    analystAgent := services.NewAnalystAgent(llmClient, ...)
    traderAgent := services.NewTraderAgent(llmClient, ...)
    riskManager := risk.NewRiskManagerAgent(llmClient, ...)
    
    // 5. Setup API routes
    router := api.SetupRoutes(arbitrageService, questEngine, ...)
    
    // 6. Start background services
    collector.Start()
    signalProcessor.Start()
    questEngine.Start()
    
    // 7. Start HTTP server
    return router.Run(":8080")
}
No DI Container: Services are explicitly wired in startup order, making the dependency graph visible and debuggable.

API Routes

Registered in internal/api/routes.go:
EndpointHandlerPurpose
GET /healthHealthHandlerService health check
GET /api/market/*MarketHandlerMarket data queries
GET /api/arbitrage/opportunitiesArbitrageHandlerSpot arbitrage opportunities
GET /api/futures/opportunitiesFuturesArbitrageHandlerFunding rate arbitrage
GET /api/analysis/signalsSignalHandlerTrading signals
POST /api/autonomous/beginAutonomousHandlerStart autonomous mode
POST /api/autonomous/pauseAutonomousHandlerPause autonomous mode
GET /api/questsQuestHandlerQuest status and progress
See API reference at /health for complete endpoint documentation.

ccxt-service (Bun)

Bun + TypeScript service providing a unified HTTP/gRPC interface to 100+ exchanges via the CCXT library.

Structure

services/ccxt-service/
├── index.ts              # Main entrypoint, HTTP + gRPC servers
├── grpc-server.ts        # gRPC service implementation
├── proto/                # Generated protobuf bindings
└── test-setup.ts         # Test mocks and setup

Responsibilities

Market Data

  • Ticker retrieval
  • Order book snapshots
  • Historical OHLCV data
  • Funding rate queries

Order Execution

  • Place orders (market, limit, stop)
  • Cancel orders
  • Query order status
  • Fetch balances and positions

HTTP Endpoints

// Admin endpoints (require ADMIN_API_KEY)
GET  /admin/health              // Service health
POST /admin/init-exchange       // Initialize exchange connection
GET  /admin/exchanges           // List configured exchanges

// Public endpoints
GET  /ticker/:exchange/:symbol  // Get ticker for symbol
POST /order/place               // Place order
POST /order/cancel              // Cancel order
GET  /balance/:exchange         // Get account balance

gRPC Interface

Defined in protos/ccxt_service.proto:
service CCXTService {
  rpc GetTicker(TickerRequest) returns (TickerResponse);
  rpc PlaceOrder(OrderRequest) returns (OrderResponse);
  rpc CancelOrder(CancelRequest) returns (CancelResponse);
  rpc GetBalance(BalanceRequest) returns (BalanceResponse);
}
Admin API Key: Production mode requires ADMIN_API_KEY env var. Admin endpoints are disabled if not set.

Configuration

# Required
ADMIN_API_KEY=your-secure-key

# Optional
PORT=3000
GRPC_PORT=50051
LOG_LEVEL=info

telegram-service (Bun)

Bun + TypeScript service using grammY framework for Telegram bot commands and notification delivery.

Structure

services/telegram-service/
├── index.ts              # Bot commands, webhook/polling, HTTP server
├── grpc-server.ts        # gRPC delivery interface
├── proto/                # Generated protobuf bindings
└── test-setup.ts         # Test mocks

Bot Commands

CommandDescription
/startInitialize bot and bind operator profile
/statusShow autonomous mode status and active quests
/beginStart autonomous trading mode
/pausePause autonomous trading mode
/balanceShow wallet balances
/positionsShow open positions
/performanceShow trading performance summary
/doctorRun diagnostic health checks
/liquidateLiquidate specific position
/liquidate_allEmergency liquidate all positions

Notification Types

The service delivers notifications for:
  • Quest Updates: Quest start, progress, completion
  • Trading Events: Order fills, position changes, PnL updates
  • Risk Alerts: Stop-loss triggers, drawdown warnings, emergency halts
  • System Events: Service starts, health degradation, errors

HTTP Endpoints

GET  /health                    // Service health
POST /admin/send                // Send admin message (requires ADMIN_API_KEY)
POST /webhook                   // Telegram webhook endpoint

gRPC Interface

service TelegramService {
  rpc SendMessage(MessageRequest) returns (MessageResponse);
  rpc SendNotification(NotificationRequest) returns (NotificationResponse);
  rpc HealthCheck(Empty) returns (HealthResponse);
}

Configuration

# Required
TELEGRAM_BOT_TOKEN=your-bot-token
ADMIN_API_KEY=your-secure-key

# Webhook mode
TELEGRAM_USE_POLLING=false
TELEGRAM_WEBHOOK_URL=https://your-domain.com
TELEGRAM_WEBHOOK_PATH=/webhook
TELEGRAM_WEBHOOK_SECRET=your-webhook-secret

# Backend integration
TELEGRAM_API_BASE_URL=http://localhost:8080
Use polling mode for local development and webhook mode for production deployments.

Service Communication

Communication Patterns

Protocol Selection

CommunicationProtocolReason
Backend → CCXTHTTP/RESTRequest-response pattern, retry logic
Backend → TelegramgRPCLow latency, streaming, type safety
Telegram → BackendHTTP/RESTSimple webhook integration
Services → RedisRedis ProtocolDistributed locks, PubSub

Health Checks

All services expose health check endpoints:

Backend API

curl http://localhost:8080/health
Returns:
{
  "status": "healthy",
  "services": {
    "database": "up",
    "redis": "up",
    "ccxt_service": "up",
    "telegram_service": "up"
  },
  "timestamp": "2026-03-03T08:00:00Z"
}

CCXT Service

curl http://localhost:3000/admin/health \
  -H "X-Admin-API-Key: your-key"

Telegram Service

curl http://localhost:3001/health
Health checks validate:
  • Service process is running
  • Database connectivity
  • Redis connectivity
  • Exchange API accessibility
  • Telegram API accessibility

Next Steps

Data Flow

See how data flows through services

Quest Engine

Autonomous scheduling architecture

Build docs developers (and LLMs) love