B10
BNWT v10.0 Whitepaper
Go to BNWT
Technical Whitepaper & Architectural Specification // Release 10.0

BNWT v10 Technical Whitepaper & System Architecture

An exhaustive software engineering dissection of the zero-backend financial charting terminal: asynchronous multi-exchange WebSocket multiplexing, high-DPI HTML5 2D Canvas rasterization, Pearson correlation pattern forecasting, institutional liquidity zone scanning, and real-time risk engines.

Lead Developer & Architect
Gikunju Muriuki
Runtime & Rendering Stack
ES6+ SPA // HTML5 2D Canvas
Supported Liquidity Venues
7 Exchanges (WSS + REST)
Section 01

System Overview & Architectural Philosophy

ENTRY: startApp() // DOMContentLoaded
System Architecture / Engineering

BNWT Version 10, architected by Gikunju Muriuki, is a client-side, zero-backend Single-Page Application (SPA) engineered in pure, dependency-free ECMAScript (ES6+). By bypassing Virtual DOM diffing overhead and third-party charting abstractions, the runtime communicates directly with the browser’s native HTML5 2D Canvas API, WebSocket (WSS) bidirectional sockets, Fetch REST pipelines, and Web Storage (localStorage).

Bootstrapping occurs deterministically via startApp() upon DOMContentLoaded. To eliminate Temporal Dead Zone (TDZ) ReferenceError exceptions inside asynchronous frame callbacks, critical UI overlays (dmgInfoPanel, dmgInfoCloseBtn, dmgInfoContent) are bound immediately at closure initialization. The architecture decouples asynchronous network mutation from display rasterization through a dirty-flag requestAnimationFrame (rAF) render loop gated by needsRender.

DPR Scaling: canvas.width = rect.width * (window.devicePixelRatio || 1)
Render Gate: if (needsRender) { render(); needsRender = false; }
State Hydration: localStorage.getItem("bnw_chart_state") // Fault-tolerant JSON
Plain-English Translation // What Is This App?

Think of BNWT as a professional Wall Street trading terminal built completely from scratch by Gikunju Muriuki that runs directly inside your browser or phone with zero middleman servers slowing it down.

Instead of redrawing the screen endlessly and draining your battery, the app only repaints pixels when a new live price arrives or when you touch the chart. It also remembers your exact setup—exchange, coin, zoom level, and indicators—and saves downloaded price bars to your device so the terminal still works even if your Wi-Fi disconnects.

STORAGE NAMESPACES: bnw_chart_state • bnw_candles_* • bnw_calc_state
Subsystem Core Engineering Mechanism Functional Output
MarketProviders Polymorphic REST adapter map + resolveAssetPair() symbol normalizer Unifies 7 exchanges into standardized chronological OHLCV arrays.
initWebSocketEngine Full-duplex WSS multiplexer + exponential backoff REST polling fallback Sub-second live candle updates with automatic self-healing failover.
render() Pipeline 8-layer painter's algorithm on DPR-scaled HTML5 2D Canvas 60+ FPS candlesticks, session bands, crosshairs, and analytical overlays.
Ghost Candles Z-normalized sliding-window Pearson correlation (r ≥ 0.70) Finds historical structural twins and projects future price trajectories.
SMC & DMG Engines ATR-normalized Order Block/FVG scanner + 11-tier decile range matrix Maps institutional supply/demand zones and premium/discount pricing.
TopDownEngine 6-timeframe SMA(20/50) crossover scanner + annualized σ index Real-time macro trend alignment and annualized standard deviation volatility.
Section 02

Multi-Exchange Data Ingestion & Streaming Pipeline

7 LIQUIDITY VENUES // WSS + REST
System Architecture / Engineering

External liquidity providers enforce incompatible ticker formats, timestamp epochs (seconds vs. milliseconds), and array orderings. The MarketProviders strategy map and resolveAssetPair(exchange, asset) normalize Binance, Hyperliquid, Bybit, XT, Coinbase, Kraken, and BitMart into canonical ascending {time, open, high, low, close, volume} structures—including specialized routing for Nikkei 225 (JP225 → xyz:JP225 on Hyperliquid) and Tether Gold (XAUT → XAUTUSDT on Binance).

Live ticks arrive over full-duplex WebSockets (initWebSocketEngine) and mutate the trailing bar inside handleIncomingTick(), enforcing a strict 10,000-candle circular buffer cap via candles.shift(). If a socket fails or is unsupported, activateRESTFallbackLoop() engages an exponential backoff poller starting at 2,000 ms and scaling by 1.5× up to 30,000 ms during outages. Panning near the oldest loaded candle triggers mutex-locked loadMoreHistory() pagination with O(1) Set timestamp deduplication and seamless scrollOffset compensation.

Plain-English Translation // Live Feeds & Self-Healing

Every exchange speaks a different technical language—some send timestamps in seconds, others in milliseconds, and some send price lists backward. BNWT acts as a universal translator that converts all 7 exchanges into one clean format.

