djmad

[MAD] Acceleration based dampened SMA projections

This indicator utilizes concepts of arrays inside arrays to calculate and display projections of multiple Smoothed Moving Average (SMA) lines via polylines.

This is partly an experiment as an educational post, on how to work with multidimensional arrays by using User-Defined Types

------------------

Input Controls for User Interaction:
The indicator provides several input controls, allowing users to adjust parameters like the SMA window, acceleration window, and dampening factors.
This flexibility lets users customize the behavior and appearance of the indicator to fit their analysis needs.

sma length:
Defines the length of the simple moving average (SMA).

acceleration window:
Sets the window size for calculating the acceleration of the SMA.

Input Series:
Selects the input source for calculating the SMA (typically the closing price).

Offset:
Determines the offset for the input source, affecting the positioning of the SMA. Here it´s possible to add external indicators like bollinger bands,.. in that case as double sma this sma should be very short.
(Thanks Fikira for that idea)

Startfactor dampening:
Initial dampening factor for the polynomial curve projections, influencing their starting curvature.

Growfactor dampening:
Growth rate of the dampening factor, affecting how the curvature of the projections changes over time.

Prediction length:
Sets the length of the projected polylines, extending beyond the current bar.

cleanup history:
Boolean input to control whether to clear the previous polyline projections before drawing new ones.

Key technologies used in this indicator include:

User-Defined Types (UDT):
This indicator uses UDT to create a custom type named type_polypaths.
This type is designed to store information for each polyline, including an array of points (array<chart.point>), a color for the polyline, and a dampening factor.
UDTs in Pine Script enable the creation of complex data structures, which are essential for organizing and manipulating data efficiently.
type type_polypaths
    array<chart.point>  polyline_points = na
    color               polyline_color  = na
    float               dampening_factor= na

Arrays and Nested Arrays:
The script heavily utilizes arrays.
For example, it uses a color array (colorpreset) to store different colors for the polyline.
Moreover, an array of type_polypaths (polypaths) is used, which is an array consisting of user-defined types. Each element of this array contains another array (polyline_points), demonstrating nested array usage.
This structure is essential for handling multiple polylines, each with its set of points and attributes.
var type_polypaths [] polypaths = array.new<type_polypaths>()

Polyline Creation and Manipulation:
The core visual aspect of the indicator is the creation of polylines.
Polyline points are calculated based on a dampened polynomial curve, which is influenced by the SMA's slope and acceleration.

Filling initial dampening data
    array_size = 9
    middle_index = math.floor(array_size / 2)
    for i = 0 to array_size - 1
        damp_factor = f_calculate_damp_factor(i, middle_index, Startfactor, Growfactor)
        polyline_color = colorpreset.get(i)
        polypaths.push(type_polypaths.new(array.new<chart.point>(0, na), polyline_color, damp_factor))

The script dynamically generates these polyline points and stores them in the polyline_points array of each type_polypaths instance based on those prefilled dampening factors
if barstate.islast or cleanup == false
    for damp_factor_index = 0 to polypaths.size() - 1
        GET_RW = polypaths.get(damp_factor_index)
        GET_RW.polyline_points.clear()

        for i = 0 to predictionlength
            y = f_dampened_poly_curve(bar_index + i , src_input[src_off], sma_slope[src_off], sma_acceleration[src_off], GET_RW.dampening_factor)
            p = chart.point.from_index(bar_index + i - src_off, y)
            GET_RW.polyline_points.push(p)
        polypaths.set(damp_factor_index, GET_RW)

Polyline Drawout
The polyline is then drawn on the chart using the polyline.new() function, which uses these points and additional attributes like color and width.
    for pl_s = 0 to polypaths.size() - 1
        GET_RO = polypaths.get(pl_s)
        polyline.new(points = GET_RO.polyline_points, line_width = 1, line_color = GET_RO.polyline_color, xloc = xloc.bar_index)

If the cleanup input is enabled, existing polylines are deleted before new ones are drawn, maintaining clarity and accuracy in the visualization.
if cleanup
    for pl_delete in polyline.all
        pl_delete.delete()

------------------

The mathematics
in the (ABDP) indicator primarily focuses on projecting the behavior of a Smoothed Moving Average (SMA) based on its current trend and acceleration.

SMA Calculation:
The indicator computes a simple moving average (SMA) over a specified window (sma_window). This SMA serves as the baseline for further calculations.

Slope and Acceleration Analysis:
It calculates the slope of the SMA by subtracting the current SMA value from its previous value. Additionally, it computes the SMA's acceleration by evaluating the sum of differences between consecutive SMA values over an acceleration window (acceleration_window). This acceleration represents the rate of change of the SMA's slope.
sma_slope = src_input - src_input[1]
sma_acceleration = sma_acceleration_sum_calc(src_input, acceleration_window) / acceleration_window

sma_acceleration_sum_calc(src, window) =>
    sum = 0.0
    for i = 0 to window - 1
        if not na(src[i + 2])
            sum := sum + src[i] - 2 * src[i + 1] + src[i + 2]
    sum

Dampening Factors:
Custom dampening factors for each polyline, which are based on the user-defined starting and growth factors (Startfactor, Growfactor).
These factors adjust the curvature of the projected polylines, simulating various future scenarios of SMA movement.
f_calculate_damp_factor(index, middle, start_factor, growth_factor) =>
    start_factor + (index - middle) * growth_factor

Polynomial Curve Projection:
Using the SMA value, its slope, acceleration, and dampening factors, the script calculates points for polynomial curves. These curves represent potential future paths of the SMA, factoring in its current direction and rate of change.
f_dampened_poly_curve(index, initial_value, initial_slope, acceleration, damp_factor) =>
    delta = index - bar_index
    initial_value + initial_slope * delta + 0.5 * damp_factor * acceleration * delta * delta

damp_factor = f_calculate_damp_factor(i, middle_index, Startfactor, Growfactor)



Have fun trading :-)

Trader & coder. TA & NFTs.
bitblockwizard.com more at bitblockart.com
오픈 소스 스크립트

이 스크립트의 오써는 참된 트레이딩뷰의 스피릿으로 이 스크립트를 오픈소스로 퍼블리쉬하여 트레이더들로 하여금 이해 및 검증할 수 있도록 하였습니다. 오써를 응원합니다! 스크립트를 무료로 쓸 수 있지만, 다른 퍼블리케이션에서 이 코드를 재사용하는 것은 하우스룰을 따릅니다. 님은 즐겨찾기로 이 스크립트를 차트에서 쓸 수 있습니다.

면책사항

이 정보와 게시물은 TradingView에서 제공하거나 보증하는 금융, 투자, 거래 또는 기타 유형의 조언이나 권고 사항을 의미하거나 구성하지 않습니다. 자세한 내용은 이용 약관을 참고하세요.

차트에 이 스크립트를 사용하시겠습니까?