VisibleChart█ OVERVIEW
This library is a Pine programmer’s tool containing functions that return values calculated from the range of visible bars on the chart.
This is now possible in Pine Script™ thanks to the recently-released chart.left_visible_bar_time and chart.right_visible_bar_time built-ins, which return the opening time of the leftmost and rightmost bars on the chart. These values update as traders scroll or zoom their charts, which gives way to a class of indicators that can dynamically recalculate and draw visuals on visible bars only, as users scroll or zoom their charts. We hope this library's functions help you make the most of the world of possibilities these new built-ins provide for Pine scripts.
For an example of a script using this library, have a look at the Chart VWAP indicator.
█ CONCEPTS
Chart properties
The new chart.left_visible_bar_time and chart.right_visible_bar_time variables return the opening time of the leftmost and rightmost bars on the chart. They are only two of many new built-ins in the `chart.*` namespace. See this blog post for more information, or look them up by typing "chart." in the Pine Script™ Reference Manual .
Dynamic recalculation of scripts on visible bars
Any script using chart.left_visible_bar_time or chart.right_visible_bar_time acquires a unique property, which triggers its recalculation when traders scroll or zoom their charts in such a way that the range of visible bars on the chart changes. This library's functions use the two recent built-ins to derive various values from the range of visible bars.
Designing your scripts for dynamic recalculation
For the library's functions to work correctly, they must be called on every bar. For reliable results, assign their results to global variables and then use the variables locally where needed — not the raw function calls.
Some functions like `barIsVisible()` or `open()` will return a value starting on the leftmost visible bar. Others such as `high()` or `low()` will also return a value starting on the leftmost visible bar, but their correct value can only be known on the rightmost visible bar, after all visible bars have been analyzed by the script.
You can plot values as the script executes on visible bars, but efficient code will, when possible, create resource-intensive labels, lines or tables only once in the global scope using var , and then use the setter functions to modify their properties on the last bar only. The example code included in this library uses this method.
Keep in mind that when your script uses chart.left_visible_bar_time or chart.right_visible_bar_time , your script will recalculate on all bars each time the user scrolls or zooms their chart. To provide script users with the best experience you should strive to keep calculations to a minimum and use efficient code so that traders are not always waiting for your script to recalculate every time they scroll or zoom their chart.
Another aspect to consider is the fact that the rightmost visible bar will not always be the last bar in the dataset. When script users scroll back in time, a large portion of the time series the script calculates on may be situated after the rightmost visible bar. We can never assume the rightmost visible bar is also the last bar of the time series. Use `barIsVisible()` to restrict calculations to visible bars, but also consider that your script can continue to execute past them.
Look first. Then leap.
█ FUNCTIONS
The library contains the following functions:
barIsVisible()
Condition to determine if a given bar is within the users visible time range.
Returns: (bool) True if the the calling bar is between the `chart.left_visible_bar_time` and the `chart.right_visible_bar_time`.
high()
Determines the value of the highest `high` in visible bars.
Returns: (float) The maximum high value of visible chart bars.
highBarIndex()
Determines the `bar_index` of the highest `high` in visible bars.
Returns: (int) The `bar_index` of the `high()`.
highBarTime()
Determines the bar time of the highest `high` in visible bars.
Returns: (int) The `time` of the `high()`.
low()
Determines the value of the lowest `low` in visible bars.
Returns: (float) The minimum low value of visible chart bars.
lowBarIndex()
Determines the `bar_index` of the lowest `low` in visible bars.
Returns: (int) The `bar_index` of the `low()`.
lowBarTime()
Determines the bar time of the lowest `low` in visible bars.
Returns: (int) The `time` of the `low()`.
open()
Determines the value of the opening price in the visible chart time range.
Returns: (float) The `open` of the leftmost visible chart bar.
close()
Determines the value of the closing price in the visible chart time range.
Returns: (float) The `close` of the rightmost visible chart bar.
leftBarIndex()
Determines the `bar_index` of the leftmost visible chart bar.
Returns: (int) A `bar_index`.
rightBarIndex()
Determines the `bar_index` of the rightmost visible chart bar.
Returns: (int) A `bar_index`
bars()
Determines the number of visible chart bars.
Returns: (int) The number of bars.
volume()
Determines the sum of volume of all visible chart bars.
Returns: (float) The cumulative sum of volume.
ohlcv()
Determines the open, high, low, close, and volume sum of the visible bar time range.
Returns: ( ) A tuple of the OHLCV values for the visible chart bars. Example: open is chart left, high is the highest visible high, etc.
chartYPct(pct)
Determines a price level as a percentage of the visible bar price range, which depends on the chart's top/bottom margins in "Settings/Appearance".
Parameters:
pct : (series float) Percentage of the visible price range (50 is 50%). Negative values are allowed.
Returns: (float) A price level equal to the `pct` of the price range between the high and low of visible chart bars. Example: 50 is halfway between the visible high and low.
chartXTimePct(pct)
Determines a time as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
chartXIndexPct(pct)
Determines a `bar_index` as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
whenVisible(src, whenCond, length)
Creates an array containing the `length` last `src` values where `whenCond` is true for visible chart bars.
Parameters:
src : (series int/float) The source of the values to be included.
whenCond : (series bool) The condition determining which values are included. Optional. The default is `true`.
length : (simple int) The number of last values to return. Optional. The default is all values.
Returns: (float ) The array ID of the accumulated `src` values.
avg(src)
Gathers values of the source over visible chart bars and averages them.
Parameters:
src : (series int/float) The source of the values to be averaged. Optional. Default is `close`.
Returns: (float) A cumulative average of values for the visible time range.
median(src)
Calculates the median of a source over visible chart bars.
Parameters:
src : (series int/float) The source of the values. Optional. Default is `close`.
Returns: (float) The median of the `src` for the visible time range.
vVwap(src)
Calculates a volume-weighted average for visible chart bars.
Parameters:
src : (series int/float) Source used for the VWAP calculation. Optional. Default is `hlc3`.
Returns: (float) The VWAP for the visible time range.
Search in scripts for "vwap"
Nifty & BN 2 Candle Theory Back Testing and Alert Notification How To Initiate Long Trade-in Index Future/ Buy Call Options – 3 Min TF
▪ If The Index Futures Trades Above The VWAP, the Following Parameters are Checked For 2 Candle Theory on the long side
▪ RSI Trades Above 50 & Between 50-75/80
▪ Volume Of 2 Consecutive Bars Is Above 50 K for BN & 125 K For Nifty
▪ All the indicators (Parabolic SAR, Super Trend, VMA, VWAP) Below the Candles
▪ When the above conditions are met enter In 3rd Candle, With 1st Candle High As SL
How I Initiate Short Trade-In Index Future/ Buy Put Options – 3 Min TF
▪ If The Index Futures Trades Below The VWAP, the Following Parameters are Checked For 2 Candle Theory on the short side
▪ RSI Trades Below 40 & Between 40-25/20
▪ Volume Of 2 Consecutive Bars Is Above 50 K for BN & 125 K For Nifty
▪ All the Indicators (Parabolic SAR, Super Trend, VMA, VWAP) Above The Candles
▪ When the above conditions are met enter In 3rd Candle, With 1st Candle High As SL
The indicator checks the above and notifies to enter a long trade and short trade respectively. There is also volume cutoff and change in the volumes respectively, also non-trading times that can be set.
[EG] MA ATR ChannelsGreetings - the aim of this indicator was to code a single indicator with a selectable moving average, so I could examine price relationships to MA's and Average True Range (ATR) bollinger type bands. You can obviously approach this tool in so many different ways so I am going to share first an overview of moving averages and a short overview of how I use this this indicator.
Simple ( SMA ) – A simple average of the past N (length) prices. Just add the price data for each N (bar) and divide the total by N.
Exponential ( EMA ) – An exponential moving average with a greater weight for recent prices. The weighting is exponential. An N-period EMA takes more than N data points into account and gradually dilutes past data’s effect.
Double Exponential ( DEMA ) - Same as an EMA , the Double exponential moving average , or DEMA , is a measure of a security's trending average price that gives the even more weight to recent price data. Aimed to help reduce lag.
Triple Exponential ( TEMA ) - Same as an EMA , the Triple exponential moving average , or TEMA , is a measure of a security's trending average price that gives the even more weight to recent price data than EMA or DEMA . Aimed to help reduce lag.
Weighted ( WMA ) – An average of the past N prices with a linear weighting, again giving greater weight to more recent prices.
Hull ( HMA ) - The Hull Moving Average (developed by Alan Hull) has the purpose of reducing lag, increasing responsiveness while at the same time eliminating noise. It emphasises recent prices over older ones, resulting in a fast-acting yet smooth moving average that can be used to identify the prevailing market trend.
Wilder's (RMA) - Wilder's smoothing is a type of exponential moving average . It takes one parameter, the period n, and price. Larger values for n will have a greater smoothing effect on the input data but will also create more lag. It is equivalent to a 2n-1 Exponential Moving Average . For example, a 10 period Wilder's smoothing is the same as a 19 period exponential moving average .
Symmetrically Weighted ( SWMA ) - Weight distribution starts from median of given period and it's reduced linearly to the sides so the ending and starting point of period have the least weight. It's smooth and fast but reacts late to trend changes on higher lengths (lookback).
Arnaud Legoux ( ALMA ) - Arnaud Legoux Moving Average removes small price fluctuations and enhances trend via applying a moving average twice, once from left to right, and once from right to left and combines both. At the end of this process the phase shift (price lag) commonly associated with moving averages is significantly reduced.
Volume-Weighted ( VWMA ) - A Volume-Weighted Moving Average gives a different weight to each closing price and this weight depends on the volume of that period. For example, the closing price of a day with high volume will have a greater weight on the moving average value.
Volume Weighted Average Price ( VWAP ) - Though not necessarily a MA - Volume-weighted average price ( VWAP ) is a ratio of the cumulative share price to the cumulative volume traded over a given time period and so I thought would be useful as an ATR tool. The VWAP is calculated using the opening price for each day and adjusting in real time right up until the close of the session. Thus, the calculation uses intraday data only.
So what is Average True Range ?
Average True Range is a measure of volatility . It's an area that represents roughly how much you can expect a security to change in price over a time period. Average true range is usually calculated by applying Wilders Smoothing to True Range. If you want regular ATR - use RMA as the input for the ATR. The ATR is then divided into periods based on derivatives of Phi (3.14) and Fibs (0.618, 1.618 etc.) You will notice price bounces off the lines. Look for patterns.
The indicator - consisting of 3 parts:
Price/Fast MA - this is an MA anywhere between 3-20 periods that is reflective of very recent price action. It is red when price is below - and green when above. Recommendations : SMA , EMA , WMA , HMA
Trend/Medium MA - this is a slower MA that you could set anywhere between 30 - 100 periods that is reflective of overall bull/bear market trend depending on both it's direction and whether the Price MA / price is lower or higher. Recommendations: EMA , WMA , VWMA , RMA, ALMA
Average True Range - this is a way to measure and visualise range the price may be capable of in - if it is towards or below the 2.1 multiplier - a bull reversal is more likely and vice versea. The multi's are set to factors of Pi and Fibonacci ratio's. Green channel means bullish, red channel means bearish. Gold means sign of a likely reversal. If the PMA enters the channel - it is likely the reversal is cancelled for a short period more.
Recommendations : RMA, EMA , VWMA , ALMA , SWMA , VWAP
How I use it :
First of all - Consider longs when channel is green - or going to bounce on a support line - and consider shorts based on the opposite. This is not a buy/sell indicator - this is a MAP to PRICE to give reference and meaning to price movements across multiple time frames - very useful when using with a volume indicator and an RSI. I personally use it on the 3m chart but change the TFM to 5 for 15m data.
If you wish to see any other more exotic or interesting MA's added please feel free to request them in the comments ! And thanks for checking out my first indicator
Tradingview ToolkitA new trader's biggest barrier to entry is lack of understanding where they are in terms of time and price and with tradingview free they are often limited to just 1 or 2 extra indicators as many new traders slap on RSI and MACD as 2/3 free ones. While these indicators are fine for trend analysis, its important to know where the price is in relation to time. Thus, this all-in-one script is meant to have a lot of customizable utility to save on indicator spots and act as a hotspot for many common needs.
-2 Sets of VWAP line w/ standard deviation bands with customizable timeframes.
-1 more customizable timeframe VWAP line (no std dev bands) to use as a long time frame reference
-Ability to plot previous VWAP close prices over current timeframe on all VWAP lines w/ basic color changing if price closes above/below
-2 Sets of Bollinger Bands with customizable source length and MA type
-3 customizable moving averages with custom timeframe/resolutions
-Inside candle barcolor repainter to easily notice if a candle was inside the range of the previous candle (price contraction)
Not meant to have everything on at once, but simply a place to enable and disable different things and save spots for more important things
Altered True Strength Indicator (TSI) Reupload-
Altered TSI provides a slightly more volatile signal that demonstrates extremities in price action with greater success than standard TSI. In addition, I added bull/bear cross indicators (green/red) to make it easier to notice the crosses to save time when the market is moving fast (I couldn't find a regular TSI script with this addition). Finally, the signal also has overextension parameters (red and green lines)
I think this is best used on Intraday time frames as the signals respond to volatility very well and using Heikin Ashi candles, trend is more visual. In this particular example, I am showing SPY on the 3m time chart (my favorite short time frame) and the signal alone provided many opportunities for trades when using simple divergences and countering overextension direction when short term (blue) signal crosses either
In the first example (purple lines), SPY ramps but it was a dull signal given the signal strength flatlining- we would be looking for a short entry. When the signal fires, it provides a clean $1.50 move down in spy.
In the second example (orange), the blue signal provides a nice V shape (rebound signal) in which we are looking for a long entry. 390.50 is a strong SPY support in confluence with 2nd std dev VWAP extension, but disregarding that bull signal fires resulting in a 2 dollar move upwards. Exit is provided when blue line crosses green overextension.
In the third example (white), we are searching for a short entry at 392.5 resistance in confluence with divergently higher highs. Bear cross signal when fired and a significant cross is visible provides a $2.50 move to the downside with a potential exit provided when blue line crosses red overextension line in confluence with previous LOD area.
In the fourth example (green), we watch as the blue line provides a V pattern, we are searching for a long entry. If you didn't take a riskier long at 2nd std dev VWAP overextension with V recovery on blue line at red overextension for a ride to vwap, then you are looking for a secondary entry long as you wouldn't take the trade at resistance (vwap). Bullishly divergent lows provide this entry and the signal does not bear cross at all (but looking for significant crosses is more important even if the signal were to make a minor bear cross). Bullishly divergent double bottom provides a long entry to end of day with a nice clean signal for a $5.00 move until eod or when signal crosses overextension range.
Ideally, close to the money options or SPY/SPXS/SPXL are best used in the intraday time frame.
Again, this is not a standalone indicator but it's best used in conjunction with other indicators/trading strategies
Any questions feel free to comment
VolumeWeightedAveragePriceHey guys,
here i present an advanced version of the standard VWAP indicator, with some configurable offsets.
The basic VWAP is an intraday average price weighted by volume to offer great levels to enter a trade (long or short).
The Formula looks like this:
VWAP= (∑Price * Volume) / ∑Volume
Its very simple to use: if the price closes above the VWAP its bullish, if it closes below its bearish. Because it acts as support and resistance, you can find good entries around this level and also on its offsets.
Feel free to ask if something is unclear now.
Cheers
Chart Mojo Neutral Unwound CloudPlots days high/low and the Chart Mojo neutral cloud, the zone between vwap and 50% range. A secondary gravity right behind the opening 1 min range. The gray crosses are the vwap the gold dots are 50% of developing range. The shaded area between vwap and 50% range is the Chart Mojo cloud...I think of it as traders from the open tend to unwind to it many times a day. More returns on a trend day but you will see urges toward it on trend days. Price tends to urge to it ahead of 10:30 session "1" and 1:15 Session 2. If you get used to watching it and its relationship to price and the opening 1 min range you should start to see tendencies as to when price unwinds toward it.. etc. Where price is in relation to the cloud and the clouds relationship to the opening 1 min range can reveal real time bias. You will being to see, upon observation how traders target the vwap and 50% with target tier of buys and sells etc. Often unwinds to the zones gravity. It takes force or a catalyst to break the gravity. I use it in conjuction with Time Zone theory and Wave and Pattern force...and look to leading correlating hi beta movers and internals like tick and new streaming highs-new straming lows to get jump on what you see on a big etf or index etc. If you intraday tendencies the neutral is very helpful.
MTF Regression with Forecast### **MTF Regression with Forecast, Treasury Yield, Additional Variable & VWAP Filter - Enhanced with Long Regression**
Unlock advanced market insights with our **MTF Regression** indicator, meticulously designed for traders seeking comprehensive multi-timeframe analysis combined with powerful forecasting tools. Whether you're a seasoned trader or just starting out, this indicator offers a suite of features to enhance your trading strategy.
#### **🔍 Key Features:**
- **Multi-Timeframe (MTF) Regression:**
- **Fast, Slow, & Long Regressions:** Analyze price trends across multiple timeframes to capture both short-term movements and long-term trends.
- **Customizable Price Inputs:**
- **Flexible Price Selection:** Choose between Close, Open, High, or Low prices to suit your trading style.
- **Price Transformation:** Option to apply Exponential Moving Averages (EMA) for smoother trend analysis.
- **Diverse Regression Methods:**
- **Multiple Algorithms:** Select from Linear, Exponential, Hull Moving Average (HMA), Weighted Moving Average (WMA), or Spline regressions to best fit your analysis needs.
- **Integrated External Data:**
- **10-Year Treasury Yield:** Incorporate macroeconomic indicators to refine regression accuracy.
- **Additional Variables:** Enhance your analysis by integrating data from other tickers (e.g., NASDAQ:AAPL).
- **Advanced Filtering Options:**
- **VWAP Filter:** Align signals with the Volume Weighted Average Price for improved trade entries.
- **Price Action Filter:** Ensure price behavior supports the generated signals for higher reliability.
- **Enhanced Signal Generation:**
- **Bullish & Bearish Signals:** Identify potential trend reversals and continuations with clear visual cues.
- **Predictive Signals:** Forecast future price movements with forward-looking arrows based on regression slopes.
- **Slope & Acceleration Thresholds:** Customize minimum slope and acceleration levels to fine-tune signal sensitivity.
- **Forecasting Capabilities:**
- **Projection Lines:** Visualize future price trends by extending regression lines based on current slope data.
- **User-Friendly Interface:**
- **Organized Settings Groups:** Easily navigate through price inputs, regression settings, integration options, and more.
- **Customizable Alerts:** Stay informed with configurable alerts for bullish, bearish, and predictive signals.
#### **📈 Why Choose MTF Regression Indicator?**
- **Comprehensive Analysis:** Combines multiple regression techniques and external data sources for a well-rounded market view.
- **Flexibility:** Highly customizable to fit various trading strategies and preferences.
- **Enhanced Decision-Making:** Provides clear signals and forecasts to support informed trading decisions.
- **Efficiency:** Optimized to deliver reliable performance without overloading your trading platform.
Elevate your trading game with the **MTF Regression with Forecast, Treasury Yield, Additional Variable & VWAP Filter** indicator. Harness the power of multi-timeframe analysis and predictive forecasting to stay ahead in the dynamic markets.
---
*Feel free to reach out for more information or support. Happy Trading!*
Multi-Timeframe Trend TableThe "Multi-Timeframe Trend Table" indicator is a tool that consolidates a variety of critical trading metrics into a single, easy-to-read table format. This indicator is especially useful for traders who need to analyze multiple timeframes and indicators simultaneously to make informed trading decisions. By displaying a broad spectrum of data including trend information, rangebound status, volatility levels, VWAP (Volume Weighted Average Price), and specific candlestick patterns, the indicator provides a comprehensive overview of market conditions across different timeframes.
Functionality and Components
At its core, the indicator provides real-time insights into market trends by showing whether each timeframe is experiencing an upward, downward, or neutral trend based on simple moving averages. This is complemented by the "Rangebound" status, which indicates whether the price is trading within a defined range, giving insights into market consolidation periods. This can be critical for identifying breakouts or breakdowns from established ranges.
Volatility Measurement
Another key feature of the indicator is the "Volatility" column, which rates the market's volatility on a scale from 1 to 10. This feature uses the Average True Range (ATR) to assess how drastically prices are changing within a given timeframe, providing a numerical value that helps traders understand the intensity of price movements. High volatility levels (scores above 6) are highlighted, which can be crucial for strategies that prefer high volatility.
VWAP and Candlestick Patterns
The indicator also displays the VWAP, which is essential for traders who focus on volume as it shows the average price a security has traded at throughout the day, based on both volume and price. It is especially useful for traders looking to confirm trend directions or catch potential reversals. Additionally, the "Candle" column enhances the indicator's utility by identifying specific candlestick patterns like Doji, Hammer, Inverted Hammer, Bullish Engulfing, and Bearish Engulfing, which are pivotal for pinpointing momentum changes and potential entry or exit points.
Usage Strategy
Traders can utilize this indicator by setting up specific rules based on the information provided. For instance, a possible strategy could involve entering a trade when a Bullish Engulfing pattern appears in a low-volatility environment as indicated by a volatility score under 6, suggesting a potential uptrend start with limited downside risk. Similarly, a trader might consider exiting a position or taking a short position when a Bearish Engulfing pattern is identified during high volatility periods, signaling possible sharp price declines.
Adaptability and Customization
An added advantage is the indicator’s adaptability; traders can customize which columns to display based on their trading preferences and strategies. Whether focusing on trends, volatility, or candlestick patterns, users can configure the table to match their specific needs. This makes it a versatile tool suited for various trading styles and objectives, from day trading to swing trading.
Overall Utility
Overall, the "Multi-Timeframe Trend Table" indicator is an invaluable asset for traders who manage multiple instruments across different timeframes, offering a bird's-eye view of the markets in one concise table. It aids in quick decision-making by providing all necessary data points at a glance, reducing the need to switch between multiple charts and potentially missing critical market movements. By integrating trend analysis with volatility and candlestick patterns, it equips traders with a powerful synthesis of technical analysis tools to enhance their trading strategies and improve market timing.
Trend Deviation strategy - BTC [IkkeOmar]Intro:
This is an example if anyone needs a push to get started with making strategies in pine script. This is an example on BTC, obviously it isn't a good strategy, and I wouldn't share my own good strategies because of alpha decay.
This strategy integrates several technical indicators to determine market trends and potential trade setups. These indicators include:
Directional Movement Index (DMI)
Bollinger Bands (BB)
Schaff Trend Cycle (STC)
Moving Average Convergence Divergence (MACD)
Momentum Indicator
Aroon Indicator
Supertrend Indicator
Relative Strength Index (RSI)
Exponential Moving Average (EMA)
Volume Weighted Average Price (VWAP)
It's crucial for you guys to understand the strengths and weaknesses of each indicator and identify synergies between them to improve the strategy's effectiveness.
Indicator Settings:
DMI (Directional Movement Index):
Length: This parameter determines the number of bars used in calculating the DMI. A higher length may provide smoother results but might lag behind the actual price action.
Bollinger Bands:
Length: This parameter specifies the number of bars used to calculate the moving average for the Bollinger Bands. A longer length results in a smoother average but might lag behind the price action.
Multiplier: The multiplier determines the width of the Bollinger Bands. It scales the standard deviation of the price data. A higher multiplier leads to wider bands, indicating increased volatility, while a lower multiplier results in narrower bands, suggesting decreased volatility.
Schaff Trend Cycle (STC):
Length: This parameter defines the length of the STC calculation. A longer length may result in smoother but slower-moving signals.
Fast Length: Specifies the length of the fast moving average component in the STC calculation.
Slow Length: Specifies the length of the slow moving average component in the STC calculation.
MACD (Moving Average Convergence Divergence):
Fast Length: Determines the number of bars used to calculate the fast EMA (Exponential Moving Average) in the MACD.
Slow Length: Specifies the number of bars used to calculate the slow EMA in the MACD.
Signal Length: Defines the number of bars used to calculate the signal line, which is typically an EMA of the MACD line.
Momentum Indicator:
Length: This parameter sets the number of bars over which momentum is calculated. A longer length may provide smoother momentum readings but might lag behind significant price changes.
Aroon Indicator:
Length: Specifies the number of bars over which the Aroon indicator calculates its values. A longer length may result in smoother Aroon readings but might lag behind significant market movements.
Supertrend Indicator:
Trendline Length: Determines the length of the period used in the Supertrend calculation. A longer length results in a smoother trendline but might lag behind recent price changes.
Trendline Factor: Specifies the multiplier used in calculating the trendline. It affects the sensitivity of the indicator to price changes.
RSI (Relative Strength Index):
Length: This parameter sets the number of bars over which RSI calculates its values. A longer length may result in smoother RSI readings but might lag behind significant price changes.
EMA (Exponential Moving Average):
Fast EMA: Specifies the number of bars used to calculate the fast EMA. A shorter period results in a more responsive EMA to recent price changes.
Slow EMA: Determines the number of bars used to calculate the slow EMA. A longer period results in a smoother EMA but might lag behind recent price changes.
VWAP (Volume Weighted Average Price):
Default settings are typically used for VWAP calculations, which consider the volume traded at each price level over a specific period. This indicator provides insights into the average price weighted by trading volume.
backtest range and rules:
You can specify the start date for backtesting purposes.
You can can select the desired trade direction: Long, Short, or Both.
Entry and Exit Conditions:
LONG:
DMI Cross Up: The Directional Movement Index (DMI) indicates a bullish trend when the positive directional movement (+DI) crosses above the negative directional movement (-DI).
Bollinger Bands (BB): The price is below the upper Bollinger Band, indicating a potential reversal from the upper band.
Momentum Indicator: Momentum is positive, suggesting increasing buying pressure.
MACD (Moving Average Convergence Divergence): The MACD line is above the signal line, indicating bullish momentum.
Supertrend Indicator: The Supertrend indicator signals an uptrend.
Schaff Trend Cycle (STC): The STC indicates a bullish trend.
Aroon Indicator: The Aroon indicator signals a bullish trend or crossover.
When all these conditions are met simultaneously, the strategy considers it a favorable opportunity to enter a long trade.
SHORT:
DMI Cross Down: The Directional Movement Index (DMI) indicates a bearish trend when the negative directional movement (-DI) crosses above the positive directional movement (+DI).
Bollinger Bands (BB): The price is above the lower Bollinger Band, suggesting a potential reversal from the lower band.
Momentum Indicator: Momentum is negative, indicating increasing selling pressure.
MACD (Moving Average Convergence Divergence): The MACD line is below the signal line, signaling bearish momentum.
Supertrend Indicator: The Supertrend indicator signals a downtrend.
Schaff Trend Cycle (STC): The STC indicates a bearish trend.
Aroon Indicator: The Aroon indicator signals a bearish trend or crossover.
When all these conditions align, the strategy considers it an opportune moment to enter a short trade.
Disclaimer:
THIS ISN'T AN OPTIMAL STRATEGY AT ALL! It was just an old project from when I started learning pine script!
The backtest doesn't promise the same results in the future, always do both in-sample and out-of-sample testing when backtesting a strategy. And make sure you forward test it as well before implementing it!
Furthermore this strategy uses both trend and mean-reversion systems, that is usually a no-go if you want to build robust trend systems .
Don't hesitate to comment if you have any questions or if you have some good notes for a beginner.
ATR Bands with Optional Risk/Reward Colors█ OVERVIEW
This indicator projects ATR bands and, optionally, colors them based on a risk/reward advantage for those who trade breakouts/breakdowns using moving averages as partial or full exit points.
█ DEFINITIONS
► True Range
The True Range is a measure of the volatility of a financial asset and is defined as the maximum difference among one of the following values:
- The high of the current period minus the low of the current period.
- The absolute value of the high of the current period minus the closing price of the previous period.
- The absolute value of the low of the current period minus the closing price of the previous period.
► Average True Range
The Average True Range was developed by J. Welles Wilder Jr. and was introduced in his 1978 book titled "New Concepts in Technical Trading Systems". It is calculated as an average of the true range values over a certain number of periods (usually 14) and is commonly used to measure volatility and set stop-loss and profit targets (1).
For example, if you are looking at a daily chart and you want to calculate the 14-day ATR, you would take the True Range of the previous 14 days, calculate their average, and this would be the ATR for that day. The process is then repeated every day to obtain a series of ATR values over time.
The ATR can be smoothed using different methods, such as the Simple Moving Average (SMA), the Exponential Moving Average (EMA), or others, depending on the user's preferences or analysis needs.
► ATR Bands
The ATR bands are created by adding or subtracting the ATR from a reference point (usually the closing price). This process generates bands around the central point that expand and contract based on market volatility, allowing traders to assess dynamic support and resistance levels and to adapt their trading strategies to current market conditions.
█ INDICATOR
► ATR Bands
The indicator provides all the essential parameters for calculating the ATR: period length, time frame, smoothing method, and multiplier.
It is then possible to choose the reference point from which to create the bands. The most commonly used reference points are Open, High, Low, and Close, but you can also choose the commonly used candle averages: HL2, HLC3, HLCC4, OHLC4. Among these, there is also a less common "OC2", which represents the average of the candle body. Additionally, two parameters have been specifically created for this indicator: Open/Close and High/Low.
With the "Open/Close" parameter, the upper band is calculated from the higher value between Open and Close, while the lower one is calculated from the lower value between Open and Close. In the case of bullish candles, therefore, the Close value is taken as the starting point for the upper band and the Open value for the lower one; conversely, in bearish candles, the Open value is used for the upper band and the Close value for the lower band. This setting can be useful for precautionally generating broader bands when trading with candlesticks like hammers or inverted hammers.
The "High/Low" parameter calculates the upper band starting from the High and the lower band starting from the Low. Among all the available options, this one allows drawing the widest bands.
Other possible options to improve the drawing of ATR bands, aligning them with the price action, are:
• Doji Smoothing: When the current candle is a doji (having the same Open and Close price), the bands assume the values they had on the previous candle. This can be useful to avoid steep fluctuations of the bands themselves.
• Extend to High/Low: Extends the bands to the High or Low values when they exceed the value of the band.
• Round Last Cent: Expands the upper band by one cent if the price ends with x.x9, and the lower band if the price ends with x.x1. This function only works when the asset's tick is 0.01.
► Risk/Reward Advantage
The indicator optionally colors the ATR bands after setting a breakpoint, one or two risk/reward ratios, and a series of moving averages. This function allows you to know in advance whether entering a trade can provide an advantage over the risk. The band is colored when the ratio between the distance from the break point to the band and the distance from the break point to the first available moving average reaches at least the set ratio value. It is possible to set two colorings, one for a minimum risk/reward ratio and one for an optimal risk/reward ratio.
The break point can be chosen between High/Low (High in case of breakout, Low in case of breakdown) or Open/Close (on breakouts, Close with bullish candles or Open with bearish candles; on breakdowns, Close with bearish candles or Open with bullish candles).
It is possible to choose up to 10 moving averages of various types, including the VWAP with the Anchor Period (2).
Depending on the "Price to MA" setting, the bands can be individually or simultaneously colored.
By selecting "Single Direction," the risk/reward calculation is performed only when all moving averages are above or below the break point, resulting in only one band being colored at a time. For this reason, when the break point is in between the moving averages, the calculation is not executed. This setting can be useful for strategies involving price movement from a level towards a series of specific moving averages (for example, in reversals starting from a certain level towards the VWAP with possible partial take profits on some previous moving averages, or simply in trend following towards one or more moving averages).
Choosing "Both Directions" the risk/reward ratio is calculated based on the first available moving averages both above and below the price. This setting is useful for those who operate in range bound markets or simply take advantage of movements between moving averages.
█ NOTE
This script may not be suitable for scalping strategies that require immediate entries due to the inability to know the ATR of a candle in advance until its closure. Once the candle is closed, you should have time to place a stop or stop-limit order, so your strategy should not anticipate an immediate start with the next candle. Even more conveniently, if your strategy involves an entry on a pullback, you can place a limit order at the breakout level.
(1) www.tradingview.com
(2) For convenience, the code for the Anchor Period has been entirely copied from the VWAP code provided by TradingView.
Market Internals (TICK, ADD, VOLD, TRIN, VIX)OVERVIEW
This script allows you to perform data transformations on Market Internals, across exchanges, and specify signal parameters, to more easily identify sentiment extremes.
Notable transformations include:
1. Cumulative session values
2. Directional bull-bear Ratios and Percent Differences
3. Data Normalization
4. Noise Reduction
This kind of data interaction is very useful for understanding the relationship between two mutually exclusive metrics, which is the essence of Market Internals: Up vs. Down. Even so, they are not possible with symbol expressions alone. And the kind of symbol expression needed to produce baseline data that can be reliably transformed is opaque to most traders, made worse by the fact that prerequisite symbol expressions themselves are not uniform across symbols. It's very nuanced, and if this last bit was confusing … exactly.
All this to say, rather than forcing that burden onto you, I've baked the baseline symbol expressions into the indicator so: 1) the transform functions consistently ingest the baseline data in the correct format and 2) you don't have to spend time trying to figure it all out. Trading is hard. There's no need to make it harder.
INPUTS
Indicator
Allows you to specify the base Market Internal and Exchange data to use. The list of Market Internals is simplified to their fundamental representation (TICK, ADD, VOLD, TRIN, VIX, ABVD, TKCD), and the list of Exchange data is limited to the most common (NYSE, NASDAQ, All US Stocks). There are also options for basic exchange combinations (Sum or Average of NYSE & NASDAQ).
Mode
Short for "Plot Mode", this is where you specify the bars style (Candles, Bars, Line, Circles, Columns) and the source value (used for single value plots and plot color changes).
Scale
This is the first and second data transformation grouped together. The default is to show the origin data as it might appear on a chart. You can then specify if each bar should retain it's unique value (Bar Value) or be added to a running total (Cumulative). You can also specify if you would like the data to remain unaltered (Raw) or converted to a directional ratio (Ratio) or a percentage (Percent Diff). These options determine the scale of the plot.
Both Ratio and Percent Diff. convert a given symbol into a positive or negative number, where positive numbers are bullish and negative numbers are bearish.
Ratio will divide Bull values by Bear values, then further divide -1 by the quotient if it is less than 1. For example, if "0.5" was the quotient, the Ratio would be "-2".
Percent Diff. subtracts Bear values from Bull values, then divides that difference by the sum of Bull and Bear values multiplied by 100. If a Bull value was "3" and Bear value was "7", the difference would be "-4", the sum would be "10", and the Percent Diff. would be "-40", as the difference is both bearish and 40% of total.
Ratio Norm. Threshold
This is the third data transformation . While quotients can be less than 1, directional ratios are never less than 1. This can lead to barcode-like artifacts as plots transition between positive and negative values, visually suggesting the change is much larger than it actually is. Normalizing the data can resolve this artifact, but undermines the utility of ratios. If, however, only some of the data is normalized, the artifact can be resolved without jeopardizing its contextual usefulness.
The utility of ratios is how quickly they communicate proportional differences. For example, if one side is twice as big as the other, "2" communicates this efficiently. This necessarily means the numerical value of ratios is worth preserving. Also, below a certain threshold, the utility of ratios is diminished. For example, an equal distribution being represented as 0, 1, 1:1, 50/50, etc. are all equally useful. Thus, there is a threshold, above which we want values to be exact, and below which the utility of linear visual continuity is more important. This setting accounts for that threshold.
When this setting is enabled, a ratio will be normalized to 0 when 1:1, scaled linearly toward the specified threshold when greater than 1:1, and then retain its exact value when the threshold is crossed. For example, with a threshold of "2", 1:1 = 0, 1.5:1 = 1, 2:1 = 2, 3:1 = 3, etc.
With all this in mind, most traders will want to set the ratios threshold at a level where accuracy becomes more important than visual continuity. If this level is unknown, "2" is a good baseline.
Reset cumulative total with each new session
Cumulative totals can be retained indefinitely or be reset each session. When enabled, each session has its own cumulative total. When disabled, the cumulative total is maintained indefinitely.
Show Signal Ranges
Because everything in this script is designed to make identifying sentiment extremes easier, an obvious inclusion would be to not only display ranges that are considered extreme for each Market Internal, but to also change the color of the plot when it is within, or beyond, that range. That is exactly what this setting does.
Override Max & Min
While the min-max signal levels have reasonable defaults for each symbol and transformation type, the Override Max and Override Min options allow you to … (wait for it) … override the max … and min … signal levels. This may be useful should you find a different level to be more suitable for your exact configuration.
Reduce Noise
This is the fourth data transformation . While the previous Ratio Norm. Threshold linearly stretches values between a threshold and 0, this setting will exponentially squash values closer to 0 if below the lower signal level.
The purpose of this is to compress data below the signal range, then amplify it as it approaches the signal level. If we are trying to identify extremes (the signal), minimizing values that are not extreme (the noise) can help us visually focus on what matters.
Always keep both signal zones visible
Some traders like to zoom in close to the bars. Others prefer to keep a wider focus. For those that like to zoom in, if both signals were always visible, the bar values can appear squashed and difficult to discern. For those that keep a wider focus, if both signals were not always visible, it's possible to lose context if a signal zone is vertically beyond the pane. This setting allows you to decide which scenario is best for you.
Plot Colors
These define the default color, within signal color, and beyond signal color for Bullish and Bearish directions.
Plot colors should be relative to zero
When enabled, the plot will inherit Bullish colors when above zero and Bearish colors when below zero. When disabled and Directional Colors are enabled (below), the plot will inherit the default Bullish color when rising, and the default Bearish color when falling. Otherwise, the plot will use the default Bullish color for all directions.
Directional colors
When the plot colors should be relative to zero (above), this changes the opacity of a bars color if moving toward zero, where "100" percent is the full value of the original color and "0" is transparent. When the plot colors are NOT relative to zero, the plot will inherit Bullish colors when rising and Bearish colors when falling.
Differentiate RTH from ETH
Market Internal data is typically only available during regular trading hours. When this setting is enabled, the background color of the indicator will change as a reminder that data is not available outside regular trading hours (RTH), if the chart is showing electronic trading hours (ETH).
Show zero line
Similar to always keeping signal zones visible (further up), some traders prefer zooming in while others prefer a wider context. This setting allows you to specify the visibility of the zero line to best suit your trading style.
Linear Regression
Polynomial regressions are great for capturing non-linear patterns in data. TradingView offers a "linear regression curve", which this script is using as a substitute. If you're unfamiliar with either term, think of this like a better moving average.
Symbol
While the Market Internal symbol will display in the status line of the indicator, the status line can be small and require more than a quick glance to read properly. Enabling this setting allows you to specify if / where / how the symbol should display on the indicator to make distinguishing between Market Internals more efficient.
Speaking of symbols, this indicator is designed for, and limited to, the following …
TICK - The TICK subtracts the total number of stocks making a downtick from the total number of stocks making an uptick.
ADD - The Advance Decline Difference subtracts the total number of stocks below yesterdays close from the total number of stocks above yesterdays close.
VOLD - The Volume Difference subtracts the total declining volume from the total advancing volume.
TRIN - The Arms Index (aka. Trading Index) divides the ratio of Advancing Stocks / Volume by the ratio of Declining Stocks / Volume. Given the inverse correlation of this index to market movement, when transforming it to a Ratio or Percent Diff., its values are inverted to preserve the bull-bear sentiment of the transformations.
VIX - The CBOE Volatility Index is derived from SPX index option prices, generating a 30-day forward projection of volatility. Given the inverse correlation of this index to market movement, when transforming it to a Ratio or Percent Diff., its values are inverted and normalized to the sessions first bar to preserve the bull-bear sentiment of the transformations. Note: If you do not have a Cboe CGIF subscription , VIX data will be delayed and plot unexpectedly.
ABVD - The Above VWAP Difference is an unofficial index measuring all stocks above VWAP as a percent difference. For the purposes of this indicator (and brevity), TradingViews PCTABOVEVWAP has has been shortened to simply be ABVD.
TKCD - The Tick Cumulative Difference is an unofficial index that subtracts the total number of market downticks from the total number of market upticks. Where "the TICK" (further up) is a measurement of stocks ticking up and down, TKCD is a measurement of the ticks themselves. For the purposes of this indicator (and brevity), TradingViews UPTKS and DNTKS symbols have been shorted to simply be TKCD.
INSPIRATION
I recently made an indicator automatically identifying / drawing daily percentage levels , based on 4 assumptions. One of these assumptions is about trend days. While trend days do not represent the majority of days, they can have big moves worth understanding, for both capitalization and risk mitigation.
To this end, I discovered:
• Article by Linda Bradford Raschke about Capturing Trend Days.
• Video of Garrett Drinon about Trend Day Trading.
• Videos of Ryan Trost about How To Use ADD and TICK.
• Article by Jason Ruchel about Overview of Key Market Internals.
• Including links to resources outside of TradingView violates the House Rules, but they're not hard to find, if interested.
These discoveries inspired me adopt the underlying symbols in my own trading. I also found myself wanting to make using them easier, the net result being this script.
While coding everything, I also discovered a few symbols I believe warrant serious consideration. Specifically the Percent Above VWAP symbols and the Up Ticks / Down Ticks symbols (referenced as ABVD and TKCD in this indicator, for brevity). I found transforming ABVD or TKCD into a Ratio or Percent Diff. to be an incredibly useful and worthy inclusion.
ABVD is a Market Breadth cousin to Brian Shannon's work, and TKCD is like the 3rd dimension of the TICKs geometry. Enjoy.
Buying Selling Volume StrategyFirst I would like to give the original credit and thanks to @ceyhun for his amazing volume script.
The way I decided to convert it into a strategy is divided into multiple types.
First, I decided in order to smooth out the values and make it more accurate to adapt the values to multiple timeframes.
After that I took the initial values from the buyers and sellers , and made a rest operation between them to have a flat difference between the power of both sides.
WIth that later on I decided to to apply a volatility filter,in this case bollinger bands, in order to find out potential leading trends.
At the same time in order to filter even more, I decided to make use as well for weekly VWAP values of the asset used.
Lastly I added a dynamic risk management into it , based on the ATR Daily values of the asset values.
As for the rules used, for example for long, I am looking that the price of the asset is above the weekly VWAP, after that I am checking that the MTF volume rest operation is both bullish and above the upper side of the bollinger.
For short we would want the asset to be below the weekly VWAP, and the volume to be bearish and above the upper side of bollinger.
The exit is either based on daily ATR values multipliers, or if we have a reverse condition.
If you have any questions, please let me know !
Range Analysis - By LeviathanThe Interactive Range Analysis script is an essential tool for analyzing price ranges. It automatically draws important range levels, generates a Volume Profile or Open Interest profile and horizontal/vertical heatmaps, plots the anchored VWAP, draws Fibonacci levels, and much more.
How to use the indicator:
1. The script will prompt you to select the "Start Time" and "End Time" using Tradingview's interactive interface. These two points will determine the length of the range.
2. Once you have selected the range, the script will automatically anchor the range highs and lows to the highest and lowest close/wick/hlc3/ohlc4 (whichever you prefer).
3. You can then begin exploring different tools and options such as Quarters, Eighths, Fibonacci, Outer Levels, VWAP, Horizontal Volume/OI Heatmap, Vertical Volume/OI Heatmap, Fixed Range Volume Profile, Open Interest Profile, Value Area, VAH, VAL, and POC.
4. You can adjust the range by dragging the Start Time and End Time anchors or by removing/reapplying the script.
Tool overview
Range Levels
After selecting your preferred time range, the script will identify and draw a range high level and a range low level, which serve as a base for other important levels. “Half” is the level halfway between the range high and range low. “Quarters” will, as the name suggests, split the range into four equal zones (quarters) and “Eighths” will split the range into eight equal zones (eighths).
”Fibonacci” option allows you to display Fibonacci retracement levels (0.786, 0.618, 0.382, 0.236). “VWAP” will plot a Volume Weighted Average Price, anchored to the start of the range. “Direction” input lets you choose whether your range is UP or DOWN trending in order to make sure that the Fibonacci levels and labels are generated and assigned correctly. With “Outer” turned ON, the script will also generate active levels (quarters/eighths/Fibonacci) above and below the selected price range. “Extend Right” will extend all levels to the right indefinitely, while “Extend (+Bars)” lets you choose how far right the levels get extended. “Diagonal Line” is drawn from the bottom left of the range to the top right of the range or from the top left of the range to the bottom right of the range, depending on the “Direction” input.
Volume Profile / Open Interest Profile
After selecting the “Data Type”, Volume Profile or OI Profile can be generated by turning ON the “Volume/OI Profile” option.
“Resolution” input defines the amount of nodes/rows in the range that are used in profile/heatmap generation for distributing the data. While you can increase the “Resolution” to get better, more granular profiles, you should keep in mind that you might need to lower the resolution when generating profiles for larger ranges.
”Node Type” offers you two options when it comes to the representation of data: Up/Down - divides a node in two sections for up volume/OI and down volume/OI, Total - one node for total volume/OI and Delta - net difference in up volume/OI and down volume/OI.
”Profile Position” lets you choose whether the profile is positioned on the left side of the range or on the right side of the range.
“Profile Direction” determines whether the profile nodes are facing right or left.
“Profile Type” enables you to visualize the nodes in a classic way (Type 1) or in a way where down volume/negative OI are positioned on the left side of the y axis and up volume/positive OI on the right side of the y axis.
“Node Size (%)” defines how much space in the range can be taken by the profile’s nodes. Eg. 50% will allow the largest node to extend to the middle of the range (and others scaled accordingly), 100% will allow the largest node to extend the max right point of the range (and others scaled accordingly).
”Value Area (%)” defines the VA zone, which represents the area where the most volume occured (usually 70% or 68%).
”Horizontal Heatmap” will display a heatmap-like overlay, that will help you identify the price levels where most volume/open interest action occurred.
”Vertical Heatmap” will display a heatmap-like overlay, that will help you identify the points in time where most volume/open interest action occurred.
A more detailed description of this indicator is coming in the next few days.
Important:
* If volume or OI profile does not get generated, try lowering the resolution.
* Once in a while, the script will disappear from your chart. Just remove and reapply.
* Open Interest data is only avaiable on Binance Perpetual Futures pairs
To learn more, read the tooltips in the indicator’s settings and stay tuned for upcoming additions (Range Market Structure, Liquidation Levels, Range Statistics,…)
Big Poppa Code Strat & Momentum Strategy IndicatorThis indicator is a combination of a few things in order to work with a unique trading style gleaned from Callme100k, jrgreatness, TrustMyLevels , FaithInTheStrat, Rob Smith and Saty Mahajan.
This Indicator is created to help you day trade using, ATR Fibonacci Levels, Price Action and Momentum.
It displays Fibonacci Levels Based on ATR to indicate when a security is 0.236, 0.382 +- the Days Open, +- the Days Open, 0.618 +- the Days Open and 1.0 +- Days Open.
To understand this script you need to understand
Average True Range (ATR)
1 Bar Inside Bar
2 Bar Outside Bar (Break either the top or bottom)
3 Bar Engulfing Bar
Strat Setups - 212, 322, 312
Fibonacci - 0.236, 0.382, 0.618, 1.0
Moving Averages
A Trend is considered bullish when (green)
Current Price is greater than the Fast EMA Value (8)
Fast EMA is greater than PIVOT EMA Value (21)
Pivot EMA is greater than SLOW EMA Value (34)
OR Hull is trending up and the Price is above the Volume Weighted Moving Average and price is above VWAP
A trend is considered Bearish when (red)
Current Price is less than the Fast EMA Value (8)
Fast EMA is less than PIVOT EMA Value (21)
Pivot EMA is less than SLOW EMA Value (34)
OR Hull is trending down and the Price is below the Volume Weighted Moving Average and price is below VWAP
If these conditions are not met then the Momentum is in Conflict (orange)
The Momentum band will match the color of the current trend
The table that is present can be turned off at any time lets you see
1) If Moving Averages are showing bullish, bearish or in conflict
2) If There us Time Frame Continuity, (if 5 min up, are all the other timeframes up also)
3) How much of the ATR have we moved on the day
4) Are we in Call or Put range for the day based on ATR Fib Levels
The Ideal situation for entering a call
1) Momentum is Green
2) FTFC on Green
3) A Strat Actionable Signal is present
4) You are in the call range, 0.236 - 0.618 ATR + the Price
5) The ATR still has room, I.e only 50% of the ATR has been run already
Ideal situation from entering a put
1) Momentum is red
2) FTFC on Red
3) A Strat Actionable Signal is present
4) You are in the put range, 0.236 - 0.618 ATR - the Price
5) The ATR still has room, I.e only 50% of the ATR has been run already
Exit the trade for these reasons you entered (for profit or loss)
1) ATR has no more room
2) FTFC is now in conflict
3) Momentum has shifted
Take Profit when
1) You reach a new ATR Level 0.618, 1.0 , -0.618, -1, etc
Passive Stop Loss
1) Open Price if you are aggressive
2) Next ATR Level Down or Up
Feel free to take profit and leave runners
This script does not give signals, you should do your own research, I am not a financial advisors, I am simply applying principles of seasoned veterans to code. You make all decisions about how you buy, sell and trade. The creator of this script makes no promises and takes no responsibility for your personal trading.
To research the methods described above look up
Rob Smith : The Strat
Saty Mahajan : ATR Levels
Fibonacci
Using the HULL Moving Average
Exponential Moving Averages
VWAP
VWMA
TurntLibraryLibrary "TurntLibrary"
Collection of functions created for simplification/easy referencing. Includes variations of moving averages, length value oscillators, and a few other simple functions based upon HH/LL values.
ma(source, length, type)
Apply a moving average to a float value
Parameters:
source : Value to be used
length : Number of bars to include in calculation
type : Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
Returns: Smoothed value of initial float value
curve(src, len, lb1, lb2)
Exaggerates curves of a float value designed for use as an exit signal.
Parameters:
src : Initial value to curve
len : Number of bars to include in calculation
lb1 : (Default = 1) First lookback length
lb2 : (Default = 2) Second lookback length
Returns: Curved Average
fragma(src, len, space, str)
Average of a moving average and the previous value of the moving average
Parameters:
src : Initial float value to use
len : Number of bars to include in calculation
space : Lookback integer for second half of average
str : Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
Returns: Fragmented Average
maxmin(x, y)
Difference of 2 float values, subtracting the lowest from the highest
Parameters:
x : Value 1
y : Value 2
Returns: The +Difference between 2 float values
oscLen(val, type)
Variable Length using a oscillator value and a corresponding slope shape ("Incline",Decline","Peak","Trough")
Parameters:
val : Oscillator Value to use
type : Slope of length curve ("Incline",Decline","Peak","Trough")
Returns: Variable Length Integer
hlAverage(val, smooth, max, min, type, include)
Average of HH,LL with variable lengths based on the slope shape ("Incline","Decline","Trough") value relative to highest and lowest
Parameters:
val : Source Value to use
smooth
max
min
type
include : Add "val" to the averaging process, instead of more weight to highest or lowest value
Returns: Variable Length Average of Highest Lowest "val"
pct(val)
Convert a positive float / price to a percentage of it's highest value on record
Parameters:
val : Value To convert to a percentage of it's highest value ever
Returns: Percentage
hlrange(x, len)
Difference between Highest High and Lowest Low of float value
Parameters:
x : Value to use in calculation
len : Number of bars to include in calculation
Returns: Difference
midpoint(x, len, smooth)
The average value of the float's Highest High and Lowest Low in a number of bars
Parameters:
x : Value to use in calculation
len
smooth : (Default=na) Optional smoothing type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
Returns: Midpoint
Physics CandlesPhysics Candles embed volume and motion physics directly onto price candles or market internals according to the cyclic pattern of financial securities. The indicator works on both real-time “ticks” and historical data using statistical modeling to highlight when these values, like volume or momentum, is unusual or relatively high for some periodic window in time. Each candle is made out of one or more sub-candles that each contain their own information of motion, which converts to the color and transparency, or brightness, of that particular candle segment. The segments extend throughout the entire candle, both body and wicks, and Thick Wicks can be implemented to see the color coding better. This candle segmentation allows you to see if all the volume or energy is evenly distributed throughout the candle or highly contained in one small portion of it, and how intense these values are compared to similar time periods without going to lower time frames. Candle segmentation can also change a trader’s perspective on how valuable the information is. A “low” volume candle, for instance, could signify high value short-term stopping volume if the volume is all concentrated in one segment.
The Candles are flexible. The physics information embedded on the candles need not be from the same price security or market internal as the chart when using the Physics Source option, and multiple Candles can be overlayed together. You could embed stock price Candles with market volume, market price Candles with stock momentum, market structure with internal acceleration, stock price with stock force, etc. My particular use case is scalping the SPX futures market (ES), whose price action is also dictated by the volume action in the associated cash market, or SPY, as well as a host of other securities. Physics allows you to embed the ES volume on the SPY price action, or the SPY volume on the ES price action, or you can combine them both by overlaying two Candle streams and increasing the Number of Overlays option to two. That option decreases the transparency levels of your coloring scheme so that overlaying multiple Candles converges toward the same visual color intensity as if you had one. The Candle and Physics Sources allows for both Symbols and Spreads to visualize Candle physics from a single ticker or some mathematical transformation of tickers.
Due to certain TradingView programming restrictions, each Candle can only be made out of a maximum of 8 candle segments, or an “8-bit” resolution. Since limits are just an opportunity to go beyond, the user has the option to stack multiple Candle indicators together to further increase the candle resolution. If you don’t want to see the Candles for some particular period of the day, you can hide them, or use the hiding feature to have multiple Candles calibrated to show multiple parts of the trading day. Securities tend to have low volume after hours with sharp spikes at the open or close. Multiple Candles can be used for multiple parts of the trading day to accommodate these different cycles in volume.
The Candles do not need be associated with the nominal security listed on the TV chart. The Candle Source allows the user to look at AAPL Candles, for instance, while on a TSLA or SPY chart, each with their respective volume actions integrated into the candles, for instance, to allow the user to see multiple security price and volume correlation on a single chart.
The physics information currently embeddable on Candles are volume or time, velocity, momentum, acceleration, force, and kinetic energy. In order to apply equations of motion containing a mass variable to financial securities, some analogous value for mass must be assumed. Traders often regard volume or time as inextricable variables to a securities price that can indicate the direction and strength of a move. Since mass is the inextricable variable to calculating the momentum, force, or kinetic energy of motion, the user has the option to assume either time or volume is analogous to mass. Volume may be a better option for mass as it is not strictly dependent on the speed of a security, whereas time is.
Data transformations and outlier statistics are used to color code the intensity of the physics for each candle segment relative to past periodic behavior. A million shares during pre-market or a million shares during noontime may be more intense signals than a typical million shares traded at the open, and should have more intense color signals. To account for a specific cyclic behavior in the market, the user can specify the Window and Cycle Time Frames. The Window Time Frame splits up a Cycle into windows, samples and aggregates the statistics for each window, then compares the current physics values against past values in the same window. Intraday traders may benefit from using a Daily Cycle with a 30-minute Window Time Frame and 1-minute Sample Time Frame. These settings sample and compare the physics of 1-minute candles within the current 30-minute window to the same 30-minute window statistics for all past trading days, up until the data limit imposed by TradingView, or until the Data Collection Start Date specified in the settings. Longer-term traders may benefit from using a Monthly Cycle with a Weekly Time Frame, or a Yearly Cycle with a Quarterly Time Frame.
Multiple statistics and data transformation methods are available to convey relative intensity in different ways for different trading signals. Physics Candles allows for both Normal and Log-Normal assumptions in the physics distribution. The data can then be transformed by Linear, Logarithmic, Z-Score, or Power-Law scoring, where scoring simply assigns an intensity to the relative physics value of each candle segment based on some mathematical transformation. Z-scoring often renders adequate detection by scoring the segment value, such as volume or momentum, according to the mean and standard deviation of the data set in each window of the cycle. Logarithmic or power-law transformation with a gamma below 1 decreases the disparity between intensities so more less-important signals will show up, whereas the power-law transformation with gamma values above 1 increases the disparity between intensities, so less more-important signals will show up. These scores are then converted to color and transparency between the Min Score and the Max Score Cutoffs. The Auto-Normalization feature can automatically pick these cutoffs specific to each window based on the mean and standard deviation of the data set, or the user can manually set them. Physics was developed with novices in mind so that most users could calibrate their own settings by plotting the candle segment distributions directly on the chart and fiddling with the settings to see how different cutoffs capture different portions of the distribution and affect the relative color intensities differently. Security distributions are often skewed with fat-tails, known as kurtosis, where high-volume segments for example, have a higher-probabilities than expected for a normal distribution. These distribution are really log-normal, so that taking the logarithm leads to a standard bell-shaped distribution. Taking the Z-score of the Log-Normal distribution could make the most statistical sense, but color sensitivity is a discretionary preference.
Background Philosophy
This indicator was developed to study and trade the physics of motion in financial securities from a visually intuitive perspective. Newton’s laws of motion are loosely applied to financial motion:
“A body remains at rest, or in motion at a constant speed in a straight line, unless acted upon by a force”.
Financial securities remain at rest, or in motion at constant speed up or down, unless acted upon by the force of traders exchanging securities.
“When a body is acted upon by a force, the time rate of change of its momentum equals the force”.
Momentum is the product of mass and velocity, and force is the product of mass and acceleration. Traders render force on the security through the mass of their trading activity and the acceleration of price movement.
“If two bodies exert forces on each other, these forces have the same magnitude but opposite directions.”
Force arises from the interaction of traders, buyers and sellers. One body of motion, traders’ capitalization, exerts an equal and opposite force on another body of motion, the financial security. A securities movement arises at the expense of a buyer or seller’s capitalization.
Volume
The premise of this indicator assumes that volume, v, is an analogous means of measuring physical mass, m. This premise allows the application of the equations of motion to the movement of financial securities. We know from E=mc^2 that mass has energy. Energy can be used to create motion as kinetic energy. Taking a simple hypothetical example, the interaction of one short seller looking to cover lower and one buyer looking to sell higher exchange shares in a security at an agreed upon price to create volume or mass, and therefore, potential energy. Eventually the short seller will actively cover and buy the security from the previous buyer, moving the security higher, or the buyer will actively sell to the short seller, moving the security lower. The potential energy inherent in the initial consolidation or trading activity between buy and seller is now converted to kinetic energy on the subsequent trading activity that moves the securities price. The more potential energy that is created in the consolidation, the more kinetic energy there is to move price. This is why point and figure traders are said to give price targets based on the level of volatility or size of a consolidation range, or why Gann traders square price and time, as time is roughly proportional to mass and trading activity. The build-up of potential energy between short sellers and buyers in GME or TSLA led to their explosive moves beyond their standard fundamental valuations.
Position
Position, p, is simply the price or value of a financial security or market internal.
Time
Time, t, is another means of measuring mass to discover price behavior beyond the time snapshots that simple candle charts provide. We know from E=mc^2 that time is related to rest mass and energy given the speed of light, c, where time ≈ distance * sqrt(mass/E). This relation can also be derived from F=ma. The more mass there is, the longer it takes to compute the physics of a system. The more energy there is, the shorter it takes to compute the physics of a system. Similarly, more time is required to build a “resting” low-volatility trading consolidation with more mass. More energy added to that trading consolidation by competing buyers and sellers decreases the time it takes to build that same mass. Time is also related to price through velocity.
Velocity = (p(t1) – p(t0)) / p(t0)
Velocity, v, is the relative percent change of a securities price, p, over a period of time, t0 to t1. The period of time is between subsequent candles, and since time is constant between candles within the same timeframe, it is not used to calculate velocity or acceleration. Price moves faster with higher velocity, and slower with slower velocity, over the same fixed period of time. The product of velocity and mass gives momentum.
Momentum = mv
This indicator uses physics definition of momentum, not finance’s. In finance, momentum is defined as the amount of change in a securities price, either relative or absolute. This is definition is unfortunate, pun intended, since a one dollar move in a security from a thousand shares traded between a few traders has the exact same “momentum” as a one dollar move from millions of shares traded between hundreds of traders with everything else equal. If momentum is related to the energy of the move, momentum should consider both the level of activity in a price move, and the amount of that price move. If we equate mass to volume to account for the level of trading activity and use physics definition of momentum as the product of mass and velocity, this revised definition now gives a thousand-times more momentum to a one-dollar price move that has a thousand-times more volume behind it. If you want to use finance’s volume-less definition of momentum, use velocity in this indicator.
Acceleration = v(t1) – v(t0)
Acceleration, a, is the difference between velocities over some period of time, t0 to t1. Positive acceleration is necessary to increase a securities speed in the positive direction, while negative acceleration is necessary to decrease it. Acceleration is related to force by mass.
Force = ma
Force is required to change the speed of a securities valuation. Price movements with considerable force have considerably more impact on future direction. A change in direction requires force.
Kinetic Energy = 0.5mv^2
Kinetic energy is the energy that a financial security gains from the change in its velocity by force. The built-up of potential energy in trading consolidations can be converted to kinetic energy on a breakout from the consolidation.
Cycle Theory and Relativity
Just as the physics of motion is relative to a point of reference, so too should the physics of financial securities be relative to a point of reference. An object moving at a 100 mph towards another object moving in the same direction at 100 mph will not appear to be moving relative to each other, nor will they collide, but from an outsider observer, the objects are going 100 mph and will collide with significant impact if they run into a stationary object relative to the observer. Similarly, trading with a hundred thousand shares at the open when the average volume is a couple million may have a much smaller impact on the price compared to trading a hundred thousand shares pre-market when the average volume is ten thousand shares. The point of reference used in this indicator is the average statistics collected for a given Window Time Frame for every Cycle Time Frame. The physics values are normalized relative to these statistics.
Examples
The main chart of this publication shows the Force Candles for the SPY. An intense force candle is observed pre-market that implicates the directional overtone of the day. The assumption that direction should follow force arises from physical observation. If a large object is accelerating intensely in a particular direction, it may be fair to assume that the object continues its direction for the time being unless acted upon by another force.
The second example shows a similar Force Candle for the SPY that counters the assumption made in the first example and emphasizes the importance of both motion and context. While it’s fair to assume that a heavy highly accelerating object should continue its course, if that object runs into an obstacle, say a brick wall, it’s course may deviate. This example shows SPY running into the 50% retracement wall from the low of Mar 2020, a significant support level noted in literature. The example also conveys Gann’s idea of “lost motion”, where the SPY penetrated the 50% price but did not break through it. A brick wall is not one atom thick and price support is not one tick thick. An object can penetrate only one layer of a wall and not go through it.
The third example shows how Volume Candles can be used to identify scalping opportunities on the SPY and conveys why price behavior is as important as motion and context. It doesn’t take a brick wall to impede direction if you know that the person driving the car tends to forget to feed the cats before they leave. In the chart below, the SPY breaks down to a confluence of the 5-day SMA, 20-day SMA, and an important daily trendline (not shown) after the bullish bounce from the 50% retracement days earlier. High volume candles on the SMA signify stopping volume that reverse price direction. The character of the day changes. Bulls become more aggressive than bears with higher volume on upswings and resistance, whiles bears take on a defensive position with lower volume on downswings and support. High volume stopping candles are seen after rallies, and can tell you when to take profit, get out of a position, or go short. The character change can indicate that its relatively safe to re-enter bullish positions on many major supports, especially given the overarching bullish theme from the large reaction off the 50% retracement level.
The last example emphasizes the importance of relativity. The Volume Candles in the chart below are brightest pre-market even though the open has much higher volume since the pre-market activity is much higher compared to past pre-markets than the open is compared to past opens. Pre-market behavior is a good indicator for the character of the day. These bullish Volume Candles are some of the brightest seen since the bounce off the 50% retracement and indicates that bulls are making a relatively greater attempt to bring the SPY higher at the start of the day.
Infrequently Asked Questions
Where do I start?
The default settings are what I use to scalp the SPY throughout most of the extended trading day, on a one-minute chart using SPY volume. I also overlay another Candle set containing ES future volume on the SPY price structure by setting the Physics Source to ES1! and the Number of Overlays setting to 2 for each Candle stream in order to account for pre- and post-market trading activity better. Since the closing volume is exponential-like up until the end of the regular trading day, adding additional Candle streams with a tighter Window Time Frame (e.g., 2-5 minute) in the last 15 minutes of trading can be beneficial. The Hide feature can allow you to set certain intraday timeframes to hide one Candle set in order to show another Candle set during that time.
How crazy can you get with this indicator?
I hope you can answer this question better. One interesting use case is embedding the velocity of market volume onto an internal market structure. The PCTABOVEVWAP.US is a market statistic that indicates the percent of securities above their VWAP among US stocks and is helpful for determining short term trends in the US market. When securities are rising above their VWAP, the average long is up on the day and a rising PCTABOVEVWAP.US can be viewed as more bullish. When securities are falling below their VWAP, the average short is up on the day and a falling PCTABOVEVWAP.US can be viewed as more bearish. (UPVOL.US - DNVOL.US) / TVOL.US is a “spread” symbol, in TV parlance, that indicates the decimal percent difference between advancing volume and declining volume in the US market, showing the relative flow of volume between stocks that are up on the day, and stocks that are down on the day. Setting PCTABOVEVWAP.US in the Candle Source, (UPVOL.US - DNVOL.US) / TVOL.US in the Physics Source, and selecting the Physics to Velocity will embed the relative velocity of the spread symbol onto the PCTABOVEVWAP.US candles. This can be helpful in seeing short term trends in the US market that have an increasing amount of volume behind them compared to other trends. The chart below shows Volume Candles (top) and these Spread Candles (bottom). The first top at 9:30 and second top at 10:30, the high of the day, break down when the spread candles light up, showing a high velocity volume transfer from up stocks to down stocks.
How do I plot the indicator distribution and why should I even care?
The distribution is visually helpful in seeing how different normalization settings effect the distribution of candle segments. It is also helpful in seeing what physics intensities you want to ignore or show by segmenting part of the distribution within the Min and Max Cutoff values. The intensity of color is proportional to the physics value between the Min and Max Cutoff values, which correspond to the Min and Max Colors in your color scheme. Any physics value outside these Min and Max Cutoffs will be the same as the Min and Max Colors.
Select the Print Windows feature to show the window numbers according to the Cycle Time Frame and Window Time Frame settings. The window numbers are labeled at the start of each window and are candle width in size, so you may need to zoom into to see them. Selecting the Plot Window feature and input the window number of interest to shows the distribution of physics values for that particular window along with some statistics.
A log-normal volume distribution of segmented z-scores is shown below for 30-minute opening of the SPY. The Min and Max Cutoff at the top of the graph contain the part of the distribution whose intensities will be linearly color-coded between the Min and Max Colors of the color scheme. The part of the distribution below the Min Cutoff will be treated as lowest quality signals and set to the Min Color, while the few segments above the Max Cutoff will be treated as the highest quality signals and set to the Max Color.
What do I do if I don’t see anything?
Troubleshooting issues with this indicator can involve checking for error messages shown near the indicator name on the chart or using the Data Validation section to evaluate the statistics and normalization cutoffs. For example, if the Plot Window number is set to a window number that doesn’t exist, an error message will tell you and you won’t see any candles. You can use the Print Windows option to show windows that do exist for you current settings. The auto-normalization cutoff values may be inappropriate for your particular use case and literally cut the candles out of the chart. Try changing the chart time frame to see if they are appropriate for your cycle, sample and window time frames. If you get a “Timeframe passed to the request.security_lower_tf() function must be lower than the timeframe of the main chart” error, this means that the chart timeframe should be increased above the sample time frame. If you get a “Symbol resolve error”, ensure that you have correct symbol or spread in the Candle or Physics Source.
How do I see a relative physics values without cycles?
Set the Window Time Frame to be equal to the Cycle Time Frame. This will aggregate all the statistics into one bucket and show the physics values, such as volume, relative to all the past volumes that TV will allow.
How do I see candles without segmentation?
Segmentation can be very helpful in one context or annoying in another. Segmentation can be removed by setting the candle resolution value to 1.
Notes
I have yet to find a trading platform that consistently provides accurate real-time volume and pricing information, lacking adequate end-user data validation or quality control. I can provide plenty of examples of real-time volume counts or prices provided by TradingView and other platforms that were significantly off from what they should have been when comparing against the exchanges own data, and later retroactively corrected or not corrected at all. Since no indicator can work accurately with inaccurate data, please use at your own discretion.
The first version is a beta version. Debugging and validating code in Pine script is difficult without proper unit testing. Please report any bugs with enough information to reproduce them and indicate why they are important. I also encourage you to export the data from TradingView and verify the calculations for your particular use case.
The indicator works on real-time updates that occur at a higher frequency than the candle time frame, which TV incorrectly refers to as ticks. They use this terminology inaccurately as updates are really aggregated tick data that can take place at different prices and may not accurately reflect the real tick price action. Consequently, this inaccuracy also impacts the real-time segmentation accuracy to some degree. TV does not provide a means of retaining “tick” information, so the higher granularity of information seen real-time will be lost on a disconnect.
TV does not provide time and sales information. The volume and price information collected using the Sample Time Frame is intraday, which provides only part of the picture. Intraday volume is generally 50 to 80% of the end of day volume. Consequently, the daily+ OHLC prices are intraday, and may differ significantly from exchanged settled OHLC prices.
The Cycle and Window Time Frames refer to calendar days and time, not trading days or time. For example, the first window week of a monthly cycle is the first seven days of the month, not the first Monday through Friday of trading for the month.
Chart Time Frames that are higher than the Window Time Frames average the normalized physics for price action that occurred within a given Candle segment. It does not average price action that did not occur.
One of the main performance bottleneck in TradingView’s Pine Script is client-side drawing and plotting. The performance of this indicator can be increased by lowering the resolution (the number of sub-candles this indicator plots), getting a faster computer, or increasing the performance of your computer like plugging your laptop in and eliminating unnecessary processes.
The statistical integrity of this indicator relies on the number of samples collected per sample window in a given cycle. Higher sample counts can be obtained by increasing the chart time frame or upgrading the TradingView plan for a higher bar count. While increasing the chart time frame doesn’t increase the visual number of bars plotted on the chart, it does increase the number of bars that can be pulled at a lower time frame, up to 100,000.
Due to a limitation in Pine Scripts request_lower_tf() function, using a spread symbol will only work for regular trading hours, not extended trading hours.
Ideally, velocity or momentum should be calculated between candle closes. To eliminate the need to deal with price gaps that would lead to an incorrect statistical distributions, momentum is calculated between candle open and closes as a percent change of the price or value, which should not be an issue for most liquid securities.
Moving Average Compendium RefurbishedThis is my effort to bring together in a single script the widest range of moving averages possible.
I aggregated the calculation of averages within a library.
For more information about the library follow the link:
Basically this indicator is the visual result of this library.
You can choose the moving average and the script updates the chart as per the type.
The unique parameters of certain moving averages remain at their default values.
To have a rainbow of moving averages I also made an indicator:
Available moving averages:
AARMA = 'Adaptive Autonomous Recursive Moving Average'
ADEMA = '* Alpha-Decreasing Exponential Moving Average'
AHMA = 'Ahrens Moving Average'
ALMA = 'Arnaud Legoux Moving Average'
ALSMA = 'Adaptive Least Squares'
AUTOL = 'Auto-Line'
CMA = 'Corrective Moving average'
CORMA = 'Correlation Moving Average Price'
COVWEMA = 'Coefficient of Variation Weighted Exponential Moving Average'
COVWMA = 'Coefficient of Variation Weighted Moving Average'
DEMA = 'Double Exponential Moving Average'
DONCHIAN = 'Donchian Middle Channel'
EDMA = 'Exponentially Deviating Moving Average'
EDSMA = 'Ehlers Dynamic Smoothed Moving Average'
EFRAMA = '* Ehlrs Modified Fractal Adaptive Moving Average'
EHMA = 'Exponential Hull Moving Average'
EMA = 'Exponential Moving Average'
EPMA = 'End Point Moving Average'
ETMA = 'Exponential Triangular Moving Average'
EVWMA = 'Elastic Volume Weighted Moving Average'
FAMA = 'Following Adaptive Moving Average'
FIBOWMA = 'Fibonacci Weighted Moving Average'
FISHLSMA = 'Fisher Least Squares Moving Average'
FRAMA = 'Fractal Adaptive Moving Average'
GMA = 'Geometric Moving Average'
HKAMA = 'Hilbert based Kaufman\'s Adaptive Moving Average'
HMA = 'Hull Moving Average'
JURIK = 'Jurik Moving Average'
KAMA = 'Kaufman\'s Adaptive Moving Average'
LC_LSMA = '1LC-LSMA (1 line code lsma with 3 functions)'
LEOMA = 'Leo Moving Average'
LINWMA = 'Linear Weighted Moving Average'
LSMA = 'Least Squares Moving Average'
MAMA = 'MESA Adaptive Moving Average'
MCMA = 'McNicholl Moving Average'
MEDIAN = 'Median'
REGMA = 'Regularized Exponential Moving Average'
REMA = 'Range EMA'
REPMA = 'Repulsion Moving Average'
RMA = 'Relative Moving Average'
RSIMA = 'RSI Moving average'
RVWAP = '* Rolling VWAP'
SMA = 'Simple Moving Average'
SMMA = 'Smoothed Moving Average'
SRWMA = 'Square Root Weighted Moving Average'
SW_MA = 'Sine-Weighted Moving Average'
SWMA = '* Symmetrically Weighted Moving Average'
TEMA = 'Triple Exponential Moving Average'
THMA = 'Triple Hull Moving Average'
TREMA = 'Triangular Exponential Moving Average'
TRSMA = 'Triangular Simple Moving Average'
TT3 = 'Tillson T3'
VAMA = 'Volatility Adjusted Moving Average'
VIDYA = 'Variable Index Dynamic Average'
VWAP = '* VWAP'
VWMA = 'Volume-weighted Moving Average'
WMA = 'Weighted Moving Average'
WWMA = 'Welles Wilder Moving Average'
XEMA = 'Optimized Exponential Moving Average'
ZEMA = 'Zero-Lag Exponential Moving Average'
ZSMA = 'Zero-Lag Simple Moving Average'
Moving_AveragesLibrary "Moving_Averages"
This library contains majority important moving average functions with int series support. Which means that they can be used with variable length input. For conventional use, please use tradingview built-in ta functions for moving averages as they are more precise. I'll use functions in this library for my other scripts with dynamic length inputs.
ema(src, len)
Exponential Moving Average (EMA)
Parameters:
src : Source
len : Period
Returns: Exponential Moving Average with Series Int Support (EMA)
alma(src, len, a_offset, a_sigma)
Arnaud Legoux Moving Average (ALMA)
Parameters:
src : Source
len : Period
a_offset : Arnaud Legoux offset
a_sigma : Arnaud Legoux sigma
Returns: Arnaud Legoux Moving Average (ALMA)
covwema(src, len)
Coefficient of Variation Weighted Exponential Moving Average (COVWEMA)
Parameters:
src : Source
len : Period
Returns: Coefficient of Variation Weighted Exponential Moving Average (COVWEMA)
covwma(src, len)
Coefficient of Variation Weighted Moving Average (COVWMA)
Parameters:
src : Source
len : Period
Returns: Coefficient of Variation Weighted Moving Average (COVWMA)
dema(src, len)
DEMA - Double Exponential Moving Average
Parameters:
src : Source
len : Period
Returns: DEMA - Double Exponential Moving Average
edsma(src, len, ssfLength, ssfPoles)
EDSMA - Ehlers Deviation Scaled Moving Average
Parameters:
src : Source
len : Period
ssfLength : EDSMA - Super Smoother Filter Length
ssfPoles : EDSMA - Super Smoother Filter Poles
Returns: Ehlers Deviation Scaled Moving Average (EDSMA)
eframa(src, len, FC, SC)
Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA)
Parameters:
src : Source
len : Period
FC : Lower Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average
SC : Upper Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average
Returns: Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA)
ehma(src, len)
EHMA - Exponential Hull Moving Average
Parameters:
src : Source
len : Period
Returns: Exponential Hull Moving Average (EHMA)
etma(src, len)
Exponential Triangular Moving Average (ETMA)
Parameters:
src : Source
len : Period
Returns: Exponential Triangular Moving Average (ETMA)
frama(src, len)
Fractal Adaptive Moving Average (FRAMA)
Parameters:
src : Source
len : Period
Returns: Fractal Adaptive Moving Average (FRAMA)
hma(src, len)
HMA - Hull Moving Average
Parameters:
src : Source
len : Period
Returns: Hull Moving Average (HMA)
jma(src, len, jurik_phase, jurik_power)
Jurik Moving Average - JMA
Parameters:
src : Source
len : Period
jurik_phase : Jurik (JMA) Only - Phase
jurik_power : Jurik (JMA) Only - Power
Returns: Jurik Moving Average (JMA)
kama(src, len, k_fastLength, k_slowLength)
Kaufman's Adaptive Moving Average (KAMA)
Parameters:
src : Source
len : Period
k_fastLength : Number of periods for the fastest exponential moving average
k_slowLength : Number of periods for the slowest exponential moving average
Returns: Kaufman's Adaptive Moving Average (KAMA)
kijun(_high, _low, len, kidiv)
Kijun v2
Parameters:
_high : High value of bar
_low : Low value of bar
len : Period
kidiv : Kijun MOD Divider
Returns: Kijun v2
lsma(src, len, offset)
LSMA/LRC - Least Squares Moving Average / Linear Regression Curve
Parameters:
src : Source
len : Period
offset : Offset
Returns: Least Squares Moving Average (LSMA)/ Linear Regression Curve (LRC)
mf(src, len, beta, feedback, z)
MF - Modular Filter
Parameters:
src : Source
len : Period
beta : Modular Filter, General Filter Only - Beta
feedback : Modular Filter Only - Feedback
z : Modular Filter Only - Feedback Weighting
Returns: Modular Filter (MF)
rma(src, len)
RMA - RSI Moving average
Parameters:
src : Source
len : Period
Returns: RSI Moving average (RMA)
sma(src, len)
SMA - Simple Moving Average
Parameters:
src : Source
len : Period
Returns: Simple Moving Average (SMA)
smma(src, len)
Smoothed Moving Average (SMMA)
Parameters:
src : Source
len : Period
Returns: Smoothed Moving Average (SMMA)
stma(src, len)
Simple Triangular Moving Average (STMA)
Parameters:
src : Source
len : Period
Returns: Simple Triangular Moving Average (STMA)
tema(src, len)
TEMA - Triple Exponential Moving Average
Parameters:
src : Source
len : Period
Returns: Triple Exponential Moving Average (TEMA)
thma(src, len)
THMA - Triple Hull Moving Average
Parameters:
src : Source
len : Period
Returns: Triple Hull Moving Average (THMA)
vama(src, len, volatility_lookback)
VAMA - Volatility Adjusted Moving Average
Parameters:
src : Source
len : Period
volatility_lookback : Volatility lookback length
Returns: Volatility Adjusted Moving Average (VAMA)
vidya(src, len)
Variable Index Dynamic Average (VIDYA)
Parameters:
src : Source
len : Period
Returns: Variable Index Dynamic Average (VIDYA)
vwma(src, len)
Volume-Weighted Moving Average (VWMA)
Parameters:
src : Source
len : Period
Returns: Volume-Weighted Moving Average (VWMA)
wma(src, len)
WMA - Weighted Moving Average
Parameters:
src : Source
len : Period
Returns: Weighted Moving Average (WMA)
zema(src, len)
Zero-Lag Exponential Moving Average (ZEMA)
Parameters:
src : Source
len : Period
Returns: Zero-Lag Exponential Moving Average (ZEMA)
zsma(src, len)
Zero-Lag Simple Moving Average (ZSMA)
Parameters:
src : Source
len : Period
Returns: Zero-Lag Simple Moving Average (ZSMA)
evwma(src, len)
EVWMA - Elastic Volume Weighted Moving Average
Parameters:
src : Source
len : Period
Returns: Elastic Volume Weighted Moving Average (EVWMA)
tt3(src, len, a1_t3)
Tillson T3
Parameters:
src : Source
len : Period
a1_t3 : Tillson T3 Volume Factor
Returns: Tillson T3
gma(src, len)
GMA - Geometric Moving Average
Parameters:
src : Source
len : Period
Returns: Geometric Moving Average (GMA)
wwma(src, len)
WWMA - Welles Wilder Moving Average
Parameters:
src : Source
len : Period
Returns: Welles Wilder Moving Average (WWMA)
ama(src, _high, _low, len, ama_f_length, ama_s_length)
AMA - Adjusted Moving Average
Parameters:
src : Source
_high : High value of bar
_low : Low value of bar
len : Period
ama_f_length : Fast EMA Length
ama_s_length : Slow EMA Length
Returns: Adjusted Moving Average (AMA)
cma(src, len)
Corrective Moving average (CMA)
Parameters:
src : Source
len : Period
Returns: Corrective Moving average (CMA)
gmma(src, len)
Geometric Mean Moving Average (GMMA)
Parameters:
src : Source
len : Period
Returns: Geometric Mean Moving Average (GMMA)
ealf(src, len, LAPercLen_, FPerc_)
Ehler's Adaptive Laguerre filter (EALF)
Parameters:
src : Source
len : Period
LAPercLen_ : Median Length
FPerc_ : Median Percentage
Returns: Ehler's Adaptive Laguerre filter (EALF)
elf(src, len, LAPercLen_, FPerc_)
ELF - Ehler's Laguerre filter
Parameters:
src : Source
len : Period
LAPercLen_ : Median Length
FPerc_ : Median Percentage
Returns: Ehler's Laguerre Filter (ELF)
edma(src, len)
Exponentially Deviating Moving Average (MZ EDMA)
Parameters:
src : Source
len : Period
Returns: Exponentially Deviating Moving Average (MZ EDMA)
pnr(src, len, rank_inter_Perc_)
PNR - percentile nearest rank
Parameters:
src : Source
len : Period
rank_inter_Perc_ : Rank and Interpolation Percentage
Returns: Percentile Nearest Rank (PNR)
pli(src, len, rank_inter_Perc_)
PLI - Percentile Linear Interpolation
Parameters:
src : Source
len : Period
rank_inter_Perc_ : Rank and Interpolation Percentage
Returns: Percentile Linear Interpolation (PLI)
rema(src, len)
Range EMA (REMA)
Parameters:
src : Source
len : Period
Returns: Range EMA (REMA)
sw_ma(src, len)
Sine-Weighted Moving Average (SW-MA)
Parameters:
src : Source
len : Period
Returns: Sine-Weighted Moving Average (SW-MA)
vwap(src, len)
Volume Weighted Average Price (VWAP)
Parameters:
src : Source
len : Period
Returns: Volume Weighted Average Price (VWAP)
mama(src, len)
MAMA - MESA Adaptive Moving Average
Parameters:
src : Source
len : Period
Returns: MESA Adaptive Moving Average (MAMA)
fama(src, len)
FAMA - Following Adaptive Moving Average
Parameters:
src : Source
len : Period
Returns: Following Adaptive Moving Average (FAMA)
hkama(src, len)
HKAMA - Hilbert based Kaufman's Adaptive Moving Average
Parameters:
src : Source
len : Period
Returns: Hilbert based Kaufman's Adaptive Moving Average (HKAMA)
NoBrain BreakoutUse 3min. Time frame.
Buy Stock Selection:-
When Close Price Cross Monthly Standard Pivot R1 & Monthly Standard Pivot R1 is Greater than Previous Day High( PDH ) Or Close.
Price must be Above 44 MA ,48 EMA & Vwap
***Buy When 3min Candle closed Above Camarilla R4 or Monthly Standard Pivot R1 whichever is High.
Sell Stock Selection:-
When Close Price Cross Monthly Standard Pivot S1 & Monthly Standard Pivot S1 is Less than Previous Day Low( PDL ) Or Close.
Price must be Below 44 MA ,48 EMA & Vwap
***Sell When 3min Candle closed Below Camarilla S4 or Monthly Standard Pivot S1 whichever is Low.
Trading time for
1st wave 9.30am to 10.45am.
2nd wave 12.45pm to 2.45pm.
(Based on NSE/ BSE India)
Indicators:-
1) Pivot Points Standard - Time Frame monthly.only select R1
2) Pivot Points Camarilla- Only select R4.
3) SMA 44
4) EMA 48
5) Vwap
6) For Trailing Stop Loss use SuperTrend- Length-13 Factor-2.7 or Length-15 Factor-3 (3min Timeframe)
Multi-Timeframe (MTF) Dashboard by RiTzMulti-Timeframe Dashboard
Shows values of different Indiactors on Multiple-Timeframes for the selected script/symbol
VWAP : if LTP is trading above VWAP then Bullish else if LTP is trading below VWAP then Bearish.
ST(21,1) : if LTP is trading above Supertrend (21,1) then Bullish , else if LTP is trading below Supertrend (21,1) then Bearish.
ST(14,2) : if LTP is trading above Supertrend (14,2) then Bullish , else if LTP is trading below Supertrend (14,2) then Bearish.
ST(10,3) : if LTP is trading above Supertrend (10,3) then Bullish , else if LTP is trading below Supertrend (10,3) then Bearish.
RSI(14) : Shows value of RSI (14) for the current timeframe.
ADX : if ADX is > 75 and DI+ > DI- then "Bullish ++".
if ADX is < 75 but >50 and DI+ > DI- then "Bullish +".
if ADX is < 50 but > 25 and DI+ > DI- then "Bullish".
if ADX is above 75 and DI- > DI+ then "Bearish ++".
if ADX is < 75 but > 50 and DI- > DI+ then "Bearish+".
if ADX is < 50 but > 25 and DI- > DI+ then "Bearish".
if ADX is < 25 then "Neutral".
MACD : if MACD line is above Signal Line then "Bullish", else if MACD line is below Signal Line then "Bearish".
PH-PL : "< PH > PL" means LTP is trading between Previous Timeframes High(PH) & Previous Timeframes Low(PL) which indicates Rangebound-ness.
"> PH" means LTP is trading above Previous Timeframes High(PH) which indicates Bullish-ness.
"< PL" means LTP is trading below Previous Timeframes Low(PL) which indicates Bearish-ness.
Alligator : If Lips > Teeth > Jaw then Bullish.
If Lips < Teeth < Jaw then Bearish.
If Lips > Teeth and Teeth < Jaw then Neutral/Sleeping.
If Lips < Teeth and Teeth > Jaw then Neutral/Sleeping.
Settings :
Style settings :-
Dashboard Location: Location of the dashboard on the chart
Dashboard Size: Size of the dashboard on the chart
Bullish Cell Color: Select the color of cell whose value is showing Bullish-ness.
Bearish Cell Color: Select the color of cell whose value is showing Bearish-ness.
Neutral Cell Color: Select the color of cell whose value is showing Rangebound-ness.
Cell Transparency: Select Transparency of cell.
Column Settings :-
You can select which Indicators values should be displayed/hidden.
Timeframe Settings :-
You can select which timeframes values should be displayed/hidden.
Note :- I'm not a pro Developer/Coder , so if there are any mistakes or any suggestions for improvements in the code then do let me know!
Note :- Use in Live market , might show wrong values for timeframes other than current timeframe in closed market!!
Nifty / Banknifty Dashboard by RiTzNifty / Banknifty Dashboard :
Shows Values of different Indicators on current Timeframe for the selected Index & it's main constituents according to weightage in index.
customized for Nifty & Banknifty (You can customize it according to your needs for the markets/indexes you trade in)
Interpretation :-
VWAP : if LTP is trading above VWAP then Bullish else if LTP is trading below VWAP then Bearish.
ST(21,1) : if LTP is trading above Supertrend (21,1) then Bullish , else if LTP is trading below Supertrend (21,1) then Bearish.
ST(14,2) : if LTP is trading above Supertrend (14,2) then Bullish , else if LTP is trading below Supertrend (14,2) then Bearish.
ST(10,3) : if LTP is trading above Supertrend (10,3) then Bullish , else if LTP is trading below Supertrend (10,3) then Bearish.
RSI(14) : Shows value of RSI (14) for the current timeframe.
ADX : if ADX is > 75 and DI+ > DI- then "Bullish ++".
if ADX is < 75 but >50 and DI+ > DI- then "Bullish +".
if ADX is < 50 but > 25 and DI+ > DI- then "Bullish".
if ADX is above 75 and DI- > DI+ then "Bearish ++".
if ADX is < 75 but > 50 and DI- > DI+ then "Bearish+".
if ADX is < 50 but > 25 and DI- > DI+ then "Bearish".
if ADX is < 25 then "Neutral".
MACD : if MACD line is above Signal Line then "Bullish", else if MACD line is below Signal Line then "Bearish".
PDH-PDL : "< PDH > PDL" means LTP is trading between Previous Days High(PDH) & Previous Days Low(PDL) which indicates Rangebound-ness.
"> PDH" means LTP is trading above Previous Days High(PDH) which indicates Bullish-ness.
"< PDL" means LTP is trading below Previous Days Low(PDL) which indicates Bearish-ness.
Alligator : If Lips > Teeth > Jaw then Bullish.
If Lips < Teeth < Jaw then Bearish.
If Lips > Teeth and Teeth < Jaw then Neutral/Sleeping.
If Lips < Teeth and Teeth > Jaw then Neutral/Sleeping.
Settings :
Style settings :-
Dashboard Location: Location of the dashboard on the chart
Dashboard Size: Size of the dashboard on the chart
Bullish Cell Color: Select the color of cell whose value is showing Bullish-ness.
Bearish Cell Color: Select the color of cell whose value is showing Bearish-ness.
Neutral Cell Color: Select the color of cell whose value is showing Rangebound-ness.
Cell Transparency: Select Transparency of cell.
Columns Settings :-
You can select which Indicators values should be displayed/hidden.
Rows Settings :-
You can select which Stocks/Symbols values should be displayed/hidden.
Symbol Settings :-
Here you can select the Index & Stocks/Symbols
Dashboard for Index : select Nifty/Banknifty
if you select Nifty then Nifty spot, Nifty current Futures and the stocks with most weightage in Nifty index will be displayed on the Dashboard/Table.
if you select Banknifty then Banknifty spot, Banknifty current Futures and the stocks with most weightage in Banknifty index will be displayed on the Dashboard/Table.
You can Customise it according to your needs, you can choose any Symbols you want to use.
Note :- This is inspired from "RankDelta" by AsitPati and "Nifty and Bank Nifty Dashboard v2" by cvsk123 (Both these scripts are closed source!)
I'm not a pro Developer/Coder , so if there are any mistakes or any suggestions for improvements in the code then do let me know!
Super scalpThis is scalp strategy based on the confluence of 3 indicators
ema 9 , supertrend and vwap
when supertrend buy signal is generated and the price is above ema and vwap scalp buy signal is generated
when supertrend sell signal is generated and the price is below ema and vwap scalp sell signal is generated