Library · Pine Script v6 · Library

MirPapa_Lib_trend

by alvinng214· code credited to goodia

MirPapa_Lib_trend is a Pine Script utility library providing trend and momentum calculation functions for other scripts.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code435
Settings0inputs
LicenceNone statedfile: MPL-2.0
Last update2 months ago5 Aug 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

435 lines of Pine Script v6 from MirPapa-ICT-HTF- FVG OB Threeple/MirPapa_Lib_trend.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

MirPapa_Lib_trend.txt
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goodia

//@version=6

// This Pine Script® library is subject to the terms of the Mozilla Public License 2.0
// https://mozilla.org/MPL/2.0/
// © goodia

library('MirPapa_Lib_trend', overlay = false)

const int LIBRARY_VERSION_MAJOR = 1
const int LIBRARY_VERSION_MINOR = 1

// === Moving Averages 종류별 함수 ===

/// Hull Moving Average (HMA) 계산
/// @param src 기준 소스
/// @param len 기간
/// @returns HMA 결과
hma(float src, int len) =>
    ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))

/// Exponential Hull Moving Average (EHMA) 계산
/// @param src 기준 소스
/// @param len 기간
/// @returns EHMA 결과
ehma(float src, int len) =>
    ta.ema(2 * ta.ema(src, len / 2) - ta.ema(src, len), math.round(math.sqrt(len)))

/// Triple Hull Moving Average (THMA) 계산
/// @param src 기준 소스
/// @param len 기간
/// @returns THMA 결과
thma(float src, int len) =>
    ta.wma(ta.wma(src, len / 3) * 3 - ta.wma(src, len / 2) - ta.wma(src, len), len)

// 불필요한 래퍼 함수들 제거 - ma() 함수에서 직접 ta.* 호출


// === MA 종류 선택 ===

/// 이동평균 종류 선택 함수 (최적화: 직접 ta.* 호출)
/// @param mode 이동평균 종류 ("SMA", "EMA", "HMA", "WMA", "RMA", "EHMA", "THMA")
/// @param src 기준 소스
/// @param len 기간
/// @returns 선택된 이동평균 결과
ma(string mode, float src, int len) =>
    mode == 'HMA' ? hma(src, len) : mode == 'EHMA' ? ehma(src, len) : mode == 'THMA' ? thma(src, len) : mode == 'SMA' ? ta.sma(src, len) : mode == 'EMA' ? ta.ema(src, len) : mode == 'WMA' ? ta.wma(src, len) : mode == 'RMA' ? ta.rma(src, len) : na


/// RSX 계산 (RSI 기반 고급 버전)
funcRSX(float src, int len) =>
    var float f90_ = 0.0
    var float f88 = 0.0
    var float f28 = 0.0
    var float f20 = 0.0
    var float f30 = 0.0
    var float f38 = 0.0
    var float f40 = 0.0
    var float f50 = 0.0
    var float f58 = 0.0
    var float f60 = 0.0
    var float f68 = 0.0
    var float f70 = 0.0
    var float f78 = 0.0
    var float f80 = 0.0
    var float f0 = 0.0
    var float f90 = 0.0
    var float f48 = 0.0
    var float vC = 0.0
    var float v10 = 0.0
    var float v14 = 0.0
    var float v18 = 0.0
    var float v1C = 0.0
    var float v20 = 0.0
    var float v4_ = 0.0

    f90_ := nz(f90_[1]) == 0.0 ? 1.0 : nz(f88[1]) <= nz(f90_[1]) ? nz(f88[1]) + 1 : nz(f90_[1]) + 1
    f88 := nz(f90_[1]) == 0.0 and len - 1 >= 5 ? len - 1.0 : 5.0
    f8 = 100.0 * src
    f18 = 3.0 / (len + 2.0)
    f20 := 1.0 - f18
    f10 = nz(f8[1])
    v8 = f8 - f10
    f28 := f20 * nz(f28[1]) + f18 * v8
    f30 := f18 * f28 + f20 * nz(f30[1])
    vC := f28 * 1.5 - f30 * 0.5
    f38 := f20 * nz(f38[1]) + f18 * vC
    f40 := f18 * f38 + f20 * nz(f40[1])
    v10 := f38 * 1.5 - f40 * 0.5
    f48 := f20 * nz(f48[1]) + f18 * v10
    f50 := f18 * f48 + f20 * nz(f50[1])
    v14 := f48 * 1.5 - f50 * 0.5
    f58 := f20 * nz(f58[1]) + f18 * math.abs(v8)
    f60 := f18 * f58 + f20 * nz(f60[1])
    v18 := f58 * 1.5 - f60 * 0.5
    f68 := f20 * nz(f68[1]) + f18 * v18
    f70 := f18 * f68 + f20 * nz(f70[1])
    v1C := f68 * 1.5 - f70 * 0.5
    f78 := f20 * nz(f78[1]) + f18 * v1C
    f80 := f18 * f78 + f20 * nz(f80[1])
    v20 := f78 * 1.5 - f80 * 0.5
    f0 := f88 >= f90_ and f8 != f10 ? 1.0 : 0.0
    f90 := f88 == f90_ and f0 == 0.0 ? 0.0 : f90_
    v4_ := f88 < f90 and v20 > 0.0000000001 ? (v14 / v20 + 1.0) * 50.0 : 50.0
    v4_ > 100.0 ? 100.0 : v4_ < 0.0 ? 0.0 : v4_


