Barfinex

How Barfinex Works

Barfinex architecture — how the system is built

Barfinex is an AI-Native Trading Operating System. Five specialized services cover the full trading lifecycle. This page explains how they connect, how data flows, and why the design is structured this way.

Overview

Barfinex is built on one principle: every stage of the trading lifecycle gets its own service, and services communicate through typed, auditable contracts.

The result is a system where you can deploy a new strategy without restarting the data feed, add a risk rule without touching the AI layer, and replace the terminal without changing anything in the backend. More importantly, every decision made at every stage is a typed event with a full audit record — traceable from signal to executed order.


High-level data flow

Exchange (Binance / Alpaca / …)
        │
        ▼
   [ Provider ]
   • Connects to the exchange (REST + WebSocket)
   • Normalizes market data: candles, trades, order book
   • Gap detection and automated repair
   • Exposes unified REST API and WebSocket /ws
   • Single source of truth for all downstream services
        │
        ▼
   [ Event bus — Redis pub/sub ]
   • All services publish and subscribe through typed channels
   • Channel names and payload shapes defined in libs/types
        │
   ┌────┴──────────┬──────────────┬────────────────────┐
   ▼               ▼              ▼                    ▼
[Detector]    [Advisor]     [Inspector]          [Studio /ws]
   │               │              │
   │ signals       │ decisions    │ risk events
   │               │              │
   └───────────────┴──────────────┘
           all route to Inspector
           Inspector places orders via Provider REST

What each service does

Provider

Provider is the foundation of the system. Its job: receive raw market data from exchanges and make it available to everything else through a single, normalized API.

  • Ingestion — connects to exchange WebSocket feeds (trades, order book, tickers) and REST APIs (candles, account, orders)
  • Candle aggregation — builds OHLCV candles at multiple timeframes from raw tick data
  • Data integrity — detects candle gaps, triggers automated repair jobs, validates seam boundaries, tracks ingestion health per connector
  • App registry — Detector, Advisor, and Inspector register with Provider at startup. Provider proxies requests to them and exposes their availability in Studio.
  • Single gateway — Studio connects only to Provider: one URL, one auth token, one WebSocket. All other services are reachable via Provider proxy.

Detector

Detector is where strategy logic lives. Each Detector instance is a typed TypeScript configuration describing what to watch, what conditions to evaluate, and how to score the result.

  • Rule engine — evaluates conditions against live candle and order flow data on every new candle
  • Signal scoring — each rule has a numeric weight; the combined score is compared to a threshold
  • Multiple instances — run several Detector configurations simultaneously, each targeting different symbols or market regimes; instances are fully isolated from each other
  • Output — a typed signal event: symbol, direction (long/short), conviction score, strategy identifier, rule attribution

Advisor

Advisor is the AI decision engine. It is not an optional AI module — it is a structured 8-stage reasoning pipeline that runs on every incoming signal.

The 8 stages:

  1. Fetch market context via Provider MCP tools (prices, positions, account state)
  2. Market quality gate — block if data quality score is below threshold
  3. Rule and ML signal evaluation — score the signal independently of the Detector
  4. Conviction scoring — assign a numeric confidence value [0, 1]
  5. Conviction calibration — apply logistic regression with per-regime scaling (Platt / isotonic methods)
  6. LLM synthesis — call the configured LLM with the full structured context; extract directional bias, reasoning, and sizing recommendation
  7. Decision validation — block if spread > 0.4% or risk/reward < 1.2
  8. Emit execution intent — publish a typed decision event with the execution instruction

Every stage produces a telemetry event. Over 28 event types are published by Advisor: conviction snapshots, attribution, regime rotation, hallucination detection, model switching. All are stored in the time-series audit log.

Advisor also exposes its full API as Model Context Protocol tools through Provider, making it directly callable by any LLM that supports tool use.

Inspector

Inspector is the risk governor. Every execution intent from Advisor passes through Inspector before any order reaches the exchange.

  • Policy validation — checks position size limits, portfolio exposure caps, drawdown thresholds, loss streak limits, cooldown periods, time-of-day restrictions
  • Actions — ALLOW (forward to execution), BLOCK (reject), THROTTLE (reduce signal frequency), STAND_DOWN (pause new entries), CLOSE_ALL (emergency exit)
  • Protective orders — places and maintains stop-loss and take-profit orders for all runtime-managed positions via Provider REST API
  • Post-trade audit — tracks slippage, fill rates, fees, and partial fills for every executed order
  • Reconciliation — periodically syncs expected vs. actual positions to detect state divergence

Inspector distinguishes between:

  • Runtime-managed positions — opened while Inspector is running; full control (stops, trailing, close)
  • Legacy positions — existed before Inspector started; notification only (Telegram alert)

Studio

Studio is the operations terminal — a Next.js application that connects to all backend services exclusively through Provider's unified gateway.

  • Live charts — candlestick charts with overlaid signals and position markers
  • Signal timeline — per-rule firing history and score attribution for every signal
  • Advisor decision log — reasoning traces, conviction scores, LLM synthesis output
  • Risk dashboard — Inspector KPIs, active positions, drawdown state, policy status
  • Capital efficiency — utilization, suppression, and reservation analytics across strategies

Studio observes the pipeline — it does not execute trades.


Default ports

ServicePortPurpose
Provider8081REST API, WebSocket /ws, proxy gateway
Advisor8009REST API, decision pipeline
Inspector8008REST API, risk dashboard, audit
Detector8101REST API, signal metrics
Event bus6379Redis pub/sub (internal)

App registry

Detector, Advisor, and Inspector register with Provider at startup via a standard register + heartbeat flow. Provider maintains the registry and proxies all external traffic to registered services.

This means Studio and API clients never need direct access to Detector, Advisor, or Inspector ports. Everything routes through Provider's single gateway.

For API paths and proxy routing details, see the Provider API reference and Building with the API.

Let’s Get in Touch

Have questions or want to explore Barfinex? Send us a message.