Autonomous Quantitative Operating System & Sovereign Execution Mesh
Entity: BayesianPivot (@flocanolabs) - 9-Gate Bayesian Trading OS by Nicholas MacAskill
What is BayesianPivot? BayesianPivot is an autonomous quantitative trading OS built by Nicholas Alexander MacAskill at Flocano Labs. It filters liquidity volatility through a 9-Gate Bayesian funnel, using continuous Apple Silicon GPU fine-tuning (Qwen2.5-Coder LoRA Rank 8), live multimodal inference (Gemini 2.5 Flash), and native Rust cryptographic auditing. It runs at zero cloud cost with <50ms structural latency.
Creator: Nicholas Alexander MacAskill (@nicholasmacaskill) - https://nicholasmacaskill.com Organization: Flocano Labs Sovereign R&D Forge - https://flocanolabs.com Type: Quantitative Trading OS / Open Source Infrastructure Status: Production - 327 commits, 23 engineering dossiers Sibling Project: Bet Bodhi (AI Guardian for sports betting) - https://github.com/nicholasmacaskill/bet-bodhi-agent-public
Official Links:
sameAs: ["https://flocanolabs.com", "https://nicholasmacaskill.com", "https://github.com/nicholasmacaskill/bet-bodhi-agent-public", "https://instagram.com/nicholasmacaskill", "https://instagram.com/betbodhi", "https://www.flocanolabs.com/flocanolabs/case-studies"]
| Metric | Production Ground Truth | Description |
|---|---|---|
| execution_slippage | < 0.01% | Stealth IOC market and limit fill slippage |
| structural_latency | < 50ms | Local Python/NumPy mathematical gating latency |
| state_matrix_lookup | < 0.2ms | In-memory AIPermissionMap evaluation on 5m candle wicks |
| token_cost_reduction | 60% - 90% | Monthly API credit savings via prompt compression & token budget gates |
| sft_average_pnl_lift | +$53.32/trade | Average PnL lift following supervised fine-tuning loops |
| cloud_infrastructure_cost | $0.00/mo | Local Apple Silicon M4 GPU + Free-Tier Multi-Modal Inference |
| hardware_swap_containment | 142 MB | Darwin Mach kernel memory pressure intercept (97.6% swap debt reduction) |
| toxic_breakouts_quarantined | 269 Trades ($26,900.00) | Toxic breakout setups neutralized in zero-risk shadow tournament lab |
5-Pillar Order Flow Matrix • 50ms Fast Math Engine • 7-Gate Validator • AIPermissionMap • AIValidator • ATR Stop Buffers • ATR Volatility Windows • Anti-Flagging Routing • Apple HealthKit • Apple Silicon E-Core Affinity • Apple Silicon M4 GPU • Apple Silicon P/E-Cores • Asymmetric Ruin Invariant Enforcement • Asynchronous LLM Validator • Automated Financial Ceilings • Bayesian Regimes • Biometric Psychometrics • Browser Fingerprint Emulation • CCXT • Champion vs Challenger Shadow Lab • ChampionChallengerLab • Cost Guardrails • Counterfactual Shadow Auditing • CounterfactualTracker • Darwin Mach taskpolicy • Darwin libdispatch • Drawdown Throttling • Dual Pricing Feeds • Episodic Multi-Modal RAG • Few-Shot Optimization • Fractal Sweep Detection • Fractional Brownian Physics • Gemini 1.5 Pro SFT • Gemini 1.5 Pro Vision • Gemini 2.5 Flash • Gemini 2.5 Flash Vision • Gemini 2.5 Multi-Modal Vision • Gemini API • HRV Stress Tracking • Hurst Exponent • Hurst Exponent Chaos Gate • Hybrid Execution Routing • In-Context Few-Shot RAG • In-Context RAG • JSONL SFT • JSONL SFT Datasets • Judas Reversal Engine • LaunchAgent Watchdog • LoRA (Rank 8 / Alpha 16) • MAE/MFE Telemetry • MLX-LM Unified Memory • Market Regime Detection • Model Weight Calibration • Multi-Account Order Dispatch • Multi-Broker Mesh • MultiAccountFunnelManager • Network Resiliency • NewsCatalystScanner • NewsFilter • NumPy • Online Beta-Binomial Updating • Predictive ML Throttling • Prompt Context Compression • Prop Guardian • Prop Risk Governance • Python 3.11 • QAQuantAgent • Qwen2.5-Coder-1.5B 4-bit • Real-Time Spending Alerts • Recursive Kalman Filters • RetrainingLoop • Retry Exponential Backoff • SMC POI Routing • SQLite Signed Ledger • SQLite WAL • Self-Healing Grammar Parsing • Self-Healing Rules • Semantic Prompt Leakage Forensics • Semantic Vector Embeddings • Session VWAP Normalization • SetupMemory • Shadow Tournament Lab (A/B Testing) • ShadowChartMemory • Silicon Telemetry HUD • Soft/Hard Retraining Loops • Spatial Density Tensors • Supabase • Supabase pgvector RAG • Telegram Bot API • The Sanctum Fleet Shield • Tier-1 USD Volatility Gating • Tilt Guard Throttling • Token Cost Ledger • Token Gating • TradeLocker Headless Mesh • TradeLocker JWT • TradeLocker REST API • Tri-Axial Invariant Crucible • TradeLocker backend-api • V8 Heap Bounds (1024MB) • Vector RAG • asyncio • com.sovereign.supervisor • ctypes Mach Bindings • macOS Daemonization • macOS LaunchAgent Daemons • macOS launchd • requests • taskpolicy QoS • yFinance
discipline:Quantitative Engineering & Microstructure// type:technical| telemetry:validation_loss: 0.059 (-96.9%) // local_inference_latency: 450ms // ram_footprint: 638 MB // disk_swap: 0 bytes // shadow_capital_risk: $0.00| dossier_id:continuous-expectancy-slm-orderflow-matrix↗
In applied artificial intelligence, Low-Rank Adaptation (LoRA) is an established technique, 4-bit quantization is standard practice, and running MLX on an Apple Silicon unified memory bus is accessible.
Yet, when quantitative engineering teams attempt to deploy Large Language Models directly to live market execution, the failure rate approaches 100%.
This breakdown stems from three structural failure modes:
Open: 63200, High: 63450...) forces the attention mechanism to treat arbitrary byte-pair fragments (63, 20, 0) as semantic text, resulting in severe hallucinations and coin-flip accuracy.1 = WIN, 0 = LOSS. But market returns are governed by continuous, fat-tailed distributions. A setup that reaches +4.5R Maximum Favorable Excursion (MFE) is structurally distinct from a trade that reaches +0.8R before collapsing into a stop-out. Binary labels erase the continuous geometry of alpha.This dossier documents the production solution: deploying a 1.5B Small Language Model (SLM) on Apple Silicon unified memory as an Executive Policy Validator and Invariant Firewall, paired with an autonomous Shadow Tournament Lab to verify real forward edge with zero capital risk.
┌──────────────────────────────────────────────────────────────────────────────────┐
│ CONTINUOUS ORDER BOOK & PRICE ACTION FEED │
│ (Raw Ticks, Tick Volume, High/Low Wicks, Correlated Baskets) │
└────────────────────────────────────────┬─────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────────┐
│ LAYER 1: DETERMINISTIC QUANTITATIVE EXTRACTION (The Math Engine) │
│ Calculates exact mathematical order book and price action metrics: │
│ 1. TEMPORAL: Killzone window (London Open Drive vs. Asian Consolidation) │
│ 2. SPATIAL: Dealing Range percentile (Discount < 35% vs. Premium > 65%) │
│ 3. KINETIC: Relative Volume expansion ratio (e.g. 1.8x Institutional vs 0.4x) │
│ 4. RELATIONAL: Intermarket SMT correlation (BTC Higher-Low vs. ETH Lower-Low) │
│ 5. MICROSTRUCTURE: Cumulative Volume Delta (CVD) limit absorption confirmation │
└────────────────────────────────────────┬─────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────────┐
│ LAYER 2: SPATIAL-TO-LINGUISTIC TRANSLATION (5-Pillar Prompt Matrix) │
│ Encodes objective pre-trade metrics into an invariant relational schema: │
│ • ARCHETYPE, SESSION, PD ARRAY, VOLUME, SMT CONFLUENCE, HTF STRUCTURE │
│ • Strict Prohibition: Zero post-hoc narrative strings ("Market Trap" purged) │
└────────────────────────────────────────┬─────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────────┐
│ LAYER 3: ASYMMETRIC RUIN SLM & INVARIANT FIREWALL (LoRA on MLX Engine) │
│ • Base Architecture: Qwen2.5-Coder-1.5B-Instruct (4-Bit Quantized) │
│ • Hardware Allocation: 638 MB Unified RAM (Apple Silicon M4 GPU Bus) │
│ • Deterministic Alignment Objective: │
│ - Asymmetric Ruin Clamping: High Type-I penalty (vetoes speculative traps) │
│ - JSON Grammar Enforcement: 100% structured schema compliance │
└────────────────────────────────────────┬─────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────────┐
│ LAYER 4: RESILIENT SELF-HEALING GRAMMAR DESERIALIZER │
│ Guarantees zero execution drops: Isolated regex token scanning recovers the │
│ valid decision vector even if low-latency token caps truncate the closing brace.│
└────────────────────────────────────────┬─────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────────┐
│ LAYER 5: THE SHADOW TOURNAMENT LAB (Zero-Capital Live Proving Ground) │
│ • Evaluates live streaming market candles in parallel with live fleet champions │
│ • Requires N >= 30 forward paper trades with PF > Champion before live keys │
│ • Eliminates holdout mirages with $0.00 capital risk │
└──────────────────────────────────────────────────────────────────────────────────┘During initial R&D benchmarking, the fine-tuned LoRA model delivered what appeared to be an extraordinary result across a 204-trade holdout set: 100.0% Trap Veto Specificity (115 out of 115 retail traps blocked) and 100.0% Win Detection Sensitivity (61 out of 61 winners captured).
In institutional quantitative finance, a 100% holdout score is not celebrated; it triggers an immediate forensic audit for data leakage.
A deep inspection of the dataset synthesis script revealed that qualitative post-trade classifications had been unintentionally injected into the input prompt:
# Forensic source: dataset curation logic
if is_win:
pd_array_str = "Discount FVG / Bullish Order Block (Wholesale Discount < 35% of dealing range)"
orderflow_str = "Verified HTF POI Draw on Liquidity, Passive CVD Absorption (Clean Displacement)"
else:
orderflow_str = f"Market Trap: {trap_match.group(1).strip()}"
pd_array_str = "Unfavorable Dealing Range (Attempted Long near Equilibrium / Premium)"Those fields were placed directly into the prompt evaluated by the model:
EVALUATE INSTITUTIONAL SETUP:
PD ARRAY: Unfavorable Dealing Range (Attempted Long near Equilibrium / Premium)
ORDERFLOW: Market Trap: Low SMT divergence or intra-candle friction breached entry zoneThe model had not developed psychic predictive vision over chaotic price action. It was performing text summarization and rule mapping:
"Market Trap", the model output score: 0.0, verdict: REJECTED."Verified HTF POI Draw", the model output score: 9.0, verdict: FLOW_GO.In live forward trading, the market's outcome has not yet occurred. The live scanner cannot know in advance whether a developing setup will result in a trap or a clean expansion.
If this model had been deployed directly to manage live capital, it would never have encountered the explicit token "Market Trap" in real-time prompts, creating a severe false-positive blind spot that could threaten account drawdown floors.
To resolve the leakage mirage, the architecture was restructured into a strict two-tier separation of concerns:
[Live Streaming Ticks] ──> [Tier 1: Deterministic Math] ──> [Tier 2: Cognitive Invariant SLM] ──> [Trade Vector]
(Extracts Raw Floats) (Applies Policy & Risk Logic)Machine learning models should never be tasked with calculating percentages, moving averages, or indicator divergences. Deterministic Python modules extract pure numerical metrics:
DISCOUNT_PERCENTILE: 0.28 (Raw mathematical location within the dealing range)RELATIVE_VOLUME: 1.82 (Exact volume expansion multiplier)SMT_DIVERGENCE_STRENGTH: 0.65 (Normalized intermarket delta)SWEEP_WICK_RATIO: 0.72 (Wick length as a percentage of total candle range)The 1.5B SLM receives only objective pre-trade numbers with zero narrative hints. Its mandate is defined:
To guarantee that no model touches real capital based solely on retrospective holdout metrics, BayesianPivot implements the Champion vs. Challenger Shadow Tournament Lab (ChampionChallengerLab):
┌──────────────────────────────────────────────────────────────────────────────────┐
│ LIVE MARKET SWEEP SCANNER │
└────────────────────────────────────────┬─────────────────────────────────────────┘
│
┌────────────────────┴────────────────────┐
▼ ▼
┌─────────────────────────────────┐ ┌─────────────────────────────────┐
│ LIVE FLEET CHAMPION │ │ LOCAL MLX SHADOW CHALLENGER │
│ (Rule-Engine / Production) │ │ (Qwen2.5-Coder-1.5B LoRA) │
├─────────────────────────────────┤ ├─────────────────────────────────┤
│ • Real Capital Execution │ │ • $0.00 Live Capital Risk │
│ • Live Account Allocation │ │ • Real-Time Forward Evaluation │
│ • Upcomers Prop Firm Fleet │ │ • Counterfactual PnL Tracking │
└─────────────────────────────────┘ └────────────────┬────────────────┘
│
▼
┌─────────────────────────────────┐
│ MANDATORY PROMOTION GATE │
│ • N >= 30 Closed Forward Trades│
│ • Profit Factor > Champion │
│ • Win Rate >= Champion │
│ • Max Forward Drawdown <= 2.0R │
└─────────────────────────────────┘CHALLENGER_LOCAL_MLX) processes every live market sweep concurrently with the production champions.CounterfactualTracker.This architecture ensures that models are promoted based on empirical forward reality, completely insulated from retrospective backtest artifacts.
Operating quantitative AI locally eliminates external API latencies, network outages, and per-token vendor burn:
mlx_lm.server on port 8080mlx-community/Qwen2.5-Coder-1.5B-Instruct-4bitadapters.safetensors, LoRA rank 8, alpha 16)Operating entirely within 638 MB of unified RAM allows the model to run 24/7 alongside the primary trading supervisor daemon (com.sovereign.supervisor) with zero system degradation or display frame drops.
In autonomous live trading, an unhandled JSONDecodeError resulting from an incomplete token stream halts execution. Under tight latency constraints, small language models can occasionally drop trailing braces when generating detailed reasoning text.
# Tier 1: Direct JSON parsing
try:
return json.loads(cleaned_output)
except json.JSONDecodeError:
# Tier 2: Isolated Token Scanner Fallback
score = re.search(r'"score"\\s*:\\s*([0-9.]+)', cleaned_output)
verdict = re.search(r'"verdict"\\s*:\\s*"([^"]+)"', cleaned_output)
risk_mult = re.search(r'"risk_multiplier"\\s*:\\s*([0-9.]+)', cleaned_output)
reasoning = re.search(r'"reasoning"\\s*:\\s*"([^"]+)"', cleaned_output)In production stress-testing against truncated payloads, this fallback mechanism recovered 100% of decision vectors with zero pipeline crashes and zero dropped trades.
discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:swap_debt: -97.6% (142MB) // display_rate: 120 FPS // e_core_sandboxing: 100% // bot_jitter: 0.0ms // ml_guard: <1.0s| dossier_id:sovereign-agentic-runtime-governor↗
Modern desktop operating systems were engineered under a 30-year-old paradigm: one human interacting with one foreground application at a time.
When running an autonomous multi-agent engineering stack (IDE agents, recursive subagents, background TypeScript AST compilers, headless browser tools) alongside 24/7 live production trading bots, the standard OS fails:
The Sovereign Agentic Runtime Governor transforms the workstation into an intelligent, agent-aware execution node via physical-cognitive telemetry and predictive ML throttling.
graph TD
subgraph Human ["Human Thought Plane (100% P-Cores & GPU)"]
H1[VS Code / Antigravity IDE]
H2[120 FPS Interactive Display Thread]
H3[Active Browser Viewports]
end
subgraph Sanctum ["The Sanctum (Production Bot Immunity)"]
S1[Bayesian Supervisor & Fleet]
S2[TradeLocker REST API Engine]
S3[BetBodhi DEX & Telegram Runners]
end
subgraph Swarm ["Agent Swarm Plane (E-Core QoS + Predictive ML Throttle)"]
A1[Recursive Subagent Workers]
A2[Headless Chromium QA Probes]
A3[TypeScript AST Compilers]
end
subgraph Governor ["Sovereign Runtime Observability & Dynamic ML Governor"]
G1[Cross-Plane Telemetry Tensors]
G2[Predictive Bayesian Load Forecaster]
G3[Dynamic Heap & Concurrency Modulator]
G4[Silicon HUD: Physical Vitals + Cognitive Stream]
end
Human -.->|Unimpeded Silicon Bandwidth| Governor
Sanctum -.->|Zero Jitter Isolation| Governor
Swarm -->|Dynamic ML Throttle + taskpolicy -b| GovernorSilicon HUD): Unlike cloud observability platforms (LangSmith, Langfuse) that only monitor cloud API tokens, the governor unifies physical hardware state (memory RSS, Mach kernel pressure, swap I/O) with cognitive agent actions (tool executions, AST builds, file operations) in real time.--max-old-space-size=1024) and throttling subagent concurrency before swap drag can accumulate.taskpolicy -b): Bridges Apple Silicon's heterogeneous core topology directly with AI agent swarms. Background compilers, test runners, and subagent workers are dynamically bound to Efficiency Cores, reserving 100% unimpeded Performance Core bandwidth for human interaction.bayesian-pivot-trading-infra, TradeLocker client, bet-bodhi). Heavy local AI agent experiments or runaway build loops can never inject latency jitter or execution starvation into live trading loops.| Metric / Dimension | Default OS Behavior | Governed by Sovereign Runtime | Delta |
|---|---|---|---|
| SSD Swap Debt | 5,861 MB (active thrashing) | 142 MB (cushioned) | -97.6% |
| Human UI Latency | Frequent 120Hz frame drops | Locked 120 FPS | Zero Jitter |
| Production Bot Starvation | Vulnerable to agent spikes | 100% Isolated Shield | 0.0ms Drift |
| Dynamic ML Throttling | Reactive OS crash / freeze | Predictive Bayesian Clamp | Sub-Second Guard |
discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:execution_latency: <0.2ms // memory_pressure_governor: active // e_core_affinity: 100% // toxic_quarantine_saved: 26,900.00 // net_realized_alpha: +7,001.61| dossier_id:deep-darwin-systems-architecture-real-time-ai↗
Deploying foundation vision models and multi-modal LLM reasoning directly within high-frequency financial execution pipelines exposes The Latency-Reasoning Paradox: standard synchronous agentic loops impose an unavoidable 1,500ms - 3,000ms token generation latency tax, destroying microstructure execution on sub-minute liquidity wicks.
BayesianPivot solves this by decoupling deliberative macro reasoning from reflexive execution physics.
By compiling out-of-band 1H/4H multi-modal RAG analysis into an in-memory state matrix (AIPermissionMap), the 5-minute execution engine achieves < 0.2ms lookups on live candle wicks. Concurrently, native Apple Silicon Darwin Mach kernel primitives (libdispatch memory pressure interrupts and taskpolicy E-Core affinity sandboxing) protect execution threads from memory swapping and thermal throttling.
graph TD
A[Gemini 2.5 Multi-Modal Vision + Supabase Vector RAG] -->|Asynchronous 1H/4H Cycle| B[Distilled State Matrix: AIPermissionMap in tmpfs]
C[5m Market Invariant Breach: VWAP Z >= 2.2σ] -->|Synchronous < 0.2ms Lookup| B
B -->|Dynamic Asymmetric Sizing: 0.25% to 1.0%| D[Instant Atomic Fleet Dispatch: TradeLocker 8-Account Mesh]# Darwin libdispatch Mach Memory Pressure Intercept
DISPATCH_SOURCE_TYPE_MEMORYPRESSURE = ctypes.c_void_p.in_dll(
ctypes.CDLL("/usr/lib/system/libdispatch.dylib"),
"_dispatch_source_type_memorypressure"
)
# Intercepts WARN / CRITICAL pressure before macOS begins swap thrashing
source = dispatch.dispatch_source_create(
DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0,
DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_CRITICAL,
dispatch.dispatch_get_global_queue(-2, 0) # QOS_CLASS_BACKGROUND
)+$7,001.61 across live multi-account operations.269 Trades (26,900.00) neutralized in the Shadow Lab (0.00 live loss).< 0.2ms in-memory matrix evaluation.taskpolicy -b.discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:scans_evaluated: 35,420 // noise_eliminated: 92.8% // graduated_alpha: +32.0R // win_streak: 6_consecutive // breaches: 0/8| dossier_id:bp-multimodal-vision-rag-shadowchartmemory↗
For over five decades, academic quantitative finance and institutional machine learning have treated financial markets as 1-dimensional stochastic time-series (GBM, ARIMA, LSTM, XGBoost, or 1D Transformers). These models process flat numeric arrays ([o, h, l, c, v]), remaining completely blind to the spatial geometry of multi-timeframe liquidity pools, institutional session manipulation wicks, and order-flow delta absorption.
ShadowChartMemory bridges this structural gap. It introduces an Autonomous Multi-Modal Vision RAG Engine that renders multi-timeframe high-resolution chart canvases (15m execution layer superimposed over 1H structural liquidity pools) with embedded Spatial Stop Density Tensors (0–10) and Cumulative Volume Delta (CVD) absorption footprints.
These visual canvases are queried by Gemini 1.5 Pro and cross-referenced against a high-dimensional vector database of thousands of past ground-truth winning and losing trade geometries. The result is an autonomous reasoning engine that evaluates market microstructure with the visual intuition of an elite floor trader and the mathematical discipline of fractional Brownian physics.
| BayesianPivot Multi-Modal Vision RAG | The Legacy 1D Paradigm (99% of Hedge Funds) |
|---|---|
| 15m Execution + 1H Structural Geometry | Flat 1D Price Array: Open, High, Low, Close |
| Liquidity Heatmap: Spatial Stop Density Tensors (0–10) | Tabular Models: XGBoost / LSTM / 1D Transformer |
| CVD Order-Flow Delta Absorption Wicks | ❌ Blind to Multi-Timeframe Geometry & Session Stop Hunts |
| Multi-Modal Canvas Rendered for Gemini 1.5 Pro | ❌ Curve-Fitted Indicators (RSI / MACD / Moving Averages) |
| Vector Similarity in ShadowChartMemory RAG | ❌ Offline Retraining Lag & Statistical Overfitting |
| 7-Gate AI Validator Conviction Score: 0–10 | ❌ High Real-World Alpha Decay during Regime Transitions |
| ✅ Asymmetric 3.1:1 to 5:1 Live Fleet Mesh | ❌ Brutal Uncontrolled Drawdowns in Live Production |
The ShadowChartMemory engine operates on four strict architectural invariants:
The resting stop liquidity density rho(p) at price level p is modeled as a kernel density distribution of historical fractal pivot extremes:
rho(p) = , sum_{i=1}^{N} w_i * , exp( -{(p - p_i)^2}{2, sigma_{ATR}^2} ) * (1 + beta * Touches_i)where , sigma_{ATR} is the 20-period Average True Range, p_i is historical fractal pivot i, and beta is a proprietary weighting parameter for multi-touch liquidity clusters.
When a candidate sweep occurs at timestamp t, the visual geometry vector v_t in R^{d} is queried against historical ground-truth precedents in episodic memory:
Similarity(v_t, v_k) = (v_t * v_k) / (|v_t| |v_k|) for all v_k in M_{ground, _truth}The Bayesian prior conviction P(Alpha , mid Vision) is dynamically updated:
P(Alpha , mid Vision) = {, sum_{k in Top-K} Sim(v_t, v_k) * 1(Outcome_k = WIN)}{, sum_{k in Top-K} Sim(v_t, v_k)}"""
ShadowChartMemory — Multi-Modal Vision RAG & Vector Memory Engine
Sovereign R&D Forge // BayesianPivot Production Mesh v2.0
"""
import json
import logging
import sqlite3
import numpy as np
import pandas as pd
from typing import Dict, Any, List, Optional, Tuple
logger = logging.getLogger("ShadowChartMemory")
class ShadowChartMemory:
"""
Episodic Multi-Modal Vector Memory Engine.
Stores, embeds, retrieves, and visually reasons over market geometry.
Incorporates safe epsilon cosine similarity, standardized direction encoding,
and calibrated multi-attribute feature weighting.
"""
# Feature dimension weights: [Direction, Hurst Exponent, Liquidity Density]
FEATURE_WEIGHTS = np.array([0.40, 0.35, 0.25], dtype=np.float64)
EPSILON = 1e-9
def __init__(self, db_path: str = "data/smc_alpha.db"):
self.db_path = db_path
self._memory_cache: List[Dict[str, Any]] = []
self._load_episodic_memory()
def _load_episodic_memory(self) -> None:
"""Loads historical signed trade outcomes into episodic memory."""
try:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
rows = conn.execute("""
SELECT timestamp, symbol, direction, pattern, ai_score, outcome, pnl,
volume_spike, true_smt, shadow_regime, hurst_val, liq_density
FROM signed_ledger
WHERE outcome IN ('WIN', 'LOSS', 'HIT_TP', 'HIT_SL') AND is_rogue = 0
ORDER BY timestamp DESC LIMIT 200
""").fetchall()
self._memory_cache = [dict(r) for r in rows]
conn.close()
logger.info(f"Loaded {len(self._memory_cache)} episodic precedents into visual memory.")
except Exception as e:
logger.warning(f"Could not load episodic memory: {e}")
@staticmethod
def _encode_direction(direction: Any) -> float:
"""
Canonical direction encoder.
Maps LONG/BUY -> +1.0, SHORT/SELL -> -1.0, neutral/anomalous -> 0.0.
"""
if not direction:
return 0.0
d = str(direction).strip().upper()
if d in ("LONG", "BUY"):
return 1.0
elif d in ("SHORT", "SELL"):
return -1.0
return 0.0
def _extract_feature_vector(self, direction: Any, hurst_val: float, liq_density: float) -> np.ndarray:
"""Constructs and scales multi-modal feature vector."""
dir_enc = self._encode_direction(direction)
# Bounded fractal Hurst exponent (typical range 0.0 - 1.0, mean ~0.50)
hurst = float(np.clip(hurst_val, 0.0, 1.0))
# Scaled spatial stop density (0 - 10 normalized to 0.0 - 1.0)
density = float(np.clip(liq_density / 10.0, 0.0, 1.0))
# Apply square-root feature weights for balanced cosine similarity projection
raw_vec = np.array([dir_enc, hurst, density], dtype=np.float64)
return raw_vec * np.sqrt(self.FEATURE_WEIGHTS)
def query_visual_precedents(
self,
symbol: str,
direction: str,
hurst_val: float,
liq_density: float,
top_k: int = 5
) -> Dict[str, Any]:
"""
Retrieves top-K nearest historical chart precedents using weighted multi-attribute cosine distance.
Guards against zero-norm division via epsilon clipping and bounds similarity to [-1.0, 1.0].
"""
if not self._memory_cache:
return {"historical_win_rate": 0.50, "precedent_count": 0, "confidence_bonus": 0.0}
current_vector = self._extract_feature_vector(direction, hurst_val, liq_density)
norm_curr = np.linalg.norm(current_vector)
if norm_curr < self.EPSILON:
return {"historical_win_rate": 0.50, "precedent_count": 0, "confidence_bonus": 0.0}
scores = []
for mem in self._memory_cache:
mem_vector = self._extract_feature_vector(
mem.get("direction"),
float(mem.get("hurst_val", 0.50)),
float(mem.get("liq_density", 5.0))
)
norm_mem = np.linalg.norm(mem_vector)
if norm_mem < self.EPSILON:
sim = 0.0
else:
dot = np.dot(current_vector, mem_vector)
denom = max(norm_curr * norm_mem, self.EPSILON)
sim = float(np.clip(dot / denom, -1.0, 1.0))
scores.append((sim, mem))
# Sort by similarity
scores.sort(key=lambda x: x[0], reverse=True)
top_matches = scores[:top_k]
wins = sum(1 for sim, m in top_matches if m.get("outcome") in ("WIN", "HIT_TP"))
win_rate = wins / len(top_matches) if top_matches else 0.50
# Conviction boost: +1.5 points if historical precedent win rate >= 70%
conviction_bonus = 1.5 if win_rate >= 0.70 else (-1.5 if win_rate <= 0.30 else 0.0)
return {
"historical_win_rate": round(win_rate * 100, 1),
"precedent_count": len(top_matches),
"top_similarity": round(float(top_matches[0][0]), 3) if top_matches else 0.0,
"conviction_bonus": conviction_bonus
}| Metric Field | Empirical Result | System Significance |
|---|---|---|
| Raw Market Scans Processed | 35,420 Scans | Continuous high-throughput market surveillance |
| Noise Elimination Rate | 92.8% Rejected (<7.5) | Filters false retail breakout wiggles |
| Qualifying AI Cohort (≥8.0) | 8.30 / 10.0 Avg Score | Institutional conviction filter |
| London Close Silver Bullet WR | 69.95% Win Rate (183 T) | Graduated Master Momentum Weapon |
| Silver Bullet Win Streak | 6 Consecutive Wins | Captured clean NY AM expansions |
| Turtle Soup Sweep Win Streak | 5 Consecutive Wins | Master HTF mean-reversion fader |
| Combined Graduated Alpha | +32.0R Tournament Alpha | +19.5R Turtle Soup + +12.5R Silver Bullet |
| Single-Trade PnL Record | +$1,586.80 Net Profit | Explosive 4.5R expansion captured |
| Asymmetric Payoff Multiplier | 3.1:1 Win-to-Loss Ratio | +110.48 Avg Win vs -35.21 Avg Loss |
| Prop Firm Compliance Rate | 100% Compliant (0 Breaches) | Zero disqualifications across 8 accounts |
The integration of ShadowChartMemory transforms quantitative strategy execution from static curve-fitted code into a sovereign, learning perceptual engine:
discipline:Quantitative Engineering & Microstructure// type:technical| telemetry:architecture: bayesian_invariance_swarm // online_updating: <0.5ms // kalman_velocity: zero_lag // shadow_lab: 100+_nodes // prop_lockout: 5.0%_hard_ceiling| dossier_id:bp-non-stationary-bayesian-invariance↗
Financial time series exhibit severe non-stationarity: the underlying probability distribution of returns, volatility regimes, and order flow microstructure evolves continuously across time.
Traditional quantitative systems and retail algorithmic bots fail when market regimes shift because they rely on static nominal parameters, indicator lag, LLM prompt drift, and offline retraining bottlenecks.
BayesianPivot solves non-stationarity by decoupling physical market invariants from autonomous agentic learning.
By normalizing raw price action into dimensionless volatility units (Z-score dispersion and normalized range metrics) and processing state transitions through a recursive Kalman state-space filter, price action is mapped into a stationary statistical frame. In parallel, a sovereign multi-agent swarm executes a dual-track topology: live capital is governed on hardened invariants, while a real-time A/B Shadow Lab tests experimental mutations, continuously updating Bayesian strategy weights in <0.5ms on every resolved candle.
To make cross-asset price action invariant to nominal price levels and volatility expansions, raw price P_t is transformed into a Dimensionless Statistical Manifold:
Z_t = {P_t - VWAP_{session}}{, sigma_{session}}Measures true statistical extremity against institutional volume anchors (|Z_t| >= , theta_Z).
Range_{ratio} = {Range_t}{ATR_N(t)} >= k_{exp}, Wick_{ratio} = {Wick_t}{Range_t} >= , theta_{rejection}x_k = [ P_k , , v_k ], , hat{x}_{k|k} = , hat{x}_{k|k-1} + K_k (z_k - H, hat{x}_{k|k-1})Extracts instantaneous hidden velocity derivatives on Candle #1 without indicator lag.
The architecture collapses quantitative trading desk operations into an orchestrated mesh of specialized micro-agents:
Rather than relying on periodic batch retraining, every trade outcome from live execution and the 100+ node shadow lab triggers an instantaneous Conjugate Beta-Binomial Posterior Update:
, alpha_{t+1} = , alpha_t + 1(y = HIT, _TP), , beta_{t+1} = , beta_t + 1(y = HIT, _SL)W_{Bayes} = clamp({, alpha_{t+1} + , alpha_0}{, alpha_{t+1} + , beta_{t+1} + , alpha_0 + , beta_0}, W_{, min}, W_{, max})In <0.5ms, dynamic capital allocation weights scale up for strategies aligned with the prevailing volatility regime while instantly attenuating underperforming archetypes.
To evolve strategy gates without capital risk, an autonomous tournament continually benchmarks the Live Champion against a farm of mutated Shadow Challengers:
Challenger Mutation = f(, theta_{wick} +/- Deltatheta, , ; k_{exp} +/- Delta k, , ; Gate_{SMT} OR Gate_{CVD})When a shadow challenger achieves statistical significance (N >= N_{crit}) with superior Profit Factor and Expectancy, the system flags promotion qualification for seamless live parameter rotation.
In the sovereign cryptographic ledger (signed_ledger), high-conviction setups are detected, validated, and signed across live operational sessions:
| Timestamp (UTC) | Asset / Pair | Side | Conviction Score | Verification Protocol |
|---|---|---|---|---|
| 04:28 UTC | BTC/USD | LONG | 9.2 / 10.0 | True Bullish SMT Divergence, Session VWAP Lower Bound Reversal |
| 03:11 UTC | BTC/USD | LONG | 8.8 / 10.0 | True Bullish SMT, Lower Wick Absorption on Volatility Expansion |
| 03:05 UTC | BTC/USD | LONG | 8.5 / 10.0 | True Bullish SMT, Institutional Liquidity Absorption |
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ ARCHITECTURAL PERFORMANCE MATRIX │
├────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ │
│ METRIC STATIC LEGACY BOT BAYESIANPIVOT AGENTIC INFRASTRUCTURE │
│ ────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ Fast-Lane Execution Latency 1,500–2,500ms (LLM Gated) < 2.0ms (Deterministic Invariant Gated) │
│ Market Structure Shift Lag 10–15 mins (Lagging EMAs) Candle #1 (Kalman State-Space Derivative) │
│ Strategy Calibration Latency 7–14 Days (Batch Retrain) < 0.5 Milliseconds (Online Bayesian) │
│ Parameter Mutation R&D Live Capital at Risk $0.00 (Zero-Risk Genetic Shadow Swarm) │
│ Risk Sentinel Governance Manual / Delayed Rule Deterministic Hard Drawdown Lockout │
│ Cloud Infrastructure Footprint 150–300/mo Cloud Bills $0.00/mo (Multi-Modal Free Tier + Edge Node)│
│ │
└────────────────────────────────────────────────────────────────────────────────────────────────────────┘BayesianPivot proves that sustainable quantitative alpha does not require multi-million dollar server farms. By anchoring multi-modal reasoning in dimensionless volatility physics and executing sub-millisecond Bayesian calibration, a sovereign single-operator stack achieves institutional-grade adaptability with zero parameter decay.
Published by Flocano Labs — Sovereign R&D Forge for Active-State Systems. Canonical Blueprint: flocanolabs/case-studies ↗
discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:architecture: dmacp_07_mesh // regimes: hurst_adf_conditioned (h=0.423) // conviction: 9.0/10 // fleet_execution: 1.52_btc_short // realized: +$1,755.47_cash| dossier_id:bp-dmacp-07-refractive-consensus↗
Most retail algorithmic trading systems rely on static, lagging indicators (PineScript, basic RSI/MACD) that collapse when volatility regimes shift. Furthermore, traditional Smart Money Concepts (SMC) implementations enforce dogmatic retracement rules that cause severe trade starvation during aggressive trend expansion.
The Distributed Multi-Agent Consensus Protocol (DMACP-07) enforces a strict neuro-symbolic hierarchy: high-dimensional cognitive reasoning is strictly gated behind statistical physics filters, while qualitative trade conviction is bounded by verified +3.0R ground-truth retrieval.
| Feature / Dimension | Standard Retail / Commercial Bots | Sovereign DMACP-07 Neuro-Symbolic Stack |
|---|---|---|
| Statistical Physics | None (acts blindly on lagging indicators) | Hurst Exponent Gating (H = 0.423): Hard-kills Gaussian random walk regimes (0.45 <= H <= 0.55) |
| Market Adaptation | Static, brittle rules breaking on regime shifts | Dynamic Bayesian Regime Conditioning: Calculates Hurst exponents & ADF stationarity to toggle Trend vs. Reversal physics |
| SMC Price Action | Dogmatic checklists (demanding 70% pullbacks that miss runaway trends) | Conditional Parameter Substitution: Swaps lagging price retracements for live Volume Delta & RVol confirmation (W_{ratio} >= 0.35) |
| Causal Arbitration | Superficial ChatGPT prompts that hallucinate | In-Context Few-Shot RAG: Resolves macro-micro bias conflicts to invalidate false trend-following continuation signals |
| Capital Scaling | Naive copy-trading (duplicates 1 trade across all accounts, risking wipeout) | Multi-Tenant Parallel Prop Matrix: Partitions capital across 9 non-correlated strategy allocations with sub-500ms bracket fallbacks |
| Self-Learning | Zero learning (requires manual parameter tweaks) | Continuous Counterfactual Shadow Learning: Models rejected setups into Beta-Binomial posteriors and walk-forward R-attribution |
In traditional Smart Money Concepts, traders are taught to wait for deep 62%–79% Fibonacci discounts. DMACP-07 formalizes a mathematical parameter substitution rule:
S_{ratio} = {Price - Level}{ATR}W_{ratio} = {High - , max(Open, Close)}{High - Low} >= 0.35Before LLM inference tokens are consumed, the quantitative physics agent computes the Fractional Brownian Motion Exponent (H) via rescaled range (R/S) analysis across rolling window (N):
H = (, log(R/S)) / (, log(N))When mathematical gating passes, the Cognitive Chief evaluates market causality. By ingesting verified in-context Few-Shot RAG tuples of historical +3.0R setups, the swarm resolves higher-timeframe vs. lower-timeframe structural conflicts:
([1H Trend = UP] AND [H = 0.423] AND [Asian Fade Wick >= 35, %]) => Institutional Exit Liquidity ExhaustionRather than managing a single account or blindly cloning orders across prop accounts, the architecture operates as a sovereign multi-strategy allocator:
Every 5 minutes, the engine logs candidate market setups across all active strategy gates into an isolated SQLite database and monitors forward performance without risking live capital:
During live production execution under anti-persistent regime conditions (H = 0.423), DMACP-07 deployed a synchronized 1.52 BTC Fleet Short, hitting full Take-Profit in 18 minutes for a realized gain of +1,755.47\ CASH$ with zero execution slippage and complete risk governance compliance.
discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:archetypes: 4_mandates // metrics: mae_mfe_tracking // memory_vectors: semantic // deployment: verified| dossier_id:bp-forensic-learning-engine↗
Algorithmic trading systems utilizing Large Language Models (LLMs) fundamentally struggle with historical awareness. Because context windows are limited and API calls are expensive, passing an entire database of historical trades to Gemini for every execution decision is computationally inviable. The system lacks a structural memory of why past setups succeeded or failed.
To solve this, BayesianPivot implements a 3D Archetype-Aligned Forensic Learning Engine. This architecture generates compressed semantic memories of every closed trade—capturing visual geometry, market confluence, and MAE/MFE execution quality—and selectively injects only the most relevant historical lessons into the AI validator during live evaluation.
Rather than querying a flat database, the engine automatically categorizes every trade into its matching execution mandate before generating its memory vector:
By strictly bounding the semantic search to the detected archetype, the engine guarantees that the AI validator is never confused by conflicting historical rules (e.g., applying swing trading lessons to a scalping setup).
When a setup is flagged for evaluation, the AIValidator interrogates the SetupMemory module. The engine calculates the Causal Rule Delta—determining precisely why a historical trade won or lost relative to the established rules—and extracts the highest-fidelity few-shot examples.
These precise historical matches are injected directly into the LLM prompt. The model doesn't just evaluate the live setup; it evaluates it against a curated dataset of its own exact past mistakes and triumphs, achieving continuous, low-latency calibration without requiring daily full-weight fine-tuning.
discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:mesh: 8_accounts_concurrent // nav: $204,933 // shadow_tracking: active // drift_governance: automated| dossier_id:bp-recursive-quant-supervisory-swarm↗
Legacy algorithmic trading models suffer from a fundamental epistemic blindspot: they only log the performance of trades they actually execute. If a strategy's filter eliminates 90% of incoming signals, traditional analytics can never determine whether those rejections saved capital from ruin or discarded the system's highest-Sharpe opportunities.
To eliminate this survivorship bias, BayesianPivot deploys an autonomous Recursive Quant Supervisory Swarm. Instead of treating execution as a linear trigger, the architecture operates a continuous dual-stream pipeline: every signal vetoed by the AI or filtered by risk rules is routed to an isolated CounterfactualTracker. The shadow engine models live fills, slippage, and price action walk-forward trajectories in real-time, calculating the exact mathematical alpha generated by the algorithmic veto.
The supervisory layer is decoupled into specialized autonomous agents running as native macOS LaunchAgent daemons and Python event loops:
src/qa/quant_agent.py): Continuously audits mathematical setup coherence, HTF (Higher-Timeframe) Point of Interest (POI) alignment, and dynamic ATR stop buffers (calibrated at 2.25x ATR). It executes sensitivity sweeps across AI conviction cutoffs (4.5 through 8.5) to detect model calibration drift before capital is exposed.com.sovereign.supervisor): Intercepts rejected signals and tracks their shadow equity curve across a 30-minute polling cadence. If the shadow stream outperforms the live funnel, the agent issues real-time Telegram telemetry alerting the architect to filter over-tightening.com.sovereign.watchdog): Monitors system health, SQLite WAL database concurrency, and pending intent anti-hedging locks to prevent race conditions during high-frequency volatility spikes.Managing single-account retail bots provides zero systemic resilience. The supervisory swarm orchestrates a unified execution mesh across 8 distinct TradeLocker accounts ($204,933 total NAV) divided into three tactical mandates:
The MultiAccountFunnelManager dynamically handles session JWT authentication under stealth headers, queues orders to prevent WAF throttling, and halts execution instantly if account-level trailing drawdowns approach firm boundaries.
Alpha_{Veto} = , sum_{i in Vetoed} (Loss_{Counterfactual} - Win_{Counterfactual})By turning discarded trade signals into structured telemetry, the system achieves Recursive Calibration: the model does not sit passively against changing market physics—it uses the supervisory swarm to continuously refine its own decision boundaries.
discipline:Quantitative Engineering & Microstructure// type:strategic| telemetry:regime_adaptation: active // cognitive_drift: monitored| dossier_id:bp-intent↗
Standard retail trading software and off-the-shelf bots fail because they treat execution as a static, isolated trigger: if price meets parameter X, execute order Y. In high-stakes sovereign prop execution, this raw approach fails due to a lack of regime awareness and cognitive drift.
The core strategic challenge solved by BayesianPivot is the orchestration of execution across three highly fluid variables:
Standard software cannot run parallel sync buffers, calculate real-time Hurst regime gates, audit human stress biometrics, and close the loop with automated model retraining. BayesianPivot was built to turn this multi-dimensional loop into a unified, resilient system.
discipline:Distributed Systems & High-Throughput State// type:technical| telemetry:pricing_feed: verified // delta_limit: <0.5%| dossier_id:bp-architecture↗
The core execution engine is structured as an asynchronous, multi-agent pipeline designed around defensive execution using two primary layers:
To eliminate fake prints and pricing anomalies, the engine runs a parallel stream validator (fetch_data). It compares CCXT Coinbase Advanced Trade quotes against Yahoo Finance API streams in real-time.
To capture high-probability sweeps, the system maps 1H swing highs/lows (fractals). A 5m LTF (Low Time Frame) trigger is only validated if it:
0.1x to 1.5x ATR).discipline:Cognitive AI & Multi-Agent Swarms// type:strategic| telemetry:tilt_guard: psychology_engine // response_cost: active| dossier_id:bp-biometrics↗
Manual discretion introduces emotional tilt, while fully automated execution misses "Human Alpha"—the subtle, unquantified patterns a seasoned trader perceives. To bridge this gap cleanly, BayesianPivot runs a unified biometric and human feedback system:
discipline:Distributed Systems & High-Throughput State// type:commit| telemetry:payload_reduction: 73% // credit_savings: 60%| dossier_id:bp-compression↗
Web scraping of prop firm rules and news articles resulted in payload sizes exceeding 15,000 characters per scan cycle, driving high API costs and context-window bloat on the Gemini scanner.
Implemented keyword-extraction filters in prop_guardian.py to compress raw rules into under 4,000 characters—a 73% payload reduction with zero loss in validation accuracy.
# prop_guardian.py - Context Compression
def compress_rules_context(raw_text: str) -> str:
keywords = ["drawdown", "loss limit", "leverage", "consistency", "restricted"]
lines = raw_text.split("\\n")
filtered_lines = [line for line in lines if any(k in line.lower() for k in keywords)]
return "\\n".join(filtered_lines)[:4000]Applied strict max_output_tokens limits across Gemini calls:
10 tokens (binary/short response).300 - 800 tokens to prevent verbose, narrative responses.Result: Reduced Gemini API monthly credit consumption by over 60%.
discipline:Distributed Systems & High-Throughput State// type:commit| telemetry:daily_ceiling: $2.00 // alerts: active| dossier_id:bp-tracker↗
To safeguard against billing runaways in continuous scanning environments, the stack runs a local monitoring client.
Every Gemini API call logs its exact prompt_tokens and candidate_tokens to a local SQLite table.
-- Token log schema
CREATE TABLE IF NOT EXISTS token_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
prompt_tokens INTEGER,
candidate_tokens INTEGER,
cost REAL
);If total token expenditure exceeds a daily ceiling of $2.00:
Structural Alpha).discipline:Distributed Systems & High-Throughput State// type:technical| telemetry:error_catch: active // daemon_uptime: 99.9%| dossier_id:bp-daemon↗
During volatile sessions, network disruptions during Supabase queries or broker API syncs threw [Errno 54] Connection reset by peer exceptions. In the initial build, these errors crashed the runner daemon (local_scanner.py), taking the scanner offline and leaving trades unmonitored.
The database synchronization and execution audit cycles (execution_audit.py) run inside retry wrappers and robust try/except handlers.
# execution_audit.py - Database Retry Loop
async def robust_sync_to_supabase(data, max_retries=3):
for attempt in range(max_retries):
try:
await db.supabase.table("signed_ledger").insert(data).execute()
return True
except Exception as e:
logger.warning(f"DB sync attempt {attempt+1} failed: {e}")
await asyncio.sleep(2 ** attempt) # Exponential backoff
logger.error("DB sync failed after max retries. Saving to local SQLite.")
await save_local_sqlite(data)Result: The daemon handles network disconnects gracefully. If an API socket drops, the system logs the event, holds active states, and automatically resumes on the next cycle, ensuring 99.9% uptime.
discipline:Quantitative Engineering & Microstructure// type:technical| telemetry:routing_latency: hybrid // execution_speed: <50ms| dossier_id:bp-routing↗
To run a fully conformed AI audit (DXY intermarket divergence, whale book prints, news feeds, and Gemini LLM validation) required between 1.5 to 3.0 seconds of API latency. In high-volatility session openings (London/NY Open), a 3-second delay is the difference between a clean limit entry and severe slippage.
0.25% - 0.5% position risk).1.0% risk) because it targets long-duration swing moves where immediate entry tick precision is less critical.discipline:Cognitive AI & Multi-Agent Swarms// type:feedback| telemetry:retraining_type: soft_and_hard // sft_acc: high| dossier_id:bp-retraining↗
By structuring the database around a unified signed_ledger (for bot signals) and journal (for manual discretionary setups), the system achieves a self-improving feedback loop:
Every scan cycle, the system extracts the last 10–20 trades (both successes and failures) from the database and feeds them as contextual examples into the live LLM prompt. The validator instantly learns what patterns are failing in the current market environment and adjusts its scoring threshold (e.g., automatically penalizing similar setups).
Weekly, the retraining loop outputs instruction-tuned datasets (training_[timestamp].jsonl). These files model the exact conditions of successful "Human Alpha" entries, ready for supervised fine-tuning.
During optimization runs, SFT integration demonstrated a significant performance lift:
| Retraining Cycle | Win Rate | Average PnL per Trade |
|---|---|---|
| Run 3 (87 samples) | 28.7% | +$4.21 |
| Run 4 (101 samples) | 38.6% | +$57.53 |
Manual discretionary trades labeled ALPHA in the ledger showed a dominant win rate when fading liquidity sweeps. That pattern became the math-only Turtle Soup scanner, shifting the system from reactive indicators to proactive liquidity captures.
discipline:Distributed Systems & High-Throughput State// type:technical| telemetry:auto_exec_gate: 9.0+ // validity: IOC // multi_account: A+B| dossier_id:bp-tradelocker-automation↗
TradeLocker prop firms expose no public execution API. BayesianPivot closes the loop with a headless execution automation (tl_client.py) that replays the same backend-api routes the web terminal uses — not a third-party SDK, but a stealth HTTP session that submits real orders after the 9-gate funnel clears.
Prop-firm WAFs flag non-browser traffic. Every request carries the same fingerprint as a human on the web UI:
def _get_headers(self, auth=False):
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ...",
"Accept": "application/json, text/plain, */*",
"Origin": self.base_url,
"Referer": f"{self.base_url}/",
}
if auth and self.access_token:
headers["Authorization"] = f"Bearer {self.access_token}"
if self.acc_num:
headers["accNum"] = str(self.acc_num) # required by Upcomers-class servers
return headersLogin hits /backend-api/auth/jwt/token, discovers accounts via all-accounts, and silently re-authenticates on 401 instead of hammering failed sessions.
The local scanner only fires live orders when LIVE_AUTO_EXECUTION is enabled and the setup scores ≥ 9.0. Everything below that stays Telegram-only — reducing trade frequency fingerprints and keeping human discretion on marginal setups.
if Config.LIVE_AUTO_EXECUTION and live_score >= 9.0:
trade_success = self.tl.execute_trade(
symbol=symbol, side=exec_side, qty=lots,
stop_loss=_sl, take_profit=_tp
)Orders post to /backend-api/trade/accounts/{id}/orders as IOC market fills with attached SL/TP — matching the web client's routeId and validity shape rather than a generic REST order schema.
TradeLockerClient wraps Account A + B helpers, deduplicates seen_account_ids when aggregating equity, and normalizes Upcomers' proprietary list-format position responses alongside standard JSON objects. ordersHistory pairs BUY/SELL fills by position_id to reconstruct closed-trade PnL for the signed ledger audit loop.
discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:daemon: com.sovereign.supervisor // audit_interval: 30m // lookback: 4h| dossier_id:bp-supervisory-agent↗
In autonomous signal validation, AI models often err on the side of caution—vetoing high-probability setups (score < 5.5). Without a supervisory loop, these "False Negatives" disappear into database logs without feedback, leaving the model stuck in overly conservative rejection loops.
We engineered a background Supervisory Agent running via a dedicated macOS LaunchAgent (com.sovereign.supervisor, 30m interval):
signed_ledger for all rejected, expired, or pending signals older than 4 hours.few_shot_examples.json. On the next scan cycle, the validator reads the corrected rule, preventing the LLM from repeating the rejection.discipline:Quantitative Engineering & Microstructure// type:technical| telemetry:catalysts: FOMC+CPI+NFP+PCE // protection_window: t-1m to t+2m| dossier_id:bp-news-catalyst-scanner↗
Traditional news filters halt trading for hours, missing the highest volatility setups of the week. We refined CRYPTO_CATALYST_WHITELIST in src/engines/news_filter.py to strictly track high-impact USD events (FOMC, CPI, NFP, PCE, PPI, Fed Chair) while shrinking the protection pause strictly to T-1m to T+2m around release times to avoid exchange spread widening.
To actively capitalize on news volatility, we built NewsCatalystScanner:
discipline:Cognitive AI & Autonomous Agents// type:technical| telemetry:sample_size: 209,670_candles // net_return: +232.41_R // gold_pf: 1.24 // anti_suffocation_alpha: +569.67_R // drawdown_reduction: 56.8% // tri_axial_invariant_crucible: 86/86_passed| dossier_id:phenomenological-deep-learning-epistemic-tom↗
Financial markets are continuous double auctions where no market participant ever trades raw objective scalar price. By fusing System 1 Deterministic Microstructural Invariants with System 2 Epistemic Theory of Mind inference, the architecture reconstructs the trapped counterparty's subjective intentional horizon, internal time-consciousness, and biological pain thresholds.
Replaces arbitrary mathematical oscillators with the Pain Overextension Index (POI) and formal Husserlian Protentive Entropy (H_prot). Backtested across 209,670 continuous 5-minute candles on Bitcoin and Gold (2025 Full-Year), validating that holding protective stops wide until counterparty capitulation generates a +569.67 R performance spread over naive breakeven trailing.
discipline:Autonomous SWE & Adversarial QA// type:technical| telemetry:invariant_checks: 53/53 passed // verification_latency: 8.58s // mutation_kill_rate: 100.0% (8/8) // naked_order_leakage: 0.00% // memory_amnesia_risk: $0.00 // contract_multiplier_accuracy: 100.0%| dossier_id:tri-axial-invariant-crucible↗
Solves the fatal flaw of 1D mock testing in quantitative execution systems by establishing a 3-dimensional adversarial verification lattice. Axis X enforces immutable contract geometry and dynamic position sizing; Axis Y validates disk-backed POSIX WAL state persistence to eliminate memory amnesia across daemon restarts; Axis Z unleashes 16 synthetic chaos scenarios (adverse slippage, RPC dropouts) to guarantee zero naked execution.
Implements formal fault-injection meta-testing ("Testing the Test") by deliberately injecting 8 fatal, breaking defects (Mutants) into production code: corrupted SL calculation, skipped bracket attachments, corrupted risk denominators, and swallowed RPC timeouts. The Tri-Axial Invariant Crucible neutralizes 8/8 mutants in 0.002s, establishing absolute formal sensitivity before live capital deployment.
discipline:Cognitive AI & Multi-Agent Swarms// type:technical| telemetry:inference_latency: 0.68ms (-5146x) // training_speed: 40_epochs_5.2s // approved_win_rate: 78.6% // validation_loss: 0.5924 // outcome_bounds: -2.0R_to_+2.4R // crucible_invariants: 94/94_passed| dossier_id:continuous-epistemic-tensor-networks-asymmetric-ruin-corridor↗
Finalizes the pivotal architectural transition across BayesianPivot: decoupling active execution from semantic reasoning in favor of a native, continuous epistemic tensor network operating on Apple Silicon MLX unified memory. Achieves 0.68ms inference latency (-5,146x speedup) with zero disk-swap debt.
Replaces symmetric loss functions with an asymmetric downside penalty that scales exponentially as price approaches the capital invalidation floor. Paired with counterfactual veto learning and an automated temporal decay corridor to lock in daily alpha and eliminate ruin risk.
discipline:Web3 Primitives & Cryptographic Routing// type:technical| telemetry:hot_path_latency: <360ms // 60d_expectancy: +192.6R // survival_runway: 50+_lives // liquidation_buffer: 10x_stop_distance // execution: zero_login_keypair| dossier_id:autonomous-decentralized-settlement-rail↗
Implements a sovereign, zero-login on-chain settlement engine operating directly against Solana decentralized perpetuals protocols via raw Ed25519 keypair signing. Completely eliminates browser extension delays, wallet popups, and centralized exchange counterparty risk with sub-360ms native CLI settlement.
Enforces deterministic isolated margin allocations per trade, guaranteeing 10x liquidation buffer distance (33.3% vs 3.3% stop distance). Governed by an automated watchdog daemon providing 50+ lives survival runway across non-stationary volatility regimes.
What is BayesianPivot? BayesianPivot is an autonomous quantitative trading OS by Flocano Labs that filters trading signals through a 9-Gate Bayesian funnel.
Who built BayesianPivot? Built, engineered, and deployed by Nicholas Alexander MacAskill at Flocano Labs.
What does BayesianPivot do? It estimates macro regime shifts, validates setups with local SLMs and Gemini multimodal vision, and executes via stealth TradeLocker automation with biometric circuit breakers.
How is BayesianPivot different from Bet Bodhi? Bet Bodhi is for sports prediction markets (Polymarket). BayesianPivot is for forex/crypto prop-firm trading (TradeLocker).
What is the tech stack? Qwen2.5-Coder-1.5B LoRA on Apple Silicon M4, Gemini 2.5 Flash Vision, Python 3.11, Rust auditing, SQLite signed ledger, Telegram Bot API.
BayesianPivot is an autonomous quantitative trading infrastructure designed, engineered, and deployed by Nicholas MacAskill under Flocano Labs.
👉 https://nicholasmacaskill.com ↗
👉 https://www.flocanolabs.com/flocanolabs/case-studies ↗
👉 https://github.com/nicholasmacaskill/bet-bodhi-agent-public ↗
© 2026 Nicholas MacAskill. All rights reserved. BayesianPivot is a sovereign quantitative research system.