Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
BitResonantPublic

About

A real-time synthesis engine that turns live crypto order flow into sound. Trades stream in from Binance over WebSocket, get reduced to five microstructure metrics off the main thread, and drive three noise-excited synthesis engines.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

SoniChain

SoniChain turns live crypto order flow into sound, so the state of a market can be followed by ear while the eyes are on something else. Trades arrive from Binance over WebSocket, a Web Worker reduces them to five microstructure metrics, and those metrics drive three noise-excited synthesis engines (subtractive, FM and a physical-model waveguide) written in RNBO and running as WebAssembly. It runs as a web app and as a Tauri desktop app.

Matteo Caruso Linardon (sole author: DSP design in Max/RNBO, frontend architecture, market-metric layer, UX).

License: CC BY-NC-SA 4.0

▶ Demo on YouTube: the app running on the live Binance stream.

SoniChain demo video on YouTube

A first version of the project worked, but it sounded static, it grew irritating within a single working session, and it gave no sense of market direction, because I had kept price off the pitch axis on purpose. I set it aside for several months. The rebuild maps price to pitch after all, through discrete intervals. The up/down metaphor that listeners already know stays, the continuous glide that makes direct price-to-pitch mappings tiring is removed, and some resolution is traded for a display that can stay on in the background.

Scope. SoniChain is a perceptual monitoring instrument. It issues no signals, executes no orders, holds no credentials, and makes no claim that listening to it improves any trading outcome. It reads Binance's public aggTrade stream and turns it into sound. Nothing here is financial advice.


Contents


Design intent

A chart tells someone who is looking at it what happened. Market monitoring is a sustained-attention task: long stretches where nothing happens, a few seconds that matter, and a visual channel that only works while the eyes are on it.

Hearing is omnidirectional, needs no fixation, and is good at picking up changes in a stream the listener has stopped consciously following. Sonification as a field builds on this. Mapping a value straight to pitch usually produces a continuous glissando, which tends to sound like an alarm, and few people will leave an alarm running in the background.

Tolerability over long sessions is the goal the mappings were designed for and the reason the first version was set aside. It has not been measured. The available evidence is a pilot, reported as such in Listening sessions.


The first version

The first version was complete and working. It used a wavetable oscillator pair with this mapping:

Market data Audio parameter Synthesis technique
24h trend Timbre (wavetable position) Morphing across the Y axis (256 frames) between "bear" and "bull" spectral profiles
Price micro-variations Beat frequency (detune) Phase interference between two phasor~-driven oscillators (binaural-beat simulation)
Trade density Amplitude (gain) Dynamic gain mapping with line~ for smooth envelopes
Price volatility Pitch Real-time quantization onto a G Mixolydian scale spanning two octaves

Pitch was assigned to volatility to keep price off the pitch axis. In use, three problems came up, and I put the project aside for several months.

The sound was static. A wavetable read at a stable rate only changes its spectrum when the morph position changes, and market data moved that position slowly. After a few minutes the ear stopped parsing the sound, which is the main risk for a peripheral display.

It became irritating over long sessions. Two detuned oscillators produce a continuous, unresolving beat, which is pleasant for thirty seconds and wearing over an hour.

Market direction was hard to read. With pitch on volatility, nothing in the mapping told the ear which way the market was going.

The rebuild started from the price-to-pitch metaphor. It is common because listeners understand it immediately; what makes it tiring is the continuous mapping. Taking the discrete derivative of price and quantizing it to a scale interval keeps the metaphor and removes the glissando.

The second change was moving from wavetables to physical modelling. A physically modelled resonator has internal behaviour: energy enters, circulates, decays and interacts with the excitation, so the result sounds played. In this project the market is the performer and the DSP is the instrument. A sample library could have given a similar organic quality, at the cost of shipping megabytes of audio in a desktop app.

The engines below follow from this restart, including the shared external noise excitation, which works as the bow the market draws across whichever instrument is selected.


Design decisions and their costs

Price as intervals

price drives pitch through its discrete derivative over the last two ticks, stepped through a pre-quantized scale array. A positive Δ moves the pitch up, and the interval width scales with |Δ|. Each engine runs 8 voices, so transients trigger overlapping discrete notes that decay like a harp.

I considered two alternatives. Continuous price-to-pitch follows the data most closely, and it produces a portamento that never resolves, reads as a siren, and is hard to habituate to. Keeping price off pitch altogether, as the first version did, made market direction unreadable. Quantized intervals keep the direction cue without the continuous slide.

Cost: price moves smaller than one scale step are inaudible, so the display drops the micro-structure a continuous mapping would keep. I accepted that loss to get a display people keep switched on.

