PickMyTradeLib

PickMyTradeLib — Market Microstructure & Quantitative Finance Library for Pine Script.
Provides analytically rigorous, academically grounded functions covering five domains:
(1) Synthetic bid-ask spread estimation (Roll 1984, Corwin-Schultz 2012),
(2) Market illiquidity & price impact (Amihud 2002, Kyle 1985),
(3) OHLC-efficient volatility estimators (Garman-Klass 1980, Parkinson 1980, Rogers-Satchell 1991),
(4) Fractal & complexity measures (Higuchi 1988, Hurst R/S, Katz 1988),
(5) Realized distributional moments (skewness, excess kurtosis, realized variance).
All functions are pure Pine — no request.security calls, no external dependencies.
Compatible with any instrument and timeframe. Import with:
import PickMyTrade/PickMyTradeLib/1 as pmtq
rollSpread(src, len, zLen)
Roll's (1984) synthetic bid-ask spread estimator.
Exploits the negative serial covariance of price changes that
arises from the bid-ask bounce. Requires no order-book data.
Formula: spread = 2 * sqrt(max(0, -Cov(Δp_t, Δp_{t-1})))
Reference: Roll, R. (1984). "A Simple Implicit Measure of the
Effective Bid-Ask Spread in an Efficient Market." JoF 39(4).
Parameters:
src (float): Price series (typically close)
len (simple int): Lookback window for covariance estimation (minimum 10)
zLen (simple int): Window for z-score normalisation (default = len * 3)
Returns: SpreadResult with value, zscore, and anomaly flag
corwinSchultz(h, l, zLen)
Corwin & Schultz (2012) high-low spread estimator.
Derives the effective spread from the ratio of two-day to
one-day high-low ranges. More robust than Roll on noisy series.
Reference: Corwin, S. & Schultz, P. (2012). "A Simple Way to
Estimate Bid-Ask Spreads from Daily High and Low Prices."
JoF 67(2), 719-760.
Parameters:
h (float): High series
l (float): Low series
zLen (simple int): Window for z-score normalisation
Returns: SpreadResult
amihud(src, vol, len, zLen)
Amihud (2002) illiquidity ratio.
Measures how much price moves per unit of trading volume —
higher values mean illiquid markets where small trades move price.
Formula: ILLIQ_t = |r_t| / Volume_t, smoothed over len bars.
Reference: Amihud, Y. (2002). "Illiquidity and stock returns."
Journal of Financial Markets 5(1), 31-56.
Parameters:
src (float): Price series for return calculation
vol (float): Volume series
len (simple int): Rolling average window
zLen (simple int): Z-score window
Returns: SpreadResult (value = illiquidity ratio, z-scored)
kyleLambda(src, vol, len)
Kyle's Lambda — price impact coefficient (Kyle 1985).
Estimates how aggressively price responds to signed order flow.
Approximates signed volume as: buy volume when close >= open,
sell volume otherwise. Lambda = OLS slope of Δprice on signed vol.
Reference: Kyle, A.S. (1985). "Continuous Auctions and Insider
Trading." Econometrica 53(6), 1315-1335.
Parameters:
src (float): Price series
vol (float): Volume series
len (simple int): Regression window (minimum 15)
Returns: SpreadResult (value = lambda slope)
garmanKlass(o, h, l, c, len)
Garman-Klass (1980) volatility estimator.
Uses OHLC data to estimate variance more efficiently than
close-to-close (theoretical efficiency ratio ≈ 7.4×).
Formula: σ² = 0.5*(ln H/L)² − (2ln2−1)*(ln C/O)²
Reference: Garman, M. & Klass, M. (1980). "On the Estimation
of Security Price Volatilities from Historical Data."
Journal of Business 53(1), 67-78.
Parameters:
o (float): Open series
h (float): High series
l (float): Low series
c (float): Close series
len (simple int): Averaging window
Returns: VolResult with daily, annual, and rank fields
parkinson(h, l, len)
Parkinson (1980) volatility estimator.
Uses only High and Low — ignores close. More efficient than
close-to-close (theoretical efficiency ≈ 5.2×) but assumes
no overnight gaps or drift. Good intraday baseline.
Reference: Parkinson, M. (1980). "The Extreme Value Method
for Estimating the Variance of the Rate of Return."
Journal of Business 53(1), 61-65.
Parameters:
h (float): High series
l (float): Low series
len (simple int): Averaging window
Returns: VolResult
rogersSatchell(o, h, l, c, len)
Rogers-Satchell (1991) volatility estimator.
Accounts for non-zero drift — unbiased even when price trends.
The only classical OHLC estimator that handles drift correctly.
Formula: σ² = ln(H/C)*ln(H/O) + ln(L/C)*ln(L/O)
Reference: Rogers, L. & Satchell, S. (1991). "Estimating
Variance From High, Low and Closing Prices."
Annals of Applied Probability 1(4), 504-512.
Parameters:
o (float): Open series
h (float): High series
l (float): Low series
c (float): Close series
len (simple int): Averaging window
Returns: VolResult
higuchifd(src, len, kMax)
Higuchi (1988) Fractal Dimension.
Estimates the fractal complexity of a time series directly from
the data. D = 1 → perfectly smooth trend. D = 2 → pure noise.
D < 1.4: trending. 1.4-1.6: random walk. D > 1.6: mean-reverting.
This implementation uses the average of k=2..kMax curve lengths
and OLS regression of log(L_k) on log(k) to get the slope (= -FD).
Reference: Higuchi, T. (1988). "Approach to an irregular time
series on the basis of the fractal theory." Physica D 31(2).
Parameters:
src (float): Input price series
len (simple int): Number of bars to sample (minimum 20, recommended 30-50)
kMax (simple int): Maximum lag (2-8; higher = more stable but slower)
Returns: FractalResult with fd, regime string, and normalised [0,1]
hurstRS(src, len)
Hurst Exponent via Rescaled Range (R/S) analysis.
H > 0.55 → persistent trend-following (long memory).
H ≈ 0.50 → random walk (no memory).
H < 0.45 → mean-reverting (anti-persistent).
Note: FD and Hurst are complementary: FD = 2 - H (theoretically).
Parameters:
src (float): Input price series
len (simple int): Lookback length (minimum 30, recommended 60-100)
Returns: float Hurst exponent in [0, 1]
moments(src, len)
Rolling distributional moments of a return series.
Computes mean, standard deviation, skewness, and excess kurtosis
over a rolling window using Welford's online algorithm for
numerical stability.
Parameters:
src (float): Input series (typically log returns: math.log(close/close[1]))
len (simple int): Rolling window length
Returns: MomentResult with mean, stdev, skew, kurt
normalise(src, len)
Normalise any float series to [0, 1] over a rolling window.
Parameters:
src (float): Input series
len (simple int): Lookback for min/max
Returns: float in [0.0, 1.0]
ewZscore(src, len)
Exponentially weighted z-score — reacts faster than simple z-score.
Parameters:
src (float): Input series
len (simple int): EMA length for mean and variance estimation
Returns: float z-score
zscoreColor(z)
Colour helper — maps a [-3, 3] z-score to a green-grey-red gradient.
z < -2: bright green (anomaly low) z > 2: bright red (anomaly high)
Parameters:
z (float): Z-score value
Returns: color
SpreadResult
Holds a complete spread estimate result with its z-score
Fields:
value (series float): Raw spread estimate (in price units or as ratio)
zscore (series float): Rolling z-score of the estimate vs lookback window
isAnomaly (series bool): True when zscore > threshold (default 2.0)
VolResult
Holds a volatility estimate with annualisation
Fields:
daily (series float): Daily volatility estimate (fraction of price)
annual (series float): Annualised estimate (daily * sqrt(252))
rank (series float): 0-100 percentile rank vs lookback window
FractalResult
Fractal / complexity measurement result
Fields:
fd (series float): Fractal Dimension value (1.0 = smooth trend, 2.0 = noise)
regime (series string): "Trending" when fd < 1.4, "Random" 1.4–1.6, "Choppy" > 1.6
normalised (series float): fd linearly mapped to 0.0 (trend) – 1.0 (noise)
MomentResult
Rolling moment statistics
Fields:
mean (series float): Rolling mean
stdev (series float): Rolling standard deviation
skew (series float): Rolling skewness (negative = left tail)
kurt (series float): Rolling excess kurtosis (positive = fat tails / leptokurtic)
Perpustakaan pine
Dengan semangat TradingView yang sesungguhnya, penulis telah menerbitkan kode Pine ini sebagai pustaka sumber terbuka agar programmer Pine lain dari komunitas kami dapat menggunakannya kembali. Salut untuk penulis! Anda dapat menggunakan pustaka ini secara pribadi atau dalam publikasi sumber terbuka lainnya, tetapi penggunaan kembali kode ini dalam publikasi diatur oleh Tata Tertib.
For Tradovate: bit.ly/4a1KBrY
For all other supported brokers: bit.ly/4qEbU2G
Pernyataan Penyangkalan
Perpustakaan pine
Dengan semangat TradingView yang sesungguhnya, penulis telah menerbitkan kode Pine ini sebagai pustaka sumber terbuka agar programmer Pine lain dari komunitas kami dapat menggunakannya kembali. Salut untuk penulis! Anda dapat menggunakan pustaka ini secara pribadi atau dalam publikasi sumber terbuka lainnya, tetapi penggunaan kembali kode ini dalam publikasi diatur oleh Tata Tertib.
For Tradovate: bit.ly/4a1KBrY
For all other supported brokers: bit.ly/4qEbU2G