OPEN-SOURCE SCRIPT
Обновлено

Cosine-Weighted MA ATR [InvestorUnknown]

8008
The Cosine-Weighted Moving Average (CWMA) ATR (Average True Range) indicator is designed to enhance the analysis of price movements in financial markets. By incorporating a cosine-based weighting mechanism, this indicator provides a unique approach to smoothing price data and measuring volatility, making it a valuable tool for traders and investors.

Cosine-Weighted Moving Average (CWMA)
  • The CWMA is calculated using weights derived from the cosine function, which emphasizes different data points in a distinctive manner. Unlike traditional moving averages that assign equal weight to all data points, the cosine weighting allocates more significance to values at the edges of the data window. This can help capture significant price movements while mitigating the impact of outlier values.
  • The weights are shifted to ensure they remain non-negative, which helps in maintaining a stable calculation throughout the data series. The normalization of these weights ensures they sum to one, providing a proportional contribution to the average.

// Function to calculate the Cosine-Weighted Moving Average with shifted weights
f_Cosine_Weighted_MA(series float src, simple int length) =>
    var float[] cosine_weights = array.new_float(0)
    array.clear(cosine_weights)  // Clear the array before recalculating weights
    for i = 0 to length - 1
        weight = math.cos((math.pi * (i + 1)) / length) + 1  // Shift by adding 1
        array.push(cosine_weights, weight)

    // Normalize the weights
    sum_weights = array.sum(cosine_weights)
    for i = 0 to length - 1
        norm_weight = array.get(cosine_weights, i) / sum_weights
        array.set(cosine_weights, i, norm_weight)

    // Calculate Cosine-Weighted Moving Average
    cwma = 0.0
    if bar_index >= length
        for i = 0 to length - 1
            cwma := cwma + array.get(cosine_weights, i) * close
    cwma


Cosine-Weighted ATR Calculation
  • The ATR is an essential measure of volatility, reflecting the average range of price movement over a specified period. The Cosine-Weighted ATR uses a similar weighting scheme to that of the CWMA, allowing for a more nuanced understanding of volatility. By emphasizing more recent price movements while retaining sensitivity to broader trends, this ATR variant offers traders enhanced insight into potential price fluctuations.

// Function to calculate the Cosine-Weighted ATR with shifted weights
f_Cosine_Weighted_ATR(simple int length) =>
    var float[] cosine_weights_atr = array.new_float(0)
    array.clear(cosine_weights_atr)
    for i = 0 to length - 1
        weight = math.cos((math.pi * (i + 1)) / length) + 1  // Shift by adding 1
        array.push(cosine_weights_atr, weight)

    // Normalize the weights
    sum_weights_atr = array.sum(cosine_weights_atr)
    for i = 0 to length - 1
        norm_weight_atr = array.get(cosine_weights_atr, i) / sum_weights_atr
        array.set(cosine_weights_atr, i, norm_weight_atr)

    // Calculate Cosine-Weighted ATR using true ranges
    cwatr = 0.0
    tr = ta.tr(true)  // True Range
    if bar_index >= length
        for i = 0 to length - 1
            cwatr := cwatr + array.get(cosine_weights_atr, i) * tr
    cwatr


Signal Generation
  • The indicator generates long and short signals based on the relationship between the price (user input) and the calculated upper and lower bands, derived from the CWMA and the Cosine-Weighted ATR. Crossover conditions are used to identify potential entry points, providing a systematic approach to trading decisions.

// - - - - - CALCULATIONS - - - - - //{
bar   b                             = bar.new()
float src                           = b.calc_src(cwma_src)

float cwma                          = f_Cosine_Weighted_MA(src, ma_length)

// Use normal ATR or Cosine-Weighted ATR based on input
float atr                           = atr_type == "Normal ATR" ? ta.atr(atr_len) : f_Cosine_Weighted_ATR(atr_len)

// Calculate upper and lower bands using ATR
float cwma_up                       = cwma + (atr * atr_mult)
float cwma_dn                       = cwma - (atr * atr_mult)

float src_l                         = b.calc_src(src_long)
float src_s                         = b.calc_src(src_short)

// Signal logic for crossovers and crossunders
var int signal                      = 0
if ta.crossover(src_l, cwma_up)
    signal := 1
if ta.crossunder(src_s, cwma_dn)
    signal := -1
//}


Backtest Mode and Equity Calculation
To evaluate its effectiveness, the indicator includes a backtest mode, allowing users to test its performance on historical data:
  • Backtest Equity: A detailed equity curve is calculated based on the generated signals over a user-defined period (startDate to endDate).
  • Buy and Hold Comparison: Alongside the strategy’s equity, a Buy-and-Hold equity curve is plotted for performance comparison.


Visualization and Alerts
  • The indicator features customizable plots, allowing users to visualize the CWMA, ATR bands, and signals effectively. The colors change dynamically based on market conditions, with clear distinctions between long and short signals.
  • Alerts can be configured to notify users of crossover events, providing timely information for potential trading opportunities.

Информация о релизе
Added option to use custom Timeframes on current chart Timeframe for CWMA and ATR.


simple bool   custom_tf             = input.bool(false, "Custom Timeframes", group = G2)
simple string cwma_tf               = input.timeframe("", "CWMA Timeframe", group = G2)
simple string atr_tf                = input.timeframe("", "ATR Timeframe", group = G2)

float cwma                          = custom_tf ? request.security("", cwma_tf, f_Cosine_Weighted_MA(src, ma_length)) : f_Cosine_Weighted_MA(src, ma_length)

float atr                           = custom_tf ? request.security("", atr_tf,(atr_type == "Normal ATR" ? ta.atr(atr_len) : f_Cosine_Weighted_ATR(atr_len))) : (atr_type == "Normal ATR" ? ta.atr(atr_len) : f_Cosine_Weighted_ATR(atr_len))
Информация о релизе
Fixed issue with custom CWMA source not being passed correctly into the calculation.
Информация о релизе
Updated the code to pinescript v6, added backtesting library v2 with more backtesting functions and removed old backtesting functions from the code

Отказ от ответственности

Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.