# jasonlinkai/trading-server architecture

> Architecture diagram of the GitHub repository jasonlinkai/trading-server, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-12). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/jasonlinkai/trading-server
- Repository: https://github.com/jasonlinkai/trading-server

## Overview

Step 1: Identify Project Type & Purpose
- This is a Node.js/Express-based, serverless trading microservice written in TypeScript.
- Deployed on Google Cloud Functions, it exposes HTTP API endpoints for placing orders and querying/closing positions on multiple exchanges (currently Binance and BitMEX).
- Core features: IP whitelist middleware, environment-variable configuration, a factory-based service layer to dispatch exchange-specific logic.

Step 2: Analyze File Structure & Architectural Patterns
##### Top-level
- Dockerfile, package.json, tsconfig.json, .env.example → build & runtime config
- request-*.json, server_log.txt → sample payloads & logs
##### src/
- constants/ & enums/ → shared values & env-mapping
- middleware/ipWhitelist.ts → Express middleware enforcing IP filtering
- routes/ (order.ts, position.ts) → HTTP route handlers (controllers)
- factories/TradingServiceFactory.ts → Factory pattern to instantiate the correct exchange service
- services/TradingService/… → Exchange-specific implementations (binance.ts, bitmex.ts) behind a common interface
- utils/ (logger.ts, formatting.ts) → cross-cutting concerns
##### Patterns
- Layered (Ingress → Middleware → Routing/Controllers → Service Factory → Service Implementation → External API)
- Factory pattern for pluggable exchange services
- Interface abstraction for service contracts

Step 3: Extract Key Insights from README
- Deployment target: Google Cloud Functions (stateless, event-driven)
- Endpoints:
POST /api/:exchange/order → place order
(similarly /position, /close-position)
- Uses .env for secrets/config

Step 4: Define Main Components & Their Relationships
##### Clients / Producers
- TradingView or any HTTP client → sends JSON payload to your API
##### API Gateway / HTTP Trigger
- Google Cloud Functions front-end
##### Express Application (inside Cloud Function)
a. Middleware Layer
– IP whitelist filter
b. Routing Layer
– order.ts → handles /api/:exchange/order
– position.ts → handles /api/:exchange/position
c. Controller / Handler
– Validate request, extract exchange, parameters
d. Factory Layer
– TradingServiceFactory → returns an instance of BinanceService or BitmexService depending on “exchange” path param
e. Service Layer
– Exchange-specific logic (REST calls to external exchange APIs, leverage, stop-loss, take-profit)
f. Utility Layer
– Logger → writes structured logs to Cloud Logging or local server_log.txt
– Formatting → request/response transformation
##### External Dependencies
- Exchange REST/WebSocket APIs (Binance, BitMEX)
- Google Cloud environment (Secret Manager for env vars, Cloud Logging)

– Ingress Zone (Clients → HTTP Trigger)
– Runtime Zone (GCF/Express) subdivided into:
- Middleware (IP Whitelist)
- Routing (Order, Position)
- Factory (TradingServiceFactory)
- Service Implementations (BinanceService, BitmexService)
- Utilities (Logger, Formatter)
– External Zone (Binance API, BitMEX API, Cloud Secret Manager, Cloud Logging)

– Trigger → Middleware → Route Handler → Factory → Service → External API
– External API → Service → Handler → Response → Client
– Handler/Service → Logger → Cloud Logging

c) Patterns
– Group “Factory + Service Implementations” and annotate “Factory Pattern”
– Show interface boundary between route handler and exchange service

d) Technologies
– Indicate “Google Cloud Functions” as hosting platform
– Mark “.env / Secret Manager” as config store

Step 6: Tailoring to This Project
- Clearly that there is no persistent in-process state—each request cold/warm starts the same Express app
- Pluggable service layer (easy to add new exchanges)

