The Sine-Weighted MA ATR is a technical analysis tool designed to emphasize recent price data using sine-weighted calculations, making it particularly well-suited for analyzing cyclical markets with repetitive patterns. The indicator combines the Sine-Weighted Moving Average (SWMA) and a Sine-Weighted Average True Range (SWATR) to enhance price trend detection and volatility analysis.
Sine-Weighted Moving Average (SWMA):
Unlike traditional moving averages that apply uniform or exponentially decaying weights, the SWMA applies Sine weights to the price data.
Emphasis on central data points: The Sine function assigns more weight to the middle of the lookback period, giving less importance to the beginning and end points. This helps capture the main trend more effectively while reducing noise from recent volatility or older data.
// Function to calculate the Sine-Weighted Moving Average f_Sine_Weighted_MA(seriesfloatsrc,simpleintlength)=> varfloat[]sine_weights=array.new_float(0) array.clear(sine_weights)// Clear the array before recalculating weights fori=0tolength-1 weight=math.sin((math.pi*(i+1))/length) array.push(sine_weights,weight) // Normalize the weights sum_weights=array.sum(sine_weights) fori=0tolength-1 norm_weight=array.get(sine_weights,i)/sum_weights array.set(sine_weights,i,norm_weight) // Calculate Sine-Weighted Moving Average swma=0.0 ifbar_index>=length fori=0tolength-1 swma:=swma+array.get(sine_weights,i)*close swma
Sine-Weighted ATR:
This is a variation of the Average True Range (ATR), which measures market volatility. Like the SWMA, the ATR is smoothed using Sine-based weighting, where central values are more heavily considered compared to the extremities. This improves sensitivity to changes in volatility while maintaining stability in highly volatile markets.
// Function to calculate the Sine-Weighted ATR f_Sine_Weighted_ATR(simpleintlength)=> varfloat[]sine_weights_atr=array.new_float(0) array.clear(sine_weights_atr) fori=0tolength-1 weight=math.sin((math.pi*(i+1))/length) array.push(sine_weights_atr,weight) // Normalize the weights sum_weights_atr=array.sum(sine_weights_atr) fori=0tolength-1 norm_weight_atr=array.get(sine_weights_atr,i)/sum_weights_atr array.set(sine_weights_atr,i,norm_weight_atr) // Calculate Sine-Weighted ATR using true ranges swatr=0.0 tr=ta.tr(true)// True Range ifbar_index>=length fori=0tolength-1 swatr:=swatr+array.get(sine_weights_atr,i)*tr swatr
ATR Bands:
Upper and lower bands are created by adding/subtracting the Sine-Weighted ATR from the SWMA. These bands help identify overbought or oversold conditions, and when the price crosses these levels, it may generate long or short trade signals.
// - - - - - CALCULATIONS - - - - - //{ barb=bar.new() floatsrc=b.calc_src(swma_src) floatswma=f_Sine_Weighted_MA(src,ma_length) // Use normal ATR or Sine-Weighted ATR based on input floatatr=atr_type=="Normal ATR"?ta.atr(atr_len):f_Sine_Weighted_ATR(atr_len) // Calculate upper and lower bands using ATR floatswma_up=swma+(atr*atr_mult) floatswma_dn=swma-(atr*atr_mult) floatsrc_l=b.calc_src(src_long) floatsrc_s=b.calc_src(src_short) // Signal logic for crossovers and crossunders varintsignal=0 ifta.crossover(src_l,swma_up) signal:=1 ifta.crossunder(src_s,swma_dn) signal:=-1 //}
Signal Logic:
Long/Short Signals are triggered when the price crosses above or below the Sine-Weighted ATR bands
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.
Alerts The indicator includes built-in alerts for both long and short signals, ensuring users are promptly notified when market conditions meet the criteria for an entry or exit.
Информация о релизе
Added option to use Custom Timeframes on current chart for SWMA and ATR.
simpleboolcustom_tf=input.bool(false,"Custom Timeframes",group=G2) simplestringswma_tf=input.timeframe("","SWMA Timeframe",group=G2) simplestringatr_tf=input.timeframe("","ATR Timeframe",group=G2) floatswma=custom_tf?request.security("",swma_tf,f_Sine_Weighted_MA(src,ma_length)):f_Sine_Weighted_MA(src,ma_length) // Use normal ATR or Sine-Weighted ATR based on input floatatr=custom_tf?request.security("",atr_tf,(atr_type=="Normal ATR"?ta.atr(atr_len):f_Sine_Weighted_ATR(atr_len))):(atr_type=="Normal ATR"?ta.atr(atr_len):f_Sine_Weighted_ATR(atr_len))
Информация о релизе
Fixed issue with custom SWMA 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, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.