AutoFiboRetraceLibrary "AutoFiboRetrace"
TODO: add library description here
fun(x) TODO: add function description here
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
Statistics
normalize_heatmap
Description:
This was a simple indicator to indicate the heatmap area of an asset price, in a relative given time period. In default the lookback period was set to 50 bars, indicating the current state of the price within the previous lookback period. The color scheme was using the rainbow palette, which set blue as the cooling-off area, and red as the heating area. The indicator doesn't take into account momentum strategy and thus doesn't consider the future direction of the asset price. Note: cooling-off area, can be considered to entry or adding position as a DCA strategy.
Data Normalize:
norm = (x - min) / (max - min)
Feature:
Heatmap color condition
Weighted Moving average (Additional)
% Price change (by OP)To visually evaluate the percentage change in price over any time period
This handsome indicator shows exact % price change at each candle by displaying a circle at the level of the change. To read numerical value, point at the circle of the relevant bar corresponding to the candle you are interested in, and look at the scale.
TotalCap Structure CandlesIdeal to see the overvaluation or undervaluation of the market observing the structural divergences.
You can also do your technical analysis on this structure, helping to understand the total market.
Let the simplicity of your strategy be your strength, successes.
trading YM based on pair tradingThis is inspired by some online free webinars. Didn't pay for the strategy/ course. I just figured it out myself. So there might be problem with this strategy.
Theory: It is based on something called cointegrated. Cointegration means the difference between 2 securities are stable in long term. When the difference is bigger / smaller than normal, then there is space to make profit. You can use some tests to check if they are cointegration. I don't think YM and NQ are strictly cointegrated. I used other platform to test the cointegration. They are not cointegrated. There are multiple ways to do pair trading. I use "Y = A - B * (A /B)" to do this. The back test on tradingview can only trade one security. This is not pair trading in this backtest. But only do long and short based on the theory of pair trading. The max drawdown is huge. You should be careful before doing anything with this strategy.
Welcome to give some advice on improvement.
VarianceVariance is a measure of dispersion, simply put, it is measuring how distant data is from it's mean(average). This indicator allows you to see when variance is increasing or decreasing, as well as when it is at an extreme value. Thru this, you can get a more accurate description of risk. When variance is increasing/high, you know to expect larger moves, as data(price) is far and getting farther from the mean. and when it is low/decreasing, you know that price movement is more likely to be less volatile due to data clustering closer to the mean, ie ; smaller values.
Variance is not a signal generating indicator in and of itself, but is more a tool to help tell you WHEN to trade. Use in conjunction with signal generating indicators such as Z-score to find entries.
For example, trading z score extremes when variance is increasing.
Variance works well alongside measurements of historical volatility to get a more accurate measurement of market risk/ volatility .
GRID SPOT TRADING ALGORITHM - GRID BOT TRADING STRATEGYGRID SPOT TRADING ALGORITHM : LONG ONLY STRATEGY OPEN SOURCE
This is a long only strategy for spot assets.
HOW IT WORKS
Grid trading is a trading strategy where an investor creates a so-called "price grid". The basic idea of the strategy is to repeatedly buy at the pre-specified price and then wait for the price to rise above that level and then sell the position (and vice versa with shorting or hedging).
FEATURES
Grids: This algorithm has a total of 10 grids.
Take profit: The trader can increase or decrease the distance between the grids from the User Interface panel, the distance between one grid and another represents the take profit.
Management: The algorithm buys 10% of the capital every time the price breaks down a grid and sells during a rise to the next higher grid. The initial capital is invested in 10 sizes which represent 10% of the capital per trade.
Stop Loss: The algorithm knows no stop loss as long as it is not activated from the User Interface panel. By activating the stop loss from the User Interface panel the algorithm will insert a close condition on all trades which will be calculated from the last lower grid.
Trades: Trades are opened only if the price is within the grid. If the market leaves the grid the algorithm will not buy new positions or sell new positions.
Optimal market conditions: The favorable market for this algorithm is the sideways market.
LIMITATIONS OF THE MODEL
The trader must take into account that this is a static model. It only works perfectly well if the market is in a sideways phase and incurs heavy losses if the market takes a downward trend. The model is unusable for an uptrend. The trader must therefore carefully analyze the market where he intends to use this strategy, making sure that the price is in a sideways phase.
USES
Indispensable research and backtesting tool for those using bots for their investments. The algorithm produces a backtesting of the strategy for past history. It is used by professional traders to understand if this strategy has been profitable on a market and what parameters to use for bots using this strategy (Kucoin, Binance etc.).
If you would like to develop your own algorithm with customized conditions based on a grid strategy, please contact us.
If you need help in using this tool, please contact us without hesitation.
Volume CompressorTurns volume into a more informative representation, ready to be further analyzed
...
Rationale
Volume
Back in the "before the quant" days I was a big fan of market & volume profile. Thing is J. Steidlmayer had lotta different ideas & works aside of profiling, it's just most of them ain't got to mainstream, one of them was "Hot / Cold volume" (yes, you can't really google it). From my interpretation, the idea was that in a given asset there is a usual constant volume that stays there no matter what, and if it ever changes it changes very slow and gradually; and there's another kind of, so to say, 'active' volume that actually influences price dynamics and very volatile by its nature. So I've met concept lately, and decided to quantify & model it one day when I'll have an idea how. That day was yesterday.
Compression
When we do music we always use different kinds of filters (low-pass, high pass, etc) for equalization and filtering itself. That stuff we use in finance as well. What we also always use in music are compressors, there dynamic processors that automatically adjust volume so it will be more consistent. Almost all the cool music you hear is compressed (both individual instruments (especially vocals) and the whole track afterwards), otherwise stuff will be too quite and too weak to flex on it, and also DJing it would be a nightmare. I am a big adept of loudness war. So I was like, how can I use compression in finance, when ima get an idea? That day was yesterday as well.
Volume structure
Being inspired by Steidlmayer's idea, I decided to distinguish volume this way:
1) Passive / static volume. The ~ volume that's always there no matter what (hedges, arbitrages, spread legs, portfolio parts etc etc), doesn't affect things;
2) Active / dynamic volume. The volume that flows from one asset to another, really matters and affects things;
3) Excess volume. The last portion of number 2 volume, that doesn't represent any powerful value to affect things.
Now it's clear that we can get rid of number 1 and number 3, the components that don't really matter, and concentrate on number 2 in order to improve information gain, both for ourselves and for the models we feed this data. How?
Model
I don't wanna explain it all in statistical / DSP way for once.
First of all, I think the population of volumes is log-normally distributed, so let's take logs of volumes, now we have a ~ normally distributed data. We take linearly weighted mean, add and subtract linearly weighted standard deviation from it, these would be our thresholds, the borders between different kinds of volumes explained before.
The upper threshold is for downward compression, that will not let volume pass it higher.
The lower threshold is for upward compression, all the volumes lower than this threshold will be brought up to the threshold's level.
Then we apply multipliers to the thresholds in order to adjust em and find the sweet spots. We do it the same way as in sound engineering when we don't aim for overcompression, we adjust the thresholds until they start to touch the signal and all good.
Afterwards, we delete all the number 1 and number 3 volume, leaving us exclusively with the clear main component, ready to be processed further.
We return the volumes to dem real scale.
About the parameters, based on testing I don't recommend changing the thresholds from dem default values, first of all they make sense statistically and second they work as intended.
Window length can and should be adjusted, find your own way, or leave the default value. ML (moving location) length is up to you as well.
So yeah, you can see now we can smooth the data and make it visually appealing not only by applying a smooth filter over it.
All good TV?
All Central Bank Interest RatesWith another period of mass interest rates manipulation, I created this indicator to show them all. It reveals latest interest ratest (at a time of the last update) and a date when each central bank manipulated the rates.
If you would rather view a single pair data check: and
Portfolio Laboratory [Kioseff Trading]Hello!
This script looks to experiment with historical portfolio performance. However, a hypothetical cash balance is not used; weighted percentage increases and decreases are used.
You can select up to 10 assets to include in the portfolio. Long and short positions are possible.
Show in the image are the portfolio's weight, the total return of the portfolio and the total return of the asset on the chart over the selected timeframe.
Shown in the image above are the constituents of the portfolio, which can include any asset, the weighted percentage gain/loss of the constituents in addition to 10 major indices and their respective total percentage gain/loss over the timeframe.
Shown in the image above are the dividend yield % of the portfolio and relevant portfolio metrics - ex-post calculations are applied and are predicated on simple returns.
Shown in the image above is a portfolio of all short positions; portfolio calculations adjusted to the modifications.
Also shown is a change in the index the portfolio is calculated against. I have been asked a few times to include NIFTY 50 in my scripts - I made sure this was achieved, lol!
Show in the image is a performance line of performance of percentage increases/decreases for the index calculated against, the asset on the chart, and the portfolio.
All lines start simultaneously on the selected start date at the close price of the session for the asset on your chart.
However, the right-hand scale, whether displaying price or percent, cannot be used to assess the performance of each line - they are useful for visualization only and can extend below zero on a low-priced asset. Calculations will not execute correctly when selecting a start date prior to any asset in the portfolio's first trading session; calculations do not begin on the first bar of the asset on your chart.
I decided to code the script this way so statistics remain fixed when moving from asset to asset!
To compensate for this limitation, I included a label plot and background color change at the first session in which all assets in the portfolio had at least one bar of price data. You can adjust the calculation start date to the date portrayed on the label to test al possible price data!
The statistics table, and the performance lines, can be hidden in the user input section.
I plan on putting a bit more work into this script. I have some ideas on what to include; however, any input is greatly appreciated! If there's something you would like me to include please let me know.
@scheplick mentioned me in a script he recently coded:
My inspiration came from his script! I thank him for that!
Z-Score with Buy & Sell SignalsThis is my open-source indicator of z-score with buy and sell indicators.
I see there are other z-score indicators, I just am particular about how I like my z-scores calculated and so decided to make my own and add buy and sell signals to help guide me. And I figured I could share it openly here!
What is a Z-Score
A z-score is a statistical measures of the distance, in standard deviations, a value is from its given mean. It is expressed as a standard deviation (or SD). The further a value (in this case, a stock) is from their mean, the more likely a regression to the mean is possible (i.e. a return to the average). So if a stock is trading at 3 standard deviations away from its mean, then we can anticipate it wanting to regress back towards 1 to 0 standard deviations from its mean (i.e. sell off back to a value that brings it closer to that SD).
The inverse is true if it is trading below.
Z-Scores and Stocks
Stocks, like everything in nature, like to trade between -1 and +1 SD away from its mean. Anything above this, we can interpret that there is "stress" on the stock. Anything over 2.50 is tremendous stress on the stock and we can anticipate that it will want to revert to its mean in the near future and bring that value down to at least 1, ideally between the -0.5 and 0.5 range.
Please note, I set the standard VERY high for the indicator to issue a buy and sell signal (/=2.50). Lately with the volatility, stocks have been entering these ranges frequently and so there have been plenty of signals, but traditionally in a stable environment you may not get these signals. I set the bar extremely high because I want to avoid false buy and sell signals (you will still get them though, nothing is perfect!). So the value in this indicator is in interpreting the actual z-score itself, so please be sure you understand exactly what the Z-score is (see the description above).
How the indicator works
The indicator works by calculating the average Z-Score between a stocks high and low. This indicator will present the average deviation a stock has from its high and low average. The higher the Z-Score, the more "overbought" the stock is. The lower the z-score, the more "oversold" the stock is. It uses the previous 500 candles worth of data to calculate its SMA and its Standard deviation in order to calculate the z-score.
Anytime a stock trades 2.50 SDs or more above or below its mean, you will be presented with a Buy or Sell signal, as generally, statistically speaking, after something has travelled 2.50 SDs aware from its mean, there is an increased probability of a reversion happening.
You can use this indicator to determine whether the stock is trading within normal parameters or not and to help you in your analysis as to whether or not a stock could be shorted or longed.
I personally like this for swing trading on the 1 hour chart; however, this can be used on any time from 1 minute to 1 hour. It also allows you to track a stocks progress in its reversion to the mean.
Examples of it in Use:
Gold ETF (ARCA: GLD) on 1 minute
Dow Jones ETF (ARCA: DIA) on 1 minute (my favourite Stock!)
SPY ETF (ARCA: SPY) on 1 hour chart
Disclaimer:
This is not meant to be placed as a sole and single strategy. It should be used in COJUNCTION with your other strategies to help you make a determination.
No indicator is infallible and should never be relied on 100%!
Please let me know your questions/comments/experiences/recommendations below!
Thanks everyone!
Market Profile Fixed ViewSome instruments does not provide any volume information, therefore, as a fixed volume profile user, I needed a fixed market profile indicator to use the same principles, regardless of whether the volumes are available or not.
This script draws a market profile histogram corresponding to price variations within a specific duration, you only need to specify Start and End date/time values to see the histogram on your chart.
Details
Two lines corresponding to highest/lowest prices are displayed around the histogram
The redline corresponds to the POC (point of control)
Options
Start calculation
End calculation
Bars number (histogram resolution, currently locked to a max value of 50 bars)
Display side/Width (allows to modify size of bars, to the left or to the right)
Bars/Borders/POC Color customization
Notes
This script will probably be updated (to add VAH/VAL zones, and maybe other options). However, some common market profile attributes have not been implemented yet since I don't really use them)
MonthlyReturnsVsMarketLibrary "MonthlyReturnsVsMarket" is a repackaging of the script here
Credits to @QuantNomad for orginal script
Now you can avoid to pollute your own strategy's code with the monthly returns table code and just import the library and call displayMonthlyPnL(int precision) function
To be used in strategy scripts.
SymMatrixTableSimple Example Table for Displaying Price, RSI, Volume of multiple Tickers on selected Timeframe
Displays Price, RSI and Volume of 3 Tickers and Timeframe selected by user input
Conditional Table Cell coloring
Price color green if > than previous candle close and red if < previous candle close
RSI color green if < 30 and red if > 70 (RSI14 by default)
Volume color green if above average volume and red if less than that (SMA20 volume by default)
Can turn on/off whole table, header columns, row indices, or select individual columns or rows to show/hide
// Example Mixed Type Matrix To Table //
access the simple example script by uncommenting the code at the end
Basically I wanted to have the headers and indices as strings and the rest of the matrix for the table body as floats, then conditional coloring on the table cells
And also the functionality to turn rows and columns on/off from table through checkboxes of user input
Before I was storing each of the values separately in arrays that didn't have a centralized way of controlling table structure
so now the structure is :
- string header array, string index array
- float matrix for table body
- color matrix with bool conditions for coloring table cells
- bool checkboxes for controlling table display
Coins x Value CalculatorThrough this script you will be able to calculate in real time your total number of coins correlated to the value that is at that moment, so you will not need to log into the brokerage or be simulating sales to know what your total value is in the asset...
To use it, just add it to your favorites and then right after adding it to the chart, clicking on its gear, a field will appear for you to enter your total amount of coins corresponding to that chart, then immediately calculate the value that is the total of your coins , will also show the entire history of appreciation or devaluation that its capital corresponding to that asset had.
Translator Portuguese:
Através desse script você poderá calcular em tempo real o seu numero de moedas total correlacionado ao valor que se encontra naquele momento ,assim nao precisara logar na corretora ou ficar simulando vendas para saber qual valor esta seu total no ativo...
Para usar basta adicionar ele a seus favoritos e então logo após adicionar ao gráfico, clicando na engrenagem dele aparecera um campo para voce digitar sua quantidade de moedas total correspondente a aquele gráfico logo em seguida calculara imediatamente o valor que se encontra o total de suas moedas, também mostrara todo o histórico de valorização ou desvalorização que seu capital correspondente aquele ativo teve.
Wick/ Long / Short Monitor- Wanted to check if price movement on a particular candle for day trading is less than my target movement.
- A user can place this on chart and on the candles where the price movement is not as predicted from the open price, a red * will be placed above or below the bar
- it is best used in fixed profit scalping strategy
All Time LowThis script is to remind you of how much you would lose if the price went down to the all time low.
This will make you think twice about your purchases!
Sell Half On DoubleNotes:
- In settings leave 0 for actual price, or set a new price and the SHOD levels will change too.
Squeeze Detector 3000This is a bespoke, unfinished script for Kyle.
It is primarily designed to be used to provide useful data for unusually volatile stocks premarket, and for some other situations too.
Featuring:
Pre/post market volume
Short data
RVOL
ATR and turnover
Taylor RuleThe Taylor rule is a simple formula that John Taylor devised to guide policymakers. It calculates what the federal funds rate should be, as a function of the output gap and current inflation. Here, we measure the output gap as the difference between potential output and real GDP. Inflation is measured by changes in the CPI, and we use a target inflation rate of 2%. We also assume a steady-state real interest rate of 2%.
Esqvair's Neural Reversal Probability IndicatorIntroduction
Esqvair's Neural Reversal Probability Indicator is the indicator that shows probability of reversal.
Warning: This script should only be used on 1 minute chart.
How to use
When a signal appears (by default it is a green bar), a reversal should be expected.
The signal appears when the indicator value >= Threshold.
If you want more signals, you must lower the threshold, if less, you must increase the threshold.
For some assets, like Forex pairs, you have to optimize the threshold yourself, but for most stocks, the default threshold works well.
How well a threshold fits an asset depends on the volatility of the asset.
For most assets, the indicator ranges from 35 to 75.
Settings
Smoothing - The default is 1, which means no smoothing. Indicator smoothing by SMA.
Threshold - default 71.0 is responsible for the occurrence of signals, read "How to use" part to learn more
The Indicator
This indicator is a pre-trained neural network that was trained outside of TradingView and then its structure and weights values were converted to PineScript.
Warning: A neural network is a black box in the sense that although it can approximate any function, studying its structure will not give you any idea about the structure of the function being approximated.
Possible questions
Why does the indicator value most time range from 35 to 75 when the probability should ranges from 0 to 100?
-Due to some randomness in the markets, a neural network can never be 100% sure.
What data was used to train the neural network?
-This was BTCUSD 1 minute chart data from 02/05/2020 to 02/05/2022.
Where did you train the neural network and convert it to PineScript?
-I used a programming language that I know.
CanvasLibrary "Canvas"
A library implementing a kind of "canvas" using a table where each pixel is represented by a table cell and the pixel color by the background color of each cell.
To use the library, you need to create a color matrix (represented as an array) and a canvas table.
The canvas table is the container of the canvas, and the color matrix determines what color each pixel in the canvas should have.
max_canvas_size() Function that returns the maximum size of the canvas (100). The canvas is always square, so the size is equal to rows (as opposed to not rows multiplied by columns).
Returns: The maximum size of the canvas (100).
get_bg_color(color_matrix) Get the current background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas.
Parameters:
color_matrix : The color matrix.
Returns: The current background color.
get_fg_color(color_matrix) Get the current foreground color of the color matrix. This is the default color used when drawing pixels.
Parameters:
color_matrix : The color matrix.
Returns: The current foreground color.
set_bg_color(color_matrix, bg_color) Set the background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas.
Parameters:
color_matrix : The color matrix.
bg_color : The new background color.
set_fg_color(color_matrix, fg_color) Set the foreground color of the color matrix. This is the default color used when drawing pixels.
Parameters:
color_matrix : The color matrix.
fg_color : The new foreground color.
color_matrix_rows(color_matrix, rows) Function that returns how many rows a color matrix consists of.
Parameters:
color_matrix : The color matrix.
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Returns: The number of rows a color matrix consists of.
pixel_color(color_matrix, x, y, rows) Get the color of the pixel at the specified coordinates.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Returns: The color of the pixel at the specified coordinates.
draw_pixel(color_matrix, x, y, pixel_color, rows) Draw a pixel at the specified X and Y coordinates. Uses the specified color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
pixel_color : The color of the pixel.
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
draw_pixel(color_matrix, x, y, rows) Draw a pixel at the specified X and Y coordinates. Uses the current foreground color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
erase_pixel(color_matrix, x, y, rows) Erase a pixel at the specified X and Y coordinates, replacing it with the background color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
init_color_matrix(rows, bg_color, fg_color) Create and initialize a color matrix with the specified number of rows. The number of columns will be equal to the number of rows.
Parameters:
rows : The number of rows the color matrix should consist of. This can be omitted, but if used, can speed up execution. It can never be greater than "max_canvas_size()".
bg_color : (Optional) The initial background color. The default is black.
fg_color : (Optional) The initial foreground color. The default is white.
Returns: The array representing the color matrix.
init_canvas(color_matrix, pixel_width, pixel_height, position) Create and initialize a canvas table.
Parameters:
color_matrix : The color matrix.
pixel_width : (Optional) The pixel width (in % of the pane width). The default width is 0.35%.
pixel_height : (Optional) The pixel width (in % of the pane height). The default width is 0.60%.
position : (Optional) The position for the table representing the canvas. The default is "position.middle_center".
Returns: The canvas table.
clear(color_matrix, rows) Clear a color matrix, replacing all pixels with the current background color.
Parameters:
color_matrix : The color matrix.
rows : The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
update(canvas, color_matrix, rows) This updates the canvas with the colors from the color matrix. No changes to the canvas gets plotted until this function is called.
Parameters:
canvas : The canvas table.
color_matrix : The color matrix.
rows : The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Vertical LinesSPEICALLY USED FOR BANKNIFTY RIGHT NOW
Draw vertical lines based on script, based on many conditions :
Conditions used right now are :
1. its a wednesday and the range of day is less than 600 points