Order-flow imbalance as a stereo lean

maker_side, the buyer-is-maker flag used as a proxy for order-flow imbalance, drives the stereo image: sell pressure leans left, buy pressure leans right. The two channel gains move in opposition between 1.0 and 0.28 (about 11 dB apart) with a 1-second glide, so both channels always carry signal and the image drifts smoothly from side to side.

Timbre or a second pitch layer could also carry this cue. Both need conscious decoding, which spends the attention the display is meant to save. Spatial position is perceived before it is interpreted.

A hard pan was ruled out for two reasons tied to long sessions: it leaves one ear in silence, which is tiring, and at the trade rates of this stream it would flicker on every other trade. The glide turns a binary flag into a continuous lean that reads as pressure building up over time.

Cost: mono playback removes the cue. With a single earbud or a mono sum, the two gains add up to the same value whether the market is buying or selling, so the information cancels out completely. The display's most important signal is also the one most sensitive to the listening setup.

An adaptive scale

The value range is re-derived continuously. A 30-second calibration window captures each metric's min and max; after that, the thresholds jump to any new peak and decay linearly toward zero over 60 seconds, so the mapping follows changes in market regime. scaling/recalibration re-runs the capture on demand, and OutputScope.svelte applies the same scheme to the meters.

I tried a fixed range, calibrated once, first. A quiet market became inaudible and a volatile one saturated the top of the range, so the display went flat in the two conditions where it has the most to report.

Cost: absolute comparability. The same pitch, brightness or reverb tail can mean different things at different times, because the display reports the present relative to the recent past. After an hour away you can't read an absolute level off it. It works as a change detector and should be read as one.

One excitation model for three engines

All three engines are excited by the same external noise source, weighted by market_volume and low-passed by density before it reaches any engine. The noise is never summed into the output. In the FM engine it drives the modulation-index envelope; in the waveguide it is injected into the loop like a pluck.

Giving each engine its own native excitation (oscillator attacks for FM, an impulse for the string) would have been quicker to build and closer to each engine's conventional sound. I chose the shared excitation because the rest of the design depends on it.

Cost: each engine had to be rebuilt to take its excitation from outside, and both bugs described below came from that rebuild. None of the engines can produce a hard attack, so the palette is limited to sustained textures. In return, switching engines changes the timbre and leaves the meaning of each metric unchanged, so what a listener has learned carries over to the new voice. The same routing is what makes the switch click-free (see below).

There are three engines because the listening sessions showed that timbral tolerance is personal. A texture one listener can keep on for an hour, another wants off after five minutes. Since the display only works if people keep it on, letting them pick a voice is a requirement. Three is the smallest set I found that covers distinct characters: struck glass, a warm pad, a bowed string.

All three engines always running

A theme switch instantiates and tears down nothing. All three engine banks compute continuously, and the instrument parameter drives three gate~ 8 objects that route the shared excitation to the active bank. The other two keep running without input, so their resonators ring out naturally while the new one starts.

Gating or freeing the inactive banks would save CPU, and the measured cost below makes a case for it. Here the gate sits upstream of resonant models with physical tails: cutting the output would chop the outgoing voice mid-ring, while cutting the excitation lets it decay like a struck instrument. The switch has no click, mute or gap, and it needed no crossfade code because it follows from the topology. Once excitation is a routable signal, switching instruments becomes a routing problem.

Cost: about three times the DSP work for one audible engine, all the time. The measured figure is 3.2% of one core, flat across configurations, so the headroom is there on the test machine, and the choice depends on that headroom.

Sensitivity as a user control

market_volume passes through a logarithmic transfer curve with three settings: Low, Med, High. Low makes the display a quiet alarm for large events; High exposes the small pulses underneath.

The first version used a single curve that I tuned myself. A listener wanted to hear more than that tuning let through: the small movements I had suppressed as noise were the ones they were listening for. The right setting depends on how much attention the listener wants to give the display, so the choice is theirs.

Cost: one more control to understand before the display behaves as expected, and three response curves to keep consistent.

Raw numbers on the wire, scaling at the ends

crypto.worker.ts posts raw metrics and normalizes none of them: price, market_volume, density (inter-onset interval in ms), maker_side (0 or 1) and volatility (standard deviation of log-returns over a 64-tick ring buffer). Scaling happens twice downstream, in the RNBO control layer for audio and in OutputScope for the display. The worker only guarantees that finite numbers cross the boundary; a NaN price ends the tick before it can reach an RNBO parameter and glitch the audio.