It opens a live WebSocket "hotline" so every trade moves the chart in real time. If your connection drops, it automatically switches to checking every 2 seconds (slowing gently up to 30 seconds if offline so your device never freezes). Dragging backward into the past quietly downloads older history without jumping your screen.

01. BINANCE
REST: /api/v3/klines
WSS: stream.binance.com:9443
Native ms epochs; &endTime pagination; @kline_{tf} stream.
02. HYPERLIQUID
REST: POST /info
WSS: api.hyperliquid.xyz/ws
candleSnapshot JSON; routes JP225 to xyz:JP225 perpetuals.
03. BYBIT
REST: /v5/market/kline
WSS: stream.bybit.com/v5
Reverses descending result.list; linear/spot category switch.
04. XT EXCHANGE
REST: /v4/public/kline
WSS: ws.xt.com/public
Lowercase underscore pairs; kline@{pair},{interval} topic.
05. COINBASE
REST: /products/{id}/candles
WSS: ws-feed.exchange.coinbase
Scales sec × 1000; remaps [t,l,h,o,c]; 300-bar windowing.
06. KRAKEN
REST: /0/public/OHLC
MODE: Adaptive REST Poll
Maps BTC → XBTUSD; dynamic key extraction; &since lookback.
07. BITMART
REST: /quotation/v3/klines
WSS: ws-manager-compress
Seconds-to-ms scaling; &before pagination; spot/ticker feed.
FAILOVER ENGINE
2000ms → 30000ms (1.5×)
Automatic recovery + localStorage offline fallback.
Section 03

Canvas Coordinate Geometry & Viewport Transforms

AFFINE PROJECTION // GESTURE FSM
System Architecture / Engineering

Every frame projects discrete time-series elements onto a 2D Euclidean viewport using affine linear transformations. Horizontal placement maps bar index i via X(i) = chartWidth - (N - 1 - i) * totalBarWidth + scrollOffset, while arbitrary future or historical timestamps are projected through timeToX(). Vertically, yMap(price) maps bounded extrema padded by ±55% of the visible range, transitioning seamlessly from automatic scaling (autoScaleY = true) to manual axis compression (manualYScaleFactor ∈ [0.05, 15.0]) and vertical panning (manualYOffset).

AFFINE Y-AXIS PROJECTION & UTC SESSION WINDOWS:
yMap(P) = chartHeight − ((P − adjMin) / (adjMax − adjMin)) × (chartHeight − 10)
ASIA: 00:00–09:00 UTC
LONDON: 07:00–16:00 UTC
NEW YORK: 13:00–22:00 UTC

A unified pointer and touch gesture finite-state machine handles horizontal drag panning, right-edge 95px Y-axis vertical scaling (with dblclick auto-scale reset), rAF-throttled wheel zooming (candleWidth ∈ [2px, 50px]), two-finger Euclidean pinch-to-zoom (Math.hypot(Δx, Δy)), and an interactive crosshair HUD displaying live O/H/L/C telemetry.

Plain-English Translation // Smooth Controls & Sessions

Behind the scenes, BNWT uses fast geometry math to turn raw numbers (like "$94,250.50 at 14:35") into exact pixel locations on your screen—even when you zoom way in or stretch the price axis vertically.

It automatically shades the background to show when major global financial hubs—Asia, London, and New York—are open for trading, and lets you inspect any candle's exact Open, High, Low, and Close values by hovering your mouse or sliding your finger across the screen.

Section 04

Quantitative & Algorithmic Engines

4 PROPRIETARY ANALYTICAL MODULES

4.1 Ghost Candles Pattern Matching Engine

computeGhostPredictions() // r ≥ 0.70

This non-parametric forecasting module extracts the trailing W = min(35, ⌊N/3⌋) closing prices and normalizes them into scale-invariant relative return vectors: x[k] = (close[k] - close[0]) / close[0]. It then performs an exhaustive sliding-window scan across historical data up to N - W - 30, evaluating structural similarity via the Pearson Product-Moment Correlation Coefficient mapped onto [0, 1] via (r + 1) / 2.

PEARSON SIMILARITY & AFFINE PROJECTION:
Score = ( [∑(xᵢyᵢ) − (∑xᵢ∑yᵢ)/W] / √[(∑xᵢ² − (∑xᵢ)²/W)(∑yᵢ² − (∑yᵢ)²/W)] + 1 ) / 2
If Score ≥ 0.70: P_proj[j] = P_hist[j] × (currentEndPrice / sourceEndPrice)

Matches scoring below 70% are discarded. Valid matches extract the subsequent 30 historical candles, rescale all OHLC coordinates by scaleRatio, and project them forward onto future timestamps (lastRealTime + (idx + 1) * avgInterval).

Plain-English Translation

Financial markets often repeat historical patterns. Ghost Candles takes the shape of the last 35 price bars and searches backward through history to find a past moment that moved the exact same way (requiring at least a 70% match). When it finds a match, it takes the 30 candles that happened right after that past event, resizes them to today's price, and draws translucent "ghost" bars into the future so you can see how the market played out last time.

