Hub style indicators for advanced streaming
Stream hubs calculate indicators in real time. You add bars to one BarHub, and every indicator hub subscribed to it updates automatically, including when a bar arrives late or is revised.
When to use stream hubs
Use stream hubs when any of these apply:
- Several indicators share one live feed
- An indicator is calculated from another indicator, such as RSI of EMA
- Bars can arrive out of order, be revised, or be removed
- The current bar is still forming and changes on every tick
For one indicator over bars that always arrive in order, a Buffer list is simpler. For a one-time calculation over history, use Batch style. To see how per-bar cost compares with re-running a Series method, see Bars that arrive one at a time.
Basic usage
Create a bar hub, subscribe indicator hubs to it, and add bars as they arrive:
using FacioQuo.Stock.Indicators;
// the data source
BarHub barHub = new();
// indicator hubs subscribe to the bar hub
SmaHub smaHub = barHub.ToSmaHub(20);
RsiHub rsiHub = barHub.ToRsiHub(14);
// call from your feed's message handler as each bar arrives
void OnBarReceived(Bar bar)
{
barHub.Add(bar);
RsiResult rsi = rsiHub.Results[^1];
if (rsi.Rsi > 70)
{
Console.WriteLine($"{bar.Timestamp:d}: Overbought at {bar.Close:C2}");
}
}When Add returns, every subscribed hub has already updated, so you can read Results right away. Single-input indicator hubs like these hold one result per bar; two-series hubs, RenkoHub, and aggregator hubs can hold fewer or more results than bars. Values are null until the indicator has enough bars to warm up; each indicator's page lists its warmup period.
Prior bars (optional)
A hub works from its first bar, with no history required; its values are simply null until the warmup period has passed. If you already have earlier bars, you can add them before live bars arrive, so values are available sooner:
BarHub barHub = new();
// optional: add earlier bars, in one call or one at a time
barHub.Add(historicalBars);
// a hub created after bars are added calculates over them at once
RsiHub rsiHub = barHub.ToRsiHub(14);
// add live bars as they arrive
barHub.Add(liveBar);Adding a collection gives the same results as adding its bars one at a time, and you can subscribe hubs before or after adding them.
Update the current bar
Add a bar with the same Timestamp as one the hub already holds to replace it. Use this to update the bar that is still forming as each tick arrives:
// each tick revises the one-minute bar that is still forming
barHub.Add(new Bar(minuteStart, open, high, low, lastPrice, volume));Every subscribed hub recalculates from that bar forward. A bar that arrives late, with a timestamp earlier than the newest bar, is inserted in time order and recalculated the same way. To remove bars, or to handle bars the hub refuses, see Corrections and memory.
Chaining indicators
Subscribe one indicator hub to another to calculate an indicator from another indicator's results. For the broader concept, see Chaining indicators.
BarHub barHub = new();
// RSI of EMA
EmaHub emaHub = barHub.ToEmaHub(20);
RsiHub rsiOfEma = emaHub.ToRsiHub(14);
// or in one expression
RsiHub rsiHub = barHub
.ToEmaHub(20)
.ToRsiHub(14);
// adding a bar updates the EMA, then the RSI
barHub.Add(newBar);Two-series indicators
A two-series hub observes two providers, such as two indicators of one BarHub or two BarHub feeds:
BarHub barHub = new();
// spread between a fast and a slow moving average
PairMathHub spread = barHub
.ToEmaHub(12)
.Minus(barHub.ToEmaHub(26));A result is added once both providers hold the same timestamp. A timestamp that only one provider holds produces no result, where the Series method throws. Late, revised, or removed values on either side are recalculated like any other correction.
Two-series stream hubs (choose Stream on each page for its example):
- IndyMath two-series methods, such as
.Minus(otherSource) - Beta coefficient (β)
- Correlation coefficient
- Price Relative Strength (PRS)
Live feeds and threads
🚩 Data corruption risk
A hub is not safe for concurrent use. If two threads add bars to the same hub at the same time, its results can be corrupted without any error. Add bars from one thread at a time, as shown below; see Threading and live feeds for the full rules.
A client that you read in a loop, such as .NET's ClientWebSocket, receives one message at a time, so you can call Add directly with nothing more:
// your own loop that reads and parses each message
await foreach (Bar bar in ReadBarsAsync(socket, cancellationToken))
{
barHub.Add(bar);
}You need more only when bars reach the hub from several threads at once, such as a client library that raises message events on different threads, or several connections feeding one hub. In that case, put a lock around Add, or write bars to a feed, which queues them and adds them one at a time. To read results on a different thread from the one adding bars, use Snapshot(), or read under the same lock. Threading and live feeds covers each option.
If your data source delivers trade ticks, or smaller bars than you want to analyze, combine them into larger bars with a streaming aggregator hub and subscribe your indicator hubs to it.
Cache size
Each hub keeps up to 100,000 results by default and drops the oldest when it exceeds that. To use less memory, set a smaller maxCacheSize on the bar hub; every hub subscribed to it uses the same size.
BarHub barHub = new(maxCacheSize: 1_000);
RsiHub rsiHub = barHub.ToRsiHub(14);A hub throws ArgumentOutOfRangeException when it is created if the size is too small for its warmup. After you create your hubs, barHub.MinCacheSize reports the smallest size the whole chain needs. Keep the cache larger than the history you read or might correct; see Cache size and pruning.
Stop streaming
// stop one indicator; the others keep updating
smaHub.Unsubscribe();
// end the stream: every hub in the chain stops updating
barHub.EndTransmission();A stopped hub keeps its Results, which you can still read.
Example: moving average crossover
BarHub barHub = new();
// optional: earlier bars, so the 200-period EMA has values sooner
barHub.Add(historicalBars);
EmaHub fastEma = barHub.ToEmaHub(50);
EmaHub slowEma = barHub.ToEmaHub(200);
void OnBarReceived(Bar bar)
{
barHub.Add(bar);
// a crossover needs two results
if (fastEma.Results.Count < 2)
{
return;
}
EmaResult fastPrior = fastEma.Results[^2];
EmaResult slowPrior = slowEma.Results[^2];
EmaResult fastNow = fastEma.Results[^1];
EmaResult slowNow = slowEma.Results[^1];
// comparisons with null (during warmup) are false
if (fastPrior.Ema < slowPrior.Ema && fastNow.Ema > slowNow.Ema)
{
Console.WriteLine($"{bar.Timestamp:u}: fast EMA crossed above slow EMA");
}
}See also
- Threading and live feeds for multi-threaded feeds, feed options, and reading results across threads
- Corrections and memory for removing bars, refused bars, cache sizing, and fault recovery
- Custom observers for pushing results into a UI, database, or alerting pipeline
- Streaming aggregator hubs for combining ticks or bars into larger bars in real time
- Buffer lists for simple incremental processing
- Indicators for available stream hub indicators