[blackcat] L3 Candle Skew 3821 TraderLevel 3
Background
By modeling skew to produce long and short entry points.
Function
The concept of skew comes from physics and statistics, and is used in market technical analysis to reflect the expectation of future stock price distribution. Because the return distribution of stocks in the trend market has skew (Skew), it is reasonable to judge the trend continuity according to the historical and current skew. It is precisely because the stock price rises that there is a skew. The greater the strength of the rise, the greater the angle of inclination and the greater the skew. The degree of this upward or downward slope in the statistical distribution of stock prices is defined as skew. Through the size of skew, we can know the direction, inertia and extent of the stock's rise or fall, and find stocks with a high probability of quick profit. The technical indicator introduced today is a simplified but effective stock price skew model used to generate buying and selling points.
The principle of this technical indicator is based on the success rate test results of different moving averages corresponding to different skews as follows:
10 trading cycles profit 5% success rate (%)
5 period moving average 10 period moving average 20 period moving average 30 period moving average 60 period moving average
skew>=0 51.36 52.26 52.65 52.55 52.08
skew>=0.5 55.44 58.06 60.56 62.37 65.66
skew>=1 59.72 63.06 67.07 69.78 70.62
skew>=1.5 63.01 67.08 71.61 72.9 70.61
skew>=2 65.53 70.22 74.18 73.76 70.12
skew>=2.5 67.89 72.93 75.32 73.66 68.92
skew>=3 70.07 75.32 75.69 72.54 67.45
skew>=3.5 71.85 77.05 75.32 73.63 63.82
skew>=4 73.6 78.06 74.19 68.96 59.91
skew>=4.5 76.04 78.56 72.85 69.55 49.24
skew>=5 77.44 78.88 71.58 67.28 51.69
skew>=5.5 78.97 78.39 70.33 64.31 49.7
skew>=6 79.68 78.07 68.82 61.65 53.57
Table 1
As can be seen from the above table, with the increase of the 5-period and 10-period moving average skew values, the success rate is increasing, but after the 20- and 30-period moving average skew values increase to an upper bound, it shows a downward trend. When the skew of the 20-period and 30-period moving averages is greater than 0.5, the 10-period profit of 5% is above 60%, and when it is greater than 1.5, the success rate can reach above 70%. The larger the 5-period moving average skew, the higher the success rate, but often because the short-term skew is too large, the stock price has risen rapidly to a high level, and chasing up is risky, which is not suitable for the investment habits of most people, so prudent investors may like to do swings. Investors may wish to pay more attention to the skew of the 20-period and 30-period moving averages. Based on the above analysis, as a short-term trading enthusiast, I need to choose the 5-period and 10-period moving average skew, and consider the medium-term trend as a compromise, and I also need to consider the 20-period moving average skew. Finally, according to the principle of personal preference, I chose 3 groups of periods based on Fibonacci magic numbers: 3 periods, 8 periods, 21 periods, and skews that take into account both short-term and mid-line trends. So, I named this indicator number 3821 as a distinction.
002084 1D from TradingView
BTCUSDT 1H from TradingView
Tesla 1D from TradingView
Buscar en scripts para "腾讯10大股东"
GT 5.1 Strategy═════════════════════════════════════════════════════════════════════════
█ OVERVIEW
People often look an indicator in their technical analysis to enter a position. We may also need to look at the signals of one or more indicators to verify the signals given by some indicators. In this context, I developed a strategy to test whether it really works by choosing some of the indicators that capture trend changes with the same characteristics. Also, since the subject is to catch the trend change, I thought it would be right to include an indicator using the heikin ashi logic. By averaging and smoothing the market noise, Heiken Ashi makes it easier to detect the direction of the trend helps to see possible reversal points on the chart. However, it should be noted that Heiken Ashi is a lagging indicator.
I picked 5 different indicators (but their purpose are similar) and combined them to produce buy and sell signals based on your choice(not repaint). First of all let's get some information about our indicators. So you will understand me why i picked these indicators and what is the meaning of their signals.
1 — Coral Trend Indicator by LazyBear
Coral Trend Indicator is a linear combination of moving averages, all obtained by a triple or higher order exponential smoothing. The indicator comes with a trend indication which is based on the normalized slope of the plot. the usage of this indicator is simple. When the color of the line is green that means the market is in uptrend. But when the color is red that means the market is in downtrend.
As you see the original indicator it is simple to find is it in uptrend or downtrend.
So i added a code to find when the color of the line change. When it turns green to red my script giving sell signals, when it turns red to green it gives buy signals.
I hide the candles to show you more clearly what is happening when you choose only Coral Strategy. But sometimes it is not enough only using itself. Even if green dots turn to red it continues in uptrend. So we need a to look another indicator to approve our signal.
2 — SSL channel by ErwinBeckers
Known as the SSL , the Semaphore Signal Level channel is an indicator that combines moving averages to provide you with a clear visual signal of price movement dynamics. In short, it's designed to show you when a price trend is forming. This indicator creates a band by calculating the high and low values according to the determined period. Simply if you decide 10 as period, it calculates a 10-period moving average on the latest 10 highs. Calculate a 10-period moving average on the latest 10 lows. If the price falls below the low band, the downtrend begins, if the price closes above the high band, the uptrend begins. Lets look the original form of indicator and learn how it using.
If the red line is below and the green band is above, it means that we are in uptrend, and if it is on the opposite side, it means that we are in downtrend. Therefore, it would be logical to enter a position where the trend has changed. So i added a code to find when the crossover has occured.
As you see in my strategy, it gives you signals when the trend has changed. But sometimes it is not enough only using this indicator itself. So lets look 2 indicator together in one chart.
Look circle SSL is saying it is in downtrend but Coral is saying it has entered in uptrend. if we just look to coral signal it can misleads us. So it can be better to look another indicator for validating our signals.
3 — Heikin Ashi RSI Oscillator by JayRogers
The Heikin-Ashi technique is used by technical traders to identify a given trend more easily. Heikin-Ashi has a smoother look because it is essentially taking an average of the movement. There is a tendency with Heikin-Ashi for the candles to stay red during a downtrend and green during an uptrend, whereas normal candlesticks alternate color even if the price is moving dominantly in one direction. This indicator actually recalculates the RSI indicator with the logic of heikin ashi. Due to smoothing, the bars are formed with a slight lag, reflecting the trend rather than the exact price movement. So lets look the original version to understand more clearly. If red bars turn to green bars it means uptrend may begin, if green bars turn to red it means downtrend may begin.
As you see HARSI giving lots of signal some of them is really good but some of them are not very well. Because it gives so much signals Now i will change time period and lets look same chart again.
Now results are better because of heikin ashi's logic. it is not suitable for day traders, it gives more accurate result when using the time period is longer. But it can be useful to use this indicator in short time periods using with other indicators. So you may catch the trend changes more accurately.
4 — MACD DEMA by ToFFF
This indicator uses a double EMA and MACD algorithm to analyze the direction of the trend. Though it might seem a tough task to manage the trades with the help of MACD DEMA once you know how the proper way to interpret the signal lines, it will be an easy task.
This indicator also smoothens the signal lines with the time series algorithm which eventually makes the higher time frame important. So, expecting better results in the lower time frame can result in big losses as the data reading from the MACD DEMA will not be accurate. In order to understand the function of this indicator, you have to know the functions of the EMA also.
The exponential moving average tends to give more priority to the recent price changes. So, expecting better results when the volatility is very high is a very risky approach to trade the market. Moreover, the MACD has some lagging issues compared to the EMA, so it is super important to use a trading method that focuses on the higher time frame only. What does MACD 12 26 Close 9 mean? When the DEMA-9 crosses above the MACD(12,26), this is considered a bearish signal. It means the trend in the stock – its magnitude and/or momentum – is starting to shift course. When the MACD(12,26) crosses above the DEMA-9, this is considered a bullish signal. Lets see this indicator on Chart.
When the blue line crossover red line it is good time to buy. As you see from the chart i put arrows where the crossover are appeared.
When the red line crossover blue line it is good time to sell or exit from position.
5 — WaveTrend Oscillator by LazyBear
This is a technical indicator that creates high and low bands between two values. It then creates a trend indicator that draws waves with highs and lows within these boundaries. WaveTrend is a widely used indicator for finding direction of an asset.
Calculation period: number of candles used to calculate WaveTrend, defaults to 10. Averaging period: number of candles used to average WaveTrend, defaults to 21.
As you see in chart when the lines crossover occured my strategy gives buy or sell signals.
═════════════════════════════════════════════════════════════════════════
█ HOW TO USE
I hope you understand how the indicators I mentioned above work and what they are used for. Now, I will explain in detail how to use the strategy I have created.
When you enter the settings section, you will see 5 types of indicators. If you want to use the signals of the indicators, simply tick the box next to the indicators. Also, under each option there is an area where you can set the "lookback". This setting is a field that will make the signals overlap when you select more than one option. If you are going to trade with only one option, you should make sure that this field is 0. Otherwise, it may continue to generate as many signals as you choose.
Lets see in chart for easy understanding.
As you see chart, if i chose only HARSI with lookback 0 (HARSI and CORAL should be 1 minumum because of algorithm-we looking 1 bar before, others 0 because we are looking crossovers), it will give signals only when harsı bar's color changed. But when i changed Lookback as 7 it will be like this in chart.
Now i will choose 2 indicator with settings of their lookback 0.
As you see it will give signals when both of them occurs same time. But HARSI is an indicator giving very early signal so we can enter position 5-6 bars after the first bar color change. So i will change HARSI Lookback settings as 7. Lets look what happens when we use lookback option.
So it wil be useful to change lookback settings to find best signals in each time period and in each symbol. But it shouldnt be too high. Because you can be late to catch trend's starting.
this is an image of MACD and WAVE trend used and lookback option are both 6.
Now lets see an example with 3 options are chosen with lookback option 11-1-5
Now lets talk about indicators settings. After strategy options you will see each indicators settings, you can change their settings as you desired. So each indicators signal will be changed according to your adjustment.
I left strategy options with default settings. You can change it manually as if you want.
═════════════════════════════════════════════════════════════════════════
█ LIMITATIONS: Don't rely on non-standard charts results. For example Heikin Ashi is a technical analysis method used with the traditional candlestick chart.Heikin Ashi vs. Candlestick Chart: The decisive visual difference between Heikin Ashi and the traditional chart is that Heikin Ashi flattens the traditional candlestick chart using a modified formula.
The primary advantage of Heikin Ashi is that it makes the chart more reader-friendly and helps users identify and analyze trends .
Because Heikin Ashi provides averaged price information rather than real-time price and reacts slowly to volatility — not suitable for scalpers and high-frequency traders. I added HARSI indicator as a supportive signal because it is useful with using CORAL and SSL channel indicators. If you change your candle types to Heikin Ashi , your profit will change in good way but dont rely on it.
═════════════════════════════════════════════════════════════════════════
█ THANKS:
Special thanks to authors of the scripts that i used.
@LazyBear and @ErwinBeckers and @JayRogers and @ToFFF
═════════════════════════════════════════════════════════════════════════
█ DISCLAIMER
Any trade decisions you make are entirely your own responsibility.
STD/C-Filtered, N-Order Power-of-Cosine FIR Filter [Loxx]STD/C-Filtered, N-Order Power-of-Cosine FIR Filter is a Discrete-Time, FIR Digital Filter that uses Power-of-Cosine Family of FIR filters. This is an N-order algorithm that turns the following indicator from a static max 16 orders to a N orders, but limited to 50 in code. You can change the top end value if you with to higher orders than 50, but the signal is likely too noisy at that level. This indicator also includes a clutter and standard deviation filter.
See the static order version of this indicator here:
STD/C-Filtered, Power-of-Cosine FIR Filter
Amplitudes for STD/C-Filtered, N-Order Power-of-Cosine FIR Filter:
What are FIR Filters?
In discrete-time signal processing, windowing is a preliminary signal shaping technique, usually applied to improve the appearance and usefulness of a subsequent Discrete Fourier Transform. Several window functions can be defined, based on a constant (rectangular window), B-splines, other polynomials, sinusoids, cosine-sums, adjustable, hybrid, and other types. The windowing operation consists of multipying the given sampled signal by the window function. For trading purposes, these FIR filters act as advanced weighted moving averages.
What is Power-of-Sine Digital FIR Filter?
Also called Cos^alpha Window Family. In this family of windows, changing the value of the parameter alpha generates different windows.
f(n) = math.cos(alpha) * (math.pi * n / N) , 0 ≤ |n| ≤ N/2
where alpha takes on integer values and N is a even number
General expanded form:
alpha0 - alpha1 * math.cos(2 * math.pi * n / N)
+ alpha2 * math.cos(4 * math.pi * n / N)
- alpha3 * math.cos(4 * math.pi * n / N)
+ alpha4 * math.cos(6 * math.pi * n / N)
- ...
Special Cases for alpha:
alpha = 0: Rectangular window, this is also just the SMA (not included here)
alpha = 1: MLT sine window (not included here)
alpha = 2: Hann window (raised cosine = cos^2)
alpha = 4: Alternative Blackman (maximized roll-off rate)
This indicator contains a binomial expansion algorithm to handle N orders of a cosine power series. You can read about how this is done here: The Binomial Theorem
What is Pascal's Triangle and how was it used here?
In mathematics, Pascal's triangle is a triangular array of the binomial coefficients that arises in probability theory, combinatorics, and algebra. In much of the Western world, it is named after the French mathematician Blaise Pascal, although other mathematicians studied it centuries before him in India, Persia, China, Germany, and Italy.
The rows of Pascal's triangle are conventionally enumerated starting with row n = 0 at the top (the 0th row). The entries in each row are numbered from the left beginning with k=0 and are usually staggered relative to the numbers in the adjacent rows. The triangle may be constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero entry 1. Each entry of each subsequent row is constructed by adding the number above and to the left with the number above and to the right, treating blank entries as 0. For example, the initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row.
Rows of Pascal's Triangle
0 Order: 1
1 Order: 1 1
2 Order: 1 2 1
3 Order: 1 3 3 1
4 Order: 1 4 6 4 1
5 Order: 1 5 10 10 5 1
6 Order: 1 6 15 20 15 6 1
7 Order: 1 7 21 35 35 21 7 1
8 Order: 1 8 28 56 70 56 28 8 1
9 Order: 1 9 36 34 84 126 126 84 36 9 1
10 Order: 1 10 45 120 210 252 210 120 45 10 1
11 Order: 1 11 55 165 330 462 462 330 165 55 11 1
12 Order: 1 12 66 220 495 792 924 792 495 220 66 12 1
13 Order: 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
For a 12th order Power-of-Cosine FIR Filter
1. We take the coefficients from the Left side of the 12th row
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
2. We slice those in half to
1 13 78 286 715 1287 1716
3. We reverse the array
1716 1287 715 286 78 13 1
This is our array of alphas: alpha1, alpha2, ... alphaN
4. We then pull alpha one from the previous order, order 11, the middle value
11 Order: 1 11 55 165 330 462 462 330 165 55 11 1
The middle value is 462, this value becomes our alpha0 in the calculation
5. We apply these alphas to the cosine calculations
example: + alpha4 * math.cos(6 * math.pi * n / N)
6. We then divide by the sum of the alphas to derive our final coefficient weighting kernel
**This is only useful for orders that are EVEN, if you use odd ordering, the following are the coefficient outputs and these aren't useful since they cancel each other out and result in a value of zero. See below for an odd numbered oder and compare with the amplitude of the graphic posted above of the even order amplitude:
What is a Standard Deviation Filter?
If price or output or both don't move more than the (standard deviation) * multiplier then the trend stays the previous bar trend. This will appear on the chart as "stepping" of the moving average line. This works similar to Super Trend or Parabolic SAR but is a more naive technique of filtering.
What is a Clutter Filter?
For our purposes here, this is a filter that compares the slope of the trading filter output to a threshold to determine whether to shift trends. If the slope is up but the slope doesn't exceed the threshold, then the color is gray and this indicates a chop zone. If the slope is down but the slope doesn't exceed the threshold, then the color is gray and this indicates a chop zone. Alternatively if either up or down slope exceeds the threshold then the trend turns green for up and red for down. Fro demonstration purposes, an EMA is used as the moving average. This acts to reduce the noise in the signal.
Included
Bar coloring
Loxx's Expanded Source Types
Signals
Alerts
STD-Stepped, Variety N-Tuple Moving Averages [Loxx]STD-Stepped, Variety N-Tuple Moving Averages is the standard deviation stepped/filtered indicator of the following indicator
Variety N-Tuple Moving Averages is a moving average indicator that allows you to create 1- 30 tuple moving average types; i.e., Double-MA, Triple-MA, Quadruple-MA, Quintuple-MA, ... N-tuple-MA. This version contains 5 different moving average types including T3. A list of tuples can be found here if you'd like to name the order of the moving average by depth: Tuples extrapolated
STD-Stepped, You'll notice that this is a lot of code and could normally be packed into a single loop in order to extract the N-tuple MA, however due to Pine Script limitations and processing paradigm this is not possible ... yet.
If you choose the EMA option and select a depth of 2, this is the classic DEMA ; EMA with a depth of 3 is the classic TEMA , and so on and so forth this is to help you understand how this indicator works. This version of NTMA is restricted to a maximum depth of 30 or less. Normally this indicator would include 50 depths but I've cut this down to 30 to reduce indicator load time. In the future, I'll create an updated NTMA that allows for more depth levels.
This is considered one of the top ten indicators in forex. You can read more about it here: forex-station.com
How this works
Step 1: Run factorial calculation on the depth value,
Step 2: Calculate weights of nested moving averages
factorial(nemadepth) / (factorial(nemadepth - k) * factorial(k); where nemadepth is the depth and k is the weight position
Examples of coefficient outputs:
6 Depth: 6 15 20 15 6
7 Depth: 7 21 35 35 21 7
8 Depth: 8 28 56 70 56 28 8
9 Depth: 9 36 34 84 126 126 84 36 9
10 Depth: 10 45 120 210 252 210 120 45 10
11 Depth: 11 55 165 330 462 462 330 165 55 11
12 Depth: 12 66 220 495 792 924 792 495 220 66 12
13 Depth: 13 78 286 715 1287 1716 1716 1287 715 286 78 13
Step 3: Apply coefficient to each moving average
For QEMA, which is 5 depth EMA , the caculation is as follows
ema1 = ta. ema ( src , length)
ema2 = ta. ema (ema1, length)
ema3 = ta. ema (ema2, length)
ema4 = ta. ema (ema3, length)
ema5 = ta. ema (ema4, length)
qema = 5 * ema1 - 10 * ema2 + 10 * ema3 - 5 * ema4 + ema5
Included:
Alerts
Loxx's Expanded Source Types
Bar coloring
Signals
Standard deviation stepping
Variety N-Tuple Moving Averages [Loxx]Variety N-Tuple Moving Averages is a moving average indicator that allows you to create 1- 30 tuple moving average types; i.e., Double-MA, Triple-MA, Quadruple-MA, Quintuple-MA, ... N-tuple-MA. This version contains 5 different moving average types including T3. A list of tuples can be found here if you'd like to name the order of the moving average by depth: Tuples extrapolated
You'll notice that this is a lot of code and could normally be packed into a single loop in order to extract the N-tuple MA, however due to Pine Script limitations and processing paradigm this is not possible ... yet.
If you choose the EMA option and select a depth of 2, this is the classic DEMA; EMA with a depth of 3 is the classic TEMA, and so on and so forth this is to help you understand how this indicator works. This version of NTMA is restricted to a maximum depth of 30 or less. Normally this indicator would include 50 depths but I've cut this down to 30 to reduce indicator load time. In the future, I'll create an updated NTMA that allows for more depth levels.
This is considered one of the top ten indicators in forex. You can read more about it here: forex-station.com
How this works
Step 1: Run factorial calculation on the depth value,
Step 2: Calculate weights of nested moving averages
factorial(nemadepth) / (factorial(nemadepth - k) * factorial(k); where nemadepth is the depth and k is the weight position
Examples of coefficient outputs:
6 Depth: 6 15 20 15 6
7 Depth: 7 21 35 35 21 7
8 Depth: 8 28 56 70 56 28 8
9 Depth: 9 36 34 84 126 126 84 36 9
10 Depth: 10 45 120 210 252 210 120 45 10
11 Depth: 11 55 165 330 462 462 330 165 55 11
12 Depth: 12 66 220 495 792 924 792 495 220 66 12
13 Depth: 13 78 286 715 1287 1716 1716 1287 715 286 78 13
Step 3: Apply coefficient to each moving average
For QEMA, which is 5 depth EMA, the caculation is as follows
ema1 = ta.ema(src, length)
ema2 = ta.ema(ema1, length)
ema3 = ta.ema(ema2, length)
ema4 = ta.ema(ema3, length)
ema5 = ta.ema(ema4, length)
qema = 5 * ema1 - 10 * ema2 + 10 * ema3 - 5 * ema4 + ema5
Included:
Alerts
Loxx's Expanded Source Types
Bar coloring
Inside Bar SetupScript Details
- This script plots Inside Bar for given day in selected time-frame (applicable only for Timeframes < Day)
- Basis plotted inside bar, relevant targets are marked on the chart
- Targets can be customised from script settings. Example, if range of mother candle is 10 points, then T1 is 10 * x above/below mother candle and T2 is 10 * y above/below mother candle. This x & y are configured via script settings
How to use this script ?
- This script works well on 10-15 mins timeframe for stocks, 15/30 mins timeframe for nifty index and 30/60 mins time frame for bank nifty index
- If mother candle high is broken, take long trade with SL of mother candle low and if low is broken, take short trade with SL of mother candle high
Remember:
1. Above logic is to be combined with support/resistances i.e. price action. This script is an add-on to price action analysis giving you more conviction.
2. If range of mother candle is very high, it is recommended to avoid the trade.
3. Basis inside bar formed on higher time frame, take trade on basis of lower time frame i.e if inside bar is formed on 60 mins, take trade on the basis of 10-15 mins time frame
Example:
1. As seen in the chart, Nifty is near it's resistance and we are seeing Inside Bar being formed, In such scenario, even if High of Mother Candle is broken, we should be more interested to short as we are near resistance and probability of getting our targets in long side is less.
2. So, if I see breakdown of mother candle i.e. price going below low of mother candle, we will short with SL of high of mother candle.
3. As seen in the chart, both the targets are achieved.
Additional Info:
1. Targets on Long/Short Side can be configured via settings. For indices 1 times/1.5 times the range works well.
2. This script plots targets basis the first inside bar formed in the day for selected time frame.
3. Inside bars formed through out the day are coloured separately but lines are plotted only on the basis of 1st formed inside bar as this strategy works well for the first formed inside bar)
4. Don't forget to check volume in case of breakout/breakdown.
Note:
1. Mother Candle - First Candle of Inside Bar
2. Child Candle - Candle formed inside Mother Candle (Second Candle of Inside Bar)
Happy Trading :)
Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTESTSmoothed Heikin Ashi Trend on chart - Backtest
This is a backtest of the Smoothed Heikin Ashi Trend indicator, which computes the reverse candle close price required to flip a Heikin Ashi trend from red to green and vice versa. The original indicator can be found in the scripts section of my profile.
This particular back test uses this indicator with a Trend following paradigm with a percentage-based stop loss.
Note, that backtesting performance is not always indicative of future performance, but it does provide some basis for further development and walk-forward / live testing.
Testing was performed on Bitcoin , as this is a primary target market for me to use this kind of strategy.
Sample Backtesting results as of 10th June 2022:
Backtesting parameters:
Position size: 10% of equity
Long stop: 1% below entry
Short stop: 1% above entry
Repainting: Off
Smoothing: SMA
Period: 10
8 Hour:
Number of Trades: 1046
Gross Return: 249.27 %
CAGR Return: 14.04 %
Max Drawdown: 7.9 %
Win percentage: 28.01 %
Profit Factor (Expectancy): 2.019
Average Loss: 0.33 %
Average Win: 1.69 %
Average Time for Loss: 1 day
Average Time for Win: 5.33 days
1 Day:
Number of Trades: 429
Gross Return: 458.4 %
CAGR Return: 15.76 %
Max Drawdown: 6.37 %
Profit Factor (Expectancy): 2.804
Average Loss: 0.8 %
Average Win: 7.2 %
Average Time for Loss: 3 days
Average Time for Win: 16 days
5 Day:
Number of Trades: 69
Gross Return: 1614.9 %
CAGR Return: 26.7 %
Max Drawdown: 5.7 %
Profit Factor (Expectancy): 10.451
Average Loss: 3.64 %
Average Win: 81.17 %
Average Time for Loss: 15 days
Average Time for Win: 85 days
Analysis:
The strategy is typical amongst trend following strategies with a less regular win rate, but where profits are more significant than losses. Most of the losses are in sideways, low volatility markets. This strategy performs better on higher timeframes, where it shows a positive expectancy of the strategy.
The average win was positively impacted by Bitcoin’s earlier smaller market cap, as the percentage wins earlier were higher.
Overall the strategy shows potential for further development and may be suitable for walk-forward testing and out of sample analysis to be considered for a demo trading account.
Note in an actual trading setup, you may wish to use this with volatility filters, combined with support resistance zones for a better setup.
As always, this post/indicator/strategy is not financial advice, and please do your due diligence before trading this live.
Original indicator links:
On chart version -
Oscillator version -
Update - 27/06/2022
Unfortunately, It appears that the original script had been taken down due to auto-moderation because of concerns with no slippage / commission. I have since adjusted the backtest, and re-uploaded to include the following to address these concerns, and show that I am genuinely trying to give back to the community and not mislead anyone:
1) Include commission of 0.1% - to match Binance's maker fees prior to moving to a fee-less model.
2) Include slippage of 10 ticks (This is a realistic slippage figure from searching online for most crypto exchanges)
3) Adjust account balance to 10,000 - since most of us are not millionaires.
The rest of the backtesting parameters are comparable to previous results:
Backtesting parameters:
Initial capital: 10000 dollars
Position size: 10% of equity
Long stop: 2% below entry
Short stop: 2% above entry
Repainting: Off
Smoothing: SMA
Period: 10
Slippage: 10 ticks
Commission: 0.1%
This script still remains to shows viability / profitablity on higher term timeframes (with slightly higher drawdown), and I have included the backtest report below to document my findings:
8 Hour:
Number of Trades: 1082
Gross Return: 233.02%
CAGR Return: 14.04 %
Max Drawdown: 7.9 %
Win percentage: 25.6%
Profit Factor (Expectancy): 1.627
Average Loss: 0.46 %
Average Win: 2.18 %
Average Time for Loss: 1.33 day
Average Time for Win: 7.33 days
Once again, please do your own research and due dillegence before trading this live. This post is for education and information purposes only, and should not be taken as financial advice.
Scalping The Bull IndicatorName: Scalping The Bull Indicator
Category: Scalping, Trend Following, Mean Reversion.
Timeframe: 1M, 5M, 30M, 1D depending on the specific technique.
Technical Analysis: The indicator supports the operations of the trader named "Scalping The Bull" which uses price action and exponential moving averages.
Suggested usage: Altcoin showing strong trends for scalping and intra-day trades. Trigger points are used as entry and exit points and to be used to understand when a signal has more power.
It is possible to identify the following conformations:
Shimano: look at the price records of a consecutive series of closings between the EMA 60 and the EMA 223 when a certain threshold is reached. Use the trigger points as price structures to identify entry and exit zones (e.g. breakout of the yesterday high as for entry point) .
Bomb: look at the price registers a percentage variation in a single candle, greater than a threshold such as 2%, in particular on shorter timeframes and around the trigger points.
Viagra: look at there is a consecutive series of closes below the EMA 10.
Downward fake: look when, after a cross under (Death Cross), the price returns above the EMA 223 using the yesterday high as a trigger point.
Emergence: look at the EMA 60 is about to cross over the EMA 223.
Anti-crossing: look at, after an important price rise and a subsequent retracement, the EMA 60 is about to cross under the EMA 223 but a bullish impulse brings the price back above the EMAs.
For Sales: look at two types of situations: 1) when the price falls by more than 10% from the opening price and around the yesterday’s low or 2) when the price falls and then reaches, in the last 5 days, a bigger percentage and then breaks a trigger point.
Colour change: look at the opening price of the session - indicated as a trigger point.
Third touch of EMA 60: look for 3 touches below the EMA 60, and enter when there is a close above the EMA 60.
Third touch of EMA 223: look for 3 touches when there are 3 touches below the EMA 223, and enter when there is a close above the EMA 60.
Bud: look at price when it crosses upwards the average 10 and subsequently at least 2 "rest" candles are between the maximum and minimum of the breaking candle.
Fake on EMA 10: look for the open of a candle higher than the EMA 10, the minimum of the candle lower and the closing price returns above the EMA 10..
For Stop Loss and Profit Targets consider a proper R/R depending on Risk Management, using price structures such as the low of the entering candle and a quick Position Management moving quickly the Stop-Loss at Break-Even.
Configuration:
Market
EMA: The indicator automatically configure itself on market it knows (Binance, Piazza Affari and NASDAQ) otherwise it can be configured manually fo Crypto market (5/10/60/223) or Stock Market (5/10/50/200).
Additional Average: You can display an additional average, e.g. 20-period average.
Chart elements:
Session Separators: indicates the beginning of the current session (in blue)
Background: signals with the background in green an uptrend situation ( 60 > 223) and in red background a downtrend situation (60 < 223).
Trigger points:
Today's highs and lows: draw on the chart the opening price of the daily candle and the highs and lows of the day (high in purple, low in red and open in green)
Yesterday's highs and lows: draw on the chart the opening price of the daily candle, the highs and lows of the previous day (high in yellow, low in red).
Credits
Massimo : for refactoring and suggestions.
Ratings AlgoThe ratings algo is my discount version of the many paid-for algorithms put out by numerous different companies. A technical "rating" (by default between -10 and 10) is produced for each candle, telling the user when to buy, sell, or hold. I took 11 of my personal favorite indicators to develop a rating system. They are:
50/200 SMA crossover
10/20 SMA crossover
10/20 LSMA crossover
10/20 EMA crossover
"Arnold" a rate-of-change analysis of a smoothed LSMA
PVT and OBV momentum
MACD
RSI
DMI
Fisher Transform
The ratings system is very basic (a more complex, detailed version will be coming in the future!) where each indicator returns -1, 0, or 1, and the MAs and Oscillators are stratified with a user-defined weighting. The total calculation is based on the function:
maweight * (average of MA ratings) + oscillator weight * (average of osc ratings)
If the total value > user-defined threshold, the bar is teal, and if > 2.5 * threshold, is green, and vice versa for orange/red respectively. Purple is given if the total value is close to zero.
"Strong" signals are printed if the bar changes to either green or red and exits are printed if the bars change from green/red to any other color.
A table is also produced showing what each indicator is indicating, either "Buy" "Sell" or "Hold.
Reversal Bands are printed, intended to be used as areas where a trade might be exited if the market is sideways. If a Strong Buy signal is produced, it may be a good idea to enter the trade, and hold until the price enters the reversal bands, then hold until a candle closes outside the band for the first time.
This indicator truly shines in trending markets (like most indicators), but with very fast-acting exit signals and reversal zones, will facilitate minimal losses and possibly even profits in sideways markets.
Weighted RiskONessRevision of tedtalksmacro's risk-on metric. Number go up means global markets are more risk-on; number go down means more risk-off. Weights now allow you to adjust the weights of various elements of the indicator. These are exponentials with the weight being the power / 10.
I.e. setting gold's weight to 10 takes it's value ^ (10 / 10). Setting it to 5 would square root it (^5/10 = ^1/2) while 20 would square it (^20/10 = ^2).
A green line means "riskONess" has gone up in the last day, red means down.
Resolution minimum for the indicator is 1D due to TradingView's limitations.
Double SupertrendThis strategy is based on a custom indicator that was created based on the Supertrend indicator. At its core, there are always 2 super trend indicators with different factors to reduce market noise (false signals).
The strategy/indicator has some parameters to improve the signals and filters.
TECHNICAL ANALYSIS
☑ Show Indicators
This option will enable/disable the Supertrend indicators on the chart.
☑ Length
The length will be used on the Supertrend Indicator to calculate its values.
☑ Dev Fast
The fast deviation or factor from one of the super trend indicators. This will be the leading indicator for entry signals, as well as for the exit signals.
☑ Dev Slow
The slow deviation or factor from one of the super trend indicators. This will be the confirmation indicator for entry and exit signals.
☑ Exit Type
It's possible to select from 4 options for the exit signals. Exit signals always take profit target.
☑ ⥹ Reversals
This option will make the strategy/indicator calculate the exit signals based on the difference between the given period's highest and lowest candle value (see Period on this list). It's displayed on the chart with the cross. As it's possible to verify in the image below, there are multiple exit spots for every entry.
☑ ⥹ ATR
Using ATR as a base indicator for exit signals will make the strategy/indicator place limit/stop orders. Candle High + ATR for longs, Candle Low - ATR for shorts. The strategy will show the ATR level for take profit and stick with it until the next signal. This way, the take profit value remains based on the candle of the entry signal.
☑ ⥹ Fast Supertrend
With this option selected, the exit signals will be based on the Fast Supertsignal value, mirrored to make a profit.
☑ ⥹ Slow Supertrend
With this option selected, the exit signals will be based on the Slow Supertsignal value, which is mirrored to take profit.
☑ Period
This will represent the number of candles used on the exit signals when Reversals is selected as Exit Type. It's also used to calculate the gradient used on the Fills and Supertrend signals.
☑ Multiplier
It's used on the take profit when the ATR option is selected on the Exit Type.
STRATEGY
☑ Use The Strategy
This will enable/disable the strategy to show the trades calculations.
☑ Show Use Long/Short Entries
Option to make the strategy show/use Long or Short signals. Available only if Use The Strategy is enabled
☑ Show Use Exit Long/Short
Option to make the strategy show/use Exit Long or Short signals (valid when Reversals option is selected on the Exit Type). Available only if Use The Strategy is enabled
☑ Show Use Add Long/Short
Option to make the strategy show/use Add Long or Short signals. With this option enabled, the strategy will place multiple trades in the same direction, almost the same concept as a pyramiding parameter. It's based on the Fast Supersignal when the candle fails to cross and reverses. Available only if Use The Strategy is enabled
☑ Trades Date Start/End
The date range that the strategy will check the market data and make the trades
HOW TO USE
It's very straightforward. A long signal will appear as a green arrow with a text Long below it. A short signal will appear as a red arrow with a text Short above it. It's ideal to wait for the candle to finish to validate the signal.
The exit signals are optional but give a good idea of the configuration used when backtesting. Each market and timeframe will have its own configuration for the best results. On average, sticking to ATR as an exit signal will have less risk than the other options.
☑ Entry Signals
Follow the arrows with Long/Short texts on them. Wait for the signal candle to close to validate the entry.
☑ Exit Signals
Use them to close your position or to trail stop your orders and maximize profits. Select the exit type suitable for each timeframe and market
☑ Add Entries
It's possible to increase the position following the add margin/contracts based on the Add signals. Not mandatory, but may work as reentries or late entries using the same signal.
☑ What about Stop Loss?
The stop-loss levels were not included as a separated signal because it's already in the chart. There are some possible ideas for the stop loss:
☑⥹ Candle High/Low (2nd recommend option)
When it's a Long signal from the entry signal candle, the stop loss can be the Low value of the same candle. Very tight stop loss in some cases, depending on the candle range
☑⥹ Local Top/Bottom
Selecting the local top/bottom as stop loss will give the strategy more room for false breakouts or reversals, keeping the trade open and minimizing noises. Increases the risk
☑⥹ Fast Supertrend (1st recommend option)
The fast supertrend can be used as stop-loss as well. making it a moving level and working close to trail stop management
☑⥹ Fixed Percentage
It's possible to use a fixed risk percentage for the trades, making the risk easier to control and project. Since the market volatility is not fixed, this may affect the accuracy of the trades
☑⥹ Based on the ATR (3rd recommend option)
When the exit type option ATR is selected, it will display the take profit level for that entry. Just mirror that value and put it as stop-loss, or multiply that amount by 1.5 to have more room for market noise.
EXAMPLE CONFIGURATIONS
Here are some configuration ideas for some markets (all of them are from crypto, especially futures markets)
BTCUSDT 15min - Default configuration
BTCUSDT 1h - Length 10 | Dev Fast 3 | Dev Slow 4 | Exit Type ATR | Period 50 | Multiplier 1
BTCUSDT 4h - Length 10 | Dev Fast 2 | Dev Slow 4 | Exit Type ATR | Period 50 | Multiplier 1
ETHUSDT 15min - Length 20 | Dev Fast 1 | Dev Slow 3 | Exit Type Fast Supertrend | Period 50 | Multiplier 1
IOTAUSDT 15min - Length 10 | Dev Fast 1 | Dev Slow 2 | Exit Type Slow Supertrend | Period 50 | Multiplier 1
OMGUSDT 15min - Length 10 | Dev Fast 1 | Dev Slow 4 | Exit Type Slow Supertrend | Period 50 | Multiplier 1
VETUSDT 15min - Length 10 | Dev Fast 3 | Dev Slow 4 | Exit Type Slow Supertrend | Period 50 | Multiplier 1
HOW TO FIND OTHER CONFIGURATIONS
Here are some steps to find suitable configurations
select a market and time frame
enable the Use This Strategy option on the strategy
open the strategy tester panel and select the performance summary
open the strategy configuration and go to properties
change the balance to the same price of the symbol (example: BTCUSDT 60.000, use 60.000 as balance)
go back to the inputs tab and keep changing the parameters until you see the net profit be positive and bigger than the absolute value of the drawdown
in case you can't find a suitable configuration, try other timeframes
Since the tester reflects what happened in the past candles, it's not guaranteed to give the same results. However, this indicator/Strategy can be used with other indicators as a leading signal or confirmation signal.
MathConstantsLibrary "MathConstants"
Mathematical Constants
E() The number e
Log2E() The number log (e)
Log10E() The number log (e)
Ln2() The number log (2)
Ln10() The number log (10)
LnPi() The number log (pi)
Ln2PiOver2() The number log (2*pi)/2
InvE() The number 1/e
SqrtE() The number sqrt(e)
Sqrt2() The number sqrt(2)
Sqrt3() The number sqrt(3)
Sqrt1Over2() The number sqrt(1/2) = 1/sqrt(2) = sqrt(2)/2
HalfSqrt3() The number sqrt(3)/2
Pi() The number pi
Pi2() The number pi*2
PiOver2() The number pi/2
Pi3Over2() The number pi*3/2
PiOver4() The number pi/4
SqrtPi() The number sqrt(pi)
Sqrt2Pi() The number sqrt(2pi)
SqrtPiOver2() The number sqrt(pi/2)
Sqrt2PiE() The number sqrt(2*pi*e)
LogSqrt2Pi() The number log(sqrt(2*pi))
LogSqrt2PiE() The number log(sqrt(2*pi*e))
LogTwoSqrtEOverPi() The number log(2 * sqrt(e / pi))
InvPi() The number 1/pi
TwoInvPi() The number 2/pi
InvSqrtPi() The number 1/sqrt(pi)
InvSqrt2Pi() The number 1/sqrt(2pi)
TwoInvSqrtPi() The number 2/sqrt(pi)
TwoSqrtEOverPi() The number 2 * sqrt(e / pi)
Degree() The number (pi)/180 - factor to convert from Degree (deg) to Radians (rad).
Grad() The number (pi)/200 - factor to convert from NewGrad (grad) to Radians (rad).
PowerDecibel() The number ln(10)/20 - factor to convert from Power Decibel (dB) to Neper (Np). Use this version when the Decibel represent a power gain but the compared values are not powers (e.g. amplitude, current, voltage).
NeutralDecibel() The number ln(10)/10 - factor to convert from Neutral Decibel (dB) to Neper (Np). Use this version when either both or neither of the Decibel and the compared values represent powers.
Catalan() The Catalan constant
Sum(k=0 -> inf){ (-1)^k/(2*k + 1)2 }
EulerMascheroni() The Euler-Mascheroni constant
lim(n -> inf){ Sum(k=1 -> n) { 1/k - log(n) } }
GoldenRatio() The number (1+sqrt(5))/2, also known as the golden ratio
Glaisher() The Glaisher constant
e^(1/12 - Zeta(-1))
Khinchin() The Khinchin constant
prod(k=1 -> inf){1+1/(k*(k+2))^log(k,2)}
Turtle Trade Channels Indicator TUTCILegendary trade system which proved that great traders can be made, not born.
Turtle Trade Experiment made 80% annual return for 4 years and made 150 million $
Turtle Trade trend following system is a complete opposite to the "buy low and sell high" approach.
This trend following system was taught to a group of average and normal individuals, and almost everyone turned into a profitable trader.
They used the basis logic of well known DONCHIAN CHANNELS which developed by Richard Donchian.
The main rule is "Trade an 20-day breakout and take profits when an 10-day high or low is breached ". Examples:
Buy a 20-day breakout and close the trade when price action reaches a 10-day low.
Go short a 20-day breakout and close the trade when price action reaches a 10-day high.
In this indicator,
The red line is the trading line which indicates the trend directio n:
Price bars over the trend line indicates uptrend
Price bars under the trend line means downtrend
The dotted blue line is the exit line.
Original system is:
Go long when the price High is equal to or above previous 20 day Highest price.
Go short when the price Low is equal to or below previous 20 day Lowest price.
Exit long positions when the price touches the exit line
Exit short positions when the price touches the exit line
Recommended initial stop-loss is ATR * 2 from the opening price.
Default system parameters were 20,10 and 55,20.
Original Turtle Rules:
To trade exactly like the turtles did, you need to set up two indicators representing the main and the failsafe system.
Set up the main indicator with EntryPeriod = 20 and ExitPeriod = 10 (A.k.a S1)
Set up the failsafe indicator with EntryPeriod = 55 and ExitPeriod = 20 using a different color. (A.k.a S2)
The entry strategy using S1 is as follows
Buy 20-day breakouts using S1 only if last signaled trade was a loss.
Sell 20-day breakouts using S1 only if last signaled trade was a loss.
If last signaled trade by S1 was a win, you shouldn't trade -Irregardless of the direction or if you traded last signal it or not-
The entry strategy using S2 is as follows:
Buy 55-day breakouts only if you ignored last S1 signal and the market is rallying without you
Sell 55-day breakouts only if you ignored last S1 signal and the market is pluging without you
You can Highlight the chart with provided trade signals:
Green background color when Long
Red background color when Short
No background color when flat
WARNING: TURTLE TRADE STOP or ADDING more UNITS RULES ARE NOT INCLUDED.
Author: Kıvanç Özbilgiç
Also you can show or hide trade signals with the button on the settings menu
RSI EMA CrossOver RameshThe RSI is one of the most popular technical indicators. The RSI measures the internal strength of the security. The RSI indicator oscillates between oversold and over bought levels, where a trader is advised to look for buying opportunities when the stock is in over sold region and selling opportunities when the stock is in over bought region.
The RSI with EMA strategy signals a trade when EMA of 7 period RSI crosses over the EMA of a 14 period RSI.
Buy: when 10 EMA of 7 period RSI crossing up 10 EMA of a 14 period RSI
Sell: when 10 EMA of 7 period RSI crossing down 10 EMA of a 14 period RSI
EMA = Exponential Moving Average
Crossover = Simple crossover between current RSI values and its 10 day EMA
Multi SMA EMA WMA HMA BB (4x5 MAs Bollinger Bands) Adv MTF - RRBMulti SMA EMA WMA HMA 4x5 Moving Averages with Bollinger Bands Advanced MTF by RagingRocketBull 2019
Version 1.0
This indicator shows multiple MAs of any type SMA EMA WMA HMA etc with BB and MTF support, can show MAs as dynamically moving levels.
There are 4 MA groups + 1 BB group, a total of 4 TFs * 5 MAs = 20 MAs. You can assign any type/timeframe combo to a group, for example:
- EMAs 12,26,50,100,200 x H1, H4, D1, W1 (4 TFs x 5 MAs x 1 type)
- EMAs 8,10,13,21,30,50,55,100,200,400 x M15, H1 (2 TFs x 10 MAs x 1 type)
- D1 EMAs and SMAs 8,10,12,26,30,50,55,100,200,400 (1 TF x 10 MAs x 2 types)
- H1 WMAs 7,77,89,167,231; H4 HMAs 12,26,50,100,200; D1 EMAs 89,144,169,233,377; W1 SMAs 12,26,50,100,200 (4 TFs x 5 MAs x 4 types)
- +1 extra MA type/timeframe for BB
There are several versions: Simple, MTF, Pro MTF, Advanced MTF and Ultimate MTF. This is the Advanced MTF version. The Differences are listed below. All versions have BB
- Simple: you have 2 groups of MAs that can be assigned any type (5+5)
- MTF: +2 custom Timeframes for each group (2x5 MTF) +1 TF for BB, TF XY smoothing
- Pro MTF: 4 custom Timeframes for each group (4x3 MTF), 1 TF for BB, MA levels and show max bars back options
- Advanced MTF: +2 extra MAs/group (4x5 MTF), custom Ticker/Symbols, Timeframe <>= filter, Remove Duplicates Option
- Ultimate MTF: +individual settings for each MA, custom Ticker/Symbols
Features:
- 4x5 = 20 MAs of any type
- 4x MTF groups with XY step line smoothing
- +1 extra TF/type for BB MAs
- 4x5 = 20 MA levels with adjustable group offsets, indents and shift
- supports any existing type of MA: SMA, EMA, WMA, Hull Moving Average (HMA)
- custom tickers/symbols for each group - you can compare MAs of the same symbol across exchanges
- show max bars back option
- show/hide both groups of MAs/levels/BB and individual MAs
- timeframe filter: show only MAs/Levels with TFs <>= Current TF
- hide MAs/Levels with duplicate TFs
- support for custom TFs that are not available in free accounts: 2D, 3D etc
- support for timeframes in H: H, 2H, 4H etc
Notes:
- Uses timeframe textbox instead of input resolution dropdown to allow for 240 120 and other custom TFs
- Uses symbol textbox instead of input symbol to avoid establishing multiple dummy security connections to the current ticker - otherwise empty symbols will prevent script from running
- Possible reasons for missing MAs on a chart:
- there may not be enough bars in history to start plotting it. For example, W1 EMA200 needs at least 200 bars on a weekly chart.
- price << default Y smoothing step 5. For charts with low/fractional prices (i.e. 0.00002 << 5) adjust X Y smoothing as needed (set Y = 0.0000001) or disable it completely (set X,Y to 0,0)
- TradingView Replay Mode UI and Pinescript security calls are limited to TFs >= D (D,2D,W,MN...) for free accounts
- attempting to plot any TF < D1 in Replay Mode will only result in straight lines, but all TFs will work properly in history and real-time modes. This is not a bug.
- Max Bars Back (num_bars) is limited to 5000 for free accounts (10000 for paid), will show error when exceeded. To plot on all available history set to 0 (default)
- Slow load/redraw times. This indicator becomes slower, its UI less responsive when:
- Pinescript Node.js graphics library is too slow and inefficient at plotting bars/objects in a browser window. Code optimization doesn't help much - the graphics engine is the main reason for general slowness.
- the chart has a long history (10000+ bars) in a browser's cache (you have scrolled back a couple of screens in a max zoom mode).
- Reload the page/Load a fresh chart and then apply the indicator or
- Switch to another Timeframe (old TF history will still remain in cache and that TF will be slow)
- in max possible zoom mode around 4500 bars can fit on 1 screen - this also slows down responsiveness. Reset Zoom level
- initial load and redraw times after a param change in UI also depend on TF. For example:
D1/W1 - 2 sec, H1/H4 - 5-6 sec, M30 - 10 sec, M15/M5 - 4 sec, M1 - 5 sec.
M30 usually has the longest history (up to 16000 bars) and W1 - the shortest (1000 bars).
- when indicator uses more MAs (plots) and timeframes it will redraw slower. Seems that up to 5 Timeframes is acceptable, but 6+ Timeframes can become very slow.
- show_last=last_bars plot limit doesn't affect load/redraw times, so it was removed from MA plot
- Max Bars Back (num_bars) default/custom set UI value doesn't seem to affect load/redraw times
- In max zoom mode all dynamic levels disappear (they behave like text)
1. based on 3EmaBB, uses plot*, barssince and security functions
2. you can't set certain constants from input due to Pinescript limitations - change the code as needed, recompile and use as a private version
3. Levels = trackprice implementation
4. Show Max Bars Back = show_last implementation
5. swma has a fixed length = 4, alma and linreg have additional offset and smoothing params
6. Smoothing is applied by default for visual aesthetics on MTF. To use exact ma mtf values (lines with stair stepping) - disable it
Good Luck! You can explore, modify/reuse the code to build your own indicators.
Wyckoff Volume ColorThis volume indicator is intended to be used for the Wyckoff strategy.
Green volume bar indicates last price close above close 10 days ago together with volume larger than 2 * SMA(volume, 20)
Blue volume bar indicates last price close above close 10 days ago together with volume less than 2 * SMA(volume, 20)
Orange volume bar indicates last price close lower than close 10 days ago together with volume less than 2 * SMA(volume, 20)
Red volume bar indicates last price close lower than close 10 days ago together with volume larger than 2 * SMA(volume, 20)
The main purpose is to have green bars with a buying climax and red bars with a selling climax.
Three variables can be changed by simply pressing the settings button.
How many days back the closing price is compared to. Now 10 days.
How many times the SMA(volume) is multiplied by. Now times 2.
How many days the SMA(volume) consists by. Now 20 days.
M-OscillatorThe M-Oscillator is a bounded oscillator that moves between (-14) and (+14), it gives early buy/sell signals, spots divergences, displays overbought/oversold levels, and provides re-entry points, and it also work as a trend identifier.
Interpretation
• M-Oscillator is plotted along the bottom of the price chart; it fluctuates between positive and negative 14.
• Movement above 10 is considered overbought, and movement below -10 is oversold.
• In sharp moves to the upside, the M-Oscillator fluctuates between 5 and 14, while in down side it fluctuates between -5 and -14.
• In an uptrend, the M-Oscillator fluctuates between zero and 14 and vice versa.
Trading tactics
Overbought/Oversold: We define the overbought area as anywhere above the 10 level.
The oversold area is below -10. When the M-Oscillator goes above 10 (overbought) and then re-crosses it to the downside, a sell signal is triggered.
When the M-Oscillator surpasses -10 to the downside and then re-crosses back above this level, a buy signal is triggered.
This tactic is only successful during sideways markets; during an uptrend, the oscillator will remain in its overbought territory for long period of times.
During a downtrend, it will remain in oversold for a long time.
Divergence
Divergence is one of the most striking features of the M-Oscillator.
It is a very important aspect of technical analysis that enhances trading tactics enormously; it shows hidden weakness or strength in the market, which is not apparent in the price action.
A positive divergence occurs when the price is declining and makes a lower low, while M-Oscillator witnesses a higher low.
A negative divergence occurs when the price is rising and makes a higher High, while the M-Oscillator makes a lower high, which indicates hidden weakness in the market.
Divergences are very important as they give us early hints of trend reversal (weekly chart)
Luxy Sector & Industry RS AnalyzerEver wonder why some stocks soar while others in the same sector barely move? Or why your perfectly timed entry still loses money? Possibly the answer can be found in Relative Strength.
The Luxy Sector & Industry RS Analyzer solves a critical problem that most traders overlook: picking strong stocks in strong sectors AND strong industries . It's not enough for a stock to go up - you want stocks that are crushing their competition at both the sector AND industry level. This indicator does the heavy lifting by automatically comparing your stock against its sector ETF, industry ETF, the broader market, sector leader, and industry leader, giving you a complete multi-level picture of relative performance.
What makes this different?
- Automatic sector AND industry detection - no manual setup required
- Multi-level hierarchy analysis: Market → Sector → Industry → Stock
- Multi-timeframe analysis (1 month to 1 year) in one glance
- Industry ETF mapping (30+ industries covered)
- Clear 0-100 scoring system with letter grades (A+ to F)
- Works on stocks, crypto, forex, and commodities
- Real-time updates with anti-repaint protection
Think of it as your performance dashboard - instantly showing you if you're trading a champion or a laggard at every level of the market hierarchy.
METHODOLOGY & ATTRIBUTION
This indicator is based on classical Relative Strength (RS) analysis principles from technical analysis. RS methodology compares an asset's price performance against a benchmark to identify relative outperformance or underperformance. This concept has been used by professional traders and institutions for decades.
Key Concepts Used:
Relative Strength (RS) - Classical technical analysis concept measuring comparative performance
Multi-Level Hierarchy Analysis - Market → Sector → Industry → Stock comparison
Sector Rotation Analysis - Identifying which sectors are leading or lagging the market
Industry Rotation Analysis - Identifying which industries are leading within their sectors
Multi-period Performance Analysis - Evaluating strength across multiple timeframes
Beta Calculation - Standard statistical measure of volatility relative to a benchmark
DISCLAIMER: This indicator is for educational and informational purposes only. It should not be considered financial advice or a recommendation to buy or sell. Past performance does not guarantee future results. Trading involves risk and may not be suitable for all investors. Always do your own research and consult with a financial advisor before making investment decisions.
with all rows visible - capture when stock has strong RS score (70+) so users can see what a "good" setup looks like]
WHAT THE INDICATOR SHOWS
1. AUTOMATIC ASSET TYPE DETECTION
The indicator automatically identifies what you're analyzing and adjusts accordingly:
Stocks - Compares to sector ETF (XLK, XLF, XLV, etc.) and SPY
Crypto - Compares to Total Crypto Market Cap and Bitcoin
Forex - Compares to relevant currency index (DXY, EXY, etc.)
Commodities - Compares to Gold (GLD) as benchmark
Indices - Compares to broader market indices
How it works: The indicator reads your chart's asset type and ticker, then automatically maps it to the correct sector or benchmark. For stocks, it uses intelligent sector detection (looking at the sector field) to match you with the right sector ETF. For example:
- Technology stocks get compared to XLK (Technology Select Sector SPDR)
- Financial stocks get compared to XLF (Financial Select Sector SPDR)
- Healthcare stocks get compared to XLV (Health Care Select Sector SPDR)
This happens instantly when you add the indicator to any chart - no configuration needed.
2. SECTOR & MARKET BENCHMARKS
What is a Sector ETF?
A sector ETF is an exchange-traded fund that tracks a specific industry group. For example, XLK contains all major technology companies. By comparing your stock to its sector ETF, you can see if your stock is outperforming or underperforming its peers.
The indicator shows three key comparison points:
Stock vs Sector (Benchmark)
This tells you how your stock performs compared to companies in the same industry. Positive numbers mean your stock is beating the sector average. Negative numbers mean it's lagging behind.
Stock vs Market (SPY)
This shows performance against the broader S&P 500 index. This is important because even if a stock beats its sector, the entire sector might be weak. You want stocks that beat both their sector AND the market.
Sector vs Market
This reveals "sector rotation" - whether money is flowing into or out of this sector. When this number is positive, the whole sector is hot and leading the market. This is powerful because strong sectors tend to lift all boats, making it easier to find winners.
3. MULTI-PERIOD PERFORMANCE ANALYSIS
The indicator calculates performance across four timeframes simultaneously:
1 Month (1M) - Recent short-term momentum
3 Months (3M) - Medium-term trend strength
6 Months (6M) - Longer-term positioning
1 Year (1Y) - Full-cycle performance view
Why multiple periods matter:
A stock might look great over 1 month but terrible over 6 months - that's a red flag. The best stocks show consistent strength across all timeframes . When you see positive RS (Relative Strength) values across all four periods, you've found a stock with sustained outperformance.
Each row in the table shows:
- Raw performance percentage for that period
- RS value (the difference compared to benchmark)
- Color coding: Green for positive, red for negative, white for neutral
4. SECTOR LEADER COMPARISON
The indicator automatically identifies and compares your stock to the sector leader - the dominant stock in that industry.
Sector leaders by industry:
Technology: Apple (AAPL)
Healthcare: UnitedHealth (UNH)
Financial: JPMorgan Chase (JPM)
Energy: ExxonMobil (XOM)
Consumer Discretionary: Amazon (AMZN)
Consumer Staples: Walmart (WMT)
And more...
Why this matters:
Comparing to the leader shows you if you're trading a champion or a follower. If your stock consistently beats the sector leader, you've found something special. If it's lagging the leader, you might want to trade the leader instead.
Optional Custom Leader:
You can override the automatic leader and compare to any stock you choose. This is useful if you want to benchmark against a specific competitor or reference stock.
NEW! INDUSTRY ANALYSIS (STOCKS ONLY)
The indicator now provides multi-level analysis by automatically detecting and comparing your stock to its specific industry , not just the broad sector.
Why Industry matters:
Technology sector (XLK) contains many different industries: Software, Semiconductors, Hardware, etc. A software stock might beat the broad tech sector but lag behind other software companies. Industry analysis provides this granular view.
Industry ETF Mapping (30+ industries):
Software/Applications: IGV (iShares Software ETF)
Semiconductors: SMH (VanEck Semiconductor ETF)
Biotech: IBB (iShares Biotechnology ETF)
Pharmaceuticals: XPH (SPDR Pharmaceuticals ETF)
Banks: KBE (SPDR S&P Bank ETF)
Regional Banks: KRE (SPDR Regional Banking ETF)
Oil & Gas Exploration: XOP (SPDR Oil & Gas Exploration ETF)
Homebuilders: XHB (SPDR Homebuilders ETF)
Retail: XRT (SPDR S&P Retail ETF)
Aerospace & Defense: ITA (iShares U.S. Aerospace & Defense ETF)
And many more...
Industry Leader Mapping:
The indicator also identifies the leader within each industry:
Software: Microsoft (MSFT)
Semiconductors: NVIDIA (NVDA)
Biotech: Amgen (AMGN)
Pharmaceuticals: Eli Lilly (LLY)
Banks: JPMorgan (JPM)
Oil Exploration: ConocoPhillips (COP)
And more...
New Table Rows for Stocks:
Industry ETF Performance - How the specific industry performed (green background)
Industry Leader Performance - How the top stock in the industry performed
vs Industry RS - Your stock's outperformance vs its industry ETF
Industry vs Sector RS - Is this industry hot or cold within its sector?
vs Industry Leader RS - Your stock's performance vs the industry's best
Why this is powerful:
A stock that beats both its sector AND its industry is showing strength at every level. This indicates true relative strength, not just riding sector-wide momentum.
Optional Custom Industry:
You can override automatic detection for both Industry ETF and Industry Leader in settings.
5. RS SCORE & GRADING SYSTEM (0-100)
The heart of the indicator is the RS Score - a weighted calculation that distills all the performance data into one clear number from 0 to 100.
How the score is calculated:
FOR STOCKS (with Industry data):
The indicator splits the weight between Sector (60%) and Industry (40%):
SECTOR RS (60% of total weight):
1 Month RS: 24% weight (40% × 0.6)
3 Month RS: 18% weight (30% × 0.6)
6 Month RS: 12% weight (20% × 0.6)
1 Year RS: 6% weight (10% × 0.6)
INDUSTRY RS (40% of total weight):
1 Month RS: 16% weight (40% × 0.4)
3 Month RS: 12% weight (30% × 0.4)
6 Month RS: 8% weight (20% × 0.4)
1 Year RS: 4% weight (10% × 0.4)
FOR OTHER ASSETS (Crypto, Forex, Commodities):
Uses full 100% weight on benchmark:
1 Month RS: 40% weight
3 Month RS: 30% weight
6 Month RS: 20% weight
1 Year RS: 10% weight
It starts at 50 (neutral) and adds or subtracts points based on your asset's relative strength in each period.
Bonus points:
+5 points if the sector is outperforming the market (sector rotation is bullish)
+5 points if the industry is outperforming its sector (hot industry) - STOCKS ONLY
+5 points if RS momentum is improving (getting stronger over time)
-5 points if RS momentum is declining (getting weaker)
The final score is capped between 0-100.
Letter Grade System:
90-100: A+ - Elite performer, crushing the sector
85-89: A - Excellent, strong outperformer
80-84: A- - Very good, above average
75-79: B+ - Good, solid performer
70-74: B - Above average, decent strength
65-69: B- - Slightly above average
60-64: C+ - Average, neutral strength
55-59: C - Below average
50-54: C- - Weak, slight underperformance
45-49: D+ - Concerning weakness
40-44: D - Poor, significant underperformance
0-39: F - Failing, avoid this stock
What scores mean for trading:
- RS Score above 70: Strong stocks worth considering for long positions
- RS Score 50-70: Average stocks, better opportunities elsewhere
- RS Score below 50: Weak stocks, avoid or consider for shorts
6. CONSISTENCY SCORE
This metric shows what percentage of time periods show positive RS .
For STOCKS (with Industry data):
Counts both Sector RS periods AND Industry RS periods (up to 8 total periods):
- If a stock beats both sector and industry in all 4 periods each: Consistency = 100% (8/8)
- If it beats in 6 out of 8 total periods: Consistency = 75%
- If it beats in 4 out of 8 total periods: Consistency = 50%
For OTHER ASSETS:
Counts benchmark periods only (4 total):
- If it beats benchmark in all 4 periods (1M, 3M, 6M, 1Y): Consistency = 100%
- If it beats in 3 out of 4 periods: Consistency = 75%
- If it beats in 2 out of 4 periods: Consistency = 50%
Why consistency matters:
A high RS Score with low consistency might indicate a recent spike that could fade. The best stocks show both high RS Score AND high consistency - they're strong now AND have been strong historically at both the sector AND industry level.
Look for stocks with:
Consistency above 75%: Very reliable strength across all levels
Consistency 50-75%: Decent but check other metrics
Consistency below 50%: Weak or erratic, proceed with caution
7. BETA CALCULATION (Volatility Measure)
Beta measures how much more volatile your stock is compared to its sector.
Beta > 1.2 : High volatility - stock moves more aggressively than sector (marked as "High")
Beta 0.8-1.2 : Normal volatility - moves roughly in line with sector
Beta < 0.8 : Low volatility - stock is more stable than sector (marked as "Low")
Formula used:
Beta = Correlation(Stock, Sector) × (Standard Deviation of Stock / Standard Deviation of Sector)
This uses a 20-period calculation for reliability.
How to use Beta:
- High Beta stocks offer bigger gains but also bigger risks - good for aggressive traders
- Low Beta stocks are more defensive - good for conservative positions
- Match Beta to your risk tolerance and strategy
8. DAYS ABOVE/BELOW SECTOR
This tracks consecutive periods (bars) where your stock outperforms or underperforms its sector.
Days Above Sector:
Counts how many bars in a row your stock has beaten the sector.
10+ days: Strong sustained strength (shown in bright green)
5-9 days: Building momentum (shown in yellow)
1-4 days: Early strength (shown in white)
0 days: Not currently outperforming
Days Below Sector:
Counts how many bars in a row your stock has lagged the sector.
10+ days: Sustained weakness (shown in bright red)
5-9 days: Losing momentum (shown in orange)
1-4 days: Minor weakness (shown in white)
0 days: Not underperforming (this is good!)
Why this matters:
Long streaks show trend persistence. A stock with 15+ days above sector is riding strong momentum. A stock with 15+ days below sector is in a sustained downtrend relative to peers.
9. PRICE VS 52-WEEK HIGH
Shows where current price sits relative to its 52-week high (or equivalent for your timeframe).
95%+ (green) : Stock is near all-time highs - strong positioning
80-94% (yellow) : Stock is in a pullback but still relatively strong
Below 80% : Stock has pulled back significantly from highs
Why this matters:
The strongest stocks stay near their highs. When you see a stock with high RS Score AND price near 52W high, you've found a stock with institutional support and strong buying pressure.
10. RELATIVE VOLUME
Compares current volume to the 20-period average volume.
1.5x+ (green) : High volume - significant interest and participation
Around 1.0x : Average volume - normal trading activity
Below 1.0x : Low volume - less interest or inactive period
Why volume matters:
High relative volume confirms price moves. When a stock makes a strong move on 2x or 3x normal volume, it's more likely to sustain. Low volume moves are often just noise.
11. AVERAGE RS STRENGTH
This calculates the average absolute value of all RS readings across the four timeframes.
It shows the magnitude of divergence from the sector, regardless of direction. A high number means the stock moves very differently from its sector (could be much stronger or much weaker). A low number means it tracks closely with the sector.
High Average RS: Stock has strong character, moves independently
Low Average RS: Stock follows sector closely, lacks individual strength
12. SECTOR ROTATION SIGNAL
This indicator automatically detects when a sector is experiencing bullish rotation - meaning money is flowing into the sector and it's outperforming the broader market.
Condition for bullish rotation:
Sector must be beating SPY (market) in both 1-month AND 3-month periods.
Why this matters:
Stocks in hot sectors tend to perform better because they have tailwinds from sector-wide buying. When sector rotation is bullish and your stock has a high RS Score, you've found an ideal setup.
The indicator adds +5 bonus points to the RS Score when sector rotation is bullish.
13. MOMENTUM DETECTION
The indicator compares 1-month RS to 3-month RS to detect if momentum is improving or declining.
RS Momentum Improving: 1M RS is better than 3M RS - stock is getting stronger (adds +5 to score)
RS Momentum Declining: 1M RS is worse than 3M RS - stock is getting weaker (subtracts -5 from score)
Why momentum matters:
You want to catch stocks as momentum is building, not after it's already peaked. Improving momentum suggests the strength is accelerating, not fading.
14. OVERALL ASSESSMENT & RECOMMENDATION
The indicator provides two quick summary rows:
Overall Rating:
Based on grade and RS Score, you get an instant quality rating:
Strong Leader (A/A+) - Top tier stock, crushing it
Above Average (A-/B+) - Solid performer, better than most
Average (B/B-) - Middle of the pack
Below Average (C/C+) - Struggling, watch carefully
Underperformer (D/F) - Weak stock, underperforming badly
Trading Signal:
Combines multiple factors to give setup quality:
STRONG BUY SETUP - RS Score 70+, Consistency 75+, AND sector rotation bullish. This is the perfect storm - strong stock, consistent strength, hot sector.
BULLISH - RS Score 60+, Consistency 50+. Good quality stock worth considering.
NEUTRAL - RS Score 50+. Okay but not exciting, better opportunities exist.
WEAK - RS Score 40-49. Below average, risky.
AVOID - RS Score below 40. Stay away, too weak.
IMPORTANT: These are educational signals only, not financial advice. Always do your own analysis and risk management.
KEY FEATURES
1. AUTOMATIC EVERYTHING
- Auto-detects asset type (stock, crypto, forex, commodity, index)
- Auto-maps stocks to correct sector ETF (11 sectors covered)
- Auto-maps stocks to correct industry ETF (30+ industries covered)
- Auto-identifies sector leader AND industry leader
- Auto-selects appropriate market benchmark
- Zero configuration required - just add to chart
2. MULTI-ASSET SUPPORT
Works on all asset classes:
US Stocks - Compares to sector ETFs (XLK, XLF, XLV, etc.)
Crypto - Compares to Total Crypto Market Cap
Forex - Compares to currency indices (DXY, EXY, etc.)
Commodities - Compares to Gold (GLD)
Indices - Compares to broader market benchmarks
3. FLEXIBLE DISPLAY
9 table positions (top/middle/bottom, left/center/right)
4 size options (tiny, small, normal, large)
Show/hide table completely
Real-time indicator toggle
4. TIMEFRAME FLEXIBILITY
Choose your analysis timeframe:
Chart Timeframe (default) - Uses whatever timeframe your chart is on
Fixed: 1 Hour, 4 Hours, Daily, Weekly - Forces calculations to specific timeframe
This means you can be on a 5-minute chart but analyze RS on Daily timeframe if you prefer.
5. RS SCORE FILTERING
Set a minimum RS Score threshold to only see strong stocks:
Set to 0 - Shows all stocks
Set to 70 - Only displays stocks with RS Score 70+ (strong stocks only)
Warning message displays if stock doesn't meet threshold
Perfect for screening - quickly scan multiple charts and the indicator only shows tables for stocks that pass your quality filter.
6. CUSTOM LEADER COMPARISON
Override automatic leader detection:
Compare to any ticker you choose
Benchmark against specific competitors
Use your own reference stocks
7. COMPREHENSIVE TOOLTIPS
Every input parameter and every table row has detailed tooltips explaining:
What the metric measures
How to interpret the values
What thresholds indicate strength/weakness
Why it matters for trading
Hover over any element to learn - it's like having a trading coach built in.
8. SMART ALERTS
Built-in alert system for key events:
Divergence Alerts:
Get notified when your stock diverges significantly from its sector.
Bullish Divergence: Stock beating sector by threshold percentage
Bearish Divergence: Stock losing to sector by threshold percentage
Set your threshold (default 5%) - this determines how big a divergence triggers the alert.
RS Score Alerts:
Get notified when RS Score crosses your threshold:
Crossed Above: RS Score went from below to above your threshold (bullish)
Crossed Below: RS Score dropped from above to below threshold (bearish)
Set your threshold (default 70) to focus on strong stocks.
Sector Rotation Alert:
Fires when sector shows bullish rotation (outperforming market).
HOW TO USE THE INDICATOR
FOR SWING TRADERS:
1. Add indicator to your watchlist stocks
2. Look for RS Score 70+ with Consistency 75%+
3. Check if sector rotation is bullish (bonus!)
4. Verify price is near 52W high (95%+)
5. Wait for entry setup on your chart
6. Use stop loss below key support
Example Setup:
Stock shows:
- RS Score: 82 (Grade: A-)
- Consistency: 100% (strong across all periods)
- Sector Rotation: Bullish
- Price vs 52W High: 96%
- Days Above Sector: 12 days
- Relative Volume: 1.8x
This is a textbook strong stock in a hot sector near highs - ideal for swing long.
FOR POSITION TRADERS:
1. Focus on 6-month and 1-year RS values
2. Look for sustained outperformance (Consistency 75%+)
3. Prefer lower Beta stocks (less volatility)
4. Check Days Above Sector for trend persistence
5. Monitor RS Score monthly, exit if drops below 60
FOR ACTIVE TRADERS:
1. Use on intraday timeframes (1H or 4H)
2. Set RS Score filter to 60+ for quick screening
3. Enable Divergence Alerts
4. Watch for momentum improving signal
5. Higher Beta stocks offer more movement
FOR SHORT SELLERS:
1. Look for RS Score below 40 (Grade: D or F)
2. Check for declining momentum
3. Verify Days Below Sector is increasing (10+)
4. Sector rotation should be bearish
5. Price should be well off 52W high
WHAT MAKES A PERFECT SETUP:
The holy grail combination:
RS Score: 75+ (A- or better)
Consistency: 80%+ (strong across time - beats sector AND industry)
Sector Rotation: Bullish (hot sector)
Industry vs Sector: Positive (hot industry within sector)
Days Above Sector: 10+ (sustained strength)
Momentum: Improving (getting stronger)
Price vs 52W High: 90%+ (near highs)
Relative Volume: 1.5x+ (volume confirmation)
When you find this combination, you've located a stock with every advantage in its favor - strong at the stock level, industry level, AND sector level. That's multi-level confirmation of relative strength.
IMPORTANT NOTES
Data Reliability:
All calculations use lookahead=off for anti-repaint protection
Historical values will never change
Real-time indicator toggle only affects the visual clock icon, not data reliability
All security requests are properly configured to prevent future data leakage
Sector Mapping Notes:
Sector detection uses TradingView's sector field
Some stocks may not have sector data - indicator will adapt
Sector ETFs used: XLK, XLF, XLV, XLE, XLY, XLP, XLI, XLB, XLRE, XLU, XLC
Major market ETFs (SPY, QQQ, DIA) are treated as market benchmarks, not stocks
Multi-Asset Notes:
Crypto compares to CRYPTOCAP:TOTAL (total crypto market cap)
Forex compares to relevant currency index based on base currency
Commodities compare to Gold (GLD) as primary commodity benchmark
Custom leaders can be set for any asset type
FREQUENTLY ASKED QUESTIONS
Q: What does RS Score of 75 actually mean?
A: It means your stock is strongly outperforming its sector across multiple timeframes. The score is weighted toward recent performance (1-month gets 40% weight), so 75 indicates sustained relative strength with emphasis on current momentum.
Q: My stock has high RS Score but is going down. Why?
A: RS Score measures relative performance (vs sector/market), not absolute price direction. A stock can fall 5% while its sector falls 10% - that's still positive relative strength. In bear markets or sector corrections, high RS stocks often fall less than peers.
Q: Should I only trade stocks with RS Score above 70?
A: For long positions, yes - focus on 70+ scores. These stocks have proven they can beat their sector. However, for pairs trading or relative value plays, you might also short stocks with scores below 40 while longing stocks above 70.
Q: What if my stock doesn't have a sector?
A: The indicator handles this gracefully. If no sector is detected, it will compare directly to the market (SPY for stocks). Some rows may show N/A, but the indicator will still provide useful market-relative data.
Q: Why does the sector sometimes show N/A?
A: This happens when: 1) Your asset has no sector classification, 2) The stock IS the sector ETF itself, 3) You're analyzing a non-stock asset (crypto, forex, commodity). The indicator adapts by focusing on market-relative metrics instead.
Q: Can I use this on cryptocurrencies?
A: Yes! The indicator automatically detects crypto and compares to the Total Crypto Market Cap (CRYPTOCAP:TOTAL). You can also set a custom leader like Bitcoin (BTCUSD) to compare against the dominant crypto.
Q: What's the difference between RS Score and Consistency?
A: RS Score is the weighted average of how much you're beating the sector (magnitude). Consistency is what percentage of time periods show outperformance (reliability). You want both high - that means strong AND consistent.
Q: Do the alerts repaint?
A: No. All alerts fire only on bar close (barstate.isconfirmed) and use properly configured data with lookahead=off. Once an alert fires, it's final and won't change.
Q: What timeframe should I use?
A: For swing trading: Daily or Weekly. For day trading: 1H or 4H. For position trading: Weekly. Use "Chart Timeframe" mode and switch your chart timeframe to change the analysis period easily.
Q: Why is Days Above Sector showing 0?
A: This means your stock is not currently outperforming its sector. If Days Below Sector is also 0, it means the RS is exactly neutral (very rare). Check the actual RS values to see current standing.
Q: Can I compare to a different market benchmark than SPY?
A: Currently the indicator uses SPY (S&P 500) as the default US stock market benchmark. For crypto it uses CRYPTOCAP:TOTAL, for forex it uses currency indices, etc. The benchmark auto-adjusts based on asset type.
Q: What's a good Beta value?
A: It depends on your strategy. Aggressive traders prefer Beta above 1.2 (more volatility = bigger moves). Conservative traders prefer Beta 0.8-1.0 (more stable). Beta is neutral - it's about matching your risk tolerance.
Q: How often does the table update?
A: With Real-time Indicator enabled: Every tick (constant updates). With it disabled: Only on bar close. Either way, the underlying data is identical and non-repainting - the toggle only affects update frequency and the clock icon display.
Q: My stock is showing "AVOID" but it's up 50% this year. Is the indicator wrong?
A: Not necessarily. The indicator measures RELATIVE performance. If your stock is up 50% but the sector is up 100%, your stock is actually underperforming by 50%. The indicator helps you identify when you should switch to stronger stocks in the same sector.
Q: What does "Strong Buy Setup" really mean?
A: It means three things aligned: 1) RS Score above 70 (strong stock), 2) Consistency above 75% (reliable strength), 3) Sector rotation is bullish (hot sector). This combination historically correlates with stocks that continue outperforming. However, this is NOT financial advice - always do your own analysis.
Q: Can I use this for options trading?
A: Yes! High RS Score stocks make good candidates for call options (bullish bets) while low RS Score stocks may work for puts (bearish bets). Higher Beta stocks will have more volatile options (higher premiums but more movement).
Q: Why is my crypto showing N/A for sector?
A: Cryptocurrencies don't have "sectors" like stocks do. Instead, the indicator compares crypto to the total crypto market cap. This is normal and expected behavior.
Q: What happens if I'm analyzing an ETF?
A: If you're analyzing a sector ETF (like XLK), it will compare to SPY (market). If you're analyzing SPY itself, some comparisons won't be available (can't compare SPY to itself). The indicator intelligently adapts to avoid circular comparisons.
Q: What if my stock doesn't have industry data?
A: Not all stocks are mapped to specific industries (only 30+ major industries are covered). If no industry is detected, the indicator will still work using only sector analysis. The RS Score calculation will use 100% sector weight instead of the 60%/40% split.
Q: Why does Industry vs Sector matter?
A: Industry vs Sector shows if your specific industry is hot or cold within its broader sector. For example, Semiconductors (SMH) might be outperforming Technology sector (XLK) even though both are up. This helps you find not just strong sectors, but the strongest industries within those sectors.
Q: Can I disable Industry analysis?
A: Yes! In the "Industry Analysis" settings group, you can toggle off "Show Industry Analysis in Table" to hide all industry rows. However, even when hidden, industry data still contributes to the RS Score calculation for stocks.
Q: Why is my Consistency Score lower for stocks than other assets?
A: For stocks with industry data, Consistency counts 8 periods (4 Sector + 4 Industry periods) instead of just 4. This means the bar is higher - your stock needs to beat both sector AND industry consistently. A stock that beats sector in all 4 periods but lags industry in 2 periods will show 75% consistency (6/8), not 100%.
BEST PRACTICES
Use as a screening tool - Set RS Score filter to 70+ and quickly scan your watchlist. Only strong stocks will show the table.
Combine with technical analysis - RS Score tells you WHAT to trade, your chart tells you WHEN to enter.
Check multiple timeframes - Switch between Daily and Weekly to see if strength holds across different time horizons.
Monitor sector rotation - When sector goes from bearish to bullish rotation, it's often a great time to enter stocks in that sector.
Watch Industry vs Sector - Stocks in hot industries within hot sectors have double tailwinds. Prioritize Industry vs Sector positive values.
Pay attention to consistency - High RS Score with low consistency might be a spike that fades. Look for 70%+ consistency across BOTH sector and industry.
Use the leader comparison - If your stock consistently beats both sector leader AND industry leader, you may have found the next champion.
Watch days above/below sector - Long streaks (15+ days) indicate strong trends. Look for these in conjunction with high RS Score.
Set alerts on key stocks - Enable RS Score alerts at 70 threshold to get notified when watchlist stocks become strong.
Consider Beta for position sizing - Size smaller positions in high Beta stocks, larger in low Beta stocks for balanced risk.
Exit when RS Score drops - If a stock's RS Score falls below 60, consider reducing or exiting - the strength may be fading.
Leverage industry-level insight - If Industry ETF is weak but stock is strong, that's standout strength. If Industry is hot but stock is lagging, consider switching to the industry leader instead.
SETTINGS EXPLAINED
Display Settings:
Show Performance Table - Master on/off switch for the table
Table Position - 9 positions available (corners, edges, center)
Table Size - 4 sizes (tiny, small, normal, large) for different screen sizes
Timeframe Settings:
Chart Timeframe (recommended) - Dynamic, uses whatever chart TF you're on
Fixed Timeframes - Locks analysis to 1H, 4H, Daily, or Weekly regardless of chart
Filtering Settings:
Minimum RS Score - Set threshold (0-100) for displaying table
Show Warning - When enabled, displays message if stock doesn't meet filter
Alert Settings:
Divergence Alerts - Enable alerts when stock diverges from sector
Threshold (%) - How big a divergence triggers alert (default 5%)
RS Score Alerts - Enable alerts when RS Score crosses threshold
Threshold - What RS Score level triggers alert (default 70)
Sector Analysis Settings:
Use Custom Sector ETF - Override automatic sector ETF detection
Sector ETF Symbol - Enter any sector ETF to compare against
Use Custom Sector Leader - Override automatic sector leader detection
Sector Leader Symbol - Enter any ticker as sector leader
Industry Analysis Settings:
Use Custom Industry ETF - Override automatic industry ETF detection
Industry ETF Symbol - Enter specific industry ETF (e.g., IGV, SMH)
Use Custom Industry Leader - Override automatic industry leader detection
Industry Leader Symbol - Enter specific industry leader
Show Industry Analysis - Toggle all industry rows on/off
Display Settings:
Show Real-time Indicator - Toggle clock icon in header (doesn't affect data)
WHAT THIS INDICATOR DOESN'T DO
To set proper expectations:
Does NOT provide entry/exit signals - this is a strength analyzer, not a trading system
Does NOT predict future price movement - shows current and historical relative strength
Does NOT guarantee profits - strong RS stocks can still decline
Does NOT replace your own analysis - use as one tool among many
Does NOT work on stocks with no sector data - will adapt but some rows show N/A
This indicator is a decision support tool . It helps you identify which stocks are showing relative strength so you can make more informed trading decisions. You still need your own entry strategy, risk management, and position sizing rules.
SUPPORT & CONTACT
Questions or feedback? Use the comments section below or send me a message.
If you find this indicator useful, please give it a boost and share with other traders who might benefit from relative strength analysis.
FINAL REMINDER
This indicator is a tool for analyzing relative strength - it shows you which stocks are outperforming their sector and market. It does NOT provide financial advice or trade signals. Always conduct your own research, manage your risk appropriately, and consult with a financial advisor before making investment decisions.
Past performance of relative strength does not guarantee future results. Strong stocks can become weak, and sectors rotate in and out of favor. Use this indicator as part of a comprehensive trading strategy, not as a standalone decision-making system.
Trade smart, manage risk, and may your RS Scores stay high!
If you got till here and you like my work a BOOST and a COMMENT would make me happy
Macro Range HighlighterThis Pine Script indicator creates visual boxes that highlight specific time-based price ranges throughout the trading day, operating in New York Eastern Time. It offers two distinct modes: a standard hourly range mode and a classic ICT (Inner Circle Trader) Macro mode.
Two Operating Modes
Mode 1: Standard Hourly 50-09 Ranges (Default)
This mode identifies and highlights the price range during the final 10 minutes of each hour (xx:50) through the first 9 minutes of the next hour (xx:09).
Examples of captured ranges:
08:50 - 09:09
09:50 - 10:09
10:50 - 11:09
11:50 - 12:09
12:50 - 13:09
13:50 - 14:09
14:50 - 15:09
And continues for each hour...
Excluded Time Periods:
The indicator excludes certain periods that cross into or occur during market close and the daily reset:
02:50 - 03:09 (excluded to avoid interference with overnight session)
15:50 - 18:09 (excluded to avoid end-of-regular-hours and the 18:00 ET trading day reset)
This means you will NOT see boxes during the 16:00 or 17:00 hours, as these fall within the excluded window.
Mode 2: Classic ICT Macro Times
When enabled, this mode shows ONLY four specific time windows that are significant in ICT methodology:
02:33 - 02:59 (London Midnight Macro)
04:03 - 04:29 (London Open Macro)
13:10 - 13:39 (New York Lunch Macro)
15:15 - 15:44 (New York Close Macro)
When this mode is active, all standard hourly ranges are disabled, including the 02:50-03:09 range.
Green Line - Open Price
Represents the open price of the first candle when the range begins
This line is static once set - it shows where price opened when entering the time window
Extends horizontally across the entire duration of the box
Example: If the range starts at 08:50 and that candle opens at 18,500, the green line will be drawn at 18,500
Blue Line - Evolving Midpoint
Represents the dynamic midpoint between the range high and range low
This line continuously recalculates as new highs or lows are made within the time window
Calculation: Midpoint = (Range High + Range Low) / 2
Evolution example:
At 08:50, range is 18,480 (low) to 18,520 (high), midpoint = 18,500
At 08:55, price makes new high of 18,540, midpoint updates to 18,510
At 09:02, price makes new low of 18,470, midpoint updates to 18,505
The line visually adjusts up and down as the range expands
Extension: The line extends horizontally from the start of the range to the current bar (or end of range)
This gives traders a visual reference for the "fair value" or equilibrium point of the range
Red Line - Close Price
Represents the close price of the most recent candle within the time window
This line updates continuously with each new bar's close price
Extends horizontally across the range
When the range completes (exits the time window), it shows the final close price of the last bar in the range
Example: As price moves from 08:50 to 09:09, the red line will track the close of each candle: 18,505 → 18,510 → 18,508 → 18,515, etc.
This indicator provides a sophisticated visual framework for analyzing specific time-based price behavior. The evolving midpoint (blue line and optional yellow plot) is particularly powerful because it gives you real-time feedback on where the "fair value" of the range is as it develops, allowing you to make informed decisions about whether price is extended or returning to equilibrium. The three-line system (open/mid/close) creates a complete picture of price action within each critical time window, whether you're using standard hourly analysis or focusing on ICT's specific macro times.
Trade The Matric / MACD-RSI Hybrid Candles**"MACD-RSI Hybrid Candles"** is a **custom TradingView Pine Script (v6)** indicator that **replaces your chart’s default candles** with **dynamically colored, intensity-adjusted candles** based on **combined MACD and RSI signals**.
It’s a **visual fusion** of:
- **MACD Histogram** → Momentum & Trend Strength
- **RSI** → Overbought/Oversold & Trend Confirmation
- **Dynamic Transparency** → Visualizes **signal strength**
The result? **At-a-glance confirmation of bullish/bearish phases** — no need to check subcharts.
---
## OVERVIEW: What This Indicator Does
| Feature | Purpose |
|-------|--------|
| **Replaces price candles** | Entire chart becomes a **live MACD-RSI signal map** |
| **Colors based on dual confirmation** | Only strong when **both** MACD and RSI agree |
| **Transparency = momentum intensity** | Brighter = stronger signal |
| **Labels & Alerts** | Highlights **phase changes** (bullish/bearish shifts) |
---
## USER INPUTS (Customizable)
| Input | Default | Description |
|------|--------|-----------|
| `fastLen` | 12 | MACD Fast EMA |
| `slowLen` | 26 | MACD Slow EMA |
| `signalLen` | 9 | MACD Signal Line |
| `rsiLen` | 14 | RSI Period |
| `showLabels` | true | Show "Bullish Phase" / "Bearish Phase" labels |
> Standard settings — tweak for sensitivity.
---
## CORE CALCULATIONS
### 1. **MACD**
```pinescript
macdLine = ta.ema(close, fastLen) - ta.ema(close, slowLen)
signalLine = ta.ema(macdLine, signalLen)
hist = macdLine - signalLine
```
- `hist > 0` → **Bullish momentum**
- `hist < 0` → **Bearish momentum**
### 2. **RSI**
```pinescript
rsi = ta.rsi(close, rsiLen)
```
- `rsi > 50` → **Bullish bias**
- `rsi < 50` → **Bearish bias**
---
## DUAL CONFIRMATION LOGIC
| Condition | Meaning |
|--------|--------|
| `bullCond = macdBull and rsiBull` | **MACD hist > 0** AND **RSI > 50** → **Confirmed Bullish** |
| `bearCond = macdBear and rsiBear` | **MACD hist < 0** AND **RSI < 50** → **Confirmed Bearish** |
| Otherwise | **Neutral / Conflicted** |
> Only **strong, aligned signals** get bright colors.
---
## DYNAMIC INTENSITY & TRANSPARENCY (Key Feature)
```pinescript
maxHist = ta.highest(math.abs(hist), 100)
intensity = math.abs(hist) / maxHist
transp = 90 - (intensity * 80)
```
### How It Works:
1. Finds **strongest MACD histogram value** in last 100 bars
2. Compares **current histogram** to that peak → `intensity` (0 to 1)
3. **Transparency scales from 90 (faint) → 10 (bright)**
| Intensity | Transparency | Visual Effect |
|---------|--------------|-------------|
| 0% (weak) | 90 | Almost transparent |
| 50% | 50 | Medium |
| 100% | 10 | **Vivid, bold candle** |
> **Brighter candle = stronger momentum relative to recent history**
---
## CANDLE COLOR LOGIC
| Condition | Candle & Wick Color | Transparency |
|--------|---------------------|------------|
| **Confirmed Bullish** (`bullCond`) | **Lime Green** | Dynamic (10–90) |
| **Confirmed Bearish** (`bearCond`) | **Red** | Dynamic (10–90) |
| **Neutral / Conflicted** | **Gray** | Fixed 80 (faint) |
> **Wicks and borders match body** → full candle takeover
---
## VISUAL OUTPUT
### 1. **Custom Candles**
```pinescript
plotcandle(open, high, low, close, color=barColor, wickcolor=barColor, bordercolor=barColor)
```
- **Replaces default chart candles**
- **No original candles visible**
### 2. **Labels (Optional)**
- **"Bullish Phase"** → Green label **below low** when:
- MACD histogram **crosses above zero**
- AND RSI **> 50**
- **"Bearish Phase"** → Red label **above high** when:
- MACD histogram **crosses below zero**
- AND RSI **< 50**
> Up to **500 labels** (`max_labels_count=500`)
---
## ALERTS (Built-In)
| Alert | Trigger |
|------|--------|
| **Bullish MACD-RSI Signal** | `ta.crossover(hist, 0) and rsi > 50` |
| **Bearish MACD-RSI Signal** | `ta.crossunder(hist, 0) and rsi < 50` |
> Message: *"MACD crossed above zero with RSI > 50 — Bullish phase."*
---
## HOW TO READ THE CHART
| Visual | Market State | Interpretation |
|-------|-------------|----------------|
| **Bright Lime Candles** | **Strong Bullish Momentum** | High conviction — trend accelerating |
| **Faint Lime Candles** | **Weak Bullish** | Momentum present but not strong |
| **Bright Red Candles** | **Strong Bearish Momentum** | Downtrend with power |
| **Faint Red Candles** | **Weak Bearish** | Selling pressure, but fading |
| **Gray Candles** | **Conflicted / Choppy** | MACD and RSI disagree — avoid |
| **"Bullish Phase" Label** | **New Uptrend Starting** | Entry signal |
| **"Bearish Phase" Label** | **New Downtrend Starting** | Short signal |
---
## TRADING STRATEGY (Example)
### **Long Entry**
1. Wait for **"Bullish Phase" label**
2. Confirm **bright lime candles** (intensity > 50%)
3. Enter on **pullback to support** or **breakout**
4. **Stop Loss**: Below recent swing low
5. **Take Profit**: Trail with EMA or at resistance
### **Short Entry**
1. Wait for **"Bearish Phase" label**
2. Confirm **bright red candles**
3. Enter on **rally to resistance**
> **Best in trending markets** — avoid choppy ranges.
---
## UNIQUE FEATURES
| Feature | Benefit |
|-------|--------|
| **Dual Confirmation** | Avoids false MACD signals in overbought/oversold zones |
| **Dynamic Transparency** | Shows **relative strength** — not just direction |
| **Full Candle Replacement** | Clean, uncluttered chart |
| **Phase Labels** | Marks **exact trend change points** |
| **Built-in Alerts** | No extra setup needed |
---
## LIMITATIONS
| Issue | Note |
|------|------|
| **Lagging by design** | MACD & RSI are reactive |
| **Repainting?** | **No** — all on close |
| **No volume filter** | Add separately for better accuracy |
| **Labels can clutter** | Toggle off in choppy markets |
| **Intensity uses 100-bar lookback** | May lag in very long trends |
---
## BEST USE CASES
| Market | Timeframe | Style |
|-------|----------|------|
| Stocks, Forex, Crypto | 15m, 1H, 4H | Swing / Trend Following |
| **Avoid**: Sideways markets | Yes | High noise = many gray candles |
---
## COMPARISON TO STANDARD MACD/RSI
| Feature | This Indicator | Standard MACD + RSI |
|-------|----------------|---------------------|
| Visual | **Candles = signal** | Subchart lines |
| Confirmation | Built-in dual logic | Manual |
| Strength | Dynamic brightness | Histogram height |
| Alerts | Phase changes | Need custom |
| Chart Clutter | Low | High (two panels) |
> **This is a "one-panel" momentum dashboard**
---
## SUMMARY: What This Indicator Does
> **"MACD-RSI Hybrid Candles"** turns your **entire price chart into a live momentum heatmap** where:
>
> 1. **Candle color** = **MACD + RSI agreement** (Bullish / Bearish / Neutral)
> 2. **Brightness** = **Momentum strength** vs. recent 100 bars
> 3. **Labels & Alerts** = **Trend phase changes** (zero-line crosses with RSI filter)
>
> It **eliminates subcharts** and gives **instant visual confirmation** of:
> - **Trend direction**
> - **Momentum power**
> - **High-probability entries**
---
**Ideal for traders who want:**
- **No indicator panels**
- **Clear, color-coded signals**
- **Strength at a glance**
- **Automated alerts on trend shifts**
---
**Pro Tip**: Use with **volume** or **support/resistance** for **higher win rate**.
J&C indicator📊 Indicators Used
10 MA (Fast) - Short-term trend direction
40 MA (Slow) - Long-term trend direction
🟢 LONG Signal Conditions (ALL must be true)
10 MA is rising (uptrend)
40 MA is rising (strong uptrend)
10 MA > 40 MA (fast above slow = bullish)
Price action: Low touched below 10 MA, but close is above 40 MA
This means price dipped but found support
Algorithm Predator - ML-liteAlgorithm Predator - ML-lite
This indicator combines four specialized trading agents with an adaptive multi-armed bandit selection system to identify high-probability trade setups. It is designed for swing and intraday traders who want systematic signal generation based on institutional order flow patterns , momentum exhaustion , liquidity dynamics , and statistical mean reversion .
Core Architecture
Why These Components Are Combined:
The script addresses a fundamental challenge in algorithmic trading: no single detection method works consistently across all market conditions. By deploying four independent agents and using reinforcement learning algorithms to select or blend their outputs, the system adapts to changing market regimes without manual intervention.
The Four Trading Agents
1. Spoofing Detector Agent 🎭
Detects iceberg orders through persistent volume at similar price levels over 5 bars
Identifies spoofing patterns via asymmetric wick analysis (wicks exceeding 60% of bar range with volume >1.8× average)
Monitors order clustering using simplified Hawkes process intensity tracking (exponential decay model)
Signal Logic: Contrarian—fades false breakouts caused by institutional manipulation
Best Markets: Consolidations, institutional trading windows, low-liquidity hours
2. Exhaustion Detector Agent ⚡
Calculates RSI divergence between price movement and momentum indicator over 5-bar window
Detects VWAP exhaustion (price at 2σ bands with declining volume)
Uses VPIN reversals (volume-based toxic flow dissipation) to identify momentum failure
Signal Logic: Counter-trend—enters when momentum extreme shows weakness
Best Markets: Trending markets reaching climax points, over-extended moves
3. Liquidity Void Detector Agent 💧
Measures Bollinger Band squeeze (width <60% of 50-period average)
Identifies stop hunts via 20-bar high/low penetration with immediate reversal and volume spike
Detects hidden liquidity absorption (volume >2× average with range <0.3× ATR)
Signal Logic: Breakout anticipation—enters after liquidity grab but before main move
Best Markets: Range-bound pre-breakout, volatility compression zones
4. Mean Reversion Agent 📊
Calculates price z-scores relative to 50-period SMA and standard deviation (triggers at ±2σ)
Implements Ornstein-Uhlenbeck process scoring (mean-reverting stochastic model)
Uses entropy analysis to detect algorithmic trading patterns (low entropy <0.25 = high predictability)
Signal Logic: Statistical reversion—enters when price deviates significantly from statistical equilibrium
Best Markets: Range-bound, low-volatility, algorithmically-dominated instruments
Adaptive Selection: Multi-Armed Bandit System
The script implements four reinforcement learning algorithms to dynamically select or blend agents based on performance:
Thompson Sampling (Default - Recommended):
Uses Bayesian inference with beta distributions (tracks alpha/beta parameters per agent)
Balances exploration (trying underused agents) vs. exploitation (using proven winners)
Each agent's win/loss history informs its selection probability
Lite Approximation: Uses pseudo-random sampling from price/volume noise instead of true random number generation
UCB1 (Upper Confidence Bound):
Calculates confidence intervals using: average_reward + sqrt(2 × ln(total_pulls) / agent_pulls)
Deterministic algorithm favoring agents with high uncertainty (potential upside)
More conservative than Thompson Sampling
Epsilon-Greedy:
Exploits best-performing agent (1-ε)% of the time
Explores randomly ε% of the time (default 10%, configurable 1-50%)
Simple, transparent, easily tuned via epsilon parameter
Gradient Bandit:
Uses softmax probability distribution over agent preference weights
Updates weights via gradient ascent based on rewards
Best for Blend mode where all agents contribute
Selection Modes:
Switch Mode: Uses only the selected agent's signal (clean, decisive)
Blend Mode: Combines all agents using exponentially weighted confidence scores controlled by temperature parameter (smooth, diversified)
Lock Agent Feature:
Optional manual override to force one specific agent
Useful after identifying which agent dominates your specific instrument
Only applies in Switch mode
Four choices: Spoofing Detector, Exhaustion Detector, Liquidity Void, Mean Reversion
Memory System
Dual-Layer Architecture:
Short-Term Memory: Stores last 20 trade outcomes per agent (configurable 10-50)
Long-Term Memory: Stores episode averages when short-term reaches transfer threshold (configurable 5-20 bars)
Memory Boost Mechanism: Recent performance modulates agent scores by up to ±20%
Episode Transfer: When an agent accumulates sufficient results, averages are condensed into long-term storage
Persistence: Manual restoration of learned parameters via input fields (alpha, beta, weights, microstructure thresholds)
How Memory Works:
Agent generates signal → outcome tracked after 8 bars (performance horizon)
Result stored in short-term memory (win = 1.0, loss = 0.0)
Short-term average influences agent's future scores (positive feedback loop)
After threshold met (default 10 results), episode averaged into long-term storage
Long-term patterns (weighted 30%) + short-term patterns (weighted 70%) = total memory boost
Market Microstructure Analysis
These advanced metrics quantify institutional order flow dynamics:
Order Flow Toxicity (Simplified VPIN):
Measures buy/sell volume imbalance over 20 bars: |buy_vol - sell_vol| / (buy_vol + sell_vol)
Detects informed trading activity (institutional players with non-public information)
Values >0.4 indicate "toxic flow" (informed traders active)
Lite Approximation: Uses simple open/close heuristic instead of tick-by-tick trade classification
Price Impact Analysis (Simplified Kyle's Lambda):
Measures market impact efficiency: |price_change_10| / sqrt(volume_sum_10)
Low values = large orders with minimal price impact ( stealth accumulation )
High values = retail-dominated moves with high slippage
Lite Approximation: Uses simplified denominator instead of regression-based signed order flow
Market Randomness (Entropy Analysis):
Counts unique price changes over 20 bars / 20
Measures market predictability
High entropy (>0.6) = human-driven, chaotic price action
Low entropy (<0.25) = algorithmic trading dominance (predictable patterns)
Lite Approximation: Simple ratio instead of true Shannon entropy H(X) = -Σ p(x)·log₂(p(x))
Order Clustering (Simplified Hawkes Process):
Tracks self-exciting event intensity (coordinated order activity)
Decays at 0.9× per bar, spikes +1.0 when volume >1.5× average
High intensity (>0.7) indicates clustering (potential spoofing/accumulation)
Lite Approximation: Simple exponential decay instead of full λ(t) = μ + Σ α·exp(-β(t-tᵢ)) with MLE
Signal Generation Process
Multi-Stage Validation:
Stage 1: Agent Scoring
Each agent calculates internal score based on its detection criteria
Scores must exceed agent-specific threshold (adjusted by sensitivity multiplier)
Agent outputs: Signal direction (+1/-1/0) and Confidence level (0.0-1.0)
Stage 2: Memory Boost
Agent scores multiplied by memory boost factor (0.8-1.2 based on recent performance)
Successful agents get amplified, failing agents get dampened
Stage 3: Bandit Selection/Blending
If Adaptive Mode ON:
Switch: Bandit selects single best agent, uses only its signal
Blend: All agents combined using softmax-weighted confidence scores
If Adaptive Mode OFF:
Traditional consensus voting with confidence-squared weighting
Signal fires when consensus exceeds threshold (default 70%)
Stage 4: Confirmation Filter
Raw signal must repeat for consecutive bars (default 3, configurable 2-4)
Minimum confidence threshold: 0.25 (25%) enforced regardless of mode
Trend alignment check: Long signals require trend_score ≥ -2, Short signals require trend_score ≤ 2
Stage 5: Cooldown Enforcement
Minimum bars between signals (default 10, configurable 5-15)
Prevents over-trading during choppy conditions
Stage 6: Performance Tracking
After 8 bars (performance horizon), signal outcome evaluated
Win = price moved in signal direction, Loss = price moved against
Results fed back into memory and bandit statistics
Trading Modes (Presets)
Pre-configured parameter sets:
Conservative: 85% consensus, 4 confirmations, 15-bar cooldown
Expected: 60-70% win rate, 3-8 signals/week
Best for: Swing trading, capital preservation, beginners
Balanced: 70% consensus, 3 confirmations, 10-bar cooldown
Expected: 55-65% win rate, 8-15 signals/week
Best for: Day trading, most traders, general use
Aggressive: 60% consensus, 2 confirmations, 5-bar cooldown
Expected: 50-58% win rate, 15-30 signals/week
Best for: Scalping, high-frequency trading, active management
Elite: 75% consensus, 3 confirmations, 12-bar cooldown
Expected: 58-68% win rate, 5-12 signals/week
Best for: Selective trading, high-conviction setups
Adaptive: 65% consensus, 2 confirmations, 8-bar cooldown
Expected: Varies based on learning
Best for: Experienced users leveraging bandit system
How to Use
1. Initial Setup (5 Minutes):
Select Trading Mode matching your style (start with Balanced)
Enable Adaptive Learning (recommended for automatic agent selection)
Choose Thompson Sampling algorithm (best all-around performance)
Keep Microstructure Metrics enabled for liquid instruments (>100k daily volume)
2. Agent Tuning (Optional):
Adjust Agent Sensitivity multipliers (0.5-2.0):
<0.8 = Highly selective (fewer signals, higher quality)
0.9-1.2 = Balanced (recommended starting point)
1.3 = Aggressive (more signals, lower individual quality)
Monitor dashboard for 20-30 signals to identify dominant agent
If one agent consistently outperforms, consider using Lock Agent feature
3. Bandit Configuration (Advanced):
Blend Temperature (0.1-2.0):
0.3 = Sharp decisions (best agent dominates)
0.5 = Balanced (default)
1.0+ = Smooth (equal weighting, democratic)
Memory Decay (0.8-0.99):
0.90 = Fast adaptation (volatile markets)
0.95 = Balanced (most instruments)
0.97+ = Long memory (stable trends)
4. Signal Interpretation:
Green triangle (▲): Long signal confirmed
Red triangle (▼): Short signal confirmed
Dashboard shows:
Active agent (highlighted row with ► marker)
Win rate per agent (green >60%, yellow 40-60%, red <40%)
Confidence bars (█████ = maximum confidence)
Memory size (short-term buffer count)
Colored zones display:
Entry level (current close)
Stop-loss (1.5× ATR)
Take-profit 1 (2.0× ATR)
Take-profit 2 (3.5× ATR)
5. Risk Management:
Never risk >1-2% per signal (use ATR-based stops)
Signals are entry triggers, not complete strategies
Combine with your own market context analysis
Consider fundamental catalysts and news events
Use "Confirming" status to prepare entries (not to enter early)
6. Memory Persistence (Optional):
After 50-100 trades, check Memory Export Panel
Record displayed alpha/beta/weight values for each agent
Record VPIN and Kyle threshold values
Enable "Restore From Memory" and input saved values to continue learning
Useful when switching timeframes or restarting indicator
Visual Components
On-Chart Elements:
Spectral Layers: EMA8 ± 0.5 ATR bands (dynamic support/resistance, colored by trend)
Energy Radiance: Multi-layer glow boxes at signal points (intensity scales with confidence, configurable 1-5 layers)
Probability Cones: Projected price paths with uncertainty wedges (15-bar projection, width = confidence × ATR)
Connection Lines: Links sequential signals (solid = same direction continuation, dotted = reversal)
Kill Zones: Risk/reward boxes showing entry, stop-loss, and dual take-profit targets
Signal Markers: Triangle up/down at validated entry points
Dashboard (Configurable Position & Size):
Regime Indicator: 4-level trend classification (Strong Bull/Bear, Weak Bull/Bear)
Mode Status: Shows active system (Adaptive Blend, Locked Agent, or Consensus)
Agent Performance Table: Real-time win%, confidence, and memory stats
Order Flow Metrics: Toxicity and impact indicators (when microstructure enabled)
Signal Status: Current state (Long/Short/Confirming/Waiting) with confirmation progress
Memory Panel (Configurable Position & Size):
Live Parameter Export: Alpha, beta, and weight values per agent
Adaptive Thresholds: Current VPIN sensitivity and Kyle threshold
Save Reminder: Visual indicator if parameters should be recorded
What Makes This Original
This script's originality lies in three key innovations:
1. Genuine Meta-Learning Framework:
Unlike traditional indicator mashups that simply display multiple signals, this implements authentic reinforcement learning (multi-armed bandits) to learn which detection method works best in current conditions. The Thompson Sampling implementation with beta distribution tracking (alpha for successes, beta for failures) is statistically rigorous and adapts continuously. This is not post-hoc optimization—it's real-time learning.
2. Episodic Memory Architecture with Transfer Learning:
The dual-layer memory system mimics human learning patterns:
Short-term memory captures recent performance (recency bias)
Long-term memory preserves historical patterns (experience)
Automatic transfer mechanism consolidates knowledge
Memory boost creates positive feedback loops (successful strategies become stronger)
This architecture allows the system to adapt without retraining , unlike static ML models that require batch updates.
3. Institutional Microstructure Integration:
Combines retail-focused technical analysis (RSI, Bollinger Bands, VWAP) with institutional-grade microstructure metrics (VPIN, Kyle's Lambda, Hawkes processes) typically found in academic finance literature and professional trading systems, not standard retail platforms. While simplified for Pine Script constraints, these metrics provide insight into informed vs. uninformed trading , a dimension entirely absent from traditional technical analysis.
Mashup Justification:
The four agents are combined specifically for risk diversification across failure modes:
Spoofing Detector: Prevents false breakout losses from manipulation
Exhaustion Detector: Prevents chasing extended trends into reversals
Liquidity Void: Exploits volatility compression (different regime than trending)
Mean Reversion: Provides mathematical anchoring when patterns fail
The bandit system ensures the optimal tool is automatically selected for each market situation, rather than requiring manual interpretation of conflicting signals.
Why "ML-lite"? Simplifications and Approximations
This is the "lite" version due to necessary simplifications for Pine Script execution:
1. Simplified VPIN Calculation:
Academic Implementation: True VPIN uses volume bucketing (fixed-volume bars) and tick-by-tick buy/sell classification via Lee-Ready algorithm or exchange-provided trade direction flags
This Implementation: 20-bar rolling window with simple open/close heuristic (close > open = buy volume)
Impact: May misclassify volume during ranging/choppy markets; works best in directional moves
2. Pseudo-Random Sampling:
Academic Implementation: Thompson Sampling requires true random number generation from beta distributions using inverse transform sampling or acceptance-rejection methods
This Implementation: Deterministic pseudo-randomness derived from price and volume decimal digits: (close × 100 - floor(close × 100)) + (volume % 100) / 100
Impact: Not cryptographically random; may have subtle biases in specific price ranges; provides sufficient variation for agent selection
3. Hawkes Process Approximation:
Academic Implementation: Full Hawkes process uses maximum likelihood estimation with exponential kernels: λ(t) = μ + Σ α·exp(-β(t-tᵢ)) fitted via iterative optimization
This Implementation: Simple exponential decay (0.9 multiplier) with binary event triggers (volume spike = event)
Impact: Captures self-exciting property but lacks parameter optimization; fixed decay rate may not suit all instruments
4. Kyle's Lambda Simplification:
Academic Implementation: Estimated via regression of price impact on signed order flow over multiple time intervals: Δp = λ × Δv + ε
This Implementation: Simplified ratio: price_change / sqrt(volume_sum) without proper signed order flow or regression
Impact: Provides directional indicator of impact but not true market depth measurement; no statistical confidence intervals
5. Entropy Calculation:
Academic Implementation: True Shannon entropy requires probability distribution: H(X) = -Σ p(x)·log₂(p(x)) where p(x) is probability of each price change magnitude
This Implementation: Simple ratio of unique price changes to total observations (variety measure)
Impact: Measures diversity but not true information entropy with probability weighting; less sensitive to distribution shape
6. Memory System Constraints:
Full ML Implementation: Neural networks with backpropagation, experience replay buffers (storing state-action-reward tuples), gradient descent optimization, and eligibility traces
This Implementation: Fixed-size array queues with simple averaging; no gradient-based learning, no state representation beyond raw scores
Impact: Cannot learn complex non-linear patterns; limited to linear performance tracking
7. Limited Feature Engineering:
Advanced Implementation: Dozens of engineered features, polynomial interactions (x², x³), dimensionality reduction (PCA, autoencoders), feature selection algorithms
This Implementation: Raw agent scores and basic market metrics (RSI, ATR, volume ratio); minimal transformation
Impact: May miss subtle cross-feature interactions; relies on agent-level intelligence rather than feature combinations
8. Single-Instrument Data:
Full Implementation: Multi-asset correlation analysis (sector ETFs, currency pairs, volatility indices like VIX), lead-lag relationships, risk-on/risk-off regimes
This Implementation: Only OHLCV data from displayed instrument
Impact: Cannot incorporate broader market context; vulnerable to correlated moves across assets
9. Fixed Performance Horizon:
Full Implementation: Adaptive horizon based on trade duration, volatility regime, or profit target achievement
This Implementation: Fixed 8-bar evaluation window
Impact: May evaluate too early in slow markets or too late in fast markets; one-size-fits-all approach
Performance Impact Summary:
These simplifications make the script:
✅ Faster: Executes in milliseconds vs. seconds (or minutes) for full academic implementations
✅ More Accessible: Runs on any TradingView plan without external data feeds, APIs, or compute servers
✅ More Transparent: All calculations visible in Pine Script (no black-box compiled models)
✅ Lower Resource Usage: <500 bars lookback, minimal memory footprint
⚠️ Less Precise: Approximations may reduce statistical edge by 5-15% vs. academic implementations
⚠️ Limited Scope: Cannot capture tick-level dynamics, multi-order-book interactions, or cross-asset flows
⚠️ Fixed Parameters: Some thresholds hardcoded rather than dynamically optimized
When to Upgrade to Full Implementation:
Consider professional Python/C++ versions with institutional data feeds if:
Trading with >$100K capital where precision differences materially impact returns
Operating in microsecond-competitive environments (HFT, market making)
Requiring regulatory-grade audit trails and reproducibility
Backtesting with tick-level precision for strategy validation
Need true real-time adaptation with neural network-based learning
For retail swing/day trading and position management, these approximations provide sufficient signal quality while maintaining usability, transparency, and accessibility. The core logic—multi-agent detection with adaptive selection—remains intact.
Technical Notes
All calculations use standard Pine Script built-in functions ( ta.ema, ta.atr, ta.rsi, ta.bb, ta.sma, ta.stdev, ta.vwap )
VPIN and Kyle's Lambda use simplified formulas optimized for OHLCV data (see "Lite" section above)
Thompson Sampling uses pseudo-random noise from price/volume decimal digits for beta distribution sampling
No repainting: All calculations use confirmed bar data (no forward-looking)
Maximum lookback: 500 bars (set via max_bars_back parameter)
Performance evaluation: 8-bar forward-looking window for reward calculation (clearly disclosed)
Confidence threshold: Minimum 0.25 (25%) enforced on all signals
Memory arrays: Dynamic sizing with FIFO queue management
Limitations and Disclaimers
Not Predictive: This indicator identifies patterns in historical data. It cannot predict future price movements with certainty.
Requires Human Judgment: Signals are entry triggers, not complete trading strategies. Must be confirmed with your own analysis, risk management rules, and market context.
Learning Period Required: The adaptive system requires 50-100 bars minimum to build statistically meaningful performance data for bandit algorithms.
Overfitting Risk: Restoring memory parameters from one market regime to a drastically different regime (e.g., low volatility to high volatility) may cause poor initial performance until system re-adapts.
Approximation Limitations: Simplified calculations (see "Lite" section) may underperform academic implementations by 5-15% in highly efficient markets.
No Guarantee of Profit: Past performance, whether backtested or live-traded, does not guarantee future performance. All trading involves risk of loss.
Forward-Looking Bias: Performance evaluation uses 8-bar forward window—this creates slight look-ahead for learning (though not for signals). Real-time performance may differ from indicator's internal statistics.
Single-Instrument Limitation: Does not account for correlations with related assets or broader market regime changes.
Recommended Settings
Timeframe: 15-minute to 4-hour charts (sufficient volatility for ATR-based stops; adequate bar volume for learning)
Assets: Liquid instruments with >100k daily volume (forex majors, large-cap stocks, BTC/ETH, major indices)
Not Recommended: Illiquid small-caps, penny stocks, low-volume altcoins (microstructure metrics unreliable)
Complementary Tools: Volume profile, order book depth, market breadth indicators, fundamental catalysts
Position Sizing: Risk no more than 1-2% of capital per signal using ATR-based stop-loss
Signal Filtering: Consider external confluence (support/resistance, trendlines, round numbers, session opens)
Start With: Balanced mode, Thompson Sampling, Blend mode, default agent sensitivities (1.0)
After 30+ Signals: Review agent win rates, consider increasing sensitivity of top performers or locking to dominant agent
Alert Configuration
The script includes built-in alert conditions:
Long Signal: Fires when validated long entry confirmed
Short Signal: Fires when validated short entry confirmed
Alerts fire once per bar (after confirmation requirements met)
Set alert to "Once Per Bar Close" for reliability
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
SD Levels + EMASD Levels + EMA
Overview:
The SD Levels + EMA indicator combines volatility-based standard deviation levels with dual EMA signals to help traders identify potential breakout zones, overextended regions, and trend shifts. It overlays key market structure levels directly on the chart, giving a clear visual roadmap of intraday and daily strength zones.
🧠 Core Features
1. Standard Deviation Levels (SD Module)
Calculates volatility using annualized standard deviation from the selected source (hlc3 by default).
Automatically plots:
Settlement level
±0.33 SD, ±0.66 SD, ±1 SD, ±1.33 SD, ±1.66 SD, ±2 SD bands
Optionally displays:
Previous day’s high/low
Current day’s running high/low
These levels help spot volatility extremes, mean reversion zones, and breakout potential.
2. EMA Module
Plots two customizable EMAs (default = 5 and 10 periods).
Highlights bullish/bearish crossovers with clear up/down triangles.
Generates alerts for crossover events.
Includes an optional $-spaced grid (default $25) with user-defined levels above and below current price.
3. Visual & Utility Options
Optional info table showing:
Current Price
EMA 5
EMA 10
Real-time trend direction (Bullish ↑, Bearish ↓, Neutral)
Lightweight, non-repainting logic optimized for intraday timeframes.
User-friendly inputs to toggle each module independently.
⚙️ Recommended Use
Combine SD zones with EMA crossovers to confirm volatility-based breakouts or fade reversions near extremes.
The extended ±SD ladder helps traders map confluence areas between volatility expansion and EMA momentum.
🛠 Customization
Adjust SD sensitivity via level toggles and settlement source.
Modify grid spacing, number of levels, and EMA periods.
Enable/disable tables, labels, and individual components to match your charting style.
📢 Alerts
🔔 Bullish EMA Cross: EMA 5 crosses above EMA 10
🔔 Bearish EMA Cross: EMA 5 crosses below EMA 10
⚡ Summary
A hybrid indicator that merges volatility-based structure (SD levels) with trend-based momentum (EMA crosses)—ideal for traders who want to visualize both mean-reversion zones and trend continuation opportunities within a single tool.






















