Turtle Trading Risk Adjusted Position Size CalculatorTurtle Trading Risk Adjusted Position Size Calculator
Hello Traders !
Turtle Trading Risk Adjustment Calculator (inspired by the Turtle Traders Position sizing methods) aims to objectively help day traders allocate the appropriate position size per trade by scaling different instruments by their risk, as measured by their volatility via the ATR (default - Average of 14 period True Range). By doing so This volatility-based position sizing method normalizes risk across different asset classes.
Understanding The formula
Formula U normalizes positions sizes among any non FX asset, by representing a standard unit of risk as a fraction of volatility adjusted by a risk coefficient (note higher risk coeff values (high uncertainty) will lead to lower trade capital allocation i.e lower position size - Varying the risk coefficient is relevant in expressing uncertainty) and scaled to ones trading account size relative to 1 contract of the asset to be traded, This is referred to as the Dollar volatility, formula D.
Dollar volatility is a bit confusing but in essence it is simply a factor of the asset price such that quantity sums to ones Trading account balance or how many times larger ones trading account is than the assets current market price, or more formally The amount of value a $1 change in the contract would impact your trading account given you are current trading all you account equity.
Formula TVPP is my own adaptation of the Turtle Trading Position Sizing formulas and the standard value per pip formula adjusted for volatility, this iteration has the same logic as stated above although the formulas vary.
Hope this is Useful, Wishing you Luck in your Trading Journey - u got this !!
Statistics
Futures/Spot Ratiowhat is Futures /Spot Ratio?
Although futures and spot markets are separate markets, they are correlated. arbitrage bots allow this gap to be closed. But arbitrage bots also have their limits. so there are always slight differences between futures and spot markets. By analyzing these differences, the movements of the players in the market can be interpreted and important information about the price can be obtained. Futures /Spot Ratio is a tool that facilitates this analysis.
what it does?
it compresses the ratio between two selected spot and futures trading pairs between 0 and 100. its purpose is to facilitate use and interpretation. it also passes a regression (Colorful Regression) through the middle of the data for the same purpose.
about Colorful Regression:
how it does it?
it uses this formula:
how to use it?
use it to understand whether the market is priced with spot trades or leveraged positions. A value of 50 is the breakeven point where the ratio of the spot and leveraged markets are equal. Values above 50 indicate excess of long positions in the market, values below 50 indicate excess of short positions. I have explained how to interpret these ratios with examples below.
RS Stage AnalysisThis script trying to detect different lifecycle of stock / Stages.
There is mainly 4 stages of stocks.
1) stage 1 - Accumulation = color = aqua
2) stage 2 - Advancing = color = green
3) stage 3 - Distribution = color = yellow
4) stage 4 - Declining = color = red
At some point the condition i wrote wont detect any stage.
XLY/XLP RatioThe XLY/XLP ratio is a financial indicator that measures the ratio between the two ETFs (Exchange Traded Funds) Consumer Discretionary Select Sector SPDR Fund (XLY) and Consumer Staples Select Sector SPDR Fund (XLP). This ratio is often used by traders and investors as a measure of the relative success of companies in the consumer goods and consumer services sectors.
A higher XLY/XLP ratio indicates that consumer confidence is higher and people are more willing to spend their money on non-essential items, such as entertainment or luxury goods (discretionary spending). A lower XLY/XLP ratio, on the other hand, indicates that consumer confidence is lower and people are more willing to spend their money on essential items like food and household items (staple spending).
The interpretation of the XLY/XLP ratio depends on the current market situation and the analysis of the economic and political factors that may influence consumption. If the XLY/XLP ratio rises, it could be an indication of a growing economy and increasing consumer sentiment. However, if it falls, it could be an indication of a weakening economy or declining consumer confidence.
It is important to note that the XLY/XLP indicator should not be used as the sole indicator to make trading decisions. It is advisable to also consider other indicators, such as technical and fundamental analysis, before making a decision.
Gaps [Kioseff Trading]Hello!
This script "Gaps" is a continuation and improvement on a subset indicator included in the "Quartile Volume; Volume Aggregation; US Range Bars; Gaps)" script!
As advised by @thebearfib, the "Gaps" indicator is now standalone!
Features
Stat: Avg. Bars to Fill Up Gap
Stat: Avg. Bars to Fill Down Gap
Stat: Cumulative Up Gap % Increase
Stat: Cumulative Down Gap % Increase
Stat: Avg Up Gap % Increase
Stat: Avg Down Gap % Decrease
Nearest Unfilled Up Gaps and Down Gaps Displayed in Table
% Price Move Requirement, Including Dollar Amount, for Nearest Unfilled Gaps to Fill
Gaps Marked on Chart, Including Partially Filled Gaps and The % Amount a Partially Filled Gap Has Been Violated
Gaps Chart
The image above shows the data tables included in the indicator!
Settings
The image above shows various settings for the indicator!
The image above shows how partially filled gaps are marked using the default settings.
Exceeded price areas are shaded darker; however, by selecting the "No Partially Filled Gaps" option, the indicator will treat partially filled gaps differently.
The image above shows alternative behavior! Instead of the gap changing color it narrows in size.
The image above shows the indicator's behavior when selecting to show gap data in labels.
Therefore, when a gap is small and the box text is imperceptible, you can select to show the data in a label.
Additionally, you can select to display a "Gaps Chart".
The image above shows this feature enabled. The gaps chart shows the sequence of price gaps for the asset as candlesticks.
Thank you for checking this out; if you'd like other features included please let me know!
Highest/Lowest value since X time ago, various indicatorsThis script will count the bars back since the last time the current bar indicator value was either this low or this high.
It will provide the time in either, seconds, minutes, hours, days, weeks, months, or years.
please note:
There are currently no alerts setup for this script.
the length options only apply to the sources that have the "(MA)" in their name.
There is a horizontal line display issue which corrects once you adjust the amount of sources you want to use.
Once you select the amount of sources you would like to use, align the indicator so the horizontal lines match up with the table lines.
If find any bugs in the script, let me know.
Price Data LabelThis indicator gives you the ability to see historical data for each bar on the chart by simply hovering over the high of the bar, similar to the functionality of MarketSmith.
Data for each bar includes:
Open
High
Low
Close + Change
Percentage Change
Closing Range
Volume
Volume Percent based on 50 day average
Distance to 4 selectable moving averages
Example of stats on a historical bar:
* Note this only works on the last 500 historical bars. If you use bar replay it will work with 500 historical bars from the last bar.
* If you have multiple indicators on your chart, in order to see the data you will need to use visual order to bring to front. This can be done by clicking the three dots next to the indicator name and selecting visual order.
Correlation Coefficient TableThis is a sample PineSript code implementation using Correlation Coefficient. It uses the ta.correlation library of Pinescript and calculates the correlation based on user input length. The results are then plotted on a table. The corr value displays the actual correlation coefficient value while the Corr Status displays the interpretation of the correlation coefficient values.
The script takes the following input
Source Symbol - This is the base symbol which will be used in calculating correlation coefficient. In my case, since i am looking more often on crypto. I defaulted it to BTCUSDT
Symbol 1 - Symbol 5 - These are the coins that will be compared to our base symbol for correlation.
Source - You can select on which price source you want to be calculated. By default this is set to candle close price.
Length - The number of price bar to look back and retrieve correlation coefficient. Set to 20 bars by default.
Table Settings - Since the correlation coefficient are displayed on a table. An option to customize the table settings are presented.
The Correlation Status column was based on this Interpretation:
For more information, read this article www.tradingview.com
Global (World) Monetary Supply M2 (measured in USD)This is the Global Monetary Supply M2 of the richest and most populous countries that have info from at least 2008
It is measured in USD (converting the M2 of each of the countries respective currencies and virtually converting them into USD)
This is less than the global liquidity as it does not include the countries' assets in other currencies (on their balance sheets), it only focuses on the monetary supply of each of the countries own currencies.
DataChartLibrary "DataChart"
Library to plot scatterplot or heatmaps for your own set of data samples
draw(this)
draw contents of the chart object
Parameters:
this : Chart object
Returns: current chart object
init(this)
Initialize Chart object.
Parameters:
this : Chart object to be initialized
Returns: current chart object
addSample(this, sample, trigger)
Add sample data to chart using Sample object
Parameters:
this : Chart object
sample : Sample object containing sample x and y values to be plotted
trigger : Samples are added to chart only if trigger is set to true. Default value is true
Returns: current chart object
addSample(this, x, y, trigger)
Add sample data to chart using x and y values
Parameters:
this : Chart object
x : x value of sample data
y : y value of sample data
trigger : Samples are added to chart only if trigger is set to true. Default value is true
Returns: current chart object
addPriceSample(this, priceSampleData, config)
Add price sample data - special type of sample designed to measure price displacements of events
Parameters:
this : Chart object
priceSampleData : PriceSampleData object containing event driven displacement data of x and y
config : PriceSampleConfig object containing configurations for deriving x and y from priceSampleData
Returns: current chart object
Sample
Sample data for chart
Fields:
xValue : x value of the sample data
yValue : y value of the sample data
ChartProperties
Properties of plotting chart
Fields:
title : Title of the chart
suffix : Suffix for values. It can be used to reference 10X or 4% etc. Used only if format is not format.percent
matrixSize : size of the matrix used for plotting
chartType : Can be either scatterplot or heatmap. Default is scatterplot
outliersStart : Indicates the percentile of data to filter out from the starting point to get rid of outliers
outliersEnd : Indicates the percentile of data to filter out from the ending point to get rid of outliers.
backgroundColor
plotColor : color of plots on the chart. Default is color.yellow. Only used for scatterplot type
heatmapColor : color of heatmaps on the chart. Default is color.red. Only used for heatmap type
borderColor : border color of the chart table. Default is color.yellow.
plotSize : size of scatter plots. Default is size.large
format : data representation format in tooltips. Use mintick.percent if measuring any data in terms of percent. Else, use format.mintick
showCounters : display counters which shows totals on each quadrants. These are single cell tables at the corners displaying number of occurences on each quadrant.
showTitle : display title at the top center. Uses the title string set in the properties
counterBackground : background color of counter table cells. Default is color.teal
counterTextColor : text color of counter table cells. Default is color.white
counterTextSize : size of counter table cells. Default is size.large
titleBackground : background color of chart title. Default is color.maroon
titleTextColor : text color of the chart title. Default is color.white
titleTextSize : text size of the title cell. Default is size.large
addOutliersToBorder : If set, instead of removing the outliers, it will be added to the border cells.
useCommonScale : Use common scale for both x and y. If not selected, different scales are calculated based on range of x and y values from samples. Default is set to false.
plotchar : scatter plot character. Default is set to ascii bullet.
ChartDrawing
Chart drawing objects collection
Fields:
properties : ChartProperties object which determines the type and characteristics of chart being plotted
titleTable : table containing title of the chart.
mainTable : table containing plots or heatmaps.
quadrantTables : Array of tables containing counters of all 4 quandrants
Chart
Chart type which contains all the information of chart being plotted
Fields:
properties : ChartProperties object which determines the type and characteristics of chart being plotted
samples : Array of Sample objects collected over period of time for plotting on chart.
displacements : Array containing displacement values. Both x and y values
displacementX : Array containing only X displacement values.
displacementY : Array containing only Y displacement values.
drawing : ChartDrawing object which contains all the drawing elements
PriceSampleConfig
Configs used for adding specific type of samples called PriceSamples
Fields:
duration : impact duration for which price displacement samples are calculated.
useAtrReference : Default is true. If set to true, price is measured in terms of Atr. Else is measured in terms of percentage of price.
atrLength : atrLength to be used for measuring the price based on ATR. Used only if useAtrReference is set to true.
PriceSampleData
Special type of sample called price sample. Can be used instead of basic Sample type
Fields:
trigger : consider sample only if trigger is set to true. Default is true.
source : Price source. Default is close
highSource : High price source. Default is high
lowSource : Low price source. Default is low
tr : True range value. Default is ta.tr
Global Monetary Supply M2 Vs the Global GDP This indicator compares the Global (world) Monetary Supply (measured in USD) compared to the Global GDP.
This can be useful to measure the "money printing speed" of the world compare to the "world gdp growth", the higher the slope (angle of growth) the more money printing.
It includes the exact same countries of the Global M2 indicator (done by me), to make fair the comparison, which has the richest and most populous countries so to have a clear overview.
There tough a few very populated countries excluded, the details can be found on the Global M2 indicator script and reason for exclusion.
Enjoy!
Feature ScalingLibrary "Feature_Scaling"
FS: This library helps you scale your data to certain ranges or standarize, normalize, unit scale or min-max scale your data in your prefered way. Mostly used for normalization purposes.
minmaxscale(source, min, max, length)
minmaxscale: Min-max normalization scales your data to set minimum and maximum range
Parameters:
source
min
max
length
Returns: res: Data scaled to the set minimum and maximum range
meanscale(source, length)
meanscale: Mean normalization of your data
Parameters:
source
length
Returns: res: Mean normalization result of the source
standarize(source, length, biased)
standarize: Standarization of your data
Parameters:
source
length
biased
Returns: res: Standarized data
unitlength(source, length)
unitlength: Scales your data into overall unit length
Parameters:
source
length
Returns: res: Your data scaled to the unit length
TableBuilderLibrary "TableBuilder"
A helper library to make it simpler to create tables in pinescript
This is a simple table building library that I created because I personally feel that the built-in table building method is too verbose. It features chaining methods and variable arguments.
There are many features that are lacking because the implementation is early, and there may be antipatterns because I am not familiar with the runtime behavior like pinescript. If you have any comments on code improvements or features you want, please comment :D
Hurst Exponent Trend filterHello Traders !!
Hurst Exponent Trend filter utalises the Hurst Exponent and VAWMA (one of my other unique indicators - check my script publishings to use) to categorise the market and decide whether its Trending, H > 0.5, In random Geometric Brownian Motion (GBM) H = 0.5 or Mean reverting (Contrarian), H < 0.5, When Trending a Trend following indicator -The VAWMA- is color highlighted, By doing so, theoreticaly price noise is eleimnated leaving statsitcaly true zones of price action Trend.
What is The Hurst Exponent ?
Developed by The Hydrologist Edwin Harlod Hurst, The Hurst Exponent measures auto correlation in time series sets, Its first applicartions were in the natural world, e.g. in measureing the volume of water in a river.
Although since then it has had applications in Finance, this may be largly due to autocorrelation functions being usefull tools in univaritae time series anaylyis.
The Hurst Exponent (H) aims to segment the market into three differnet states, Trending (H > 0.5), Random Geometric Brownian Motion (H = 0.5) and Mean Reverting / Contrarian (H < 0.5). In my interpritation this can be used as a trend filter that iliminates market noise, which may be achived by only focusing on trending zones.
How to Interprit the Indicator :
Focusing on the Above image, When H > 0.5 A trend is presnet, to decide the directional bias, both VAWMA`s position is checked, given the fast VAWMA > slow VAWMA and the current close > the fast VAWMA a bulish bias is present, signafied by a vibrant green fill between the fast VAWMA and price action. note the exact opposite logic for a bearish bias and H > 0.5 (signafied by a vibrant red fill). .
I will continue to update this Trading Indicator.
PS : Thats given I can hopfully remmember
Happy Trading !!
SILLibrary "SIL"
mean_src(x, y)
calculates moving average : x is the source of price (OHLC) & y = the lookback period
Parameters:
x
y
stan_dev(x, y, z)
calculates standard deviation, x = source of price (OHLC), y = the average lookback, z = average given prior two float and intger inputs, call the f_avg_src() function in f_stan_dev()
Parameters:
x
y
z
vawma(x, y)
calculates volume weighted moving average, x = source of price (OHLC), y = loookback period
Parameters:
x
y
gethurst(x, y, z)
calculates the Hurst Exponent and Hurst Exponent average, x = source of price (OHLC), y = lookback period for Hurst Exponent Calculation, z = lookback period for average Hurst Exponent
Parameters:
x
y
z
Multi-Asset Month/Month % change 10yr Averages10 Year Averages of Month-on-Month % change: Shows current asset, and 3x user input assets
-For comparing seasonal tendencies among different assets.
-Choose from a variety of monthly average measures as source: sma(close, length), sma(ohlc4, length); as well as sma's of vwap, vwma, volume, volatility. (sma = simple moving average).
-Averages based on month cf previous month: i.e. Feb % = Feb compared to Jan; Jan % = Jan compared to prev year's Dec. Average of the last 10yrs of these values is the printed value.
-Plot on current year (2023), or previous year (2022). If Plotting on current year, and a month of year has not yet occured, a 9yr average will be printed.
/// notes ///
-daily bars in month is a global setting; so choose assets which have similar trading days per month. i.e. Crypto: length = 30 (days per month); Stocks/FX/Indices: length = 21 (days per month).
-only plots on Daily timeframe.
10yr Avgs; Plotting with Year = 2022; using sma(close, 21) as source for average M/M change
CBDE OscillatorWhat makes The Universe grow at an accelerating pace?
Dark Energy.
What makes The Economy grow at an accelerating pace?
Debt.
Debt is the Dark Energy of The Economy.
The Central Bank Dark Energy Oscillator (CBDEO) is a companion to the popular CBDET (Central Bank Dark Energy Tracer) script.
CBDEO is an oscillator that shows up in a separate TradingView pane in order to provide a relative change signal. It uses the same equations to aggregate central bank liquidity that are used in CBDET, and adds unique analysis tools that provide rate of change data.
There are 2 signals in the chart. First is the change/delta on a per bar basis, based on the chart time frame. The default style for this plot is "columns". This style parameter can be changed in the settings, along with each plot's visibility.
The second plot is a divergence signal that tests the change vs a simple moving average of the CBDET signal (central bank liquidity). The SMA length is customizable in the Input tab within the settings for the indicator. The SMA is based on the chart's current time frame.
The changes in liquidity on various time frames, and calculated as divergence against the liquidity signal SMA can be useful in determining the rate of change in liquidity, and therefore potential thrust in market price action.
Fundamentals Graphing [Kioseff Trading]Hello!
This script "Fundamental Comparison" allows you to compare almost any fundamental metric across 40 assets; various charting methods are employable!
Thank you to @TradingView / @PineCoders for providing the framework in the "Financials on Chart" indicator - thereby expediting a generous portion of work (:
Features
Most metrics included in the "Financials on Chart" indicator are graphable
Scatter chat
Histogram
Bar chart
Pie chart
Reversible scaling
Adjusts to the size of your chart
10 industry presets
Custom symbol dataset
Retrieve, graph, and compare fundamental data by quarter/year. The indicator can "look back" to grab fundamental data from previous quarters/years.
Sortable data - ascending/descending
Built-in search function
Self-Adjusting Graph
The graph adjusts to the orientation/size of your chart!
The image above shows the graph on a price chart with a 229 bar difference.
The image above shows the same price chart; however, there's now a 1941 bar difference to which the fundamentals graph automatically adjusts!
The images above show the same expansion/reduction for the pie chart; all graph types shrink and expand with the price chart.
Fundamental Metrics
The image above shows most of the settings for the indicator!
Most of the metrics from the "Financials on Chart" indicator are included!
Quarterly or annual data are retrievable, in addition to industry presets.
Additionally, you can retrieve the financial data any number of intervals back (so long as the data exists and is provided by TradingView)
The image above shows an example of retrieving a fundamental metric from a previous FQ. The same can be done with FY!
Sortable Data
All data retrieved by the indicator is sortable - allowing for, hopefully, easier evaluations (:
The image above exemplifies the capability!
Data from any quarter/year can be sorted similarly.
Reversible Scale / Reversible Color Scheme
A seemingly trivial feature: a reversible scale and color scheme should assist in instances where "a higher number is bad" and a "lower number is good" - in addition to other scenarios.
For instance,
The image above shows a graph for taxes. The scale and color scheme have not been reversed and, presently, larger columns are correlating to a smaller amount of money out/in than smaller columns.
This can be fixed by reversing the scale.
The image above shows the "Reverse Scale" feature selected. Consequently, larger columns correlate to a larger amount of money out/in.
Similarly, a "Reverse Colors" feature is available. A useful option when a more positive number is "bad" and a less positive number is "good".
For instance,
The image above shows graphing for the Beneish M-Score.
A more positive number is generally interpreted as "bad"; a less positive number is generally interpreted as "good".
However, our color scheme doesn't seem to correspond (unless one considers red = good and green = bad)
Let's enable the reverse color feature.
The image above shows the completion of the process!
Finally, there's a built-in search feature that's a bit difficult to use; however, should you grow comfortable with it you may save some time sorting through fundamental data.
Big thanks to @rumpypumpydumpy for providing an easy-to-work-with framework for the pie chart!
That's all for now; thank you for checking this out.
VIX Reference IndicatorHello everyone,
Releasing my VIX reference indicator.
What is it:
This indicator displays the current trading behaviour of the VIX.
It displays it in Z-Score Format along with identifying previous areas of reversal and displaying when the RSI is overbought or oversold on the VIX.
Who is it good for:
It is good for both day and swing traders who use the VIX in their trading plans.
It permits traders to look at different aspects of the VIX (RSI, Z-Score and Reversal areas) simultaneously while they are watching their current traded stock.
How does it work:
The indicator works by converting the VIX into a Z-Score (similar to bollinger bands).
It then plots the VIX out in Z-Score format in the indicator.
Because it is plotting the VIX based on Z-Score, it looks back to previous areas where the Z-Score led to a reversal (i.e. what was the lowest or highest Z-Score the VIX achieved in the lookback period before reversing).
It also looks at the RSI of the VIX. If the VIX RSI crosses at or above 70 (overbought), it will change the colour of the line to green. This means the VIX is overbought and will likely sell and thus, the thesis is, as the VIX sells, the stock you are trading should come up.
Below is a picture of the different aspects of the indicator:
Customaization:
Per usual, you can customize the colours and bands to your liking.
You are also able to specify the RSI length you want to look at as well as the Z-Score Reversal length and the timeframe length of the chart you are looking at.
The default settings are 75 Average Length lookback for the Z-Score Reversal and the Chart and 14 period RSI.
TIPS:
The most persuasive setups are when you get all 3 of the following:
1. A signal that supports the thesis (buy or sell) along with:
2. An RSI signal that supports the z-score signal along with:
3. The VIX trading at an extreme end of its Z-Score range
Example:
In the example above you will see the following conditions are met:
1. Z-Score historical reversal point identified (short)
2. VIX RSI is oversold (short)
3. VIX is at the bottom of its Z-Score range (short)
As always, I have done a quick tutorial video for your reference which you can see below:
Leave your questions/comments/requests below or on the video as I am always happy to get feedback on improvements and functionality.
Thank you everyone checking it out and safe trades!
Correlation Matrix + Heatmap - By LeviathanA quick and easy way to visualize the correlation between 10 different symbols over a custom period of time, in the form of a matrix with a heatmap visualization and additional tools such as price increase/decrease %, multi-timeframe function, customizable appearance and more.
The indicator displays correlation coefficients for each pair of 10 assets in a matrix format, where the rows and columns represent the assets being compared between each other. The color of each cell corresponds with the strength of the correlation coefficient, allowing you to quickly identify which assets are strongly correlated, and which are not, and use that information to adjust risk or even get trade ideas. Coupled with the "Price Change" function, the script will help you find trade opportunities based on eg. the long-term correlation strength and short-term price direction differences between two assets. The "Correlation Length" input defines the number of bars used for calculating the correlation, while "Price Change Length" defines the bar to which the current price is compared when calculating price change (eg. the input 20 means that the script will compare the price of the candle close that occurred 20 bars ago and the current price).
Correlation coefficient:
The correlation coefficient is a statistical measure that quantifies the degree of linear relationship between two variables. The correlation coefficient ranges from -1 to 1, with 1 being perfect positive correlation and -1 being perfect negative correlation.
• A correlation coefficient of 1 indicates a perfect positive linear relationship between two variables. This means that when one variable increases, the other variable also increases in a proportional manner.
• A correlation coefficient of 0 indicates no linear relationship between two variables. This means that changes in one variable do not affect the other variable.
• A correlation coefficient of -1 indicates a perfect negative linear relationship between two variables. This means that when one variable increases, the other variable decreases in a proportional manner.
Inspired by @RicardoSantos's script
libKageMiscLibrary "libKageMisc"
Kage's Miscelaneous library
print(_value)
Print a numerical value in a label at last historical bar.
Parameters:
_value : (float) The value to be printed.
Returns: Nothing.
barsBackToDate(_year, _month, _day)
Get the number of bars we have to go back to get data from a specific date.
Parameters:
_year : (int) Year of the specific date.
_month : (int) Month of the specific date. Optional. Default = 1.
_day : (int) Day of the specific date. Optional. Default = 1.
Returns: (int) Number of bars to go back until reach the specific date.
bodySize(_index)
Calculates the size of the bar's body.
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.
Returns: (float) The size of the bar's body in price units.
shadowSize(_direction)
Size of the current bar shadow. Either "top" or "bottom".
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) The size of the chosen bar's shadow in price units.
shadowBodyRatio(_direction)
Proportion of current bar shadow to the bar size
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) Ratio of the shadow size per body size.
bodyCloseRatio(_index)
Proportion of chosen bar body size to the close price
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.()
Returns: (float) Ratio of the body size per close price.
lastDayOfMonth(_month)
Returns the last day of a month.
Parameters:
_month : (int) Month number.
Returns: (int) The number (28, 30 or 31) of the last day of a given month.
nameOfMonth(_month)
Return the short name of a month.
Parameters:
_month : (int) Month number.
Returns: (string) The short name ("Jan", "Feb"...) of a given month.
pl(_initialValue, _finalValue)
Calculate Profit/Loss between two values.
Parameters:
_initialValue : (float) Initial value.
_finalValue : (float) Final value = Initial value + delta.
Returns: (float) Profit/Loss as a percentual change.
gma(_Type, _Source, _Length)
Generalist Moving Average (GMA).
Parameters:
_Type : (string) Type of average to be used. Either "EMA", "HMA", "RMA", "SMA", "SWMA", "WMA" or "VWMA".
_Source : (series float) Series of values to process.
_Length : (simple int) Number of bars (length).
Returns: (float) The value of the chosen moving average.
xFormat(_percentValue, _minXFactor)
Transform a percentual value in a X Factor value.
Parameters:
_percentValue : (float) Percentual value to be transformed.
_minXFactor : (float) Minimum X Factor to that the conversion occurs. Optional. Default = 10.
Returns: (string) A formated string.
isLong()
Check if the open trade direction is long.
Returns: (bool) True if the open position is long.
isShort()
Check if the open trade direction is short.
Returns: (bool) True if the open position is short.
lastPrice()
Returns the entry price of the last openned trade.
Returns: (float) The last entry price.
barsSinceLastEntry()
Returns the number of bars since last trade was oppened.
Returns: (series int)
getBotNameFrosty()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getBotNameZig()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getTicksValue(_currencyValue)
Converts currency value to ticks
Parameters:
_currencyValue : (float) Value to be converted.
Returns: (float) Value converted to minticks.
getSymbol(_botName, _botCustomSymbol)
Formats the symbol string to be used with a bot
Parameters:
_botName : (string) Bot name constant. Either BOT_NAME_FROSTY or BOT_NAME_ZIG. Optional. Default is empty string.
_botCustomSymbol : (string) Custom string. Optional. Default is empy string.
Returns: (string) A string containing the symbol for the bot. If all arguments are empty, the current symbol is returned in Binance format.
showProfitLossBoard()
Calculates and shows a board of Profit/Loss through the years.
Returns: Nothing.
MVRV Z Score and MVRV Free Float Z-ScoreIMPORTANT: This script needs as much historic data as possible. Please run it on INDEX:BTCUSD , BNC:BLX or another chart of sufficient length.
MVRV
The MVRV (Market Value to Realised Value Ratio) simply divides bitcoins market cap by bitcoins realized market cap. This was previously impossible on Tradingview but has now been made possible thanks to Coinmetrics providing us with the realized market cap data.
In the free float version, the free float market cap is used instead of the regular market cap.
Z-Score
The MVRV Z-score divides the difference between Market cap and realized market cap by the historic standard deviation of the market cap.
Historically, this has been insanely accurate at detecting bitcoin tops and bottoms:
A Z-Score above 7 means bitcoin is vastly overpriced and at a local top.
A Z-Score below 0.1 means bitcoin is underpriced and at a local bottom.
In the free float version, the free float market cap is used instead of the regular market cap.
The Z-Score, also known as the standard score is hugely popular in a wide range of mathematical and statistical fields and is usually used to measure the number of standard deviations by which the value of a raw score is above or below the mean value of what is being observed or measured.
Credits
MVRV Z Score initially created by aweandwonder
MVRV initially created by Murad Mahmudov and David Puell