Simple Trendlines📈 Trendlines, made easy.
Simple Trendlines is a carefully made library that provides an easy and accessible way to draw trendlines on the chart.
Containing only 10 properties and 2 methods, the implementation is designed to be understandable through an object-oriented structure and provides developers the opportunity to expand without having to deal with slope calculation while also ensuring that there's no leakage between the trendlines before they're drawn.
Developers only need to provide 5 expressions to get everything up in running. This includes the following but is not limited to
The x-axis
Point A (Y1 Value)
Point B (Y2 Value)
A condition to draw the line
A condition to keep the trendline under continuation
Automatic x-axis calculation is not a built-in feature due to the inconsistency it could bring.
📕 Quick Example
import HoanGhetti/SimpleTrendlines/1 as tl
input_len = input.int(defval = 10)
pivotLow = fixnan(ta.pivotlow(input_len, input_len))
xAxis = ta.valuewhen(ta.change(pivotLow), bar_index, 0) - ta.valuewhen(ta.change(pivotLow), bar_index, 1)
prevPivot = ta.valuewhen(ta.change(pivotLow), pivotLow, 1)
pivotCondition = ta.change(pivotLow) and pivotLow > prevPivot
plData = tl.new(x_axis = xAxis, offset = input_len)
plData.drawLine(pivotCondition, prevPivot, pivotLow)
plData.drawTrendline(close > 0)
plData.lines.trendline.set_style(line.style_dashed)
plData.lines.trendline.set_width(2)
plData.lines.startline.set_width(2)
Excluding the styling at the bottom, that was only 8 lines of code which yields the following result.
⏳ Before continuing
The library does not support block-scoped execution. Conditions must be declared before and integrated as a parameter. This doesn't limit any capabilities and only involves thinking logically about precedence. It was made this way for code readability and to keep things organized.
The offset value inside the TrendlineSettings object can potentially affect performance (although very minimal) if you're using strict mode. When using strict mode, it loops through historical values to then do backend calculations.
🔽 Getting Started 🔽
Creating trendlines without a library isn't a hard task. However, the library features a built-in system called strict mode. We'll dive further into this below.
Creating an Instance
You can create an instance of the library by calling the new() function. Passing an identifier is conventionally mandatory in this case so you can reference properties and methods.
import HoanGhetti/SimpleTrendlines/2 as tl
lineData = tl.new(int x_axis, int offset, bool strictMode, int strictType)
___
int x_axis (Required) The distance between point A and point B provided by the user.
int offset (Optional) The offset from x2 and the current bar_index. Used in situations where conditions execute ahead of where the x2 location is such as pivót events.
bool strictMode (Optional) Strict mode works in the backend of things to ensure that the price hasn't closed below the trendline before the trendline is drawn.
int strictType (Optional) Only accepts 0 and 1, 0 ensures that the price during slope calculation is above the line, and 1 ensures that the price during slope calculation is below the line.
The Initial Line
After instantiating the library, we can go ahead use the identifer we made above and create an instance of our initial line by calling the drawLine() method.
lineData.drawLine(bool condition, float y1, float y2, float src)
___
bool condition (Required) The condition in order to draw a new line.
float y1 (Required) The y-value of point A.
float y2 (Required) The y-value of point B.
float src (Optional) Determines which value strict mode will actively check for leakage before a trendline is drawn.
Typically used if you're not referencing OHLC values for your y-values, or you want to check for another value to exceed the line besides using the close value.
The Trendline
The trendline that gets drawn solely uses the values of the initial line and can be called using the drawTrendline() method. The library enforces a condition as a parameter in order to maintain simplicity.
lineData.drawTrendline(bool condition)
___
bool condition (Required) The condition in order to maintain and continue drawing the trendline.
⚙️ Features
🔹 Automatic Slope Calculation
In the background, the library calculates the next Y2 and X2 values on every tick for the trendline. Preventing the developer from having to do such a process themself.
🔹 Object-Oriented
Each object contains manipulative properties that allow the developer to debug and have the freedom they want.
🔹 Enforced Error Checking
Runtime errors have been put in place to ensure you're doing things correctly.
🔹 Strict Mode & Offset
Strict mode can only be used when the offset value is over 0. It's a feature that's only meant to function under scenarios where a condition executes further than where the X2 is relative to the current bar_index value.
Let's think about pivot systems. As you're aware, pivot events are detected based on historical factors. If a swing low occurred nth bars ago, then the pivot condition will execute at the current bar_index instead of executing nth bars back.
Now because of this, what if you wanted to draw a trendline when the pivot event is executed? The offset value takes care of this just as you would when developing your other scripts, basically how we always do bar_index - n. However, what does this mean for strict mode?
The photo below represents the logic behind the execution.
When looking at this image, imagine this just happened, the event just executed and the trendline is now drawn. Pay attention to all the values inside the surrounding box. As you can see there are some candles that closed below the trendline before the trendline was drawn.
From what I can see 5-6 candles closed below the trendline during slope calculation. The goal of strict mode is to be a provisional system that prevents such occurrences from happening.
Here's a photo with strict mode on.
🔹 Strict Type
A parameter used in the new() function that acts as a representation of what strict mode should calculate for. It accepts only two values, 0 and 1.
0 - Ensures that all candles have closed above the trendline before the trendline is drawn.
1 - Ensures that all candles have closed below the trendline before the trendline is drawn.
In the most recent photo above, I used 0 for strict type, since I was wanting to have a clean trendline and ensure that not a single candlestick closed below.
If you want to reference something else besides the close value during strict mode calculation, you can change it in the drawLine() method.
If it's still difficult to understand, think 0 for pivot lows, and 1 for pivot highs.
📕 Methods and Property Inheritance
The library isn't crazy, but hopefully, it helps.
That is all.👍
Chỉ báo và chiến lược
Sniffer
╭━━━╮╱╱╱╱╭━╮╭━╮
┃╭━╮┃╱╱╱╱┃╭╯┃╭╯
┃╰━━┳━╮╭┳╯╰┳╯╰┳━━┳━╮
╰━━╮┃╭╮╋╋╮╭┻╮╭┫┃━┫╭╯
┃╰━╯┃┃┃┃┃┃┃╱┃┃┃┃━┫┃
╰━━━┻╯╰┻╯╰╯╱╰╯╰━━┻╯
Overview
A vast majority of modern data analysis & modelling techniques rely upon the idea of hidden patterns, wether it is some type of visualisation tool or some form of a complex machine learning algorithm, the one thing that they have in common is the belief, that patterns tell us what’s hidden behind plain numbers. The same philosophy has been adopted by many traders & investors worldwide, there’s an entire school of thought that operates purely based on chart patterns. This is where Sniffer comes in, it is a tool designed to simplify & quantify the job of pattern recognition on any given price chart, by combining various factors & techniques that generate high-quality results.
This tool analyses bars selected by the user, and highlights bar clusters on the chart that exhibit similar behaviour across multiple dimensions. It can detect a single candle pattern like hammers or dojis, or it can handle multiple candles like morning/evening stars or double tops/bottoms, and many more. In fact, the tool is completely independent of such specific candle formations, instead, it works on the idea of vector similarity and generates a degree of similarity for every single combination of candles. Only the top-n matches are highlighted, users get to choose which patterns they want to analyse and to what degree, by customising the feature-space.
Background
In the world of trading, a common use-case is to scan a price chart for some specific candlestick formations & price structures, and then the chart is further analysed in reference to these events. Traders are often trying to answer questions like, when was the last time price showed similar behaviour, what are the instances similar to what price is doing right now, what happens when price forms a pattern like this, what were some of other indicators doing when this happened last(RSI, CCI, ADX etc), and many other abstract ideas to have a stronger confluence or to confirm a bias.Having such a context can be vital in making better informed decisions, but doing this manually on a chart that has thousands of candles can have many disadvantages. It’s tedious, human errors are rather likely, and even if it’s done with pin-point accuracy, chances are that we’ll miss out on many pieces of information. This is the thought that gave birth to Sniffer .
Sniffer tries to provide a general solution for pattern-based analysis by deploying vector-similarity computation techniques, that cover the full-breadth of a price chart and generate a list of top-n matches based on the criteria selected by the user. Most of these techniques come from the data science space, where vector similarity is often implemented to solve classification & clustering problems. Sniffer uses same principles of vector comparison, and computes a degree of similarity for every single candle formation within the selected range, and as a result generates a similarity matrix that captures how similar or dissimilar a set of candles is to the input set selected by the user.
How It Works
A brief overview of how the tool is implemented:
- Every bar is processed, and a set of features are mapped to it.
- Bars selected by the user are captured, and saved for later use.
- Once the all the bars have been processed, candles are back-tracked and degree of similarity is computed for every single bar(max-limit is 5000 bars).
- Degree of similarity is computed by comparing attributes like price range, candle breadth & volume etc.
- Similarity matrix is sorted and top-n results are highlighted on the chart through boxes of different colors.
A brief overview of the features space for bars:
- Range: Difference between high & low
- Body: Difference between close & open
- Volume: Traded volume for that candle
- Head: Upper wick for green candles & lower wick for red candles
- Tail: Lower wick for green candles & upper wick for red candles
- BTR: Body to Range ratio
- HTR: Head to Range ratio
- TTR: Tail to Range ratio
- HTB: Head to Body ratio
- TTB: Tail to Body ratio
- ROC: Rate of change for HL2 for four different periods
- RSI: Relative Strength Index
- CCI: Commodity Channel Index
- Stochastic: Stochastic Index
- ADX: DMI+, DMI- & ADX
A brief overview of how degree of similarity is calculated:
- Each bar set is compared to the inout bar set within the selected feature space
- Features are represented as vectors, and distance between the vectors is calculated
- Shorter the distance, greater the similarity
- Different distance calculation methods are available to choose from, such as Cosine, Euclidean, Lorentzian, Manhattan, & Pearson
- Each method is likely to generate slightly different results, users are expected to select the method & the feature space that best fits their use-case
How To Use It
- Usage of this tool is relatively straightforward, users can add this indicator to their chart and similar clusters will be highlighted automatically
- Users need to select a time range that will be treated as input, and bars within that range become the input formation for similarity calculations
- Boxes will be draw around the clusters that fit the matching criteria
- Boxes are color-coded, green color boxes represent the top one-third of the top-n matches, yellow boxes represent the middle third, red boxes are for bottom third, and white box represents user-input
- Boxes colors will be adjusted as you adjust input parameters, such as number of matches or look-back period
User Settings
Users can configure the following options:
- Select the time-range to set input bars
- Select the look-back period, number of candles to backtrack for similarity search
- Select the number of top-n matches to show on the chart
- Select the method for similarity calculation
- Adjust the feature space, this enables addition of custom features, such as pattern recognition, technical indicators, rate of change etc
- Toggle verbosity, shows degree of similarity as a percentage value inside the box
Top Features
- Pattern Agnostic: Designed to work with variable number of candles & complex patterns
- Customisable Feature Space: Users get to add custom features to each bar
- Comprehensive Comparison: Generates a degree of similarity for all possible combinations
Final Note
- Similarity matches will be shown only within last 4500 bars.
- In theory, it is possible to compute similarity for any size candle formations, indicator has been tested with formations of 50+ candles, but it is recommended to select smaller range for faster & cleaner results.
- As you move to smaller time frames, selected time range will provide a larger number of candles as input, which can produce undesired results, it is advised to adjust your selection when you change time frames. Seeking suggestions on how to directly receive bars as user input, instead of time range.
- At times, users may see array index out of bound error when setting up this indicator, this generally happens when the input range is not properly configured. So, it should disappear after you select the input range, still trying to figure out where it is coming from, suggestions are welcome.
Credits
- @HeWhoMustNotBeNamed for publishing such a handy PineScript Logger, it certainly made the job a lot easier.
ATR OSC and Volume Screener (ATROSCVS)In today's world of trading, having the right tools and indicators can make all the difference. With the vast number of cryptocurrencies available, I've found it challenging to keep track of the market's overall direction and make informed decisions. That's where the ATR OSC and Volume Screener comes in, a powerful Pine Script that I use to identify potential trading opportunities across multiple cryptocurrencies, all in one convenient place.
This script combines two essential components: the ATR Oscillator (ATR OSC) and a Volume Screener. It is designed to work with the TradingView platform. Let me explain how this script works and how it benefits my trading.
Firstly, the ATR Oscillator is an RSI-like oscillator that performs better under longer lookback periods. Unlike traditional RSI, the ATR OSC doesn't lose its min and max ranges with a long lookback period, as the scale remains intact. It calculates the true range by considering the high, low, open, and close prices of a financial instrument, and uses this true range instead of the standard deviation in a modified z-score calculation. This unique approach helps provide a more precise assessment of the market's volatility.
The Volume Screener, on the other hand, helps me identify unusual trading volumes across various cryptocurrencies. It employs a normalized volume calculation method, effectively filtering out outliers and highlighting potentially significant trading opportunities.
One feature I find particularly impressive about the ATR OSC and Volume Screener is its versatility and the way it displays information using color gradients. With support for over 30 different cryptocurrencies, including popular options like Bitcoin (BTC), Ethereum (ETH), Ripple (XRP), and Dogecoin (DOGE), I can monitor a wide range of markets simultaneously. The color gradient on the grid is visually appealing and makes it easy to identify the strength of the indicators for each cryptocurrency, allowing me to make quick comparisons and spot potential trading opportunities.
The customizable input options allow me to fine-tune the script to suit my individual trading preferences and strategies. In summary, the ATR OSC and Volume Screener has been an invaluable tool for me as I navigate the ever-evolving world of cryptocurrencies. By combining the power of the ATR Oscillator with a robust Volume Screener, this Pine Script makes it easier than ever to identify promising trading opportunities and stay ahead of the game.
The color gradient in the ATR OSC and Volume Screener is essential for visually representing the data on the heatmap. It uses a range of colors to indicate the strength of the indicators for each cryptocurrency, making it easier to understand the market dynamics at a glance.
In the heatmap, the color gradient typically starts from a cooler color, such as blue or green, at the lower extremes (low ATR OSC values) and progresses towards warmer colors, like yellow, orange, or red, as the ATR OSC values approach the upper extremes (high ATR OSC values). This color-coding system enables me to quickly identify and interpret the data without having to examine individual numerical values.
For example, cooler colors (blue or green) might represent lower values of the ATR Oscillator, suggesting oversold conditions in the respective cryptocurrencies. On the other hand, warmer colors (yellow, orange, or red) indicate higher ATR OSC values, signaling overbought market conditions. This visual representation allows me to make rapid comparisons between different cryptocurrencies and spot potential trading opportunities more efficiently.
By utilizing the color gradient in the heatmap, the ATR OSC and Volume Screener simplifies the analysis of multiple cryptocurrencies, helping me to quickly identify market trends and make better-informed trading decisions.
I highly recommend testing the ATR OSC and Volume Screener and seeing the difference it can make in your trading decisions. Happy trading!
DataChartLibrary "DataChart"
Library to plot scatterplot or heatmaps for your own set of data samples
draw(this)
draw contents of the chart object
Parameters:
this : Chart object
Returns: current chart object
init(this)
Initialize Chart object.
Parameters:
this : Chart object to be initialized
Returns: current chart object
addSample(this, sample, trigger)
Add sample data to chart using Sample object
Parameters:
this : Chart object
sample : Sample object containing sample x and y values to be plotted
trigger : Samples are added to chart only if trigger is set to true. Default value is true
Returns: current chart object
addSample(this, x, y, trigger)
Add sample data to chart using x and y values
Parameters:
this : Chart object
x : x value of sample data
y : y value of sample data
trigger : Samples are added to chart only if trigger is set to true. Default value is true
Returns: current chart object
addPriceSample(this, priceSampleData, config)
Add price sample data - special type of sample designed to measure price displacements of events
Parameters:
this : Chart object
priceSampleData : PriceSampleData object containing event driven displacement data of x and y
config : PriceSampleConfig object containing configurations for deriving x and y from priceSampleData
Returns: current chart object
Sample
Sample data for chart
Fields:
xValue : x value of the sample data
yValue : y value of the sample data
ChartProperties
Properties of plotting chart
Fields:
title : Title of the chart
suffix : Suffix for values. It can be used to reference 10X or 4% etc. Used only if format is not format.percent
matrixSize : size of the matrix used for plotting
chartType : Can be either scatterplot or heatmap. Default is scatterplot
outliersStart : Indicates the percentile of data to filter out from the starting point to get rid of outliers
outliersEnd : Indicates the percentile of data to filter out from the ending point to get rid of outliers.
backgroundColor
plotColor : color of plots on the chart. Default is color.yellow. Only used for scatterplot type
heatmapColor : color of heatmaps on the chart. Default is color.red. Only used for heatmap type
borderColor : border color of the chart table. Default is color.yellow.
plotSize : size of scatter plots. Default is size.large
format : data representation format in tooltips. Use mintick.percent if measuring any data in terms of percent. Else, use format.mintick
showCounters : display counters which shows totals on each quadrants. These are single cell tables at the corners displaying number of occurences on each quadrant.
showTitle : display title at the top center. Uses the title string set in the properties
counterBackground : background color of counter table cells. Default is color.teal
counterTextColor : text color of counter table cells. Default is color.white
counterTextSize : size of counter table cells. Default is size.large
titleBackground : background color of chart title. Default is color.maroon
titleTextColor : text color of the chart title. Default is color.white
titleTextSize : text size of the title cell. Default is size.large
addOutliersToBorder : If set, instead of removing the outliers, it will be added to the border cells.
useCommonScale : Use common scale for both x and y. If not selected, different scales are calculated based on range of x and y values from samples. Default is set to false.
plotchar : scatter plot character. Default is set to ascii bullet.
ChartDrawing
Chart drawing objects collection
Fields:
properties : ChartProperties object which determines the type and characteristics of chart being plotted
titleTable : table containing title of the chart.
mainTable : table containing plots or heatmaps.
quadrantTables : Array of tables containing counters of all 4 quandrants
Chart
Chart type which contains all the information of chart being plotted
Fields:
properties : ChartProperties object which determines the type and characteristics of chart being plotted
samples : Array of Sample objects collected over period of time for plotting on chart.
displacements : Array containing displacement values. Both x and y values
displacementX : Array containing only X displacement values.
displacementY : Array containing only Y displacement values.
drawing : ChartDrawing object which contains all the drawing elements
PriceSampleConfig
Configs used for adding specific type of samples called PriceSamples
Fields:
duration : impact duration for which price displacement samples are calculated.
useAtrReference : Default is true. If set to true, price is measured in terms of Atr. Else is measured in terms of percentage of price.
atrLength : atrLength to be used for measuring the price based on ATR. Used only if useAtrReference is set to true.
PriceSampleData
Special type of sample called price sample. Can be used instead of basic Sample type
Fields:
trigger : consider sample only if trigger is set to true. Default is true.
source : Price source. Default is close
highSource : High price source. Default is high
lowSource : Low price source. Default is low
tr : True range value. Default is ta.tr
Range Sentiment Profile [LuxAlgo]The Range Sentiment Profile indicator is inspired from the volume profile and aims to indicate the degree of bullish/bearish variations within equidistant price areas inside the most recent price range.
The most bullish/bearish price areas are highlighted through lines extending over the entire range.
🔶 SETTINGS
Length: Most recent bars used for the calculation of the indicator.
Rows: Number of price areas the price range is divided into.
Use Intrabar: Use intrabar data to compute the range sentiment profile.
Timeframe: Intrabar data timeframe.
🔶 USAGE
This tool can be used to easily determine if a certain price area contain more significant bullish or bearish price variations. This is done by obtaining an estimate of the accumulation of all the close to open variations occurring within a specific profile area.
A blue range background indicates a majority of bullish variations within each area while an orange background indicates a majority of bearish variations within each area.
Users can easily identify the areas with the most bullish/bearish price variations by looking at the bullish/bearish maximums.
It can be of interest to see where profile bins might have no length, these can indicate price areas with price variations with alternating signs (bullish variations are followed by a bearish sign) and similar body. They can also indicate a majority of either bullish or bearish variations alongside a minority of more significant opposite variations.
These areas can also provide support/resistance, as such price entering these areas could reverse.
Users can obtain more precise results by allowing the profile to use intrabar data. This will change the calculation of the profile, see the details section for more information.
🔶 DETAILS
The Range Sentiment Profile's design is similar to the way a volume profile is constructed.
First the maximum/minimum values over the most recent Length bars are obtained, these define the calculation range of the profile.
The range is divided into Rows equidistant areas. We then see if price lied within a specific area, if it's the case we accumulate the difference between the closing and opening price for that specific area.
Let d = close - open . The length of the bin associated to a specific area is determined as follows:
length = Width / 100 * Area / Max
Where Area is the accumulated d within the area, and Max the maximum value between the absolute value of each accumulated d of all areas.
The percentage visible on each bin is determined as 100 multiplied by the accumulated d within the area divided by the total absolute value of d over the entire range.
🔹 Intrabar Calculation
When using intrabar data the range sentiment profile is calculated differently.
For a specific area and candle within the interval, the accumulated close to open difference is accumulated only if the intrabar candle of the user selected timeframe lies within the area.
This can return more precise results compared to the standard method, at the cost of a higher computation time.
Intrabar Run Count Indicator [tbiktag]• OVERVIEW
Introducing the Intrabar Run Count Indicator , a tool designed to detect potential non-randomness in intrabar price data. It utilizes the statistical runs test to examine the number of sequences ( runs ) of positive and negative returns in the analyzed price series. As deviations from random-walk behavior of returns may indicate market inefficiencies , the Intrabar Run Count Indicator can help traders gain a better understanding of the price dynamics inside each chart bar and make more informed trading decisions.
• USAGE
The indicator line expresses the deviation between the number of runs observed in the dataset and the expected number of runs under the hypothesis of randomness. Thus, it gauges the degree of deviation from random-walk behavior. If, for a given chart bar, it crosses above the critical value or crosses below the negative critical value, this may indicate non-randomness in the underlying intrabar returns. These instances are highlighted by on-chart signals and bar coloring. The confidence level that defines the critical value, as well as the number of intrabars used for analysis, are selected in the input settings.
It is important to note that the readings of the Intrabar Run Count Indicator do not convey directional information and cannot predict future asset performance. Rather, they help distinguish between random and potentially tradable price movements, such as breakouts, reversals, and gap fillings.
• DETAILS
The efficient-market hypothesis implies that the distribution of returns should be random, reflecting the idea that all available information is already priced into the asset. However, in practice, financial markets may not always be perfectly efficient due to factors such as market frictions, information asymmetry, and irrational behavior of market participants. As a result, inefficiency (non-randomness) can occur, potentially creating opportunities for trading strategies.
To search for potential inefficiencies, the Intrabar Run Count Indicator analyzes the distribution of the signs of returns. The central assumption underlying the indicator's logic is that if the asset price follows a random-walk pattern, then the probability of the next return being positive or negative (i.e., the next price value being larger or smaller than the current value) follows a binomial distribution. In this case, the number of runs is also a random variable, and, for a large sample, its conditional distribution is approximately normal with a well-defined mean and variance (see this link for the exact expressions). Thus, the observed number of runs in the price series is indicative of whether or not the time series can be regarded as random. In simple words, if there are too few runs or too many runs, it is unlikely a random time series. A trivial example is a series with all returns of the same sign.
Quantitatively, the deviation from randomness can be gauged by calculating the test statistic of the runs test (that serves as an indicator line ). It is defined as the absolute difference between the observed number of runs and the expected number of runs under the null hypothesis of randomness, divided by the standard deviation of the expected number of runs. If the test statistic is negative and exceeds the negative critical value (at a given confidence level), it suggests that there are fewer runs than expected for a random-walking time series. Likewise, if the test statistic exceeds the positive critical value, it is indicative of more runs than expected for a random series. The sign of the test statistic can also be informative, as too few runs can be sometimes indicative of mean-reverting behavior.
• CONCLUSION
The Intrabar Run Count Indicator can be a useful tool for traders seeking to exploit market inefficiencies and gain a better understanding of price action within each chart bar. However, it is important to note that the runs test only evaluates the distributional properties of the data and does not provide any information on the underlying causes of the non-randomness detected. Additionally, like any statistical test, it can sometimes produce false-positive signals. Therefore, this indicator should be used in conjunction with other analytical techniques as part of a trading strategy.
3D Engine OverlayThe Overlay 3D Engine is an advanced and innovative indicator designed to render 3D objects on a trading chart using Pine Script language. This tool enables users to visualize complex geometric shapes and structures on their charts, providing a unique perspective on market trends and data. It is recommended to use this indicator with a time frame of 1 week or greater.
The code defines various data structures, such as vectors, faces, meshes, locations, objects, and cameras, to represent the 3D objects and their position in the 3D space. It also provides a set of functions to manipulate these structures, such as scaling, rotating, and translating the objects, as well as calculating their perspective transformation based on a given camera.
The main function, "render," takes a list of 3D objects (the scene) and a camera as input, processes the scene, and then generates the corresponding 2D lines to be drawn on the chart. The true range of the asset's price is calculated using an Exponential Moving Average (EMA), which helps adjust the rendering based on the asset's volatility.
The perspective transformation function "perspective_transform" takes a mesh, a camera, an object's vertical offset, and the true range as input and computes the 2D coordinates for each vertex in the mesh. These coordinates are then used to create a list of polygons that represent the visible faces of the objects in the scene.
The "process_scene" function takes a list of 3D objects and a camera as input and applies the perspective transformation to each object in the scene, generating a list of 2D polygons that represent the visible faces of the objects.
Finally, the "render" function iterates through the list of 2D polygons and draws the corresponding lines on the chart, effectively rendering the 3D objects in a 2D projection on the trading chart. The rendering is done using Pine Script's built-in "line" function, which allows for scalable and efficient visualization of the objects.
One of the challenges faced while developing the Overlay 3D Engine indicator was ensuring that the 3D objects rendered on the chart would automatically scale correctly for different time frames and trading pairs. Various assets and time frames exhibit different price ranges and volatilities, which can make it difficult to create a one-size-fits-all solution for rendering the 3D objects in a visually appealing and easily interpretable manner.
To overcome this challenge, I implemented a dynamic scaling mechanism that leverages the true range of the asset's price and a calculated ratio. The true range is calculated using an Exponential Moving Average (EMA) of the difference between the high and low prices of the asset. This measure provides a smooth estimate of the asset's volatility, which is then used to adjust the scaling of the 3D objects rendered on the chart.
The ratio is calculated by dividing the asset's opening price by the true range, which is then divided by a constant factor (32 in this case). This ratio effectively normalizes the scaling of the 3D objects based on the asset's price and volatility, ensuring that the rendered objects appear correctly sized and positioned on the chart, regardless of the time frame or trading pair being analyzed.
By incorporating the true range and the calculated ratio into the rendering process, the Overlay 3D Engine indicator is able to automatically adjust the scaling of the 3D objects on the chart, providing a consistent and visually appealing representation of the objects across various time frames and trading pairs. This dynamic scaling mechanism enhances the overall utility and versatility of the indicator, making it a valuable tool for traders and analysts seeking a unique perspective on market trends.
In addition to the dynamic scaling mechanism mentioned earlier, the Overlay 3D Engine indicator also employs a sophisticated perspective transformation to render the 3D objects on the chart. Perspective transformation is an essential aspect of 3D graphics, as it provides the necessary conversion from 3D coordinates to 2D coordinates, allowing the 3D objects to be displayed on a 2D chart.
The perspective transformation process in the Overlay 3D Engine indicator begins by taking the 3D mesh data of the objects and transforming their vertices based on the position, orientation, and field of view of a virtual camera. The camera's field of view (FOV) is adjusted using a tangent function, which ensures that the rendered objects appear with the correct perspective, regardless of the chart's aspect ratio.
Once the vertices of the 3D objects have been transformed, the perspective-transformed 2D coordinates are then used to create polygons that can be rendered on the chart. These polygons represent the visible faces of the 3D objects and are drawn using lines that connect the transformed vertices.
The incorporation of perspective transformation in the Overlay 3D Engine indicator ensures that the 3D objects are rendered with a realistic appearance, providing a visually engaging and informative representation of the market trends. This technique, combined with the dynamic scaling mechanism, makes the Overlay 3D Engine indicator a powerful and innovative tool for traders and analysts seeking to visualize and interpret market data in a unique and insightful manner.
In summary, the Overlay 3D Engine indicator offers a novel way to interpret and visualize market data, enhancing the overall trading experience by providing a unique perspective on market trends.
Adaptive Candlestick Pattern Recognition System█ INTRODUCTION
Nearly three years in the making, intermittently worked on in the few spare hours of weekends and time off, this is a passion project I undertook to flesh out my skills as a computer programmer. This script currently recognizes 85 different candlestick patterns ranging from one to five candles in length. It also performs statistical analysis on those patterns to determine prior performance and changes the coloration of those patterns based on that performance. In searching TradingView's script library for scripts similar to this one, I had found a handful. However, when I reviewed the ones which were open source, I did not see many that truly captured the power of PineScrypt or leveraged the way it works to create efficient and reliable code; one of the main driving factors for releasing this 5,000+ line behemoth open sourced.
Please take the time to review this description and source code to utilize this script to its fullest potential.
█ CONCEPTS
This script covers the following topics: Candlestick Theory, Trend Direction, Higher Timeframes, Price Analysis, Statistic Analysis, and Code Design.
Candlestick Theory - This script focuses solely on the concept of Candlestick Theory: arrangements of candlesticks may form certain patterns that can potentially influence the future price action of assets which experience those patterns. A full list of patterns (grouped by pattern length) will be in its own section of this description. This script contains two modes of operation for identifying candlestick patterns, 'CLASSIC' and 'BREAKOUT'.
CLASSIC: In this mode, candlestick patterns will be identified whenever they appear. The user has a wide variety of inputs to manipulate that can change how certain patterns are identified and even enable alerts to notify themselves when these patterns appear. Each pattern selected to appear will have their Profit or Loss (P/L) calculated starting from the first candle open succeeding the pattern to a candle close specified some number of candles ahead. These P/L calculations are then collected for each pattern, and split among partitions of prior price action of the asset the script is currently applied to (more on that in Higher Timeframes ).
BREAKOUT: In this mode, P/L calculations are held off until a breakout direction has been confirmed. The user may specify the number of candles ahead of a pattern's appearance (from one to five) that a pattern has to confirm a breakout in either an upward or downward direction. A breakout is constituted when there is a candle following the appearance of the pattern that closes above/at the highest high of the pattern, or below/at its lowest low. Only then will percent return calculations be performed for the pattern that's been identified, and these percent returns are broken up not only by the partition they had appeared in but also by the breakout direction itself. Patterns which do not breakout in either direction will be ignored, along with having their labels deleted.
In both of these modes, patterns may be overridden. Overrides occur when a smaller pattern has been detected and ends up becoming one (or more) of the candles of a larger pattern. A key example of this would be the Bearish Engulfing and the Three Outside Down patterns. A Three Outside Down necessitates a Bearish Engulfing as the first two candles in it, while the third candle closes lower. When a pattern is overridden, the return for that pattern will no longer be tracked. Overrides will not occur if the tail end of a larger pattern occurs at the beginning of a smaller pattern (Ex: a Bullish Engulfing occurs on the third candle of a Three Outside Down and the candle immediately following that pattern, the Three Outside Down pattern will not be overridden).
Important Functionality Note: These patterns are only searched for at the most recently closed candle, not on the currently closing candle, which creates an offset of one for this script's execution. (SEE LIMITATIONS)
Trend Direction - Many of the patterns require a trend direction prior to their appearance. Noting TradingView's own publication of candlestick patterns, I utilize a similar method for determining trend direction. Moving Averages are used to determine which trend is currently taking place for candlestick patterns to be sought out. The user has access to two Moving Averages which they may individually modify the following for each: Moving Average type (list of 9), their length, width, source values, and all variables associated with two special Moving Averages (Least Squares and Arnaud Legoux).
There are 3 settings for these Moving Averages, the first two switch between the two Moving Averages, and the third uses both. When using individual Moving Averages, the user may select a 'price point' to compare against the Moving Average (default is close). This price point is compared to the Moving Average at the candles prior to the appearance of candle patterns. Meaning: The close compared to the Moving Average two candles behind determines the trend direction used for Candlestick Analysis of one candle patterns; three candles behind for two candle patterns and so on. If the selected price point is above the Moving Average, then the current trend is an 'uptrend', 'downtrend' otherwise.
The third setting using both Moving Averages will compare the lengths of each, and trend direction is determined by the shorter Moving Average compared to the longer one. If the shorter Moving Average is above the longer, then the current trend is an 'uptrend', 'downtrend' otherwise. If the lengths of the Moving Averages are the same, or both Moving Averages are Symmetrical, then MA1 will be used by default. (SEE LIMITATIONS)
Higher Timeframes - This script employs the use of Higher Timeframes with a few request.security calls. The purpose of these calls is strictly for the partitioning of an asset's chart, splitting the returns of patterns into three separate groups. The four inputs in control of this partitioning split the chart based on: A given resolution to grab values from, the length of time in that resolution, and 'Upper' and 'Lower Limits' which split the trading range provided by that length of time in that resolution that forms three separate groups. The default values for these four inputs will partition the current chart by the yearly high-low range where: the 'Upper' partition is the top 20% of that trading range, the 'Middle' partition is 80% to 33% of the trading range, and the 'Lower' partition covers the trading range within 33% of the yearly low.
Patterns which are identified by this script will have their returns grouped together based on which partition they had appeared in. For example, a Bullish Engulfing which occurs within a third of the yearly low will have its return placed separately from a Bullish Engulfing that occurred within 20% of the yearly high. The idea is that certain patterns may perform better or worse depending on when they had occurred during an asset's trading range.
Price Analysis - Price Analysis is a major part of this script's functionality as it can fundamentally change how patterns are shown to the user. The settings related to Price Analysis include setting the number of candles ahead of a pattern's appearance to determine the return of that pattern. In 'BREAKOUT' mode, an additional setting allows the user to specify where the P/L calculation will begin for a pattern that had appeared and confirmed. (SEE LIMITATIONS)
The calculation for percent returns of patterns is illustrated with the following pseudo-code (CLASSIC mode, this is a simplified version of the actual code):
type patternObj
int ID
int partition
type returnsArray
float returns
// No pattern found = na returned
patternObj TEST_VAL = f_FindPattern()
priorTestVal = TEST_VAL
if not na( priorTestVal )
pnlMatrixRow = priorTestVal.ID
pnlMatrixCol = priorTestVal.partition
matrixReturn = matrix.get(PERCENT_RETURNS, pnlMatrixRow, pnlMatrixCol)
percentReturn = ( (close - open ) / open ) * 100%
array.push(matrixReturn.returns, percentReturn)
Statistic Analysis - This script uses Pine's built-in array functions to conduct the Statistic Analysis for patterns. When a pattern is found and its P/L calculation is complete, its return is added to a 'Return Array' User-Defined-Type that contains numerous fields which retain information on a pattern's prior performance. The actual UDT is as follows:
type returnArray
float returns = na
int size = 0
float avg = 0
float median = 0
float stdDev = 0
int polarities = na
All values within this UDT will be updated when a return is added to it (some based on user input). The array.avg , array.median and array.stdev will be ran and saved into their respective fields after a return is placed in the 'returns' array. The 'polarities' integer array is what will be changed based on user input. The user specifies two different percentages that declare 'Positive' and 'Negative' returns for patterns. When a pattern returns above, below, or in between these two values, different indices of this array will be incremented to reflect the kind of return that pattern had just experienced.
These values (plus the full name, partition the pattern occurred in, and a 95% confidence interval of expected returns) will be displayed to the user on the tooltip of the labels that identify patterns. Simply scroll over the pattern label to view each of these values.
Code Design - Overall this script is as much of an art piece as it is functional. Its design features numerous depictions of ASCII Art that illustrate what is being attempted by the functions that identify patterns, and an incalculable amount of time was spent rewriting portions of code to improve its efficiency. Admittedly, this final version is nearly 1,000 lines shorter than a previous version (one which took nearly 30 seconds after compilation to run, and didn't do nearly half of what this version does). The use of UDTs, especially the 'patternObj' one crafted and redesigned from the Hikkake Hunter 2.0 I published last month, played a significant role in making this script run efficiently. There is a slight rigidity in some of this code mainly around pattern IDs which are responsible for displaying the abbreviation for patterns (as well as the full names under the tooltips, and the matrix row position for holding returns), as each is hard-coded to correspond to that pattern.
However, one thing I would like to mention is the extensive use of global variables for pattern detection. Many scripts I had looked over for ideas on how to identify candlestick patterns had the same idea; break the pattern into a set of logical 'true/false' statements derived from historically referencing candle OHLC values. Some scripts which identified upwards of 20 to 30 patterns would reference Pine's built-in OHLC values for each pattern individually, potentially requesting information from TradingView's servers numerous times that could easily be saved into a variable for re-use and only requested once per candle (what this script does).
█ FEATURES
This script features a massive amount of switches, options, floating point values, detection settings, and methods for identifying/tailoring pattern appearances. All modifiable inputs for patterns are grouped together based on the number of candles they contain. Other inputs (like those for statistics settings and coloration) are grouped separately and presented in a way I believe makes the most sense.
Not mentioned above is the coloration settings. One of the aims of this script was to make patterns visually signify their behavior to the user when they are identified. Each pattern has its own collection of returns which are analyzed and compared to the inputs of the user. The user may choose the colors for bullish, neutral, and bearish patterns. They may also choose the minimum number of patterns needed to occur before assigning a color to that pattern based on its behavior; a color for patterns that have not met this minimum number of occurrences yet, and a color for patterns that are still processing in BREAKOUT mode.
There are also an additional three settings which alter the color scheme for patterns: Statistic Point-of-Reference, Adaptive coloring, and Hard Limiting. The Statistic Point-of-Reference decides which value (average or median) will be compared against the 'Negative' and 'Positive Return Tolerance'(s) to guide the coloration of the patterns (or for Adaptive Coloring, the generation of a color gradient).
Adaptive Coloring will have this script produce a gradient that patterns will be colored along. The more bullish or bearish a pattern is, the further along the gradient those patterns will be colored starting from the 'Neutral' color (hard lined at the value of 0%: values above this will be colored bullish, bearish otherwise). When Adaptive Coloring is enabled, this script will request the highest and lowest values (these being the Statistic Point-of-Reference) from the matrix containing all returns and rewrite global variables tied to the negative and positive return tolerances. This means that all patterns identified will be compared with each other to determine bullish/bearishness in Adaptive Coloring.
Hard Limiting will prevent these global variables from being rewritten, so patterns whose Statistic Point-of-Reference exceed the return tolerances will be fully colored the bullish or bearish colors instead of a generated gradient color. (SEE LIMITATIONS)
Apart from the Candle Detection Modes (CLASSIC and BREAKOUT), there's an additional two inputs which modify how this script behaves grouped under a "MASTER DETECTION SETTINGS" tab. These two "Pattern Detection Settings" are 'SWITCHBOARD' and 'TARGET MODE'.
SWITCHBOARD: Every single pattern has a switch that is associated with its detection. When a switch is enabled, the code which searches for that pattern will be run. With the Pattern Detection Setting set to this, all patterns that have their switches enabled will be sought out and shown.
TARGET MODE: There is an additional setting which operates on top of 'SWITCHBOARD' that singles out an individual pattern the user specifies through a drop down list. The names of every pattern recognized by this script will be present along with an identifier that shows the number of candles in that pattern (Ex: " (# candles)"). All patterns enabled in the switchboard will still have their returns measured, but only the pattern selected from the "Target Pattern" list will be shown. (SEE LIMITATIONS)
The vast majority of other features are held in the one, two, and three candle pattern sections.
For one-candle patterns, there are:
3 — Settings related to defining 'Tall' candles:
The number of candles to sample for previous candle-size averages.
The type of comparison done for 'Tall' Candles: Settings are 'RANGE' and 'BODY'.
The 'Tolerance' for tall candles, specifying what percent of the 'average' size candles must exceed to be considered 'Tall'.
When 'Tall Candle Setting' is set to RANGE, the high-low ranges are what the current candle range will be compared against to determine if a candle is 'Tall'. Otherwise the candle bodies (absolute value of the close - open) will be compared instead. (SEE LIMITATIONS)
Hammer Tolerance - How large a 'discarded wick' may be before it disqualifies a candle from being a 'Hammer'.
Discarded wicks are compared to the size of the Hammer's candle body and are dependent upon the body's center position. Hammer bodies closer to the high of the candle will have the upper wick used as its 'discarded wick', otherwise the lower wick is used.
9 — Doji Settings, some pulled from an old Doji Hunter I made a while back:
Doji Tolerance - How large the body of a candle may be compared to the range to be considered a 'Doji'.
Ignore N/S Dojis - Turns off Trend Direction for non-special Dojis.
GS/DF Doji Settings - 2 Inputs that enable and specify how large wicks that typically disqualify Dojis from being 'Gravestone' or 'Dragonfly' Dojis may be.
4 Settings related to 'Long Wick Doji' candles detailed below.
A Tolerance for 'Rickshaw Man' Dojis specifying how close the center of the body must be to the range to be valid.
The 4 settings the user may modify for 'Long Legged' Dojis are: A Sample Base for determining the previous average of wicks, a Sample Length specifying how far back to look for these averages, a Behavior Setting to define how 'Long Legged' Dojis are recognized, and a tolerance to specify how large in comparison to the prior wicks a Doji's wicks must be to be considered 'Long Legged'.
The 'Sample Base' list has two settings:
RANGE: The wicks of prior candles are compared to their candle ranges and the 'wick averages' will be what the average percent of ranges were in the sample.
WICKS: The size of the wicks themselves are averaged and returned for comparing against the current wicks of a Doji.
The 'Behavior' list has three settings:
ONE: Only one wick length needs to exceed the average by the tolerance for a Doji to be considered 'Long Legged'.
BOTH: Both wick lengths need to exceed the average of the tolerance of their respective wicks (upper wicks are compared to upper wicks, lower wicks compared to lower) to be considered 'Long Legged'.
AVG: Both wicks and the averages of the previous wicks are added together, divided by two, and compared. If the 'average' of the current wicks exceeds this combined average of prior wicks by the tolerance, then this would constitute a valid 'Long Legged' Doji. (For Dojis in general - SEE LIMITATIONS)
The final input is one related to candle patterns which require a Marubozu candle in them. The two settings for this input are 'INCLUSIVE' and 'EXCLUSIVE'. If INCLUSIVE is selected, any opening/closing variant of Marubozu candles will be allowed in the patterns that require them.
For two-candle patterns, there are:
2 — Settings which define 'Engulfing' parameters:
Engulfing Setting - Two options, RANGE or BODY which sets up how one candle may 'engulf' the previous.
Inclusive Engulfing - Boolean which enables if 'engulfing' candles can be equal to the values needed to 'engulf' the prior candle.
For the 'Engulfing Setting':
RANGE: If the second candle's high-low range completely covers the high-low range of the prior candle, this is recognized as 'engulfing'.
BODY: If the second candle's open-close completely covers the open-close of the previous candle, this is recognized as 'engulfing'. (SEE LIMITATIONS)
4 — Booleans specifying different settings for a few patterns:
One which allows for 'opens within body' patterns to let the second candle's open/close values match the prior candles' open/close.
One which forces 'Kicking' patterns to have a gap if the Marubozu setting is set to 'INCLUSIVE'.
And Two which dictate if the individual candles in 'Stomach' patterns need to be 'Tall'.
8 — Floating point values which affect 11 different patterns:
One which determines the distance the close of the first candle in a 'Hammer Inverted' pattern must be to the low to be considered valid.
One which affects how close the opens/closes need to be for all 'Lines' patterns (Bull/Bear Meeting/Separating Lines).
One that allows some leeway with the 'Matching Low' pattern (gives a small range the second candle close may be within instead of needing to match the previous close).
Three tolerances for On Neck/In Neck patterns (2 and 1 respectively).
A tolerance for the Thrusting pattern which give a range the close the second candle may be between the midpoint and close of the first to be considered 'valid'.
A tolerance for the two Tweezers patterns that specifies how close the highs and lows of the patterns need to be to each other to be 'valid'.
The first On Neck tolerance specifies how large the lower wick of the first candle may be (as a % of that candle's range) before the pattern is invalidated. The second tolerance specifies how far up the lower wick to the close the second candle's close may be for this pattern. The third tolerance for the In Neck pattern determines how far into the body of the first candle the second may close to be 'valid'.
For the remaining patterns (3, 4, and 5 candles), there are:
3 — Settings for the Deliberation pattern:
A boolean which forces the open of the third candle to gap above the close of the second.
A tolerance which changes the proximity of the third candle's open to the second candle's close in this pattern.
A tolerance that sets the maximum size the third candle may be compared to the average of the first two candles.
One boolean value for the Two Crows patterns (standard and Upside Gapping) that forces the first two candles in the patterns to completely gap if disabled (candle 1's close < candle 2's low).
10 — Floating point values for the remaining patterns:
One tolerance for defining how much the size of each candle in the Identical Black Crows pattern may deviate from the average of themselves to be considered valid.
One tolerance for setting how close the opens/closes of certain three candle patterns may be to each other's opens/closes.*
Three floating point values that affect the Three Stars in the South pattern.
One tolerance for the Side-by-Side patterns - looks at the second and third candle closes.
One tolerance for the Stick Sandwich pattern - looks at the first and third candle closes.
A floating value that sizes the Concealing Baby Swallow pattern's 3rd candle wick.
Two values for the Ladder Bottom pattern which define a range that the third candle's wick size may be.
* This affects the Three Black Crows (non-identical) and Three White Soldiers patterns, each require the opens and closes of every candle to be near each other.
The first tolerance of the Three Stars in the South pattern affects the first candle body's center position, and defines where it must be above to be considered valid. The second tolerance specifies how close the second candle must be to this same position, as well as the deviation the ratio the candle body to its range may be in comparison to the first candle. The third restricts how large the second candle range may be in comparison to the first (prevents this pattern from being recognized if the second candle is similar to the first but larger).
The last two floating point values define upper and lower limits to the wick size of a Ladder Bottom's fourth candle to be considered valid.
█ HOW TO USE
While there are many moving parts to this script, I attempted to set the default values with what I believed may help identify the most patterns within reasonable definitions. When this script is applied to a chart, the Candle Detection Mode (along with the BREAKOUT settings) and all candle switches must be confirmed before patterns are displayed. All switches are on by default, so this gives the user an opportunity to pick which patterns to identify first before playing around in the settings.
All of the settings/inputs described above are meant for experimentation. I encourage the user to tweak these values at will to find which set ups work best for whichever charts they decide to apply these patterns to.
Refer to the patterns themselves during experimentation. The statistic information provided on the tooltips of the patterns are meant to help guide input decisions. The breadth of candlestick theory is deep, and this was an attempt at capturing what I could in its sea of information.
█ LIMITATIONS
DISCLAIMER: While it may seem a bit paradoxical that this script aims to use past performance to potentially measure future results, past performance is not indicative of future results . Markets are highly adaptive and often unpredictable. This script is meant as an informational tool to show how patterns may behave. There is no guarantee that confidence intervals (or any other metric measured with this script) are accurate to the performance of patterns; caution must be exercised with all patterns identified regardless of how much information regarding prior performance is available.
Candlestick Theory - In the name, Candlestick Theory is a theory , and all theories come with their own limits. Some patterns identified by this script may be completely useless/unprofitable/unpredictable regardless of whatever combination of settings are used to identify them. However, if I truly believed this theory had no merit, this script would not exist. It is important to understand that this is a tool meant to be utilized with an array of others to procure positive (or negative, looking at you, short sellers ) results when navigating the complex world of finance.
To address the functionality note however, this script has an offset of 1 by default. Patterns will not be identified on the currently closing candle, only on the candle which has most recently closed. Attempting to have this script do both (offset by one or identify on close) lead to more trouble than it was worth. I personally just want users to be aware that patterns will not be identified immediately when they appear.
Trend Direction - Moving Averages - There is a small quirk with how MA settings will be adjusted if the user inputs two moving averages of the same length when the "MA Setting" is set to 'BOTH'. If Moving Averages have the same length, this script will default to only using MA 1 regardless of if the types of Moving Averages are different . I will experiment in the future to alleviate/reduce this restriction.
Price Analysis - BREAKOUT mode - With how identifying patterns with a look-ahead confirmation works, the percent returns for patterns that break out in either direction will be calculated on the same candle regardless of if P/L Offset is set to 'FROM CONFIRMATION' or 'FROM APPEARANCE'. This same issue is present in the Hikkake Hunter script mentioned earlier. This does not mean the P/L calculations are incorrect , the offset for the calculation is set by the number of candles required to confirm the pattern if 'FROM APPEARANCE' is selected. It just means that these two different P/L calculations will complete at the same time independent of the setting that's been selected.
Adaptive Coloring/Hard Limiting - Hard Limiting is only used with Adaptive Coloring and has no effect outside of it. If Hard Limiting is used, it is recommended to increase the 'Positive' and 'Negative' return tolerance values as a pattern's bullish/bearishness may be disproportionately represented with the gradient generated under a hard limit.
TARGET MODE - This mode will break rules regarding patterns that are overridden on purpose. If a pattern selected in TARGET mode would have otherwise been absorbed by a larger pattern, it will have that pattern's percent return calculated; potentially leading to duplicate returns being included in the matrix of all returns recognized by this script.
'Tall' Candle Setting - This is a wide-reaching setting, as approximately 30 different patterns or so rely on defining 'Tall' candles. Changing how 'Tall' candles are defined whether by the tolerance value those candles need to exceed or by the values of the candle used for the baseline comparison (RANGE/BODY) can wildly affect how this script functions under certain conditions. Refer to the tooltip of these settings for more information on which specific patterns are affected by this.
Doji Settings - There are roughly 10 or so two to three candle patterns which have Dojis as a part of them. If all Dojis are disabled, it will prevent some of these larger patterns from being recognized. This is a dependency issue that I may address in the future.
'Engulfing' Setting - Functionally, the two 'Engulfing' settings are quite different. Because of this, the 'RANGE' setting may cause certain patterns that would otherwise be valid under textbook and online references/definitions to not be recognized as such (like the Upside Gap Two Crows or Three Outside down).
█ PATTERN LIST
This script recognizes 85 patterns upon initial release. I am open to adding additional patterns to it in the future and any comments/suggestions are appreciated. It recognizes:
15 — 1 Candle Patterns
4 Hammer type patterns: Regular Hammer, Takuri Line, Shooting Star, and Hanging Man
9 Doji Candles: Regular Dojis, Northern/Southern Dojis, Gravestone/Dragonfly Dojis, Gapping Up/Down Dojis, and Long-Legged/Rickshaw Man Dojis
White/Black Long Days
32 — 2 Candle Patterns
4 Engulfing type patterns: Bullish/Bearish Engulfing and Last Engulfing Top/Bottom
Dark Cloud Cover
Bullish/Bearish Doji Star patterns
Hammer Inverted
Bullish/Bearish Haramis + Cross variants
Homing Pigeon
Bullish/Bearish Kicking
4 Lines type patterns: Bullish/Bearish Meeting/Separating Lines
Matching Low
On/In Neck patterns
Piercing pattern
Shooting Star (2 Lines)
Above/Below Stomach patterns
Thrusting
Tweezers Top/Bottom patterns
Two Black Gapping
Rising/Falling Window patterns
29 — 3 Candle Patterns
Bullish/Bearish Abandoned Baby patterns
Advance Block
Collapsing Doji Star
Deliberation
Upside/Downside Gap Three Methods patterns
Three Inside/Outside Up/Down patterns (4 total)
Bullish/Bearish Side-by-Side patterns
Morning/Evening Star patterns + Doji variants
Stick Sandwich
Downside/Upside Tasuki Gap patterns
Three Black Crows + Identical variation
Three White Soldiers
Three Stars in the South
Bullish/Bearish Tri-Star patterns
Two Crows + Upside Gap variant
Unique Three River Bottom
3 — 4 Candle Patterns
Concealing Baby Swallow
Bullish/Bearish Three Line Strike patterns
6 — 5 Candle Patterns
Bullish/Bearish Breakaway patterns
Ladder Bottom
Mat Hold
Rising/Falling Three Methods patterns
█ WORKS CITED
Because of the amount of time needed to complete this script, I am unable to provide exact dates for when some of these references were used. I will also not provide every single reference, as citing a reference for each individual pattern and the place it was reviewed would lead to a bibliography larger than this script and its description combined. There were five major resources I used when building this script, one book, two websites (for various different reasons including patterns, moving averages, and various other articles of information), various scripts from TradingView's public library (including TradingView's own source code for *all* candle patterns ), and PineScrypt's reference manual.
Bulkowski, Thomas N. Encyclopedia of Candlestick Patterns . Hoboken, New Jersey: John Wiley & Sons Inc., 2008. E-book (google books).
Various. Numerous webpages. CandleScanner . 2023. online. Accessed 2020 - 2023.
Various. Numerous webpages. Investopedia . 2023. online. Accessed 2020 - 2023.
█ AKNOWLEDGEMENTS
I want to take the time here to thank all of my friends and family, both online and in real life, for the support they've given me over the last few years in this endeavor. My pets who tried their hardest to keep me from completing it. And work for the grit to continue pushing through until this script's completion.
This belongs to me just as much as it does anyone else. Whether you are an institutional trader, gold bug hedging against the dollar, retail ape who got in on a squeeze, or just parents trying to grow their retirement/save for the kids. This belongs to everyone.
Private Beta for new features to be tested can be found here .
Vires In Numeris
Volume / Open Interest "Footprint" - By LeviathanThis script generates a footprint-style bar (profile) based on the aggregated volume or open interest data within your chart's visible range. You can choose from three different heatmap visualizations: Volume Delta/OI Delta, Total Volume/Total OI, and Buy vs. Sell Volume/OI Increase vs. Decrease.
How to use the indicator:
1. Add it to your chart.
2. The script will use your chart's visible range and generate a footprint bar on the right side of the screen. You can move left/right, zoom in/zoom out, and the bar's data will be updated automatically.
Settings:
- Source: This input lets you choose the data that will be displayed in the footprint bar.
- Resolution: Resolution is the number of rows displayed in a bar. Increasing it will provide more granular data, and vice versa. You might need to decrease the resolution when viewing larger ranges.
- Type: Choose between 3 types of visualization: Total (Total Volume or Total Open Interest increase), UP/DOWN (Buy Volume vs Sell Volume or OI Increase vs OI Decrease), and Delta (Buy Volume - Sell Volume or OI Increase - OI Decrease).
- Positive Delta Levels: This function will draw boxes (levels) where Delta is positive. These levels can serve as significant points of interest, S/R, targets, etc., because they mark the zones where there was an increase in buy pressure/position opening.
- Volume Aggregation: You can aggregate volume data from 8 different sources. Make sure to check if volume data is reported in base or quote currency and turn on the RQC (Reported in Quote Currency) function accordingly.
- Other settings mostly include appearance inputs. Read the tooltips for more info.
Stochastic Momentum Index (SMI) of Money Flow Index (MFI)"He who does not know how to make predictions and makes light of his opponents, underestimating his ability, will certainly be defeated by them."
(Sun Tzu - The Art of War)
▮ Introduction
The Stochastic Momentum Index (SMI) is a technical analysis indicator that uses the difference between the current closing price and the high or low price over a specific time period to measure price momentum.
On the other hand, the Money Flow Index (MFI) is an indicator that uses volume and price to measure buying and selling pressure.
When these two indicators are combined, they can provide a more comprehensive view of price direction and market strength.
▮ Improvements
By combining SMI with MFI, we can gain even more insights into the market. One way to do this is to use the MFI as an input to the SMI, rather than just using price.
This means we are measuring momentum based on buying and selling pressure rather than just price.
Another way to improve this indicator is to adjust the periods to suit your specific trading needs.
▮ What to look
When using the SMI MFI indicator, there are a few things to look out for.
First, look at the SMI signal line.
When the line crosses above -40, it is considered a buy signal, while the crossing below +40 is considered a sell signal.
Also, pay attention to divergences between the SMI MFI and the price.
If price is rising but the SMI MFI is showing negative divergence, it could indicate that momentum is waning and a reversal could be in the offing.
Likewise, if price is falling but the SMI MFI is showing positive divergence, this could indicate that momentum is building and a reversal could also be in the offing.
In the examples below, I show the use in conjunction with the price SMI, in which the MFI SMI helps to anticipate divergences:
In summary, the SMI MFI is a useful indicator that can provide valuable insights into market direction and price strength.
By adjusting the timeframes and paying attention to divergences and signal line crossovers, traders can use it as part of a broader trading strategy.
However, remember that no indicator is a magic bullet and should always be used in conjunction with other analytics and indicators to make informed trading decisions.
Modified Mannarino Market Risk Indicator MMMRI MMRIModified Mannarino Market Risk Indicator MMMRI was developed by "Nobody Special Finance" as an enhancement to the original MMRI developed by Gregory Mannarino. The original and modified version were created as a way to gauge current level of risk in the market. This published indicator includes both versions along with ability to customize the symbols, denominators, and ratio factors that are used within their formulas. Additional options have been included to colorize the candles, plot, and level fills, as well as the option to show or hide a table containing the realtime values for both versions, along with the current dollar strength and 10Y yield.
Levels of market risk are denoted by dashed lines which represent the following levels: 0-50 slight risk, 50-100 low risk, 100-200 moderate risk, 200-300 high risk, 300+ extreme risk. The plot displays whichever of the following two formulas has been selected in the indicator settings, the default choice has been set to MMMRI:
MMRI = (USD Strength * USD Interest Rate) / 1.61
MMMRI = (Debt / GDP) * (USD Strength * USD Interest Rate) / 1.61
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!
RedK EVEREX - Effort Versus Results ExplorerRedK EVEREX is an experimental indicator that explores "Volume Price Analysis" basic concepts and Wyckoff law "Effort versus Result" - by inspecting the relative volume (effort) and the associated (relative) price action (result) for each bar - showing the analysis as an easy to read "stacked bands" visual. From that analysis, we calculate a "Relative Rate of Flow" - an easy to use +100/-100 oscilator that can be used to trigger a signal when a bullish or bearish mode is detected for a certain user-selected length of bars.
Basic Concepts of VPA
-------------------------------
(The topics of VPA & Wyckoff Effort vs Results law are too comprehensive to cover here - So here's just a very basic summary - please review these topics in detail in various sources available here in TradingView or on the web)
* Volume Price Analysis (VPA) is the examination of the number of shares or contracts of a security that have been traded in a given period, and the associated price movement. By analyzing trends in volume in conjunction with price movements, traders can determine the significance of changes in price and what may unfold in the near future.
* Oftentimes, high volumes of trading can infer a lot about investors’ outlook on a market or security. A significant price increase along with a significant volume increase, for example, could be a credible sign of a continued bullish trend or a bullish reversal. Adversely, a significant price decrease with a significant volume increase can point to a continued bearish trend or a bearish trend reversal.
* Incorporating volume into a trading decision can help an investor to have a more balanced view of all the broad market factors that could be influencing a security’s price, which helps an investor to make a more informed decision.
* Wyckoff's law "Effort versus results" dictates that large effort is expected to be accompanied with big results - which means that we should expect to see a big price move (result) associated with a large relative volume (effort) for a certain trading period (bar).
* The way traders use this concept in chart analysis is to mainly look for imbalances or invalidation. for example, when we observe a large relative volume that is associated with very limited price change - that should trigger an early flag/warning sign that the current price trend is facing challenges and may be an early sign of "reversal" - this applies in both bearish and bullish conditions. on the other hand, when price starts to trend in a certain direction and that's associated with increasing volume, that can act as kind of validation, or a confirmation that the market supports that move.
How does EVEREX work
---------------------------------
* EVEREX inspects each bar and calculates a relative value for volume (effort) and "strength of price movement" (result) compared to a specified lookback period. The results are then visualized as stacked bands - the lower band represents the relative volume, the upper band represents the relative price strength - with clear color coding for easier analysis.
* The scale of the band is initially set to 100 (each band can occupy up to 50) - and that can be changed in the settings to 200 or 400 - mainly to allow a "zoom in" on the bands.
* Reading the resulting stacked bands makes it easier to see "balanced" volume/price action (where both bands are either equally strong, or equally weak), or when there's imbalance between volume and price (for example, a compression bar will show with high volume band and very small/tiny price action band) - another favorite pattern in VPA is the "Ease of Move", which will show as a relatively small volume band associated with a large "price action band" (either bullish or bearish) .. and so on.
* a bit of a techie piece: why the use of a custom "Normalize()" function to calculate "relative" values in EVEREX?
When we evaluate a certain value against an average (for example, volume) we need a mechanism to deal with "super high" values that largely exceed that average - I also needed a mechanism that mimics how a trader looks at a volume bar and decides that this volume value is super low, low, average, above average, high or super high -- the issue with using a stoch() function, which is the usual technique for comparing a data point against a lookback average, is that this function will produce a "zero" for low values, and cause a large distortion of the next few "ratios" when super large values occur in the data series - i researched multiple techniques here and decided to use the custom Normalize() function - and what i found is, as long as we're applying the same formula consistently to the data series, since it's all relative to itself, we can confidently use the result. Please feel free to play around with this part further if you like - the code is commented for those who would like to research this further.
* Overall, the hope is to make the bar-by-bar analysis easier and faster for traders who apply VPA concepts in their trading
What is RROF?
--------------------------
* Once we have the values of relative volume and relative price strength, it's easy from there to combine these values into a moving index that can be used to track overall strength and detect reversals in market direction - if you think about it this a very similar concept to a volume-weighted RSI. I call that index the "Relative Rate of Flow" - or RROF (cause we're not using the direct volume and price values in the calculation, but rather relative values that we calculated with the proprietary "Normalize" function in the script.
* You can show RROF as a single or double-period - and you can customize it in terms of smoothing, and signal line - and also utilize the basic alerts to get notified when a change in strength from one side to the other (bullish vs bearish) is detected
* In the chart above, you can see how the RROF was able to detect change in market condition from Bearsh to Bullish - then from Bullish to Bearish for TSLA with good accuracy.
Other Usage Options in EVEREX
------------------------------------
* I wrote EVEREX with a lot of flexibility and utilization in mind, while focusing on a clean and easy to use visual - EVEREX should work with any time frame and any instrument - in instruments with no volume data, only price data will be used.
* You can completely hide the "EVEREX bands" and use EVEREX as a single or dual period strength indicator (by exposing the Bias/Sentiment plot which is hidden by default) -
here's how this setup would look like - in this mode, you will basically be using EVEREX the same way you're using a volume-weighted RSI
* or you can hide the bias/sentiment, and expose the Bulls & Bears plots (using the indicator's "Style" tab), and trade it like a Bull/Bear Pressure Index like this
* you can choose Moving Average type for most plot elements in EVEREX, including how to deal with the Lookback averaging
* you can set EVEREX to a different time frame than the chart
* did i mention basic alerts in this v1.0 ?? There's room to add more VPA-specific alerts in future version (for example, when Ease-of-Move or Compression bars are detected...etc) - let me know if the comments what you want to see
Final Thoughts
--------------------
* EVEREX can be used for bar-by-bar VPA analysis - There are so much literature out there about VPA and it's highly recommended that traders read more about what VPA is and how it works - as it adds an interesting (and critical) dimension to technical analysis and will improve decision making
* RROF is a "strength indicator" - it does not track price values (levels) or momentum - as you will see when you use it, the price can be moving up, while the RROF signal line starts moving down, reflecting decreasing strength (or otherwise, increasing bear strength) - So if you incorporate EVEREX in your trading you will need to use it alongside other momentum and price value indicators (like MACD, MA's, Trend Channels, Support & Resistance Lines, Fib / Donchian..etc) - to use for trade confirmation
Markdown: The Pine Editor's Hidden Gem💬 Markdown, a markup language
Markdown is a portable, lightweight markup language that can be used for everything whether you're building a website, documentation, or even presentations.
Platforms like Discord, Reddit, and GitHub support Markdown and is the widely go-to option for text formatting due to its simplicity. Pine Script is a language that also utilizes Markdown, specifically in the Pine Editor where it can really be used to some extent.
Since the release of libraries, user-defined types, and methods, Pine Script is entering an age where developers will be highly dependent on libraries due to the capabilities Pine has inherited recently. It would be no surprise if a few people got together and took their time to thoroughly develop an entire project/library centered around improving Pine Script's built-in functions and providing developers with easier ways of achieving things than they thought they could.
As you're all aware, hovering over functions (and more) in the editor pops up a prompt that specifies the parameters, types, and what the function returns. Pine Script uses Markdown for that, so I figured we could go ahead and push that feature to its limits and see what we can do.
Today we'll go over how we can utilize Markdown in Pine Script, and how you can make your library's built-in functions stand out more than they did previously.
For more information, visit www.markdownguide.org
📕 General Notes
Markdown syntax only works on functions and methods.
Using arrays as parameters as of 2/21/2023 breaks the Markdown system.
The prompt window holds a max of 166 characters on one line before overflowing.
There is no limit on how long the prompt window can be.
🔽 Getting Started 🔽
▶️ Headings
If you have experience in HTML, Markdown, or even Microsoft Word then you already have a grasp of how headings work and look.
To simplify it, headings make the given text either massive or tiny depending on how many number symbols are provided.
When defining headings, you must have a space between the number (#) symbol, and the text. This is typical syntax throughout the language.
Pine Script uses bold text by applying (**) for their titles on their built-ins (e.g. @returns) but you could also use heading level 4 (####) and have it look the same.
▶️ Paragraphs & Line Breaks
You may want to provide extensive details and examples relating to one function, in this case, you could create line breaks. Creating line breaks skips to the next line so you can keep things organized as a result.
To achieve a valid line break and create a new paragraph, you must end the line with two or more spaces.
If you want to have an empty line in between, apply a backslash (\).
Backslashes (\) are generally not recommended for every line break. In this case, I only recommend using them for empty lines.
▶️ Text Formatting
Markdown provides text formatting such as bold, italics, and strikethrough.
For bolding text, you can apply open and close (**) or (__).
For italicizing text, you can apply open and close (*) or (_).
For bolding and italicizing text, you can apply open and close (***) or (___).
For s̶t̶r̶i̶k̶e̶t̶h̶r̶o̶u̶g̶h̶, you need to apply open and close (~~).
This was mentioned in the Headers section, but Pine Script's main titles (e.g. @returns or @syntax) use bold (**) by default.
▶️ Blockquotes
Blockquotes in Pine Script can be visualized as a built-in indentation system.
They are declared using greater than (>) and everything will be auto-aligned and indented until closed.
By convention you generally want to include the greater than (>) on every line that's included in the block quote. Even when not needed.
If you would like to indent even more (nested blockquotes), you can apply multiple greater than symbols (>). For example, (>>)
Blockquotes can be closed by ending the next line with only one greater than (>) symbol, or by using a horizontal rule.
▶️ Horizontal Rules
Horizontal rules in Pine Script are what you see at the very top of the prompt in built-ins.
When hovering, you can see the top of the prompt provides a line, and we can actually reproduce these lines.
These are extremely useful for separating information into their own parts and are accessed by applying 3 underscores (___), or 3 asterisks (***).
Horizontal rules were mentioned above, when we were discussing block quotes. These can also be used to close blockquotes as well.
Horizontal rules require a minimum of 3 underscores (___) or 3 asterisks (***).
▶️ Lists
Lists give us a way to structure data in a somewhat neat way. There are multiple ways to start a list, such as
1. First Item (number followed by a period)
- First Item (dash)
+ First Item (plus sign)
* First Item (asterisk)
Using number-based lists provide an ordered list, whereas using (-), (+), or (*) will provide an unordered list (bullet points).
If you want to begin an unordered list with a number that ends with a period, you must use an escape sequence (\) after the number.
Standard indentation (tab-width) list detection isn't supported, so to nest lists you have to use blockquotes (>) which may not look as appealing.
▶️ Code Blocks
Using code blocks allows you to write actual Pine Script code inside the prompt.
It's a game changer that can potentially help people understand how to execute functions quickly.
To use code blocks, apply three 3 open and close backquotes (```). Built-in's use (```pine) but there's no difference when we apply it.
Considering that tab-width indentation isn't detected properly, we can make use of the blockquotes mentioned above.
▶️ Denotation
Denoting can also be seen as highlighting a background layer behind text. They're basically code blocks, but without the "block".
Similar to how code blocks work, we apply one backquote open and close (`).
Make sure to only use this on important keywords. There really isn't a conventional way of applying this.
It's up to you to decide what people should have their eyes tracked onto when they hover over your functions.
If needed, look at how Pine Script's built-in variables and functions utilize this.
▶️ Tables
Tables are possible in Markdown, although they may look a bit different in the Pine Editor.
They are made by separating text with vertical bars (|).
The headers are detected when there is a minimum of one hyphen (-) below them.
You can align text by using a colon as I do in the photo. Hyphens must be connected to the colon in order to display correctly.
Tables aren't ideal to use in the editor but are there if anyone wants to give it a go.
▶️ Links & Images
Markdown supports images and hyperlinks, which means we can also do that here in the Pine Editor. Cool right?
If you want to create a hyperlink, surround the displayed text in open and close brackets .
If you want to load a photo into your prompt, it's the same syntax as the hyperlink, except it uses a (!)
See syntax list below.
Here are realistic usage examples. (Snippets from code below)
These follow the same syntax as the built-ins.
I'm not using horizontal rules here, but it's entirely up to you.
▶️ Syntax List
Headings
Level 1: #
Level 2: ##
Level 3: ###
Level 4: ####
Level 5: #####
Level 6: ######
Line Breaks
Text (two spaces)
Text\ (backslash)
Text Formatting
Bold (**)
Italic (**)
Strikethrough (~~)
Blockquotes
Indent (>)
Double Indent (>>)
Triple Indent (>>>) and so on.
Horizontal Rules
(___) or (***)
Lists
Ordered List (1.)
Unordered List (-) or (+) or (*)
Code Blocks
(```) or (```pine)
Denotation
(`)
Tables
(|) and (-) and (:)
Hyperlinks
(URL)
Images
! (URL)
Hope this helps. 👍
Elliott Wave [LuxAlgo]The Elliott Wave indicator allows users to detect Elliott Wave (EW) impulses as well as corrective segments automatically on the chart. These are detected and displayed serially, allowing users to keep track of the evolution of an impulse or corrective wave.
Fibonacci retracements constructed from detected impulse waves are also included.
This script additionally allows users to get alerted on a wide variety of trigger conditions (see the ALERTS section below).
🔶 SETTINGS
🔹 Source
• "high" -> options high, close, maximum of open/close
• "low" -> options low, close, minimum of open/close
🔹 ZigZag
• The source and length are used to check whether a new Pivot Point is found.
Example:
• source = high/low, length = 10:
• There is a new pivot high when:
- previous high is higher than current high
- the highs of 10 bars prior to previous high are all lower
• These pivot points are used to form the ZigZag lines, which in their turn are used for pattern recognition
🔶 USAGE
The basic principles we use to identify Elliott Wave impulses are:
• A movement in the direction of the trend ( Motive/Impulse wave ) is divided in 5 waves (Wave 1 -> 5)
• The Corrective Wave (against the trend) is divided in 3 waves (Wave A -> C)
• The waves can be subdivided in smaller waves
• Wave 2 can’t retrace more than the beginning of Wave 1
• Wave 4 does not overlap with the price territory of Wave 1
Here we see an example:
Let's look at the development:
• 1 bar after point (5) a confirmed 5 Motive Wave pattern is found (1 -> 5; The 5 Waves can also be seen as one large Wave 1 ).
• Next, the script draws a set of Fibonacci lines, which are area's where the Corrective Wave potentially will bounce.
Here we see the fifth wave is getting larger, the previous highest point is updated, and the Wave 5 is larger than Wave 3 :
(At this point, the pattern is invalidated, and it display as dotted)
Further progression in time:
At this point, a confirmed " 3 Corrective Wave pattern " is found (a -> c)
When a new high has developed, a circle is drawn (in the same color of the lines)
However, when the bottom of the drawn box has breached, a red cross will be visualized.
Further progression:
Later on, a bearish confirmed " 5 Motive Wave pattern " is found (1 -> 5):
When a Corrective Wave becomes invalidated, the ABC pattern will display as dashed (not dotted):
🔶 TECHNIQUES
Pine Script™ introduces methods!
• More information can be found here:
• Pine Script™ v5 User Manual 👉 Methods
• Pine Script™ language reference manual 👉 method
🔶 ALERTS
Dynamic alerts are included in the script, you only need to set 1 alert to receive following messages:
• When a new EW Motive Pattern is found (Bullish/Bearish )
• When a new EW Corrective Pattern is found (Bullish/Bearish )
• When an EW Motive Pattern is invalidated (Bullish/Bearish )
• When an EW Corrective Pattern is invalidated (Bullish/Bearish )
• When possible, a start of a new EW Motive Wave is found (Bullish/Bearish )
• Here is information how you can set these alerts()
Fundamentals Graphing [Kioseff Trading]Hello!
This script "Fundamental Comparison" allows you to compare almost any fundamental metric across 40 assets; various charting methods are employable!
Thank you to @TradingView / @PineCoders for providing the framework in the "Financials on Chart" indicator - thereby expediting a generous portion of work (:
Features
Most metrics included in the "Financials on Chart" indicator are graphable
Scatter chat
Histogram
Bar chart
Pie chart
Reversible scaling
Adjusts to the size of your chart
10 industry presets
Custom symbol dataset
Retrieve, graph, and compare fundamental data by quarter/year. The indicator can "look back" to grab fundamental data from previous quarters/years.
Sortable data - ascending/descending
Built-in search function
Self-Adjusting Graph
The graph adjusts to the orientation/size of your chart!
The image above shows the graph on a price chart with a 229 bar difference.
The image above shows the same price chart; however, there's now a 1941 bar difference to which the fundamentals graph automatically adjusts!
The images above show the same expansion/reduction for the pie chart; all graph types shrink and expand with the price chart.
Fundamental Metrics
The image above shows most of the settings for the indicator!
Most of the metrics from the "Financials on Chart" indicator are included!
Quarterly or annual data are retrievable, in addition to industry presets.
Additionally, you can retrieve the financial data any number of intervals back (so long as the data exists and is provided by TradingView)
The image above shows an example of retrieving a fundamental metric from a previous FQ. The same can be done with FY!
Sortable Data
All data retrieved by the indicator is sortable - allowing for, hopefully, easier evaluations (:
The image above exemplifies the capability!
Data from any quarter/year can be sorted similarly.
Reversible Scale / Reversible Color Scheme
A seemingly trivial feature: a reversible scale and color scheme should assist in instances where "a higher number is bad" and a "lower number is good" - in addition to other scenarios.
For instance,
The image above shows a graph for taxes. The scale and color scheme have not been reversed and, presently, larger columns are correlating to a smaller amount of money out/in than smaller columns.
This can be fixed by reversing the scale.
The image above shows the "Reverse Scale" feature selected. Consequently, larger columns correlate to a larger amount of money out/in.
Similarly, a "Reverse Colors" feature is available. A useful option when a more positive number is "bad" and a less positive number is "good".
For instance,
The image above shows graphing for the Beneish M-Score.
A more positive number is generally interpreted as "bad"; a less positive number is generally interpreted as "good".
However, our color scheme doesn't seem to correspond (unless one considers red = good and green = bad)
Let's enable the reverse color feature.
The image above shows the completion of the process!
Finally, there's a built-in search feature that's a bit difficult to use; however, should you grow comfortable with it you may save some time sorting through fundamental data.
Big thanks to @rumpypumpydumpy for providing an easy-to-work-with framework for the pie chart!
That's all for now; thank you for checking this out.
Flare🔶 METHODS
• Pine Script™ introduces methods ( 1 , 2 )! Much kuddos for the developers, Tradingview, and all who has worked on it!
• This educational script will show the simplified way of writing built-in methods, not to create a new method.
🔹 Simplified way of writing built-in methods:
· Instead of:
newArray = array.new()
array.unshift(newArray, 1)
lin = line.new(na, na, na, na)
line.set_xy1(lin, bar_index , close)
line.set_xy2(lin, bar_index + 10, close)
label newLabel = label.new(bar_index, high)
if barstate.islast
label.delete(newLabel)
· We now can write it like this:
newArray = array.new()
newArray.unshift(1)
lin = line.new(na, na, na, na)
lin.set_xy1(bar_index , close)
lin.set_xy2(bar_index + 10, close)
label newLabel = label.new(bar_index, high)
if barstate.islast
newLabel.delete()
——————————————————————————————————————————————————————————
· When using sometimes brackets are necessary:
label lab = label.new(bar_index, high)
if barstate.islast
label.set_color(lab, color.red)
label.delete(lab )
· ->
label lab = label.new(bar_index, high)
if barstate.islast
lab.set_color(color.red)
(lab ).delete() // lab .delete() doesn't compile at the moment
——————————————————————————————————————————————————————————
🔶 OVERVIEW OF SCRIPT
• The basic principles are:
· Find 1 point ( close ) x bars back from current bar ( settings: 'x close back').
· Create a 'Flare' shaped object from that point to current bar or further (dependable of "Width of Flare").
· Calculate where current close is located versus the Flare lines.
· On that bases, change colour and draw plotshapes.
· Below bar if current close is located in the upper part of the Flare
· Above bar if current close is located in the lower part of the Flare
· Above & Below if located in the middle part of the Flare
-> Above & Below colours has 3 different colours (adjustable), dependable on the position
🔶 EXAMPLES
· Neutral zone:
· Light Bullish zone:
· Bullish zone:
· Very Bullish / Overbought zone:
· Light Bearish zone:
· Bearish zone:
· Very Bearish / Oversold zone:
🔶 TECHNIQUES
🔹 I. Make a User Defined Type (UDT) Flare, with:
· 5x linefill - array of linefill
· int iDir, which captures the direction (current location of close in Flare)
· color cCol, this is a colour variable in relation to the direction.
🔹 II. Different functions will add a new Flare object, and update the values on each bar.
· Explanation of each function can be found in the script.
🔶 EXTRA's
· The input.color() is located in the function set_flare_B(flare obj)
· Best to put the inputs at the beginning of the script, I included this alternative just to show it is possible (but mostly not ideal)
· Background colour (settings: Bgcolor) can be enabled for better visibility of colours
Recursive Auto-Pitchfork [Trendoscope]"Say Hi" to object oriented programming with Pinescript using types and methods. This is the beginning of new era of Pinescript where we are moving from isolated scripts containing indicator and strategies to whole ecosystem of Object Oriented Programming with libraries of highly reusable components. Those who are familiar with programming would have already realised how big these improvements are and what it brings to the table.
With this script, I am not just providing an indicator for traders but also an introduction for programmers on how to design and build object oriented components in Pinescript using types and methods. Big thanks to Tradingview and Pine development team for making this happen. We look forward for many such gifts in the future :)
🎲 Architecture
As mentioned before, we are not just building an indicator here. But, an ecosystem of components. Using Types and Methods we can visualise libraries as Classes. Thus, we can build an ecosystem of libraries in layered approach to enhance effective code reusability.
Generic architecture can be visualised as below
Coming to the specific case of Auto Pitchfork indicator, the indicator code is less than 50 lines for logic and around 100 lines of inputs. But, most of the heavy-lifting is done by the libraries underneath. Here is a snapshot of related libraries and how they are connected.
All libraries are divided into two portions.
Types - Contains only type definitions
Methods - Contains only method definitions related to the types defined in the Types library
Together, these libraries can be visualised as Class. Methods are defined in such a way all exported methods are related to Types and no other functions or features are defined. If we need further functionality which does not depend on the types, we need to do this via some other library and use them here. Similarly, we should not define any methods related to these types in other libraries.
Reason for splitting the libraries to types and methods is to enable updating methods without disturbing types. Since libraries create interdependencies due to versioning, it is best if we do less updates on the type definitions. Splitting the two enables adding more features while keeping the type definition version intact.
🎲 Base Libraries
Base libraries are those which does not have any dependency. They form basic structures which are later used in other libraries. These libraries need to be crafted carefully so that minimal updates are done later on. Any updates on these libraries will impact all the dependent libraries and scripts.
🎯 Drawing
DrawingTypes - Defines basic drawing types Point, Line, Label, Box, Linefill and related property types.
DrawingMethods - All the methods or functionality surrounding Basic types are defined here.
🎲 Layer 1 Libraries
These are the libraries which has direct dependency on base libraries.
🎯 Zigzag
ZigzagTypes - Types required for defining Zigzag and Divergence
ZigzagMethods - Methods associated with Zigzag Type definitions.
🎯Pitchfork
PitchforkTypes - Basic and Drawing Types for Pitchfork objects
PitchforkMethods - Methods associated with Pitchfork type definitions
🎲 Indicator and Settings
Indicator draws pitchfork based on recursive zigzag configurations. Recursive zigzag is derived with following logic:
Base level zigzag is calculated with regular zigzag algorithm with given length and depth
Next level zigzag is calculated based on base zigzag. And we recursively calculate higher level zigzags until we are left with 4 or less pivots or when no further reduction is possible
On every level of zigzag, we then check the last 3 pivots and draw pitchfork based on the retracement ratio.
Indicator settings are summarised in the tooltips and are as below.
Finally, big thanks to my partner @CryptoArch_ for bringing up the topic of pitchfork for our next development.
Intrabar Analyzer [Kioseff Trading]Hello!
This indicator (Intrabar Analyzer) presents intrabar data in various derivative forms.
On-Chart Features
Traditional price data down to 1 min.
Heikin-Ashi price data down to 1 min.
Kagi price data down to 1 min.
Point & Figure price data down to 1 min.
Renko price data down to 1 min.
Linebreak price data down to 1 min.
LinReg channel
SMA
EMA
ALMA
Echomorphic Average (A @kaigouthro special!)
HMA
RMA
WMA
VWMA
VWAP
SWMA
SAR
Supertrend
On-Chart Features
Price x Volume graph
Intrabar technical rating
Positive volume index
Negative volume index
Price volume trend
RSI
%k
ROC
MFI
MFC
OBV
CCI
BBW
CMO
COG
KCW
MOM
RANGE
%r
Let's look at the objects populated by the indicator!
The image above shows what data correlates to the populated graphs!
Let's dial in on the price x volume graph.
The image above provides an example/explanation of the price x volume graph. All data is sourced from a lower timeframe (configurable - default = 1 minute).
Colors are configurable; the plot characters are configurable.
The numbers above show an alternative view of the price x volume graph!
Price graph
The price graph can populate 6 variations of price data: traditional, heikin-ashi, renko, point & figure, line break, and kagi.
The subsequent images will show all available forms of price data, in addition to a randomly selected, on-chart technical indicator!
Kagi + LinReg
Traditional + EMA
Renko + SAR
Point & Figure + ALMA
Heikin-Ashi + Supertrend
Line Break + VWAP
You can display up to three indicators concomitantly - all calculated using intrabar data!
Lastly, the indicator displays the TradingView calculated technical rating for the intrabar.
The technical ratings are multiplied by x100 and oriented left & right of the price box. Left values are negative; right values are positive. The "0" value is not shown; therefore, if the technical rating isn't highlighted then the rating is "0".
The image above shows the technical rating system in action (:
That's it!
This was a fun project and I'm certainly willing to add more - let me know if there's anything you'd like included.
Additionally, a future feature involves compatibility with any custom indicator! Stay tuned; thank you for checking this out (:
Thank you to @kaigouthro, TradingView and @PineCoders for providing some cool libraries to play with!
Recession Warning Traffic LightThis is an indicator that uses 6 different metrics to determine the combined probability of a recession and compares the high probability warning periods against actual historical periods of recession.
GREEN tells us that the referenced recession indicators are not exhibiting any warning. Observe the long stretches of “all-green” in between recessionary periods in the chart above.
RED will show a full-on warning level for that particular recession indicator, signaling that monitoring of this sector is clearly showing a problem – which has in the past, reliably exhibited itself as a forewarning of recessions.
Adding green and red together can help determine a combined probability of recession.
IMPORTANT: Your chart should be on 1d and set to SPX , DJI ,or NDQ indices
Precious metals: This indicator calculates the relative prices of Gold & rhodium. Gold is a flight-to-quality asset. Rhodium is the rarest of precious industrial metals and prices spike when the economy is heating up. In front of a recession, the upper relative movement of rhodium precedes gold.
Stock markets: This indicator compares closing prices to growth rate curves of the SPX. This indication is the noisiest but tells us very well when the recession has ended. Stock market indices, which respond to “smart money” moving out of markets when the other indicators begin to warn of recession, or when markets become overheated and rise to historically unsustainable levels.
Yield curve: This indicator compares the 3m & 10y treasuries and detects yield curve inversions. Interest rates are controlled by the Federal Reserve and by the purchasers in the Federal Treasury auction markets, which together create the treasury yield curve. This inversion is the most reliable recession indicator. These happen during a flight to quality.
Federal Reserve: This indicator measures GDP and detects contraction which is technically a recession. This is usually one of the last indicators to enter a Warning state, and it could be 6 months delayed simply confirming what may have already been projected.
Money Supply. This indicator measures the M2 money supply, which typically grows about 1% per calendar quarter. When this shrinks, it's tapping the brakes on the economy. This can also lead to yield curve inversion. This is also a measure of inflation and its effects on the aggregate money supply (liquid capital) available for short-term economic activity, or which can be directed into the purchase of long-term, less liquid assets.
Leading Economic factors: There is a whole basket of leading economic indicators that, as collections, reflect overall growth or contraction of economic activity. These indicators include measures of level and growth in productivity, employment, housing, consumer confidence, industrial purchasing confidence, and much more. These indicators may or may not be detached from the broader economy, and often provide up to 6 months of foresight. For more information please visit www.conference-board.org
Actual Recession: Central Bank indicators are published by the Federal Reserve and reflect their own analysis of national and regional economic health, as well as their calculations of the likelihood of a recession. The Federal Reserve has a recession ticker which is used to plot periods of actual recessions on this indicator for comparison.
RSI Impact Heat Map [Trendoscope]Here is a simple tool to measure and display outcome of certain RSI event over heat map.
🎲 Process
🎯Event
Event can be either Crossover or Crossunder of RSI on certain value.
🎯Measuring Impact
Impact of the event after N number of bars is measured in terms of highest and lowest displacement from the last close price. Impact can be collected as either number of times of ATR or percentage of price. Impact for each trigger is recorded separately and stored in array of custom type.
🎯Plotting Heat Map
Heat map is displayed using pine tables. Users can select heat map size - which can vary from 10 to 90. Selecting optimal size is important in order to get right interpretation of data. Having higher number of cells can give more granular data. But, chart may not fit into the window. Having lower size means, stats are combined together to get less granular data which may not give right picture of the results. Default value for size is 50 - meaning data is displayed in 51X51 cells.
Range of the heat map is adjusted automatically based on min and max value of the displacement. In order to filter out or merge extreme values, range is calculated based on certain percentile of the values. This will avoid displaying lots of empty cells which can obscure the actual impact.
🎲 Settings
Settings allow users to define their event, impact duration and reference, and few display related properties. The description of these parameters are as below:
🎲 Use Cases
In this script, we have taken RSI as an example to measure impact. But, we can do this for any event. This can be price crossing over/under upper/lower bollinger bands, moving average crossovers or even complex entry or exit conditions. Overall, we can use this to plot and evaluate our trade criteria.
🎲 Interpretation
Q1 - If more coloured dots appear on the top right corner of the table, then the event is considered to trigger high volatility and high risk environment.
Q2 - If more coloured dots appear on the top left corner, then the events are considered to trigger bearish environment.
Q3 - If more coloured dots appear on the bottom left corner of the chart, then the events are considered insignificant as they neither generate higher displacement in positive or negative side. You can further alter outlier percentage to reduce the bracket and hence have higher distribution move towards
Q4 - If more coloured dots appear on the bottom right corner, then the events are considered to trigger bullish environment.
Will also look forward to implement this as library so that any conditions or events can be plugged into it.
Market Sessions - By LeviathanA simple indicator to help you keep track of 4 market sessions (default: Tokyo, London, New York, Sydney) in 4 different visual forms (boxes, timeline, zones, colored candles) with many other useful tools.
You can choose between 4 different market sessions. The default ones are Tokyo, London, New York and Sydney but you can easily customize the times, names and colors to make the script plot any session you need. Sessions can be viewed in 4 different ways: boxes, zones, timelines, or just colored candles, all with customizable appearances. You can make your chart cleaner by merging sessions overlaps, choosing a custom lookback period and also picking between various additional settings such as viewing session High/Low or Open/Close change in % or pips, hiding weekends, viewing the Open/Close Line to identify session’s direction and 0.5 level to see session’s “Equilibrium” and much more. More updates with interesting tools will be added in the future.
Note: The script will plot the correct default Tokyo, London, New York and Sydney sessions automatically, your chart/Tradingview app timezone does not matter! If you wish to tweak the open/close times of sessions, just make sure you input them in UTC (but even this can be changed later in the settings)
Settings Overview
SESSIONS
- You can show/hide Tokyo Session, rename it, change the color and set up start/end time.
- You can show/hide London Session, rename it, change the color and set up start/end time.
- You can show/hide New York Session, rename it, change the color and set up start/end time.
- You can show/hide Sydney Session, rename it, change the color and set up start/end time.
* Keep in mind that you can fully change and customize these sessions and therefore create any other sessions or a zone you wish to display.
ADDITIONAL TOOLS AND SETTINGS
1. “Change (Pips)” - this will add the pip distance between Session High and Session Low or the pip distance between Session Open and Session Close to the session label.
2. “Change (%)” - this will add the percentage distance between Session High and Session Low or the percentage distance between Session Open and Session Close to the session label.
3. “Merge Overlaps” - this will merge the overlapping sessions and show only one at a time (end of Tokyo is moved to start of London, the end of London is moved to the start of New York, end of New York is moved to start of Sydney and end of Sydney is moved to start of Tokyo).
4. “Hide Weekends” - this will prevent the script from plotting sessions over the weekend when the markets are closed.
5. “Open/Close Line” - this will draw a line from the session open to the session close (or current price, if session is ongoing).
6. “Session 0.5 Level” - this will draw a horizontal line halfway between the session’s high and the session’s low.
7. “Color Candles” - this will color the bars/candlesticks with the color of the session in which they occurred.
8. Display Type” - Choose between three different ways of session visualization (Boxes, Zones and Candles).
9. “Lookback (Days)” - this input tells the script to only draw sessions for X days back (1 = one day).
10. “Change (%/Pips) Source) - this is where you choose the source of “Change (Pips)” and ”Change (%) ” labels. Picking “Session High/Low” will show you the change between Session High and Session Low and picking “Session Open/Close” will show you the change between Session Open and Session Close.
11. “Input Timezone” - this defines the timezone of the session start/end inputs (you don’t have to change this unless you know what you’re doing)
Make sure to read future update logs to keep track of the most recent additions and settings of this script.
Box generation code inspired by Jos(TradingCode), session box visuals inspired by @boitoki's FX Market Sessions
Financials - Comparing CompaniesHello All
For a while I have been working on this indicator to compare financials of the companies and sort them accordingly. Finally I completed and published it. I preferred using new object type feature in Pine language™ and I hope it might be an example and helpful for the developers.
First of all, as we have limitation on security calls, the indicator can get and compare financials for 5 companies only. also Chart time frame must be 1Day or higher! ( I recommend 1Day time frame ). if not then the indicator stops and shows the error message: "Please set the time frame 1Day or higher" . More important than others: You should choose the companies from the same sector! Compare apples to apples :)
The Financials in the indicator:
Earnings Per Share
Price to Earnings Ratio
Price to Sales Ratio
Price to Book Ratio
Profit Margin
Dept to Equity
Current Ratio
Market Capitalization
Also more information shown for each stocks:
Closing Price, sets the color accordingly
2 Simple/Exponential moving average, you can set the length, also it checks if it is rising/falling and sets the color accordingly
Volume info
Average volume (20 days), you can set the period
Currency for each security
Lets see some features in it:
it sorts the companies according to the financials:
If you move the mouse onto any header then it shows explanation about the financial:
You can change location and text size:
You can set the type of Moving averages as SMA or EMA and you can also set the length for both . Headers for both are changed automatically by MA type and length
Colors for Closing price and MA cells are set automatically:
For new Objects in Pine language click here
P.S. You can use this indicator while analyzing the financials of the companies in same sector/industry. So please don't ask for the alerts :)
Enjoy!
Golden PocketGolden Pocket
This marks up the fibonacci retracement levels of 0.65 and 0.618 by default, these levels are often referred to as the golden pocket.
They are known by this because when price has an impulse either to the up or downside, price will end up retracing at some point. This Golden pocket often lines up with other means of confluence where it's considered a good entry price from the retrace.
Unlike standard fib retracement indicators, these boxes will extend with current price until they are hit. As well as this, there is a moving average filter which you can set to higher timeframes meaning that you can choose to only look for golden pockets which are following the higher time frame trend. You can easily monitor all of your settings by setting up just 1 alert.
Settings
You have the option to enable/disable the line which marks out the pivot points the fib is being calculated from, you can also change the colour and style of the line.
Below this you have the option to choose what colour the fib boxes are and what colour they change to once price hits it. If you want them to disappear change the colours opacity to 0%.
If you want to change the golden pocket levels you can do that by changing the 0.618 or 0.65 levels in the settings.
The pivot distance controls what part defines a pivot high or low, it must be the highest/lowest to the left/right of the pivot candle count.
MA filter will only accept golden pockets which are trending with the Moving average.
You can change all the settings of the Moving average which acts as a filter including which timeframe it is calculated on.
Alerts
Simply toggle this on int the settings and then click on the 3 dots next to the indicators name, 'add alert', leave the top boxes as they are, you can name the alert anything you like but once you confirm this, it will monitor all golden pockets on the particular asset and timeframe you are looking at. The alerts are set up to trigger as soon as price touches one of the boxes.
Use Cases
We like setting are moving average up on the daily timeframe and using the Moving average filter so we know we are only trading with the higher timeframe trend. From there we can set up alerts on any lower timeframe.
Feel free to use any part of this script in your own code, please just give us a mention so we can check out your contributions to the community as well!
Happy to take in any suggestions or ways of improving