Midprice Indicator

Parameters: period = 14 (2–200)

Overview

The Midprice indicator tracks the central tendency of price movement by calculating the midpoint between recent highs and lows over a user defined period, effectively smoothing out market noise while maintaining sensitivity to significant range shifts. This calculation uses the formula (Period High + Period Low) / 2 to establish a dynamic reference level that adapts as market ranges expand or contract. Price trading above the midprice line suggests bullish control over the recent range, while sustained movement below indicates bearish dominance of the price structure. Traders apply midprice as both a trend filter and a mean reversion tool, since it identifies when price has moved too far from its natural equilibrium without the computational complexity of weighted averages. Unlike oscillators that require separate indicator panels, midprice overlays directly on the price chart, providing an intuitive visual reference that helps traders spot potential support and resistance zones where price tends to pause or reverse.

Implementation Examples

Compute Midprice from slices or candles:

use vectorta::indicators::midprice::{midprice, MidpriceInput, MidpriceParams};
use vectorta::utilities::data_loader::{Candles, read_candles_from_csv};

// Using high/low slices
let high = vec![100.0, 102.0, 101.5, 103.0, 105.0, 104.5];
let low  = vec![ 99.0,  98.0,  99.5, 100.0, 102.0, 103.0];
let params = MidpriceParams { period: Some(14) };
let input = MidpriceInput::from_slices(&high, &low, params);
let result = midprice(&input)?; // result.values

// Using with Candles (defaults: high/low, period=14)
let candles: Candles = read_candles_from_csv("data/sample.csv")?;
let input = MidpriceInput::with_default_candles(&candles);
let result = midprice(&input)?;

// Access values
for v in result.values { println!("midprice: {}", v); }

API Reference

Input Methods
// From high/low slices
MidpriceInput::from_slices(&[f64], &[f64], MidpriceParams) -> MidpriceInput

// From candles with custom sources
MidpriceInput::from_candles(&Candles, &str, &str, MidpriceParams) -> MidpriceInput

// From candles with defaults (high/low, period=14)
MidpriceInput::with_default_candles(&Candles) -> MidpriceInput
Parameters Structure
pub struct MidpriceParams {
    pub period: Option<usize>, // Default: 14
}
Output Structure
pub struct MidpriceOutput {
    pub values: Vec<f64>, // Midprice series
}
Validation, Warmup & NaNs
  • period > 0 and period ≤ data.len(); otherwise MidpriceError::InvalidPeriod.
  • high.len() == low.len(); otherwise MidpriceError::MismatchedDataLength.
  • First finite index = first; require at least period valid points after first, else MidpriceError::NotEnoughValidData.
  • Warmup: indices [0 .. first+period-2] are NaN; first valid output at first+period-1.
Error Handling
use vectorta::indicators::midprice::{midprice, MidpriceError};

match midprice(&input) {
    Ok(output) => process(output.values),
    Err(MidpriceError::EmptyData) => eprintln!("empty data"),
    Err(MidpriceError::InvalidPeriod { period, data_len }) =>
        eprintln!("invalid period {} for length {}", period, data_len),
    Err(MidpriceError::NotEnoughValidData { needed, valid }) =>
        eprintln!("need {} valid points after first, got {}", needed, valid),
    Err(MidpriceError::AllValuesNaN) => eprintln!("all values NaN"),
    Err(MidpriceError::MismatchedDataLength { high_len, low_len }) =>
        eprintln!("length mismatch: high={}, low={}", high_len, low_len),
    Err(MidpriceError::InvalidLength { expected, actual }) =>
        eprintln!("output length mismatch: expected={}, actual={}", expected, actual),
}

Python Bindings

Basic Usage

Calculate Midprice using NumPy arrays:

import numpy as np
from vectorta import midprice

high = np.array([100.0, 102.0, 101.5, 103.0, 105.0, 104.5])
low  = np.array([ 99.0,  98.0,  99.5, 100.0, 102.0, 103.0])

# period defaults to 14 when not specified elsewhere
values = midprice(high, low, 14)

# Optional kernel selection, e.g., kernel="avx2"
values = midprice(high, low, 20, kernel="auto")

print("Midprice:", values)
Streaming Real-time Updates

Process real-time high/low updates:

from vectorta import MidpriceStream

stream = MidpriceStream(14)
for high, low in price_feed:
    y = stream.update(high, low)
    if y is not None:
        print("midprice:", y)
Batch Processing

Sweep a range of periods and get a matrix result:

import numpy as np
from vectorta import midprice_batch

high = np.array([...], dtype=np.float64)
low  = np.array([...], dtype=np.float64)

result = midprice_batch(high, low, (5, 30, 5))  # (start, end, step)
values = result["values"]  # shape: (rows, cols)
periods = result["periods"]  # [5, 10, 15, 20, 25, 30]

print(values.shape, periods)

JavaScript / WASM

Basic Usage

Calculate Midprice in JavaScript/TypeScript:

import { midprice_js } from 'vectorta-wasm';

const high = new Float64Array([100.0, 102.0, 101.5, 103.0, 105.0, 104.5]);
const low  = new Float64Array([ 99.0,  98.0,  99.5, 100.0, 102.0, 103.0]);
const result = midprice_js(high, low, 14);
console.log('Midprice:', result);
Memory-Efficient Operations

Use zero-copy operations for large datasets:

import { midprice_alloc, midprice_free, midprice_into, memory } from 'vectorta-wasm';

const high = new Float64Array([/* your data */]);
const low  = new Float64Array([/* your data */]);
const n = high.length;

const highPtr = midprice_alloc(n);
const lowPtr  = midprice_alloc(n);
const outPtr  = midprice_alloc(n);

new Float64Array(memory.buffer, highPtr, n).set(high);
new Float64Array(memory.buffer, lowPtr, n).set(low);

midprice_into(highPtr, lowPtr, outPtr, n, 14);

const out = new Float64Array(memory.buffer, outPtr, n).slice();
console.log('Midprice:', out);

midprice_free(highPtr, n);
midprice_free(lowPtr, n);
midprice_free(outPtr, n);
Batch Processing

Test multiple periods efficiently:

import { midprice_batch } from 'vectorta-wasm';

const high = new Float64Array([/* historical highs */]);
const low  = new Float64Array([/* historical lows  */]);

const config = { period_range: [5, 30, 5] }; // (start, end, step)
const result = midprice_batch(high, low, config);

// result: { values: Float64Array, periods: number[], rows: number, cols: number }
const { values, periods, rows, cols } = result as any;
console.log('Grid periods:', periods);

// Extract row for a given period
function rowFor(period: number): Float64Array {
  const idx = periods.indexOf(period);
  const off = idx * cols;
  return values.slice(off, off + cols);
}

Performance Analysis

Comparison:
View:
Loading chart...

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

Related Indicators