Multi Asset + Correlation OverlayFrom time to time, you may want to overlay multiple assets on the same chart instead of using multi-chart views. This can be a much cleaner way of viewing and comparing multiple assets. There is some functionality built into TradingView that lets you do this to a certain extent, but I wanted additional options, correlation labeling and ways to adjust the overlay location. So, today I am releasing to the community my Multi-Asset + Correlation Overlay script / indicator.
What is does: This script allows you to overlay the price of any ticker onto your chart. It also labels the line with the ticker name, and calculates / labels the correlation coefficient of your newly overlayed asset.
How to use it: Add the indicator to your chart. Then, go into the indicator settings to set the ticker of the asset you want to pull in along with how you want to "offset" it. Your 2 tickers may not be priced near each-other, so the offset setting allows you to pull the ticker you added up/down to better visually align with your chart's price range/layout. For instance, if the asset you added is priced $400 higher than the underlying chart price, you may want to set the offset to -400.
If you would like to add multiple tickers and multiple overlays, you can do that by just adding the indicator to your chart more than once. The color is adjustable, and the ticker of the asset will print to the right of the line representing the asset price. The script also calculates the correlation coefficient between the ticker overlay and the underlying chart asset. The correlation coefficient prints to the right of the ticker.
Statistics
Swap Trading Pair Price This script was inspired by STEPN, where we should always be aware of the price change between GSTUSDT and SOLUSDT to make better profit.
We can easily compare any trading pair price from any desired exchange we want even if they don't have direct trading pair on certain exchange to monitor thier price correlation.
We can define the lower range we are prefer to sell GST into SOL and the upper range to buy SOL into GST
[Mubeen] True Bar VolumeTrue Bar Volume, or TB Volume, is an indicator that measures the volume against the price action that has occurred.
Volume can sometimes be miss leading as it does not necessary show whether it had an impact on the price of the underlying, as one individual (represented as one volume) who has put $100 into the underlying can impact the underlying the same as hundred individuals (represented as hundred volume) putting $1 into the underlying: but the volume will widely differ and can cause confusion for outsiders. With the True Bar indicator, it aims to show abnormal behaviour in the price change against the amount of volume that was stated. It visualises the effect of the volume on the underlying by colour coding the different levels of True Bar results, divided into Red, Yellow, Green, Purple.
Red indicates that the price has changed way out of portion compared with the volume that was seen. It is compared against the highest TB Volume values through selected periods and once the volume as broken out of the high, it is considered an anomaly.
Yellow indicates that the TB Volume values are representing the mean values so it is considered as normal trading activity. Spikes in yellow values can also be seen as rise in high interest in the underlying.
Green indicates that the TB Volume values are under performing in market activity.
Purple indicates that is it a null result as investors might be looking for a better entry into a market, or seen as interest is low in the market.
TB Volume should not be used on it's own as it only gives a reporting measurement of the volume performance, which may be meaningless without the supplementation of other indicators.
CoinFlip Indicator + StrategyFlip a coin every Monday.
Heads, go long. Tail, go short. Stoploss at 1 ATR, and Take profit at 1 ATR too. 1:1 risk to reward ratio.
After backtesting 2018, 2019, and 2020 with 28 major currency pairs. We are getting close to a 50% win rate with an 8% standard deviation.
Believe it or not, this simple performs better than lots of the popular indicators out there.
Don't believe me? Test it out yourself!!
Use this as a baseline for your backtest and expose all your other crappy indicators :)
HOW TO USE:
As an indicator:
1. Use a daily chart
2. Green arrow below chart, go long, set a stop-loss at 1 x ATR, and take profit at 1 x ATR
3. Red arrow above chart, go short, set a stop-loss at 1 x ATR, and take profit at 1 x ATR
As an indicator:
1. In setting, set a year to test (default to 2020)
2. Go to the strategy tester and observe the stats
P.s. You can also set the period of the ATR to another value other than 14 periods.
OrdinaryLeastSquaresLibrary "OrdinaryLeastSquares"
One of the most common ways to estimate the coefficients for a linear regression is to use the Ordinary Least Squares (OLS) method.
This library implements OLS in pine. This implementation can be used to fit a linear regression of multiple independent variables onto one dependent variable,
as long as the assumptions behind OLS hold.
solve_xtx_inv(x, y) Solve a linear system of equations using the Ordinary Least Squares method.
This function returns both the estimated OLS solution and a matrix that essentially measures the model stability (linear dependence between the columns of 'x').
NOTE: The latter is an intermediate step when estimating the OLS solution but is useful when calculating the covariance matrix and is returned here to save computation time
so that this step doesn't have to be calculated again when things like standard errors should be calculated.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
Returns: Returns both the estimated OLS solution and a matrix that essentially measures the model stability (xtx_inv is equal to (X'X)^-1).
solve(x, y) Solve a linear system of equations using the Ordinary Least Squares method.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
Returns: Returns the estimated OLS solution.
standard_errors(x, y, beta_hat, xtx_inv) Calculate the standard errors.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
beta_hat : The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
xtx_inv : This is (X'X)^-1, which means we take the transpose of the X matrix, multiply that the X matrix and then take the inverse of the result.
This essentially measures the linear dependence between the columns of the X matrix.
Returns: The standard errors.
estimate(x, beta_hat) Estimate the next step of a linear model.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
beta_hat : The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
Returns: Returns the new estimate of Y based on the linear model.
FunctionPolynomialFitLibrary "FunctionPolynomialFit"
Performs Polynomial Regression fit to data.
In statistics, polynomial regression is a form of regression analysis in which
the relationship between the independent variable x and the dependent variable
y is modelled as an nth degree polynomial in x.
reference:
en.wikipedia.org
www.bragitoff.com
gauss_elimination(A, m, n) Perform Gauss-Elimination and returns the Upper triangular matrix and solution of equations.
Parameters:
A : float matrix, data samples.
m : int, defval=na, number of rows.
n : int, defval=na, number of columns.
Returns: float array with coefficients.
polyfit(X, Y, degree) Fits a polynomial of a degree to (x, y) points.
Parameters:
X : float array, data sample x point.
Y : float array, data sample y point.
degree : int, defval=2, degree of the polynomial.
Returns: float array with coefficients.
note:
p(x) = p * x**deg + ... + p
interpolate(coeffs, x) interpolate the y position at the provided x.
Parameters:
coeffs : float array, coefficients of the polynomial.
x : float, position x to estimate y.
Returns: float.
Volume Filtered *All Candlestick Patterns* [KT] Hello!
This script uses TradingView's *All Candlestick Patterns* indicator and includes a volume filter.
The frequency of each candlestick pattern is recorded in addition to the subsequent session's outcome - higher or lower close.
The requisite volume for the pattern is configurable; formations will not be distinguished when volume is less than the defined lower threshold.
For example, setting the volume threshold to 10% forces the script to identify candlestick patterns in which volume for the session (candle) is 10% greater than the volume moving average. All candlestick patterns with volume less than (1.10 * volume MA) are discounted.
The script counts the frequency of each pattern - the number of times the pattern occurred - in addition to the next candle's outcome.
Pertinent statistics are displayed in the table, which can be hidden.
I plan on working on the script quite a bit more; please comment a suggestion if you have one! What else should be included?
RSI and Golden Cross ScreenerIts an example of basic cyclic screener. Looks for conditions on RSI and for Golden crosses for N bars back on top40 crypto on Binance. Feel free to contact me via tg @davidkohen if you got any questions!
It's an improvement of an old QuantNomad's idea :)
Key Financials A simple table with up to 9 key financials on your chart.
Simple, easy and configurable.
Market Profile Visible RangeSup TV, 2 important points .
1) surprisingly, it's the first MP Visible Range script on TV;
2) This one doesn't use any bagging/binning*, instead each row represents the time spent on the actual minimal price steps (aka ticks).
The script will be further extended with usual market profile related functionally in future updates. At this point we have:
- Profile itself (each row represents how many bars touch the given price);
- Mode of the profile (called POC)**;
* Still it will be introduced in future when I will find / design the proper aggregating technique. It is vital for processing very wide price ranges (for example, 500 days on ES futures).
** The script correctly calculates POC by finding all the modes in the data & choosing the closest one to data's midrange.
For this kind of technical instrument finally it was more convenient to use Pine Script 5 (btw it's my first Pine 5).
Basically this script is a side-effect of another R&D I'm doing, the stuff is useful tho so let's go.
By choosing length we both specify the amount of data to be processed & the profile's location screen-wise. It's pretty cool and & useful, on my screen it's always almost touching the left side and still always visible.
The code is heavily commented in order to be understood fast, nothing fantastic, just a lil patience required this time.
Rationale
Market & volume profiles are well known concepts, lotta info available, the most important point of all that is that MP is just another way of visualizing data that lets you notice things you don't usually notice on sequential charts. From my side I can only add that it's better to use your own brain for thinking and reconsidering using volume profile in all the cases, especially on decentralized markets (unless you're aggregating ALL the volume data from everywhere, including options, OTC etc).
Here is it, for you
Loft Strategy V4This strategy is an advanced version of the Loft Strategy V1, I shared earlier. (Loft Strategy V1 consists of a kalman filter (by alexgrover ) and a "stop and reverse" line which is following and the kalman filter. If the price goes in the same direction as the position side, the "stop and reverse" line approaches the kalman filter as set on the "Approach Decrease Step" parameter.)
In addition to the previous version, it includes a martingale like deviation and multiple take-profit.
Here it is some parameters definitions of the strategy:
Kalman Filter: The higher this parameter, the faster and more aggressive the filter. Otherwise the filter goes very smoothly
Beginning Approach: First approximation as a percentage of stop-n-reverse line
Final Approach: Minimum approximation of stop-n-reverse line
Approach Decrease Step: If the price moves in the same direction as the strategy, the approach percentage is reduced by this parameter. Otherwise nothing do
Base Order Quantity: Initial capital of position
Max Safe Order Attempt: This parameter determines the maximum number of times the strategy will raise the bet after losing in a row.
Safe Order Deviation: if the last trade is loss, multiply the bet by this parameter (aka. martingale factor)
Profit Deviation: if last trade in loss, multiply the take-profit points
Max Order Quantity: Maximum capital allowed for a position
TP1, TP2, TP3 : Take profit spots in percentage
QT1, QT2, QT3: Amount of take-profit spots
Stop Loss: Maximum stop loss allowed for a trade
Long Entry, Short Entry: Only long side, only short side or both side
Safe Stop After TP2: If the price reaches the TP2 point, move the stop-loss point to the entry price.
Safe Stop After TP1: If the price reaches TP1, move the stop-loss point to the stop-n-reverse line.
Feature scalerFeature scaler | Pine Utilities series, ready to be used in "study-on-study" fashion |
Includes min-max, normalization, standardization and unit length scaling.
One and only source: en.wikipedia.org
Endpoint inputs allow to set an interval of interest for min-max scaler.
Can be (and should be) applied to other studies, or to the chart itself. In this example, I applied min-max scaling to weighted linear regression's slope values.
Unfortunately, "All data" is still "experimental" and works only on charts where less than 5000 bars are available. max_bars_back() didn't help.
Sup TV
Valuation TableHey folks, I hope you are all doing well!
This is an indicator that you can use to help you to evaluate companies. There are a few things I added to the valuation table that I personally use and I will explain what they are.
I added Joel Greenblatt's ROC% because it takes Earnings before Interest and Taxes to reflect more closely what the company earns from its operations, while including the cost of depreciation/amortization of assets. A high double digit figure often means that the company has a defensible edge versus its competitors (e.g. a strong brand or a unique product). It's good for relative valuation (comparing two companies in the same industry).
I also added Donald Yacktman's forward rate of return. Yacktman defines forward rate of return as the normalized free cash flow yield plus real growth plus inflation . Unlike the Earnings Yield %, the Forward Rate of Return uses the normalized Free Cash Flow of the past seven years, and considers growth. The forward rate of return can be thought of as the return that investors buying the stock today can expect from it in the future. Yacktman’s Forward Rate of Return may or may not be a useful metric. However, it does present new ways to see and think about stocks we may want to buy.
I added a box called "real price" and that is from Peter Lynch's book, "One Up on Wall Street," where he talked about how the real price of the stock is really the current price - Net Cash Per Share.
I would also personally pair this script with TradingView's built in financial indicators that shows the revenue growth, net income, etc.
Note: the script only works on the weekly timeframe and it will take some time to load because it has a lot of data.
Heavy Weight Stocks for Bank NiftyHeavy Weight Stocks for Bank Nifty
Stocks which are part of Bank Nifty are displayed in the table.
If the %Change > 1 then bold green
If the %Change <1 and >0, then light green
If the %Change < -1 then bold red
If the %Change > -1 and <0 then light green
NSE:BANKNIFTY
NSE:HDFCBANK
NSE:ICICIBANK
NSE:AXISBANK
NSE:KOTAKBANK
NSE:SBIN
NSE:NIFTY
NSE:RELIANCE
NSE:HDFC
divergenceLibrary "divergence"
divergence: divergence algorithm with top and bottom kline tolerance
regular_bull(series, series, simple, simple, simple, simple, simple) regular_bull: regular bull divergence, lower low src but higher low osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
hidden_bull(series, series, simple, simple, simple, simple, simple) hidden_bull: hidden bull divergence, higher low src but lower low osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
regular_bear(series, series, simple, simple, simple, simple, simple) regular_bear: regular bear divergence, higher high src but lower high osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
hidden_bear(series, series, simple, simple, simple, simple, simple) hidden_bear: hidden bear divergence, lower high src but higher high osc
Parameters:
series : float src: the source series
series : float osc: the oscillator index
simple : int lbL: look back left
simple : int lbR: look back right
simple : int rangeL: min look back range
simple : int rangeU: max look back range
simple : int tolerance: the number of tolerant klines
Returns: array:
least_squares_regressionLibrary "least_squares_regression"
least_squares_regression: Least squares regression algorithm to find the optimal price interval for a given time period
basic_lsr(series, series, series) basic_lsr: Basic least squares regression algorithm
Parameters:
series : int t: time scale value array corresponding to price
series : float p: price scale value array corresponding to time
series : int array_size: the length of regression array
Returns: reg_slop, reg_intercept, reg_level, reg_stdev
trend_line_lsr(series, series, series, string, series, series) top_trend_line_lsr: Trend line fitting based on least square algorithm
Parameters:
series : int t: time scale value array corresponding to price
series : float p: price scale value array corresponding to time
series : int array_size: the length of regression array
string : reg_type: regression type in 'top' and 'bottom'
series : int max_iter: maximum fitting iterations
series : int min_points: the threshold of regression point numbers
Returns: reg_slop, reg_intercept, reg_level, reg_stdev, reg_point_num
simple_squares_regressionLibrary "simple_squares_regression"
simple_squares_regression: simple squares regression algorithm to find the optimal price interval for a given time period
basic_ssr(series, series, series) basic_ssr: Basic simple squares regression algorithm
Parameters:
series : float src: the regression source such as close
series : int region_forward: number of candle lines at the right end of the regression region from the current candle line
series : int region_len: the length of regression region
Returns: left_loc, right_loc, reg_val, reg_std, reg_max_offset
search_ssr(series, series, series, series) search_ssr: simple squares regression region search algorithm
Parameters:
series : float src: the regression source such as close
series : int max_forward: max number of candle lines at the right end of the regression region from the current candle line
series : int region_lower: the lower length of regression region
series : int region_upper: the upper length of regression region
Returns: left_loc, right_loc, reg_val, reg_level, reg_std_err, reg_max_offset
on_balance_volumeLibrary "on_balance_volume"
on_balance_volume: custom on balance volume
obv_diff(string, simple) obv_diff: custom on balance volume diff version
Parameters:
string : type: the moving average type of on balance volume
simple : int len: the moving average length of on balance volume
Returns: obv_diff: custom on balance volume diff value
obv_diff_norm(string, simple) obv_diff_norm: custom normalized on balance volume diff version
Parameters:
string : type: the moving average type of on balance volume
simple : int len: the moving average length of on balance volume
Returns: obv_diff: custom normalized on balance volume diff value
moving_averageLibrary "moving_average"
moving_average: moving average variants
variant(string, series, simple) variant: moving average variants
Parameters:
string : type: type in
series : float src: the source series of moving average
simple : int len: the length of moving average
Returns: float: the moving average variant value
SuperTrend OptimizerHello!
This indicator attempts to optimize Supertrend parameters. To achieve this, 102 parameter combinations are tested concurrently - the top three performers are listed in descending order.
Parameters,
Factor: Changes to this parameter shifts the tested factor range. For instance, increasing the factor measure from 3.00 to 3.01 (+0.01) will remove 3.00 from the tested range - this setting controls the lower threshold of the range. The upper threshold, in all instances, is the lower Factor threshold + 3.3 (i.e. 3.0(lower) - 6.3(upper), 4.0(lower) - 7.3(upper), 2.5(lower) - 5.8(upper))
ATR period: Changes to this parameter shifts the tested ATR period range. For instance, increasing the ATR measure from 10 to 11 (+1) will remove 10 from the tested range - this setting controls the lower threshold of the range. The upper threshold, in all instances, is the lower threshold + 2 (i.e. 10(lower) - 12(upper), 11(lower) - 13(upper), 9(lower), - 11(upper))
The Factor parameter is modifiable to any positive decimal number; the ATR parameter is modifiable to any positive integer. Changing either parameter shifts the tested parameter combination range. Both parameters can be changed in the settings, to which you control the lower threshold of the range. If, for instance, you were to change the Factor measurement from 3.0 to 4.1 (+1.1) the 4.0 Factor measurement, and all Factor measures less than 4.0, will be excluded from the performance test.
Consequently, a Supertrend test will be performed with a Factor of 4.1 and an ATR period of 10 (default). This test repeats at 0.1 Factor intervals and 1.0 ATR intervals.
Therefore, assume you modify the Factor lower threshold to 3.1 and the ATR lower threshold to 10. The indicator will test three Supertrend systems with a Factor of 3.1 and an ATR period of 10.. then 11.. 12, then three systems with a Factor of 3.2 and an ATR period of 10.. then 11.. 12... until (lower Factor threshold + 3.3) and (lower ATR threshold + 2) are tested... which in this example is... a Factor of 6.4 and an ATR period of 12.
The tested Factor range and ATR range are displayed in a bottom right table alongside the top performing parameter combinations.
Of course, you can change the the lower thresholds, which means you can test numerous Supertrend parameter combinations! However, no greater than 102 parameter combinations will be tested simultaneously; the best performing Supertrend parameters are plotted on the chart automatically.
I will be working on this indicator more tomorrow! Let me know if you have questions or anything you would like included!
(I of course added something fun in the script. Be sure to try it with bar replay!)
StrengthA mathematically elegant, native & modern way how to measure velocity/ strength/ momentum. As you can see it looks like MACD, but !suddenly! has N times shorter code (disregard the functions), and only 1 parameter instead of 3. OMG HOW DID HE DO IT?!?
MACD: "Let's take one filter (1 parameter), than another filter (2 parameters), then let's take dem difference, then let's place another filter over the difference (3rd parameter + introduction of a nested calculation), and let's write a whole book about it, make thousands of multi-hours YouTube videos about it, and let's never mention about the amount of uncertainty being introduced by multiple parameters & introduction of the nested calculation."
Strength: "let's get real, let's drop a weighted linear regression & usual linear regression over the data of the same length, take dem slopes, then make the difference over these slopes, all good. And then share it with people w/o putting an ® sign".
Fyi, regressions were introduced centuries ago, maybe decades idk, the point is long time ago, and computational power enough to calculate what I'm saying is slightly more than required for macd.
Rationale.
Linearly weighted linear regression has steeper slope (W) than the usual linear regression slope (S) due to the fact that the recent datapoints got more weight. This alone is enough of a metric to measure velocity. But still I've recalled macd and decided to make smth like it cuz I knew it'll might make you happy. I realized that S can be used instead of smoothing the W, thus eliminating the nested calculation and keeping entropy & info loss in place. And see, what we get is natural, simple, makes sense and brings flex. I also wanna remind you that by applying regression we maximize the info gain by using all the data in the window, instead of taking difference between the first and the last datapoints.
This script is dedicated to my friend Fabien. Man, you were the light in the darkness in that company. You'll get your alien green Lambo if you'll really want it, no doubts on my side bout that.
Good hunting
Bond Yeild CurveBond Yeild Curve
A bond yeild curve is a line that plot the interest rate of bonds of each maturity dates.
The slope of the curve give the future of economy cycle.
if the slope could be normal (positive), flat or even inverted.
This indicator aquired data of bond yeild provided by TradingView.
How to use it.
Select the country of the bond / another country to compare.
Select the maturity of bond (this indicator set 2Y, 5Y, 10Y and 20Y as default).
You can toggle to 3 different data set; Yeild, Spread (10Y-2Y) and Yeild Curve.
In case that you select the "Yeild Curve", you can customize the desired past period to compare.
How we can get the benefit.
- If the current spread is greater than 1.0, it suppose that the economy of that country probably is ok.
- if the current spread is between 0 - 1.0, it suppose to be flatted and probably turn to invert and the economy cound be in a recession soon.
- if the current spread is below 0, it suppose to be inverted and economy is in recession.
when knowing the state of economy, it would help us to manage our investment.
When you select "Yeild"
When you select "Spread"
When you select "Yeild Curve"
I'm new for this.
if any idea, correction and suggestion, i do appreciate it.