Value At Risk Channel [AstrideUnicorn]The Value at Risk Channel (VaR Channel) is a trading indicator designed to help traders control the level of risk exposure in their positions. The user can select a time period and a probability value, and the indicator will plot the upper and lower limits that the price can reach during the selected time period with the given probability.
CONCEPTS
The indicator is based on the Value at Risk (VaR) calculation. VaR is an important metric in risk management that quantifies the degree of potential financial loss within a position, portfolio or company over a specific period of time. It is widely used by financial institutions like banks and investment companies to forecast the extent and likelihood of potential losses in their portfolios.
We use the so-called “historical method” to compute VaR. The algorithm looks at the history of past returns and creates a histogram that represents the statistical distribution of past returns. Assuming that the returns follow a normal distribution, one can assign a probability to each value of return. The probability of a specific return value is determined by the distribution percentile to which it belongs.
HOW TO USE
Let’s assume you want to plot the upper and lower limits that price will reach within 4 hours with 5% probability. To do this, go to the indicator Settings tab and set the Timeframe parameter to "4 hours'' and the Probability parameter to 5.0.
You can use the indicator to set your Stop-Loss at the price level where it will trigger with low probability. And what's more, you can measure and control the probability of triggering.
You can also see how likely it is that the price will reach your Take-Profit within a specific period of time. For example, you expect your target level to be reached within a week. To determine this probability, set the Timeframe parameter to "1 week" and adjust the Probability parameter so that the upper or lower limit of your VaR channel is close to your Take-Profit level. The resulting Probability parameter value will show the probability of reaching your target in the expected time.
The indicator can be a useful tool for measuring and managing risk, as well as for developing and fine-tuning trading strategies. If you find other uses for the indicator, feel free to share them in the comments!
SETTINGS
Timeframe - sets the time period, during which the price can reach the upper or lower bound of the VaR channel with the probability, set by the Probability parameter.
Probability - specifies the probability with which the price can reach the upper or lower bound of the VaR channel during the time period specified by the Timeframe parameter.
Window - specifies the length of history (number of historical bars) used for VaR calculation.
Statistics
Opening Price ChangeThis script shows the change from the market opening price to the market closing price of the previous day in percent.
With this you can quickly get an overview of historical data for the change of the respective day.
Important: the market closing price is always used for the calculation and not the pre/post market price.
The label with the change value is always placed above the first opens regular market bar. If the change is positive, the label is draw with a green background, is the change is negative you will have a red background.
SPY Volume Weighted CloseHey everyone!
Deciding to make this indicator public and open access.
This is a volume weighted close indicator for SPY. It is a statistics based indicator.
How it works:
It uses volume data mixed with some price action data to prospectively predict where SPY's price will close within a 30 minute interval.
As such, its different from other indicators in the sense that its not reactive, it proactive and actively predicts the price that SPY will see within the next 30 minutes and where SPY will most likely close at.
It has 3 bands. The main centre band (blue, but colour can be changed) is the most likely price that SPY will close at within the next 30 minutes.
The Upper Level Confidence and Lower Level Confidence bands are the expected range that the analysis thinks SPY will remain confined in based on current volume and price action.
How to Use it:
I personally use this in place of VWAP, but the applications are infinite. Take a look at the chart below:
Applications:
This is specifically programmed for SPY but I have used it with other stocks such as QQQ, UPRO and DIA. However, using it with those stocks, the upper and lower confidence bands are not helpful. But YMMV with other stocks. This is specifically designed for SPY.
Let me know your questions and thoughts!
Thanks for reading and checking this out!
deseasonalized_modDescription:
As in the decomposition of time series data, the indicator was modified from the deseasonalized process, to avoid overfitting as in the original format, aiming to exclude seasonal component (shorter time-period in consideration), thus leaving trend and irregularity. The indicator is expected to identify short-term trends, based on the given timeframe.
Notes:
Length set to 10-bar as default, while reducing the length to e.g. 8 increase more responsive of the fitted data, however inline to increase a false trend identification (bias-variance trade-off). To be noted, the indicator wasn't a momentum indicator, thus can only expect the trend identifier instead. If the price is above the fitted line (indicator), and experiencing a retracement, regularly expected to be bounced around the fitted line (support), while if breaks to the downside, expected a trend reversal, and become a (resistance).
Feature:
Buy/Long overlay signal
Sell/Short overlay signal
Alert
DatasetWeatherTokyoMeanAirTemperatureLibrary "DatasetWeatherTokyoMeanAirTemperature"
Provides a data set of the monthly mean air temperature (°C) for the city of Tokyo in Japan.
this was just for fun, no financial implications in this.
reference:
www.data.jma.go.jp
TOKYO WMO Station ID:47662 Lat 35o41.5'N Lon 139o45.0'E
year_()
the years of the data set.
Returns: array : year values.
january()
the january values of the dataset
Returns: array\ : data values for january.
february()
the february values of the dataset
Returns: array\ : data values for february.
march()
the march values of the dataset
Returns: array\ : data values for march.
april()
the april values of the dataset
Returns: array\ : data values for april.
may()
the may values of the dataset
Returns: array\ : data values for may.
june()
the june values of the dataset
Returns: array\ : data values for june.
july()
the july values of the dataset
Returns: array\ : data values for july.
august()
the august values of the dataset
Returns: array\ : data values for august.
september()
the september values of the dataset
Returns: array\ : data values for september.
october()
the october values of the dataset
Returns: array\ : data values for october.
november()
the november values of the dataset
Returns: array\ : data values for november.
december()
the december values of the dataset
Returns: array\ : data values for december.
annual()
the annual values of the dataset
Returns: array\ : data values for annual.
select_month(idx)
get the temperature values for a specific month.
Parameters:
idx : int, month index (1 -> 12 | any other value returns annual average values).
Returns: array\ : data values for selected month.
select_value(year_, month_)
get the temperature value of a specified year and month.
Parameters:
year_ : int, year value.
month_ : int, month index (1 -> 12 | any other value returns annual average values).
Returns: float : value of specified year and month.
diff_to_median(month_)
the difference of the month air temperature (ºC) to the median of the sample.
Parameters:
month_ : int, month index (1 -> 12 | any other value returns annual average values).
Returns: float : difference of current month to median in (Cº)
Gap Stats v2This helpful analysis tool displays a table of days a stock has gapped, how much it gapped by and what percentage of the gap was covered.
It is meant to be used on the daily timeframe and can help you distinguish if gaps are going to be filled or not. I like to use it mainly on medium + cap stocks
that have gapped overnight or pre-market and see what the tendency is with how it behaves after a major gap.
Plots CAGR lines for a given set of ratesPlots CAGR lines for a given set of rates from a specified time. It will be helpful to see how the rate of growth of a security's price is changing over a period of time. It also calculates the current CAGR from the time specified. Works on D, W, M timeframes.
Crypto Terminal [Kioseff Trading]Hello!
Introducing Crypto Terminal (:
The indicator makes use of cryptocurrency data provided by vendor INTOTHEBLOCK.
NOTE: The cryptocurrency on your chart must be paired with USD or USDT. Data won't load otherwise - possibly transient. For instance, BTCUSD or BTCUSDT, ETHUSD or ETHUSDT.
Provided datasets:
Twitter Sentiment Data
Telegram Sentiment Data
Whale Data (i.e. % of Asset Belonging to Whales)
$100,000+ Transactions
Bulls/Bears (Bulls Buying | Bears Selling)
Current Position PnL (Currently Open Positions for the Coin are Retrieved and Plotted. Data is Split into Currently Profitable Positions, Losing Positions, and B/E Positions)
Average Balance
Holders/Traders Percentage (Addresses are Retrieved and Classified as Holding Accounts or Trader Accounts)
Correlation
Futures OI
Perpetual OI
Zero Balance Addresses
Flow (Money Inflow & Outflow)
Active Addresses
Average Transaction Time
Realized PnL (Addresses with Realized Profits, Realized Losses, and B/E)
Cruisers
A few more data points are provided.
Additionally, you can plot the values of any dataset in a pane below price.
Below are images of plottable data; different cryptocurrencies will be shown for each example (:
Twitter sentiment data.
Assess this data lightly; difficult to confirm accuracy.
Telegram sentiment data.
Assess this data lightly; difficult to confirm accuracy.
Percentage of asset belonging to whales.
$100,000+ transactions (volume oriented)
Bulls buying; bears selling.
Current positions at profit; current positions at loss; current positions at breakeven.
Average balance.
Percentage of asset belonging to traders; percentage of asset belonging to holders.
Asset's 30-interval correlation to BTC.
Perpetual open interest.
Zero-balance addresses.
Flows.
Active addresses.
Average transaction time.
Addresses at realized profit; addresses at realized loss; addresses at breakeven.
Cruiser data.
Futures open interest.
Naturally, this data isn't provided for every cryptocurrency; NaN values are returned in some instances.
Table 1
I provided three data tables, which load independently, so you don't have to change plotted data to access values.
Table 2
Lastly, you can create a 10-asset crypto index and run calculations against it.
The image shows an example.
I'll update this script with additional calculations/data in the near future. If you've any suggestions - please let me know!
Enjoy (:
Inflation Adjusted Performance: Ticker/M2 money supplyPlots current ticker / M2 money supply, to give an idea of 'inflation adjusted performance'.
~In the above, see the last decade of bullish equities is not nearly as impressive as it seems when adjusted to account for the FED's money printing.
~Works on all timeframes/ assets; though M2 money supply is daily data release, so not meaningful to plot this on timeframe lower than daily.
~To display on same pane; comment-out line 6 and un-comment line 7; then save, remove and re-add indicator.
~Scale on the right is meaningless; this indicator is just to show/compare the shape of the charts.
[MT Trader] Backtest template w/ Supertrend Strategy---EN: In this strategy template you will find some functions already pre-programmed to be used in your strategies to speed up the programming process, among them we can highlight the default stop loss and take profit functions, which will help to set easily and quickly, defining the price range in which we want to prevent large losses or protect our profits from unexpected market movements.
🔴 Stop Loss: Among the functions of the stop loss are the 4 most known, first we have the fixed percentage range (%) and price ($), when the price reaches this fixed price will limit the losses of the operation avoiding larger losses, then we have the average true range (ATR), a moving average of true range and X period that can give us good reference points to place our stop loss, finally the last point higher or lower is the most used by traders to place their stop loss.
In addition, the price range between the entry and stop loss can be converted into a trailing stop loss.
🟢 Take Profit: We have 3 options for take profit, just like stop loss, the fixed range of percentage(%) and price($), are available, in addition to this we have the 1:# ratio option, which multiplies by X number the range between the entry and stop loss to use it as take profit, perfect for strategies that use ATR or last high/low point for their strategy.
📈 Heikin Ashi Entrys: The heikin ashi entries are trades that are calculated based on heikin ashi candles but their price is executed in Japanese candles, thus avoiding the false results that occur in heikin candlestick charts, making that in certain cases better results are obtained in the strategies that are executed with this option compared to Japanese candlesticks.
📊 Dashboard: A more visual and organized way to see the results and data needed for our strategy.
Feel free to use this template to program your own strategies, if you find bugs or want to request a new feature let me know in the comments or through my telegram @hvert_mt
__________________________________________________________________________________________________________________________________________________
---ES: En esta plantilla de estrategia podrás encontrar algunas funciones ya pre-programadas para ser usadas en tus estrategias para acelerar procesos de programación, entre ellas podemos destacar las funciones por defecto de stop loss y take profit, que ayudaran a establecer de manera fácil y rápida, definiendo los rango de precio en los que queremos prevenirnos de perdidas grandes o proteger nuestras ganancias de movimientos inesperados del mercado.
🔴 Stop Loss: Entre las funciones del stop loss están las 4 más conocidas, en primer lugar tenemos el rango de porcentaje fijo(%) y el precio($), cuando el precio alcance este precio fijo se limitaran las perdidas de la operación evitando perdidas mas grandes, después tenemos el promedio de rango verdadero(ATR), una media móvil del rango verdadero y X periodo que nos puede dar buenos puntos de referencia para colocar nuestro stop loss, por ultimo el ultimo punto mas alto o mas bajo es de los mas usados por los traders para colocar su stop loss.
Adicional a esto, el rango de precio entre la entrada y el stop loss se puede convertir en un trailing stop loss.
🟢 Take Profit: Tenemos 3 opciones para take profit, al igual que en el stop loss, el rango fijo de porcentaje(%) y precio($) se encuentran disponibles, adicional a esto tenemos la opción de ratio 1:#, que multiplica por X numero el rango entre la entrada y el stop loss para usarlo como take profit, perfecto para estrategias que usen ATR o ultimo punto alto/bajo.
📈 Entradas Heikin Ashi: Las entradas Heikin Ashi son trades que son calculados en base a las velas Aeikin Ashi pero su precio esta ejecutado a velas japonesas, evitando así los falsos resultados que se producen en graficas de velas Heikin, esto haciendo que en ciertos casos se obtengan mejores resultados en las estrategias que son ejecutadas con esta opción en comparación con las velas japonesas.
📊 Panel de Control: Una manera mas visual y organizada de ver los resultados y datos necesarios de nuestra estrategia.
Siéntete libre de usar esta plantilla para programar tus propias estrategias, si encuentras errores o quieres solicitar una nueva función házmelo saber en los comentarios o a través de mi Telegram: @hvert_mt
Key Performance IndicatorWe are happy to introduce the Key Performance Indicator by Detlev Matthes. This is an amazing tool to quantify the efficiency of a trading system and identify potential spots of improvement.
Abstract
A key performance indicator with high explanatory value for the quality of trading systems is introduced. Quality is expressed as an indicator and comprises the individual values of qualitative aspects. The work developing the KPI was submitted for the 2017 VTAD Award and won first prize.
Introduction
Imagine that you have a variety of stock trading systems from which to select. During backtesting, each trading system will deliver different results with regard to its indicators (depending on, inter alia, its parameters and the stock used). You will also get different forms of progression for profit development. It requires great experience to select the “best” trading system from this variety of information (provided by several indicators) and significantly varying equity progression forms. In this paper, an indicator will be introduced that expresses the quality of a trading system in just one figure. With such an indicator, you can view the results of one backtest at a glance and also more easily compare a variety of backtesting results with one another.
If you are interested in learning more about the calculations behind this indicator then I have included a link to the english version of his research paper.
Along with this, we now offer indicator development services. If you are interested in learning more then feel free to reach out to get a quote for your project.
**Please note that we have NOT inputted any real strategy into the code and therefore it is not producing any real value. Feel free to change the code as desired to test any strategy!**
drive.google.com
Breakout Probability (Expo)█ Overview
Breakout Probability is a valuable indicator that calculates the probability of a new high or low and displays it as a level with its percentage. The probability of a new high and low is backtested, and the results are shown in a table— a simple way to understand the next candle's likelihood of a new high or low. In addition, the indicator displays an additional four levels above and under the candle with the probability of hitting these levels.
The indicator helps traders to understand the likelihood of the next candle's direction, which can be used to set your trading bias.
█ Calculations
The algorithm calculates all the green and red candles separately depending on whether the previous candle was red or green and assigns scores if one or more lines were reached. The algorithm then calculates how many candles reached those levels in history and displays it as a percentage value on each line.
█ Example
In this example, the previous candlestick was green; we can see that a new high has been hit 72.82% of the time and the low only 28.29%. In this case, a new high was made.
█ Settings
Percentage Step
The space between the levels can be adjusted with a percentage step. 1% means that each level is located 1% above/under the previous one.
Disable 0.00% values
If a level got a 0% likelihood of being hit, the level is not displayed as default. Enable the option if you want to see all levels regardless of their values.
Number of Lines
Set the number of levels you want to display.
Show Statistic Panel
Enable this option if you want to display the backtest statistics for that a new high or low is made. (Only if the first levels have been reached or not)
█ Any Alert function call
An alert is sent on candle open, and you can select what should be included in the alert. You can enable the following options:
Ticker ID
Bias
Probability percentage
The first level high and low price
█ How to use
This indicator is a perfect tool for anyone that wants to understand the probability of a breakout and the likelihood that set levels are hit.
The indicator can be used for setting a stop loss based on where the price is most likely not to reach.
The indicator can help traders to set their bias based on probability. For example, look at the daily or a higher timeframe to get your trading bias, then go to a lower timeframe and look for setups in that direction.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Strategy BackTest Display Statistics - TraderHalaiThis script was born out of my quest to be able to display strategy back test statistics on charts to allow for easier backtesting on devices that do not natively support backtest engine (such as mobile phones, when I am backtesting from away from my computer). There are already a few good ones on TradingView, but most / many are too complicated for my needs.
Found an excellent display backtest engine by 'The Art of Trading'. This script is a snippet of his hard work, with some very minor tweaks and changes. Much respect to the original author.
Full credit to the original author of this script. It can be found here: www.tradingview.com
I decided to modify the script by simplifying it down and make it easier to integrate into existing strategies, using simple copy and paste, by relying on existing tradingview strategy backtester inputs. I have also added 3 additional performance metrics:
- Max Run Up
- Average Win per trade
- Average Loss per trade
As this is a work in progress, I will look to add in more performance metrics in future, as I further develop this script.
Feel free to use this display panel in your scripts and strategies.
Thanks and enjoy :)
FunctionDynamicTimeWarpingLibrary "FunctionDynamicTimeWarping"
"In time series analysis, dynamic time warping (DTW) is an algorithm for
measuring similarity between two temporal sequences, which may vary in
speed. For instance, similarities in walking could be detected using DTW,
even if one person was walking faster than the other, or if there were
accelerations and decelerations during the course of an observation.
DTW has been applied to temporal sequences of video, audio, and graphics
data — indeed, any data that can be turned into a linear sequence can be
analyzed with DTW. A well-known application has been automatic speech
recognition, to cope with different speaking speeds. Other applications
include speaker recognition and online signature recognition.
It can also be used in partial shape matching applications."
"Dynamic time warping is used in finance and econometrics to assess the
quality of the prediction versus real-world data."
~~ wikipedia
reference:
en.wikipedia.org
towardsdatascience.com
github.com
cost_matrix(a, b, w)
Dynamic Time Warping procedure.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: matrix optimum match matrix.
traceback(M)
perform a backtrace on the cost matrix and retrieve optimal paths and cost between arrays.
Parameters:
M : matrix, cost matrix.
Returns: tuple:
array aligned 1st array of indices.
array aligned 2nd array of indices.
float final cost.
reference:
github.com
report(a, b, w)
report ordered arrays, cost and cost matrix.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: string report.
10yr, 20yr, 30yr Averages: Month/Month % Change; SeasonalityCalculates 10yr, 20yr and 30yr averages for month/month % change
~shows seasonal tendencies in assets (best in commodities). In above chart: August is a seasonally bullish month for Gold: All the averages agree. And January is the most seasonally bullish month.
~averages represent current month/previous month. i.e. Jan22 average % change represents whole of jan22 / whole of dec21
~designed for daily timeframe only: I found calling monthly data too buggy to work with, and I thought weekly basis may be less precise (though it would certainly reduce calculation time!)
~choose input year, and see the previous 10yrs of monthly % change readings, and previous 10yrs Average, 20yr Average, 30yr Average for the respective month. Labels table is always anchored to input year.
~user inputs: colors | label sizes | decimal places | source expression for averages | year | show/hide various sections
~multi-yr averges always print, i.e if only 10yrs history => 10yr Av = 20yr Av = 30yr Av. 'History Available' label helps here.
Based on my previously publised script: "Month/Month Percentage % Change, Historical; Seasonal Tendency"
Publishing this as seperate indicator because:
~significantly slower to load (around 13 seconds)
~non-premium users may not have the historical bars available to use 20yr or 30yr averages =>> prefer the lite/speedier version
~~tips~~
~after loading, touch the new right scale; then can drag the table as you like and seperate it from price chart
##Debugging/tweaking##
Comment-in the block at the end:
~test/verifify specific array elements elements.
~see the script calculation/load time
~~other ideas ~~
~could tweak the array.slice values in lines 313 - 355 to show the last 3 consecutive 10yr averages instead (i.e. change 0, 10 | 0,20 | 0, 30 to 0, 10 | 10, 20 | 20,30)
~add 40yr average by adding another block to each of the array functions, and tweaking the respective labels after line 313 (though this would likely add another 5 seconds to the load time)
~use alternative method for getting obtaining multi-year values from individual month elements. I used array.avg. You could try array.median, array.mode, array.variance, array.max, array.min (lines 313-355)
Percentage Up/Down vs lowest/highestPercentage difference at current price (close) to lowest and highest certain number of bars ago (14, 36, 96).
Quantity Theory of Money (Inflation Growth Rate)Quantity Theory of Money ( Inflation Growth Rate)
Equation:
%ΔM+%ΔV=%ΔP+%ΔY
M - Money Supply , V - Money Velocity , Y - Real GDP, P - Price
This script only takes into account money supply theory and does not account for increases/decreases in inflation due to energy costs. QTM Calculation is compared to USIRYY , USCCPI , and Sticky Price CPI . Flex_CPI and Flex_Core_CPI are not available in Trading View for comparison.
Simple Moving Average Default it set to 3 quarters for smoothing purposes. You can change this via the input window as you see fit.
FunctionKellyCriterionLibrary "FunctionKellyCriterion"
Kelly criterion methods.
the kelly criterion helps with the decision of how much one should invest in
a asset as long as you know the odds and expected return of said asset.
simplified(win_p, rr)
simplified version of the kelly criterion formula.
Parameters:
win_p : float, probability of winning.
rr : float, reward to risk rate.
Returns: float, optimal fraction to risk.
usage:
simplified(0.55, 1.0)
partial(win_p, loss_p, win_rr, loss_rr)
general form of the kelly criterion formula.
Parameters:
win_p : float, probability of the investment returns a positive outcome.
loss_p : float, probability of the investment returns a negative outcome.
win_rr : float, reward on a positive outcome.
loss_rr : float, reward on a negative outcome.
Returns: float, optimal fraction to risk.
usage:
partial(0.6, 0.4, 0.6, 0.1)
from_returns(returns)
Calculate the fraction to invest from a array of returns.
Parameters:
returns : array trade/asset/strategy returns.
Returns: float, optimal fraction to risk.
usage:
from_returns(array.from(0.1,0.2,0.1,-0.1,-0.05,0.05))
final_f(fraction, max_expected_loss)
Final fraction, eg. if fraction is 0.2 and expected max loss is 10%
then you should size your position as 0.2/0.1=2 (leverage, 200% position size).
Parameters:
fraction : float, aproximate percent fraction invested.
max_expected_loss : float, maximum expected percent on a loss (ex 10% = 0.1).
Returns: float, final fraction to invest.
usage:
final_f(0.2, 0.5)
hpr(fraction, trade, biggest_loss)
Holding Period Return function
Parameters:
fraction : float, aproximate percent fraction invested.
trade : float, profit or loss in a trade.
biggest_loss : float, value of the biggest loss on record.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
hpr(fraction=0.05, trade=0.1, biggest_loss=-0.2)
twr(returns, rr, eps)
Terminal Wealth Relative, returns a multiplier that can be applied
to the initial capital that leadds to the final balance.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, optimal fraction to invest.
usage:
twr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
ghpr(returns, rr, eps)
Geometric mean Holding Period Return, represents the average multiple made on the stake.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
ghpr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
run_coin_simulation(fraction, initial_capital, n_series, n_periods)
run multiple coin flipping (binary outcome) simulations.
Parameters:
fraction : float, fraction of capital to bet.
initial_capital : float, capital at the start of simulation.
n_series : int , number of simulation series.
n_periods : int , number of periods in each simulation series.
Returns: matrix(n_series, n_periods), matrix with simulation results per row.
usage:
run_coin_simulation(fraction=0.1)
run_asset_simulation(returns, fraction, initial_capital)
run a simulation over provided returns.
Parameters:
returns : array, trade, asset or strategy percent returns.
fraction : float , fraction of capital to bet.
initial_capital : float , capital at the start of simulation.
Returns: array, array with simulation results.
usage:
run_asset_simulation(returns=array.from(0.1,-0.2,0.-3,0.4), fraction=0.1)
strategy_win_probability()
calculate strategy() current probability of positive outcome in a trade.
strategy_avg_won()
calculate strategy() current average won on a trade with positive outcome.
strategy_avg_loss()
calculate strategy() current average lost on a trade with negative outcome.
FLEX KDJ INDHi Dears!
Here you have this ability to define different methods to aquire high and low bonds in KDJ indicator.
Thses Topologies are available in Popup menu and could be defined by user:
- "AVG" : Use average of cashed data in both High and low Bond
- "MEDIAN" : Use median of cashed data in both High and low Bond
- "MAX" : Use Max of cashed data in both High and low Bond
- "MIN" : Use Min of cashed data in both High and low Bond
- "WIDE" : Use Max of cashed data in High and Min of them for low Bond
- "NARROW" : Use Min of cashed data in High and Max of them for low Bond
- "FIX" : Use predefined constant values by user in 'Max BOND' and 'Min BOND'
- "GAUSS" Use statistical standard deviation method and 'Mult. Max BOND' and 'Mult. Min BOND' to calculate High and low Bond.
In "LEFT RANGE" and "RIGHT RANGE" you can define the range which be used to find pivot and extremum points in calculation of highest and lowest LONG-TERM KDJ Line.
'MEMORY' is the size of cash that you want to collect the extracted data from extreimum points for highest and lowest LONG-TERM-KDJ. If overflowing from this point the oldest value would be kicked from cash.
Other parts are same in KDJ Indicators.
Enjoy trading!
Shakib.
Market Sessions(4sessions)Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM))) Special for CLUB SM)))
Historical US Bond Yield CurvePreface: I'm just the bartender serving today's freshly blended concoction; I'd like to send a massive THANK YOU to all the coders and PineWizards for the locally-sourced ingredients. I am simply a code editor, not a code author. Many thanks to these original authors!
Source 1 (Aug 8, 2019):
Source 2 (Aug 11, 2019):
About the Indicator: The term yield curve refers to the yields of U.S. treasury bills, notes, and bonds in order from shortest to longest maturity date. The yield curve describes the shapes of the term structures of interest rates and their respective terms to maturity in years. The slope of the yield curve tells us how the bond market expects short-term interest rates to move in the future based on bond traders' expectations about economic activity and inflation. The best use of the yield curve is to get a sense of the economy's direction rather than to try to make an exact prediction. This indicator plots the U.S. yield curve as maturity (x-axis/time) vs yield (y-axis/price) in addition to historical yield curves and advanced data tickers . The visual array of historical yield curves helps investors visualize shifts in the yield curve that are useful when identifying & forecasting economic conditions. The bond market can help predict the direction of the economy which can be useful in crafting your investment strategy. An inverted 10y/2y yield curve for durations longer than 5 consecutive trading days signals an almost certain recession on the horizon. An inversion happens when short-term bonds pay better than longer-term bonds. There is Federal Reserve Board data that suggests the 10y3m may be a better predictor of recessions.
Features: Advanced dual data ticker that performs curve & important spread analysis, plus additional hover info. Advanced yield curve data labels with additional hover info. Customizable historical curves and color theme.
‼ IMPORTANT: Hover over labels/tables for advanced information. Chart asset and timeframe may affect the yield curve results; I have found consistently accurate results using BINANCE:BTCUSDT on 1d timeframe. Historical curve lookbacks will have an effect on whether the curve analysis says the curve is bull/bear steepening/flattening, so please use appropriate lookbacks.
⚠ DISCLAIMER: Not financial advice. Not a trading system. DYOR. I am not affiliated with the original authors, TradingView, Binance, or the Federal Reserve Board.
About the Editor: I am a former FINRA Registered Representative, inventor/patent holder, futures trader, and hobby PineScripter.
Month/Month Percentage % Change, Historical; Seasonal TendencyTable of monthly % changes in Average Price over the last 10 years (or the 10 yrs prior to input year).
Useful for gauging seasonal tendencies of an asset; backtesting monthly volatility and bullish/bearish tendency.
~~User Inputs~~
Choose measure of average: sma(close), sma(ohlc4), vwap(close), vwma(close).
Show last 10yrs, with 10yr average % change, or to just show single year.
Chose input year; with the indicator auto calculating the prior 10 years.
Choose color for labels and size for labels; choose +Ve value color and -Ve value color.
Set 'Daily bars in month': 21 for Forex/Commodities/Indices; 30 for Crypto.
Set precision: decimal places
~~notes~~
-designed for use on Daily timeframe (tradingview is buggy on monthly timeframe calculations, and less precise on weekly timeframe calculations).
-where Current month of year has not occurred yet, will print 9yr average.
-calculates the average change of displayed month compared to the previous month: i.e. Jan22 value represents whole of Jan22 compared to whole of Dec21.
-table displays on the chart over the input year; so for ES, with 2010 selected; shows values from 2001-2010, displaying across 2010-2011 on the chart.
-plots on seperate right hand side scale, so can be shrunk and dragged vertically.
-thanks to @gabx11 for the suggestion which inspired me to write this
.srb suite vol & infoThe volume indicator
what can replace the built-in volume indicator and It also has some useful features.
and designed to work as overlay in the same pane with open-source indicator by default.
Regular volume Indicator
Volume SMA plot
Large Volume ! emphasize by color & mark.
Ultra Volume ! overlay marking ; x2 x4 x6 lager than regular average volume. it will help you can take the reversal
BTC-agg. Volume
4 BTC-spot & 4 BTC-PERP volume aggregated.
It might helps you don't miss out on important volume flows.
Weighted to spot trading volume when using PERP+spot volume.
If enabled, BTC-agg.Vol automatically applied when selecting BTC-pair.
Information panel (optimized for crypto-currency)
BTC-PERP price & delta (when Binance:BTCUSDT selected)
BTC dominance, Binance:BTCUSDTPERP OI
Symbol, Price, Daily up/down
ATR14 (for checking current volatility)
Recommended setup for .srb suite
tradingview | chart setting > Appearance > Top margin 0%, Bottom margin 0% for optimized screen usage
tradingview | chart setting > Appearance > Right margin 57
.srb suite vol & info --> Visual Order > Bring to Front
.srb suite vol & info --> Pin to scale > No scale (Full-screen)