Liquidation Ranges + Volume/OI Dots [Kioseff Trading]Hello!
Introducing a multi-faceted indicator "Liquidation Ranges + Volume Dots" - this indicator replicates the volume dot tools found on various charting platforms and populates a liquidation range on crypto assets!
Features
Volume/OI dots populated according to user settings
Size of volume/OI dots corresponds to degree of abnormality
Naked level volume dots
Fixed range capabilities for volume/OI dots
Visible time range capabilities for volume/OI dots
Lower timeframe data used to discover iceberg orders (estimated using 1-minute data)
S/R lines drawn at high volume/OI areas
Liquidation ranges for crypto assets (10x - 100x)
Liquidation ranges are calculated using a popular crypto exchange's method
# of violations of liquidation ranges are recorded and presented in table
Pertinent high volume/OI price areas are recorded and presented in table
Personalized coloring for volume/OI dots
Net shorts / net long for the price range recorded
Lines shows reflecting net short & net long increases/decreases
Configurable volume/OI heatmap (displayed between liquidation ranges)
And some more (:
Liquidation Range
The liquidation range component of the indicator uses a popular crypto exchange's calculation (for liquidation ranges) to populate the chart for where 10x - 100x leverage orders are stopped out.
The image above depicts features corresponding to net shorts and net longs.
The image above shows features corresponding to liquidation zones for the underlying coin.
The image above shows the option to display volume/oi delta at the time the corresponding grid was traded at.
The image above shows an instance of using the "fixed range" feature for the script.
*The average price of the range is calculated to project liquidation zones.
*Heatmap is calculated using OI (or volume) delta.
Huge thank you to Pine Wizard @DonovanWall for his range filter code!
Price ranges are automatically detected using his calculation (:
Volume / OI Dots
Similar to other charting platforms, the volume/OI dots component of the indicator distinguishes "abnormal" changes in volume/OI; the detected price area is subsequently identified on the chart.
The detection method uses percent rank and calculates on the last bar of the chart. The "agelessness" of detection is contingent on user settings.
The image above shows volume dots in action; the size of each volume dot corresponds to the amount of volume at the price area.
Smaller dots = lower volume
Larger dots = higher volume
The image above exemplifies the highest aggression setting for volume/OI dot detection.
The table oriented top-right shows the highest volume areas (discovered on the 1-minute chart) for the calculated period.
The open interest change and corresponding price level are also shown. Results are listed in descending order but can also be listed in order of occurrence (most relevant).
Additionally, you can use the visible time range feature to detect volume dots.
The feature shows and explains how the visible range feature works. You select how many levels you want to detect and the script will detect the selected number of levels.
For instance, if I select to show 20 levels, the script will find the 20 highest volume/OI change price areas and distinguish them.
The image above shows a narrower price range.
The image above shows the same price range; however, the script is detecting the highest OI change price areas instead of volume.
* You can also set a fixed range with this feature
* Naked levels can be used
Additionally, you can select for the script to show only the highest volume/ OI change price area for each bar. When active, the script will successively identify the highest volume / OI change price area for the most recent bars.
Naked Levels
The image above shows and explains how naked levels can be detected when using the script.
And that's pretty much it!
Of course, there're a few more features you can check out when you use the script that haven't been explained here (:
Thank you again to @DonovanWall
Thank you to @Trendoscope for his binary insertion sort library (:
Thank you to @PineCoders for their time library
Thank you for checking this out!
Statistics
CC Trend strategy 2- Downtrend ShortTrend Strategy #2
Indicators:
1. EMA(s)
2. Fibonacci retracement with a mutable lookback period
Strategy:
1. Short Only
2. No preset Stop Loss/Take Profit
3. 0.01% commission
4. When in a profit and a closure above the 200ema, the position takes a profit.
5. The position is stopped When a closure over the (0.764) Fibonacci ratio occurs.
* NO IMMEDIATE RE-ENTRIES EVER!*
How to use it and what makes it unique:
This strategy will enter often and stop quickly. The goal with this strategy is to take losses often but catch the big move to the downside when it occurs through the Silvercross/Fibonacci combination. This is a unique strategy because it uses a programmed Fibonacci ratio that can be used within the strategy and on any program. You can manipulate the stats by changing the lookback period of the Fibonacci retracement and looking at different assets/timeframes.
This description tells the indicators combined to create a new strategy, with commissions and take profit/stop loss conditions included, and the process of strategy execution with a description of how to use it. If you have any questions feel free to PM me and boost if you found it helpful. Thank you, pineUSERS!
CHEATCODE1
High of Day Low of Day hourly timings: Statistics. Time of day %High of Day (HoD) & Low of Day (LoD) hourly timings: Statistics. Time of day % likelihood for high and low.
//Purpose:
To collect stats on the hourly occurrences of HoD and LoD in an asset, to see which times of day price is more likely to form its highest and lowest prices.
//How it works:
Each day, HoD and LoD are calculated and placed in hourly 'buckets' from 0-23. Frequencies and Percentages are then calculated and printed/tabulated based on the full asset history available.
//User Inputs:
-Timezone (default is New York); important to make sure this matches your chart's timezone
-Day start time: (default is Tradingview's standard). Toggle Custom input box to input your own custom day start time.
-Show/hide day-start vertical lines; show/hide previous day's 'HoD hour' label (default toggled on). To be used as visual aid for setting up & verifying timezone settings are correct and table is populating correctly).
-Use historical start date (default toggled off): Use this along with bar-replay to backtest specific periods in price (i.e. consolidated vs trending, dull vs volatile).
-Standard formatting options (text color/size, table position, etc).
-Option to show ONLY on hourly chart (default toggled off): since this indicator is of most use by far on the hourly chart (most history, max precision).
// Notes & Tips:
-Make sure Timezone settings match (input setting & chart timezone).
-Play around with custom input day start time. Choose a 'dead' time (overnight) so as to ensure stats are their most meaningful (if you set a day start time when price is likely to be volatile or trending, you may get a biased / misleadingly high readout for the start-of-day/ end-of-day hour, due to price's tendency for continuation through that time.
-If you find a time of day with significantly higher % and it falls either side of your day start time. Try adjusting day start time to 'isolate' this reading and thereby filter out potential 'continuation bias' from the stats.
-Custom input start hour may not match to your chart at first, but this is not a concern: simply increment/decrement your input until you get the desired start time line on the chart; assuming your timezone settings for chart and indicator are matching, all will then work properly as designed.
-Use the the lines and labels along with bar-replay to verify HoD/LoD hours are printing correctly and table is populating correctly.
-Hour 'buckets' represent the start of said hour. i.e. hour 14 would be populated if HoD or LoD formed between 14:00 and 15:00.
-Combined % is simply the average of HoD % and LoD %. So it is the % likelihood of 'extreme of day' occurring in that hour.
-Best results from using this on Hourly charts (sub-hourly => less history; above hourly => less precision).
-Note that lower tier Tradingview subscriptions will get less data history. Premium acounts get 20k bars history => circa 900 days history on hourly chart for ES1!
-Works nicely on Btc/Usd too: any 24hr assets this will give meaningful data (whereas some commodities, such as Lean Hogs which only trade 5hrs in a day, will yield less meaningful data).
Example usage on S&P (ES1! 1hr chart): manual day start time of 11pm; New York timezone; Visual aid lines and labels toggled on. HoD LoD hour timings with 920 days history:
AlexD Intraday market footprintThe indicator shows probability of a moving average non reversal at certain moment of day.
IMF_Predict line shows the probability of a reversal for the specified period.
moving average - period/2 shifted sma of typical price ( (close+high+low)/3 ).
Parameters:
Number of days - previous days to calculate the probability
SMA filter period - chart smoothing period
IMF smooth period - additional indicator smoothing after calculation
IMF predict period - period for calculating the probability of a reversal in the next N bars
Skip N hours in days(optimisation) - I recommend a half of the normal session time. Low values - long calculation time, High values - skipping days.
ATR_InfoWhat Is the Average True Range (ATR)?
The average true range (ATR) is a technical analysis indicator, introduced by market technician J. Welles Wilder Jr. in his book New Concepts in Technical Trading Systems, that measures market volatility by decomposing the entire range of an asset price for that period.
Each instrument per unit of time passes its average value of the true range, but there are moments when the volatility explodes or abruptly decays, these phenomena introduce large distortions into the average value of the true range.
The ATR_WPB function calculates the average value of the true range for the specified number of bars, while excluding paranormally large and paranormally small bars from the calculation of the average.
For example, if the instrument has passed a small ATR value, then it has many chances to continue moving, but if the instrument has passed its ATR value, then the chances of continuing to move are extremely low.
Library "ATR_Info"
ATR_Info: Calculates ATR without paranormal bars
ATR_WPB(source, period, psmall, pbig)
ATR_WPB: Calculates ATR without paranormal bars
Parameters:
source (float) : ATR_WPB: (series float) The sequence of data on the basis of which the ATP calculation will be made
period (int) : ATR_WPB: (int) Sequence size for ATR calculation
psmall (float) : ATR_WPB: (float) Coefficient for paranormally small bar
pbig (float) : ATR_WPB: (float) Coefficient for paranormally big bar
Returns: ATR_WPB: (float) ATR without paranormal bars
Stablecoins market capA simple indicator that displays either the aggregated market cap of the top five stablecoins, or it displays all coins at once (look in the settings).
Because of limitations with the sourced data the indicator only works on the daily timeframe or higher.
Risk to Reward - FIXED SL BacktesterDon't know how to code? No problem! TradingView is an excellent platform for you. ✅ ✅
If you have an indicator that you want to backtest using a risk-to-reward ratio or fixed take profit/stop loss levels, then the Risk to Reward - FIXED SL Backtester script is the perfect solution for you.
introducing Risk to Reward - FIXED SL Backtester Script which will allow you to test any indicator / Signal with RR or Fixed SL system
How does it work ?!
Once you connect the script to your indicator, it will analyze your entry points and perform calculations based on them. It will then open trades for you according to the specified inputs in the script settings.
HOW TO CONNECT IT to your indicator?
simply open your indicator code and add the below line of code to it
plot(Signal ? 100 : 0,"Signal",display = display.data_window)
Replace Signal with the long condition from your own indicator. You can also modify the value 100 to any number you prefer. After that, open the settings.
Once the script is connected to your indicator, you can choose from two options:
Risk To Reward Ratio System
Fixed TP/ SL System
🔸if you select the Risk to Reward System ⤵️
The Risk-to-Reward System requires the calculation of a stop loss. That's why I have included three different types of stop-loss calculations for you to choose from:
ATR Based SL
Pivot Low SL
VWAP Based SL
Your stop loss and take profit levels will be automatically calculated based on the selected stop loss method and your risk-to-reward ratio.
You can also adjust their values to match your desired risk level. The trades will be displayed on the chart.
with the ability to change their values to match your risk.
once this is done, trades will be displayed on the chart
🔸if you select the Fixed system ⤵️
You have 2 inputs, which are FIXED TP & Fixed SL
input the values you want, and trades will be on your chart...
I have also added a Breakeven feature for you.
with this Breakeven feature the trade will not just move SL to Entry ?! NO NO, it will place it above entry by a % you input yourself, so you always win! 🚀
Here is an example
Enjoy, and have fun, if you have any questions do not hesitate to ask
CE - Market Performance TableThe 𝓜𝓪𝓻𝓴𝓮𝓽 𝓟𝓮𝓻𝓯𝓸𝓻𝓶𝓪𝓷𝓬𝓮 𝓣𝓪𝓫𝓵𝓮 is a sophisticated market tool designed to provide valuable insights into the current market trends and the approximate current position in the Macroeconomic Regime.
Furthermore the 𝓜𝓪𝓻𝓴𝓮𝓽 𝓟𝓮𝓻𝓯𝓸𝓻𝓶𝓪𝓷𝓬𝓮 𝓣𝓪𝓫𝓵𝓮 provides the Correlation Implied Trend for the Asset on the Chart. Lastly it provides information about current "RISK ON" or "RISK OFF" periods.
Methodology:
𝓜𝓪𝓻𝓴𝓮𝓽 𝓟𝓮𝓻𝓯𝓸𝓻𝓶𝓪𝓷𝓬𝓮 𝓣𝓪𝓫𝓵𝓮 tracks the 15 underlying Stock ETF's to identify their performance and puts the combined performances together to visualize 42MACRO's GRID Equity Model.
For this it uses the below ETF's:
Dividends (SPHD)
Low Beta (SPLV)
Quality (QUAL)
Defensives (DEF)
Growth (IWF)
High Beta (SPHB)
Cyclicals (IYT, IWN)
Value (IWD)
Small Caps (IWM)
Mid Caps (IWR)
Mega Cap Growth (MGK)
Size (OEF)
Momentum (MTUM)
Large Caps (IWB)
Overall Settings:
The main time values you want to change are:
Correlation Length
- Defines the time horizon for the Correlation Table
ROC Period
- Defines the time horizon for the Performance Table
Normalization lookback
- Defines the time horizon for the Trend calculation of the ETF's
- For longer term Trends over weeks or months a length of 50 is usually pretty accurate
Visuals:
There is a variety of options to change the visual settings of what is being plotted and the two table positions and additional considerations.
Everything that is relevant in the underlying logic that can help comprehension can be visualized with these options.
Market Correlation:
The Market Correlation Table takes the Correlation of the above ETF's to the Asset on the Chart, it furthermore uses the Normalized KAMA Oscillator by IkkeOmar to analyse the current trend of every single ETF.
It then Implies a Correlation based on the Trend and the Correlation to give a probabilistically adjusted expectation for the future Chart Asset Movement. This is strengthened by taking the average of all Implied Trends.
With this the Correlation Table provides valuable insights about probabilistically likely Movement of the Asset, for Traders and Investors alike, over the defined time duration.
Market Performance:
𝓜𝓪𝓻𝓴𝓮𝓽 𝓟𝓮𝓻𝓯𝓸𝓻𝓶𝓪𝓷𝓬𝓮 𝓣𝓪𝓫𝓵𝓮 is the actual valuable part of this Indicator.
It provides valuable information about the current market environment (whether it's risk on or risk off), the rough GRID models from 42MACRO and the actual market performance.
This allows you to obtain a deeper understanding of how the market works and makes it simple to identify the actual market direction.
Utility:
The 𝓜𝓪𝓻𝓴𝓮𝓽 𝓟𝓮𝓻𝓯𝓸𝓻𝓶𝓪𝓷𝓬𝓮 𝓣𝓪𝓫𝓵𝓮 is divided in 4 Sections which are the GRID regimes:
Economic Growth:
Goldilocks
Reflation
Economic Contraction:
Inflation
Deflation
Top 5 Equity Style Factors:
Are the values green for a specific Column? If so then the market reflects the corresponding GRID behavior.
Bottom 5 Equity Style Factors:
Are the values red for a specific Column? If so then the market reflects the corresponding GRID behavior.
So if we have Goldilocks as current regime we would see green values in the Top 5 Goldilocks Cells and red values in the Bottom 5 Goldilocks Cells.
You will find that Reflation will look similar, as it is also a sign of Economic Growth.
Same is the case for the two Contraction regimes.
Webby's RSI 2.0Webby's RSI (Really Simple Indicator) 2.0 or version 5.150 as Mike himself calls it, builds upon the original Webby RSI by changing the way we measure extension from the 21-day exponential moving average.
Instead using the percentage of the low versus the 21-day exponential moving average, version 2 uses a multiple of the securities 50 day ATR (average true range) to determine the extension.
Version 2.0 also comes with some new additions, such as measuring the high vs 21-day exponential moving average when a security is below it, as well as an ATR extension from the 10-day simple moving average that Mike looks to as a guide to take partials.
Binary Option Strategy Tester with Martingale-Basic V.2In Binary options, strategy testing is a bit different. The strategy result depends upon expiry intervals and payout ratio.
My previous script was a try to resolve this but has some bugs in specific choices. The new version overcame those and added some new features useful for binary option strategy testing.
Assumption:
We are opening position at next candle after signal come
Chart interval is option expiry time.
We are taking the position at opening price
Our call will be profitable if we get a green candle and put will be profitable if we get a red candle
We can open only one trade at a time. So if we are in trade, subsequent signals will be ignored.
All Input Options:
Test Call/Put individually or both. Default BOTH
Select up to 5 Martingale levels. Default 2
Type of Martingale Trade. Default “SAME”
“SAME”: If you are trading CALL and incur a loss, you are taking CALL in subsequent Martingale levels.
“OPSITE”: if you are trading CALL and incur a loss, you are taking PUT in subsequent Martingale levels.
“FOLLOW CANDLE COLOR”: You are following candle color in Martingale levels, i.e if the loss candle is RED, you are taking PUT in subsequent candles.
“OPPOSITE CANDLE COLOR”: You are taking opposite candle color trade, i.e if the loss candle is RED, you are taking CALL in subsequent candle.
Select Specific Trading Session. Please select “USE SPECIFIC SESSION”. Default: TRUE
Put the investment amount per option. Default: 10
Payout ratio. Default: 80%
The strategy is taken from Vdub Binary Options SniperVX v1 (by @vdubus). I have deleted extra parts and kept only the necessary parts.
Result Table
Signal and Win Levels:
Signal and Loss:
Please note that Binary options trading is very risky. You must be aware of the risk and be willing to accept them in order to invest in binary options. Only invest what you can afford to lose. The past performance of any trading system, strategy, or methodology is not necessarily indicative of future results.
Buy&Sell Bullish Engulfing - The Quant Science🇺🇸
GENERAL OVERVIEW
Buy&Sell Bullish Engulfing - The Quant Science It is a Buy&Sell strategy based on the 'Bullish Engulfing' candlestick pattern. The main goal of the strategy is to achieve a consistent and sustainable return over time, with a manageable level of risk.
Bullish Engulfing
The template was developed at the top of the Indicator provided by TradingView called 'Engulfing - Bullish'.
ENTRY AND EXIT CRITERIA
Entry: A single long order is opened when the candlestick pattern is formed, and the percentage size of the order (%) is fixed by the trader through the user interface.
Exit: The long trade is closed on a percentage equity take profit-stop loss.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
🇮🇹
PANORAMICA GENERALE
Buy&Sell Bullish Engulfing - The Quant Science è una strategia Buy&Sell basata sul candlestick pattern 'Bullish Engulfing'. L'obiettivo principale della strategia è ottenere un ritorno costante e sostenibile nel tempo, con un livello gestibile di rischio.
Bullish Engulfing
Il template è stato sviluppato al top dell' Indicatore fornito da Trading View chiamato 'Engulfing - Bullish'.
CRITERI DI ENTRATA E USCITA
Entrata: viene aperto un singolo ordine long quando si forma il candlestick pattern, la size percentuale dell'ordine (%) viene selezionato tramite l'interfaccia utente dal trader.
Uscita: la chiusura della posizione avviene unicamente tramite un take profit-stop loss percentuale calcolato sul capitale.
Upgraded WatermarkThis mimics the built in watermark feature, but adds the ability to change location as well as see an equities sector and industry group.
Cycles AnalysisI strongly believe in cycles, so I wanted to create something that would give a visual representation of bull/bear markets and give a prediction based on the previous data. It's up to you how to decide what is a bull/bear cycle. There is no single rule for all assets because 20% drop in SP500 starts a bear market in traditional markets, while 35% drop for Bitcoin is a Tuesday. You have two options on how to decide when markets turn: either by a % change (traditional definition) or if there is no new high/low after X days. A softer version to show periods of no new highs/lows is to use the Stagnation option. Stagnation periods hava the same logic as the cycle change by X days: if there is no new high/low then we treat this period as a stagnation. The difference is that stagnation periods do not change cycle directions and do not participate in calculations.
The script also draws a possible "predictions" zone where the current cycle might end up. There is no magic here, it just takes previous cycles' size to draw the possible boundaries. If you decide to use percentiles then the box area will be taken from the percentiles calculations, otherwise it will come from the full data. "x" in the predictions zone represents a target mean (average) value, "o" represents a target median value.
A few things to keep in mind:
- this script is not supposed to be used in trading. It was created for analysis. It repaints. And when I say "it repaints" - it might like repaint the last 6 months of data if a new low comes and we are in a stagnation period (aka not a financial advice).
- it doesn't work with replays as it does calculations only once on the last candle.
- you need at least 3 periods to be able to calculate percentiles. And after this it will remove at least 1 period on each side. Which means that 90 percentile will not be a real 90 percentile until you have enough periods for it to be (20 in this specific case).
- it assumes that a year = 360 days, and a month = 30 days. So the duration presentation might not be exact, until you move to the day level.
- I had macro analysis in mind when I created the script, but nothing stops you from using it in a 1m time frame for BTC. Just change the time duration presentation.
- the last period is not finished, so it doesn't participate in calculations.
lib_priceactionLibrary "lib_priceaction"
a library for everything related to price action, starting off with displacements
displacement(len, min_strength, o, c)
calculate if there is a displacement and how strong it is
Parameters:
len (int) : The amount of candles to consider for the deviation
min_strength (float) : The minimum displacement strength to trigger a signal
o (float) : The source series on which calculations are based
c (float) : The source series on which calculations are based
Returns: a tuple of (bool signal, float displacement_strength)
Overgeared Library Economic Calendar-----------------------------------------------------------
Base on script -> jdehorty/EconomicCalendar
Very Big Thanks to jdehorty/EconomicCalendar
-----------------------------------------------------------
Trend Correlation HeatmapHello everyone!
I am excited to release my trend correlation heatmap, or trend heatmap for short.
Per usual, I think its important to explain the theory before we get into the use of the indicator, so let's get into the theory!
The theory:
So what is a correlation?
Correlation is the relationship one variable has to another. Correlations are the basis of everything I do as a quantitative trader. From the correlation between the same variables (i.e. autocorrelation), the correlation between other variables (i.e. VIX and SPY, SPY High and SPY Low, DXY and ES1! close, etc.) and, as well, the correlation between price and time (time series correlation).
This may sound very familiar to you, especially if you are a user, observer or follower of my ideas and/or indicators. Ninety-five percent of my indicators are a function of one of those three things. Whether it be a time series based indicator (i.e.my time series indicator), whether it be autocorrelation (my autoregressive cloud indicator or my autocorrelation oscillator) or whether it be regressive in nature (i.e. my SPY Volume weighted close, or even my expected move which uses averages in lieu of regressive approaches but is foundational in regression principles. Or even my VIX oscillator which relies on the premise of correlations between tickers.) So correlation is extremely important to me and while its true I am more of a regression trader than anything, I would argue that I am more of a correlation trader, because correlations are the backbone of how I develop math models of stocks.
What I am trying to stress here is the importance of correlations. They really truly are foundational to any type of quantitative analysis for stocks. And as such, understanding the current relationship a stock has to time is pivotal for any meaningful analysis to be conducted.
So what is correlation to time and what does it tell us?
Correlation to time, otherwise known and commonly referred to as "Time Series", is the relationship a ticker's price has to the passing of time. It is displayed in the traditional Pearson Correlation Coefficient or R value and can be any value from -1 (strong negative relationship, i.e. a strong downtrend) to + 1 (i.e. a strong positive relationship, i.e. a strong uptrend). The higher or lower the value the stronger the up or downtrend is.
As such, correlation to time tells us two very important things. These are:
a) The direction of the stock; and
b) The strength of the trend.
Let's take a look at an example:
Above we have a chart of QQQ. We can see a trendline that seems to fit well. The questions we ask as traders are:
1. What is the likelihood QQQ breaks down from this trendline?
2. What is the likelihood QQQ continues up?
3. What is the likelihood QQQ does a false breakdown?
There are numerous mathematical approaches we can take to answer these questions. For example, 1 and 2 can be answered by use of a Cumulative Distribution Density analysis (CDDA) or even a linear or loglinear regression analysis and 3 can be answered, more or less, with a linear regression analysis and standard error ascertainment, or even just a general comparison using a data science approach (such as cosine similarity or Manhattan distance).
But, the reality is, all 3 of these questions can be visualized, at least in some way, by simply looking at the correlation to time. Let's look at this chart again, this time with the correlation heatmap applied:
If we look at the indicator we can see some pivotal things. These are:
1. We have 4, very strong uptrends that span both higher AND lower timeframes. We have a strong uptrend of 0.96 on the 5 minute, 50 candle period. We have a strong uptrend at the 300 candle lookback period on the 1 minute, we have a strong uptrend on the 100 day lookback on the daily timeframe period and we have a strong uptrend on the 5 minute on the 500 candle lookback period.
2. By comparison, we have 3 downtrends, all of which have correlations less than the 4 uptrends. All of the downtrends have a correlation above -0.8 (which we would want lower than -0.8 to be very strong), and all of the uptrends are greater than + 0.80.
3. We can also see that the uptrends are not confined to the smaller timeframes. We have multiple uptrends on multiple timeframes and both short term (50 to 100 candles) and long term (up to 500 candles).
4. The overall trend is strengthening to the upside manifested by a positive Max Change and a Positive Min change (to be discussed later more in-depth).
With this, we can see that QQQ is actually very strong and likely will continue at least some upside. If we let this play out:
We continued up, had one test and then bounced.
Now, I want to specify, this indicator is not a panacea for all trading. And in relation to the 3 questions posed, they are best answered, at least quantitatively, not only by correlation but also by the aforementioned methods (CDDA, etc.) but correlation will help you get a feel for the strength or weakness present with a stock.
What are some tangible applications of the indicator?
For me, this indicator is used in many ways. Let me outline some ways I generally apply this indicator in my day and swing trading:
1. Gauging the strength of the stock: The indictor tells you the most prevalent behavior of the stock. Are there more downtrends than uptrends present? Are the downtrends present on the larger timeframes vs uptrends on the shorter indicating a possible bullish reversal? or vice versa? Are the trends strengthening or weakening? All of these things can be visualized with the indicator.
2. Setting parameters for other indicators: If you trade EMAs or SMAs, you may have a "one size fits all" approach. However, its actually better to adjust your EMA or SMA length to the actual trend itself. Take a look at this:
This is QQQ on the 1 hour with the 200 EMA with 200 standard deviation bands added. If we look at the heatmap, we can see, yes indeed 200 has a fairly strong uptrend correlation of 0.70. But the strongest hourly uptrend is actually at 400 candles, with a correlation of 0.91. So what happens if we change the EMA length and standard deviation to 400? This:
The exact areas are circled and colour coded. You can see, the 400 offers more of a better reference point of supports and resistances as well as a better overall trend fit. And this is why I never advocate for getting married to a specific EMA. If you are an EMA 200 lover or 21 or 51, know that these are not always the best depending on the trend and situation.
Components of the indicator:
Ah okay, now for the boring stuff. Let's go over the functionality of the indicator. I tried to keep it simple, so it is pretty straight forward. If we open the menu here are our options:
We have the ability to toggle whichever timeframes we want. We also have the ability to toggle on or off the legend that displays the colour codes and the Max and Min highest change.
Max and Min highest change: The max and min highest change simply display the change in correlation over the previous 14 candles. An increasing Max change means that the Max trend is strengthening. If we see an increasing Max change and an increasing Min change (the Min correlation is moving up), this means the stock is bullish. Why? Because the min (i.e. ideally a big negative number) is going up closer to the positives. Therefore, the downtrend is weakening.
If we see both the Max and Min declining (red), that means the uptrend is weakening and downtrend is strengthening. Here are some examples:
Final Thoughts:
And that is the indicator and the theory behind the indicator.
In a nutshell, to summarize, the indicator simply tracks the correlation of a ticker to time on multiple timeframes. This will allow you to make judgements about strength, sentiment and also help you adjust which tools and timeframes you are using to perform your analyses.
As well, to make the indicator more user friendly, I tried to make the colours distinctively different. I was going to do different shades but it was a little difficult to visualize. As such, I have included a toggle-able legend with a breakdown of the colour codes!
That's it my friends, I hope you find it useful!
Safe trades and leave your questions, comments and feedback below!
Price Delta HeatmapThe Price Delta Heatmap is an indicator designed to visualize the price changes of an asset over time. It helps traders identify and analyze significant price movements and potential volatility. The indicator calculates the price delta, which is the difference between the current close price and the previous close price. It then categorizes the price deltas into different color ranges to create a heatmap-like display on the chart.
The indicator uses user-defined thresholds to determine the color ranges. These thresholds represent the minimum price change required for a specific color to be assigned. The thresholds are adjustable to accommodate different asset classes and trading strategies. Positive price deltas are associated with bullish movements, while negative price deltas represent bearish movements.
The indicator plots bars color-coded according to the price delta range it falls into. The color ranges can be customized to match personal preferences or specific trading strategies. Additionally, the indicator includes signal shapes below the bars to highlight significant positive or negative price deltas. Traders can adjust the threshold values based on their preferred sensitivity to price changes. Higher threshold values may filter out minor price movements and focus on more significant shifts, while lower threshold values will capture even minor fluctuations.
****The default settings have the thresholds set to levels of 100, 50, 20, 10, 0, -10, -20, -50, and -100. These numbers are well-suited for assets such as Ethereum or Bitcoin which are larger in price than an asset that has a price of $1.50, for example. To compensate, adjust the thresholds in the settings to reflect the price delta on the desired asset. All coloration and horizontal line plots will adjust to reflect these changes.****
Traders can interpret the Price Delta Heatmap as follows:
-- Bright green bars indicate the highest positive price deltas, suggesting strong bullish price movements.
-- Green bars represent positive price deltas above the third threshold, indicating significant bullish price changes.
-- Olive bars indicate positive price deltas above the second threshold, suggesting moderate bullish price movements.
-- Yellow bars represent positive price deltas above the lowest threshold, indicating minor bullish price changes. This color is reflected on the negative side as well. Yellow bars below zero indicate negative price deltas below the lowest threshold, suggesting minor bearish price changes.
-- White bars represent zero price deltas, indicating no significant price movement.
-- Orange bars represent negative price deltas below the second threshold, indicating moderate bearish price movements.
-- Red bars indicate negative price deltas below the third threshold, suggesting significant bearish price changes.
-- Maroon bars represent the lowest negative price deltas, indicating strong bearish price movements.
The coloration of the Price Delta line itself is determined by the line's relation to the second positive and second negative thresholds (default +/- 20) - if the line is above the second positive threshold, the line is colored lime (and is reflected in a lime arrow at the bottom of the indicator); if the line is below the second negative threshold, the line is colored fuchsia (also reflected as an arrow); if the line is between thresholds, it is colored aqua.
The Price Delta Heatmap can be used in various trading strategies and applications. Some potential use cases include:
-- Trend identification : The indicator helps traders identify periods of high volatility and potential trend reversals.
-- Volatility analysis : By observing the color changes in the heatmap, traders can gauge the volatility of an asset and adjust their risk management strategies accordingly.
-- Confirmation tool : The indicator can be used as a confirmation tool alongside other technical indicators, such as trend-following indicators or oscillators.
-- Breakout trading : Traders can look for price delta bars of a specific color range to identify potential breakout opportunities.
However, it's important to note that the Price Delta Heatmap has certain limitations. These include:
-- Lagging nature : The indicator relies on historical price data, which means it may not provide real-time insights into price movements.
-- Sensitivity to thresholds : The choice of threshold values affects the indicator's sensitivity and may vary depending on the asset being traded. It requires experimentation and adjustment to find optimal values.
-- Market conditions : The indicator's effectiveness may vary depending on market conditions, such as low liquidity or sudden news events.
Traders should consider using the Price Delta Heatmap in conjunction with other technical analysis tools and incorporate risk management strategies to enhance their trading decisions.
Currency Conversion ChartReleasing this utility indicator I made for myself and thought others may find it helpful.
It is a simple currency conversion indicator. I personally trade both the TSX and the NYSE and hold both CAD and USD. As such, when I take positions in either or, I like to track how the currency I hold is affecting my position.
What the indicator does:
So, as indicated above, it converts a ticker's candlestick chart into the designated currency. You can either manually set the currency exchange rate, or search the currency exchange chart on Tradingview and it will auto-convert:
Purple arrow: The purple arrow points to the auto-input. You can search the currency you want to convert and it will automatically apply the conversion. It defaults to USD to CAD, but you can do USD to JPY, AUD to CAD, whatever currency you want provided it is available on tradingview. Alternatively, you can select manual conversion and input the manual conversion rate to apply.
Green Arrow: The green arrow refers to the conversion type. The indicator will default to static auto. This will pull the previous daily close. As currency trades at all hours, real-time is not advisable because the currency is in constant flux. Static will provide more stable results. However, you can toggle between the two. You can also just toggle Manual conversion.
Yellow arrow and red arrow: These pertain to position management. The indicator will display the change in the currency price over the designated amount of days. If you want to know how much the currency has changed in price over the last 7 or 20 days, simply put that value in the change input.
When you click manage position, you can fill out the position size variable and put the number of days you have had the position in the change parameter. This is the cost of your position. It can be options or shares. It will then adjust your position cost for the current change in the currency based on the number of days you have held it.
The indicator can be viewed on any timeframe and you can see how the conversion price compares to the listed price.
And that's basically the indicator! Its a simple utility indicator and hopefully some people will find use from it like I do!
Safe trades everyone, take care.
Perp/Spot % SpreadTo be used on BINANCE USDT PERPETUAL charts.
Automatically pulls the equivalent Binance Spot pair and plots the Spread of the Close in % terms( Value of 1 means 1% difference from Perp price)
-Positive value means Spot is trading x% ABOVE the PERP
-Negative value means Spot is trading x% UNDER the PERP
Autocorrelation OscillatorReleasing the autocorrelation oscillator.
NOTE! Please be sure to read the description. This is a theoretical indicator and its important to understand the theory behind its use.
About the indicator:
Before getting into the indicator and its functionality, its important to discuss the theoretical underpinnings of the indicator.
The autocorrelation oscillator operates on two theories of market behaviour that go hand in hand. Those theories are the market efficiency theory and the random walk theory (or hypothesis ).
Market efficiency theory: The market efficiency theory or "Efficient Market Hypothesis (EMH)" postulates that all available information is reflected in a ticker's price almost instantaneously and thus it is impossible for an investor or trader to get ahead of the market because we cannot respond to the speed that the market responds. Of course, there are many holes in this theory, the most notable being that the market is a function of humans. Absent humans and their technological integrations into the market, the market would cease to react at all. But that's besides the point. This is a widely accepted theory and one in which I can mathematically observe through statistical tests. The truth behind this theory is the market is efficient for responding to evolving economic and financial information, likely owning to huge amounts of computer and algorithmic integration into trading, and thus the market is more efficient than the average person is capable (absent computerized algorithms and integration) of ascertaining nuanced financial and economic circumstances. By the time we the people can appraise information, the market has already acted on it. And that is the main premise of the EMH.
The next theory is the Random Walk Theory or Hypothesis (RWH). This builds on the EMH and essentially postulates that the market reacts so quickly to price in current circumstances that it is too random for people to truly exploit and benefit from.
The result of these two theories is two-fold and can be summarized as such:
a) The market behaves in a chaotic fashion that is seemingly random and is incapable of being predicted effectively; and
b) The market is more efficient than a person in incorporating key fundamental information, contributing to the high degree of seemingly random behaviour.
So, how does this help us?
It is said, because of the EMH and the RWH, the only way to truly exploit the market for profit is by:
a) Buying and holding and investing under the bias that stocks will eventually rise in value; or
b) For short term trading, exploiting the pricing anomalies within the data.
So how do we exploit pricing anomalies within the data?
Well, in my own research on market efficiency and behaviour, I have identified many ways of figuring out some anomalies. One of the most effective ways is by looking at simple correlation of lagged values, or autocorrelation for short.
What is autocorrelation and how to use it in relation to EMH and RWH?
Autocorrelation refers to the correlative relationship among the values in a series. Put simply, its the relationship of the same variable over time. For example, if we wanted to look at the auto-correlation of a ticker's high price, we would take, say, 5 to 7 previous high prices and correlate them with the current high price in a series dataset. If the EMH and RWH are true, the correlation among all the variables should have an average less than 0.5 or greater than -0.5. This would indicate true randomness in the dataset and thus an efficient market.
However, if the average of all of the sum's of these correlations are greater than or equal to 0.5 or less than or equal to -0.5, that indicates there is a high degree of autocorrelation and thus the EMH ad RWH is being invalidated as the market is not operating efficiently. This is an anomaly and this anomaly can be exploited.
So how do we exploit it?
Well, when the EMH and RWH hypothesis is being invalidated, we can expect what I coin as a "Regression to Chaos" i.e. the market will revert back to an efficient equilibrium state. So if we have a high correlation of the lagged variables and a strong uptrend or downtrend correlation, we can expect an inefficient market to correct back to an efficient market (i.e. have a reversal from the current trend).
So how does the indicator work?
The indicator measures the lagged correlation of the previous 5 highs and lows of a ticker. A high correlation among all of the highs and lows that exceeds 0.8 would be an invalidation of the EMH and RWH and thus signal a correction to come (i.e. a Regression to Chaos).
The indicator will display this by changing colour. Red for a bearish reversal and green for a bullish. Let's take a look below using the ticker MSFT:
Above we can see the indicator identifying observed inefficiencies within the MSFT ticker on the 1 minute timeframe. The green vertical lines correspond to potential bullish reversals as a result of bearish inefficiencies, the red correspond to bearish reversals as a result of bullish inefficiencies.
You can see these lead to reversals within the ticker.
Components of the indicator:
In the chart above we see the following that are being indicated by arrows:
Red Arrows: Show the identified inefficiencies. Red for bullish inefficiencies (i.e. bearish reversal), green for bearish inefficiencies (i.e. bullish reversal)
Yellow Arrow: The lagged variable chart. This will display the current correlation among all the lagged variables the indicator is assessing.
Teal arrow: Displays the current strength of the trend by correlating the trend to time. A strong negative value (i.e. a value less than or equal to -0.5) indicates a strong downtrend, a strong positive value indicates the inverse.
You can unselect the data-tables in the settings menu if you just want to view the correlation line itself. This part of the indicator is customizable. You can also define the lookback period; however, it is strongly recommended to leave it at 14 as this maintains the use of this indicator as an oscillator.
And that is the indicator! Let me know your comments, questions and feedback below.
Safe trades everyone!
Default Strategy Template© CN_FX-999
Coded By Christian Nataliano
First Coded In 14/06/2023
Last Edited In 22/06/2023
This Is A Default Strategy Template That Can Make Your Strategy Scripts More Organized With The Benefit Of Having The Same Layouts & Not Needing To Copy Over The Common Codes Such As Displaying Backtest Results, Opening & Closing Trades, Pine Connector Capabilities And A Clean User Input Interface. This Is A Blank Strategy Script So Feel Free To Use It As Your Default Template For Your Future Strategies.
Credits To Some Of The Custom Code In The Scripts To © ZenAndTheArtOfTrading, Especially The Table Data Plotting
CNTLibraryLibrary "CNTLibrary"
Custom Functions To Help Code In Pinescript V5
Coded By Christian Nataliano
First Coded In 10/06/2023
Last Edited In 22/06/2023
Huge Shout Out To © ZenAndTheArtOfTrading and his ZenLibrary V5, Some Of The Custom Functions Were Heavily Inspired By Matt's Work & His Pine Script Mastery Course
Another Shout Out To The TradingView's Team Library ta V5
//====================================================================================================================================================
// Custom Indicator Functions
//====================================================================================================================================================
GetKAMA(KAMA_lenght, Fast_KAMA, Slow_KAMA)
Calculates An Adaptive Moving Average Based On Perry J Kaufman's Calculations
Parameters:
KAMA_lenght (int) : Is The KAMA Lenght
Fast_KAMA (int) : Is The KAMA's Fastes Moving Average
Slow_KAMA (int) : Is The KAMA's Slowest Moving Average
Returns: Float Of The KAMA's Current Calculations
GetMovingAverage(Source, Lenght, Type)
Get Custom Moving Averages Values
Parameters:
Source (float) : Of The Moving Average, Defval = close
Lenght (simple int) : Of The Moving Average, Defval = 50
Type (string) : Of The Moving Average, Defval = Exponential Moving Average
Returns: The Moving Average Calculation Based On Its Given Source, Lenght & Calculation Type (Please Call Function On Global Scope)
GetDecimals()
Calculates how many decimals are on the quote price of the current market © ZenAndTheArtOfTrading
Returns: The current decimal places on the market quote price
Truncate(number, decimalPlaces)
Truncates (cuts) excess decimal places © ZenAndTheArtOfTrading
Parameters:
number (float)
decimalPlaces (simple float)
Returns: The given number truncated to the given decimalPlaces
ToWhole(number)
Converts pips into whole numbers © ZenAndTheArtOfTrading
Parameters:
number (float)
Returns: The converted number
ToPips(number)
Converts whole numbers back into pips © ZenAndTheArtOfTrading
Parameters:
number (float)
Returns: The converted number
GetPctChange(value1, value2, lookback)
Gets the percentage change between 2 float values over a given lookback period © ZenAndTheArtOfTrading
Parameters:
value1 (float)
value2 (float)
lookback (int)
BarsAboveMA(lookback, ma)
Counts how many candles are above the MA © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are above the MA
BarsBelowMA(lookback, ma)
Counts how many candles are below the MA © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are below the EMA
BarsCrossedMA(lookback, ma)
Counts how many times the EMA was crossed recently © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many times price recently crossed the EMA
GetPullbackBarCount(lookback, direction)
Counts how many green & red bars have printed recently (ie. pullback count) © ZenAndTheArtOfTrading
Parameters:
lookback (int)
direction (int)
Returns: The bar count of how many candles have retraced over the given lookback & direction
GetSwingHigh(Lookback, SwingType)
Check If Price Has Made A Recent Swing High
Parameters:
Lookback (int) : Is For The Swing High Lookback Period, Defval = 7
SwingType (int) : Is For The Swing High Type Of Identification, Defval = 1
Returns: A Bool - True If Price Has Made A Recent Swing High
GetSwingLow(Lookback, SwingType)
Check If Price Has Made A Recent Swing Low
Parameters:
Lookback (int) : Is For The Swing Low Lookback Period, Defval = 7
SwingType (int) : Is For The Swing Low Type Of Identification, Defval = 1
Returns: A Bool - True If Price Has Made A Recent Swing Low
//====================================================================================================================================================
// Custom Risk Management Functions
//====================================================================================================================================================
CalculateStopLossLevel(OrderType, Entry, StopLoss)
Calculate StopLoss Level
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, Defval = na
StopLoss (float) : Is The Custom StopLoss Distance, Defval = 2x ATR Below Close
Returns: Float - The StopLoss Level In Actual Price As A
CalculateStopLossDistance(OrderType, Entry, StopLoss)
Calculate StopLoss Distance In Pips
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
StopLoss (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
Returns: Float - The StopLoss Value In Pips
CalculateTakeProfitLevel(OrderType, Entry, StopLossDistance, RiskReward)
Calculate TakeProfit Level
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, Defval = na
StopLossDistance (float)
RiskReward (float)
Returns: Float - The TakeProfit Level In Actual Price
CalculateTakeProfitDistance(OrderType, Entry, TakeProfit)
Get TakeProfit Distance In Pips
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
TakeProfit (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
Returns: Float - The TakeProfit Value In Pips
CalculateConversionCurrency(AccountCurrency, SymbolCurrency, BaseCurrency)
Get The Conversion Currecny Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
Parameters:
AccountCurrency (simple string) : Is For The Account Currency Used
SymbolCurrency (simple string) : Is For The Current Symbol Currency (Front Symbol)
BaseCurrency (simple string) : Is For The Current Symbol Base Currency (Back Symbol)
Returns: Tuple Of A Bollean (Convert The Currency ?) And A String (Converted Currency)
CalculateConversionRate(ConvertCurrency, ConversionRate)
Get The Conversion Rate Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
Parameters:
ConvertCurrency (bool) : Is To Check If The Current Symbol Needs To Be Converted Or Not
ConversionRate (float) : Is The Quoted Price Of The Conversion Currency (Input The request.security Function Here)
Returns: Float Price Of Conversion Rate (If In The Same Currency Than Return Value Will Be 1.0)
LotSize(LotSizeSimple, Balance, Risk, SLDistance, ConversionRate)
Get Current Lot Size
Parameters:
LotSizeSimple (bool) : Is To Toggle Lot Sizing Calculation (Simple Is Good Enough For Stocks & Crypto, Whilst Complex Is For Forex)
Balance (float) : Is For The Current Account Balance To Calculate The Lot Sizing Based Off
Risk (float) : Is For The Current Risk Per Trade To Calculate The Lot Sizing Based Off
SLDistance (float) : Is The Current Position StopLoss Distance From Its Entry Price
ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
Returns: Float - Position Size In Units
ToLots(Units)
Converts Units To Lots
Parameters:
Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
Returns: Float - Position Size In Lots
ToUnits(Lots)
Converts Lots To Units
Parameters:
Lots (float) : Is For How Many Lots Need To Be Converted Into Units (Minimun 0.01 Units)
Returns: Int - Position Size In Units
ToLotsInUnits(Units)
Converts Units To Lots Than Back To Units
Parameters:
Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
Returns: Float - Position Size In Lots That Were Rounded To Units
ATRTrail(OrderType, SourceType, ATRPeriod, ATRMultiplyer, SwingLookback)
Calculate ATR Trailing Stop
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
SourceType (int) : Is To Determine Where To Calculate The ATR Trailing From, Defval = close
ATRPeriod (simple int) : Is To Change Its ATR Period, Defval = 20
ATRMultiplyer (float) : Is To Change Its ATR Trailing Distance, Defval = 1
SwingLookback (int) : Is To Change Its Swing HiLo Lookback (Only From Source Type 5), Defval = 7
Returns: Float - Number Of The Current ATR Trailing
DangerZone(WinRate, AvgRRR, Filter)
Calculate Danger Zone Of A Given Strategy
Parameters:
WinRate (float) : Is The Strategy WinRate
AvgRRR (float) : Is The Strategy Avg RRR
Filter (float) : Is The Minimum Profit It Needs To Be Out Of BE Zone, Defval = 3
Returns: Int - Value, 1 If Out Of Danger Zone, 0 If BE, -1 If In Danger Zone
IsQuestionableTrades(TradeTP, TradeSL)
Checks For Questionable Trades (Which Are Trades That Its TP & SL Level Got Hit At The Same Candle)
Parameters:
TradeTP (float) : Is The Trade In Question Take Profit Level
TradeSL (float) : Is The Trade In Question Stop Loss Level
Returns: Bool - True If The Last Trade Was A "Questionable Trade"
//====================================================================================================================================================
// Custom Strategy Functions
//====================================================================================================================================================
OpenLong(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue)
Open A Long Order Based On The Given Params
Parameters:
EntryID (string) : Is The Trade Entry ID, Defval = "Long"
LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
Comment (string) : Is The Order Comment, Defval = Long Entry Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
OpenShort(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue)
Open A Short Order Based On The Given Params
Parameters:
EntryID (string) : Is The Trade Entry ID, Defval = "Short"
LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
Comment (string) : Is The Order Comment, Defval = Short Entry Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
TP_SLExit(FromID, TPLevel, SLLevel, PercentageClose, Comment, CommentValue)
Exits Based On Predetermined TP & SL Levels
Parameters:
FromID (string) : Is The Trade ID That The TP & SL Levels Be Palced
TPLevel (float) : Is The Take Profit Level
SLLevel (float) : Is The StopLoss Level
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
CloseLong(ExitID, PercentageClose, Comment, CommentValue, Instant)
Exits A Long Order Based On A Specified Condition
Parameters:
ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Long"
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Instant (bool) : Is For Exit Execution Type, Defval = false
Returns: Void
CloseShort(ExitID, PercentageClose, Comment, CommentValue, Instant)
Exits A Short Order Based On A Specified Condition
Parameters:
ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Short"
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Instant (bool) : Is For Exit Execution Type, Defval = false
Returns: Void
BrokerCheck(Broker)
Checks Traded Broker With Current Loaded Chart Broker
Parameters:
Broker (string) : Is The Current Broker That Is Traded
Returns: Bool - True If Current Traded Broker Is Same As Loaded Chart Broker
OpenPC(LicenseID, OrderType, UseLimit, LimitPrice, SymbolPrefix, Symbol, SymbolSuffix, Risk, SL, TP, OrderComment, Spread)
Compiles Given Parameters Into An Alert String Format To Open Trades Using Pine Connector
Parameters:
LicenseID (string) : Is The Users PineConnector LicenseID
OrderType (int) : Is The Desired OrderType To Open
UseLimit (bool) : Is If We Want To Enter The Position At Exactly The Previous Closing Price
LimitPrice (float) : Is The Limit Price Of The Trade (Only For Pending Orders)
SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
Symbol (string) : Is The Traded Symbol
SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
Risk (float) : Is The Trade Risk Per Trade / Fixed Lot Sizing
SL (float) : Is The Trade SL In Price / In Pips
TP (float) : Is The Trade TP In Price / In Pips
OrderComment (string) : Is The Executed Trade Comment
Spread (float) : is The Maximum Spread For Execution
Returns: String - Pine Connector Order Syntax Alert Message
ClosePC(LicenseID, OrderType, SymbolPrefix, Symbol, SymbolSuffix)
Compiles Given Parameters Into An Alert String Format To Close Trades Using Pine Connector
Parameters:
LicenseID (string) : Is The Users PineConnector LicenseID
OrderType (int) : Is The Desired OrderType To Close
SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
Symbol (string) : Is The Traded Symbol
SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
Returns: String - Pine Connector Order Syntax Alert Message
//====================================================================================================================================================
// Custom Backtesting Calculation Functions
//====================================================================================================================================================
CalculatePNL(EntryPrice, ExitPrice, LotSize, ConversionRate)
Calculates Trade PNL Based On Entry, Eixt & Lot Size
Parameters:
EntryPrice (float) : Is The Trade Entry
ExitPrice (float) : Is The Trade Exit
LotSize (float) : Is The Trade Sizing
ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
Returns: Float - The Current Trade PNL
UpdateBalance(PrevBalance, PNL)
Updates The Previous Ginve Balance To The Next PNL
Parameters:
PrevBalance (float) : Is The Previous Balance To Be Updated
PNL (float) : Is The Current Trade PNL To Be Added
Returns: Float - The Current Updated PNL
CalculateSlpComm(PNL, MaxRate)
Calculates Random Slippage & Commisions Fees Based On The Parameters
Parameters:
PNL (float) : Is The Current Trade PNL
MaxRate (float) : Is The Upper Limit (In Percentage) Of The Randomized Fee
Returns: Float - A Percentage Fee Of The Current Trade PNL
UpdateDD(MaxBalance, Balance)
Calculates & Updates The DD Based On Its Given Parameters
Parameters:
MaxBalance (float) : Is The Maximum Balance Ever Recorded
Balance (float) : Is The Current Account Balance
Returns: Float - The Current Strategy DD
CalculateWR(TotalTrades, LongID, ShortID)
Calculate The Total, Long & Short Trades Win Rate
Parameters:
TotalTrades (int) : Are The Current Total Trades That The Strategy Has Taken
LongID (string) : Is The Order ID Of The Long Trades Of The Strategy
ShortID (string) : Is The Order ID Of The Short Trades Of The Strategy
Returns: Tuple Of Long WR%, Short WR%, Total WR%, Total Winning Trades, Total Losing Trades, Total Long Trades & Total Short Trades
CalculateAvgRRR(WinTrades, LossTrades)
Calculates The Overall Strategy Avg Risk Reward Ratio
Parameters:
WinTrades (int) : Are The Strategy Winning Trades
LossTrades (int) : Are The Strategy Losing Trades
Returns: Float - The Average RRR Values
CAGR(StartTime, StartPrice, EndTime, EndPrice)
Calculates The CAGR Over The Given Time Period © TradingView
Parameters:
StartTime (int) : Is The Starting Time Of The Calculation
StartPrice (float) : Is The Starting Price Of The Calculation
EndTime (int) : Is The Ending Time Of The Calculation
EndPrice (float) : Is The Ending Price Of The Calculation
Returns: Float - The CAGR Values
//====================================================================================================================================================
// Custom Plot Functions
//====================================================================================================================================================
EditLabels(LabelID, X1, Y1, Text, Color, TextColor, EditCondition, DeleteCondition)
Edit / Delete Labels
Parameters:
LabelID (label) : Is The ID Of The Selected Label
X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
Text (string) : Is The Text Than Wants To Be Written In The Label
Color (color) : Is The Color Value Change Of The Label Text
TextColor (color)
EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
Returns: Void
EditLine(LineID, X1, Y1, X2, Y2, Color, EditCondition, DeleteCondition)
Edit / Delete Lines
Parameters:
LineID (line) : Is The ID Of The Selected Line
X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
X2 (int) : Is The X2 Coordinate IN BARINDEX Xloc
Y2 (float) : Is The Y2 Coordinate IN PRICE Yloc
Color (color) : Is The Color Value Change Of The Line
EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
Returns: Void
//====================================================================================================================================================
// Custom Display Functions (Using Tables)
//====================================================================================================================================================
FillTable(TableID, Column, Row, Title, Value, BgColor, TextColor, ToolTip)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
Column (int) : Is The Current Column Of The Table That Wants To Be Edited
Row (int) : Is The Current Row Of The Table That Wants To Be Edited
Title (string) : Is The String Title Of The Current Cell Table
Value (string) : Is The String Value Of The Current Cell Table
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
ToolTip (string) : Is The ToolTip Of The Current Cell In The Table
Returns: Void
DisplayBTResults(TableID, BgColor, TextColor, StartingBalance, Balance, DollarReturn, TotalPips, MaxDD)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
StartingBalance (float) : Is The Account Starting Balance
Balance (float)
DollarReturn (float) : Is The Account Dollar Reture
TotalPips (float) : Is The Total Pips Gained / loss
MaxDD (float) : Is The Maximum Drawdown Over The Backtesting Period
Returns: Void
DisplayBTResultsV2(TableID, BgColor, TextColor, TotalWR, QTCount, LongWR, ShortWR, InitialCapital, CumProfit, CumFee, AvgRRR, MaxDD, CAGR, MeanDD)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
TotalWR (float) : Is The Strategy Total WR In %
QTCount (int) : Is The Strategy Questionable Trades Count
LongWR (float) : Is The Strategy Total WR In %
ShortWR (float) : Is The Strategy Total WR In %
InitialCapital (float) : Is The Strategy Initial Starting Capital
CumProfit (float) : Is The Strategy Ending Cumulative Profit
CumFee (float) : Is The Strategy Ending Cumulative Fee (Based On Randomized Fee Assumptions)
AvgRRR (float) : Is The Strategy Average Risk Reward Ratio
MaxDD (float) : Is The Strategy Maximum DrawDown In Its Backtesting Period
CAGR (float) : Is The Strategy Compounded Average GRowth In %
MeanDD (float) : Is The Strategy Mean / Average Drawdown In The Backtesting Period
Returns: Void
//====================================================================================================================================================
// Custom Pattern Detection Functions
//====================================================================================================================================================
BullFib(priceLow, priceHigh, fibRatio)
Calculates A Bullish Fibonacci Value (From Swing Low To High) © ZenAndTheArtOfTrading
Parameters:
priceLow (float)
priceHigh (float)
fibRatio (float)
Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
BearFib(priceLow, priceHigh, fibRatio)
Calculates A Bearish Fibonacci Value (From Swing High To Low) © ZenAndTheArtOfTrading
Parameters:
priceLow (float)
priceHigh (float)
fibRatio (float)
Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
GetBodySize()
Gets The Current Candle Body Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Body Size IN POINTS
GetTopWickSize()
Gets The Current Candle Top Wick Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Top Wick Size IN POINTS
GetBottomWickSize()
Gets The Current Candle Bottom Wick Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Bottom Wick Size IN POINTS
GetBodyPercent()
Gets The Current Candle Body Size As A Percentage Of Its Entire Size Including Its Wicks © ZenAndTheArtOfTrading
Returns: The Current Candle Body Size IN PERCENTAGE
GetTopWickPercent()
Gets The Current Top Wick Size As A Percentage Of Its Entire Body Size
Returns: Float - The Current Candle Top Wick Size IN PERCENTAGE
GetBottomWickPercent()
Gets The Current Bottom Wick Size As A Percentage Of Its Entire Bodu Size
Returns: Float - The Current Candle Bottom Size IN PERCENTAGE
BullishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Engulfing Candle
Parameters:
Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Engulfing Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Engulfing Candle
BearishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bearish Engulfing Candle
Parameters:
Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Engulfing Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Engulfing Candle
Hammer(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod)
Checks If The Current Bar Is A Hammer Candle
Parameters:
Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
Star(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod)
Checks If The Current Bar Is A Hammer Candle
Parameters:
Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
Doji(MaxWickSize, MaxBodySize, DojiType, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Doji Candle
Parameters:
MaxWickSize (float) : To Specify The Maximum Lenght Of Its Upper & Lower Wick, Defval = 2
MaxBodySize (float) : To Specify The Maximum Lenght Of Its Candle Body IN PERCENT, Defval = 0.05
DojiType (int)
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Doji Candle
BullishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Harami Candle
Parameters:
Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Harami Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Harami Candle
BearishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Harami Candle
Parameters:
Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Harami Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Harami Candle
//====================================================================================================================================================
// Custom Time Functions
//====================================================================================================================================================
BarInSession(sess, useFilter)
Determines if the current price bar falls inside the specified session © ZenAndTheArtOfTrading
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls within the given time session
BarOutSession(sess, useFilter)
Determines if the current price bar falls outside the specified session © ZenAndTheArtOfTrading
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls outside the given time session
DateFilter(startTime, endTime)
Determines if this bar's time falls within date filter range © ZenAndTheArtOfTrading
Parameters:
startTime (int)
endTime (int)
Returns: A boolean - true if the current bar falls within the given dates
DayFilter(monday, tuesday, wednesday, thursday, friday, saturday, sunday)
Checks if the current bar's day is in the list of given days to analyze © ZenAndTheArtOfTrading
Parameters:
monday (bool)
tuesday (bool)
wednesday (bool)
thursday (bool)
friday (bool)
saturday (bool)
sunday (bool)
Returns: A boolean - true if the current bar's day is one of the given days
AUSSess()
Checks If The Current Australian Forex Session In Running
Returns: Bool - True If Currently The Australian Session Is Running
ASIASess()
Checks If The Current Asian Forex Session In Running
Returns: Bool - True If Currently The Asian Session Is Running
EURSess()
Checks If The Current European Forex Session In Running
Returns: Bool - True If Currently The European Session Is Running
USSess()
Checks If The Current US Forex Session In Running
Returns: Bool - True If Currently The US Session Is Running
UNIXToDate(Time, ConversionType, TimeZone)
Converts UNIX Time To Datetime
Parameters:
Time (int) : Is The UNIX Time Input
ConversionType (int) : Is The Datetime Output Format, Defval = DD-MM-YYYY
TimeZone (string) : Is To Convert The Outputed Datetime Into The Specified Time Zone, Defval = Exchange Time Zone
Returns: String - String Of Datetime
Regression Candle Conversion IndicatorHey everyone!
I got a pseudo-request a while ago for something like this, essentially the ability to track where another ticker would fall based on an alternative ticker.
I did create my ticker correlation reference indicator which directly looks at the correlation between 2 tickers. However, this is an indicator that operates on the same principle but is more pragmatic for trading.
What does it do?
Well, in keeping with the theme of what I call my indicators, this has a title that explains exactly what it does, "Regression Candle Conversion Indicator" or "RCCI" for short. It uses simple regression to convert one ticker to another. So while you are tracking one indicator, you can see where the expected value should fall on the other.
Applications?
The big application of this for me is being able to track where SPY/QQQ or IWM is falling during overnight trading sessions. Extended trading hours close at 8 pm NYSE time. After that, you have to guess where futures prices will put the ETF version of it. This indicator will allow you to track where, theoretically, the underlying ETF ticker will fall based on the current trading behaviour.
Some other applications are just the ability to track how similar or dissimilar one stock is to the other. For example, if we wanted to trade, say, Boeing using shares of DFEN or ITA (a defence specific ETF), here is what we get:
In the chart above we can see BA as the primary chart and ITA as the RCCI converted chart. We will see 2 major things that should cause us concern.
First, there is a really poor correlation between the two tickers. This indicates that ITA may not produce the best exposure if I am directly looking for Boeing exposure.
Second, there is a wide standard error. this means that the results that the RCCI is providing may be skewed up to +/- 2 points (as indicated by the standard error chart).
Let's take a look at BA and DFEN:
In the above, we can see that the correlation is not great, but the standard error is quite low.
This means that, while this may not be the best ticker for Boeing exposure, the RCCI is able to confidently calculate the ticker within +/- 0.50 cents based on BA's underlying data.
However, its important to note that it is not advisable to really rely on these results if the correlation is less than + 0.5 or greater than -0.5.
Let's take a look at a few more examples:
Above we have BA (NYSE) vs BA (NEO TSX CAD Hedged). We can see the strong relationship and high confidence calculations.
And some others:
SPX (primary) and ES1! (secondary):
RTY and IWM:
ES1! and SPY:
Customizations:
As you can see above, it is pretty straight forward. There are 3 options:
Lookback Length: Determines the length of assessment for correlation and the regression assessment.
Manual Ticker Input: The indicator will pull the data from your current chart and compare it against a manually selected indicator. You must tell the indicator which ticker you are comparing against.
Data Table: This will show you the data table which contains the standard error assessment and the correlation assessment. These are determined by your lookback length. The lookback length is defaulted to 500.
And that's the indicator! It's pretty straight forward. Hopefully you find it helpful, especially if you track futures during overnight sessions.
Leave your comments/questions and feedback below.
Thanks for checking it out!