Step 7: Diagramming Guidelines

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Ingress Zone
    subgraph "Ingress Zone"
        direction TB
        Client["TradingView / HTTP Client"]:::ingress
        HTTPTrigger["Google Cloud Function\nHTTP Trigger"]:::ingress
    end

    %% Runtime Zone
    subgraph "Runtime Zone\nNode.js/Express/TypeScript"
        direction TB
        Entry["Express App Entry Point\n(src/index.ts)"]:::compute
        EnvConfig["Env Configuration\n(.env.example,\nsrc/constants/env.ts)"]:::config
        SharedConsts["Shared Constants\n(src/constants/index.ts)"]:::config
        Enums["Enumerations\n(src/enums/index.ts)"]:::config
        Middleware["IP Whitelist Middleware\n(src/middleware/ipWhitelist.ts)"]:::middleware
        RoutingOrder["Order Route Handler\n(src/routes/order.ts)"]:::routing
        RoutingPos["Position Route Handler\n(src/routes/position.ts)"]:::routing
        Factory["Trading Service Factory\n(src/factories/TradingServiceFactory.ts)"]:::factory
        ServiceIndex["Service Interface Aggregator\n(src/services/TradingService/index.ts)"]:::factory
        BinanceService["Binance Service Implementation\n(src/services/TradingService/binance.ts)"]:::service
        BitMEXService["BitMEX Service Implementation\n(src/services/TradingService/bitmex.ts)"]:::service
        UtilsLogger["Logger Utility\n(src/utils/logger.ts)"]:::utility
        UtilsFormat["Formatting Utility\n(src/utils/formatting.ts)"]:::utility
        BuildConfig["Build & Runtime Config\n(Dockerfile, package.json,\ntsconfig.json)"]:::config
    end

    %% External Zone
    subgraph "External Zone"
        direction TB
        BinanceAPI["Binance REST/WebSocket API"]:::external
        BitMEXAPI["BitMEX REST/WebSocket API"]:::external
        SecretManager["Google Secret Manager"]:::external
        CloudLogging["Google Cloud Logging"]:::external
    end

    %% Data Flow
    Client -->|HTTP POST JSON| HTTPTrigger
    HTTPTrigger -->|invokes| Entry
    Entry --> EnvConfig
    Entry --> SharedConsts
    Entry --> Enums
    Entry -->|uses middleware| Middleware
    Middleware -->|forwards to| RoutingOrder
    Middleware -->|forwards to| RoutingPos
    RoutingOrder -->|calls| Factory
    RoutingPos -->|calls| Factory
    Factory --> ServiceIndex
    ServiceIndex --> BinanceService
    ServiceIndex --> BitMEXService
    RoutingOrder -->|logs via| UtilsLogger
    RoutingPos -->|logs via| UtilsLogger
    RoutingOrder -->|formats via| UtilsFormat
    RoutingPos -->|formats via| UtilsFormat
    BinanceService -->|REST API| BinanceAPI
    BitMEXService -->|REST API| BitMEXAPI
    Entry -->|loads config| SecretManager
    UtilsLogger -->|sends logs| CloudLogging

    %% Click Events
    click Entry "https://github.com/jasonlinkai/trading-server/blob/main/src/index.ts"
    click EnvConfig "https://github.com/jasonlinkai/trading-server/blob/main/.env.example"
    click EnvConfig "https://github.com/jasonlinkai/trading-server/blob/main/src/constants/env.ts"
    click SharedConsts "https://github.com/jasonlinkai/trading-server/blob/main/src/constants/index.ts"
    click Enums "https://github.com/jasonlinkai/trading-server/blob/main/src/enums/index.ts"
    click Middleware "https://github.com/jasonlinkai/trading-server/blob/main/src/middleware/ipWhitelist.ts"
    click RoutingOrder "https://github.com/jasonlinkai/trading-server/blob/main/src/routes/order.ts"
    click RoutingPos "https://github.com/jasonlinkai/trading-server/blob/main/src/routes/position.ts"
    click Factory "https://github.com/jasonlinkai/trading-server/blob/main/src/factories/TradingServiceFactory.ts"
    click ServiceIndex "https://github.com/jasonlinkai/trading-server/blob/main/src/services/TradingService/index.ts"
    click BinanceService "https://github.com/jasonlinkai/trading-server/blob/main/src/services/TradingService/binance.ts"
    click BitMEXService "https://github.com/jasonlinkai/trading-server/blob/main/src/services/TradingService/bitmex.ts"
    click UtilsLogger "https://github.com/jasonlinkai/trading-server/blob/main/src/utils/logger.ts"
    click UtilsFormat "https://github.com/jasonlinkai/trading-server/blob/main/src/utils/formatting.ts"
    click BuildConfig "https://github.com/jasonlinkai/trading-server/tree/main/Dockerfile"
    click BuildConfig "https://github.com/jasonlinkai/trading-server/blob/main/package.json"
    click BuildConfig "https://github.com/jasonlinkai/trading-server/blob/main/tsconfig.json"

    %% Styles
    classDef ingress fill:#a2d2ff,stroke:#026aa7,color:#000
    classDef compute fill:#bde0fe,stroke:#0077b6,color:#000
    classDef config fill:#caf0f8,stroke:#0096c7,color:#000
    classDef middleware fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef routing fill:#dcedc8,stroke:#558b2f,color:#000
    classDef factory fill:#ffe0b2,stroke:#ef6c00,color:#000
    classDef service fill:#ffccbc,stroke:#d84315,color:#000
    classDef utility fill:#eeeeee,stroke:#757575,color:#000
    classDef external fill:#e1bee7,stroke:#6a1b9a,color:#000
```