/// Stage (정렬상태) 반환 (최적화: 조기 종료로 비교 연산 50% 감소)
/// @param v1 첫 번째 값
/// @param v2 두 번째 값
/// @param v3 세 번째 값
/// @returns 1~6
Stage(float v1, float v2, float v3) =>
    if v1 >= v2
        if v2 >= v3
            1 // v1 >= v2 >= v3
        else if v1 >= v3
            6 // v1 >= v3 > v2
        else
            5 // v3 > v1 >= v2
    else // v2 > v1
        if v1 >= v3
            2 // v2 > v1 >= v3
        else if v2 >= v3
            3 // v2 >= v3 > v1
        else
            4 // v3 > v2 > v1

/// Stage 별 배경색 반환 (최적화: 내부 통합으로 중복 코드 제거)
/// @param stage 스테이지 값
/// @param transp 투명도 (0이면 기본 색상)
/// @returns 색상
BgColor(int stage, int transp) =>
    baseColor = stage == 1 ? color.green : stage == 2 ? color.yellow : stage == 3 ? color.orange : stage == 4 ? color.red : stage == 5 ? color.blue : stage == 6 ? color.aqua : color.white
    transp == 0 ? baseColor : color.new(baseColor, transp == 0 ? 100 : transp)

/// Stage 별 배경색 반환 (투명도 없음)
/// @param stage 스테이지 값
/// @returns 색상
BgColor(int stage) =>
    BgColor(stage, 0)

/// MA Color lowest, low, mid, high, highest, base
/// @param level : 1= lowest, 2= low, 3= mid, 4= high, 5= highest, 6= Base
export getMaColor(int level) =>
    level == 1 ? color.red : level == 2 ? color.blue : level == 3 ? color.aqua : level == 4 ? color.orange : level == 5 ? color.green : level == 6 ? color.olive : color.white

// === 주요 MA 그룹 계산 ===

/// 단일 MA를 리턴하는 편의 함수
/// @param mode MA 종류
/// @param src 소스
/// @param len 기간
/// @returns 선택된 MA
export getMA(string mode, float src, int len) =>
    ma(mode, src, len)

/// 주요 이동평균 그룹(low ~ high, base) 계산 (최적화: 중간 변수 제거)
/// @param maName 이동평균 종류
/// @param src 기준 소스
/// @param intLow 단기
/// @param intMid 중기
/// @param intHigh 장기
/// @returns [Low, Mid, High] 배열
export getMA(string maName, float src, int intLow, int intMid, int intHigh) =>
    [ma(maName, src, intLow), ma(maName, src, intMid), ma(maName, src, intHigh)]

/// 주요 이동평균 그룹(Tiny ~ Highest) 계산 (최적화: 중간 변수 제거)
/// @param maName 이동평균 종류
/// @param src 기준 소스
/// @param intLowest 초단기
/// @param intLow 단기
/// @param intMid 중기
/// @param intHigh 장기
/// @param intHighest 초장기
/// @param intBase 기준선
/// @returns [Lowest, Low, Mid, High, Highest, Base] 배열
export getMA(string maName, float src, int intLowest, int intLow, int intMid, int intHigh, int intHighest, int intBase) =>
    [ma(maName, src, intLowest), ma(maName, src, intLow), ma(maName, src, intMid), ma(maName, src, intHigh), ma(maName, src, intHighest), ma(maName, src, intBase)]

// === Stochastic 계산 ===