I considered a single normalizer in the worker. Audio scaling has to run at sample rate inside the DSP, and the display has different requirements.

Cost: two adaptive normalizers built on the same idea and implemented separately. They can drift apart, so the meter may show something different from what the ear hears.

A 100 ms gate on scale changes

When the user changes musical scale, TICK → RNBO forwarding is gated for 100 ms (scaleSwitching in +page.svelte).

Without the gate, in-flight price events land on the old scale array while the new one loads and produce audible bichords, at the moment the user is listening closely to the change.

Cost: up to 100 ms of market data goes unsonified. The user triggers the gap, which makes it acceptable here.


Listening sessions

There was no controlled evaluation. The material is about 4 hours of my own background use while working, spread over several days, and one session of about 20 minutes with 5 friends who heard both this version and the first one, unblinded, with no task and no control condition. It is a pilot, and the findings below should be weighed as one.

Self-use

The display never told me what the market was worth in absolute terms, as expected from the adaptive scale.

During strong buy or sell pressure, the pitch movement was recognizable and pulled my attention back before I had looked at anything. Capturing attention is what the display is specified to do.

On one occasion, with the app running in the background, I noticed that Bitcoin had been falling substantially for a while before I had checked a chart. My thought at the time was that a position with a stop-loss would have had more decision time than an unwatched chart would have given.

Caveats: I am not a trader, the position was hypothetical, nothing was backtested, and this is a single event with no counterfactual. It shows only that, once, the sound crossed the attention threshold before the screen did.

Five-listener session

Listener profile Response
3 × finance-literate investors Found it useful
1 × musician Found it intuitive
1 × non-investor Could not correlate price movement with pitch movement

Three listeners had a market model and one had a musical model to map the sound onto. The listener with neither found the display meaningless, though they did not find it unpleasant. The sonification therefore assumes a prior idea of what a price move means: it supplies the acoustic cue and relies on the listener for the concept. For a professional monitoring tool that assumption is probably acceptable. It does not support a general claim that the display is intuitive.

Changes to the shipped build

Two features come from feedback on the earlier version:

  • Three switchable engines, because timbral tolerance varied enough between listeners that a single texture would have lost some of them.
  • The logarithmic sensitivity curve with three presets, because one listener wanted to hear the light movements I had tuned out.

Outside the scope of the sessions

Fatigue, the central claim of the project. A 20-minute session can't show whether something stays tolerable for hours, and at 20 minutes even the first version was still pleasant. The only longer exposure is my own ~4 hours (n = 1, and biased). Statements about fatigue in this README are design rationale, based on psychoacoustics and on how the first version behaved.


Two DSP bugs

Both fixes are in the shipped source.

FM pad: grain from the envelope follower

The FM pad had a persistent roughness, strongest in the reverb return.

My first hypothesis was an excessive modulation index collapsing the spectrum into buzz. At the 1:1 carrier:modulator ratio, though, the index has a floor of 0.35 and a hard clamp at 2.55, well below the ~4-5 range where sidebands get dense.

The cause was a single 15 ms one-pole follower driving both amplitude and modulation index. A 15 ms follower passes energy in the band the ear hears as flutter (up to ~20 Hz) and roughness (20-300 Hz). On the amplitude path that is harmless. On the index path it becomes phase modulation of the carrier at a perceptible rate (PM-index jitter), which adds spurious sidebands.

The fix separates the followers: 15 ms for amplitude, 40 ms for the index, which puts the index path below the lower roughness boundary. The reverb was a useful clue: the output leaky integrator and the reverb combs are both leaky-integrator topologies, so they accumulated and extended the artifact, which is why it was loudest there.

Waveguide: a decay control that set colour

A buzz at a fixed frequency, independent of f0, grew over time where it should have decayed. Turning the "decay" coefficient changed the timbre and left the decay time unchanged.

The original one-pole loop filter had unity DC gain for any feedback coefficient. That coefficient only set colour, and at DC the loop became a perfect integrator over the delay period, so any DC component in the excitation accumulated without limit. The parameter called "decay" had no effect on decay.

Revision 5 replaces the single implicit stage with three explicit ones:

  1. An explicit loop gain below 1 (DECAY_MAX = 0.995), separate from damping. This is the actual decay, driven inversely by volatility (rising volatility lowers the loop gain).
  2. A first-order DC blocker inside the loop (y[n] = x[n] − x[n−1] + R·y[n−1], R = 0.999, cutoff ≈ 7-8 Hz at 48 kHz), which sets the loop's DC gain to zero so no DC circulates.
  3. Energy normalization of the injection (× (1 − loop_gain)). At high Q the comb's resonant peak is about 1/(1 − loop_gain) ≈ 200, so an uncompensated injection at high market_volume would clip. With normalization, steady-state amplitude follows the injection level independently of loop_gain, and loop_gain only sets the tail length.

