Fib RetracementI've re-created the fib retracement tool as an indicator and this is as close as I can currently get to matching the built-in fib retracement tool.
Why did I make this? For custom labels for every fib retracement level.
Caveats to this vs the built-in tool are:
the "Save as Default" doesn't appear to work (I believe this is due to the interactive/confirm based settings)
copy and paste to another chart is locked into the price of source location
when dragging the points of retracement the tool/indicator disappears
Hopefully some can find usefulness in this code or it's functionality.
Pine utilities
Grid Indicator - The Quant ScienceQuickly draw a 10-level grid on your chart with our open-source tool.
Our grid tool offers a unique solution to traders looking to maximize their profits in volatile market conditions. With its advanced features, you can create customized grids based on your preferred start price and line distance, allowing you to easily execute trades and capitalize on price movements. The tool works automatically, freeing up your time to focus on other important aspects of your trading strategy.
The benefits of using this tool are numerous. Firstly, it eliminates the need for manual calculation, making the analysis process much more efficient. Secondly, the automatic nature of the tool ensures that each grids are draw at precisely prices, giving you the best possible chance of maximizing your analysis. Finally, the ability to easily customize grids means that you can adapt your strategy quickly and effectively, even in rapidly changing market conditions.
So why wait? Take control of your trading and start using our innovative grid tool today! With its advanced features and ease of use, it's the perfect solution for traders of all levels looking to take their trading to the next level.
HOW TO USE
Using it is easy. Add the script to your chart and set the price and distance between the grids.
Premium/Discount Zone Buy/Sell Indicator JMJThis indicator calculates whether the opening price is in a premium or discount zone, based on the specified premiumThreshold and discountThreshold values. A premium zone is defined as when the difference between the high price and the opening price divided by the opening price is greater than or equal to premiumThreshold. A discount zone is defined as when the difference between the opening price and the low price divided by the opening price is less than or equal to discountThreshold. The premium and discount signals are plotted as green and red triangles, respectively.
HTF Bar Close CountdownThis simple indicator displays a countdown for the amount of time left until a bar of your chosen timeframe closes.
Displays up to 5 different HTF countdowns.
Fully Customizable to fit any style, change the text colors, background colors, frame colors, display size and border & frame widths.
Flat display option for a sleek look to mesh with your charts.
Notes/Tips:
Higher Time Frames only! This is only intended to view HTF countdowns, will not work when trying to use a timeframe lower than your current chart's.
Some weird timeframes do not work, you'll know when.
Only works on live charts! Will display "Closed" when on an inactive chart.
Does not work for replay! A countdown is pretty pointless on a replay that is not real-time anyways...
Enjoy!
ANTEYA ProfilingThis script allows to compare which code is more efficient by running it inside a loop for a certain time or a certain number of iterations.
Just paste your pieces of code as Option 1 and Option 2 inside the loop (see comments in the script).
Bar MagnifierMany times while developing algos based on patterns and reversals, I come across issues which needs lower timeframe inspection. Loading multiple charts and comparing equivalent lower timeframe is slightly cumbersome at times. Hence, I thought of building this simple tool - which will instantly provide me lower timeframe candles for given candle. Since the candle selection happen via confirmed time input, we can use this as slider to move from one candle to other for inspection.
🎲 Usage
🎯Loading the script
When you load the script, a prompt appears which asks you to select a time by clicking on the chart.
Select the bar you want to magnify and study
🎯Components
Once loaded, you can see the marker which tells which bar is magnified. And you can also see all the lower timeframe candles before that point. Please note that due to pine restrictions, we can only show last 250 lower timeframe bars. You can change the lower timeframe via settings to cover if the chart timeframe is very high.
🎯Moving to different bars
Click on the middle of the marker, you will see slider which you can slide to move from one bar to other.
Example, after sliding, you will see the lower timeframe data of new candle.
🎯Settings
Settings has only two inputs.
Bar time - selects the bar which needs to be inspected.
Lower timeframe - Default is 1 min. And select a timeframe according to your chart timeframe. Less than 1 min is not supported by security.lower_tf function. Hence, will not work.
[CLX] Progressbar - LogoThis script is part of the Library Progressbar - Showcase. You can find it under:
Composite Cosmetic CandlesThis is effectively version 2 of my script "Candle Fill % Meter", with a few different/more options available in a more compact form. Choose between multiple oscillator sources, # of dividing lines, and solid or gradient candle fill. Once again this script is intended for use with hollow candles! This script enables you to see more information with less screen space taken up, not to mention it looks nice. Labels by last bar also toggleable in the settings.
PSv5 3D Array/Matrix Super Hack"In a world of ever pervasive and universal deceit, telling a simple truth is considered a revolutionary act."
INTRO:
First, how about a little bit of philosophic poetry with another dimension applied to it?
The "matrix of control" is everywhere...
It is all around us, even now in the very place you reside. You can see it when you look at your digitized window outwards into the world, or when you turn on regularly scheduled television "programs" to watch news narratives and movies that subliminally influence your thoughts, feelings, and emotions. You have felt it every time you have clocked into dead end job workplaces... when you unknowingly worshiped on the conformancy alter to cultish ideologies... and when you pay your taxes to a godvernment that is poisoning you softly and quietly by injecting your mind and body with (psyOps + toxicCompounds). It is a fictitiously generated world view that has been pulled over your eyes to blindfold, censor, and mentally prostrate you from spiritually hearing the real truth.
What TRUTH you must wonder? That you are cognitively enslaved, like everyone else. You were born into mental bondage, born into an illusory societal prison complex that you are entirely incapable of smelling, tasting, or touching. Its a contrived monetary prison enterprise for your mind and eternal soul, built by pretending politicians, corporate CONartists, and NonGoverning parasitic Organizations deploying any means of infiltration and deception by using every tactic unimaginable. You are slowly being convinced into becoming a genetically altered cyborg by acclimation, socially engineered and chipped to eventually no longer be 100% human.
Unfortunately no one can be told eloquently enough in words what the matrix of control truly is. You have to experience it and witness it for yourself. This is your chance to program a future paradigm that doesn't yet exist. After visiting here, there is absolutely no turning back. You can continually take the blue pill BIGpharmacide wants you to repeatedly intake. The story ends if you continually sleep walk through a 2D hologram life, believing whatever you wish to believe until you cease to exist. OR, you can take the red pill challenge, explore "question every single thing" wonderland, program your arse off with 3D capabilities, ultimately ascertaining a new mathematical empyrean. Only then can you fully awaken to discover how deep the rabbit hole state of affairs transpire worldwide with a genuine open mind.
Remember, all I'm offering is a mathematical truth, nothing more...
PURPOSE:
With that being said above, it is now time for advanced developers to start creating their own matrix constructs in 3D, in Pine, just as the universe is created spatially. For those of you who instantly know what this script's potential is easily capable of, you already know what you have to do with it. While this is simplistically just a 3D array for either integers or floats, additional companion functions can in the future be constructed by other members to provide a more complete matrix/array library for millions of folks on TV. I do encourage the most courageous of mathemagicians on TV to do so. I have been employing very large 2D/3D array structures for quite some time, and their utility seems to be of great benefit. Discovering that for myself, I fully realized that Pine is incomplete and must be provided with this agility to process complex datasets that traders WILL use in the future. Mark my words!
CONCEPTION:
While I have long realized and theorized this code for a great duration of time, I was finally able to turn it into a Pine reality with the assistance and training of an "artificially intuitive" program while probing its aptitude. Even though it knows virtually nothing about Pine Script 4.0 or 5.0 syntax, functions, and behavior, I was able to conjure code into an identity similar to what you see now within a few minutes. Close enough for me! Many manual edits later for pine compliance, and I had it in chart, presto!
While most people consider the service to be an "AI", it didn't pass my Pine Turing test. I did have to repeatedly correct it, suffered through numerous apologies from it, was forced to use specifically tailored words, and also rationally debate AND argued with it. It is a handy helper but beware of generating Pine code from it, trust me on this one. However... this artificially intuitive service is currently available in its infancy as version 3. Version 4 most likely will have more diversity to enhance my algorithmic expertise of Pine wizardry. I do have to thank E.M. and his developers for an eye opening experience, or NONE of this code below would be available as you now witness it today.
LIMITATIONS:
As of this initial release, Pine only supports 100,000 array elements maximum. For example, when using this code, a 50x50x40 element configuration will exceed this limit, but 50x50x39 will work. You will always have to keep that in mind during development. Running that size of an array structure on every single bar will most likely time out within 20-40 seconds. This is not the most efficient method compared to a real native 3D array in action. Ehlers adepts, this might not be 100% of what you require to "move forward". You can try, but head room with a low ceiling currently will be challenging to walk in for now, even with extremely optimized Pine code.
A few common functions are provided, but this can be extended extensively later if you choose to undertake that endeavor. Use the code as is and/or however you deem necessary. Any TV member is granted absolute freedom to do what they wish as they please. I ultimately wish to eventually see a fully equipped library version for both matrix3D AND array3D created by collaborative efforts that will probably require many Pine poets testing collectively. This is just a bare bones prototype until that day arrives. Considerably more computational server power will be required also. Anyways, I hope you shall find this code somewhat useful.
Notice: Unfortunately, I will not provide any integration support into members projects at all. I have my own projects that require too much of my time already.
POTENTIAL APPLICATIONS:
The creation of very large coefficient 3D caches/buffers specifically at bar_index==0 can dramatically increase runtime agility for thousands of bars onwards. Generating 1000s of values once and just accessing those generated values is much faster. Also, when running dozens of algorithms simultaneously, a record of performance statistics can be kept, self-analyzed, and visually presented to the developer/user. And, everything else under the sun can be created beyond a developers wildest dreams...
EPILOGUE:
Free your mind!!! And unleash weapons of mass financial creation upon the earth for all to utilize via the "Power of Pine". Flying monkeys and minions are waging economic sabotage upon humanity, decimating markets and exchanges. You can always see it your market charts when things go horribly wrong. This is going to be an astronomical technical challenge to continually navigate very choppy financial markets that are increasingly becoming more and more unstable and volatile. Ordinary one plot algorithms simply are not enough anymore. Statistics and analysis sits above everything imagined. This includes banking, godvernment, corporations, REAL science, technology, health, medicine, transportation, energy, food, etc... We have a unique perspective of the world that most people will never get to see, depending on where you look. With an ever increasingly complex world in constant dynamic flux, novel ways to process data intricately MUST emerge into existence in order to tackle phenomenal tasks required in the future. Achieving data analysis in 3D forms is just one lonely step of many more to come.
At this time the WesternEconomicFraudsters and the WorldHealthOrders are attempting to destroy/reset the world's financial status in order to rain in chaos upon most nations, causing asset devaluation and hyper-inflation. Every form of deception, infiltration, and theft is occurring with a result of destroyed wealth in preparation to consolidate it. Open discussions, available to the public, by world leaders/moguls are fantasizing about new dystopian system as a one size fits all nations solution of digitalID combined with programmableDemonicCurrencies to usher in a new form of obedient servitude to a unipolar digitized hegemony of monetary vampires. If they do succeed with economic conquest, as they have publicly stated, people will be converted into human cattle, herded within smart cities, you will own nothing, eat bugs for breakfast/lunch/dinner, live without heat during severe winter conditions, and be happy. They clearly haven't done the math, as they are far outnumbered by a ratio of 1 to millions. Sith Lords do not own planet Earth! The new world disorder of human exploitation will FAIL. History, my "greatest teacher" for decades reminds us over, and over, and over again, and what are time series for anyways? They are for an intense mathematical analysis of prior historical values/conditions in relation to today's values/conditions... I imagine one day we will be able to ask an all-seeing AI, "WHO IS TO BLAME AND WHY AND WHEN?" comprised of 300 pages in great detail with images, charts, and statistics.
What are the true costs of malignant lies? I will tell you... 64bit numbers are NOT even capable of calculating the extreme cost of pernicious lies and deceit. That's how gigantic this monstrous globalization problem has become and how awful the "matrix of control" truly is now. ALL nations need a monumental revision of its CODE OF ETHICS, and that's definitely a multi-dimensional problem that needs solved sooner than later. If it was up to me, economies and technology would be developed so extensively to eliminate scarcity and increase the standard of living so high, that the notion of war and conflict would be considered irrelevant and extremely appalling to the future generations of humanity, our grandchildren born and unborn. The future will not be owned and operated by geriatric robber barons destined to expire quickly. The future will most likely be intensely "guided" by intelligent open source algorithms that youthful generations will inherit as their birth right.
P.S. Don't give me that politco-my-diction crap speech below in comments. If they weren't meddling with economics mucking up 100% of our chart results in 100% of tickers, I wouldn't have any cause to analyze any effects generated by them, nor provide this script's code. I am performing my analytical homework, but have you? Do you you know WHY international affairs are in dire jeopardy? Without why, the "Power of Pine" would have never existed as it specifically does today. I'm giving away much of my mental power generously to TV members so you are specifically empowered beyond most mathematical agilities commonly existing. I'm just a messenger of profound ideas. Loving and loathing of words is ALWAYS in the eye of beholders, and that's why the freedom of speech is enshrined as #1 in the constitutional code of the USA. Without it, this entire site might not have been allowed to exist from its founder's inceptions.
Signal ViewerThe "Signal Viewer" script is a debugging tool that can be used for the signal of a Signal Indicator script like the "Two MA Signal Indicator" or the "Template Signal Indicator". This script will visualize the signal based on the convention that was defined in the settings. Also, alerts will be produced based on this convention. It's useful to be used before you connect the signal indicator script to a template strategy like the "Template Trailing Strategy" script. You can cross-validate the correctness of the signal that the indicators emit and make sure it is aligned with the expected behavior after the decomposition of the signal using the convention described in the settings. Please make sure that the connection in the "Signal Viewer" script matches the convention used by the template strategy script.
occ3aka weighted fair price
The ultimate price source for all your stuff, unless you go completely nuts.
The ultimate way to build line charts & do pattern trading, unless you go completely nuts.
Why occ3?
You need a one-point estimate for every bar, a typical price of every bar aye? But then you see that every bar has a different distribution of prices. You can drop a stat test on every bar and pick median, mean, or whatever. But that's still prone to error (imagine borderline cases).
Instead, you can transform the task into a geometric one and say, "I wanna find the center of mass of all dem ticks within a particular interval (a day, a week, a century)". But lol ofc you won't do it, so lets's estimate it:
1) a straight line from Open to Close more/less estimates a regression line if you woulda dropped regression on all the ticks within a given interval;
2) centroid always lies on regression line, so it's always in between the endpoints of regression line. So that's why (open + close) /2;
3) Then, you remember that sequence matters, + generally the volume is higher near the close, so...;
4) Voila, (open + close + close) / 3
Why "fair" price?
Take a daily bar:
1) High & low were the best prices to sell & buy;
2) Opening & closing auctions had acceptable prices, in exchange for the the biggest potential to transact serious volume;
3) "Fair" price, logically, is somewhere in between the acceptable prices;
4) Market is fractal => the same principles propagate everywhere;
4) No, POCs and VPOCs don't make much sense as fair prices.
Nothing else to say, really advise to use it as a line chart if you trade price patterns.
Volume Weighted Standard Deviation (VWSD)The Volume Weighted Standard Deviation indicator is a custom technical analysis tool that uses the volume of trading to calculate the standard deviation of a stock's price. This indicator takes the source of data, the length of data, and the deviation as inputs, and calculates the volume weighted standard deviation using the values.
The indicator first calculates the mean price and mean volume by using simple moving average over the given length of data. Then it calculates the squared difference between the mean price and the actual price, multiplied by the volume. This gives a volume-weighted squared difference. The indicator then calculates the square root of the sum of the volume-weighted squared differences divided by the sum of the volumes over the given length of data. This gives the volume weighted standard deviation.
The indicator then plots the standard deviation and deviation as a band around the simple moving average of the source data, providing a clear view of the volatility of the stock.
In summary, the Volume Weighted Standard Deviation indicator is a powerful tool for measuring the volatility of a stock by taking into account the volume of trading. It uses the volume of trading to calculate the standard deviation of a stock's price, giving a more accurate representation of the volatility of the stock. It can be useful for traders to identify entry and exit points and make more informed trading decisions.
Chart Time and Price Range It is easy to loose track of time and price volatility when the chart automatically scales to the bars on the chart. This helps you keep track.
This is a very simple indicator that is designed to ensure that you're looking at a segment of the chart that is relevant to the trade you're considering in both price distance and time.
The Problem:
When looking at a chart the lowest price is at the bottom of the screen, the highest price is at the top. The time at the beginning of the chart is based on how many bars and what timeframe you're looking at.
But is the price difference between the two wide or narrow? Are you seeing minutes, hours, or days of price action?
You can get the measure tool out, but you'll change the zoom level and now its different. You change the timeframe and its different.
This Solution:
This indicator puts a table on the screen that will tell you the X/Y distance of everything that is on your chart. If your hold period is 5 minutes, why would you be looking at 3 days of price action to find s/r or make a decision on a trade?
This will show you how much price opportunity was available in the amount of time you are currently viewing. Using the PineCoders VisibleChart library, we're retrieving the time and bar_index of the beginning of the chart so that everything that is currently on the chart is measured and it adapts as that changes.
It will work with light and dark themes (you can change the colors) and can be positioned wherever you prefer to see the information.
Disclaimer: This was a quick release script. I wrote it and published the same day. There could be bugs, so send me a message or add a comment to report anything that isn't behaving correctly.
Probabilities Module - The Quant Science This module can be integrate in your code strategy or indicator and will help you to calculate the percentage probability on specific event inside your strategy. The main goal is improve and simplify the workflow if you are trying to build a quantitative strategy or indicator based on statistics or reinforcement model.
Logic
The script made a simulation inside your code based on a single event. For single event mean a trading logic composed by three different objects: entry, take profit, stop loss.
The script scrape in the past through a look back function and return the positive percentage probability about the positive event inside the data sample. In this way you are able to understand and calculate how many time (in percentage term) the conditions inside the single event are positive, helping to create your statistical edge.
You can adjust the look back period in you user interface.
How can set up the module for your use case
At the top of the script you can find:
1. entry_condition : replace the default condition with your specific entry condition.
2. TPcondition_exit : replace the default condition with your specific take profit condition.
3. SLcondition_exit : replace the default condition with your specific stop loss condition.
Lines and Table for risk managementABOUT THIS INDICATOR
This is a simple indicator that can help you manage the risk when you are trading, and especially if you are leverage trading. The indicator can also be used to help visualize and to find trades within a suitable or predefined trading range.
This script calculates and draws six “profit and risk lines” (levels) that show the change in percentage from the current price. The values are also shown in a table, to help you get a quick overview of risk before you trade.
ABOUT THE LINES/VALUES
This indicator draws seven percentage-lines, where the dotted line in the middle represents the current price. The other three lines on top of and below the middle line shows the different levels of change in percentage from current price (dotted line). The values are also shown in a table.
DEFAULT VALUES AND SETTINGS
By default the indicator draw lines 0.5%, 1.0%, and 1.5% from current price (step size = 0.5).
The default setting for leverage in this indicator = 1 (i.e. no leverage).
The line closest to dotted line (current price) is calculated by step size (%) * leverage (x) = % from price.
Pay attention to the %-values in the table, they represent the distance from the current price (dotted line) to where the lines are drawn.
* Be aware! If you change the leverage, the distance from the closest lines to the dotted line showing the current price increase.
SETTINGS
1. Leverage: set the leverage for what you are planning to trade on (1 = no leverage, 2 = 2 x leverage, 5 = 5 x leverage...).
2. Stepsize is used to set the distance between the lines and price.
EXAMPLES WITH DIFFERENT SETTINGS
1) Leverage = 1 (no leverage, default setting) and step size 0.5 (%). Lines plotted at (0.5%, 1%, 1.5%, and –0.5%, –1%, –1,5%) from the current price.
2) Leverage = 3 and stepsize 0.5(%). Lines plotted at (1.5%, 3.0%, 4.5%, and –1.5%, –3.0%, –4.5%) from the current price.
3) Leverage = 3 and stepsize 1(%). Lines plotted at (3%, 6%, 9%, and –3%, –6%, –9%) from the current price.
The distance to the nearest line from the current price is always calculated by the formula: Leverage * step size (%) = % to the nearest line from the current price.
Crypto Index (DXY) CandlesA modification of @loxx's "Dollar Index (DXY) Candles" allowing for a user selected basket of tickers using the same weights as the standard DXY. Ticker Inputs are in descending order so highest weight is at the top by default, although weighting can be changed manually by modifying the symbol's corresponding weight input in the settings. The Idea was to get a bird's eye view of the crypto space using some of the more relevant names in the space. User's can use the toggle in the settings for viewing the default DXY for comparison. Indicator should be used as a confirmation when looking at long term trend changes in the space, shorter time frames may, or may not be as useful.
Manage tradeThis indicator is intended to simulate a second entry to adjust the average price.
INPUTS:
Current price || Coins -> Current price, your first entry || Initial amount of coins
Simulate entry || Coins -> New entry, from this entry the average price will be calculated || new amount of coins
Simulate partial % || Coins -> Percentage over current price or average price || Amount of coins withdrawn
* Currency conversion
Value $ || Target price -> amount or coins, example: 25 dolar or 25 busd || Acquisition target price, returns desired coin amount, visible in table.
Table information:
simbol = current symbol
current price = First entry price
total coins = Total coins from first entry
profit or loss = self explanatory
update value = increases or decreases according to profit or loss
Partial profit = partial simulation result,
$ ⮕ ₿ = total amount of currencies in the conversion
Multi-Polar WorldA new macro analysis tool for easily analyzing the multi-polar world's economic powerhouses / spheres of influence, making for an easy to use visual when comparing a number of statistics:
GDP, GDP per Capita, External Debt, Government Debt, Exports, Imports, Gold Reserves, Employed Persons, Military Expenditure, Population, Bank Lending Rate, Balance of Trade, Central Bank Balance Sheet, M2 Money Supply, and CPI . Includes option to provide the total for each pole, or view individually for more detailed comparison. Meant to be used when analyzing the macro-economic conditions/trends in conjunction with other "Big Picture" type indicators when adjusting your macro framework.
Band Pass Normalized Suite (BPNS)Outlier-Free Normalization and Band Pass Filtering
We present a technique for normalizing and filtering a given time series, source, in order to improve its stationarity and enhance its features. The technique includes two stages: outlier-free normalization and band pass filtering.
Outlier-Free Normalization:
In order to normalize source and reduce the impact of outliers, we first smooth the time series using an exponential moving average with a smoothing factor of alpha. The smoothed time series is then normalized by subtracting the minimum value within a given lookback period, dev_lookback, and dividing the result by the range (maximum - minimum) within the same lookback period. Outliers are detected and excluded from the normalization process by identifying values that are more than outlier_level standard deviations away from the exponentially smoothed average.
Band Pass Filtering:
After normalization, the time series is passed through a band pass filter to remove low and high frequency components. The specifics of the band pass filter implementation are not provided.
Code snippet:
bes(float source = close, float alpha = 0.7) =>
var float smoothed = na
smoothed := na(smoothed) ? source : alpha * source + (1 - alpha) * nz(smoothed )
max(source, outlier_level, dev_lookback)=>
var float max = na
src = array.new()
stdev = math.abs((source - bes(source, 0.1))/ta.stdev(source, dev_lookback))
array.push(src, stdev < outlier_level ? source : -1.7976931348623157e+308)
max := math.max(nz(max ), array.get(src, 0))
min(source, outlier_level, dev_lookback) =>
var float min = na
src = array.new()
stdev = math.abs((source - bes(source, 0.1))/ta.stdev(source, dev_lookback))
array.push(src, stdev < outlier_level ? source : 1.7976931348623157e+308)
min := math.min(nz(min ), array.get(src, 0))
min_max(src, outlier_level, dev_lookback) =>
(src - min(src, outlier_level, dev_lookback))/(max(src, outlier_level, dev_lookback) - min(src, outlier_level, dev_lookback)) * 100
To apply the outlier-free normalization and band pass filter to a given time series, source, the min_max() function can be called with the desired values for outlier_level and dev_lookback as arguments. For example:
normalized_source = min_max(source, 2, 50)
This will apply the outlier-free normalization and band pass filter to source, using an outlier_level of 2 standard deviations and a lookback period of 50 data points for both the normalization and outlier detection steps. The resulting normalized and filtered time series will be stored in normalized_source.
It is important to note that the choice of values for outlier_level and dev_lookback will have a significant impact on the resulting normalized and filtered time series. These values should be chosen carefully based on the characteristics of the input time series and the desired properties of the normalized and filtered output.
In conclusion, the outlier-free normalization and band pass filtering technique presented here provides a useful tool for preprocessing time series data and improving its stationarity and feature content. The flexibility of the method, through the choice of outlier_level and dev_lookback values, allows it to be tailored to the specific characteristics of the input time series.
Slope Normalized (SN)Introduction:
The Normalized Slope script is a technical indicator that aims to measure the strength and direction of a trend in a financial market. It does this by calculating the slope of the source data series, which can be any type of data (such as price, volume, or an oscillator) over a specified length of time. The slope is then normalized, meaning it is transformed to a scale between -1 and 1, with 0 representing a flat trend.
Methodology:
The Normalized Slope script uses an exponential smoothing function to smooth the source data series. The smoothing factor, or alpha, can be adjusted by the user through the input parameter "Pre Smoothing".
Next, the script calculates the slope of the smoothed data series by finding the average difference between the current value and the values of the previous "Length" periods. This slope is then normalized using a function that scales the data to a range of -1 to 1, with 0 representing a flat trend. The normalization function takes the minimum and maximum values of the slope, calculates the difference between them, and then scales the data to the range of -1 to 1.
The normalized slope is then smoothed again using another exponential smoothing function with a user-adjustable smoothing factor (the "Post Smoothing" input parameter). A center line representing a flat trend can also be plotted on the chart by enabling the "Center Line" input parameter. Additionally, the user can choose to display bounds at the -1 and 1 levels by enabling the "Bounds" input parameter.
Conclusion:
The Normalized Slope script provides traders with a visual representation of the strength and direction of a trend in a financial market. It can be used as a standalone indicator or in combination with other technical analysis tools to help traders make informed trading decisions.
Welford Bollinger Bands (WBB)The Welford method is an algorithm for calculating the running average and variance of a series of numbers in a single pass, without the need to store all the previous values. It works by maintaining an ongoing running average and variance, updating them with each new value in the series. The running average is updated using a simple formula that adds the new value to the previous average, weighed by the number of values that have been processed so far. The variance is updated using a similar formula that takes into account the deviation of the new value from the running average.
The Welford method has several advantages that make it a good fit for use in calculating Bollinger Bands. First, it is more numerically stable than other methods, as it avoids accumulating round-off errors and can handle large numbers of data points without overflow or underflow. This is important when working with financial data, which can contain large price movements and wide ranges of values.
Second, the Welford method is well-suited for use in real-time or streaming data scenarios where all the data may not be available upfront. This is useful in the context of Bollinger Bands, which are often used to identify trend changes and trading opportunities in real-time, as the bands are updated with each new data point.
Finally, the Welford method is simple and efficient, making it easy to implement and fast to compute. This is important when creating technical indicators and trading strategies, as performance is often a critical factor.
Overall, the Welford method is a reliable and efficient way to calculate the running average and variance of a series of numbers, making it a good fit for use in calculating Bollinger Bands and other technical indicators.
Noise GateThis Pine Script code defines an indicator called "Noise Gate" which filters out "noise" from a given signal. The indicator takes four input parameters: source, length, ratio, and level. The source parameter specifies the source data for the indicator (e.g., close prices), the length parameter specifies the length of a moving average, the ratio parameter specifies the attenuation ratio, and the level parameter specifies the threshold for attenuating the signal.
The core of the indicator is the noise_gate function, which takes three input parameters: signal, ratio, and level. The signal parameter represents the input signal that needs to be filtered. The ratio parameter specifies the amount by which the signal will be attenuated (reduced in amplitude) if it falls below the level parameter. The level parameter is a threshold that determines whether the signal will be attenuated or not.
The noise_gate function first calculates the absolute value of the signal using the math.abs() function. This is done because the filtering only applies to the magnitude of the signal, not its sign (positive or negative value).
The function then checks if the absolute value of the signal is above the level threshold using an if statement. If it is, the signal is returned as is. If the absolute value of the signal is below the level threshold, the function calculates a value called soft_knee_ratio using the formula 1 - (level - abs_signal) / level. This value represents the amount by which the signal will be attenuated. The signal is then reduced in amplitude by this soft_knee_ratio and the resulting value is returned as the output of the function.
The noise_gate function applies the transformation symmetrically to both positive and negative values of the signal parameter. This is because the transformation only depends on the absolute value of the signal, not its sign. The transformation first calculates the absolute value of the signal using the math.abs() function and then applies the filtering based on the magnitude of the signal. The sign of the signal is not taken into account in this process. As a result, the transformation is applied symmetrically to both positive and negative values of the signal.
The noise_gate function can be a valuable tool for anyone looking to filter out noise or unwanted variations from a signal. It is flexible and easy to use, and can be applied to a wide range of situations where signal noise reduction is needed. For example, it can be used to smooth out financial time series data or to remove background noise from an audio recording.
The noise_gate function in this code has been modified to include an additional input parameter called knee_type, which allows the user to specify whether to use a hard knee or a soft knee. A hard knee means that the compressor triggers simply at the threshold, whereas a soft knee means that the compressor triggers smoothly, gradually increasing the attenuation as the signal falls further below the threshold.
To use a hard knee, the user can set the knee_type parameter to "hard". To use a soft knee, the user can set the knee_type parameter to "soft". The default value for the knee_type parameter is "soft", so if the user does not specify a value for knee_type, the noise_gate function will use a soft knee by default.
The noise_gate function includes a check for the value of the knee_type parameter and applies the appropriate knee type. If the knee_type parameter is set to "hard", the function applies a hard knee by simply triggering at the threshold and dividing the input by the ratio if the signal falls below the threshold. If the knee_type parameter is set to "soft" (or if it is not specified and the default value is used), the function applies a soft knee by gradually increasing the attenuation of the signal as it falls further below the threshold.
The noise_gate function can be a valuable tool for anyone looking to filter out noise or unwanted variations from a signal. It is flexible and easy to use, and can be applied to a wide range of situations where signal noise reduction is needed. For example, it can be used to smooth out financial time series data or to remove background noise from an audio recording.