# Reactive Programming in Financial Markets
Introducing a reactive programming model for algorithmic operativity in global financial markets.
# Abstract
One of the most common challenges in data analysis and algorithmic trading within financial markets is maintaining accurate tracking of market prices and their derived data. This task is crucial for updating the logic and state of our program in response to the dynamic market conditions. In this context, the following example showcases a TypeScript implementation of a reactive method, which can be seamlessly adapted to other programming languages and technologies.
# Table of Contents
# Introduction
In the context of developing a trading system, which involves a trading bot executing a specific trading strategy, it becomes crucial to define the system's market entry and exit conditions. These conditions often rely on various data analysis procedures, including technical indicators, price action calculations, fundamental data analysis, and even machine learning algorithms.
The concept of a reactive programming model emerges as a solution to efficiently handle these conditions by employing isolated components that perform calculations based on the current market conditions. Each trading system entry condition, for instance, can have its own independent component that internally determines whether the condition is favorable or not. Importantly, these components are designed to automatically update as the market evolves, ensuring that the trading system remains responsive to real-time changes.
This approach enables the construction of a seamless trading system, akin to assembling Lego pieces, where each component plays a distinct role in the system's execution, resulting in a more cohesive and manageable trading strategy.
In short the benefits of a reactive model would be:
- Streamlined declarative implementations with reduced code complexity;
- Direct access to a centralized source of truth that automatically keeps data updated;
- Decreased maintenance requirements, thanks to the inherent reactivity of the model;
- Lower probability of introducing bugs, as reactive components enhance system reliability.
# Reactive Market Components
Finally, let's take a look at some code examples that demonstrate an existing implementation created using Mida, the engine designed for algorithmic trading in global financial markets.
TIP
A market component serves as a way to encapsulate logic and data that evolve in response to changes in the underlying market
The following example declares a component made of a
Relative Strength Index indicator and a isOverbought
property reactively updated.
import { marketComponent, } from "@reiryoku/mida";
// A reactive component detecting overbought markets
const OverboughtDetector = marketComponent({
indicators: {
myIndicator: {
type: "RSI", // Use Relative Strength Index indicator
options: { length: 14, }, // Use 14 periods
input: {
timeframe: MidaTimeframe.M30, // Use M30 candles
type: "close", // Use close prices
},
},
},
computed: {
// A variable responsive to market updates
isOverbought () {
return this.myIndicator.lastValue.greaterThan(80);
},
},
// A hook fired every market update (market ticks, closed candles...)
async update () {
console.log(this.isOverbought);
},
});
Now the component can be generated with a trading account and a market symbol.
const overboughtDetector = await OverboughtDetector(myAccount, "ETHUSD");
Components can be used for any logic and data dependent on a market state. For example, this is a simple market ticker.
- Example 1
import { marketComponent, } from "@reiryoku/mida";
// A component logging the market prices
const Ticker = marketComponent({
computed: {
spread () {
return this.$ask.sub(this.$bid);
},
},
async update () {
console.log(`Market price has changed for symbol ${this.$symbol}`);
console.log(`Bid price is ${this.$bid}`);
console.log(`Ask price is ${this.$ask}`);
console.log(`The spread is ${this.spread}`);
},
});
To get back, the final use case for market components would be implementing a trading strategy made of multiple independent market components.
- Example 2
import { marketComponent, MidaTimeframe, } from "@reiryoku/mida";
const TrendDetector = marketComponent({
indicators: {
sma5: {
type: "SMA",
options: { length: 5, },
input: {
timeframe: MidaTimeframe.H1,
type: "close",
},
},
sma15: {
type: "SMA",
options: { length: 15, },
input: {
timeframe: MidaTimeframe.H1,
type: "close",
},
},
},
computed: {
isBullish () {
return this.sma5.lastValue.greaterThan(this.sma15.lastValue);
},
},
async update () {
if (this.isBullish) {
console.log("SMA5 is above SMA15");
}
else {
console.log("SMA5 is below SMA15");
}
},
});
Finally, a trading system can be seen as a market component that relies on analysis components as dependencies. It utilizes these components to make informed decisions regarding market entry, exit, or staying idle.
- Example 3
import { marketComponent, } from "@reiryoku/mida";
const TradingSystem = marketComponent({
dependencies: {
overboughtDetector: OverboughtDetector,
trendDetector: TrendDetector,
},
// A hook fired every market update and after all the dependencies have completed their update cycle
async update () {
if (this.trendDetector.isBullish && !this.overboughtDetector.isOverbought) {
// Enter the market...
}
},
});
const mySystem = await TradingSystem(myAccount, "ETHUSD");
# Component Structure
# Market State
The this
of a market component assumes the state of the component which is composed by data such as computed
variables, indicators and methods, plus some builtin variables such as the current candles, bid and ask prices
of the market, which are self-updating in response to market updates.
- Interface
// The builtin market component variables
type MidaMarketComponentState = Record<string, any> & {
$component: MidaMarketComponent;
$dependencies: MidaMarketComponentState[];
$tradingAccount: MidaTradingAccount;
$watcher: MidaMarketWatcherDirectives;
$symbol: string;
$bid: MidaDecimal;
$ask: MidaDecimal;
$ticks: MidaTick[];
$periods: Record<string, MidaPeriod[]>;
$livePeriods: Record<string, MidaPeriod>;
$indicators: Record<string, any>;
};
# Market Update
The update()
hook is triggered by various market events, such as a market tick, the closing of a candle,
or the opening or closing of the market itself. Consequently, each market event corresponds to its own specific hook.
- Example
import { marketComponent, } from "@reiryoku/mida";
const Component = marketComponent({
async tick () {
// Fired when there is a market tick
},
async periodUpdate (period) {
// Fired when a last live candlestick is updated
},
async periodClose (period) {
// Fired when a candlestick is closed
},
// Furthermore, specific timeframes can be targeted
async periodClose$M15 (period) {
// Fired when a M15 candlestick is closed
},
async marketOpen () {
// Fired when the market opens
},
async update () {
// Fired when there is any market update of the above
},
});
# Dependencies
Dependencies play a fundamental role in market components. In this context, all market updates are first delivered to the dependencies. As a result, a component is updated only after all its dependencies have been updated.
- Example
import { marketComponent, } from "@reiryoku/mida";
// A component logging the market prices
const Component = marketComponent({
dependencies: {
overboughtDetector: OverboughtDetector,
},
// Fired every market update and after the dependency has completed its update cycle
async update () {
console.log(this.overboughtDetector.isOverbought);
},
});
# Conclusion
In conclusion, algorithmic trading in global financial markets would benefit greatly from the adoption of a reactive programming model. For those familiar with Vue.js or Unity3D, I drew inspiration from my experience with these frameworks, applying their principles to the unique challenges of financial markets and programming. The traditionally closed and proprietary nature of both fields makes this publication all the more valuable, I hope it serves to inspire others for future projects.