Normalized KAMA Oscillator | Ikke OmarThis indicator demonstrates the creation of a normalized KAMA (Kaufman Adaptive Moving Average) oscillator with a table display. I will explain how the code works, providing a step-by-step breakdown. This is personally made by me:)
Input Parameters:
fast_period and slow_period: Define the periods for calculating the KAMA.
er_period: Specifies the period for calculating the Efficiency Ratio.
norm_period: Determines the lookback period for normalizing the oscillator.
Efficiency Ratio (ER) Calculation:
Measures the efficiency of price changes over a specified period.
Calculated as the ratio of the absolute price change to the total price volatility.
Smoothing Constant Calculation:
Determines the smoothing constant (sc) based on the Efficiency Ratio (ER) and the fast and slow periods.
The formula accounts for the different periods to calculate an appropriate smoothing factor.
KAMA Calculation:
Uses the Exponential Moving Average (EMA) and the smoothing constant to compute the KAMA.
Combines the fast EMA and the adjusted price change to adapt to market conditions.
Oscillator Normalization:
Normalizes the oscillator values to a range between -0.5 and 0.5 for better visualization and comparison.
Determines the highest and lowest values of the KAMA within the specified normalization period.
Transforms the KAMA values into a normalized range.
By incorporating the Efficiency Ratio, smoothing constant, and normalization techniques, the indicator actually allows for the identification of trends on different timeframes, even in extreme market conditions.
The normalization makes it much more adaptive than if you were to just use a normal KAMA line. This way you actually get a lot more data by looking at the histogram, rather than just the KAMA line.
I essentially made the KAMA into an oscillator! Please ask if you want me to code another indicator
I hope you enjoyed this.
Please ask if you have any questions<3
Сферы применения Pine
Higher TimeFrame Smooth Moving AveragesScript is designed for those who dislike how plotting a moving average from a higher timeframe on a lower timeframe chart results in a choppy zigzag line when using the standard request.security(syminfo.ticker,"x",ta.sma(src,len)) method.
My more elegant solution was to translate the chart's current timeframe, and the selected higher timeframe into seconds, then check if selected timeframe is Larger than chart timeframe, but not so large that too many bars would be necessary. Then the quotient is calculated by dividing the chosen timeframe (value in seconds) by the chart's timeframe (value in seconds).
Then take that quotient and multiply it by the chosen length. This gives us how many bars of the chart's timeframe would be used in calculating the higher timeframe Moving Average
Use the value to calculate a moving average of choice (SMA,EMA,WMA,LRC,DEMA,TEMA,TRIMA,FRAMA) thanks to @TradingView 's ta library () and @alexgrover 's () for their functions supporting series as length, making this possible.
Basically, get how many of the current chart's bars are in the higher timeframe moving average and use that as the length for calculation using chart's timeframe.
If the higher timeframe relative is too large relative to chart's timeframe, due to bar referencing limits some combinations may not be possible under current limitations, but most will work by either moving chart's timeframe higher or higher timeframe lower assuming you aren't trying to do something too extreme like plotting a weekly moving average onto a 30 second chart etc.
3D BowlingIntroducing the "3D Bowling Game" – a fun and interactive demo scene project in Pine Script, powered by a custom 3D engine! This bowling game showcases the potential of Pine Script for developing engaging and immersive experiences, even within the confines of a trading platform.
To play the game, you'll first be prompted to choose where you want to throw the ball. Next, you'll be asked to draw a line indicating the direction you want the ball to go. Sit back and enjoy as the game takes care of the rest!
The source code features various sections, including:
Types and helper functions to manipulate vectors, matrices, and angles
Routines for calculating cross products, dot products, and vector normalization
Transformation matrices for rotation and scaling
Functions for perspective transformation, mesh transformations, and face normal calculations
Culling and shading algorithms to provide a more realistic visual experience
The project's source code is an excellent starting point for anyone interested in exploring the capabilities of Pine Script beyond the typical trading indicators and strategies. The 3D Bowling Game demonstrates the flexibility of Pine Script and its potential for creating interactive experiences in a seemingly unconventional environment.
So, what are you waiting for? Dive into the source code, tweak it to your liking, or build upon it to create your own interactive 3D experiences. Enjoy the game, and happy coding!
With light. I will say there is an issue with the fact that you cant draw as may linefills as you can lines.
Strategy DesignerHello traders.
Thanks to the tool I have published, everyone who knows or does not know coding will be able to create strategies and see the results instantly on the screen. Yes it looks very nice :)
What does this script do?
Thanks to this tool, even if you don't know any coding, you will be able to create your own strategies. You can add and remove indicators.
Entrance
The first thing you need to do is to set a strategy in your mind.
Then you need to adjust the settings of the indicators installed in the system. Please set the indicators first, because later they are forgotten.
The screen for entering the parameters of the indicators will be as follows.
After entering the parameters there is an important part . In this section, we can adjust the strategy settings.
First we choose between which dates we want the strategy to run. We then choose whether we want the strategy results to be displayed in a table or not.
We choose how the Terms should be linked together. For example, if you have a condition that is expected to produce more than one receive signal, select whether these conditions are connected to each other with and or with the connector.
In this way, you can determine whether all or any of the rules in your strategy should apply.
Next, we choose whether our strategy will work in the spot market or in a bidirectional market. Yes, you can design a strategy for both spot and bidirectional trades :)
At the bottom of the above image, we see a screen where we can adjust the stop level and tp level. As a standard, adjustments are made according to the percentage level you enter. However, if you remove the tick next to the percent sign, the previous stop level and the next profit level are determined as much as the value you entered.
At the bottom is the trailing stop. When you open the trailing stop, the trailing stop becomes active in your strategy.
Very important, when the trailing stop and the stop are active at the same time, the trailing stop value is valid.
It's time to design our strategy. Each chapter that begins with an exclamation point is a separate fiction.
If you do not mark the Active button, that condition will not be included in the calculation.
Direction = It is the direction for which the fiction in this region is valid.
We came to the indicator setting screen. Here, there is a screen where we can select two different indicators on the right and left.
We choose the first indicator starting with 1.
Then we choose from the middle region how we want these two indicators to interact.
We choose our second indicator from the place starting with 2.
If you want an indicator to interact with any value, tick the box where it says Value and fill in the value in the blank. When Value is ticked, the second indicator does not work.
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.
Profiling: array of UDTs vs UDT of arraysUsing Stopwatch Library by PineCoders, I am trying to test which is faster, an array of user-defined type (UDT) objects vs an object with many child arrays.
The task is to store and manipulate array of objects having total 9 values: 4 floats, 4 strings and 1 int.
Option 1: create a UDT with 9 fields and store an array of such UDT objects.
Option 2: create a UDT with 9 arrays individually for each value.
The test task is of three stages:
Populate array(s) with some (timenow) values - in the options you can choose how many values to push into the array/arrays. Note that max size of array(s) is set independently, so you can push 1000 of elements into an array capped at 100 max size and as new elements will be pushed (added to the end) the old exceeding elements will be shifted (removed from the beginning)
Write - write to random elements of the array. Two options for writing to a UDT object: (1) assign to each field independently, (2) create a UDT object and use array.set() function.
Read - read from random elements of the array.
In the options you can how many times per bar to run each of the steps (same number for each step).
I tested by adding three indicators to the chart and choosing different options for each:
1. Array of UDT's where writing is done by creating a new UDT from the values and then using set(udt)
2. Array of UDT's where writing is done by assigning the value of each of the properties of the UDT individually (saving time on creating of a new object).
3. UDT of arrays.
As of 16 Arpil 2023 the UDT of arrays seems about 20-30% faster than the array of UDT's with setting each property without creating new UDT object.
3D EngineHello everyone,
I am excited to share with you the first 3D engine in Pine Script! This is a remarkable achievement that will enable traders to explore the possibilities of 3D objects in their technical analysis.
To use this engine, you will need to use a higher time frame (1W or greater) to load the 3D objects in time. The code is straightforward and easy to use, with various input options to customize the object's position, rotation, and scale. You can select between two default 3D objects, Pin or Ball, by changing the 'list' input string.
The 3D engine is based on the vector and mesh data structures, and it includes several utility functions to perform operations such as rotation, translation, and scaling on these structures. It also includes functions to calculate perspective transformation for projecting 3D objects onto a 2D surface, which is the essential step in rendering the object in a 2D chart.
The 'process_scene' function is the main function that converts the 3D object data into 2D polygon data, which can be rendered on the chart. This function uses the 'process_object' function, which applies the object's transformation (position, rotation, and scale) and returns a scaled and rotated mesh that is ready for projection.
At the end of the code, there is a camera object that defines the camera's position, target, and field of view. You can customize this camera object to change the perspective of the rendered object.
To make your own 3D object, you can use the included Python program to convert an OBJ file into the format used by the engine. This program converts the OBJ file into a list of vector4 objects, which can be copy-pasted into the 'pin_vertex_list' array or a similar array. Please note that this process requires some knowledge of Python and the OBJ file format.
Overall, this is a fantastic achievement that opens up new possibilities for technical analysis in Pine Script. I encourage you to try it out and see what you can create with it.
In this code, there are several functions and data structures used to represent and manipulate 3D objects in a simple 3D engine. I will explain each function in detail below:
radians(degree): Converts an angle in degrees to radians.
quat_identity(): Returns a quaternion representing the identity rotation.
quat_from_axis_angle(axis, angle): Creates a quaternion from an axis of rotation and an angle.
quat_multiply(q1, q2): Multiplies two quaternions, q1 and q2, and returns the result.
quat_conjugate(q): Returns the conjugate of a quaternion, q.
quat_rotate(q, v): Rotates a 3D vector, v, by a quaternion, q, and returns the result.
rotate_vector_by_quaternion(v, q): Rotates a 3D vector, v, by a quaternion, q, and returns the result.
scale_vector(vector, constant): Scales a 3D vector by a constant and returns the result.
scale_mesh(mesh_obj, constant): Scales a mesh by a constant and returns the new mesh.
rotate_mesh(mesh_obj, axis, angle): Rotates a mesh around a specified axis by a given angle and returns the new mesh.
quat_translate(src, offset): Translates a 3D vector, src, by an offset and returns the result.
translate_mesh(mesh_obj, offset): Translates a mesh by an offset and returns the new mesh.
perspective_transform(msh, cam): Transforms a 3D mesh into a 2D mesh using a camera.
process_object(obj, cam): Processes a 3D object with a camera and returns a 2D mesh.
size(scene): Calculates the total number of vertices in a scene.
make_poly(scene): Converts a scene of 2D meshes into an array of polygons.
process_scene(scn, cam): Processes an entire scene of 3D objects with a camera and returns an array of polygons.
These functions work together to create a simple 3D engine that can manipulate, transform, and render 3D objects as 2D polygons. The main part of the script defines the camera, vertices, and faces for a pin object, and then uses the functions to process and render the object.
Note that some types are also defined in the code, including vector2, vector3, vector4, face, mesh, mesh2d, location, object, poly4, polyg, and camera. These types represent various mathematical structures and entities used in 3D graphics, such as vectors, faces, meshes, and cameras.
Here is an explanation of the inputs for all the functions in the given code:
radians(degree):
degree: Angle in degrees to be converted to radians.
quat_from_axis_angle(axis, angle):
axis: A vector3 object representing the axis of rotation.
angle: The angle in radians to rotate about the axis.
quat_multiply(q1, q2):
q1, q2: Two quaternion objects to be multiplied.
quat_conjugate(q):
q: A quaternion object whose conjugate is to be calculated.
quat_rotate(q, v):
q: The quaternion representing the rotation.
v: The vector3 object to be rotated.
rotate_vector_by_quaternion(v, q):
v: The vector3 object to be rotated.
q: The quaternion representing the rotation.
scale_vector(vector, constant):
vector: A vector4 object to be scaled.
constant: The scaling factor.
scale_mesh(mesh_obj, constant):
mesh_obj: A mesh object to be scaled.
constant: The scaling factor.
rotate_mesh(mesh_obj, axis, angle):
mesh_obj: A mesh object to be rotated.
axis: A vector3 object representing the axis of rotation.
angle: The angle in radians to rotate the mesh.
quat_translate(src, offset):
src: A vector4 object representing the source position.
offset: A vector3 object representing the translation offset.
translate_mesh(mesh_obj, offset):
mesh_obj: A mesh object to be translated.
offset: A vector3 object representing the translation offset.
perspective_transform(msh, cam):
msh: A mesh object to be transformed.
cam: A camera object used for the transformation.
process_object(obj, cam):
obj: An object containing a mesh and its location.
cam: A camera object used for processing the object.
make_poly(scene):
scene: An array of mesh2d objects to generate polygons from.
process_scene(scn, cam):
scn: An array of objects containing meshes and their locations.
cam: A camera object used for processing the scene.
Note that some of these functions are utility functions or internal functions, and their inputs are derived from other functions or user inputs.
I will make a library eventually.
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.
Retracement and Extension Ratios [theEccentricTrader]█ OVERVIEW
This indicator displays retracement and extension ratios above or below the relevant peaks and troughs.
█ CONCEPTS
Green and Red Candles
• A green candle is one that closes with a close price equal to or above the price it opened.
• A red candle is one that closes with a close price that is lower than the price it opened.
Swing Highs and Swing Lows
• A swing high is a green candle or series of consecutive green candles followed by a single red candle to complete the swing and form the peak.
• A swing low is a red candle or series of consecutive red candles followed by a single green candle to complete the swing and form the trough.
Peak and Trough Prices (Basic)
• The peak price of a complete swing high is the high price of either the red candle that completes the swing high or the high price of the preceding green candle, depending on which is higher.
• The trough price of a complete swing low is the low price of either the green candle that completes the swing low or the low price of the preceding red candle, depending on which is lower.
Historic Peaks and Troughs
The current, or most recent, peak and trough occurrences are referred to as occurrence zero. Previous peak and trough occurrences are referred to as historic and ordered numerically from right to left, with the most recent historic peak and trough occurrences being occurrence one.
Range
The range is simply the difference between the current peak and current trough prices, generally expressed in terms of points or pips.
Retracement and Extension Ratios
Retracement and extension ratios are calculated by dividing the current range by the preceding range and multiplying the answer by 100. Retracement ratios are those that are equal to or below 100% of the preceding range and extension ratios are those that are above 100% of the preceding range.
█ FEATURES
Inputs
• Label Color
█ HOW TO USE
This indicator is intended for research purposes, strategy development and strategy optimisation. I hope it will be useful in helping to gain a better understanding of the underlying dynamics at play on any given market and timeframe.
█ LIMITATIONS
All green and red candle calculations are based on differences between open and close prices, as such I have made no attempt to account for green candles that gap lower and close below the close price of the preceding candle, or red candles that gap higher and close above the close price of the preceding candle. This may cause some unexpected behaviour on some markets and timeframes. I can only recommend using 24-hour markets, if and where possible, as there are far fewer gaps and, generally, more data to work with.
Economic Calendar EventsThis indicator provides an overlay of Events on the main chart, where each Event is visually represented by a Label and vertical Line, placed at the specified time interval for each Event.
Events are defined by user data as an input string on the settings widget panel for the indicator. The event data is a string (semicolon delimited) whose grammar is a representation of a collection of Event records, where each Event record is a comma-separated list of fields, which correspond to:
The name of the event.
The symbol or ticker to which the Event applies (or `*` if it should apply to all ticklers).
The timezone and then the year, month, day, hour, and minute of the event, respectively.
Each Event record is separated by the semicolon ";" character.
As an example , assume `evantData` is the string:
"SVB,*,UTC,2023,03,10,00,00;US CPI,*,UTC,2023,04,12,08,30;ETH Shanghai,ETHUSD,UTC,2023,04,12,08,30"
In the above case, there are 4 Events defined, three of which apply to all tickers and one applies only to ETHUSD, as follows:
The first event is named SVB and applies to all tickers at UTC time on March 10, 2023 at 12:00:00.
The second event is named US CPI and applies to all tickers at UTC time on April 12, 2023 at 08:30:00.
The third event is named ETH Shanghai and applies to the ETHUSD ticker at UTC time on April 12, 2023 at 08:30:00.
The fourth event is named FOMC Rates and applies to all tickers at UTC time on May 3, 2023 at 14:00:00.
The following is a BNF for defining event data:
market-events ::= event-record | event-record ";" market-events
event-record ::= event-name "," ticker ”,” event-timezone "," event-time
event-name ::= string
event-time>::= year "," month "," day "," hour "," minute
event-timezone ::= string
ticker ::= "*" | string
string ::= +
year ::= {4}
month ::= {2}
day ::= {2}
hour ::= {2}
minute ::= {2}
ICT Killzone SessionIt is a useful tool for identifying the London and New York open and close sessions, as well as the Asian range on the chart.
The appearance of the "killzones" can be customized by selecting colors and transparencies for each session.
Boxes can also be displayed around each session and labels with additional information can be added.
This script is compatible with intraday charts and time multipliers up to 60 minutes. It was created by Jeaw and is based on the ideas of the ICT methodology.
This script can help traders avoid entering the market during high impact news events and periods of low liquidity.
By identifying these potentially volatile times, traders can better manage their risk and improve their overall trading strategy.
London Open Killzone : 07:00 - 10:00
New York Open Killzone : 12:00 - 15:00
Asian Range : 15:00-17:00
London Close Killzone : 00:00-06:00
*Backtesting System ⚉ OVERVIEW ⚉
One of the best Systems for Backtesting your Strategies.
Incredibly flexible, simple, fast and feature-rich system — will solve most of your queries without much effort.
Many systems for setting StopLoss, TakeProfit, Risk Management and advanced Filters.
All you need to do is plug in your indicator and start Backtesting .
I intentionally left the option to use my System on Full Power before you load your indicator into it.
The system uses the built-in simple and popular moving average crossover signal for this purpose. (EMA 50 & 200).
Also Highly Recommend that you Fully use ALL of the features of this system so that you understand how they work before you ask questions.
Also tried to leave TIPS for each feature everywhere, read Tips, activate them and see how they work.
But before you use this system, I Recommend you to read the following description in Full.
—————— How to connect your indicator in 2 steps:
Adapt your indicator by adding only 2 lines of code and then connect it to this Backtesting System.
Step 1 — Create your connector, For doing so:
• 1 — Find or create in your indicator where are the conditions printing the Long-Buy and Short-Sell signals.
• 2 — Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD, RSI , Pivots, or whatever indicator with Clear Buy and Sell conditions.
//@version=5
indicator('Moving Average Cross', overlay = true)
MA200 = ta.𝚎𝚖𝚊(close, 200)
MA50 = ta.𝚎𝚖𝚊(close, 50)
// Generate Buy and Sell conditions
buy = ta.crossover (MA200, MA50)
sell = ta.crossunder (MA200, MA50)
plot(MA200, color=color.green)
plot(MA50 , color=color.red )
bgcolor(color = buy ? color.green : sell ? color.red : na, title='SIGNALS')
// ———————————————— SIGNAL FOR SYSTEM ————————————————
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, title='🔌Connector🔌', display = display.none)
// —————— 🔥 The Backtesting System expects the value to be exactly +1 for the 𝚋𝚞𝚕𝚕𝚒𝚜𝚑 signal, and -1 for the 𝚋𝚎𝚊𝚛𝚒𝚜𝚑 signal
Basically, I identified my Buy & Sell conditions in the code and added this at the bottom of my indicator code
Now you can connect your indicator to the Backtesting System using the Step 2
Step 2 — Connect the connector
• 1 — Add your updated indicator to a TradingView chart and Add the Backtesting System as well to the SAME chart
• 2 — Open the Backtesting System settings and in the External Source field select your 🔌Connector🔌 (which comes from your indicator)
_______________________________
⚉ MAIN SETTINGS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 — Select your indicator. Add your indicator by following the 2 steps described above and select it in the menu. To familiarize yourself with the system until you select your indicator, you will have an in-built strategy of crossing the two moving EMA's of 50 and 200.
Long Deals — Enable/Disable Long Deals.
Short Deals — Enable/Disable Short Deals.
Wait End Deal — Enable/Disable waiting for a trade to close at Stop Loss/Take Profit. Until the trade closes on the Stop Loss or Take Profit, no new trade will open.
Reverse Deals — To force the opening of a trade in the opposite direction.
ReEntry Deal — Automatically open the same new deal after the deal is closed.
ReOpen Deal — Reopen the trade if the same signal is received. For example, if you are already in the long and a new signal is received in the long, the trade will reopen. * Does not work if Wait End Deal is enabled.
𝐓𝐚𝐤𝐞 𝐏𝐫𝐨𝐟𝐢𝐭:
None — Disables take profit. Useful if you only want to use dynamic stoplosses such as MA, Fast-Trailing, ATR Trail.
FIXED % — Fixed take profit in percent.
FIXED $ — Fixed Take in Money.
ATR — Fixed Take based on ATR.
R:R — Fixed Take based on the size of your stop loss. For example, if your stop is 10% and R:R=1, then the Take would be 10%. R:R=3 Take would be 30%, etc.
HH / LL — Fixed Take based on the previous maximum/minimum (extremum).
𝐒𝐭𝐨𝐩 𝐋𝐨𝐬𝐬:
None — Disables Stop Loss. Useful if you want to work without a stop loss. *Be careful if Wait End Deal is enabled, the trade may not close for a long time until it reaches the Take.
FIXED % — Fixed Stop in percent.
FIXED $ — Fixed Stop in Money.
TRAILING — Dynamic Trailing Stop like on the stock exchanges.
FAST TRAIL — Dynamic Fast Trailing Stop moves immediately in profit and stays in place if the price stands still or the price moves in loss.
ATR — Fixed Stop based on the ATR.
ATR TRAIL — Dynamic Trailing Stop based on the ATR.
LO / HI — A Fixed Stop based on the last Maximum/Minimum extemum. Allows you to place a stop just behind or above the low/high candle.
MA — Dynamic Stop based on selected Moving Average. * You will have 8 types of MA (EMA, SMA, HMA, etc.) to choose from, but you can easily add dozens of other MAs, which makes this type of stop incredibly flexible.
Add % — If true, then with the "𝗦𝘁𝗼𝗽 %" parameter you can add percentages to any of the current SL. Can be especially useful when using Stop - 𝗔𝗧𝗥 or 𝗠𝗔 or 𝗟𝗢/𝗛𝗜. For example with 𝗟𝗢/𝗛𝗜 to put a stop for the last High/Low and add 0.5% additional Stoploss.
Fixed R:R — If the stop loss is Dynamic (Trailing or MA) then if R:R true can also be made Dynamic * Use it carefully, the function is experimental.
_________________________________________
⚉ TAKE PROFIT LEVELS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
A unique method of constructing intermediate Take Profit Levels will allow you to select up to 5 intermediate Take Profit Levels and one intermediate Stop Loss.
Intermediate Take Profit Levels are perfectly calculated into 5 equal parts in the form of levels from the entry point to the final Take Profit target.
All you need to do is to choose the necessary levels for fixing and how much you want to fix at each level as a percentage. For example, TP 3 will always be exactly between the entry point and the Take Profit target. And the value of TP 3 = 50 will close 50% of the amount of the remaining size of the position.
Note: all intermediate SL/TP are closed from the remaining position amount and not from the initial position size, as TV does by default.
SL 0 Position — works in the same way as TP 1-5 but it's Stop. With this parameter you can set the position where the intermediate stop will be set.
Breakeven on TP — When activated, it allows you to put the stop loss at Breakeven after the selected TP is reached. For this function to work as it should - you need to activate an intermediate Take. For example, if TP 3 is activated and Breakeven on TP = 3, then after the price reaches this level, the Stop loss will go to Breakeven.
* This function will not work with Dynamic Stoplosses, because it simply does not make sense.
CoolDown # Bars — When activated, allows you to add a delay before a new trade is opened. A new trade after CoolDown will not be opened until # bars pass and a new signal appears.
_____________________________
⚉ TIME FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Powerful time filter code that allows you to filter data based on specific time zones, dates, and session days. This code is ideal for those who need to analyze data from different time zones and weed out irrelevant data.
With Time Filter, you can easily set the starting and ending time zones by which you want to filter the data.
You can also set a start and end date for your data and choose which days of the week to include in the analysis. In addition, you can specify start and end times for a specific session, allowing you to focus your analysis on specific time periods.
_________________________________
⚉ SIGNAL FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Signal Filters — allows you to easily customize and optimize your trading strategies based on 10 filters.
Each filter is designed to help you weed out inaccurate signals to minimize your risks.
Let's take a look at their features:
__________________________________
⚉ RISK MANAGEMENT ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Risk management tools that allow you to set the maximum number of losing trades in a row, a limit on the number of trades per day or week and other filters.
Loss Streak — Set Max number of consecutive loss trades.
Win Streak — Max Winning Streak Length.
Row Loss InDay — Max of consecutive days with a loss in a row.
DrawDown % — Max DrawDown (in % of strategy equity).
InDay Loss % — Set Max Intraday Loss.
Daily Trades — Limit the number of MAX trades per day.
Weekly Trades — Limit the number of MAX trades per week.
* 🡅 I would Not Recommend using these functions without understanding how they work.
Order Size — Position Size
• NONE — Use the default position size settings in Tab "Properties".
• EQUITY — The amount of the allowed position as a percentage of the initial capital.
• Use Net Profit — On/Off the use of profit in the following trades. *Only works if the type is EQUITY.
• SIZE — The size of the allowed position in monetary terms.
• Contracts — The size of the allowed position in the contracts. 1 Сontract = Сurrent price.
________________
⚉ NOTES ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
It is important to note that I have never worked with Backtesting and the functions associated with them before.
It took me about a month of slow work to build this system.
I want to say Big Thanks:
• The PineScripters🌲 group in Telegram , the guys suggested how to implement some features. Especially @allanster
• Thanks to all those people who share their developments for free on TV and not only.
• I also thank myself for not giving up and finishing the project, and not trying to monetize the system by selling it. * Although I really want the money :)
I tried hard to make it as fast and convenient as possible for everyone who will use my code.
That's why I didn't use any libraries and dozens of heavy functions, and I managed to fit in 8+-functions for the whole code.
Absolutely every block of code I tried to make full-fledged modular, that it was easy to import/edit for myself (you).
I have abused the Ternary Pine operator a little (a lot) so that the code was as compact as possible.
Nevertheless, I tried very hard to keep my code very understandable even for beginners.
At last I managed to write 500 lines of code, making it one of the fastest and most feature-rich systems out there.
I hope everyone enjoys my work.
Put comments and write likes.
Strategy Template + Performance & Returns table + ExtrasA script I've been working on since summer 2022. A template for any strategy so you just have to write or paste the code and go straight into risk management settings
Features:
>Signal only Longs/only Shorts/Both
>Leverage system
>Proper fees calculation (even with leverage on)
>Different Stop Loss systems: Simple percentage, 4 different "move to Break Even" systems and Scaling SL after each TP order (read the disclaimer at the bottom regarding this and the TV % profitable metric)
>2 Take Profit systems: Simple percentages, or Risk/reward ratios based on SL level
>Additional option on TP so last one "rides free" until closure of position or Stoploss is hit (for more than 1 orders)
>Up to 5 TP orders
>Show or hide SL/TP levels on demand
>2 date filters. Manual filter is nothing new, enter two dates/hours and filter will turn on. BUT automatic filter is another thing (thanks to user @bfr_ for his help in codingthis feature)
>AUTOMATIC DATE FILTER. Allows you to split all historical data on the chart in X periods, then choose the range of periods used. Up to 10 but that can be changed, instructions included. Useful for WalkForward simulations, haven't seen a script in TradingView that allows you to do this and test your strategy on "unseen data" automatically
EXTRA SETTINGS
Besides, some additions I like to add to my codes:
>Returns table for monthly and weekly performance. Requires recalculation on every tick. This is a modified version of @QuantNomad's work. May add lower TF options later on
>Volume Based S/R system. Original work from @shtcoinr
>One feature that was made by me, the "portfolio table". Yields info and metrics of your strategy, current position and balance. You're able to turn it off and change its size
Should anyone find an error, or have any idea on how to improve this code, please contact me. Future updates could come, stay tuned
DISCLAIMER:
In order to have accurate StopLoss hit, I had to change the previous system, which was a "close position on candle close" instead at actual stoploss level. It was fixed, but resulted on inflation of the number of trading orders, thus reducing the percent profitable and making it strongly biased and unreal. Keep that in mind, that "real" profitability could be 2x or 3x the metric TradingView says. If your strategy has a really high trading frequency, resulting in 3000+ orders, might be a problem. Try to make use of the automatic/manual date filter as workaround, I have no means of changing this, seems it is not a bug but an intended design of the PineScript Code
HTF Bars Discrepancy Detector (for debugging)Illustrate discrepancies between two symbols of the same higher timeframe.
Sometimes:
- HTF data can come for one symbol but not for another
- or come with gaps (e.g. after HTF bar 3 in the next chart TF's candle we have HTF bar 5 for one or both symbols)
Volume [theEccentricTrader]OVERVIEW
This indicator simply bridges the gap between symbols from brokers that provide volume data and symbols from brokers that do not provide volume data. Users can select any symbol that provides volume data from the settings menu and the volume data will be displayed in histogram form on their current chart. The default volume symbol is CURRENCYCOM:US500.
CONCEPTS
Volume
Volume refers to the total number of shares or contracts that are traded during a given period of time. It is a measure of the amount of activity in the market and can be used to gauge the strength or weakness of a particular trend.
Volume is typically displayed as a histogram on trading charts, with each bar representing the total volume for a particular time period. High volume bars indicate a lot of trading activity, while low volume bars indicate relatively little trading activity.
Traders use volume in a number of ways. For example, they may use it to confirm a trend. If a stock is trending up and the volume is also increasing, this can be seen as a sign that the trend is strong and likely to continue. Conversely, if a stock is trending down and the volume is also increasing, this can be seen as a sign that the trend is weak and may be coming to an end. Volume can similarly be used to identify potential reversals. If a stock is trending up but the volume starts to decrease, this could indicate that the trend is losing momentum and that a reversal may be imminent.
FEATURES
Inputs
• Volume Symbol
Style
Users can change plot color and style from the default Style menu if so required.
NOTES
For 24-hour markets and forex volume I use the broker currency.com. As can be seen in the example above, I am using CURRENCYCOM:USDJPY to pull volume to a FOREXCOM:USDJPY chart, which otherwise would not show volume data as forex.com do not provide it.
Intra-Candles*For use with <=24 hour Hollow Candles *
Indicator for more informative candle plotting. Select from 2-6 lower timeframe candles and view the price action of the lower bars within the normal chart's candles. Plotting short time frame candles with a semi-transparent body lets you see reversals that occurred during the larger candle's formation. Use the information provided to inform your own trading decisions.
Trading Checklist - SonarlabTrading Checklist is a customizable indicator designed for traders who want to stay disciplined and stick to their trading rules. Using this indicator, you can easily create and display your own personalized checklist of trading rules directly on your TradingView chart.
The Title and the Body are two different sections, so you can set two different styles.
This indicator allows you to customize:
Text color
Text size
Text alignment
RedK DIY ZLMA: Customizable Zero-Lag MA (Educational / Utility)This script is more of an educational / utility piece rather than a fully-fledged indicator - It provides an easy way to customize and produce a zero-lag Moving average that can then be used in various scenarios
What is DIY_ZLMA?
------------------------
The DIY ZLMA is for fans and enthusiasts of researching Moving Averages (like me) - the script enables the user to play around with one of the common approaches used to reduce lag in moving averages - which was explained in this old post below
Suggested uses of the DIY_ZLMA
---------------------------------------
* The Zero-lag approach here applies 3 moving average passes to a source data series - I'll refer to these 3 passes as Base MA Pass , De-lagging Pass, and Smoothing Pass - these "passes" can be customized from the indicator settings in terms of MA Length and type. The first pass allows the choice of a "source", and the second pass allows additional fine tuning by playing around with the magnification factor. The 3rd pass (smoothing) is optional and can be skipped altogether when needed. (as noted in the script, HMA and TEMA, which are very common low-lag MA's use slightly different approach in the calculation than the one used here .. so we can't get an equivalent of either of these MA's with the customization of DIY_ZLMA parameters)
* After the user experiments with the various settings for the 3 passes, and finds a "preferred combination", the script not only plots the resulting My_ZLMA - it also produces the "1-line Pine script formula" that the user can then use in any other script, maybe to smoothen some data series, or to combine with other types of moving averages to create multi-MA cross-over trading signals... and so on.
* The DIY_ZLMA can also be added to another indicator as a signal line using the Indicator-on-Indicator feature of TradingView (review this post for step-by-step -->
)
* the script also showcases couple of recent (and very neat) Pine features: the use of User-defined Types (UDT) and User-defined Methods - which are awesome and a lot of fun to work with :)
Since this is more of a utility piece, I added as many comments as possible to the script to explain the way it works - so it's more valuable if someone finds it by searching the "Add Indicator" feature in TradingView charts
Please feel free to play around with this new toy :) and share comments and feedback below if you find this useful. I truly hope you do.
Trade Ideas to Discord WebhookTakes basic user inputs for entries, exits, stop loss and leverage.
Converts all inputs (removing unused ones) to an alert message.
Intended for use as a single alert / message.
Alert will fire as soon as activated - after that you should delete the alert to prevent multiple alerts being fired on subsequent candles.
X48 - Strategy | BreakOut & Consecutive (11in1) + Alert | V.1.2================== Read This First Before Use This Strategy ==============
*********** Please be aware that this strategy is not a guarantee of success and may lead to losses.
*********** Trading involves risk and you should always do your own research before making any decisions.
================= Thanks Source Script and Explain This Strategy ===================
► Description
Write a detailed and meaningful description that allows users to understand how your script is original, what it does, how it does it and how to use it
This Strategy Are Combine Strategy and Indicators Alert Function For Systematic Trading User.
Strategy List, Thanks For Original Source Script , From Tradingview Build-in Script From fmzquant Github
// Channel BreakOut Strategy : Calculate BreakOut Zone For Buy and Sell.
// Consecutive Bars UP/Down Strategy : The consecutive bars up/down strategy is a trading strategy used to identify potential buy and sell signals in the stock market. This strategy involves looking for a series of bars (or candles) that are either all increasing or all decreasing in price. If the bars are all increasing, it can be a signal to buy, and if the bars are all decreasing, it can be a signal to sell. This strategy can be used on any timeframe, from a daily chart to an intraday chart.
// 15m Range Length SD : Range Of High and Low Candle Price and Lookback For Calculate Buy and Sell.
Indicators Are Simple Source Script (Almost I'm Chating With CHAT-GPT and Convert pinescript V4 to V5 again for complete almost script and combine after)
// SwingHigh and SwingLow Plot For SL (StopLoss by Last Swing).
// Engulfing and 3 Candle Engulfing Plot.
// Stochastic RSI for Plot and Fill Background Paint and Plot TEXT For BULL and BEAR TREND.
// MA TYPE MODE are plot 2 line of MA Type (EMA, SMA, HMA, WMA, VWMA) for Crossover and Crossunder.
// Donchian Fans MODE are Plot Dot Line With Triangle Degree Bull Trend is Green Plot and Bear Trend is Red Plot.
// Ichimoku Cloud Are Plot Cloud A-B For Bull and Bear Trend.
// RSI OB and OS for TEXT PLOT 'OB' , 'OS' you will know after OB and OS, you can combo with other indicators that's make you know what's the similar trend look like?
// MACD for Plot Diamond when MACD > 0 and MACD < 0, you can combo with other indicators that's make you know what's the similar trend look like?
Alert Can Alert Sent When Buy and Sell or TP and SL, you can adjust text to alert sent by your self or use default setting.
========== Let'e Me Explain How To Use This Strategy =============
========== Properties Setting ==========
// Capital : Default : 1,000 USDT For Alot Of People Are Beginner Investor = It's Capital Your Cash For Investment
// Ordersize : Default Are Setting 5% / Order We Call Compounded
========== INPUT Setting ==========
// First Part Use Must Choose Checkbox For Use of Strategy and Choose TP/SL by Swing or % (can choose both)
// In Detail Of Setting Are Not Too Much, Please Read The Header Of Setting Before Change The Value
// For The Indicator In List You Want To Add Just Check ✅ From MODE Setting, It's Show On Your Chart
// You Can Custom TP/SL % You Want
========== ##### No trading strategy is guaranteed to be 100% successful. ###### =========
For Example In My Systematic Trading
Select 1/3 Strategy Setting TP/SL % Match With Timeframe TP Long Are Not Set It's Can 161.8 - 423.6% but Short Position Are Not Than 100% Just Fine From Your Aset
Choose Indicators For Make Sure Trend and Strategy are the same way like Strategy are Long Position but MACD and Sto background is bear. that's mean this time not open position.
Donchian Fans is Simple Support and Ressistant If You Don't Know How To Plot That's, This indicator plot a simple for you ><.
Make Sure With Engulfing and 3 Candle Engulfing If You Don't Know, What's The Engulfing, This Indicator are plot for you too ><.
For a Big Trend You can use Ichimoku Cloud For Check Trend, Candle Upper Than Cloud or Lower Than Cloud for Bull and Bear Trend.
Click Signal IndicatorThis is a Signal Indicator that emits signals based on mouse clicks when the indicator is added to the chart, or later on in the "Settings/Inputs" tab by changing/selecting the open time of the desired bar of each one of the signals.
It is designed to be used as an External Input for the "Template Trailing Strategy" to verify the correctness of the features the aforementioned script offers, and to provide an easy way to play around with this framework.
Last but not least this script offers a way to debug and report problems when this is necessary. Moreover, this script is a simple example you can copy-paste and create your own custom signal indicator that can be "plugged into"
the "Template Trailing Strategy" taking advantage of all the fancy stuff the TTS framework can provide!
To connect this signal indicator to the TTS you have to change the "Deal Conditions Mode" to '🔨External' and the 'External Input 🛈➡' to 'CSI:🔌Signal' in the TTS "Settings/Inputs" tab. For more information check the "Template Trailing Strategy - Part 02" video tutorial.
Vertical Lines 2A vertical line plotting function is missing in Pinescript. This is another method to plot vertical line on a chart, and an improvement on my previous script "vertical lines" .
The script hacks the plotcandle function to display just the wicks without the body. This hack simulates a vertical line. The body of the candle is non-existing since the open and close are the same and its color is set to null. The wicks are abutting resulting in a continuous vertical line.
Drawbacks include inability to set width and transparency of the lines. The plotcandle function does not allow setting the width and transparency of the wicks. This feature would be desirable.
The crossing of the RSI of overbought and undersold zones is used as an example in this published script. Any indicator can be used and this script can be executed on any other indicator by using "add indicator" on the desired indicator, and selecting the indicator as the source. I added crossover lines on the plotted RSI as an example.
//////////////////////////////////////////////////////Breakdown of the script////////////////////////////////////////////////////////
The src input determines which price data is used for the highest value calculation. By default, it is set to the close price.
The length input determines the length of the RSI calculation. By default, it is set to 14.
The mult input determines the multiplier of the highest value that is used to determine the height of the vertical lines. By default, it is set to 100%, meaning the lines will reach the highest value in the dataset.
The top and bot inputs determine the overbought and oversold levels for the RSI. By default, they are set to 70 and 30, respectively.
The current_rsi and previous_rsi variables calculate the RSI values for the current bar and the previous bar, respectively.
The hi_value variable finds the highest value in the dataset, and the hi variable calculates the height of the vertical lines based on the highest value and the user-defined multiplier. The lo variable calculates the distance between the highest value and the current price data.
The uph, dnh, upl, and dnl variables determine the height and low of the vertical lines for when the RSI crosses overbought or oversold levels.
The if statements check if the RSI has crossed overbought or oversold levels and set the uph, dnh, upl, and dnl variables accordingly.
Finally, the plotcandle() function is used to plot the vertical lines on the chart. The open and close values are set to the src input, and the high and low values are set to the uph, dnh, upl, and dnl variables. The bordercolor argument is set to na to hide the borders of the lines, and the wickcolor argument is set to green or red, depending on whether the line is an overbought or oversold crossover.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
USBOND_BackCalcDetermining bond prices from yields on US Treasuries.
Cannot be used because it is not a chart of US Treasuries and yields.
米国債の利回りから債券価格を求める。
米国債利回り以外のチャートでは使用できません。
債券価格 = 100 * (1 + 利回り(終値))^(-残年数)