Average Bullish & Bearish Percentage ChangeAverage Bullish & Bearish Percentage Change
Processes two key aspects of directional market movements relative to price levels. Unlike traditional momentum tools, it separately calculates the average of positive and negative percentage changes in price using user-defined independent counts of actual past bullish and bearish candles. This approach delivers comprehensive and precise view of average percentage changes.
FEATURES:
Count-Based Averages: Separate averaging of bullish and bearish %𝜟 based on their respective number of occurrences ensures reliable and precise momentum calculations.
Customizable Averaging: User-defined number of candle count sets number of past bullish and bearish candles used in independent averaging.
Two Methods of Candle Metrics:
1. Net Move: Focuses on the body range of the candle, emphasizing the net directional movement.
2. Full Capacity: Incorporates wicks and gaps to capture full potential of the bar.
The indicator classifies Doji candles contextually, ensuring they are appropriately factored into the bullish or bearish metrics to avoid mistakes in calculation:
1. Standard Doji - open equals close.
2. Flat Close Doji - Candles where the close matches the previous close.
Timeframe Flexibility:
The indicator can be applied across any desired timeframe, allowing for seamless multi-timeframe analysis.
HOW TO USE
Select Method of Bar Metrics:
Net Move: For analyzing markets where price changes are consistent and bars are close to each other.
Full Capacity: Incorporates wicks and gaps, providing relevant figures for markets like stocks
Set the number of past candles to average:
🟩 Average Past Bullish Candles (Default: 10)
🟥 Average Past Bullish Candles (Default: 10)
Why Percentage Change Is Important
Standardized Measurement Across Assets:
Percentage change normalizes price movements, making it easier to compare different assets with varying price levels. For example, a $1 move in a $10 stock is significant, but the same $1 move in a $1,000 stock is negligible.
Highlights Relative Impact:
By measuring the price change as a percentage of the close, traders can better understand the relative impact of a move on the asset’s overall value.
Volatility Insights:
A high percentage change indicates heightened volatility, which can be a signal of potential opportunities or risks, making it more actionable than raw price changes. Percents directly reflect the strength of buying or selling pressure, providing a clearer view of momentum compared to raw price moves, which may not account for the relative size of the move.
By focusing on percentage change, this indicator provides a normalized, actionable, and insightful measure of market momentum, which is critical for comparing, analyzing, and acting on price movements across various assets and conditions.
Statistics
ATH with Percentage DifferenceSimple ATH with difference percentage from the actual price to hit the all time high price again
BTC Price Difference (Coinbase vs Binance)BTC Price Difference (Coinbase vs Binance)BTC Price Difference (Coinbase vs Binance)BTC Price Difference (Coinbase vs Binance)BTC Price Difference (Coinbase vs Binance)BTC Price Difference (Coinbase vs Binance)BTC Price Difference (Coinbase vs Binance)BTC Price Difference (Coinbase vs Binance)
52Week Tracking TableThis indicator is nothing but a table where you can easily see how much the current price is away from the High/Close of 52 bars. Also have feature to view the data for more bars back.
Sequence Waves [OmegaTools]the sequence waves indicator, developed by omegatools, is a multi-functional tool designed to detect trends, sequences, and potential reversal signals based on price movements and volume. this indicator has two main modes, "trend" and "sequence," which determine how the indicator calculates directional changes. additional enhancements in this version include reversal signals, allowing users to identify potential long and short opportunities with specific entry cues.
input parameters
mode (mode): chooses the calculation basis for directional movement.
- "trend": uses a midline calculated from the highest high and lowest low over the "trend mode length" period to assess if the price is in an upward or downward trend.
- "sequence": compares the current price to the closing price of the previous "sequence mode length" period to detect shifts in direction.
counter mode (modec): sets whether the counter increments by a fixed amount (1 or -1) or the volume of the bar, impacting the indicator’s sensitivity.
- "fixed": increments or decrements the counter by 1.
- "volume": increments or decrements based on the period’s volume, making the indicator more responsive to high-volume periods.
percentile length (lntp): defines the lookback period for calculating overbought and oversold thresholds using a percentile method. shorter lengths make ob/os levels more reactive.
sensitivity (sens): controls the percentile-based ob/os thresholds, ranging from 10 to 100. higher values narrow ob/os zones, while lower values widen them, impacting signal frequency.
trend mode length (lnt1): sets the period length for midline calculation in trend mode, defaulting to 21. longer periods smooth the midline for detecting major trends.
sequence mode length (lnt2): sets the lookback period in sequence mode, with a default of 4. shorter lengths capture more frequent directional changes, while longer lengths smooth signals.
visual colors:
- up color (upc): sets the color for upward movements.
- down color (dnc): sets the color for downward movements.
calculation logic
midline calculation: in trend mode, a midline is derived from the average of the highest high and lowest low over the "trend mode length" period, acting as a reference to detect upward or downward movements.
counter calculation:
- in trend mode, if the close price is above the midline, the counter increases (or volume if volume mode is selected). it decreases when the price is below.
- in sequence mode, the counter increases if the close is above the closing price from "sequence mode length" periods ago and decreases if below.
the counter resets to zero on direction changes, creating clear directional transitions.
overbought/oversold percentiles: separate arrays track the counter’s values each time the direction changes, creating historical up and down values. ob and os thresholds are dynamically determined based on these arrays, with sizes limited by the percentile length and sensitivity inputs.
reversal signals: two new variables, "long" and "short," detect potential reversal points when the counter crosses specific thresholds:
- long: a long signal is generated when the counter switches to positive and exceeds the down percentile.
- short: a short signal is triggered when the counter switches to negative and exceeds the up percentile.
visual and display elements
counter plot: plots the counter value on the chart with color-coded columns, making it easy to spot directional momentum.
up and down percentiles: displays overbought (up percentile) and oversold (down percentile) thresholds to identify potential reversal zones.
regime background: the background color changes based on market regime:
- bullish (up percentile > down percentile): greenish background.
- bearish (down percentile > up percentile): reddish background.
- neutral (both percentiles equal): grayish background.
reversal signals: plotted as small triangles on the chart for visual confirmation of potential long (triangle up) and short (triangle down) reversal signals.
obs background: changes color when the counter exceeds ob or os thresholds, creating a visual cue for extreme market conditions:
- overbought: background changes to a faint down color.
- oversold: background changes to a faint up color.
status table: displayed on the right side of the chart, providing real-time status information:
- status: shows "overbought," "oversold," "long," "short," or "none" based on the current counter position.
- regime: indicates whether the market is in a "bullish," "bearish," or "neutral" state based on the percentile comparison.
- percentile up/down: displays the current up and down percentiles for quick reference.
how to use the indicator
trend following: in trend mode, use the midline-based counter to gauge if the market is in an uptrend (positive counter) or downtrend (negative counter).
reversal detection: the ob/os thresholds assist in identifying potential reversal points. when the counter exceeds the up percentile, it may indicate an overbought state, suggesting a bearish reversal. similarly, dropping below the down percentile may indicate an oversold state, suggesting a bullish reversal.
entry signals: use the long and short reversal signals for potential entry points, particularly in trending or range-bound markets. these signals are indicated by up and down triangles.
sequence trading: in sequence mode, the indicator tracks shorter-term directional shifts, making it suitable for detecting smaller momentum patterns based on recent price comparisons.
volume sensitivity: selecting volume mode enhances sensitivity to high-volume moves, allowing it to detect stronger market activity in both trend and sequence modes.
the sequence waves indicator is suited to both short-term and long-term traders. it allows for detailed trend analysis, reversal detection, and dynamic ob/os signals. the inclusion of visual reversal cues makes it a flexible tool adaptable to a variety of trading strategies.
Strategy without indicators v11. General Script Strategy
The objective of this strategy is to open buy or sell orders every new hour based on:
Whether the previous candle closed high (buy) or low (sell).
The presence of tops and bottoms to avoid opening orders at times of possible reversals.
The strategy also allows the user to set a date range (start date and end date) to calculate profit, loss, percentage of gain and percentage of loss only in that period.
2. Initial Settings and Parameters
Start Date and End Date: The start_date and end_date variables define the date range to account for profits and losses. These dates can be adjusted by the user to view results in specific periods.
3. Conditions for Order Entry
At each time change, the script checks the conditions for buying or selling, using the following variables and logic:
Detection of Bullish or Bearish Candle:
bullish_candle: True if the previous candle closed high.
bearish_candle: True if the previous candle closed lower.
Analysis of Tops and Bottoms:
To avoid opening orders close to tops and bottoms, the script uses the function find_top_and_bottom(period), which analyzes the last 500 candles and identifies the highest value (top) and the lowest value (bottom).
The variables current_top and current_bottom store these values.
next_top and next_bottom indicate whether the current candle is close to a top (prevents buying) or a bottom (prevents selling).
4. Opening Orders (Buy and Sell)
At each time change, the script checks the conditions to open buy or sell orders:
Condition for Sell:
The sell order is opened if the previous candle was bullish (bullish_candle) and is not close to a top (not next_top).
If there is an open buy order, it is closed before the new sell order.
Buy Condition:
The buy order is opened if the previous candle was bearish (bearish_candle) and is not near a bottom (not_near_bottom).
If there is an open sell order, it is closed before the new buy order.
5. Calculating Profit and Loss
The profit and loss calculation is only done within the configured date range (start_date and end_date):
Profit and Loss:
total_profit and total_loss accumulate the profit and loss values of all operations during the defined period.
percentage_gain and percentage_loss calculate the percentage of gain and loss in relation to the initial capital.
6. Displaying Results on the Chart
The script displays on the chart, next to the candles, the information on Total Profit, Total Loss, % Gain and % Loss:
Strategy Summary
Setting the Date Range: Allows you to set the period for calculating profit and loss.
Previous Candlestick Analysis: Decide whether to buy or sell based on the previous candlestick.
Preventing Entries at Tops and Bottoms: Avoids buying at tops and selling at bottoms to reduce false signals.
Result Calculation: Accumulates profits, losses and percentages within the configured date range.
Results Display on Chart: Displays the configured statistics directly on the chart, next to the candlesticks.
1. Estratégia Geral do Script
O objetivo dessa estratégia é abrir ordens de compra ou venda a cada nova hora com base em:
Se a vela anterior fechou em alta (compra) ou em baixa (venda).
A presença de topos e fundos para evitar abrir ordens em momentos de possíveis reversões.
A estratégia também permite que o usuário configure um intervalo de datas (data inicial e data final) para calcular o lucro, perda, percentual de ganho e percentual de perda apenas nesse período.
2. Configurações e Parâmetros Iniciais
Data Inicial e Data Final: As variáveis data_inicial e data_final definem o intervalo de datas para contabilizar os lucros e perdas. Essas datas podem ser ajustadas pelo usuário para visualizar resultados em períodos específicos.
3. Condições para Entrada de Ordens
A cada mudança de hora, o script verifica as condições de compra ou venda, usando as seguintes variáveis e lógicas:
Detecção de Vela de Alta ou Baixa:
vela_de_alta: Verdadeiro se a vela anterior fechou em alta.
vela_de_baixa: Verdadeiro se a vela anterior fechou em baixa.
Análise de Topos e Fundos:
Para evitar abrir ordens próximas de topos e fundos, o script utiliza a função find_top_and_bottom(periodo), que analisa as últimas 500 velas e identifica o valor mais alto (topo) e o valor mais baixo (fundo).
As variáveis topo_atual e fundo_atual armazenam esses valores.
topo_proximo e fundo_proximo indicam se a vela atual está perto de um topo (evita compra) ou de um fundo (evita venda).
4. Abertura de Ordens (Compra e Venda)
A cada mudança de hora, o script verifica as condições para abrir ordens de compra ou venda:
Condição para Venda:
A ordem de venda é aberta se a vela anterior foi de alta (vela_de_alta) e não está perto de um topo (not topo_proximo).
Se houver uma ordem de compra aberta, ela é fechada antes da nova ordem de venda.
Condição para Compra:
A ordem de compra é aberta se a vela anterior foi de baixa (vela_de_baixa) e não está perto de um fundo (not fundo_proximo).
Se houver uma ordem de venda aberta, ela é fechada antes da nova ordem de compra.
5. Cálculo de Lucros e Perdas
O cálculo de lucro e perda só é feito dentro do intervalo de datas configurado (data_inicial e data_final):
Lucro e Perda:
lucro_total e perca_total acumulam os valores de lucro e perda de todas as operações durante o período definido.
percentual_ganho e percentual_perca calculam o percentual de ganho e perda em relação ao capital inicial.
6. Exibição dos Resultados no Gráfico
O script exibe no gráfico, próximo das velas, as informações de Lucro Total, Perda Total, % de Ganho e % de Perda:
Resumo da Estratégia
Configuração de Intervalo de Datas: Permite configurar o período para cálculo do lucro e da perda.
Análise de Vela Anterior: Decide se a ordem é de compra ou venda com base na vela anterior.
Prevenção de Entradas em Topos e Fundos: Evita compras em topos e vendas em fundos para reduzir sinais falsos.
Cálculo de Resultados: Acumula lucros, perdas e percentuais dentro do período de datas configurado.
Exibição dos Resultados no Gráfico: Exibe as estatísticas configuradas diretamente no gráfico, próximo das velas.
Systematic Investment Tracker with Enhanced Features DCATürkçe Açıklama:
Bu TradingView Pine Script kodu, belirlenen tarih aralığında iki farklı yatırım stratejisi uygulayarak yatırım performansını analiz etmeyi sağlar. Kullanıcı, "Sürekli Alım" ve "Düştükçe Alım" stratejileri arasında bir karşılaştırma yapabilir. Her stratejide, toplam harcama, elde edilen miktar, ortalama maliyet ve kâr yüzdesi hesaplanır. Kod ayrıca dinamik alım miktarını ayarlama ve grafiksel işaretleyiciler ekleme özelliklerine sahiptir. Performans karşılaştırması için grafik üzerinde bilgi etiketi ve bir tablo sunulur. İki dil arasında geçiş yapma (Türkçe/İngilizce) seçeneği de mevcuttur.
English Description:
This TradingView Pine Script code enables users to analyze investment performance by applying two different investment strategies within a specified date range. Users can compare between "Systematic Purchase" and "Purchase on Decline" strategies. For each strategy, total expenditure, quantity acquired, average cost, and profit percentage are calculated. The script includes options for dynamic purchase adjustment and graphical markers. A performance comparison is presented through an info label and a table on the chart. Additionally, there is an option to switch between English and Turkish languages.
Use AI to create trend trading.This strategy is a trend trading strategy. This strategy used data from AI 2020-2023 as training data.
Based on Binance, it gives you about 6500% return from 2017 to now. But I put this strategy in a margin strategy of 5x. If you calculate the return by 5x, it brings about 783,000,000%.
If you assume there is no fee, you can earn about 8,443,000,000%.
Updated Volume SuperTrend AI (Expo)// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) creativecommons.org
// © Zeiierman
//@version=5
indicator("Volume SuperTrend AI (Expo)", overlay=true)
// ~~ ToolTips {
t1="Number of nearest neighbors in KNN algorithm (k): Increase to consider more neighbors, providing a more balanced view but possibly smoothing out local patterns. Decrease for fewer neighbors to make the algorithm more responsive to recent changes. Number of data points to consider (n): Increase for more historical data, providing a broader context but possibly diluting recent trends. Decrease for less historical data to focus more on recent behavior."
t2="Length of weighted moving average for price (KNN_PriceLen): Higher values create a smoother price line, influencing the KNN algorithm to be more stable but less sensitive to short-term price movements. Lower values enhance responsiveness in KNN predictions to recent price changes but may lead to more noise. Length of weighted moving average for SuperTrend (KNN_STLen): Higher values lead to a smoother SuperTrend line, affecting the KNN algorithm to emphasize long-term trends. Lower values make KNN predictions more sensitive to recent SuperTrend changes but may result in more volatility."
t3="Length of the SuperTrend (len): Increase for a smoother trend line, ideal for identifying long-term trends but possibly ignoring short-term fluctuations. Decrease for more responsiveness to recent changes but risk of more false signals. Multiplier for ATR in SuperTrend calculation (factor): Increase for wider bands, capturing larger price movements but possibly missing subtle changes. Decrease for narrower bands, more sensitive to small shifts but risk of more noise."
t4="Type of moving average for SuperTrend calculation (maSrc): Choose based on desired characteristics. SMA is simple and clear, EMA emphasizes recent prices, WMA gives more weight to recent data, RMA is less sensitive to recent changes, and VWMA considers volume."
t5="Color for bullish trend (upCol): Select to visually identify upward trends. Color for bearish trend (dnCol): Select to visually identify downward trends. Color for neutral trend (neCol): Select to visually identify neutral trends."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for K and N values
k = input.int(3, title = "Neighbors", minval=1, maxval=100,inline="AI", group="AI Settings")
n_ = input.int(10, title ="Data", minval=1, maxval=100,inline="AI", group="AI Settings", tooltip=t1)
n = math.max(k,n_)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for prediction values
KNN_PriceLen = input.int(20, title="Price Trend", minval=2, maxval=500, step=10,inline="AITrend", group="AI Trend")
KNN_STLen = input.int(100, title="Prediction Trend", minval=2, maxval=500, step=10, inline="AITrend", group="AI Trend", tooltip=t2)
aisignals = input.bool(true,title="AI Trend Signals",inline="signal", group="AI Trend")
Bullish_col = input.color(color.lime,"",inline="signal", group="AI Trend")
Bearish_col = input.color(color.red,"",inline="signal", group="AI Trend")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define SuperTrend parameters
len = input.int(10, "Length", minval=1,inline="SuperTrend", group="Super Trend Settings")
factor = input.float(3.0,step=.1,inline="SuperTrend", group="Super Trend Settings", tooltip=t3)
maSrc = input.string("WMA","Moving Average Source", ,inline="", group="Super Trend Settings", tooltip=t4)
upCol = input.color(color.lime,"Bullish Color",inline="col", group="Super Trend Coloring")
dnCol = input.color(color.red,"Bearish Color",inline="col", group="Super Trend Coloring")
neCol = input.color(color.blue,"Neutral Color",inline="col", group="Super Trend Coloring", tooltip=t5)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Calculate the SuperTrend based on the user's choice
vwma = switch maSrc
"SMA" => ta.sma(close*volume, len) / ta.sma(volume, len)
"EMA" => ta.ema(close*volume, len) / ta.ema(volume, len)
"WMA" => ta.wma(close*volume, len) / ta.wma(volume, len)
"RMA" => ta.rma(close*volume, len) / ta.rma(volume, len)
"VWMA" => ta.vwma(close*volume, len) / ta.vwma(volume, len)
atr = ta.atr(len)
upperBand = vwma + factor * atr
lowerBand = vwma - factor * atr
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or close < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend
if na(atr )
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Collect data points and their corresponding labels
price = ta.wma(close,KNN_PriceLen)
sT = ta.wma(superTrend,KNN_STLen)
data = array.new_float(n)
labels = array.new_int(n)
for i = 0 to n - 1
data.set(i, superTrend )
label_i = price > sT ? 1 : 0
labels.set(i, label_i)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define a function to compute distance between two data points
distance(x1, x2) =>
math.abs(x1 - x2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define the weighted k-nearest neighbors (KNN) function
knn_weighted(data, labels, k, x) =>
n1 = data.size()
distances = array.new_float(n1)
indices = array.new_int(n1)
// Compute distances from the current point to all other points
for i = 0 to n1 - 1
x_i = data.get(i)
dist = distance(x, x_i)
distances.set(i, dist)
indices.set(i, i)
// Sort distances and corresponding indices in ascending order
// Bubble sort method
for i = 0 to n1 - 2
for j = 0 to n1 - i - 2
if distances.get(j) > distances.get(j + 1)
tempDist = distances.get(j)
distances.set(j, distances.get(j + 1))
distances.set(j + 1, tempDist)
tempIndex = indices.get(j)
indices.set(j, indices.get(j + 1))
indices.set(j + 1, tempIndex)
// Compute weighted sum of labels of the k nearest neighbors
weighted_sum = 0.
total_weight = 0.
for i = 0 to k - 1
index = indices.get(i)
label_i = labels.get(index)
weight_i = 1 / (distances.get(i) + 1e-6)
weighted_sum += weight_i * label_i
total_weight += weight_i
weighted_sum / total_weight
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Classify the current data point
current_superTrend = superTrend
label_ = knn_weighted(data, labels, k, current_superTrend)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot
col = label_ == 1?upCol:label_ == 0?dnCol:neCol
plot(current_superTrend, color=col, title="Volume Super Trend AI")
upTrend = plot(superTrend==lowerBand?current_superTrend:na, title="Up Volume Super Trend AI", color=col, style=plot.style_linebr)
Middle = plot((open + close) / 2, display=display.none, editable=false)
downTrend = plot(superTrend==upperBand?current_superTrend:na, title="Down Volume Super Trend AI", color=col, style=plot.style_linebr)
fill_col = color.new(col,90)
fill(Middle, upTrend, fill_col, fillgaps=false,title="Up Volume Super Trend AI")
fill(Middle, downTrend, fill_col, fillgaps=false, title="Down Volume Super Trend AI")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Ai Super Trend Signals
Start_TrendUp = col==upCol and (col !=upCol or col ==neCol) and aisignals
Start_TrendDn = col==dnCol and (col !=dnCol or col ==neCol) and aisignals
// ~~ Add buy and sell signals
plotshape(Start_TrendUp, title="Buy Signal", location=location.belowbar, color=Bullish_col, style=shape.labelup, text="BUY")
plotshape(Start_TrendDn, title="Sell Signal", location=location.abovebar, color=Bearish_col, style=shape.labeldown, text="SELL")
Low Price VolatilityI highlighted periods of low price volatility in the Nikkei 225 futures trading.
It is Japan Standard Time (JST)
This script is designed to color-code periods in the Nikkei 225 futures market according to times when prices tend to be more volatile and times when they are less volatile. The testing period is from March 11, 2024, to November 1, 2024. It identifies periods and counts where price movement exceeded half of the ATR, and colors are applied based on this data. There are no calculations involved; it simply uses the results of the analysis to apply color.
Volume Bars [jpkxyz]
Multi-Timeframe Volume indicator by @jpkxyz
This script is a Multi-Timeframe Volume Z-Score Indicator. It dynamically calculates /the Z-Score of volume over different timeframes to assess how significantly current
volume deviates from its historical average. The Z-Score is computed for each
timeframe independently and is based on a user-defined lookback period. The
script switches between timeframes automatically, adapting to the chart's current
timeframe using `timeframe.multiplier`.
The Z-Score formula used is: (current volume - mean) / standard deviation, where
mean and standard deviation are calculated over the lookback period.
The indicator highlights periods of "significant" and "massive" volume by comparing
the Z-Score to user-specified thresholds (`zScoreThreshold` for significant volume
and `massiveZScoreThreshold` for massive volume). The script flags buy or sell
conditions based on whether the current close is higher or lower than the open.
Visual cues:
- Dark Green for massive buy volume.
- Red for massive sell volume.
- Green for significant buy volume.
- Orange for significant sell volume.
- Gray for normal volume.
The script also provides customizable alert conditions for detecting significant or massive buy/sell volume events, allowing users to set real-time alerts.
FTMO Rules MonitorFTMO Rules Monitor: Stay on Track with Your FTMO Challenge Goals
TLDR; You can test with this template whether your strategy for one asset would pass the FTMO challenges step 1 then step 2, then with real money conditions.
Passing a prop firm challenge is ... challenging.
I believe a toolkit allowing to test in minutes whether a strategy would have passed a prop firm challenge in the past could be very powerful.
The FTMO Rules Monitor is designed to help you stay within FTMO’s strict risk management guidelines directly on your chart. Whether you’re aiming for the $10,000 or the $200,000 account challenge, this tool provides real-time tracking of your performance against FTMO’s rules to ensure you don’t accidentally breach any limits.
NOTES
The connected indicator for this post doesn't matter.
It's just a dummy double supertrends (see below)
The strategy results for this script post does not matter as I'm posting a FTMO rules template on which you can connect any indicator/strategy.
//@version=5
indicator("Supertrends", overlay=true)
// Supertrend 1 Parameters
var string ST1 = "Supertrend 1 Settings"
st1_atrPeriod = input.int(10, "ATR Period", minval=1, maxval=50, group=ST1)
st1_factor = input.float(2, "Factor", minval=0.5, maxval=10, step=0.5, group=ST1)
// Supertrend 2 Parameters
var string ST2 = "Supertrend 2 Settings"
st2_atrPeriod = input.int(14, "ATR Period", minval=1, maxval=50, group=ST2)
st2_factor = input.float(3, "Factor", minval=0.5, maxval=10, step=0.5, group=ST2)
// Calculate Supertrends
= ta.supertrend(st1_factor, st1_atrPeriod)
= ta.supertrend(st2_factor, st2_atrPeriod)
// Entry conditions
longCondition = direction1 == -1 and direction2 == -1 and direction1 == 1
shortCondition = direction1 == 1 and direction2 == 1 and direction1 == -1
// Optional: Plot Supertrends
plot(supertrend1, "Supertrend 1", color = direction1 == -1 ? color.green : color.red, linewidth=3)
plot(supertrend2, "Supertrend 2", color = direction2 == -1 ? color.lime : color.maroon, linewidth=3)
plotshape(series=longCondition, location=location.belowbar, color=color.green, style=shape.triangleup, title="Long")
plotshape(series=shortCondition, location=location.abovebar, color=color.red, style=shape.triangledown, title="Short")
signal = longCondition ? 1 : shortCondition ? -1 : na
plot(signal, "Signal", display = display.data_window)
To connect your indicator to this FTMO rules monitor template, please update it as follow
Create a signal variable to store 1 for the long/buy signal or -1 for the short/sell signal
Plot it in the display.data_window panel so that it doesn't clutter your chart
signal = longCondition ? 1 : shortCondition ? -1 : na
plot(signal, "Signal", display = display.data_window)
In the FTMO Rules Monitor template, I'm capturing this external signal with this input.source variable
entry_connector = input.source(close, "Entry Connector", group="Entry Connector")
longCondition = entry_connector == 1
shortCondition = entry_connector == -1
🔶 USAGE
This indicator displays essential FTMO Challenge rules and tracks your progress toward meeting each one. Here’s what’s monitored:
Max Daily Loss
• 10k Account: $500
• 25k Account: $1,250
• 50k Account: $2,500
• 100k Account: $5,000
• 200k Account: $10,000
Max Total Loss
• 10k Account: $1,000
• 25k Account: $2,500
• 50k Account: $5,000
• 100k Account: $10,000
• 200k Account: $20,000
Profit Target
• 10k Account: $1,000
• 25k Account: $2,500
• 50k Account: $5,000
• 100k Account: $10,000
• 200k Account: $20,000
Minimum Trading Days: 4 consecutive days for all account sizes
🔹 Key Features
1. Real-Time Compliance Check
The FTMO Rules Monitor keeps track of your daily and total losses, profit targets, and trading days. Each metric updates in real-time, giving you peace of mind that you’re within FTMO’s rules.
2. Color-Coded Visual Feedback
Each rule’s status is shown clearly with a ✓ for compliance or ✗ if the limit is breached. When a rule is broken, the indicator highlights it in red, so there’s no confusion.
3. Completion Notification
Once all FTMO requirements are met, the indicator closes all open positions and displays a celebratory message on your chart, letting you know you’ve successfully completed the challenge.
4. Easy-to-Read Table
A table on your chart provides an overview of each rule, your target, current performance, and whether you’re meeting each goal. The table adjusts its color scheme based on your chart settings for optimal visibility.
5. Dynamic Position Sizing
Integrated ATR-based position sizing helps you manage risk and avoid large drawdowns, ensuring each trade aligns with FTMO’s risk management principles.
Daveatt
TradingIQ - Counter Strike IQIntroducing "Counter Strike IQ" by TradingIQ
Counter Strike IQ is an exclusive trading algorithm developed by TradingIQ, designed to trade upside/downside breakouts of varying significance. By integrating artificial intelligence and IQ Technology, Counter Strike IQ analyzes historical and real-time price data to construct a dynamic trading system adaptable to various asset and timeframe combinations.
Philosophy of Counter Strike IQ
Counter Strike IQ operates on a single premise: Support and resistance levels cannot hold forever. At some point either side must break for the underlying asset to exhibit trends; otherwise, prices would be confined to an infinitely narrowing range.
Counter Strike IQ is designed to work straight out of the box. In fact, its simplicity requires just four user settings to manage output, making it incredibly straightforward to manage.
Minimum ATR Profit, Minimum ATR Stop, EMA Filter and EMA Filter Length are the only settings that manage the performance of Counter Strike IQ!
Traders don’t have to spend hours adjusting settings and trying to find what works best - Counter Strike IQ handles this on its own.
Key Features of Counter Strike IQ
Self-Learning Breakout Detection
Employs AI and IQ Technology to identify notable breakouts in real-time.
AI-Generated Trading Signals
Provides breakout trading signals derived from self-learning algorithms.
Comprehensive Trading System
Offers clear entry and exit labels.
Performance Tracking
Records and presents trading performance data, easily accessible for user analysis.
Self-Learning Trading Exits
Counter Strike IQ learns where to exit positions.
Long and Short Trading Capabilities
Supports both long and short positions to trade various market conditions.
Strike Channel
The Strike Channel represents what Counter Strike IQ considers a tradable long opportunity or a tradable short opportunity. The Strike Channel is dynamic and adjusts from chart to chart.
IQ Graph Gradient
Introduces the IQ Graph Gradient, designed to classify extreme values in price on a grand scale.
How It Works
Counter Strike IQ operates on a straightforward heuristic: go long during significant upside price moves that break established resistance levels and go short during significant downside price moves that break established support levels.
IQ Technology, TradingIQ's proprietary AI algorithm, defines what constitutes a “significant price move” and what’s considered a tradable breakout. For Counter Strike IQ, this algorithm evaluates all historical support/resistance breaks and any subsequent breakouts. For instance, the price move following up to a breakout is measured and learned from, including the significance of the identified support/resistance level (how long it’s been active, how far price moved away from it, etc). By analyzing these patterns, Counter Strike IQ adapts to identify and trade similar future breakout sequences.
In simple terms, Counter Strike IQ learns from violations of historical support/resistance levels to identify potential entry points at currently established support/resistance levels. Using this knowledge, it determines the optimal, current support/resistance price level where a breakout has a higher chance of occurring.
For long positions, Counter Strike IQ places a stop-market order at the AI-identified resistance point. If price violates this level a market order will be placed and a long position entered. Of course, this is how the algorithm trades, users can elect to use a stop-limit order amongst other order types for position entry. After the position is entered TP1 is placed (identifiable on the price chart). TP1 has a twofold purpose:
Acts as a legitimate profit target to exit 50% of the position.
Once TP1 is closed over, the initial stop loss is converted to a trailing stop, and the long position remains active so long as price continues to uptrend.
For short positions, Counter Strike IQ places a stop-market order at the AI-identified support point. If price violates this level a market order will be placed and a short position entered. Again, this is how the algorithm trades, users can elect to use a stop-limit order amongst other order types for position entry. Upon entry TP1 is placed (identifiable on the price chart). TP1 has a twofold purpose:
Acts as a legitimate profit target to exit 50% of the position.
Once TP1 is closed over, the initial stop loss is converted to a trailing stop, and the short position remains active so long as price continues to downtrend.
As a trading system, Counter Strike IQ exits TP1 using a limit order, with all stop losses exited as stop market orders.
What Classifies As a Tradable Upside Breakout or Tradable Downside Breakout?
For Counter Strike IQ, tradable price breakouts are not manually set but are instead learned by the system. What qualifies as a significant upside or downside breakout in one market might not hold the same significance in another. Counter Strike IQ continuously analyzes historical and current support/resistance levels, how far price has extended from those levels, the raw-dollar price move leading up to a violation of those levels, their longevity, and more, to determine which future levels have a higher chance of breaking out when retested!
The image above illustrates the Strike Channel and explains the corresponding prices and levels
The green upper line represents the Long Breakout Point.
The pink lower line represents the Short Breakout Point.
Any price between the two deviation points is considered “Acceptable”.
The image above shows a long position being entered after the Upside Breakout Point was reached.
Green arrows indicate that the strategy entered a long position at the highlighted price level.
Blue arrows indicate that the strategy exited a position, whether at TP1, the initial stop loss, or at the trailing stop.
Blue lines indicate the TP1 level for the current trade. Red lines indicate the initial stop loss price.
If price closes above TP1, the initial stop loss will be replaced with a trailing stop. A blue line (similar to the blue line shown for TP1) will trail price and correspond to the trailing stop price of the trade.
The image above shows the trailing stop price, represented by a blue line, used for the long position!
You can also hover over the trade labels to get more information about the trade—such as the entry price and exit price.
The image above shows a short position being entered after the Downside Breakout Point was reached.
Red arrows indicate that the strategy entered a short position at the highlighted price level.
Blue arrows indicate that the strategy exited a position, whether at TP1, the initial stop loss, or at the trailing stop.
Blue lines indicate the TP1 level for the current trade. Red lines indicate the initial stop loss price.
If price closes below TP1, the initial stop loss will be replaced with a trailing stop. A blue line (similar to the blue line shown for TP1) will trail price and correspond to the trailing stop price of the trade.
The image above shows the trailing stop price, represented by a blue line, used for the short position!
You can also hover over the trade labels to get more information about the trade—such as the entry price and exit price.
IQ Gradient Graph
The IQ Gradient Graph provides a macro characterization of extreme prices.
The lower macro extremity of the IQ Gradient Graph is colored green, while the upper macro extremity is colored red.
Minimum Profit Target And Stop Loss
The Minimum ATR Profit Target and Minimum ATR Stop Loss setting control the minimum allowed profit target and stop loss distance. On most timeframes users won’t have to alter these settings; however, on very-low timeframes such as the 1-minute chart, users can increase these values so gross profits exceed commission.
After changing either setting, Counter Strike IQ will retrain on historical data - accounting for the newly defined minimum profit target or stop loss.
AI Direction
The AI Direction setting controls the trade direction Counter Strike IQ is allowed to take.
“Trade Longs” allows for long trades.
“Trade Shorts” allows for short trades.
EMA Filter
The EMA Filter setting controls whether the AI should implement an EMA trading filter. Simply, if the EMA Filter is active, long trades can only initiate if price is trading above the user-defined EMA. Conversely, short trades can only initiate if price is trading below the user-defined EMA.
The image above shows the EMA Filter in action!
Verifying Counter Strike IQ’s Effectiveness
Counter Strike IQ automatically tracks its performance and displays the profit factor for the long strategy and the short strategy it uses. This information can be found in the table located in the top-right corner of your chart showing.
This table shows the long strategy profit factor and the short strategy profit factor.
The image above shows the long strategy profit factor and the short strategy profit factor for Counter Strike IQ.
A profit factor greater than 1 indicates a strategy profitably traded historical price data.
A profit factor less than 1 indicates a strategy unprofitably traded historical price data.
A profit factor equal to 1 indicates a strategy did not lose or gain money when trading historical price data.
Using Counter Strike IQ
While Counter Strike IQ is a full-fledged trading system with entries and exits - manual traders can certainly make use of its on chart indications and visualizations.
The hallmark feature of Counter Strike IQ is its ability to signal a breakout near its origin point. Long entries are often signaled near the start of a large upside price move; short entries are often signaled near the start of a large downside price move.
For live analysis, the Strike Channel serves as a valuable tool for identifying breakout points.
The further price moves toward the Upside Breakout Point (green), the stronger the indication that price might breakout to the upside. Conversely, the deeper price reaches toward the Downside Breakout Point (red), the stronger the indication that price might breakout to the downside.
Of course, should buying or selling pressure stall, price may fail to breakout at the identified breakout level. This is a natural consequence of any breakout trading strategy!
With this information at hand, traders can quickly switch between charts and timeframes to identify optimized areas of interest.
Dynamic Market Correlation Analyzer (DMCA) v1.0Description
The Dynamic Market Correlation Analyzer (DMCA) is an advanced TradingView indicator designed to provide real-time correlation analysis between multiple assets. It offers a comprehensive view of market relationships through correlation coefficients, technical indicators, and visual representations.
Key Features
- Multi-asset correlation tracking (up to 5 symbols)
- Dynamic correlation strength categorization
- Integrated technical indicators (RSI, MACD, DX)
- Customizable visualization options
- Real-time price change monitoring
- Flexible timeframe selection
## Use Cases
1. **Portfolio Diversification**
- Identify highly correlated assets to avoid concentration risk
- Find negatively correlated assets for hedging strategies
- Monitor correlation changes during market events
2. Pairs Trading
- Detect correlation breakdowns for potential trading opportunities
- Track correlation strength for pair selection
- Monitor technical indicators for trade timing
3. Risk Management
- Assess portfolio correlation risk in real-time
- Monitor correlation shifts during market stress
- Identify potential portfolio vulnerabilities
4. **Market Analysis**
- Study sector relationships and rotations
- Analyze cross-asset correlations (e.g., stocks vs. commodities)
- Track market regime changes through correlation patterns
Components
Input Parameters
- **Timeframe**: Custom timeframe selection for analysis
- **Length**: Correlation calculation period (default: 20)
- **Source**: Price data source selection
- **Symbol Selection**: Up to 5 customizable symbols
- **Display Options**: Table position, text color, and size settings
Technical Indicators
1. **Correlation Coefficient**
- Range: -1 to +1
- Strength categories: Strong/Moderate/Weak (Positive/Negative)
2. **RSI (Relative Strength Index)**
- 14-period default setting
- Momentum comparison across assets
3. **MACD (Moving Average Convergence Divergence)**
- Standard settings (12, 26, 9)
- Trend direction indicator
4. **DX (Directional Index)**
- Trend strength measurement
- Based on DMI calculations
Visual Components
1. **Correlation Table**
- Symbol identifiers
- Correlation coefficients
- Correlation strength descriptions
- Price change percentages
- Technical indicator values
2. **Correlation Plot**
- Real-time correlation visualization
- Multiple correlation lines
- Reference levels at -1, 0, and +1
- Color-coded for easy identification
Installation and Setup
1. Load the indicator on TradingView
2. Configure desired symbols (up to 5)
3. Adjust timeframe and calculation length
4. Customize display settings
5. Enable/disable desired components (table, plot, RSI)
Best Practices
1. **Symbol Selection**
- Choose related but distinct assets
- Include a mix of asset classes
- Consider market cap and liquidity
2. **Timeframe Selection**
- Match timeframe to trading strategy
- Consider longer timeframes for strategic analysis
- Use shorter timeframes for tactical decisions
3. **Interpretation**
- Monitor correlation changes over time
- Consider multiple timeframes
- Combine with other technical analysis tools
- Account for market conditions and volatility
Performance Notes
- Calculations update in real-time
- Resource usage scales with number of active symbols
- Historical data availability may affect initial calculations
Version History
- v1.0: Initial release with core functionality
- Multi-symbol correlation analysis
- Technical indicator integration
- Customizable display options
Future Enhancements (Planned)
- Additional technical indicators
- Advanced correlation algorithms
- Enhanced visualization options
- Custom alert conditions
- Statistical significance testing
[Volatility] [Gain & Loss] - OverviewFX:EURUSD
Indicator Overview: Volatility & Gain/Loss - Forex Pair Analysis
This indicator, " —Overview" , is designed for users interested in analyzing the volatility and gain/loss metrics of multiple forex pairs. The tool is especially useful for traders aiming to assess currency pair volatility alongside gain and loss percentages over selected periods. It enables a clearer understanding of pair behavior and aids in decision-making.
Key Features
Customizable Volatility and Gain/Loss Periods : Define your preferred calculation periods and timeframes for both volatility and gain/loss to tailor the indicator to specific trading strategies. Multi-Pair Analysis : This indicator supports up to six forex pairs (default pairs include EURUSD, GBPUSD, USDJPY, USDCHF, AUDUSD, and USDCAD) and allows you to adjust these pairs as needed. Visual Ranking : Forex pairs are sorted by volatility, displaying the highest pairs at the top for quick reference. Top Gain/Loss Highlighting : The pair with the maximum gain and the pair with the maximum loss are highlighted in the table, making it easy to identify the best and worst performers at a glance.
Indicator Settings
Volatility Settings : Period : Adjust the number of periods used in the ATR (Average True Range) calculation. A default period of 14 is set. Timeframe : Select a timeframe (e.g., Daily, Weekly) for volatility calculation to match your analysis preference.
Gain/Loss Settings : Period : Choose the number of periods for gain/loss calculation. The default is set to 1. Timeframe : Select the timeframe for gain/loss calculation, independent of the volatility timeframe.
Symbol Selection : Configure up to six forex pairs. By default, popular forex pairs are pre-loaded but can be customized to include other currency pairs.
Output and Visualization
Table Display : This indicator displays data in a neatly structured table positioned in the top-right corner of your chart. Columns : Includes columns for the Forex Pair, Volatility Percentage, Gain Percentage, and Loss Percentage. Color Coding : Volatility is displayed in a standard color for clear readability. Gain values are highlighted in green, and Loss values are highlighted in red, allowing for quick visual differentiation. Highlighting : Rows representing the pair with the highest gain and the pair with the most significant loss are especially highlighted for emphasis.
How to Use
Volatility Analysis : This metric gives insight into the average price range movements for each pair over the specified period and timeframe, helping you evaluate the potential for rapid price changes. Gain/Loss Tracking : Gain or loss percentages show the pair's recent performance, allowing you to observe whether a currency pair is trending positively or negatively over the chosen period. Comparative Pair Ranking : Use the table to identify pairs with the highest volatility and extremes in gain or loss to guide trading decisions based on market conditions.
Ideal For
Swing Traders and Day Traders looking to understand short-term market fluctuations in currency pairs. Risk Management : Helps traders gauge pairs with higher risk (volatility) and recent performance (gain/loss) for informed position sizing and risk control.
This indicator is a comprehensive tool for visualizing and analyzing key forex pairs, making it an essential addition for traders looking to stay updated on volatility trends and recent price changes.
AutoCorrelation Test [OmegaTools]Overview
The AutoCorrelation Test indicator is designed to analyze the correlation patterns of a financial asset over a specified period. This tool can help traders identify potential predictive patterns by measuring the relationship between sequential returns, effectively assessing the autocorrelation of price movements.
Autocorrelation analysis is useful in identifying the consistency of directional trends (upward or downward) and potential cyclical behavior. This indicator provides an insight into whether recent price movements are likely to continue in a similar direction (positive correlation) or reverse (negative correlation).
Key Features
Multi-Period Autocorrelation: The indicator calculates autocorrelation across three periods, offering a granular view of price movement consistency over time.
Customizable Length & Sensitivity: Adjustable parameters allow users to tailor the length of analysis and sensitivity for detecting correlation.
Visual Aids: Three separate autocorrelation plots are displayed, along with an average correlation line. Dotted horizontal lines mark the thresholds for positive and negative correlation, helping users quickly assess potential trend continuation or reversal.
Interpretive Table: A table summarizing correlation status for each period helps traders make quick, informed decisions without needing to interpret the plot details directly.
Parameters
Source: Defines the price source (default: close) for calculating autocorrelation.
Length: Sets the analysis period, ranging from 10 to 2000 (default: 200).
Sensitivity: Adjusts the threshold sensitivity for defining correlation as positive or negative (default: 2.5).
Interpretation
Above 50 + Sensitivity: Indicates Positive Correlation. The price movements over the selected period are likely to continue in the same direction, potentially signaling a trend continuation.
Below 50 - Sensitivity: Indicates Negative Correlation. The price movements show a likelihood of reversing, which could signal an upcoming trend reversal.
Between 50 ± Sensitivity: Indicates No Correlation. Price movements are less predictable in direction, with no clear trend continuation or reversal tendency.
How It Works
The indicator calculates the logarithmic returns of the selected source price over each length period.
It then compares returns over consecutive periods, categorizing them as either "winning" (consistent direction) or "losing" (inconsistent direction) movements.
The result for each period is displayed as a percentage, with values above 50% indicating a higher degree of directional consistency (positive or negative).
A table updates with descriptive labels (Positive Correlation, Negative Correlation, No Correlation) for each tested period, providing a quick overview.
Visual Elements
Plots:
AutoCorrelation Test : Displays autocorrelation for the closest period (lag 1).
AutoCorrelation Test : Displays autocorrelation for the second period (lag 2).
AutoCorrelation Test : Displays autocorrelation for the third period (lag 3).
Average: Displays the simple moving average of the three test periods for a smoothed view of overall correlation trends.
Horizontal Lines:
No Correlation (50%): A baseline indicating neutral correlation.
Positive/Negative Correlation Thresholds: Dotted lines set at 50 ± Sensitivity, marking the thresholds for significant correlation.
Usage Guide
Adjust Parameters:
Select the Source to define which price metric (e.g., close, open) will be analyzed.
Set the Length based on your preferred analysis window (e.g., shorter for intraday trends, longer for swing trading).
Modify Sensitivity to fine-tune the thresholds based on market volatility and personal trading preference.
Interpret Table and Plots:
Use the table to quickly check the correlation status of each lag period.
Analyze the plots for changes in correlation. If multiple lags show positive correlation above the sensitivity threshold, a trend continuation may be expected. Conversely, negative values suggest a potential reversal.
Integrate with Other Indicators:
For enhanced insights, consider using the AutoCorrelation Test indicator in conjunction with other trend or momentum indicators.
This indicator offers a powerful method to assess market conditions, identify potential trend continuations or reversals, and better inform trading decisions. Its customization options provide flexibility for various trading styles and timeframes.
RBF Kijun Trend System [InvestorUnknown]The RBF Kijun Trend System utilizes advanced mathematical techniques, including the Radial Basis Function (RBF) kernel and Kijun-Sen calculations, to provide traders with a smoother trend-following experience and reduce the impact of noise in price data. This indicator also incorporates ATR to dynamically adjust smoothing and further minimize false signals.
Radial Basis Function (RBF) Kernel Smoothing
The RBF kernel is a mathematical method used to smooth the price series. By calculating weights based on the distance between data points, the RBF kernel ensures smoother transitions and a more refined representation of the price trend.
The RBF Kernel Weighted Moving Average is computed using the formula:
f_rbf_kernel(x, xi, sigma) =>
math.exp(-(math.pow(x - xi, 2)) / (2 * math.pow(sigma, 2)))
The smoothed price is then calculated as a weighted sum of past prices, using the RBF kernel weights:
f_rbf_weighted_average(src, kernel_len, sigma) =>
float total_weight = 0.0
float weighted_sum = 0.0
// Compute weights and sum for the weighted average
for i = 0 to kernel_len - 1
weight = f_rbf_kernel(kernel_len - 1, i, sigma)
total_weight := total_weight + weight
weighted_sum := weighted_sum + (src * weight)
// Check to avoid division by zero
total_weight != 0 ? weighted_sum / total_weight : na
Kijun-Sen Calculation
The Kijun-Sen, a component of Ichimoku analysis, is used here to further establish trends. The Kijun-Sen is computed as the average of the highest high and the lowest low over a specified period (default: 14 periods).
This Kijun-Sen calculation is based on the RBF-smoothed price to ensure smoother and more accurate trend detection.
f_kijun_sen(len, source) =>
math.avg(ta.lowest(source, len), ta.highest(source, len))
ATR-Adjusted RBF and Kijun-Sen
To mitigate false signals caused by price volatility, the indicator features ATR-adjusted versions of both the RBF smoothed price and Kijun-Sen.
The ATR multiplier is used to create upper and lower bounds around these lines, providing dynamic thresholds that account for market volatility.
Neutral State and Trend Continuation
This indicator can interpret a neutral state, where the signal is neither bullish nor bearish. By default, the indicator is set to interpret a neutral state as a continuation of the previous trend, though this can be adjusted to treat it as a truly neutral state.
Users can configure this setting using the signal_str input:
simple string signal_str = input.string("Continuation of Previous Trend", "Treat 0 State As", options = , group = G1)
Visual difference between "Neutral" (Bottom) and "Continuation of Previous Trend" (Top). Click on the picture to see it in full size.
Customizable Inputs and Settings:
Source Selection: Choose the input source for calculations (open, high, low, close, etc.).
Kernel Length and Sigma: Adjust the RBF kernel parameters to change the smoothing effect.
Kijun Length: Customize the lookback period for Kijun-Sen.
ATR Length and Multiplier: Modify these settings to adapt to market volatility.
Backtesting and Performance Metrics
The indicator includes a Backtest Mode, allowing users to evaluate the performance of the strategy using historical data. In Backtest Mode, a performance metrics table is generated, comparing the strategy's results to a simple buy-and-hold approach. Key metrics include mean returns, standard deviation, Sharpe ratio, and more.
Equity Calculation: The indicator calculates equity performance based on signals, comparing it against the buy-and-hold strategy.
Performance Metrics Table: Detailed performance analysis, including probabilities of positive, neutral, and negative returns.
Alerts
To keep traders informed, the indicator supports alerts for significant trend shifts:
// - - - - - ALERTS - - - - - //{
alert_source = sig
bool long_alert = ta.crossover (intrabar ? alert_source : alert_source , 0)
bool short_alert = ta.crossunder(intrabar ? alert_source : alert_source , 0)
alertcondition(long_alert, "LONG (RBF Kijun Trend System)", "RBF Kijun Trend System flipped ⬆LONG⬆")
alertcondition(short_alert, "SHORT (RBF Kijun Trend System)", "RBF Kijun Trend System flipped ⬇Short⬇")
//}
Important Notes
Calibration Needed: The default settings provided are not optimized and are intended for demonstration purposes only. Traders should adjust parameters to fit their trading style and market conditions.
Neutral State Interpretation: Users should carefully choose whether to treat the neutral state as a continuation or a separate signal.
Backtest Results: Historical performance is not indicative of future results. Market conditions change, and past trends may not recur.
Dual Momentum StrategyThis Pine Script™ strategy implements the "Dual Momentum" approach developed by Gary Antonacci, as presented in his book Dual Momentum Investing: An Innovative Strategy for Higher Returns with Lower Risk (McGraw Hill Professional, 2014). Dual momentum investing combines relative momentum and absolute momentum to maximize returns while minimizing risk. Relative momentum involves selecting the asset with the highest recent performance between two options (a risky asset and a safe asset), while absolute momentum considers whether the chosen asset has a positive return over a specified lookback period.
In this strategy:
Risky Asset (SPY): Represents a stock index fund, typically more volatile but with higher potential returns.
Safe Asset (TLT): Represents a bond index fund, which generally has lower volatility and acts as a hedge during market downturns.
Monthly Momentum Calculation: The momentum for each asset is calculated based on its price change over the last 12 months. Only assets with a positive momentum (absolute momentum) are considered for investment.
Decision Rules:
Invest in the risky asset if its momentum is positive and greater than that of the safe asset.
If the risky asset’s momentum is negative or lower than the safe asset's, the strategy shifts the allocation to the safe asset.
Scientific Reference
Antonacci's work on dual momentum investing has shown the strategy's ability to outperform traditional buy-and-hold methods while reducing downside risk. This approach has been reviewed and discussed in both academic and investment publications, highlighting its strong risk-adjusted returns (Antonacci, 2014).
Reference: Antonacci, G. (2014). Dual Momentum Investing: An Innovative Strategy for Higher Returns with Lower Risk. McGraw Hill Professional.
MAPE of Expected Value and Percent ResidualsOverview
This indicator calculates and visualizes the Mean Absolute Percentage Error (MAPE) and the percent residuals of the expected value compared to the actual closing price. The purpose of this indicator is to provide insights into the accuracy of price forecasts by comparing predicted values to actual market outcomes. The expected values are derived from the transform model, which uses the mean line from the mean and standard deviation lines as an indicator for expected price movement. Users can customize the number of periods over which calculations are averaged.
Inputs
Mean Period (Bars) : Specifies the number of bars used to calculate the moving average of the change between closing prices. This value should match the value used in the mean and standard deviation lines indicator.
MAPE Period (Bars) : Specifies the number of bars used to calculate the moving average of the absolute percentage error.
Outputs
Percent Residuals Histogram : Displays the percentage error between the predicted (expected) value and the actual closing price. The bars are color-coded, with green indicating positive residuals (i.e., the actual value is higher than the predicted value) and red indicating negative residuals (i.e., the actual value is lower than the predicted value).
Reference Line : A horizontal line at zero is added to the chart to indicate the baseline for percent residuals.
Mean Absolute Percentage Error (MAPE) Line : Plots the moving average of the absolute percentage error over the specified period, helping users gauge the average accuracy of their predictions over time.
Methodology
Calculation of Individual Bar Normalized Residuals: The normalized residuals for each bar are computed by taking the difference between the actual closing price and the predicted (expected) value, divided by the closing price. If the actual closing price is above the expected value, the residual is considered positive and is represented in green; otherwise, it is negative and represented in red. This normalization provides a standardized measure of deviation that allows for consistent comparison across different bars.
Mean Absolute Percentage Error (MAPE) Calculation: Over the user-defined period, the absolute values of the normalized residuals are computed and subsequently averaged to determine the Mean Absolute Percentage Error (MAPE). This metric quantifies the average magnitude of the forecast errors, providing a clear indication of the model's predictive accuracy over time.
How to Use
Add Indicators to Chart : First, apply the mean and standard deviation lines indicator to the chart, then add the MAPE of Expected Value and Percent Residuals indicator to evaluate the accuracy of price forecasts.
Set Parameters : Set the `Mean Period (Bars)` to be the same value in both the mean and standard deviation lines indicator and the MAPE indicator to ensure accuracy. Adjust the `MAPE Period (Bars)` to fine-tune the length of historical data used in calculating the MAPE.
Interpret Residuals and MAPE : Use the percent residuals histogram to understand how the actual closing price deviates from predictions. The MAPE line helps track the average prediction accuracy over time.
This tool is particularly useful for traders who want to evaluate the performance of their price prediction models based on the transform model and track how well their expected values, derived from mean and standard deviation lines , align with actual market movements.
XRP Comparative Price Action Indicator - Final VersionXRP Comparative Price Action Indicator - Final Version
The XRP Comparative Price Action Indicator provides a comprehensive visual analysis of XRP’s price movements relative to key cryptocurrencies and market indices. This indicator normalises price data across various assets, allowing traders and investors to assess XRP’s performance against its peers and major market influences at a glance.
Key Features:
• Normalised Price Data: Prices are scaled between 0.00 and 1.00,
enabling straightforward comparisons between different assets.
• Key Comparisons: Includes normalised prices for:
• XRP/USD (Bitstamp)
• XRP Dominance (CryptoCap)
• XRP/BTC (Bitstamp)
• BTC/USD (Bitstamp)
• BTC Dominance (CryptoCap)
• USDT Dominance (CryptoCap)
• S&P 500 (SPY)
• DXY (Dollar Index)
• ETH/USD (Bitstamp)
• ETH Dominance (CryptoCap)
• XRP/ETH (Binance)
• Visual Clarity: Each asset is plotted with distinct colors for easy identification,
with thicker lines enhancing visibility on the chart.
• Reference Lines: Optional horizontal lines indicate the minimum (0) and maximum (1) normalised values, providing clear reference points for analysis.
This indicator is ideal for traders looking to understand XRP’s relative performance, gauge market sentiment, and make informed trading decisions based on comparative price action.
Autocorrelogram (YavuzAkbay)The Autocorrelogram (ACF) is a statistical tool designed for traders and analysts to evaluate the autocorrelation of price movements over time. Autocorrelation measures the correlation of a signal with a delayed version of itself, providing insights into the degree to which past price movements influence future price movements. This indicator is particularly useful for identifying trends and patterns in time series data, helping traders make informed decisions based on historical price behavior.
Key Components and Functionality
1. Input Parameters:
Sample Size: This parameter defines the number of data points used in the calculation of the autocorrelation function. A minimum value of 9 ensures statistical relevance. The default value is set to 100, which provides a broad view of the price behavior.
Data Source: Users can select the price data they wish to analyze (e.g., closing prices). This flexibility allows traders to apply the ACF to various price types, depending on their trading strategy.
Significance Level: This parameter determines the threshold for statistical significance in the autocorrelation values. The default value is set at 1.96, corresponding to a 95% confidence level, but users can adjust it to their preferences.
Calculate Change: This boolean option allows users to choose whether to calculate the change in the selected data source (e.g., daily price changes) rather than using the raw data. Analyzing changes can highlight momentum shifts that may be obscured in absolute price levels.
2. Core Calculations:
Simple Moving Average (SMA): The indicator computes the SMA of the selected data source over the defined sample size. This average serves as a baseline for assessing deviations in price behavior.
Variance Calculation: The variance of the price changes is calculated to understand the spread of the data. The variance is scaled by the sample size to ensure that the autocorrelation values are appropriately normalized.
Lag Value: The indicator calculates a lag value based on the sample size to determine how many periods back the autocorrelation will be calculated. This helps in assessing correlations at different time intervals.
3. Autocorrelation Calculation:
The script calculates the autocorrelation for lags ranging from 0 to 53. For each lag, it computes the autocovariance (the correlation of the signal with itself at different time intervals) and normalizes this by the variance. The result is a set of autocorrelation values that indicate the strength and direction of the relationship between current and past price movements.
4. Visualization:
The autocorrelation values are plotted as lines on the chart, with different colors indicating positive and negative correlations. Lines are dynamically drawn for each lag, providing a visual representation of how past prices influence current prices. A maximum of 54 lines (for lags 0 to 53) is maintained, with the oldest line being removed when the limit is exceeded.
Significance Levels: Horizontal lines are drawn at the defined significance levels, helping traders quickly identify when the autocorrelation values exceed the statistically significant threshold. These lines serve as benchmarks for interpreting the relevance of the autocorrelation values.
How to Use the ACF Indicator
Identifying Trends: Traders can use the ACF indicator to spot trends in the data. Strong positive autocorrelation at a given lag indicates that past price movements have a lasting influence on future movements, suggesting a potential continuation of the current trend. Conversely, significant negative autocorrelation may indicate reversals or mean reversion.
Decision Making: By comparing the autocorrelation values against the significance levels, traders can make informed decisions. For example, if the autocorrelation at lag 1 is significantly positive, it may suggest that a trend is likely to persist in the immediate future, prompting traders to consider long positions.
Setting Parameters: Adjusting the sample size and significance level allows traders to tailor the indicator to their specific market conditions and trading style. A larger sample size may provide more stable estimates but could obscure short-term fluctuations, while a smaller size may capture quick changes but with higher variability.
Combining with Other Indicators: The ACF can be used in conjunction with other technical indicators (like Moving Averages or RSI) to enhance trading strategies. Confirming signals from multiple indicators can provide stronger trade confirmations.
Vertical Line on Custom DateThis Pine Script code creates a custom indicator for TradingView that draws a vertical line on the chart at a specific date and time defined by the user.
User Input: Allows the user to specify the day, hour, and minute when the vertical line should appear.
Vertical Line Drawing: When the current date and time match the user’s inputs, a vertical line is drawn on the chart at the corresponding bar, offset by one bar to align properly.
Customizable Color and Width: The vertical line is displayed in purple with a customizable width.
Overall, this indicator helps traders visually mark important dates and times on their price charts.
Power Root SuperTrend [AlgoAlpha]📈🚀 Power Root SuperTrend by AlgoAlpha - Elevate Your Trading Strategy! 🌟
Introducing the Power Root SuperTrend by AlgoAlpha, an advanced trading indicator that enhances the traditional SuperTrend by incorporating Root-Mean-Square (RMS) calculations for a more responsive and adaptive trend detection. This innovative tool is designed to help traders identify trend directions, potential take-profit levels, and optimize entry and exit points with greater accuracy, making it an excellent addition to your trading arsenal.
Key Features:
🔹 Root-Mean-Square SuperTrend Calculation : Utilizes the RMS of closing prices to create a smoother and more sensitive SuperTrend line that adapts quickly to market changes.
🔸 Multiple Take-Profit Levels : Automatically calculates and plots up to seven take-profit levels (TP1 to TP7) based on market volatility and the change in SuperTrend values.
🟢 Dynamic Trend Coloring : Visually distinguish between bullish and bearish trends with customizable colors for clearer market visualization.
📊 RSI-Based Take-Profit Signals : Incorporates the Relative Strength Index (RSI) of the distance between the price and the SuperTrend line to generate additional take-profit signals.
🔔 Customizable Alerts : Set alerts for trend direction changes, achievement of take-profit levels, and RSI-based take-profit conditions to stay informed without constant chart monitoring.
How to Use:
Add the Indicator : Add the indicator to favorites by pressing the ⭐ icon or search for "Power Root SuperTrend " in the TradingView indicators library and add it to your chart. Adjust parameters such as the ATR multiplier, ATR length, RMS length, and RSI take-profit length to suit your trading style and the specific asset you are analyzing.
Analyze the Chart : Observe the SuperTrend line and the plotted take-profit levels. The color changes indicate trend directions—green for bullish and red for bearish trends.
Set Alerts : Utilize the built-in alert conditions to receive notifications when the trend direction changes, when each TP level is drawn, or when RSI-based take-profit conditions are met.
How It Works:
The Power Root SuperTrend indicator enhances traditional SuperTrend calculations by applying a Root-Mean-Square (RMS) function to the closing prices, resulting in a more responsive trend line that better reflects recent price movements. It calculates the Average True Range (ATR) to determine the volatility and sets the upper and lower SuperTrend bands accordingly. When a trend direction change is detected—signified by the SuperTrend line switching from above to below the price or vice versa—the indicator calculates the change in the SuperTrend value. This change is then used to establish multiple take-profit levels (TP1 to TP7), each representing incremental targets based on market volatility. Additionally, the indicator computes the RSI of the distance between the current price and the SuperTrend line to generate extra take-profit signals when the RSI crosses under a specific threshold. The combination of RMS calculations, multiple TP levels, dynamic coloring, and RSI signals provides traders with a comprehensive tool for identifying trends and optimizing trade exits. Customizable alerts ensure that traders can stay updated on important market developments without needing to constantly watch the charts.
Elevate your trading strategy with the Power Root SuperTrend indicator and gain a smarter edge in the markets! 🚀✨