4.2 Smart Money Concepts (SMC) Institutional Zone Scanner

buildSmcZones() // OB & FVG

Operating on any selected reference timeframe (1m–1M), buildSmcZones() computes a 30-candle rolling range baseline (avgRange) to adaptively calibrate institutional displacement thresholds across disparate asset classes:

  • Order Blocks (bullish-ob / bearish-ob): Triggered when an impulse candle displaces price by > 1.2 × avgRange immediately following an opposing candle whose body spans ≥ 0.3 × avgRange.
  • Fair Value Gaps (bullish-fvg / bearish-fvg): Detects three-candle liquidity voids where current.low > prev2.high (bullish) or current.high < prev2.low (bearish) with gap size ≥ 0.35 × avgRange.
  • Mitigation Lifecycle & Deduplication: Simulates every zone forward from formIndex + 1; zones breached by subsequent closes (OB) or wicks (FVG) are invalidated (isValid = false). Surviving zones are deduplicated within 0.2 × avgRange and capped at the 6 freshest active levels.
Plain-English Translation

Large banks and hedge funds leave footprints when they place massive orders. The SMC scanner automatically draws shaded boxes around Order Blocks (the exact price zones where big players launched fast moves) and Fair Value Gaps (unfilled price gaps left behind during sudden surges)—and automatically erases those boxes once the market comes back to fill them.

4.3 Decile Momentum Grid (DMG) & Psychological Confluence

getDmgLevels() // 0%–100% MATRIX

findPriceContainingCandle() scans backward through the chosen higher-timeframe reference series to locate the most recent completed bar enclosing the live price (low ≤ liveClose ≤ high). getDmgLevels() partitions that candle's spread into 11 equidistant decile levels (0% through 100%) and classifies live price location into institutional valuation tiers.

80% – 100%
Super Premium
50.01% – 79.99%
At Premium
50.0% EXACT
Equilibrium
21% – 49.99%
At Discounted
0% – 20.99%
Super Discounted
±0.35% TOL
Psych Confluence

Simultaneously, generatePsychLevels() computes asset-calibrated round numbers (e.g., 250–25,000 steps for BTC; 25–1,000 for Gold). When a DMG decile intersects a psychological level within 0.35% tolerance (isPriceAlignedWithPsychLevel), the canvas elevates its stroke weight and glow to signal confluence.

Plain-English Translation

DMG acts like a 0%-to-100% ruler stretched across a major daily or weekly candle, immediately telling you whether an asset is currently "on sale" (Super Discounted) or "overpriced" (Super Premium). Even better, whenever one of those 10% ruler lines lands right on top of a major round number (like $90,000), BNWT highlights it so you spot high-probability reaction zones instantly.

4.4 Top-Down Trend & Annualized Volatility Engine

class TopDownEngine // 60s POLL

Encapsulated inside the object-oriented TopDownEngine class, this subsystem polls six timeframes (1d, 1h, 30m, 15m, 5m, 1m) every 60,000 ms to evaluate dual Simple Moving Average regimes (SMA20 vs. SMA50 relative to currentClose) into STRONG BULLISH, WEAK BULLISH, STRONG BEARISH, or WEAK BEARISH states. On every live tick, calculateVolatility() computes the 20-period return standard deviation annualized via stdDev × √365 × 100.

Plain-English Translation

Instead of forcing you to click back and forth between six different chart timeframes, this engine scans all six in the background every minute and gives you a clean scorecard—plus a live Volatility Index showing how wildly the market is swinging right now.

Section 05

Risk Management & Platform Resilience

FX SIZING // TV & PWA READY
System Architecture / Engineering

Cross-Currency Position Size Calculator (updateCalculator): Evaluates exact position unit sizing from account equity (calcBalance), risk tolerance percentage (calcRisk), and stop-loss price distance (calcStopLoss). When account currency differs from trade quote currency, getExchangeRate() fetches live spot conversion rates from https://open.er-api.com/v6/latest/{fromCurr} with automatic localStorage caching (bnw_fx_rate_*) for offline continuity.

SIZING FORMULA: Position Size = (Account Balance × (Risk % / 100) × FX_Rate) / Stop_Loss_Distance

Universal Hardware & PWA Resilience: makeAccessibleForTV() binds tabindex="0" and Enter/Space keyboard events across all interactive buttons alongside an on-screen D-Pad controller for Smart TV remotes. Meanwhile, standalone PWA detection (matchMedia("(display-mode: standalone)")), beforeinstallprompt interception, direct Android APK distribution (bnwt.apk), and defensive startup guards (hideSplash(), #licensing-gate cleanup) guarantee uninterrupted availability across desktop, mobile, and television screens.

Plain-English Translation // Safety & Everywhere Access

Before you risk a single dollar, the built-in Position Size Calculator tells you the exact safe number of coins or units to buy based on your account size, risk percentage, and stop-loss distance—converting currencies live in the background.

Whether you trade on a desktop computer, pinch-to-zoom on a smartphone, install the Android APK app, or click through menus using a Smart TV remote control, BNWT is built to work reliably everywhere.

```