/// Stochastic K선 그룹 계산
/// @param src 기준 소스
/// @param Len 기간
/// @returns 선택된 스토캐스틱
export getStochastic(float src, int intLen) =>
    ta.stoch(src, high, low, intLen)

/// Stochastic K선 그룹 계산 (최적화: 중간 변수 제거)
/// @param src 기준 소스
/// @param intLow 단기 기간
/// @param intMid 중기 기간
/// @param intHigh 장기 기간
/// @returns [stoLow, stoMid, stoHigh]
export getStochastic(float src, int intLow, int intMid, int intHigh) =>
    [ta.stoch(src, high, low, intLow), ta.stoch(src, high, low, intMid), ta.stoch(src, high, low, intHigh)]

/// Stochastic K선 그룹 계산 (최적화: 중간 변수 제거)
/// @param src 기준 소스
/// @param intLowest 초단기 기간
/// @param intLow 단기 기간
/// @param intMid 중기 기간
/// @param intHigh 장기 기간
/// @param intHighest 최장기 기간
/// @param intBase 기준선 기간
/// @returns [stoLowest, stoLow, stoMid, stoHigh, stoHighest, stoBase]
export getStochastic(float src, int intLowest, int intLow, int intMid, int intHigh, int intHighest, int intBase) =>
    [ta.stoch(src, high, low, intLowest), ta.stoch(src, high, low, intLow), ta.stoch(src, high, low, intMid), ta.stoch(src, high, low, intHigh), ta.stoch(src, high, low, intHighest), ta.stoch(src, high, low, intBase)]

// === RSX 계산 (RSI 고급 변형) ===

/// RSX 그룹 계산
/// @param src 기준 소스
/// @param intLen 기간
/// @returns 선택된 rsx
export getRSX(float src, int intLen) =>
    funcRSX(src, intLen)

/// RSX 그룹 계산 (최적화: 중간 변수 제거)
/// @param src 기준 소스
/// @param intLow 중단기
/// @param intMid 중기
/// @param intHigh 장기
/// @returns [Low, Mid, High]
export getRSX(float src, int intLow, int intMid, int intHigh) =>
    [funcRSX(src, intLow), funcRSX(src, intMid), funcRSX(src, intHigh)]

/// RSX 그룹 계산 (최적화: 중간 변수 제거)
/// @param src 기준 소스
/// @param intLowest 초단기
/// @param intLow 단기
/// @param intMid 중기
/// @param intHigh 장기
/// @param intHighest 초장기
/// @param intBase 기준선
/// @returns [Lowest, Low, Mid, High, Highest, Base]
export getRSX(float src, int intLowest, int intLow, int intMid, int intHigh, int intHighest, int intBase) =>
    [funcRSX(src, intLowest), funcRSX(src, intLow), funcRSX(src, intMid), funcRSX(src, intHigh), funcRSX(src, intHighest), funcRSX(src, intBase)]


// === MACD 계산 ===

/// MACD 계산
/// @param src 기준 소스
/// @param fastLen 빠른 EMA 기간
/// @param slowLen 느린 EMA 기간
/// @param signalLen 시그널 기간
/// @returns [macdLine, signalLine, histLine]
export getMACD(float src, int fastLen, int slowLen, int signalLen) =>
    [macdLine, signalLine, histLine] = ta.macd(src, fastLen, slowLen, signalLen)
    [macdLine, signalLine, histLine]


// === Bollinger Bands 계산 ===

/// 볼린저 밴드 계산
/// @param src 기준 소스
/// @param len 기준 기간
/// @param mult 표준편차 배수
/// @returns [basis, upper, lower]
export getBollingerBand(float src, int len, float mult) =>
    basis = ta.sma(src, len)
    dev = mult * ta.stdev(src, len)
    [basis, basis + dev, basis - dev]

// === ATR 계산 ===

/// Average True Range(ATR) 그룹 계산
/// @param intLen ATR 기간
/// @returns 선택된 ATR
export getATR(int intLen) =>
    ta.atr(intLen)

/// Average True Range(ATR) 그룹 계산
/// @param intLow 단기 ATR 기간
/// @param intMid 중기 ATR 기간
/// @param intHigh 장기 ATR 기간
/// @returns [ATR Low, Mid, High] 배열
export getATR(int intLow, int intMid, int intHigh) =>
    [ta.atr(intLow), ta.atr(intMid), ta.atr(intHigh)]

