Leverage CalculatorThis script is intended to be used as a risk management calculator.
It will calculate the best leverage to use based on the maximum percentage of loss you are willing to incur on your trading portfolio.
Also calculates the order value and order qty based on your inputs.
Please note this calculator does not take into account any trading fees imposed by the exchange you are using.
*** Only risking 1% to 5% of your portfolio is considered good risk management ***
*** Not financial advice ***
------ Settings Inputs -----------------------------------------------------------------------------------------------------
"Portfolio Size" -- enter your portfolio balance
"% Willing to lose on this trade" -- enter the percent of your portfolio you are willing to lose if the stop loss is hit
"Entry Price" -- enter the price at which you will enter the trade
"Stop Loss Price" -- enter the price at which your stop loss will be set
----------------------------------------------------------------------------------------------------------------------------
------ Outputs -------------------------------------------------------------------------------------------------------------
"Portfolio" -- displays the portfolio balance entered in settings
"max loss on trade" -- displays the % loss entered in settings and the corresponding amount of your portfolio
"Entry Price" -- displays the entry price entered in settings
"Stop Loss Price" -- displays the stop loss price entered in settings
"Stop Loss %" -- displays the calculated percentage loss from the entry price
"Leverage calc" -- displays the calculated leverage based on your max loss and stop loss settings
"Order Value" -- displays the value of the order based on the calculated leverage
"Order Qty" -- displays the calculated order qty based on the calculated leverage
Statistics
VOLD-MarketBreadth-RatioThis script provides NASDAQ and NYSE Up Volume (volume in rising stocks) and Down Volume (volume in falling stocks) ratio. Up Volume is higher than Down Volume, then you would see green label with ratio e.g 3.5:1. This means Up Volume is 3.5 times higher than Down Volume - Positive Market Breadth. If Down Volume is higher than Up Volume, then you would see red label with ratio e.g -4.5:1. This means Down Volume is 4.5 times higher than Up Volume.
For example, ratio is 1:1, then it is considered Market Breadth is Neutral.
PS: Currently TradingView provides only NASDAQ Composite Market volume data. I have requested them to provide Primary NASDAQ volume data. If they respond with new ticket for primary NQ data, I will update the script and publish the updated version. So if you have got similar table on ToS, you would see minor difference in NQ ratio.
Max drawdown daysA friendly reminder to myself and rest of the traders that market can stay low for prolonged time!!
Details are pretty simple.
Here is small comparison of the stats for major US indices.
Can also be applied to stocks. Cells are highlighted in red background ii
Drawdown/Recovery is still in progress for historical stats
Current drawdown bars/recovery bars are higher than that of median of All time stats.
CRYPTO DASHBOARD Gs₿A Simple Crypto Dashboard/Screener which indicates the Price and percentage changes for the Given Period of time i.e for 1 Hr ,4 Hrs, 1 Day, 3 Days, 3 Weeks and 3 - 12 Months. By Default it displays #BTC and its Dominance and current trading pair Price and % changes.
WhaleCrew Binance Open InterestShows Open Interest of ANY Binance pair (BTCUSD, ETHUSD, ADAUSD, ...).
Inverse and USDT pairs
Preset-Pairs (BTC, ETH, XRP, ADA, SOL, DOT, ...)
Custom Candle Colors (candles can be turned off)
Prime Number CheckerThis is not a foolproof method for finding every prime number but will work well on assets $10 to $100. I will be working on something more robust with scaling for all assets. If you want a main pane indicator with just the background coloring keep the indicator as it is. If you want a lower pane indicator get rid of the current study function and replace with the commented out study function by deleting the //. Also comment in line 28 also by deleting the //. Prime numbers are an excellent natural mathematical site of reversal and you will begin to see this as you work with them.
Any questions don't be scared to ask.
Eliza.
Bar StatisticsThis script calculates and displays some bar statistics.
For the bar length statistics, it takes every length of upper or lower movements and calculates their average (with SD), median, and max. That way, you can see whether there is a bias in the market or not.
Eg.: If for 10 bars, the market moved 2 up, then 1 down, then 3 up, then 2 down, and 2 up, the average up bars length would be at 2.33, while the average for the down length would be at 1.5, showing that upper movements last longer than down movements.
For the range statistics, it takes the true range of each bar and calculates where the close of the bar is in relation to the true low of it. So if the closing of the bar is at 10.0, the low is at 9.0, and the high is at 10.2, the candle closed in the upper third of the bar. This process is calculated for every bar and for both closing prices and open prices. It is very useful to locate biasses, and they can you a better view of the market, since for most of the time a bar will open on an extreme and close on another extreme.
Eg.: Here on the DJI, we can see that for most of the time, a month opens at the lower third (near the low) and closes at the upper third (near the high). We can also see that it is very difficult for a month to open or close on the middle of the candle, showing how important the first and the last day are for determining the trend of the rest of the month.
Weighted Harrell-Davis Quantile Estimator with AbsoluteDeviation
QUANTILE ESTIMATORS
Weighted Harrell-Davis Quantile Estimator with Absolute Deviation Fences.
DISCLAIMER:
The Following indicator/code IS NOT intended to be a formal investment advice or recommendation by the author, nor should be construed as such. Users will be fully responsible by their use regarding their own trading vehicles/assets.
The following indicator was made for NON LUCRATIVE ACTIVITIES and must remain as is, following TradingView's regulations. Use of indicator and their code are published for work and knowledge sharing. All access granted over it, their use, copy or re-use should mention authorship(s) and origin(s).
WARNING NOTICE!
THE INCLUDED FUNCTION MUST BE CONSIDERED FOR TESTING. The models included in the indicator have been taken from open sources on the web and some of them has been modified by the author, problems could occur at diverse data sceneries, compiler version, or any other externality.
Purpose:
Weighted Quantiles or <> are quite difficult to find on must systems, also it's non-weighted approach are rarely used to estimate the location parameter of price distribution WICH IS NOT NORMAL, all this in favour of it's non-robust counterpart, the Arithmetic rolling Mean or <> and it's weighted variants like the WMA, VWAP, etc.
Also, a big drawback from this is that must statistics derived from Normal-Distribution parameter location (the Mean) definitely will not fit for an efficient, nor robust estimation for price distributions, so their moments like the standard deviation, kurtosis, skewness, etc. will not be the better tools to build derived algorithms or technical indicators among price/volume.
In an effort searching better statistical tools for price distributions, I found the excellent work of Andrey Akinshin that took me to port some of their Math research contributions for the compute benchmarking field , and bring it here at the TradingView ecosystem to take a shot at the price distribution crazy fields. For a better detail of what the weighted Harrell-Davis Quantile Estimator can do, who better than drink directly from the source at References:
References:
Weighted Quantile Estimators.
DoubleMAD outlier detector based on the Harrell-Davis quantile estimator.
Unbiased median absolute deviation based on the Harrell-Davis quantile estimator.
Quantile confidence intervals for weighted samples.
Licensing:
This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International Copyright (c) 2021 (CC BY-NC-SA 4.0)
Copyright's & Mentions:
The Gamma Functions & Beta Probability Density Functions C# implementations by the Math.NET Numerics, part of the Math.NET Project.
The Regularized Incomplete (Left) Beta Function C# implementation by the SAMTools, htslib project.
The Weighted Harrell-Davis Quantile estimator ; C# & R implementations by Andrey Akinshin.
External PineScript code, methods, support & consultancy by @PineCoders staff with special mention for:
+ "ma sorter ('sort by array' example)- JD" by @Duyck.
+ Porting, mods, compilation and debugging for this script by @XeL_Arjona for the TradingView's @PineCoders community.
Function - Sequence From SeriesFunction to create a array from a sample taken from a series (ex:. close, hlc3...).
Volume PanelDisplays volume data in panel on bottom right of screen. Shows current bar, change from last bar and average of last 20 bars. This number can be changed in settings if you wish to have the average calculated on a different amount of bars.
coin statistics
This script displays statistics for 10 coins
for which coins you need to display statistics, you can specify in the script settings.
The script shows the:
- CURRENT PRICE
- RSI
- EMA
- Trend status - which is based on the closing of the candle above the em
you can also specify the length of ema and rsi in the settings
Данный скрипт отображает статистику 10 монет
за какие монеты нужно отображать статистику , вы можете указать в настройка скрипта.
скрипт показывает:
- ТЕКУЩУЮ ЦЕНУ
- RSI
- EMA
- ТРЕНДОВЫЙ СТАТУС - который основан на закрытии свечи выше ема
длину ема и рси вы так же можете указать в настройках
Kolmogorov-Smirnov TestThe Kolmogorov–Smirnov test aims to tell you if the distribution of prices (or log returns) tends to follow a normal distribution or not. You can read about this test on Wikipedia . It seems to be a basic but trusted measure in the quantitative trading world.
When KS-t columns are blue, then it's safe to assume normal distribution. When they are red, the normal distribution assumption is proven wrong by the magnitude of the KS-t value.
In the plotting tab of the script, you can activate another option that displays the probability of the distribution being actually normal. It's values are bounded between 0 and 1, like all probabilities.
This test can be useful when using statistical concepts for trading markets, like standard deviations, z-scores, etc because they all depend on the assumption of prices (or log returns) being normaly distributed.
If you see something wrong, don't hesitate to message me.
Happy trading to all.
kimchi(korea) premium percent - bithumb btc / binance btcThis script was created to confirm the fear of kimchi premium in the cryptocurrency market.
The basic operation formula is as follows.
premium(percent) = (BTC KRW - (BTC USDT x USD KRW) / (BTC USDT x USD KRW)) x 100
By calculating the premium, you can check melt up rally.
Looking at the chart, when kimchi's premium reaches 6-8 percent, BTC faces great volatility (mainly downside).
So, a color warning was made for values outside of -2~2%, which is the general kimchi premium (can be changed in settings).
Also, a zero line has been added for readability.
Also, a color change has been added to the ema to see if the value of each market moves in the opposite direction based on the previous candle's closing price. If the two markets move separately, the ema is colored red.
I think this script is a very simple indicator.
It is usually recommended to get value in a large time frame.
Thank you.
Coefficient of Variation - EMA and SMA StDevYet another way to try and measure volatility. An alternative to using ATR is Standard Deviation, it can be used to measure volatility or what is also known as risk. SD measures how dispersed or far away the data is from the mean. It's commonly seen in risk management formulas or portfolio diversification formulas. The problem however is that the numbers that ATR and SD give off from one equity might not be relative to others or its own past. For example, SPY can give a large number despite not being as volatile as other equities while others being compared to can have smaller volatility numbers and still be more volatile looking.
A solution I thought of is to use percentages that are relatable to different equities. I found out another name for this idea comes from statistics and is known as coefficient of variation, also known as relative standard deviation. This helps see the volatility as a percentage and not just a number that only relates to what is being seen at the moment. I put in a border line on the zero level to see where zero is at but also to edit in case there is such a thing as a percentage number that can be too high or too low for volatility to be looked at if needed. The average and standard deviation formulas can use either simple moving average or exponential moving average.
Intraday SeasonalityDay trading trend filter indicator designed to hep get better entries or exits based on historical opens and closes each hour.
This indicator is NOT designed as an entry or exit signal. The purpose behind it is to give you statistical information about how likely certain times of day are either bullish, bearish or neutral and use that to confirm or reject other trading signals.
For example you might be anticipating a breakout based on your strategy or another indicator but see that the next few hours are usually bearish and re-evaluate entering the trade.
The Intraday Seasonality indicator calculates the percentage of candles per hour that had a higher close than open.
Default settings are:
- a look-back of 90 days.
- extreme bullish (bright green) above 74%
-extreme bearish (bright red) below 25%
- bullish (green) above 55%
- bearish (red) below 45%
- neutral (white) exactly 50%
- no trend (gray) 46% - 54%
All of these are updatable via the settings.
This indicator is designed to work only on the 1 hour timeframe.
To use the indicator set your local timezone offset in the indicator settings.
*Due to daylight savings and certain timezones changing throughout the year there is a timezone override in the indicator settings if the indicator doesn't pick up the correct local time.
Statistical and Financial MetricsGood morning traders!
This time I want to share with you a little script that, thanks to the use of arrays, allows you to have interesting statistical and financial insights taken from the symbol on chart and compared to those of another symbol you desire (in this case the metrics taken from the perpetual future ETHUSDT are compared to those taken from the perpetual future BTCUSDT, used as a proxy for the direction of cryptocurrency market)
By enabling "prevent repainting", the data retrieved from the compared symbol won't be on real time but they will static since they will belong to the previous closed candle
Here are the metrics you can have by storing data from a variable period of candles (by default 51):
✓ Variance (of the symbol on chart in GREEN; of the compared symbol in WHITE)
✓ Standard Deviation (of the symbol on chart in OLIVE; of the compared symbol in SILVER)
✓ Yelds (of the symbol on chart in LIME; of the compared symbol in GRAY) → yelds are referred to the previous close, so they would be calculated as the the difference between the current close and the previous one all divided by the previous close
✓ Covariance of the two datasets (in BLUE)
✓ Correlation coefficient of the two datasets (in AQUA)
✓ β (in RED) → this insight is calculated in three alternative ways for educational purpose (don't worry, the output would be the same).
WHAT IS BETA (β)?
The BETA of an asset can be interpretated as the representation (in relative terms) of the systematic risk of an asset: in other terms, it allows you to understand how big is the risk (not eliminable with portfolio diversification) of an asset based on the volatilty of its yelds.
We say that this representation is made in relative terms since it is expressed according to the market portfolio: this portfolio is hypothetically the portfolio which maximizes the diversification effects in order to kill all the specific risk of that portfolio; in this way the standard deviation calculated from the yelds of this portfolio will represent just the not-eliminable risk (the systematic risk), without including the eliminable risk (the specific risk).
The BETA of an asset is calculated as the volatilty of this asset around the volatilty of the market portfolio: being more precise, it is the covariance between the yelds of the current asset and those of the market portfolio all divided by the variance of the yelds of market portfolio.
Covariance is calculated as the product between correlation coefficient, standard deviation of the first dataset and standard deviation of the second asset.
So, as the correlation coefficient and the standard deviation of the yelds of our asset increase (it means that the yelds of our asset are very similiar to those of th market portfolio in terms of sign and intensity and that the volatility of these yelds is quite high), the value of BETA increases as well
According to the Capital Asset Pricing Model (CAPM) promoted by William Sharpe (the guy of the "Sharpe Ratio") and Harry Markowitz, in efficient markets the yeld of an asset can be calculated as the sum between the risk-free interest rate and the risk premium. The risk premium of the specific asset would be the risk premium of the market portfolio multiplied with the value of beta. It is simple: if the volatility of the yelds of an asset around the yelds of market protfolio are particularly high, investors would ask for a higher risk premium that would be translated in a higher yeld.
In this way the expected yeld of an asset would be calculated from the linear expression of the "Security Market Line": r_i = r_f + β*(r_m-r_f)
where:
r_i = expected yeld of the asset
r_f = risk free interest rate
β = beta
r_m = yeld of market portfolio
I know that considering Bitcoin as a proxy of the market portfolio involved in the calculation of Beta would be an inaccuracy since it doesn't have the property of maximum diversification (since it is a single asset), but there's no doubt that it's tying the prices of altcoins (upward and downward) thanks to the relevance of its dominance in the capitalization of cryptocurrency market. So, in the lack of a good index of cryptocurrencies (as the FTSE MIB for the italian stock market), and as long the dominance of Bitcoin will persist with this intensity, we can use Bitcoin as a proxy of the market portfolio
Monthly SeasonalitySimple indicator designed as filter so you can easily see how the currency or asset performed during each month historically.
Can used to identify a possible month to enter or exit a trade in. For best results use in combination with another indicator or candle pattern to signal an entry in a historically bullish month
*This indicator is designed to be used only on the monthly chart.
Expected Range and SkewThis is an open source and updated version of my previous "Confidence Interval" script. This script provides you with the expected range over a given time period in the future and the skew of that range. For example, if you wanted to know the expected 1 standard deviation range of MSFT over the next 20 days, this will tell you that. Additionally, this script will also tell you the skew of the expected range.
How to use this script:
1) Enter the length, this will determine the number of data points used in the calculation of the expected range.
2) Enter the amount of time you want projected forward in minutes, hours, and days.
3) Input standard deviation of the expected range.
4) Pick the type of data you want shown from the dropdown menu. Your choices are either the expected range or the skew of the expected range.
5) Enter the x and y coordinates of the label (optional). This is useful so it doesn't impede your view of the plot.
Here are a few notes about this script:
First, the expected range line gives you the width of said range (upper bound - lower bound), and the label will tell you specifically what the upper and lower bounds of the expected range are.
Second, this script will work on any of the default timeframes, but you need to be careful with how far out you try to project the expected range depending on the timeframe you're using. For example, if you're using the 1min timeframe, it probably won't do you any good trying to project the expected range over the next 20 days; or if you're using the daily timeframe it doesn't make sense to try to project the expected range for the next 5 hours. You can tell if the time horizon you're trying to project doesn't work well with the chart timeframe you're using if the current price is outside of either the upper or lower bounds provided in the label. If the current price is within the upper and lower bounds provided in the label, then the time horizon that you're projecting over is reasonable for the chart timeframe you're using.
Third, this script does not countdown automatically, so the time provided in the label will stay the same. For example, in the picture above, the expected range of Dow Futures over the next 23 days from January 12th, 2021 is calculated. But when tomorrow comes it won't count down to 22 days, instead it will show the range over the next 23 days from January 13th, 2021. So if you want the time horizon to change as time goes on you will have to update this yourself manually.
Lastly, if you try to set an alert on this script, you will get a warning about it possibly repainting. This is because of the label, not the plot itself. The label constantly updates itself, which triggers the warning. I tested setting alerts on this script both with and without the inclusion of the label, and without the label the repainting warning did not occur. So remember, if you set an alert on this script you will get a warning about it possibly repainting, but this is because of the label constantly updating, not the plot itself.
Daily GAP StatsI did not write the script from scratch but rather started editing code of an existing one. The original code came from a script called GAP DETECTOR by @Asch-
First up: I am a trader, not a programmer and therefore my code most likely is inefficient. If someone with more expertise would like to help and optimize it - feel free to get in touch, I am always happy to learn some new tricks. :)
This script does 2 things:
- It shows daily gaps stats based on user inputs
- It shows color coded labels on gap days with additional information in tooltips ( important: make sure to read 'known issues/limitations' at the end )
User Inputs
==========
Although the input dialog is pretty straight forward, I do a quick rundown:
- Length: max lookback time
- Gap Direction: self explanatory
- Show All Gaps | Cont Only | Reversal Only | Off:
This refers to the way labels are displayed on gap days (again: make sure to read known issues/limitations!)
- Show All Gaps: does what it says
- Cont Only: only shows gaps where price continued in the gap direction. If you filter for gap ups and chose 'Cont only' you will only see labels on gap days where price closed above the open (and vice versa if you scan for gap downs).
- Reversal Only: you will only see labels for closes below the open on gap up days (and the opposite on gap down days)
- Off: self explanatory
- Gap Measure in ATR/PCT: self explanatory, ATR is calculated over a 10d period
- Gap Size (Abs Values): no negative values allowed here. If you filter for gap downs and enter 3 it means it will show gaps where the stock fell more than 3 ATR/PCT on the open.
- RVOL Factor: along with significant gaps should come significant volume. RVOL = volume of the gap day / 20d average volume
- Viewing Options: Placing the stats label in the window is a bit tricky (see knonw issues/limitations) and I was not sure which way I liked better. See for yourself what works best for you.
Known Isusses/Limitations:
=======================
- Positioning of the stats table:
As to my knowledge, Tradingview only allows label positioning relative to price and not relative to the chart window. I tried to always display the gap stats table in the upper right corner, using 52wk high as y-coordinate. This works ok most of the time, but is not pretty. If anybody has some fancy way to tag the label in a fixed position, please get in touch.
- Max number of labels per script:
TradingView has a limitation that allows a maxium of ~50 labels per script. If there are more labels, TradingView will automatically cut the oldest ones, without any notification. I have found this behaviour to be rather inconsistent - sometimes it'll dump labels even if there are a lot fewer than 50. Hopefully TradingView will drop this limitation at one point in the future.
Important: The inconsistent display of the gap day labels has NO INFLUENCE on the calculations in the gap stats table - the count and the calculations are complete and correct!
Intraday volatility expectationManaging expectation is important for price action traders.
This indicator mainly for intraday reference, and it plots the price change/ volatility statistics on a bar-to-bar basis, with the marking of +/- 1 and 2 sigma SD .
The user can refer to the historical volatility to manage their expectation of the velocity of price action by referring to these statistics.
[blackcat] L1 Close Histogram OscillatorLevel: 1
Background
A histogram is a special chart that is applied to statistical data that is divided into numerically ordered groups. For example groups with close relationships in the vicinity like "Close-ref(Close ,1)", "Close-ref(Close,2)" and so on. A histogram provides a snapshot of all the data so that you can quickly get an overview of the historical data, especially its general shape.In a histogram, the bars are linked - in contrast to a bar chart for categorical data, in which the bars represent categories that are in no particular order and are separated. The height of each bar in a histogram indicates either the number of individuals (called the frequency) in each group or the percentage of individuals (the relative frequency) in each group. Each individual in the data set falls into exactly one bar.
Function
L2 Close Histogram Oscillator is a novel overbought and oversold indicator that estimate the trend state by counting a specific bar relationship nearby. Once nearby bars reach consensus, it may spread to global quickly. The reason why I got this inspiration is because I have been engaged in the research of blockchain consensus mechanism. The market is a complex system, and its consensus depends on the common human characteristics: greed and fear. The trend of the market often also conforms to sociological characteristics. Maybe it's a bit complicated for me to say that. However, if you understand the principle of the spread of rumors and viruses, you can understand the situation where some individuals in the market have local consensus and gradually spread to the overall situation. This is the process of trend formation.
Key Signal
fastcounter --> fast close histogram counters
slowcounter --> slow close histogram counters
attention --> bottom price appears, with height of 10 in white
readybuy --> a small position buy opportunity after first bottom detected, with height of 20 in yellow
buylow --> a small position buy at low price, with height of 30 in lime
longentry --> a confirmed long entry signal by close histogram counter, with height of 40 in green
risk --> oscillator top is reached and trend reversal may happen, with height drop from 100 to 80 in red
Pros and Cons
Pros:
1. since this is based on consensus formation principle, i think this is a leading indicator by spreading local consensus to global
2. it is an oscillator, overbought and oversold can be easily observed.
Cons:
1. the model is not complex enough to depict market behavior exactly.
2. sideways and chop market will make this indicator's output hard to read.
Remarks
This is rare! I combined my previous theory of developing cellular automata with the market to produce such a weird indicator. I hope to inspire everyone and study market behavior in a deeper level.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
example: Event StatisticsEXPERIMENTAL:
A example on how to retrieve statistics from a recurring event.
Can be used to optimized strategy's, trade parameters, etc..