Skip to main content

System Architecture

SmallCapTrader follows Clean Architecture with Domain-Driven Design and supports dual-mode deployment — monolithic for development and sharded microservices for production.

Monolithic Mode

All services run in a single Python process. Simple deployment, minimal inter-component latency.

ComponentResponsibility
MarketDataServiceWebSocket stream parsing (Alpaca/IB)
Strategy EngineMultiple trading strategies evaluating signals
Position MonitorStop-loss, trailing stops, profit targets
Signal ArbiterPriority-based conflict resolution across strategies
Notification ServiceTelegram alerts for trades and system events
SchedulerMarket cap updates, maintenance tasks

Sharded Mode

Horizontally scalable architecture. Symbol-range partitioning via Redis pub/sub.

Processes:

ProcessCountResponsibility
sct-stream-router1Parses market data WebSocket, routes by symbol range to Redis channels
sct-shard-workerNRuns all strategies for assigned symbol range
sct-tick-recorder1Writes all ticks to QuestDB for backtesting replay
sct-backtest-workerNDistributed backtest and rule mining execution
sct-worker1Signal consumer + trade execution + position monitoring

Data Flow

Market Data WebSocket


Stream Router ─── parses trades/bars

    ├──► Redis channel: shard_a
    ├──► Redis channel: shard_b
    ├──► Redis channel: shard_c
    └──► Redis channel: shard_n ...


    Shard Workers ─── evaluate all strategies

           ├──► Validated signals → Signal Consumer
           │                           │
           │                           ▼
           │                    Broker Execution
           │                    (Alpaca / IB)

           └──► Strategy state → PostgreSQL

Data Layer

StorePurposeAccess Pattern
PostgreSQL + asyncpgTrades, positions, orders, strategies, discovered rulesRelational queries, ACID transactions
QuestDBTick data, OHLCV barsHigh-throughput time-series writes (ILP), fast range queries
RedisCaching, pub/sub shard channels, real-time stateSub-millisecond reads, message routing

Backend Stack

ComponentTechnologyRationale
LanguagePython 3.12+Type hints, async/await, ecosystem
FrameworkFastAPIOpenAPI auto-docs, dependency injection
ASGI ServerGranian (Rust)3-4x faster than Uvicorn
Package ManagerUV (Rust)10-100x faster than pip
ORMSQLAlchemy 2.0Full async support
ValidationPydantic v2Field validators, settings management
LintingRuffUnified tool (black + flake8 + isort)
LoggingstructlogStructured JSON, async-safe
Data ProcessingPolars, Pandas, NumPyHigh-performance analytics
CLITyper + RichAdministrative tooling
Type CheckingMyPy (strict)Static type safety
Testingpytest + hypothesisUnit, integration, property-based
Dependency ManagementRenovateAutomated dependency updates
CI/CDGitHub ActionsLint, typecheck, test on every push/PR
ObservabilityOpenTelemetry + Prometheus + grafanalib + PushgatewayDistributed tracing, metrics, dashboards as code, ephemeral-worker metrics push
API Contractopenapi-typescriptPydantic response models, generated TypeScript types, CI drift check

Frontend Stack

ComponentTechnology
FrameworkNext.js 16 (App Router)
UIReact 19, Tailwind CSS v4, shadcn/ui
Data FetchingTanStack Query v5
ChartsRecharts
IconsLucide React

Deployment Modes

ModeCommandUse Case
Developmentdocker compose --profile dev upHot reload, single process
Productiondocker compose --profile prod upOptimized monolithic
Shardeddocker compose --profile sharded upHorizontal scaling (8 containers)
Full Stackdocker compose --profile full up+ Prometheus, Grafana, Jaeger