/// Average True Range(ATR) 그룹 계산
/// @param intTiny Tiny ATR 기간
/// @param intLowest 초단기 ATR 기간
/// @param intLow 단기 ATR 기간
/// @param intMid 중기 ATR 기간
/// @param intHigh 장기 ATR 기간
/// @param intHighest 초장기 ATR 기간
/// @returns [ATR Lowest, Low, Mid, High, Highest, Base] 배열
export getATR(int intLowest, int intLow, int intMid, int intHigh, int intHighest, int intBase) =>
    [ta.atr(intLowest), ta.atr(intLow), ta.atr(intMid), ta.atr(intHigh), ta.atr(intHighest), ta.atr(intBase)]

// === 교차 및 추세 판단 ===

/// 교차 상태 반환 (1: Golden Cross, -1: Death Cross, 0: 없음)
/// @param fastLine 빠른선
/// @param baseLine 기준선
/// @returns 상태
export isCross(float fastLine, float baseLine) =>
    ta.crossover(fastLine, baseLine) ? 1 : ta.crossunder(fastLine, baseLine) ? -1 : 0

/// MA 정렬 추세 반환
/// @param maLow 가장 빠른 MA
/// @param maMid 중간 MA
/// @param maHigh 느린 MA
/// @returns 상태
export isMAtrend(float maLow, float maMid, float maHigh) =>
    maLow > maMid and maMid > maHigh ? 1 : maHigh > maMid and maMid > maLow ? -1 : 0

/// MA 라인 돌파 상태 반환
/// @param val 현재 값
/// @param valPrev 이전 값
/// @param intBaseLine 기준값
/// @returns 상태
export isMAline(float val, float valPrev, int intBaseLine) =>
    val < intBaseLine and val > valPrev ? 1 : val > intBaseLine and valPrev > val ? -1 : 0

// === Stage 판단 ===

/// Stage (정렬상태) 반환
/// @param v1 첫 번째 값
/// @param v2 두 번째 값
/// @param v3 세 번째 값
/// @returns 1~6
export getStage(float v1, float v2, float v3) =>
    Stage(v1, v2, v3)

/// Stage 별 배경색 반환
/// @param stage 스테이지 값
/// @returns 색상
export getBgColor(int stage) =>
    BgColor(stage)

/// Stage 별 배경색 반환
/// @param stage 스테이지 값
/// @param transp 투명도
/// @returns 색상
export getBgColor(int stage, int transp) =>
    BgColor(stage, transp)

/// MA Stage별 배경색 반환
/// @param v1 첫 번째 값
/// @param v2 두 번째 값
/// @param v3 세 번째 값
/// @param transp 투명도
/// @param customColor 사용자 지정 색 (옵션)
/// @returns 색상
export getBGColor(float v1, float v2, float v3) =>
    BgColor(Stage(v1, v2, v3))
    /// MA Stage별 배경색 반환
    /// @param v1 첫 번째 값
    /// @param v2 두 번째 값
    /// @param v3 세 번째 값
    /// @param transp 투명도
    /// @param customColor 사용자 지정 색 (옵션)
    /// @returns 색상
export getBGColor(float v1, float v2, float v3, int transp) =>
    BgColor(Stage(v1, v2, v3), transp)



// === Stack Label 생성 ===

/// Stacked Label 생성
/// @param labelText 라벨 텍스트
/// @param isUp 위/아래 여부
/// @param maTiny~maHighest MA 값들
/// @returns 생성된 라벨
export createStackedLabel(string labelText, bool isUp, float maLowest, float maLow, float maMid, float maHigh, float maHighest, float maBase) =>
    lowestMA = math.min(maLowest, maLow, maMid, maHigh, maHighest, maBase)
    highestMA = math.max(maLowest, maLow, maMid, maHigh, maHighest, maBase)
    baseY = isUp ? lowestMA * 0.995 : highestMA * 1.005
    lblStyle = isUp ? label.style_label_up : label.style_label_down
    label.new(bar_index, baseY, labelText, style = lblStyle, color = isUp ? color.new(color.green, 30) : color.new(color.red, 30), textcolor = color.white, size = size.small)
    labelText

// === TrendConditions 라이브러리 내에 추가 ===