The loop transfer is HP(z)·loop_gain·LP(z) with |HP| ≤ 1, |LP| ≤ 1 and loop_gain < 1, so the loop gain is below 1 at all frequencies and goes to 0 at DC. The loop is stable for any parameter setting, without tuning.


Performance

Measured on an Apple M4 Pro (14 logical cores), Chromium 149 headless, 48 kHz, @rnbo/js 1.3.4, with the shipped DSP.export.json. Each figure states its method; the two values that could not be measured are listed as such.

DSP cost

15 s of stereo output rendered through the full device in an OfflineAudioContext, with the five metrics driven at 2 Hz via suspend()/resume():

Configuration Wall clock for 15 s of audio Share of one core
Graphite, driven 476.4 ms 3.18%
Slate, driven 476.9 ms 3.18%
Bone, driven 479.4 ms 3.20%
Slate, parameters static 471.7 ms 3.14%
Slate, master_volume 0 (silent) 479.1 ms 3.19%

The cost is flat. Switching engine changes it by 0.02 percentage points, and muting the output changes nothing. All three engines are computed all the time: the patch instantiates 8 voice codeboxes per engine plus 2 reverb instances, 26 signal cores in total, and instrument routes the shared excitation to one bank. This table is the price of the seamless theme switch: three engines' worth of DSP for one audible voice. Theme choice has no effect on performance. Driving the parameters adds 0.04 pp over static values, within the noise.

An offline render measures throughput. It shows that the DSP needs about 3% of one core; it does not show that the audio thread meets its deadline on a loaded machine, which I have not measured.

Control path

  • Worker metric computation: 0.332 µs per tick (median of 12 runs of 200,000 ticks, Node 26, same machine, with the ring buffer and log-return maths copied verbatim from crypto.worker.ts). At the busiest trade rate measured on the live stream, that is ~0.0004% of a core.
  • Worker → main postMessage: below 0.1 ms at p99, the resolution Chrome exposes. Across 1,800 warm round trips, none resolved above one tick of the clamped timer.
  • Parameter set → audible: one render quantum (2.667 ms at 48 kHz) plus AudioContext.baseLatency, 5.333 ms in this build.
  • outputLatency: not measured. Headless Chrome reports 0 with no audio device attached. On real hardware it adds the device buffer and will be the largest figure in this list.

Network

Sampled from the live btcusdt@aggTrade stream on the same machine, in two windows of 240 s and 180 s:

240 s window 180 s window
Trades per second 12.93 7.90
Event time → local receipt, p50 86 ms 86 ms
Event time → local receipt, p99 402 ms not recorded

The software path costs single-digit milliseconds, against ~86 ms of network delay before a tick arrives and a p99 near 400 ms. The app's own latency is small by comparison, so a latency figure for the app mostly describes Binance and the route to it.

Timestamp collisions in the stream

61.6% of consecutive aggTrade events carry the same millisecond timestamp. Since density is defined as T[n] − T[n−1], it is 0 on about six ticks in ten, in both sampling windows. The metric is bimodal: a mass of zeros plus a long tail (non-zero p50 131 ms, p90 943 ms, max 3.3 s).

The 300 ms smoothing ramp on the density control path absorbs most of this, so it never showed up as an audible defect. density therefore measures burst membership as much as tempo. A rate-based definition (trades per unit time over a window) would be a different metric with a different feel, and the mappings density drives are tuned to the current one.


Architecture and data flow

The signal path runs one way: the worker computes metrics, the Svelte orchestrator forwards them as RNBO parameters, the DSP device synthesizes, and the Web Audio graph routes the result to the output and to the monitoring view. No path leads from the audio back into the data layer, so the audio cannot influence what is being measured.

flowchart TD
    subgraph ACQ["Data Acquisition · Web Worker (TypeScript)"]
        BIN["Binance WebSocket<br/>aggTrade stream"]
        WORK["crypto.worker.ts<br/>microstructure metric computation"]
        BIN -->|"raw market events"| WORK
    end

    subgraph ORCH["Orchestration · Svelte 5"]
        PAGE["+page.svelte<br/>RNBO device host"]
    end

    subgraph DSP["RNBO DSP Device · @rnbo/js + DSP.export.json"]
        direction TB
        CTRL["Control Layer<br/>adaptive scaling · log volume curve<br/>maker_side to stereo pan (OFI)"]
        NOISE["Noise excitation<br/>amplitude from market_volume"]
        FREQ["scales + note_changer<br/>price delta to quantized interval"]
        subgraph ENG["Synthesis Engines · 8-voice poly · all three always running<br/>instrument gates the excitation"]
            direction LR
            GLASS["Glassarmonica<br/>dual inharmonic biquad BPF"]
            FM["FM Pad<br/>4-op dual-serial · ratio 1:1"]
            STR["Bowed String<br/>Karplus-Strong waveguide"]
        end
        REV["Schroeder-Moorer Reverb<br/>4 comb + 2 allpass per channel<br/>RT60 from volatility · damping from density"]
        LIM["Brickwall Limiter"]
        CTRL --> NOISE
        CTRL --> FREQ
        NOISE --> ENG
        FREQ --> ENG
        FM --> REV
        STR --> REV
        GLASS -->|"dry, no reverb send"| LIM
        REV --> LIM
    end

    subgraph OUT["Audio Output + Monitoring · Web Audio API"]
        direction LR
        AC["AudioContext<br/>destination to speakers"]
        AN["AnalyserNode"]
        SCOPE["OutputScope.svelte<br/>scope / meters"]
        AC --> AN --> SCOPE
    end

    WORK -->|"postMessage TICK { 5 metrics }"| PAGE
    PAGE -->|"setRnboParam()"| CTRL
    LIM -->|"stereo out"| AC
Loading

Metric computation runs in a worker because it happens on every trade, at whatever rate Binance delivers, which is bursty and unbounded. On the main thread a burst would compete with the render loop and with the RNBO device's control updates. In a worker, a burst only delays the worker.

Parameter mapping

Each market metric modulates one DSP target. This table is where market semantics become perceptual attributes.

Market metric DSP target Perceptual intent
maker_side (order flow imbalance) Stereo lean: bearish → L, bullish → R (gains 1.0 / 0.28, glided over 1 s) A spatial, pre-attentive read of market lean, felt before it is parsed
price (discrete Δ via note_changer) Pitch / interval: Δ > 0 → ascending, width ∝ |Δ| Direction and magnitude, as a musical step
market_volume Noise excitation amplitude (log curve; Low / Med / High) Event intensity; user-selectable immersion depth
density (inter-onset interval, ms) Filter cutoff / brightness, comb gain, detune rate, reverb damping* Texture: a sparse market reads as separate events, bright and close; a busy one thickens into a darker, more diffuse wash
volatility (std-dev of log-returns, 64-tick window) Decay / feedback / loop gain, reverb RT60,* all inverse Definition: a calm market rings and sustains, a turbulent one dries out so fast events stay separable

* The reverb targets apply on Slate and Bone only. Graphite is routed dry (see Reverb), so on that theme these two metrics act through the engine alone, without a spatial dimension.

density is an interval in milliseconds, so its value grows as the market slows down. What it drives follows the parameter: a sparse market opens the excitation filters, widens the detune and darkens the reverb tail, while a busy one closes the filters and keeps the tail bright. Quiet flow sounds like distinct, present events, and heavy flow thickens into a wash.

volatility is mapped inversely everywhere: rising volatility lowers the loop gain in each engine and shortens the reverb tail, so the whole display gets drier and more articulate together. The intuitive mapping goes the other way (turbulence → a long reverberant wake); here it would smear together the events the listener needs to count when the market moves fastest.

market_volume is the only mapping the user can reshape at runtime; see Sensitivity as a user control for the reasons.

Calibration state machine

Audio output is gated at startup by an explicit phase sequence:

initial-connecting → pending-calibrate → recal-connecting → calibrating → idle

Two constraints shaped it. The adaptive scaler needs a stretch of market data to scale against, so the 30-second capture has to finish before the mapping means anything, and audio before that point would be misleading. Browsers also suspend the AudioContext until a user gesture, so the flow has to go through a click anyway.

The handoff is driven by calibrationPhase. An earlier version used a hasCalibrated boolean and broke on re-calibration, when the phase and the history disagreed. The Calibrate button is locked for ~1 s after the prompt first appears, so a click aimed at whatever was under the cursor doesn't land on a button that has just appeared there.


The RNBO patch

The DSP is a single RNBO export (DSP.export.json): a control and routing layer, three polyphonic engines, and a stereo reverb used by two of them. The four signal cores are RNBOScript codeboxes, and the notes below come from their source, which defines the constants and the topology.

All four apply per-sample one-pole smoothing (τ ≈ 5-10 ms) to each control parameter, along with explicit safety clamps and denormal flushing. Control values arrive at WebSocket rate in discrete jumps, and stepping a filter coefficient within one sample causes zipper noise.

