RSI Impact Heat Map [Trendoscope]Here is a simple tool to measure and display outcome of certain RSI event over heat map.
🎲 Process
🎯Event
Event can be either Crossover or Crossunder of RSI on certain value.
🎯Measuring Impact
Impact of the event after N number of bars is measured in terms of highest and lowest displacement from the last close price. Impact can be collected as either number of times of ATR or percentage of price. Impact for each trigger is recorded separately and stored in array of custom type.
🎯Plotting Heat Map
Heat map is displayed using pine tables. Users can select heat map size - which can vary from 10 to 90. Selecting optimal size is important in order to get right interpretation of data. Having higher number of cells can give more granular data. But, chart may not fit into the window. Having lower size means, stats are combined together to get less granular data which may not give right picture of the results. Default value for size is 50 - meaning data is displayed in 51X51 cells.
Range of the heat map is adjusted automatically based on min and max value of the displacement. In order to filter out or merge extreme values, range is calculated based on certain percentile of the values. This will avoid displaying lots of empty cells which can obscure the actual impact.
🎲 Settings
Settings allow users to define their event, impact duration and reference, and few display related properties. The description of these parameters are as below:
🎲 Use Cases
In this script, we have taken RSI as an example to measure impact. But, we can do this for any event. This can be price crossing over/under upper/lower bollinger bands, moving average crossovers or even complex entry or exit conditions. Overall, we can use this to plot and evaluate our trade criteria.
🎲 Interpretation
Q1 - If more coloured dots appear on the top right corner of the table, then the event is considered to trigger high volatility and high risk environment.
Q2 - If more coloured dots appear on the top left corner, then the events are considered to trigger bearish environment.
Q3 - If more coloured dots appear on the bottom left corner of the chart, then the events are considered insignificant as they neither generate higher displacement in positive or negative side. You can further alter outlier percentage to reduce the bracket and hence have higher distribution move towards
Q4 - If more coloured dots appear on the bottom right corner, then the events are considered to trigger bullish environment.
Will also look forward to implement this as library so that any conditions or events can be plugged into it.
Statistics
Historical Federal Fund Futures CurveUse this indicator to plot the federal funds futures implied rates term structure against historical curves
Based upon the work of @BarefootJoey, @longfiat, @OpptionsOnly
BTC / DXY, BTC / US10Y
The combination of the DXY and US02Y can be used to gauge market sentiment and assess the state of the global economy.
When the DXY is rising, it indicates that the U.S. dollar is strengthening relative to other currencies, which can lead to increased risk aversion among investors as the U.S. dollar is often seen as a safe-haven currency.
When the US02Y is rising, it suggests that market expectations for future inflation and interest rate increases are increasing, which can lead to a decrease in the value of riskier assets such as stocks.
In general, the combination of the DXY and US02Y can provide important information on the direction of global market trends and the state of the economy, and as such, they are important indicators to consider when making investment decisions.
RISK MANAGEMENTHi dear Traders,
Here I would present you my 'Risk Management' tool which is based on your buy orders, trading fees and your desired benefit.
Easily, fulfill the price and volume of each entries. Add to this, you can prepare the info about your next proposed entries, just let them not check at first and by meeting the prices then active the check-box beside it.
Two line will be presented on your candle-plot, one of the indicate the place that without any lose/win you can exit and also the desired exit position by considering user defined benefit.
Use it for free but please do not forget to boost the script.
Best regards and happy trading.
Shakib
SFC Smart Money - VolatilityIn statistics, a normal distribution is a type of continuous probability distribution for a real-valued random variable. Normal distributions are important in statistics and are often used in the natural and social sciences to represent real-valued random variables whose distributions are not known.
The indicator provide a deep statistic for the specified period. It calculate the normal distribution of all candles in the particular period, in order to measure the volatility and the probabilities. Also it separate bull from bear candles and calculate the normal distribution of each group. The calculations are mode based on open-open data and high-low data.
Volatility
Volatility is a statistical measure of the dispersion of returns for a given security or market index. In most cases, the higher the volatility , the riskier the security. Volatility is often measured from either the standard deviation or variance between returns from that same security or market index.
Volatility often refers to the amount of uncertainty or risk related to the size of changes in a security's value. A higher volatility means that a security's value can potentially be spread out over a larger range of values. This means that the price of the security can change dramatically over a short time period in either direction. A lower volatility means that a security's value does not fluctuate dramatically, and tends to be more steady.
While variance captures the dispersion of returns around the mean of an asset in general, volatility is a measure of that variance bounded by a specific period of time. Thus, we can report daily volatility , weekly, monthly, or annualized volatility .
This statistic gives very accurate information how the price moved in the past and what are normal movements and spikes. From this information, a future actions can be taken.
For better understanding, all data is calculated in pips.
Features:
- Mean - Mean is the one we are most used to, i.e. the average.
- Median -Sometimes, the data set values can have a few values which are at the extreme ends, and this might cause the mean of the data set to portray an incorrect picture.
Thus, we use the median, which gives the middle value of the sorted data set.
- Mode - In a given dataset, the mode will be the number which is occurring the most.
- Max - Maximum volatility for a given range.
- Min - Minimum volatility for a given range.
- Standard Deviation - The standard deviation tells us how far the value deviates from the mean.
- Range - Range simply gives the difference between the min and max values of the data set.
- ATR - Average True Range measures volatility, taking into account any gaps in the price movement.
- Normal Distribution - The basic premise is that given a range of observations, it is found that most of the values center around the mean and within one standard deviation
away from the mean.
- Probability - probability of outcomes.
We all know that the banks and professional traders do not trade with charts, but with different statistical methods, math. models and macroeconomics. This statistical indicator shows one of these methods.
It is recommended to use the indicator on daily timeframe . It also works on other timeframes, for example 1H for intraday analysis.
For more information how the normal distribution works, please search in internet.
SFC Smart Money BenchmarkA benchmark is a standard or point of reference, which traders can use to measure something else.
This indicator is showing how correlated pairs are performing and what is the current correlation between them.
Features:
- Market performance - daily, weekly, monthly
- Sigma - volatility . It will be coloured in red, if the volatility is bigger than one standard deviation.
-Correlation - Positive correlation will be coloured in green if it is confirmed by the P-value, negative correlation in red.
-Confidence intervals
-Determination
Markets:
- Metal sector
- US Stock Indices
- Major USD Pairs
Market performance
The indicator is plotting a table with the current performance of the particular group, for example the metal sector and all correlated Gold pairs. The table is showing the performance of the pairs based on monthly, weekly and daily bases in the same time. In this case the trader can track all pairs simultaneously and see if there are anomalies between the pairs - SMT Divergence.
For example:
We know that Gold and Silver are very strong correlated pairs. In this case if Gold is going up, but Silver not, probably this move is only current manipulation and the true move is not clear. In that moment the trader can decide not to open an order or take some profit.
With the Sigma value traders also can track the current volatility of the price. The strength of the volatility is measured by the standard deviation.
-1>Sigma<1 - The asset is moving normally
-2>Sigma<-1 or 21 - The asset is volatile
-3>Sigma<-2 or 32 - The asset is very volatile
Correlation
The indicator is showing the current correlation between all pair from the table. The correlation is set to the first pair of the table. In order to make the correlation more accurate the indicator calculates the P-value and the Determination coefficient. The confidence intervals are also displayed in order to show how strong correlation should be expected.
Pearson correlation is a measure of linear correlation between two sets of data. It is the ratio between the covariance of two variables and the product of their standard deviations; thus, it is essentially a normalized measurement of the covariance, such that the result always has a value between −1 and 1. As with covariance itself, the measure can only reflect a linear correlation of variables, and ignores many other types of relationships or correlations.
P-value evaluates how well your data rejects the null hypothesis, which states that there is no relationship between two compared groups. Successfully rejecting this hypothesis tells you that your results may be statistically significant. In academic research, p-value is defined as the probability of obtaining results ‘as extreme’ or ‘more extreme’, given that the null hypothesis is true — essentially, how likely it is that you would receive the results (or more dramatic results) you did assuming that there is no correlation or relationship (e.g. the thing that you’re testing) among the subjects
Coefficient of Determination is just the square of pearson’s correlation coefficient R. This is done as it is easier to explain linear regression in terms of R² than R. As R ranges from -1 to 1, R² would range from 0 to 1 — clearly explaining relationship with 0 being not related and 1 being perfectly related.
The correlation confidence interval is the range in which the population correlation is most likely to be found.
The degree of certainty for which it is likely to be within that range is called the confidence level.
When you collect sample data, you can not know the exact value of the correlation.
Note:
For the Stock indices there is an extra calculation, showing the current market expectations - Fear and Greed Index. The calculated index could differs a bit from the original CNN Fear and Greed indicator, because they calculate the index based on Future markets. This indicator calculate the index based on the market that we trade - indices.
Supported pairs:
-Option Gold - XAUUSD , GDX , Silver , Aluminum, Platinum , Palladium, 30Y US Yields, 10Y US Yields, 2Y US Yields, XAUEUR, XAUGBP, XAUAUD , XAUCAD , XAUCNY , XAUJPY
-Option Others - Table1: SP500 , US30, NAS100 ; Table2: DXY , EURUSD , GBPUSD , AUDUSD
Challenge training (journal)Dynamic trading journal with equity curve display. Detailed results with prop firm objectives, editable, $/month estimation, possibility to compare two strategies.
one line in parameter = one trading day. 20 days max.
For each trading day, specify : The number of trades, the number of SL, the number of total winning RR.
A table at the bottom right summarizes the days and performances during the backtest in order to have an idea of the current performance.
The bottom left table summarizes the overall performance with some key information.
Depending on the number of days traded, a monthly "salary" is deducted, taking into account the prop firm commission.
there is the possibility to define a "Type" for each trading day, 1 or 2. It allows to compare in a binary way, example for type 1: when the high time frame structure is doing well and I am confident for scalping, otherwise type 2.
Again: type 1: SL shorter by 50%, type 2: normal SL etc..
the button "separate 1 and 2" allows to display two additional equity curves : type 1 and type 2. It allows to have a quick visual comparison on the impact of our parameter studied in our backtest on our performance. at the scale of the main equity curve
All the conditions to succeed in the challenge are adjustable in the parameters. The drawdown calculation has been simplified - in order not to have to put 80 trades in the parameters window, I have gathered them by "day", and pessimistically, we consider first the stoplosses and then the take profits, simplifying the performances of the day into "one losing trade" and "one winning trade" (graphically). It is a good compromise between quantity and quality.
Use "A random day trading" indicator to spice up your training.
I hope this will be useful for you to track your performance !
Liquidation_linesLibrary "Liquidationline"
f_calculateLeverage(_leverage, _maintainance, _value, _direction)
Parameters:
_leverage
_maintainance
_value
_direction
f_liqline_update(_Liqui_Line, _killonlowhigh)
Parameters:
_Liqui_Line
_killonlowhigh
f_liqline_draw(_Liqui_Line, _priceorliq)
Parameters:
_Liqui_Line
_priceorliq
f_liqline_add(_Liqui_Line, linetoadd, _limit)
Parameters:
_Liqui_Line
linetoadd
_limit
Liquidationline
Fields:
creationtime
stoptime
price
leverage
maintainance
line_active
line_color
line_thickness
line_style
line_direction
line_finished
text_active
text_size
text_color
this library can draw typical liquidation lines, which can be called e.g. by indicator signals
You can see the default implementation in the lower part of the code, starting with RUNTIME
Don't forget to increase max lines to 500 in your script.
It can look like this screenshot here, with only minor changes to your executing script.
The base is the same
Global LiquidityPlots the sum of the balance sheets of the world's major central banks - FED, ECB, BoE, PBoC, BOJ, India and Switzerland - in a currency of your choice. Defaults to USD.
Also shows FED net liquidity (balance sheet - tga - rrp) for comparison. Uses a configurable multiplier to make the two lines viewable on the same price scale.
Median Momentum OscillatorWhat is Median Momentum Oscillator?
MedianMomentum Oscillator have bring the concept of Donchian Channels to create an band of price where Upper band is. the value of highest HIGH and Lower band is the lowest Value of LOW and then calculate the percent of Target Price to the range of Upper band and Lower Band then making its display in the term of oscillator which compare its change to last bar change.
Median Momentum Oscillator can be use as Confirmation Indicator while we design Trading strategy.
Green Background can be define as Buy signal : can be happen when White line cross Blue line Down
Red Background can be define as Buy signal : can be happen when White line cross Yellow line Up
Blue line can be use as support Line, we are expected white line to cross yellow line up in other to change its trend to be upward.
Yellow line can be use as resistance Line, we are expected white line to cross blue line up in other to change its trend to be downward.
What made Median Momentum Oscillator?
- Donchian Channels
- MA Concept
Use of Median Momentum Oscillator
- can be use as the confirmation indicator if trader apply the indicator to any trading strategy which already have trend identifier Indicator.
- can also be use as trend changer/switcher indicator.
DistributionsLibrary "Distributions"
Library with price distribution zones calculation helpers.
Based on research from "Trading Systems and Methods, 5th Edition" by Perry J. Kaufman
getZones(h, l, c, window)
Returns price distribution zones based on HLC and for some period
Parameters:
h : high price
l : low price
c : close price
window : period to calculate distributions
Returns: tuple of 5 price zones in descent order, from highest to lowest
Balance of Force Day of the Week (BOFDW)The script is a custom technical indicator for TradingView that is based on an analysis of the price movements of a financial instrument over the course of a week. The indicator uses a variety of inputs, including the open and close prices for each day of the week, to determine the "BOF" (BOF) for each day.
The BOF is calculated based on the relative magnitude of bullish and bearish price movements and is then used to determine the average BOF over a moving window of data points. This average BOF is displayed on the chart as an overlay, providing a measure of the average bullishness or bearishness of the financial instrument over the course of a week.
The indicator also allows users to specify the location of the overlay on the chart and to customize the appearance of the overlay with options for text and box colors. The script provides a number of built-in options for chart position, including the top-left, top-middle, top-right, middle-left, middle-center, middle-right, bottom-left, bottom-middle, and bottom-right corners of the chart.
Overall, this custom technical indicator is a useful tool for traders and investors who are looking to gain a deeper understanding of the price trends of a financial instrument over the course of a week. By providing a clear and concise measure of the average POF over time, the indicator can help users identify key patterns in the market and make more informed trading decisions.
PerformanceTableLibrary "PerformanceTable"
TODO: add library description here
This library was created as a library because adding a performance table to an existing strategy script made the strategy script lengthy and inconvenient to manage.
The monthly table script referenced @QuantNomad's code.
The performance table script referenced @myncrypto's code.
To use, copy and paste the code below at the bottom of the strategy script you are using, and the table for strategy performance will be displayed on a chart.
//------------Copy & Paste --------------------------------------//
import Cube_Lee/PerformanceTable/1 as PT
PT = input.bool(true, "Show Performance Table", tooltip = "전략의 성과를 우측상단에 테이블로 표시합니다.", group = "Performance Table")
MT = input.bool(true, "Show Monthly Table", tooltip = "전략의 월별 수익률을 우측하단에 테이블로 표시합니다.", group = "Performance Table")
if PT
PT.PerformanceTable()
if MT
PT.MonthlyTable()
//------------Copy & Paste---------------------------------------//
PerformanceTable()
MonthlyTable()
TemelWith this indicator, you can follow the basic ratios of stocks after the balance sheet periods.
This indicator , make it easier for a quick glance of overall company financial health without switching tabs for every single stocks.
Gösterilen Finansal Veriler. (data shown)
* Satışlar ve Net Kar (Revenue & PAT (Profit after Tax)
* Net Kar Marjı (Net Profit Margin (%))
* Brüt Kar Marjı (Gross Profit Margin (%))
* Hisse Başına Kar (Earnings Per Share)
* Özkaynak Karlılığı (RETURN ON EQUITY)
* Aktif Karlılık (RETURN ON ASSETS)
* FAVÖK Marjı (EBITDA MARGIN)
* Temettü Verimi (DIVIDENDS YIELD)
* F/K
* PD/DD (BOOK VALUE PER SHARE)
* PEG Rasyosu
* ROIC (RETURN ON INVESTED CAPITAL)
* Cari Oran (QUICK RATIO)
Toggle between Quarter/Annual Financial Data
The accuracy of the data subject to Tradingview's source, but from my observation it's accurate 95% of the time
(Verilerin doğruluğu Tradingview'in kaynağına tabidir, ancak benim gözlemime göre, zamanın %95'i doğrudur.)
Recently published data might not be available immediately
(Yakın zamanda yayınlanan veriler hemen mevcut olmayabilir.)
Past performance is not an indicator of future results.
My opinions and research are my own and do not constitute financial advice in any way whatsoever.
Nothing published by me constitutes an investment recommendation, nor should any data or Content published by me be relied upon for any investment/trading activities.
I strongly recommends that you perform your own independent research and/or speak with a qualified investment professional before making any financial decisions.
(Geçmiş performans gelecekteki sonuçların bir göstergesi değildir.
Görüş ve araştırmalarım bana aittir ve hiçbir şekilde finansal tavsiye niteliği taşımaz.
Tarafımdan yayınlanan hiçbir şey bir yatırım tavsiyesi teşkil etmez ve yayınladığım hiçbir veri veya İçeriğe herhangi bir yatırım/ticaret faaliyeti için güvenilmemelidir.
Herhangi bir finansal karar vermeden önce kendi bağımsız araştırmanızı yapmanızı ve/veya kalifiye bir yatırım uzmanıyla konuşmanızı şiddetle tavsiye ederim.)
VIX OscillatorThis is my VIX Oscillator indicator.
About it:
This indicator takes the Z-Score of the VIX and of the current ticker you are on and presents them in the format of an oscillator.
Key parts of the indicator:
A diagram of the key elements of the indicator are displayed above.
Purple Line: Represents the Z-Score of the current Ticker.
Blue Line: Represents the Z-Score of the VIX
Green fill line: Represents bullish divergence
Red fill line: Represents bearish divergence
How to use it:
Characteristics for long entries:
- Look for recent bullish divergence (green fill line)
- Look for the ticker line (purple line) to be holding above 0 (neutrality)
- look for a bullish cross (purple line (ticker) crossing over blue line (VIX))
Characteristics for short entries:
- Look for recent Bearish divergence
- Look for the VIX line (blue line) to be holding above 0 and the Ticker
- Look for the ticker line to be holding below 0
- Look for a bearish cross (blue crossing above purple)
Some principles:
The bands represent oversold, overbought and neutral.
0 is absolute neutrality. No bias here.
Anything towards + 2.5 is considered normal, moving towards overbought (2.5 or higher).
Anything towards -2.5 is considered normal, moving towards oversold (-2.5 or lower).
+2.5 or higher is overbought.
-2.5 or lower is oversold.
As always, I have prepared a quick tutorial video for your reference of this indicator:
Please let me know your questions, comments or suggestions about this indicator below.
Thank you for checking it out!
Delta Ladder [Kioseff Trading]Hello!
This script presents volume delta data in various forms!
Features
Classic mode: Volume delta boxes oriented to the right of the bar (sell closer / buy further)
On Bar mode: Volume delta boxes oriented on the bar (sell left / buy right)
Pure Ladder mode: Pure volume delta ladder
PoC highlighting
Color-coordinated delta boxes. Marginal volume differences are substantially shaded while large volume differences are lightly shaded.
Volume delta boxes can be merged and delta values removed to generate a color-only canvas reflecting vol. delta differences in price blocks.
Price bars can be split up to 497 times - allowing for greater precision.
Total volume delta for the bar and timestamp included
The image above shows Classic mode - delta blocks are oriented left/right contingent on positive/negative values!
The image above shows the same price sequence; however, delta blocks are superimposed on the price bar. Left-side blocks reflect negative delta while right-side blocks reflect positive delta! To apply this display method - select "On Bar" for the "Data Display Method" setting!
The image above shows "Pure Ladder" mode. Delta blocks remain color-coordinated; however, all delta blocks retain the same x-axis as the price bar they were calculated for!
Additionally, you can select to remove the delta values and merge the delta boxes to generate a color-based canvas indicative of volume delta at traded price levels!
The image above shows the same price sequence; however, the "Volume Assumption" setting is activated.
When active, the indicator assumes a 60/ 40 split when a level is traded at and only one metric - "buy volume" or "sell volume" is recorded. This means there shouldn't be any levels recorded where "buy volume" is greater than 0 and "sell volume" equals 0 and vice versa. While this assumption was performed arbitrarily, it may help better replicate volume delta and OI delta calculations seen on other charting platforms.
This option is configurable; you can select to have the script not assume a 60/ 40 split and instead record volume "as is" at the corresponding price level!
I plan to roll out additional features for the indicator - particularly tick-based price blocks! Stay tuned (:
Thank you!
Triangulation : Statistically Approved ReversalsA lot of calculation, but a simple and effective result displayed on the chart.
It automatically identifies a very favorable period for a price reversal, by analyzing the daily and intraday price action statistics from the maximum of the most recent bars from the historical data. No repainting. Alerts can be set.
The statistical study is done in real time for each instrument. The probabilities therefore vary over time and adapt to the latest information collected by the indicator.
The time range of the data study can be changed by simply changing the UT :
- 30m = 3.5 last months feed statistics
- 15m = 52 last days feed statistics
- 5m = 17 last days feed statistics (recommanded)
HOW TO USE
This indicator informs when we are in a time period strongly favorable to reversal.
==> Crossing probabilities of different kinds, in price and in time => Triangulation of top and bottom !
HOW It WORK :
fractal statistics on high and low formation.
hour's probabilities of making the high/low of the day are crossed with day's probabilities of making the high/low of the week.
First for the day, we study:
- value of the probability compared to the average probabilities
- value of the coefficient between the high probability and the low probability
which we then refine for the hour, with the same calculation.
Result: bright color for a day + hour with high probability, weak color if the probability is low but remains the only possible bias. Between these two possibilities, intermediate colors are possible - just like looking for shorts if the day is bullish, if it is a high probability hour!
This color is displayed in the background, only if we are forming the high of the day for tops, and the low of the day for bottoms - detected with a stochastic.
All probabilities are studied in real time for the current asset.
We will call this signal "killstats", for "killzones statistics"
fractal statistics on the probability of closure under specific predefined levels according to 36 cycles.
the probabilities of several cycles are studied, for example:
NY session versus London and Asian sessions, London session compared to its opening, NY session compared to its opening, "algorithmic cycles" ( 1h30), Opening of NY compared to its intersection with London..
Each cycle producing a probability of closing with respect to the opening price of each period. The periods are : (Etc/UTC)
15-18h / 15-16h / 9-13h / 14-17h / 18-22h / 10-12h / 9-10h30 / 10h30-12h / 12-13h30 / 13h30-15h / 15h-16h30 / 16h30-18h
The cycles can be superimposed, which allows to support or attenuate a signal for the key periods of the day: 9am-12pm, and 3pm-6pm. The period of the day covered by the study of cycles is 9h-22h.
Result : ==> a straight line with a half bell. Colors = almost transparent for 53% probability (low), and very intense for a high probability (75%). The line displayed corresponds to the opening price, which we are supposed to close within the time limit - before the end of the period, where the line stops.
If the price goes in the opposite direction to the one predicted by the statistics, then a background connects the price to the close level to be respected.
if direction and close is respected, nothing is displayed : there is no opportunity, no divergence between statistics and actual price moves.
By unchecking the "light mode", you can see each close level displayed on the chart, with the corresponding probability and the number of times the cycle was detected. The color varies from intense for a high probability (75%), to light for a low probability (53%)
We will call this signal "cyclic anomalies"
By default, as shown in the indicator presentation image, the "intersection only" option is checked: only the intersection between 1) killstats and 2) cyclic anomalies is displayed. (filter +-30% of killstats signals)
MORE INFORMATIONS
/!\ : during a backtest, it is necessary to refresh the studied data to benefit from the real time signals, and for that you have to use the replay mode. if "Backtesting informations?"is checked, labels are displayed on the graph to warn of the % distortion of the signals. I recommend using the replay mode every 250 candles, and every 1000 candles for premium accounts, to have real signals.
- Alerts can be set for killzone, or intersections ( As in presentation picture)
- The ideal use is in m5. It can trigger several times a day, sometimes in opposite directions, and sometimes not trigger for several days.
- Premium account have 20k candles data, and not 5k => signals may vary depending on your tradingview subscription.
Reinforced RSI - The Quant Science This strategy was designed and written with the goal of showing and motivating the community how to integrate our 'Probabilities' module with their own script.
We have recreated one of the simplest strategies used by many traders. The strategy only trades long and uses the overbought and oversold levels on the RSI indicator.
We added stop losses and take profits to offer more dynamism to the strategy. Then the 'Probabilities' module was integrated to create a probabilistic reinforcement on each trade.
Specifically, each trade is executed, only if the past probabilities of making a profitable trade is greater than or equal to 51%. This greatly increased the performance of the strategy by avoiding possible bad trades.
The backtesting was calculated on the NASDAQ:TSLA , on 15 minutes timeframe.
The strategy works on Tesla using the following parameters:
1. Lenght: 13
2. Oversold: 40
3. Overbought: 70
4. Lookback: 50
5. Take profit: 3%
6. Stop loss: 3%
Time period: January 2021 to date.
Our Probabilities Module, used in the strategy example:
Machine Learning: Lorentzian Classification█ OVERVIEW
A Lorentzian Distance Classifier (LDC) is a Machine Learning classification algorithm capable of categorizing historical data from a multi-dimensional feature space. This indicator demonstrates how Lorentzian Classification can also be used to predict the direction of future price movements when used as the distance metric for a novel implementation of an Approximate Nearest Neighbors (ANN) algorithm.
█ BACKGROUND
In physics, Lorentzian space is perhaps best known for its role in describing the curvature of space-time in Einstein's theory of General Relativity (2). Interestingly, however, this abstract concept from theoretical physics also has tangible real-world applications in trading.
Recently, it was hypothesized that Lorentzian space was also well-suited for analyzing time-series data (4), (5). This hypothesis has been supported by several empirical studies that demonstrate that Lorentzian distance is more robust to outliers and noise than the more commonly used Euclidean distance (1), (3), (6). Furthermore, Lorentzian distance was also shown to outperform dozens of other highly regarded distance metrics, including Manhattan distance, Bhattacharyya similarity, and Cosine similarity (1), (3). Outside of Dynamic Time Warping based approaches, which are unfortunately too computationally intensive for PineScript at this time, the Lorentzian Distance metric consistently scores the highest mean accuracy over a wide variety of time series data sets (1).
Euclidean distance is commonly used as the default distance metric for NN-based search algorithms, but it may not always be the best choice when dealing with financial market data. This is because financial market data can be significantly impacted by proximity to major world events such as FOMC Meetings and Black Swan events. This event-based distortion of market data can be framed as similar to the gravitational warping caused by a massive object on the space-time continuum. For financial markets, the analogous continuum that experiences warping can be referred to as "price-time".
Below is a side-by-side comparison of how neighborhoods of similar historical points appear in three-dimensional Euclidean Space and Lorentzian Space:
This figure demonstrates how Lorentzian space can better accommodate the warping of price-time since the Lorentzian distance function compresses the Euclidean neighborhood in such a way that the new neighborhood distribution in Lorentzian space tends to cluster around each of the major feature axes in addition to the origin itself. This means that, even though some nearest neighbors will be the same regardless of the distance metric used, Lorentzian space will also allow for the consideration of historical points that would otherwise never be considered with a Euclidean distance metric.
Intuitively, the advantage inherent in the Lorentzian distance metric makes sense. For example, it is logical that the price action that occurs in the hours after Chairman Powell finishes delivering a speech would resemble at least some of the previous times when he finished delivering a speech. This may be true regardless of other factors, such as whether or not the market was overbought or oversold at the time or if the macro conditions were more bullish or bearish overall. These historical reference points are extremely valuable for predictive models, yet the Euclidean distance metric would miss these neighbors entirely, often in favor of irrelevant data points from the day before the event. By using Lorentzian distance as a metric, the ML model is instead able to consider the warping of price-time caused by the event and, ultimately, transcend the temporal bias imposed on it by the time series.
For more information on the implementation details of the Approximate Nearest Neighbors (ANN) algorithm used in this indicator, please refer to the detailed comments in the source code.
█ HOW TO USE
Below is an explanatory breakdown of the different parts of this indicator as it appears in the interface:
Below is an explanation of the different settings for this indicator:
General Settings:
Source - This has a default value of "hlc3" and is used to control the input data source.
Neighbors Count - This has a default value of 8, a minimum value of 1, a maximum value of 100, and a step of 1. It is used to control the number of neighbors to consider.
Max Bars Back - This has a default value of 2000.
Feature Count - This has a default value of 5, a minimum value of 2, and a maximum value of 5. It controls the number of features to use for ML predictions.
Color Compression - This has a default value of 1, a minimum value of 1, and a maximum value of 10. It is used to control the compression factor for adjusting the intensity of the color scale.
Show Exits - This has a default value of false. It controls whether to show the exit threshold on the chart.
Use Dynamic Exits - This has a default value of false. It is used to control whether to attempt to let profits ride by dynamically adjusting the exit threshold based on kernel regression.
Feature Engineering Settings:
Note: The Feature Engineering section is for fine-tuning the features used for ML predictions. The default values are optimized for the 4H to 12H timeframes for most charts, but they should also work reasonably well for other timeframes. By default, the model can support features that accept two parameters (Parameter A and Parameter B, respectively). Even though there are only 4 features provided by default, the same feature with different settings counts as two separate features. If the feature only accepts one parameter, then the second parameter will default to EMA-based smoothing with a default value of 1. These features represent the most effective combination I have encountered in my testing, but additional features may be added as additional options in the future.
Feature 1 - This has a default value of "RSI" and options are: "RSI", "WT", "CCI", "ADX".
Feature 2 - This has a default value of "WT" and options are: "RSI", "WT", "CCI", "ADX".
Feature 3 - This has a default value of "CCI" and options are: "RSI", "WT", "CCI", "ADX".
Feature 4 - This has a default value of "ADX" and options are: "RSI", "WT", "CCI", "ADX".
Feature 5 - This has a default value of "RSI" and options are: "RSI", "WT", "CCI", "ADX".
Filters Settings:
Use Volatility Filter - This has a default value of true. It is used to control whether to use the volatility filter.
Use Regime Filter - This has a default value of true. It is used to control whether to use the trend detection filter.
Use ADX Filter - This has a default value of false. It is used to control whether to use the ADX filter.
Regime Threshold - This has a default value of -0.1, a minimum value of -10, a maximum value of 10, and a step of 0.1. It is used to control the Regime Detection filter for detecting Trending/Ranging markets.
ADX Threshold - This has a default value of 20, a minimum value of 0, a maximum value of 100, and a step of 1. It is used to control the threshold for detecting Trending/Ranging markets.
Kernel Regression Settings:
Trade with Kernel - This has a default value of true. It is used to control whether to trade with the kernel.
Show Kernel Estimate - This has a default value of true. It is used to control whether to show the kernel estimate.
Lookback Window - This has a default value of 8 and a minimum value of 3. It is used to control the number of bars used for the estimation. Recommended range: 3-50
Relative Weighting - This has a default value of 8 and a step size of 0.25. It is used to control the relative weighting of time frames. Recommended range: 0.25-25
Start Regression at Bar - This has a default value of 25. It is used to control the bar index on which to start regression. Recommended range: 0-25
Display Settings:
Show Bar Colors - This has a default value of true. It is used to control whether to show the bar colors.
Show Bar Prediction Values - This has a default value of true. It controls whether to show the ML model's evaluation of each bar as an integer.
Use ATR Offset - This has a default value of false. It controls whether to use the ATR offset instead of the bar prediction offset.
Bar Prediction Offset - This has a default value of 0 and a minimum value of 0. It is used to control the offset of the bar predictions as a percentage from the bar high or close.
Backtesting Settings:
Show Backtest Results - This has a default value of true. It is used to control whether to display the win rate of the given configuration.
█ WORKS CITED
(1) R. Giusti and G. E. A. P. A. Batista, "An Empirical Comparison of Dissimilarity Measures for Time Series Classification," 2013 Brazilian Conference on Intelligent Systems, Oct. 2013, DOI: 10.1109/bracis.2013.22.
(2) Y. Kerimbekov, H. Ş. Bilge, and H. H. Uğurlu, "The use of Lorentzian distance metric in classification problems," Pattern Recognition Letters, vol. 84, 170–176, Dec. 2016, DOI: 10.1016/j.patrec.2016.09.006.
(3) A. Bagnall, A. Bostrom, J. Large, and J. Lines, "The Great Time Series Classification Bake Off: An Experimental Evaluation of Recently Proposed Algorithms." ResearchGate, Feb. 04, 2016.
(4) H. Ş. Bilge, Yerzhan Kerimbekov, and Hasan Hüseyin Uğurlu, "A new classification method by using Lorentzian distance metric," ResearchGate, Sep. 02, 2015.
(5) Y. Kerimbekov and H. Şakir Bilge, "Lorentzian Distance Classifier for Multiple Features," Proceedings of the 6th International Conference on Pattern Recognition Applications and Methods, 2017, DOI: 10.5220/0006197004930501.
(6) V. Surya Prasath et al., "Effects of Distance Measure Choice on KNN Classifier Performance - A Review." .
█ ACKNOWLEDGEMENTS
@veryfid - For many invaluable insights, discussions, and advice that helped to shape this project.
@capissimo - For open sourcing his interesting ideas regarding various KNN implementations in PineScript, several of which helped inspire my original undertaking of this project.
@RikkiTavi - For many invaluable physics-related conversations and for his helping me develop a mechanism for visualizing various distance algorithms in 3D using JavaScript
@jlaurel - For invaluable literature recommendations that helped me to understand the underlying subject matter of this project.
@annutara - For help in beta-testing this indicator and for sharing many helpful ideas and insights early on in its development.
@jasontaylor7 - For helping to beta-test this indicator and for many helpful conversations that helped to shape my backtesting workflow
@meddymarkusvanhala - For helping to beta-test this indicator
@dlbnext - For incredibly detailed backtesting testing of this indicator and for sharing numerous ideas on how the user experience could be improved.
MLExtensionsLibrary "MLExtensions"
normalizeDeriv(src, quadraticMeanLength)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the first-order derivative for price).
quadraticMeanLength : The length of the quadratic mean (RMS).
Returns: nDeriv The normalized derivative of the input series.
normalize(src, min, max)
Rescales a source value with an unbounded range to a target range.
Parameters:
src : The input series
min : The minimum value of the unbounded range
max : The maximum value of the unbounded range
Returns: The normalized series
rescale(src, oldMin, oldMax, newMin, newMax)
Rescales a source value with a bounded range to anther bounded range
Parameters:
src : The input series
oldMin : The minimum value of the range to rescale from
oldMax : The maximum value of the range to rescale from
newMin : The minimum value of the range to rescale to
newMax : The maximum value of the range to rescale to
Returns: The rescaled series
color_green(prediction)
Assigns varying shades of the color green based on the KNN classification
Parameters:
prediction : Value (int|float) of the prediction
Returns: color
color_red(prediction)
Assigns varying shades of the color red based on the KNN classification
Parameters:
prediction : Value of the prediction
Returns: color
tanh(src)
Returns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
Parameters:
src : The input series (i.e., the normalized derivative).
Returns: tanh The hyperbolic tangent of the input series.
dualPoleFilter(src, lookback)
Returns the smoothed hyperbolic tangent of the input series.
Parameters:
src : The input series (i.e., the hyperbolic tangent).
lookback : The lookback window for the smoothing.
Returns: filter The smoothed hyperbolic tangent of the input series.
tanhTransform(src, smoothingFrequency, quadraticMeanLength)
Returns the tanh transform of the input series.
Parameters:
src : The input series (i.e., the result of the tanh calculation).
smoothingFrequency
quadraticMeanLength
Returns: signal The smoothed hyperbolic tangent transform of the input series.
n_rsi(src, n1, n2)
Returns the normalized RSI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the RSI calculation).
n1 : The length of the RSI.
n2 : The smoothing length of the RSI.
Returns: signal The normalized RSI.
n_cci(src, n1, n2)
Returns the normalized CCI ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the CCI calculation).
n1 : The length of the CCI.
n2 : The smoothing length of the CCI.
Returns: signal The normalized CCI.
n_wt(src, n1, n2)
Returns the normalized WaveTrend Classic series ideal for use in ML algorithms.
Parameters:
src : The input series (i.e., the result of the WaveTrend Classic calculation).
n1
n2
Returns: signal The normalized WaveTrend Classic series.
n_adx(highSrc, lowSrc, closeSrc, n1)
Returns the normalized ADX ideal for use in ML algorithms.
Parameters:
highSrc : The input series for the high price.
lowSrc : The input series for the low price.
closeSrc : The input series for the close price.
n1 : The length of the ADX.
regime_filter(src, threshold, useRegimeFilter)
Parameters:
src
threshold
useRegimeFilter
filter_adx(src, length, adxThreshold, useAdxFilter)
filter_adx
Parameters:
src : The source series.
length : The length of the ADX.
adxThreshold : The ADX threshold.
useAdxFilter : Whether to use the ADX filter.
Returns: The ADX.
filter_volatility(minLength, maxLength, useVolatilityFilter)
filter_volatility
Parameters:
minLength : The minimum length of the ATR.
maxLength : The maximum length of the ATR.
useVolatilityFilter : Whether to use the volatility filter.
Returns: Boolean indicating whether or not to let the signal pass through the filter.
backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isStopLossHit, maxBarsBackIndex, thisBarIndex)
Performs a basic backtest using the specified parameters and conditions.
Parameters:
high : The input series for the high price.
low : The input series for the low price.
open : The input series for the open price.
startLongTrade : The series of conditions that indicate the start of a long trade.`
endLongTrade : The series of conditions that indicate the end of a long trade.
startShortTrade : The series of conditions that indicate the start of a short trade.
endShortTrade : The series of conditions that indicate the end of a short trade.
isStopLossHit : The stop loss hit indicator.
maxBarsBackIndex : The maximum number of bars to go back in the backtest.
thisBarIndex : The current bar index.
Returns: A tuple containing backtest values
init_table()
init_table()
Returns: tbl The backtest results.
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winrate, stopLosses)
update_table(tbl, tradeStats)
Parameters:
tbl : The backtest results table.
tradeStatsHeader : The trade stats header.
totalTrades : The total number of trades.
totalWins : The total number of wins.
totalLosses : The total number of losses.
winLossRatio : The win loss ratio.
winrate : The winrate.
stopLosses : The total number of stop losses.
Returns: Updated backtest results table.
USD Liquidity IndexThis USD Liquidity Index composed of 2 parts, total assets and major liabilities of the Federal Reserve .
There is a certain positive correlation between USD liquidity and risk asset price changes in history.
Suggested that USD Liquidity is mostly determined by the Federal Reserve balance (without leveraged), this index deducts three major liabilities from the total assets (in green color line) of the Federal Reserve . They are the currency in circulation (WCURCIR) in gold color, the Treasury General Account (WTREGEN) in blue color, the Reverse Repo (RRPONTSYD) in red color.
The grey line is the calculation result of the USD Liquidity Index. With it goes up, liquidity increases, vice versa.
iChi Masters Regular GoldSignalThis indicator is based on the Ichimoku code, and by combining the Ichimoku code with special source codes and improving the colors and signals that you can see on chart with information such as stop,target and leverage for your trades, we made the IMR indicator so that it is easier for traders to understand the Ichimoku strategy, I hope you enjoy it :)
The Buy and Sell labels on chart is based on ichimoku lines:
when the conversion and base line cross up each other and in distance of 9 candle the ichimoku cloud has green switch too,then we have a Buy label on chart and the opposite is for the Sell labels
This indicator has no backtest and you can only see the signals and the information of that
- The Risk% is the percentage of your risk on your balance so indicator gives you the proper leverage
- In Box Mode you can specify where your box should be drawn :
1 : Cr sets the box on conversion and base cross
2 : Perfect Cross sets the box on a cross which has no cross before until 26 candles
3 : Buy_Sell sets the box on Buy or Sell labels on chart
4 : Divergence Box sets the box on Divergence triangles on chart
-The C/S Distance is the distance between cross and switch for Buy and Sell labels
-The Long and Short check boxes is for showing you the information of Buy or Sell position such as stop,target and leverage.
-The Divergence section is based on ichimoku too:
In Lead divergence, we calculate the difference between lead 1 and lead 2, and a graph is formed from their difference, by comparing the obtained graph and the candles, we find the divergence between them, and they are displayed as green arrows on the chart,And in total, three types of divergence can be seen in the chart, R1, R2 and HD
In Base divergence, we calculate the difference between Conversion and Base, and a graph is formed from their difference, by comparing the obtained graph and the candles, we find the divergence between them, and they are displayed as white arrows on the chart,And in total, three types of divergence can be seen in the chart, R1, R2 and HD
-The Switch Filter means that our Lead Divergence and Base Divergence should be close to ichimoku cloud switch
-The All High means that for long arrow of Divergences The lowest price of the previous 26 candles should be equal to the lowest price of the previous 52 candles and the opposite for sell arrow of Divergence
-In the Ichi Elements section, you can choose the visible sections on the chart:
The Cloud tick is on the chart to see the Ichi Moko cloud
The Offset tick is to move the cloud to 26 candles ahead
The Conv tick is to see the Conversion line
The Base tick is on the indicator to see the Base line
The Chiko tick is there to see the Chiko Span line on the chart
Qline tick to see the Base line which has advanced 26 candles
Buy_Sell tick to see buy and sell labels
The Ready tick is used to see the label ready for buying and selling on the chart
The Cross tick is to see the moment of the cross between the conv line and Base
The PC tick is for seeing crosses that do not have a cross until the previous 26 candles
The FakeCloud tick is used to see clouds that contain less than 26 candles
-The Super Trend Goldsignal is a combination of two atr with numbers 1.6 and 0.8
The signals that are displayed on the chart are the points where both atr signaled at the same time.
-The HigherTimeFrame tick will show you Conv, Base and Lead lines multiplied by Multiply
-The C, B, and L boxes are used to specify the numbers of Conv, Base, and Lead lines, respectively
-The Conv Box tick is for plotting the highest price in 9 candles and the lowest price in 9 candles
-The Lead2 Box ticker is for drawing the highest price in 52 candles and the lowest price in 52 candles
-The Yellow Line tick 26-52 is to indicate the places where either the highest price of 52 candles and 26 candles were equal or their lowest prices.
-Purple Line ticked 52-26 is to specify the places where the highest price of 26 and 52 and the lowest price of 26 and 52 are equal.
-The Blue Line 26-9 tick is for specifying the places where the highest price of 26 and 9 and the lowest price of 26 and 9 are equal.
GAVAD - Selling after a Strong MovimentThis strategy search for a moment whe the market make two candles are consistently strong, and open a Sell, searching the imediactly correction, on the new candle. It`s easy to see the bars on the histogram graph. Purple Bars represent the candle variation. when on candle cross ove the Signal line the graph plot an Yellow ci, if the second bar crossover the signal a green circle is ploted and the operation start on start of the next candle.
This strategy can be used in a lot of Stocks and other graphs. many times we need a small time of graph, maybe 1 or 5 minutes because the gain shoud be planned to a midle of the second candle. You need look the stocks you will use.
Stocks > 100 dolars isnt great, markets extremly volatly not too. but, Stocks that have a consistently development are very interisting. Look to markets searching maybe 0.5% or 1%.
For this moment, I make the development of a Brasilian Real x American Dollar. In 15 Minutes.
if you use in small timeframe the results can be better.
On this time we make more than 500 trades with a small lot of contracts, without a big percent profitable, but a small profit in each operation, maybe you search more than. To present a real trading system I insert a spreed to present a correct view of the results.
Each stock, Index, or crypto there is a specific configuration?
my suggestion for new stocks
You need choice a stock and using the setup search set over than 70% gain (percent profitable), using a 1% of gain and loss between 1-2%
as the exemple (WDO)
default I prepare a Brazilian Index
6-signal (6% is variation of a candle of the last candle)
10000- multiplicator (its important to configure diferences betwen a stock and an Indice)
gain 3 (this proportion will be set looking you target, how I say, 1% can be good)
loss 8 (this proportion will be set with you bankroll management, how I say, maybe 2%, you need evaluate)
for maximize operations I use in the 1 or 5 minute graph. Timeframes more large make slowlly results,
(but not unable that you use in a 1 hour or a 1 day.)
I make this script by zero. Maybe the code doesnt so organized, but is very easy to understand. If you have any doubts . leave a comment.
I hope help you.