Skip to content

Architecture

The library is split into 3 projects with a strict dependency direction: Base → Core, Data → Base → Core. Nothing in Core references Base. This is enforced by directory-level structure and is what makes the trait/concrete split possible.

Project map

flowchart TB
  subgraph "Virtufin.Core (traits, no domain)"
    Core_EAV[EAV abstractions<br/>IEntity, IAttribute,<br/>IValueProvider, Registry]
    Core_Traits[Financial contract traits<br/>ITradeAction, ITradeEvent,<br/>IExecutionState]
    Core_Behavior[Behavior traits<br/>IProcess, IDecide,<br/>IAlgebra, ISignal]
    Core_Decimal[DecimalAmount<br/>arbitrary-precision decimal]
    Core_Position[Position trait<br/>IPosition, IQuantity]
  end

  subgraph "Virtufin.Base (concrete domain)"
    Base_Currency[Currency, Cash, Stock<br/>Position, Transaction]
    Base_Scenario[Scenario, ScenarioHistory]
    Base_Contract[ContractIdentifier, UTI,<br/>Signatory, AssetIdentifier]
    Base_Exec[Executors<br/>Deterministic, Slippage,<br/>Live, ObserveOnly]
    Base_Orders[BuyOrSell, SimpleOrder&lt;U&gt;<br/>IOrderLine, IL3OrderBook]
  end

  subgraph "Virtufin.Data (serialization + reactive)"
    Data_Variant[Variant discriminated union]
    Data_FB[FlatBuffers<br/>schema + codegen]
    Data_NATS[NATS observable]
    Data_WS[WebSocket observable]
    Data_VK[Valkey observable]
  end

  Base_Currency --> Core_Decimal
  Base_Scenario --> Core_EAV
  Base_Contract --> Core_Traits
  Base_Exec --> Core_Traits
  Base_Orders --> Core_Position
  Data_Variant --> Core_Decimal
  Data_FB --> Data_Variant
  Data_NATS --> Core_EAV

The trait/concrete split

The Core project defines traits (interfaces and types that don't depend on domain primitives). The Base project provides concrete implementations of those traits.

Core (trait) Base (concrete)
ITradeAction (marker) RichTradeAction ADT (BuyOrder, SellOrder, CancelOrder, Transfer, Interest, WithdrawInterest)
ITradeEvent<A> (with A Action property) TradeEvent ADT (OrderPlaced, OrderCanceled, OrderExpired, FillReceived, ExecutionCleared, ...)
IExecutionState (marker) DeterministicState (empty), StochasticState (seeded PRNG)
IStrategyState / IPortfolioState (markers) user strategies and folded portfolio states (see Behavior Layer)
Position (record) Position<A> (generic in IFixedPointAmount<A>), PositionTransferContract<A> (concrete)
IQuantity (trait) DecimalAmountQuantity, SignedDecimalAmountQuantity

Currency.CurrencySymbol is an exhaustive enum of ~170 ISO 4217 codes (active national currencies + precious metals + supranationals + a ZZZ sentinel for testing). Historical/withdrawn codes are intentionally omitted. See src/Virtufin.Base/Currency.cs for the full list.

Why split this way?

  1. Substitutability: a function declared as IExecutor<TState, ITradeAction, ITradeEvent<ITradeAction>> is callable with any IExecutor<TState, RichTradeAction, TradeEvent> (because RichTradeAction : ITradeAction and TradeEvent : ITradeEvent<RichTradeAction>, and ITradeEvent<out A> is covariant).
  2. Testability: tests can supply a minimal IQuantity stub without depending on DecimalAmount-backed types.

The convention is enforced by direction: Base may import Core, but Core never imports Base. Code review at the PR level catches violations.

The Variant cross-cutting type

Variant lives in Virtufin.Data: one value of 18 kinds (plain .NET primitives, their arrays, arrays of variants, dictionaries) or none, a C# 15 union. In the library, ContractParameters wraps one. No other repo uses it today; the services exchange protobuf and JSON.

Virtufin.Data also holds a FlatBuffers schema of the same kinds, which FlatBuffersVariant reads — see Variant Type and FlatBuffers.

Reactive layer

Virtufin.Data provides three IObservable<T> adapters, all with auto-reconnect:

Adapter Source Notes
NatsObservable NATS subjects Subject-pattern match, re-subscribes on reconnect
WebSocketObservable WebSocket frames Reconnects with exponential backoff
ValkeyObservable Valkey keyspace notifications Key-pattern match, re-subscribes on PSUB reconnect

All three are documented under Observables.

The execution algebra

IExecutor<TState, TAction, TEvent> is the algebra of "given a current state and an action, produce the next state and an outcome event." The library provides four implementations:

Class Algorithm shape When to use
DeterministicExecutorBase<TState, TAction, TEvent> Execute → Process(state, action) Backtests, unit tests, deterministic simulations
SlippageExecutorBase<TState, TAction, TEvent> Execute → CalculateSlippage(state, action) → Process(state, action, slippage) Realistic paper trading with slippage modeling
LiveExecutorBase<TState, TAction, TEvent> Execute → Process(state, action) Production exchange routing (subclass)
ObserveOnlyExecutor<TState, TAction, TEvent> Decorator — wraps another IExecutor and records events SHADOW_* scenarios

All three base classes are abstract — subclasses define the case-by-case fill logic. The bases differ in algorithm shape, not in name or config field. See DecimalAmount for the numeric type used in fills.

IExecutor is the execute half of the trading loop. Its decide counterpart is IDecide, a specialization of IProcess — see Behavior Layer.

Worked example: the shape of an executor

using Virtufin.Base.Events.Trade;
using Virtufin.Base.Execution;

public sealed class MyExecutor : DeterministicExecutorBase<MyState, RichTradeAction, TradeEvent>
{
    public override MyState Initial => new();

    // The next state and the event that one action leads to.
    protected override (MyState NextState, TradeEvent Event) Process(MyState state, RichTradeAction action) =>
        action switch
        {
            // one arm per RichTradeAction case
            ...
        };
}

Subclass one of the bases and override Initial and Process. SlippageExecutorBase adds CalculateSlippage(state, action), returning the next state and the slippage, and its Process gets that slippage; LiveExecutorBase has ProcessAsync. RichTradeAction is a closed hierarchy (C# 15), so a switch without a default arm is checked for every action: a new action case breaks the build of every executor that does not handle it.

NativeAOT compatibility

The library is built to be NativeAOT-compatible: - All public APIs are AOT-friendly (no reflection on user types, no late binding) - JSON serialization uses source-generated JsonSerializerContexts where applicable - FlatBuffers serialization is codegen, not reflection

If you're consuming this library from an AOT-published project, the Variant and DecimalAmount types work without any AOT warnings. Subclassing IExecutor from an AOT project requires care with the case-by-case pattern matching — DynamicallyAccessedMembers annotations may be needed on the TAction type parameter.

The project file conventions: Conventions.