Control and routing layer

  • Ingest and master output: receives the five metrics, applies spatialization and scaling, and feeds a brickwall limiter ahead of the stereo output. The limiter is there because the market sets the dynamics and does not respect a headroom budget.
  • Adaptive scaling subpatch: a peak detector with an adaptive threshold whose window narrows progressively to track larger range shifts (see the trade-off).
  • market_volume sensitivity: logarithmic transfer curve, Low / Med / High.
  • Spatialization: maker_side → stereo panorama, a direct read-out of order-flow imbalance.
  • Frequency assignment (scales + note_changer): scales emits pre-quantized frequency arrays that constrain the output to the selected scale. note_changer computes the discrete derivative of the last two price ticks and drives the engine switch from the active UI theme.

Engine A: Glassarmonica (subtractive resonator)

High-Q subtractive synthesis modelled on the inharmonic spectrum of a glass harmonica. It is selected by the Graphite theme and is the only engine routed dry, with no send to the reverb.

  • Topology: two parallel resonant biquads (Direct Form I), RBJ constant 0 dB peak band-pass sections (α = sin ω / 2Q, b0 = α/a0, b2 = −α/a0, a1 = −2cos ω/a0, a2 = (1−α)/a0). The second is tuned to f0 × 2.756, an inharmonic partial ratio that gives the sound its glass character. Coefficients are recomputed at sample rate to follow modulation.
  • Resonance: a cross-channel feedback loop (input_L = in1 + fb_R·feedback, input_R = in2 + fb_L·feedback) sustains the ring across the stereo pair.
  • Excitation: pre-weighted white noise, low-passed as a function of density.
  • Modulation: density → cutoff; volatility → feedback gain, inversely (more volatility, less ring). The codebox exposes f0, Q and feedback as inlets; the metric-to-inlet mapping happens upstream.

Engine B: FM pad (dual-serial FM)

A stable, noise-excited "warm bell" pad, selected by the Slate theme and sent through the reverb. Its envelope structure comes from the jitter fix.

  • Topology: four operators in two independent serial chains, Op2 → Op1 (L) and Op4 → Op3 (R), at a 1:1 carrier:modulator ratio. An integer ratio puts each sideband on an integer multiple of f0, which gives a fully harmonic spectrum.
  • Excitation: fully external. in1/in2 carry market_volume-weighted noise that is never summed into the output; it drives the modulation-index envelope and the feedback path, the way excitation drives the delay line in Karplus-Strong. When the noise drops to zero, energy already in the system keeps decaying by the coefficient from in4, which gives a physical tail.
  • Modulation index: floor 0.35 plus an envelope component, hard-clamped at 2.55. At 1:1, indices above ~4-5 collapse the spectrum into buzz.
  • Envelopes: 15 ms follower → amplitude, 40 ms follower → index.
  • Stereo width: symmetric detune up to ±1.5 Hz between the carrier chains (≈ 3 Hz beat), a slow chorus-like movement below the point where it would read as inharmonicity.
  • Decay: a leaky integrator on the output models a K-S-like tail after the excitation stops.
  • Modulation: density → noise low-pass and detune rate; volatility → leaky-integrator feedback, inversely (more volatility, shorter tail).
  • Note from the source: the codebox has no oversampling, and the conservative index keeps FM products clear of Nyquist. Pushing f0 past ~1-2 kHz would require 2× oversampling at the patcher level.

Engine C: Bowed string (resonant waveguide)

A continuously excited Karplus-Strong waveguide, the only string-like voice in the set. It is selected by the Bone theme and sent through the reverb. The stability analysis is in the waveguide bug section.

  • Topology: a tuned delay line (length sr / f0, fractional, 2-tap linear FIR interpolation) with filtered feedback; external noise is injected continuously into the loop.
  • Damping: a fixed-coefficient averaging filter 0.5·(x[n] + x[n−1]) (zero at Nyquist), classic K-S, frequency-invariant. The two density-controlled excitation stages (brightness LP, resonant comb) are feedforward and sit outside the loop, because anything inside it is part of the stability argument.
  • Transitions: a linear crossfade (XFADE_SAMPLES = 480) on real jumps of the fundamental removes phase clicks caused by delay-buffer discontinuities.
  • Note from the source: not verified empirically in this context, since no RNBO runtime was available when it was written. Linear delay interpolation has a less flat high-frequency phase response than an allpass and is intrinsically stable, which matters in a loop whose stability was the original problem.

Reverb: Schroeder-Moorer