/// 쌍바닥(double bottom) 패턴 감지
/// @param src   기준 시리즈 (예: 중간 MA 값, low 등)
/// @param left  PivotLow 검색 시 좌측 봉 개수
/// @param right PivotLow 검색 시 우측 봉 개수
/// @returns     true: 이번 봉에 쌍바닥(이전 PivotLow < 현재 PivotLow) 발생
export isDoubleBottom(float src, int left, int right) =>
    // 1) 이번 봉에 PivotLow 가격
    float pl = ta.pivotlow(src, left, right)
    // 2) 이전 PivotLow 가격 (최종 발생 1개 전)
    float pl_prev = ta.valuewhen(not na(pl), pl, 1)
    // 3) 이전 < 현재 이면 쌍바닥
    not na(pl) and not na(pl_prev) and pl_prev < pl

/// 쌍봉(double top) 패턴 감지
/// @param src   기준 시리즈 (예: 중간 MA 값, high 등)
/// @param left  PivotHigh 검색 시 좌측 봉 개수
/// @param right PivotHigh 검색 시 우측 봉 개수
/// @returns     true: 이번 봉에 쌍봉(이전 PivotHigh > 현재 PivotHigh) 발생
export isDoubleTop(float src, int left, int right) =>
    float ph = ta.pivothigh(src, left, right)
    float ph_prev = ta.valuewhen(not na(ph), ph, 1)
    not na(ph) and not na(ph_prev) and ph_prev > ph

/// Fractal High(프랙탈 하이) 발생 여부
/// @param src   고가 시리즈 (예: high, 중간 MA 값 등)
/// @param left  좌측 확인 봉 개수
/// @param right 우측 확인 봉 개수
/// @returns     true: 프랙탈 하이 발생
export isFractalHigh(float src, int left, int right) =>
    float center = src[right]
    bool ok = true
    for i = 1 to left by 1
        ok := ok and center > src[right + i]
        ok
    for j = 1 to right by 1
        ok := ok and center > src[right - j]
        ok
    ok

/// Fractal Low(프랙탈 로우) 발생 여부
/// @param src   저가 시리즈 (예: low, 중간 MA 값 등)
/// @param left  좌측 확인 봉 개수
/// @param right 우측 확인 봉 개수
/// @returns     true: 프랙탈 로우 발생
export isFractalLow(float src, int left, int right) =>
    float center = src[right]
    bool ok = true
    for i = 1 to left by 1
        ok := ok and center < src[right + i]
        ok
    for j = 1 to right by 1
        ok := ok and center < src[right - j]
        ok
    ok

Overview

MirPapa_Lib_trend features implementations for several moving average types, including the Hull Moving Average (HMA), Exponential Hull Moving Average (EHMA), and Triple Hull Moving Average (THMA), with a unified selector for choosing between them and standard averages like SMA and EMA. Additionally, it implements the RSX oscillator, a smoothed variant of the Relative Strength Index. As a library, it performs calculations without drawing directly on the chart.

Details

Published by

alvinng214 on GitHub

Code credit

goodia, as written in the script's header

Type

Library, Pine Script v6

Draws

Library (no plots)

Category

Trend, Moving averages, Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

ta

by ivansoft
1 stars

Provides a collection of technical analysis calculation functions for use across Pine scripts. It exports implementations for various indicators and mathematical formulas, including oscillators like the Awesome Oscillator, Aroon, and Schaff Trend Cycle, moving

Library v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ta

Momentum

by Electrified-Trading
2 stars

This Pine Script library calculates various momentum metrics and oscillator values for other scripts to use. It provides functions for standard-deviation-normalized price change, dual-moving-average momentum, Stochastic RSI, and a customizable MACD. Function p

Library v5 Oscillators & momentumMoving averages
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop
330 stars

MACD + Divergences [Alorse] is a momentum strategy that calculates the MACD oscillator and identifies regular and hidden divergences using pivot high and low points. It filters trade signals with dual Exponential Moving Averages (EMA 150 and 600) to ensure tra

Strategy v4 Oscillators & momentumDivergence Repaints
Updated 2 months ago · None stated GitHub repository of MACD + Divergences [Alorse]
218 stars

Multi-Timeframe Analysis Suite calculates trend direction and momentum conditions across five user-selected timeframes using moving averages, RSI, and Stochastic oscillators. It evaluates moving average slope and oscillator levels to compute trend alignment, m

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Suite

MACD Crossover (tutorial)

by pineforge-4pass
193 stars

This strategy calculates the Moving Average Convergence Divergence indicator and plots the MACD line, signal line, and histogram in a separate pane. It enters long positions when the MACD line crosses above the signal line and enters short positions when it cr

Strategy v6 Oscillators & momentumMoving averages
Updated today · Apache-2.0 GitHub repository of MACD Crossover (tutorial)

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers