Chapter 1 • Part 1.2 • Visual & Mathematical Representations

Data Representation & Charts: Line, Candlestick (OHLCV), Kagi & Exhaustive Market Symbol Breakdown

Raw market data arrives from the exchange as a continuous, asynchronous stream of discrete execution messages (trade prints) and order book modifications. For both quantitative algorithms and human researchers, aggregating this raw stream into structured time-series is a foundational step. The specific method of data discretization — whether driven by calendar time or purely by price excursion — exerts a massive influence on systematic signal efficacy.

1. Temporal vs Non-Temporal Market Data Discretization

Conventional chartists assume clock time is the natural \(X\)-axis of market observation. In quantitative microstructure and high-frequency trading (HFT), however, two fundamentally divergent approaches to discretization exist:

Time-Based Sampling (Calendar Bars)

Examples: 1-second, 1-minute, 1-hour, daily bars.

Data is sampled at fixed time increments \(\Delta t\). The primary flaw is that market activity is non-uniform across time. During the morning opening cross, 100,000 trades may execute within a single minute, whereas during midday lull, only 500 occur. Fixed-time bars undersample information during high volatility and oversample pure noise during quiet intervals.

Information-Driven Sampling (Non-Temporal)

Examples: Kagi, Renko, Tick Bars, Volume Bars, Dollar Bars.

New observations are minted strictly when an authentic information event transpires — such as a price reversal exceeding a threshold (Kagi), exactly 1,000 trade prints occurring (Tick Bar), or $10,000,000 in nominal value exchanging hands (Dollar Bar). These bars restore Gaussian normality properties to return distributions, stabilizing machine learning models.

2. Line Charts: Mathematics, Advantages & Hidden Backtesting Traps

A Line Chart is the oldest and simplest visual representation of time series. It connects closing prices (\(P_{close}\)) across consecutive discrete epochs \(t_1, t_2, \dots, t_n\) via linear piecewise interpolation:

$$P(t) = P(t_i) + \frac{t - t_i}{t_{i+1} - t_i} \left( P(t_{i+1}) - P(t_i) \right), \quad t \in [t_i, t_{i+1}]$$

Utility of Line Charts

  • Macro Clarity: Provides immediate global trend overview free of granular intraday noise.
  • Statistical Cointegration: In statistical arbitrage and pairs trading models (e.g. testing the spread between two cointegrated stocks), computations routinely operate directly on log-close time series \(\ln(Close)\).

The Fatal Backtesting Flaw: Intra-Bar Ignorance

A line chart completely discards what transpired within the interval (the intraday High and Low). Consider a daily bar where a stock opened at $100, rallied to a High of $108, collapsed to a Low of $91, and closed at $101:

Why Line Charts Invalidate Backtests: If your trading algorithm had an active Stop-Loss order placed at $95, an evaluation based on the line chart (which only sees Close $101) would report that the position stayed green and profitable all day. In real live trading, however, the intraday dip to $91 would have triggered an instant stop-out, locking in a substantial loss. Backtests that evaluate stops on close-only data suffer from severe lookahead and survivor bias.

3. Candlestick Charts (OHLCV): Anatomy, Spans & Formal Definitions

Developed in the 18th century by Japanese rice merchant Munehisa Homma and introduced to Western finance by Steve Nison in 1991, Japanese Candlesticks compress five dimensions of market reality into every single bar: Open (O), High (H), Low (L), Close (C), and Volume (V).

Candlestick Anatomy: Bullish vs Bearish Comparison

BULLISH CANDLE High (H) Close (C) Real Body Open (O) Low (L) Close > Open BEARISH CANDLE High (H) Open (O) Real Body Close (C) Low (L) Close < Open Diagram: Comparative anatomy of Bullish (Close > Open) and Bearish (Close < Open) candlesticks
  • Real Body: The rectangular zone bounded by Open and Close. When \(Close > Open\), the bar is bullish (green/white). When \(Close < Open\), the bar is bearish (red/black).
  • Upper Shadow / Wick: The vertical line connecting the bar High to \(\max(Open, Close)\). Represents the price zone where aggressive sellers rejected higher pricing.
  • Lower Shadow / Wick: The line connecting \(\min(Open, Close)\) to the bar Low. Represents the zone where buyers stepped in to reject lower valuations.
  • Volume: Total contracts, shares, or coins matched during the candle period. Price movement unsupported by volume is statistically suspect.

Formal Candlestick Metrics for Algorithmic Feature Engineering

Machine learning models require scale-invariant, normalized dimension ratios rather than nominal point values:

Total Candle Range:
$$TR_t = High_t - Low_t$$
Absolute Body Size:
$$Body_t = |Close_t - Open_t|$$
Upper Wick Ratio:
$$UWR_t = \frac{High_t - \max(Open_t, Close_t)}{High_t - Low_t + \epsilon}$$
Lower Wick Ratio:
$$LWR_t = \frac{\min(Open_t, Close_t) - Low_t}{High_t - Low_t + \epsilon}$$

4. Formalizing Classic Candlestick Patterns into Algorithmic Boolean Logic

Subjective definitions found in classic technical literature must be translated into rigorous mathematical inequalities for deterministic algorithmic execution:

Pattern Microstructure Meaning Algorithmic Mathematical Condition
Doji Market equilibrium, balance between buyers and sellers. Body / (High - Low) < 0.05
Real body occupies less than 5% of total bar range.
Hammer Bullish rejection of lower prices after a downward trend. LowerWick >= 2.0 * Body
UpperWick <= 0.10 * Body
Close > Low + 0.65 * (High - Low)
Shooting Star Bearish exhaustion and rejection of higher pricing after an uptrend. UpperWick >= 2.0 * Body
LowerWick <= 0.10 * Body
Close < Low + 0.35 * (High - Low)
Bullish Engulfing Green candle fully encloses preceding red body. Close[-1] < Open[-1] (prior is red)
Close[0] > Open[0] (current is green)
Open[0] <= Close[-1] and Close[0] >= Open[-1]
Marubozu Pure directional dominance with zero or negligible wicks. Body / (High - Low) >= 0.95
Opened at absolute Low and closed at absolute High.

5. Kagi Charts: Reversal Thresholds, Yang/Yin Lines, Shoulders & Waists

Kagi charts (鍵, "key") originated in Japan circa 1870 with the launch of the Tokyo stock market. Kagi belongs to the class of non-temporal, path-dependent representations. The horizontal axis does not represent uniform time intervals — the series steps forward only when price direction reverses.

Algorithmic Mechanics of Kagi Step-by-Step

The trajectory of a Kagi chart is controlled by a single parameter — the Reversal Threshold, configured as either a fixed absolute dollar amount or a percentage of the prior price extremum:

  1. Trend Continuation: As long as price continues moving in the active direction, the vertical line simply extends. Small counter-trend oscillations smaller than the reversal threshold are completely discarded as sub-threshold noise.
  2. Reversal Event: To trigger a new vertical line in the opposite direction, price must reverse by at least the specified threshold:
    $$\Delta P_{reversal} \ge P_{extremum} \times Threshold$$
    When triggered, a horizontal inflection connector is drawn, and a new vertical line begins in the opposite direction.
  3. Line Weight Dynamics (Yang vs Yin):
    • Yang Line (Thick / Green): When an upward line penetrates the prior highest peak (termed the Shoulder), it instantly transforms into a thick Yang line, signaling dominant bullish regime.
    • Yin Line (Thin / Red): When a downward line breaks below the prior lowest trough (termed the Waist), it converts into a thin Yin line, signaling a bearish regime.
Kagi Anatomy: Yang/Yin Transitions, Shoulders & Waists
$103 $100 $96 $92 Waist 1 Yang Breakout Shoulder 1 Waist 2 Shoulder 2 (Higher High) Yin Breakdown Waist 3 (Lower Low) Kagi Legend: Yang (Thick Green) Bullish (Above Shoulder) Yin (Thin Red) Bearish (Below Waist) Reversal Threshold Filters Micro-noise Non-temporal Sampling
Yang Line Thick Green Line: Activated when price breaks above the previous Shoulder peak. Signifies dominant bullish market regime.
Yin Line Thin Red Line: Activated when price breaches below the prior Waist trough. Signifies a structural bearish trend.
Reversal Filter Threshold Constraint: Counter-trend swings smaller than the threshold (e.g. 2.0%) are ignored and generate zero horizontal steps.
Quantitative Value of Kagi:

Kagi charts act as a pure non-linear low-pass filter. They eliminate deceptive choppy whipsaws while preserving structural breakouts of significant market extremes. They are exceptionally potent in regime-switching algorithms and systematic trend-following architectures.

6. Alternative Smoothing Representations: Heikin-Ashi & Renko

Heikin-Ashi (Averaged Pace)

In Japanese, Heikin means "average" and Ashi means "pace". Heikin-Ashi synthesizes modified OHLC values by averaging past bars, dampening short-term noise:

$$HA_{Close} = \frac{Open + High + Low + Close}{4}$$
$$HA_{Open} = \frac{HA_{Open, -1} + HA_{Close, -1}}{2}$$
$$HA_{High} = \max(High, HA_{Open}, HA_{Close})$$
$$HA_{Low} = \min(Low, HA_{Open}, HA_{Close})$$

In a strong bullish trend, Heikin-Ashi bars display zero lower shadow. Critical Caveat for Execution: Heikin-Ashi prices are synthetic mathematical approximations! An algorithm must never route live limit orders using HA_Close as the limit price, as that price may never have existed on the exchange matching engine.

Renko Bricks (Non-Time-Based Noise Filtering & Trend Discretization)

Renko charts are among the most robust non-time-based tools for extracting persistent trend signals from noisy financial time-series. The name originates from the Japanese word renga (れんが), meaning brick. Like Kagi or Point & Figure charts, Renko completely eliminates the standard time dimension (\(\Delta t\)): a new brick is appended only when the underlying price moves by a predefined threshold, regardless of whether that progression takes 500 milliseconds or three consecutive trading days.

1. Selecting Brick Size (Box Size)

The box size \(B\) is the primary structural hyperparameter of the representation:

  • Fixed Dollar/Point Value: A constant threshold (e.g., \(B = \$1.00\) or \(B = \$2.50\)). Ideal for stationary intraday scalping and fixed-tick futures, but as an asset climbs from $100 to $500, the constant box size represents a 5x smaller percentage change, generating excessive bricks.
  • Dynamic ATR-Based Sizing: Box size dynamically scales with real-time market volatility via the Average True Range: \(B_t = ATR_{14}(t)\). The brick discretization naturally widens during high-volatility shocks, preventing algorithmic false breakouts.
$$B_{ATR} = \frac{1}{n}\sum_{i=1}^{n} \max(H_i - L_i, |H_i - C_{i-1}|, |L_i - C_{i-1}|)$$
2. The Two-Brick Reversal Rule

The defining asymmetry of Renko chart construction: continuing the active trend requires moving \(1 \times B\), whereas reversing direction requires price to clear at least \(2 \times B\) from the last brick's extreme!

$$\text{Bullish Continuation:} \quad P_{close} \ge P_{high, prev} + B$$ $$\text{Bearish Continuation:} \quad P_{close} \le P_{low, prev} - B$$ $$\text{Reversal Downward:} \quad P_{close} \le P_{low, prev} - 2B$$ $$\text{Reversal Upward:} \quad P_{close} \ge P_{high, prev} + 2B$$

This strict \(2B\) hurdle acts as a low-pass filter that shields automated execution logic from whipsaw losses in mean-reverting ranges.

Renko Anatomy (Fixed Box Size) & The Two-Brick Reversal Rule (2B Filter)
Model: Fixed-Size Renko
Important Methodological Note: This diagram and the 2-brick reversal rule model Fixed-Size Renko (constant box size where \(B = \$1.00 = \text{const}\)). In Dynamic Renko (ATR-based), the brick size \(B_t = ATR_{14}(t)\) continuously adapts to market volatility. In dynamic models, a reversal requires twice the current ATR value at that moment in time, meaning bricks in volatile regimes span wider price ranges than bricks during low-volatility consolidations.
$103 $102 $101 $100 $99 +1B Up +1B Up +1B Peak $103 B = $1 -1B Dip < 2B ignored! (Sub-threshold noise) 2B Drop ($2) -2B REVERSAL! -1B Down -1B Bottom $99 +2B +2B REVERSAL UP! Fixed Renko (B = $1.00): • Fixed size: B = const • Continuation: +1B in trend • Reversal: 2B counter-move • Clock time is eliminated • Shields against whipsaws Quant Model State: State: +1 (Bullish) Binary State Machine
+1 Box Size Trend Continuation: Adding another brick in the active direction requires price to move by precisely \(1 \times B\).
2B Reversal Hurdle Anti-Whipsaw Filter: A counter-move of 1B is ignored. Reversals strictly enforce a full \(2 \times B\) movement.
Fixed vs Dynamic Fixed Box vs ATR: Shown with constant \(B = \$1\). Dynamic ATR Renko scales brick height with market volatility.
3. Renko with Wicks vs. Classic Clean Bricks

Classic Renko: Discards intra-period price extremes entirely. Each block is drawn as a uniform geometric rectangle of height \(B\). This produces maximum visual clarity, but conceals liquidity rejection and false breakouts.

Renko with Wicks: Preserves the extreme intra-brick Highs and Lows. Prominent counter-trend wicks reveal aggressive limit order absorption and alert algorithms to imminent momentum exhaustion.

4. Algorithmic Modeling: Finite State Machines

For quantitative engines, Renko transforms continuous, noisy price streams into a discrete binary Markov state machine:

$$S_t \in \{+1 \text{ (Up Brick / Bullish State)}, -1 \text{ (Down Brick / Bearish State)}\}$$

Systematic strategies like Box-Breakout Momentum (entering after two consecutive confirmed bricks in the same direction) or Brick Trailing Stops operate with significantly reduced trade frequency and superior profit-to-turnover ratios.

Critical Quant Traps & Backtesting Hazards
1. Time Distortion (Irregular Sampling):

Bricks have non-constant durations (\(\Delta t \neq \text{const}\)). Classical statistical metrics like annualized Sharpe Ratio (\(\times \sqrt{252}\)) or autocorrelation functions assume uniform calendar time and produce heavily biased figures when applied to raw Renko series.

2. Gap Risk & Fill Assumptions:

Weekend gaps or major macro announcements can cause prices to skip 4 or 5 bricks instantly. Naive backtests assume perfect execution at each synthetic brick boundary, but real live orders fill at the market gap price, incurring severe slippage.

3. Lookahead Bias & In-Bar Sequences:

When Renko is built from aggregated 1-minute or daily OHLC bars rather than raw tick data, the true order of high and low hits is lost. This can synthesize non-existent profitable trades in simulations that collapse under live execution.

Chart Type Time Dependence Volume Representation Noise Sensitivity Algorithmic Suitability
Candlestick (OHLCV) Yes (Fixed Timeframe) Direct / Per-bar Histogram High (Captures tick/spread bounce) Limit order execution, microstructure, orderbook modeling
Heikin-Ashi Yes (Fixed Timeframe) Indirect / Smoothed Low (Exponentially filtered) Regime detection, signal smoothing (never for routing limit orders)
Kagi Chart No (Price Only) Accumulated per swing Very Low (Reversal threshold) Macro structural breakout, automated support/resistance identification
Renko Chart No (Discretized \(\Delta P = B\)) Aggregated per brick Minimal (Strict threshold stepping) State-machine trend following, volatility-adjusted trailing stops

7. Comprehensive Guide to Chart Symbols, Overlays & Indicators

Institutional trading interfaces and quant visualizers overlay several layers of mathematical metrics on the raw price canvas:

Volume Bars & Delta Volume

Plotted on the lower sub-chart. Bar height indicates total matched shares or contracts. Advanced desks monitor Delta Volume:

$$\Delta V = V_{Ask\ Buys} - V_{Bid\ Sells}$$

Positive delta signifies aggressive market buy orders lifting offers; negative delta denotes aggressive sellers hitting bids.

VWAP (Volume Weighted Average Price)

The quintessential institutional execution benchmark:

$$VWAP = \frac{\sum_{i=1}^n P_i \cdot V_i}{\sum_{i=1}^n V_i}$$

Institutional execution algorithms (such as TWAP and VWAP slicers) are evaluated against this metric. If a buy order executes below VWAP, it achieved positive execution alpha.

Moving Averages (SMA vs EMA)

Simple Moving Average (SMA): Unweighted mean of the last \(N\) periods: \(SMA_N = \frac{1}{N}\sum P_i\).

Exponential Moving Average (EMA): Weights recent observations exponentially using smoothing constant \(\alpha = \frac{2}{N+1}\): $$EMA_t = \alpha P_t + (1 - \alpha) EMA_{t-1}$$

Order Flow Footprints & Liquidity Clusters

Footprint charts render inside the candle, displaying exact executed volumes matched at every tick level: Bid_Vol x Ask_Vol.

Quant engines analyze footprints to detect institutional absorption (massive passive limit orders soaking aggressive market flow) and exhaustion.

8. Practical Python Implementation: Tick Aggregation & Kagi Line Generator

The following production Python script converts high-frequency trade prints into standardized OHLCV bars and implements the Kagi series construction algorithm:

"""
TradQor Academy - Tick to OHLCV Aggregator & Kagi Line Generator
Demonstrates converting raw market execution ticks into OHLCV bars and building Kagi series.
"""

import numpy as np
import pandas as pd

def generate_synthetic_ticks(n=5000):
    """Generates realistic synthetic trade ticks with millisecond timestamps"""
    np.random.seed(42)
    start_time = pd.Timestamp("2026-03-01 09:30:00")
    time_deltas = pd.to_timedelta(np.random.exponential(scale=50, size=n), unit='ms')
    timestamps = start_time + time_deltas.cumsum()

    price_changes = np.random.normal(loc=0.001, scale=0.15, size=n)
    prices = 100.0 + np.cumsum(price_changes)
    sizes = np.random.randint(10, 500, size=n)

    df_ticks = pd.DataFrame({'timestamp': timestamps, 'price': prices, 'size': sizes})
    return df_ticks

def aggregate_to_ohlcv(df_ticks, timeframe='1min'):
    """Resamples ticks into standard OHLCV candle bars"""
    df_ohlcv = df_ticks.set_index('timestamp').resample(timeframe).agg({
        'price': ['first', 'max', 'min', 'last'],
        'size': 'sum'
    }).dropna()

    df_ohlcv.columns = ['open', 'high', 'low', 'close', 'volume']
    return df_ohlcv

def build_kagi_series(closes, reversal_pct=1.5):
    """
    Kagi Algorithm: Computes reversal points, shoulders, waists,
    and Yang (bullish) / Yin (bearish) state transitions.
    """
    points = []
    trend = 0 # 1 = up, -1 = down
    last_extreme = closes.iloc[0]
    prior_high = last_extreme
    prior_low = last_extreme
    is_yang = True

    points.append({'price': last_extreme, 'yang': is_yang, 'type': 'start'})

    for price in closes.iloc[1:]:
        threshold = (last_extreme * reversal_pct) / 100.0

        if trend == 0:
            if price >= last_extreme + threshold:
                trend = 1
                last_extreme = price
                prior_high = price
                points.append({'price': price, 'yang': is_yang, 'type': 'shoulder'})
            elif price <= last_extreme - threshold:
                trend = -1
                last_extreme = price
                prior_low = price
                is_yang = False
                points.append({'price': price, 'yang': is_yang, 'type': 'waist'})
        elif trend == 1:
            if price > last_extreme:
                last_extreme = price
                if price > prior_high and not is_yang:
                    is_yang = True # Flipped to Yang
                prior_high = max(prior_high, price)
                points[-1] = {'price': price, 'yang': is_yang, 'type': 'shoulder'}
            elif price <= last_extreme - threshold:
                trend = -1
                last_extreme = price
                if price < prior_low:
                    is_yang = False # Flipped to Yin
                prior_low = min(prior_low, price)
                points.append({'price': price, 'yang': is_yang, 'type': 'waist'})
        elif trend == -1:
            if price < last_extreme:
                last_extreme = price
                if price < prior_low and is_yang:
                    is_yang = False
                prior_low = min(prior_low, price)
                points[-1] = {'price': price, 'yang': is_yang, 'type': 'waist'}
            elif price >= last_extreme + threshold:
                trend = 1
                last_extreme = price
                if price > prior_high:
                    is_yang = True
                prior_high = max(prior_high, price)
                points.append({'price': price, 'yang': is_yang, 'type': 'shoulder'})

    return pd.DataFrame(points)

def build_renko_series(closes, brick_size=2.0):
    """
    Renko Algorithm: constructs uniform price bricks (Box Size)
    and enforces the Two-Brick Reversal Rule.
    """
    bricks = []
    trend = 0  # 1 = up, -1 = down
    last_price = closes.iloc[0]

    for price in closes.iloc[1:]:
        if trend == 0:
            if price >= last_price + brick_size:
                trend = 1
                base = last_price
                last_price = base + brick_size
                bricks.append({'open': base, 'close': last_price, 'type': 'bullish'})
            elif price <= last_price - brick_size:
                trend = -1
                base = last_price
                last_price = base - brick_size
                bricks.append({'open': base, 'close': last_price, 'type': 'bearish'})
        elif trend == 1:
            # Bullish trend continuation
            while price >= last_price + brick_size:
                base = last_price
                last_price = base + brick_size
                bricks.append({'open': base, 'close': last_price, 'type': 'bullish'})
            # Bearish reversal: requires 2 x brick_size drop from last brick's peak
            if price <= (last_price - 2 * brick_size):
                trend = -1
                base = last_price - brick_size
                last_price = base - brick_size
                bricks.append({'open': base, 'close': last_price, 'type': 'bearish'})
                while price <= last_price - brick_size:
                    base = last_price
                    last_price = base - brick_size
                    bricks.append({'open': base, 'close': last_price, 'type': 'bearish'})
        elif trend == -1:
            # Bearish trend continuation
            while price <= last_price - brick_size:
                base = last_price
                last_price = base - brick_size
                bricks.append({'open': base, 'close': last_price, 'type': 'bearish'})
            # Bullish reversal: requires 2 x brick_size rise from last brick's trough
            if price >= (last_price + 2 * brick_size):
                trend = 1
                base = last_price + brick_size
                last_price = base + brick_size
                bricks.append({'open': base, 'close': last_price, 'type': 'bullish'})
                while price >= last_price + brick_size:
                    base = last_price
                    last_price = base + brick_size
                    bricks.append({'open': base, 'close': last_price, 'type': 'bullish'})

    return pd.DataFrame(bricks)

if __name__ == '__main__':
    ticks = generate_synthetic_ticks(10000)
    ohlcv = aggregate_to_ohlcv(ticks, '1min')
    kagi = build_kagi_series(ohlcv['close'], reversal_pct=1.0)
    renko = build_renko_series(ohlcv['close'], brick_size=1.5)
    print(f"Processed Ticks: {len(ticks):,} | OHLCV Bars: {len(ohlcv)} | Kagi Nodes: {len(kagi)} | Renko Bricks: {len(renko)}")
    print("\nFirst 5 Renko Bricks:")
    print(renko.head())

9. Interactive Laboratory: Multi-Chart Canvas Engine

Switch dynamically between representations of the exact same underlying synthetic price dataset. Observe how line charts discard volatility, Kagi removes time to isolate turning points, and Renko bricks discretize price motion into clean structural blocks:

Dynamic Multi-Chart Canvas
2.0 %
Increasing the threshold filters out minor counter-moves, retaining only primary macro trend reversals.
$2.00
Adjusting the brick size defines the price movement required to draw a new brick. Smaller bricks track granular micro-moves; larger bricks filter noise and expose macro trends.
Green candles represent net buying pressure; red candles indicate selling pressure. Lower histogram tracks underlying Volume Bars.
Most of the content is generated using AI, inaccuracies may occur