Slate (FM pad) and Bone (bowed string) go through the reverb; Graphite (glassarmonica) does not. The glassarmonica sustains itself through its own cross-channel feedback and is the dry, close voice of the set.

  • Topology: 4 parallel combs and 2 cascaded allpasses per channel, with in-loop damping.
  • Decorrelation: coprime comb lengths, different for L and R, to maximize echo density without audible periodicity. Lengths are specified in samples at 48 kHz and rescaled by sr / 48000 to keep the time ratios at other sample rates.
  • Decay law: g = 10^(−3·d / (RT60·sr)), which reaches −60 dB at t = RT60. A one-pole LPF in each comb loop (damping) models the faster high-frequency absorption of real materials.
  • Allpass: y[n] = −g·x[n] + x[n−d] + g·y[n−d], g = 0.6 (within [0.5, 0.7], for stability and echo density without metallic colouration).
  • Wet/dry: a linear crossfade. The reverb is additive and the dry and wet signals are decorrelated, so a linear crossfade doesn't produce the loudness dip that equal-power curves are meant to fix.
  • volatility → RT60, inversely. A calm market gets the longer tail, and the space contracts as volatility rises. Traced through the patch, the range is 3.25 s → 2.50 s on Slate and 1.75 s → 1.50 s on Bone, across the full normalized range of the metric. A volatile market already produces events quickly, and a long tail would blur them together; in a quiet market the longer tail fills the gaps, so the display doesn't fall silent between events.
  • density → damping (how fast the highs die inside the tail). The coefficient runs 0.2 → 1.0 across the metric's range, from a bright, near-metallic tail to a dark one. Since density is the inter-onset interval in ms, its value runs inverse to market activity: a tight trade flow gives a small value and a brighter tail.
  • Send levels: Slate is fully wet (mix = 1.0), Bone is at 0.8, and predelay is 0 on both. The FM pad has no dry path, which is why the PM-index jitter was heard there first and loudest.

Reverb time and high-frequency absorption are heard as properties of the room around a sound. Listeners notice a change of room without attending to it, and the interface never points it out. Placing volatility and density on these two attributes gives a state cue that costs no attention, unlike foreground cues such as pitch. The swing is kept narrow (0.75 s of RT60 on Slate, well short of what the topology could reach) because once a change of space is recognizable as an effect, it starts competing for attention.


Limits

  • The evaluation is a pilot: n = 5, ~20 minutes, friends, unblinded, no task and no control condition, plus ~4 hours of self-use by the author (see Listening sessions). These sessions cannot test the project's central claim about fatigue.
  • The display is not self-explanatory. A listener with no market model could not connect pitch movement to price movement. The display provides a cue and assumes the listener already knows what a price move means. The app has no onboarding or training mode.
  • Two performance figures are missing. outputLatency could not be measured headless, so the hardware side of the audio path is unquantified, and an offline render shows throughput without proving that the audio thread meets its deadline under load. The other figures in Performance come from one machine and are indicative.
  • The seamless switch runs three engines for one audible voice (by design). At 3.2% of a core this is cheap; on hardware an order of magnitude weaker it would be significant, and the always-on banks are what keep the switch inaudible.
  • Engine C has not been run against an RNBO runtime. Its stability argument is analytic.
  • The adaptive scale gives up absolute comparability. The display is a change detector by design, and this is its main limitation.
  • The order-flow cue doesn't survive mono. Single-earbud or mono-summed playback loses the most important signal in the display, and there is no redundant encoding.
  • Two normalizers, in RNBO and in OutputScope, implement the same idea separately and can disagree.
  • There is no test framework and no CI. npm run check (svelte-check, strict) is the only automated gate, which is thin coverage for a project whose correctness is largely audible.
  • Binance aggTrade only: one venue, one stream type, no order-book depth, no cross-venue aggregation. Depth would be the most informative missing metric and is out of scope.

Tech stack

SvelteKit Svelte RNBO Vite Tauri License

Layer Technology
Frontend / orchestration SvelteKit 2, Svelte 5 (+page.svelte as orchestrator)
Audio engine RNBO web export via @rnbo/js 1.3.4, loaded from static/DSP.export.json
Data layer TypeScript Web Worker (crypto.worker.ts): Binance WebSocket + metric computation
Audio I/O and monitoring Web Audio API used directly: AudioContext + AnalyserNode
Build tool Vite 6, with a custom sync-dsp plugin
Desktop shell Tauri 2 (Rust); the frontend also runs as a plain web app in development
Dev server Fixed port 1420 (strictPort: true, required by tauri dev)

Project structure

