TTM Trend

Parameters: period = 5

Overview

TTM Trend provides a simple yet effective binary trend classification by comparing the closing price to the average of a selected price source over a rolling window. The indicator returns true when price trades above this moving average and false when below, creating clear trend direction signals without the ambiguity of scaled oscillators. By defaulting to the hl2 price (average of high and low) rather than close alone, the indicator incorporates intrabar price action for more robust trend identification. This boolean output makes TTM Trend particularly valuable for algorithmic trading systems and backtesting, where clean true/false signals simplify logic and decision trees. The indicator filters much of the noise inherent in raw price data while remaining responsive enough to catch trend changes relatively early. Traders often use it as a directional filter, taking only long trades when the trend is true and short trades when false. Default parameters use a 5 period window with hl2 as the price source, optimized for responsive yet stable trend detection.

Implementation Examples

Compute TTM Trend from slices or candles:

use vectorta::indicators::ttm_trend::{ttm_trend, TtmTrendInput, TtmTrendParams};
use vectorta::utilities::data_loader::{Candles, read_candles_from_csv};

// Using with source/close slices
let source = vec![/* e.g., hl2 values */];
let close = vec![/* close prices */];
let params = TtmTrendParams { period: Some(5) }; // default: 5
let input = TtmTrendInput::from_slices(&source, &close, params);
let output = ttm_trend(&input)?; // output.values: Vec<bool>

// Using with Candles (default source="hl2")
let candles: Candles = read_candles_from_csv("data/sample.csv")?;
let input = TtmTrendInput::with_default_candles(&candles);
let output = ttm_trend(&input)?;

API Reference

Input Methods
// From candles with custom source
TtmTrendInput::from_candles(&Candles, &str, TtmTrendParams) -> TtmTrendInput

// From source/close slices
TtmTrendInput::from_slices(&[f64], &[f64], TtmTrendParams) -> TtmTrendInput

// From candles with defaults (source="hl2", period=5)
TtmTrendInput::with_default_candles(&Candles) -> TtmTrendInput
Parameters Structure
pub struct TtmTrendParams {
    pub period: Option<usize>, // Default: 5
}
Output Structure
pub struct TtmTrendOutput {
    pub values: Vec<bool>, // true if close > rolling average, else false
}
Validation, Warmup & NaNs
  • period > 0; otherwise TtmTrendError::InvalidPeriod.
  • period must not exceed available data length; otherwise TtmTrendError::InvalidPeriod.
  • There must be at least period valid points after the first finite pair of source/close; otherwise TtmTrendError::NotEnoughValidData.
  • Warmup: indices before first + period - 1 are false (no value yet). Streaming returns None until filled.
  • If writing into a preallocated slice, output length must equal min(source.len(), close.len()), else TtmTrendError::OutputLenMismatch.
Error Handling
use vectorta::indicators::ttm_trend::{ttm_trend, TtmTrendError};

match ttm_trend(&input) {
    Ok(output) => process(output.values),
    Err(TtmTrendError::AllValuesNaN) =>
        eprintln!("All values are NaN"),
    Err(TtmTrendError::InvalidPeriod { period, data_len }) =>
        eprintln!("Invalid period {} for length {}", period, data_len),
    Err(TtmTrendError::NotEnoughValidData { needed, valid }) =>
        eprintln!("Need {} valid points, got {}", needed, valid),
    Err(TtmTrendError::OutputLenMismatch { expected, got }) =>
        eprintln!("Output length mismatch: expected {}, got {}", expected, got),
    Err(TtmTrendError::InvalidKernel) =>
        eprintln!("Invalid kernel type for batch operation"),
}

Python Bindings

Basic Usage

Calculate TTM Trend using NumPy arrays:

import numpy as np
from vectorta import ttm_trend

# Prepare source (e.g., hl2) and close arrays
source = np.array([...], dtype=np.float64)
close = np.array([...], dtype=np.float64)

# Compute with explicit period (default is 5 in Rust)
vals = ttm_trend(source, close, period=5, kernel="auto")

# vals is a NumPy float64 array with NaN during warmup, then 0.0/1.0
print(vals)
Streaming Real-time Updates

Process source/close updates efficiently:

from vectorta import TtmTrendStream

stream = TtmTrendStream(period=5)
for s, c in zip(source_stream, close_stream):
    v = stream.update(s, c)
    if v is not None:
        # v is a Python bool
        handle(v)
Batch Parameter Sweep

Run many periods at once and inspect results:

import numpy as np
from vectorta import ttm_trend_batch

source = np.array([...], dtype=np.float64)
close = np.array([...], dtype=np.float64)

res = ttm_trend_batch(source, close, period_range=(5, 30, 5), kernel="auto")
print(res["values"].shape)  # (num_periods, len(source))
print(res["periods"])       # list of tested periods
CUDA Acceleration

CUDA support for TTM Trend is currently under development. The API will follow the same pattern as other CUDA-enabled indicators.

# Coming soon: CUDA-accelerated TTM Trend calculations
# Expected API will mirror other indicators once available.

JavaScript/WASM Bindings

Basic Usage

Compute TTM Trend in the browser using WASM:

import { ttm_trend_js } from 'vectorta-wasm';

const source = new Float64Array([/* e.g., hl2 values */]);
const close = new Float64Array([/* close prices */]);
const period = 5;

// Returns Float64Array with NaN in warmup, then 0.0/1.0
const values = ttm_trend_js(source, close, period);
Memory-Efficient Operations

Use zero-copy style operations with explicit memory management:

import { ttm_trend_alloc, ttm_trend_free, ttm_trend_into, memory } from 'vectorta-wasm';

const len = source.length;
const srcPtr = ttm_trend_alloc(len);
const clsPtr = ttm_trend_alloc(len);
const outPtr = ttm_trend_alloc(len);

new Float64Array(memory.buffer, srcPtr, len).set(source);
new Float64Array(memory.buffer, clsPtr, len).set(close);

// Compute directly into pre-allocated output
ttm_trend_into(srcPtr, clsPtr, outPtr, len, period);

const result = new Float64Array(memory.buffer, outPtr, len).slice();

ttm_trend_free(srcPtr, len);
ttm_trend_free(clsPtr, len);
ttm_trend_free(outPtr, len);
Batch Processing

Run multiple periods in one call:

import { ttm_trend_batch } from 'vectorta-wasm';

const config = { period_range: [5, 30, 5] }; // start, end, step
const out = ttm_trend_batch(source, close, config);

// out.values is a flat array (f64) with 0.0/1.0 values
// out.periods lists tested periods; out.rows, out.cols give shape
console.log(out.rows, out.cols, out.periods);

Performance Analysis

Comparison:
View:
Loading chart...

AMD Ryzen 9 9950X (CPU) | NVIDIA RTX 4090 (GPU) | Benchmarks: 2026-01-05

Related Indicators