SoniChain/
├── src/
│   ├── routes/
│   │   ├── +page.svelte          # Orchestrator: hosts the RNBO device, wires worker → setRnboParam
│   │   └── +layout.ts            # Disables SSR globally (SPA mode for Tauri)
│   ├── components/
│   │   ├── AudioControls.svelte  # Volume fader, asset / scale / sensitivity selectors, play/pause
│   │   ├── CryptoChart.svelte    # Price history chart with musical-note overlay
│   │   └── OutputScope.svelte    # AnalyserNode-backed scope / goniometer / dB meters
│   ├── RNBO/
│   │   ├── DSP1.json             # Authoring-side RNBO export (source of truth for the DSP)
│   │   ├── DSP1.license
│   │   └── dependencies.json
│   ├── crypto.worker.ts          # Binance WebSocket + microstructure metric computation
│   ├── themes.ts                 # Three themes (graphite / slate / bone) as CSS vars + canvas hex
│   ├── help.ts                   # Contextual help-bubble store + Svelte `help` action
│   └── app.html                  # SPA HTML shell
├── static/
│   └── DSP.export.json           # Runtime device, synced from src/RNBO/DSP1.json; do not edit
├── src-tauri/
│   ├── src/
│   │   ├── main.rs               # Tauri entry point
│   │   └── lib.rs                # Tauri commands
│   ├── tauri.conf.json           # Window config: 800×600, title "SoniChain"
│   ├── Cargo.toml
│   ├── build.rs
│   └── capabilities/             # Tauri v2 security capabilities
├── vite.config.js                # Vite 6 config + sync-dsp plugin + strictPort 1420
└── package.json

Selecting a theme also selects the engine: THEME_INSTRUMENT in +page.svelte maps each theme to an RNBO instrument value, so the theme picker is the engine selector. Visual and sonic character share one control, so they always match.


Getting started

Prerequisites

  • Node.js ≥ 20 (required by Vite 6 / SvelteKit 2) and a package manager (npm / pnpm).
  • Rust (stable) and the Tauri 2 platform prerequisites listed in the Tauri prerequisites guide, for the desktop build only.
  • A network connection for the Binance WebSocket feed. No API credentials are needed: the app uses public market streams only.

Installation

git clone https://github.com/BitResonant/SoniChain.git
cd SoniChain
npm install

Development

npm run dev          # plain web app, fixed port 1420
npm run tauri dev    # inside the Tauri desktop shell

Build

npm run build        # web build
npm run preview      # serve the production build locally
npm run tauri build  # native desktop bundle

Type-checking

npm run check        # svelte-kit sync + svelte-check (strict TypeScript)
npm run check:watch  # same, in watch mode

This is the only automated correctness gate; run it after any TypeScript or Svelte change.


DSP sync workflow

The RNBO patch is authored as src/RNBO/DSP1.json and loaded at runtime from static/DSP.export.json. A custom Vite plugin, sync-dsp, keeps the two in step:

  • On buildStart, it copies src/RNBO/DSP1.json → static/DSP.export.json.
  • During dev, it watches the source and, on change, re-copies it and triggers a full page reload so the new device loads immediately. The page fetches it with a cache-busting ?v=<timestamp> query.

To edit the DSP, change the patch in RNBO and re-export to src/RNBO/DSP1.json. static/DSP.export.json is generated, and hand edits there are overwritten on the next build. Without the plugin the two files drift apart, and the result looks like a DSP bug.


Market data feed

Market data comes from Binance's <symbol>@aggTrade WebSocket stream, consumed in crypto.worker.ts, which reconnects with a 3 s backoff on close. The worker computes the five microstructure metrics off the main thread and posts them to the page as TICK events.

The worker is hardened against what the stream actually sends: malformed JSON frames are caught and dropped, a non-finite price ends the tick, and market_volume is coerced to a finite number. In an audio pipeline a single NaN propagates into an RNBO parameter and audibly breaks the output.


License

SoniChain is released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0). You may share and adapt the material for non-commercial purposes as long as you credit Matteo Caruso Linardon, link back to the license, and distribute any derivative work under the same terms. Full terms are in the LICENSE file in the repository root.

The RNBO-generated DSP export (src/RNBO/DSP1.json and static/DSP.export.json) is machine-generated by Cycling '74's Max/RNBO export tool and is licensed separately under the terms in src/RNBO/DSP1.license. The CC BY-NC-SA grant above does not cover it.


SoniChain, BitResonant

About

A real-time synthesis engine that turns live crypto order flow into sound. Trades stream in from Binance over WebSocket, get reduced to five microstructure metrics off the main thread, and drive three noise-excited synthesis engines.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages