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
Statistics
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!
Alpha Trading - Pseudo Laplace Z ScoreAlpha Trading - Pseudo Laplace Z Score
Slowly, very slowly a lot of quant and statistical methods have diffused the world of traditional technical analysis with the world of real math - VEPS (Volatility, Entropy, Probability and Statistics).
‘Alpha Trading' is showing the world how VEPS can show the best probabilities of success with your trading journey.
We send a big thank you to tradingview platform and pine coding team, for this great platform and the possibility to show the methods to trade with quant and statistical methods.
There appears to be resistance in the industry about these methods, so it is even more important now than ever, to support this awesome platform and amazing talented team at trading view and pine coders who enable us all with this wonderful platform to produce tools based on VEPS (Volatility, Entropy, Probability and Statistics).
The newest indicator from the Alpha Trading stable is the “Pseudo Laplace Z Score” which combines the established statistical method of z score applied on asset data. Which is based on our previous indicator called the “Alpha Trading – RMS-Z score”. We have made some optimizations, to give an even better fit to the specific returns of price. Optimizations are on the observation that returns are more Laplace distributed than Normal distributed.
figure 1: pink distribution of the real signal (BTC, 2D), gray is perfect theoretical Laplace distribution.
Therefore, the data is not Normal distributed, but Laplace distributed. Our new indicator calculates the real Z-Score of an underlying asset.
As Z Score is a standardized Normal distribution, it relies upon the definition of Normal distribution. If it deviates from this, it still can give useful information, but the absolute value (distance from the mean in standard deviations) is not reliable, and therefore the use of Normal distribution has some uncertainties.
Therefore, this indicator calculates a pseudo standard deviation, based on the Laplace distribution formulas and the relating Z Score.
By looking at the resulting distribution of the indicator itself, it is close to a perfect theoretical Normal distribution. It is much closer to the theoretical curve (gray), and thus indicates that the use of this approach is correct. Now we can show absolute values (i.e. distance to mean, in standard deviations) which can thus be considered to assist in determining the probabilities with your trading.
figure 2: distribution of indicator AT - Pseudo Laplace Z Score vs a theoretical perfect Normal distribution on BTC 4h
Looking at the indicator directly, it appears that the probability of 99% is crossed very rarely, like expected. Because only 1% of all candles we would expect this probability line to be exceeded.
figure 3: BTC 8h with AT-Pseudo Laplace Z Score
Coming back to the method of a Z Score in general. What is a Z-Score?
A Z-score is a numerical measurement that describes a value's relationship to the mean of a group of values. Z-score is measured in terms of standard deviations from the mean. If a Z-score is 0, it indicates that the data point's score is identical to the mean score. A Z-score of 1.0 would indicate a value that is one standard deviation from the mean. Z-scores may be positive or negative, with a positive value indicating the score is above the mean and a negative score indicating it is below the mean.
Simply put, a z-score (also called a standard score) gives you an idea of how far from the mean a data point is.
Basic guidelines How to Use this indicator:
Consider Entering a Long Position when the indicator is low. Best moves are generally when the indicator Turns yellow(outlier)
Consider Entering a Short Position when the indicator is high. Best moves are generally when the indicator Turns yellow(outlier)
Consider the 3 confidence interval lines (gray lines) at 90%, 95%, and 99%, as possible reversal point (with related probability that it is not getting exceeded 🡪 reversal)
Probability Box Rule of Thirds [PPI]█ Probability Box Rule of Thirds
The Probability Box Rule of Thirds , is a visual indicator that helps traders identify possible overbought and oversold conditions. It does this by dividing the price range – highest high minus the lowest low of a given lookback period or date range – into thirds. Each third has distinct probability characteristics and when combined represent a probability box.
We have spent years refining the probability box concept, and have previously published a How To on Trading View – "How to Trade Probability Ranges – The Critical Rule of 1/3" which can be found here:
To quickly summarize the How To – when using the Rule of Thirds , you are using a combination of statistics, probabilities of success, and prior price action to determine when to enter a trade. The visual range division helps remove subjectivity and clearly shows when the trading odds are stacked in your favor. By identifying and taking higher probability trades, you have a higher chance of success as trading is all about probability and risk management.
Implementing the Rule of Thirds starts with finding an instrument that is consolidating and identifying the nearest important support and resistance levels based on your targeted trading timeframe or lookback period.
The range between the support and resistance levels is divided into thirds to form three zones within the consolidation range.
When going LONG , you want to BUY in the bottom third of the range. Once you buy, your objective is to hold during the middle third and sell when the price enters the top third.
When you buy in the lower third, there's a 66.6% probability of success. If you buy in the middle third, you only have a 50% / 50% chance of success. Going long in the top third of the range gives you a 33.3% chance of success as you are already close to the identified resistance level.
When going SHORT , the sequence and odds are reversed. You want to SELL in the top third of the range, hold the middle third and exit in the bottom third of the range. This gives you a 66.6% chance of success when entering in the top third, a 50% / 50% chance when entering in the middle third, and a 33.3% chance in the bottom third given you are already close to the identified support level.
When the price lies in the middle third, the even 50% / 50% odds provide no probability edge and a trader is better off waiting until the price reaches the upper or lower thirds of the price range.
The Rule of Thirds allows us to quickly visually evaluate trades based on probabilities, selectively enter trades that have the highest odds of success, and avoid likely losing trades. The Rule of Thirds gives you confidence to hold trades based on prior trading ranges and provides clear levels where the prices are likely to either reverse or start trending.
The Probability Box Rule of Thirds automatically implements the first two steps of the Rule of Thirds by using the highest high and lowest low of a given lookback period to identify the support and resistance levels, and automatically divides the range into thirds. The rest of the Rule of Thirds rules remain the same.
Just having the price within the bottom thirds or top thirds, however, does not mean the price will immediately reverse. The GE chart below is an example of a stock that remained 'stuck' in the upper thirds of the price range for an extended amount of time:
And the CVS chart below is an example where the price is 'stuck' in the lower thirds of the price range:
While the price is in the upper or lower thirds, it is very important that the trader should use other indicators to identify when a significant trend reversal occurs. Once a trend reversal event happens, the trader either enters a trade AND/OR exits a trade if already in one.
When the price exceeds the bounds of the probability box, there are three possible outcomes – a strong continuation trend, the price consolidates around the probability box edge, or a trend reversal. Your favorite indicators will help determine which event is happening.
The CVS chart above is a good example of the probability box being exceeded with the last bar. The price exceeding the price range is temporary event as the price range will expand to encompass the revised price range on the next trading day.
█ Indicator Features
Each supported timeframe – Monthly, Weekly, and Daily – allows the selection of an appropriate lookback period for your trading style. The defaults are a good starting point for swing trading and long-term investing. You many need to experiment to find the optimal lookback period for your trading style.
Even if you only day trade, the Probability Box Rule of Thirds with the appropriate lookback periods can help you visualize the bigger picture of where the instrument is heading.
When viewing the charts, you can find the currently selected lookback period above the upper edge of the price range.
The indicator will display a dotted yellow line at 50% of the price range and show the line's value when requested.
The visibility of the actual thirds and border price values are controlled by the " Show Probability Box Values " checkbox. You may need to expand the chart's right margin to see the values.
The " Show Internal Labels " checkbox controls the display of the internal ⅓ Division labels and the percentage odds, along with the 50% label. This option by default is set to off.
The " Show Error Messages " checkbox controls the display of error messages and by default is turned on. Turn off to prevent error messages from being shown on intraday timeframes. Save as indicator default to prevent having to turn off this setting each time added to chart.
The color and transparency controls allow the user to modify the colors used for each third. The default settings are optimized for use with a DARK background.
█ Implementation Notes
IMPORTANT - the Probability Box Rule of Thirds is set up to only handle Monthly, Weekly and Daily charts. This is intentional as the indicator is designed to be used for safer multiple day and longer swing trades. When viewed on intraday charts, the indicator will be hidden.
The Probability Box Rule of Thirds uses a rolling window of the equivalent number of bars for the lookback period rather than relying on the bar starting and ending dates. This allows the use of a standard number of days in the selected lookback window across various instruments and ensures fast, efficient calculations.
The lookback periods are adjusted when non-standard timeframe multipliers are used – e.g., a 12M chart timeframe and a 3-year lookback period will result in a 3 bar lookback. Fractional bars in this calculation are rounded up and any incompatible lookback period and chart timeframe combination will generate a runtime error.
In summary, the Probability Box Rule of Thirds automates and visually identifies overbought and oversold areas, which combined with the Rule of Thirds probability risk profiles, increases your odds of success through better trade selections and higher confidence in your trades.
█ Disclaimer
There is substantial risk in trading. Losses incurred in trading can be significant. Only trade with money you can afford to lose. We make no claims whatsoever regarding the impact of past or future performance on your trading results.
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!
Risk ManagementLibrary "RiskManagement"
This library keeps your money in check, and is used for testing and later on webhook-applications too. It has four volatility functions and two of them can be used to calculate a Stop-Loss, like Average True Range. It also can calculate Position Size, and the Risk Reward Ratio. But those calculations don't take leverage into account.
position_size(portfolio, risk, entry, stop_loss, use_leverage, qty_as_integer)
This function calculates the definite amount of contracts/shares/units you should use to buy or sell. This value can used by `strategy.entry(qty)` for example.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. Possible values are between 0.1 and 100%. Same usecase with strategy(default_qty_type=strategy.percent_of_equity,default_qty_value=100), except its calculation the risk only.
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
use_leverage (bool) : This value is optional. When not used or when set to false then this function will let you invest your portfolio at max.
qty_as_integer (bool) : This value is optional. When set to true this function will return a value used with integers. The largest integer less than or equal to the given number. Because some Broker/Exchanges let you trade hole contracts/shares/units only.
Returns: float
position_size_currency(portfolio, risk, entry, stop_loss)
This function calculates the definite amount of currency you should use when going long or short.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. For example: 1 is 100% and 0,01 is 1%. Default amount is 0.02 (2%).
entry (float) : This is the limit-/market-price for the current investment. In other words: The price per contract/share/units you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
Returns: float
rrr(entry, stop_loss, take_profit)
This function calculates the Risk Reward Ratio. Common values are between 1.5 and 2.0 and you should not go lower except for very few special cases.
Parameters:
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
take_profit (float) : This is the limit-/market-price when to take profits.
Returns: float
change_in_price(length)
This function calculates the difference between price now and close price of the candle 'n' bars before that. If prices are very volatile but closed where they began, then this method would show zero volatility. Over many calculations, this method returns a reasonable measure of volatility, but will always be lower than those using the highs and lows.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
maximum_price_fluctuation(length)
This function measures volatility over most recent candles, which could be used as an estimate of risk. It may also be effective as the basis for a stop-loss or take-profit, like the ATR but it ignores the frequency of directional changes within the time interval. In other words: The difference between the highest high and lowest low over 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
absolute_price_changes(length)
This function measures volatility over most recent close prices. This is excellent for comparing volatility. It includes both frequency and magnitude. In other words: Sum of differences between second to last close price and last close price as absolute value for 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
annualized_volatility(length)
This function measures volatility over most recent close prices. Its the standard deviation of close over the past 'n' periods, times the square root of the number of periods in a year.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
Total ReturnThis script calculates a Total Return index for stocks that shows the total performance of a stock, incorporating returns from both the share price and dividends.
To understand this, consider the situation where you invest in a 5% div stock and hold the position for 10 years. Assume at the end of 10 years, the price has gone up by 50%. A price chart will then show a 50% return, but in reality the investor has also received 50% of the initial investment in dividends, making his total return substantially more. Exactly how much more depends on whether the investor reinvested the dividends in the stock, or just held them as cash. If the former, his total return will be well over 100%; in the latter, his total return will be 100% exactly.
There are 2 input options:
- Dividend type: allows the user to choose "gross" or "net". Note that most stocks will have a "gross" data series whereas many will not have a "net" series.
- Reinvestment: allows the user to choose whether dividends should be reinvested in the stock ("Yes") or held in cash ("No").
Total return formula:
- With reinvestment: log((today's closing price + dividends paid today) / (yesterday's closing price))
- Without reinvestment: log(today's closing price / yesterday's closing price) + log (dividends paid thus far / first closing price)
Linear Correlation Coefficient W/ MAs and Significance TestsThis Linear CC takes into account the log-normal distribution of stock prices and performs Pearson correlation on that data set. It also smoothens the results into an easy to read oscillator, and performs a two-tail t-test on the correlation coefficient data (with a = 0.05) to determine the significance of the coefficients. Significant results are shown in a solid yellow color while insignificant results are shown in a dark yellow color (you can eyeball this with a normal LCC by looking at results around -0.5 to +0.5).
Two MAs are provided as well for a quick trend analysis. You can reduce the lookback period, but it defaults to 31 for the sake of statistical standards.
ASG Delta %This utility script provides a convenient way to calculate the percentage gain or drop of a token's price within a user-defined date range. It eliminates the need for manual measurement on individual charts, saving time and effort.
The script is particularly valuable when integrated into a daily token scanning routine for watchlists. By comparing the significant gains or drops among different tokens, traders can identify potential trading opportunities.
Simply select the desired date range, and the script will identify the highest and lowest price points achieved during that period. It then shows a visual representation in the form of a bullish or bearish box, displaying the percentage change (delta %). If the current price falls within the box's upper and lower bounds, additional percentage information can be shown in either the 'normal' or 'reverse' mode.
For instance, if a token experiences a -52.35% drop, enabling the 'Reverse' setting will reveal a potential 109.86% gain (from the low), or a 76.02% gain (from current price) or a potential drop of -16.5% (from current price) etc.. Having these basic statistics available, without having to manually chart them, especially during prolonged bear or bull markets, enables traders to make informed decisions and position themselves for more profitable trades.
I hope you find this script valuable. Your comments and recommendations are welcome as they will help improve the script's functionality further.
The Z-score The Z-score, also known as the standard score, is a statistical measurement that describes a value's relationship to the mean of a group of values. It's measured in terms of standard deviations from the mean. If a Z-score is 0, it indicates that the data point's score is identical to the mean score. Z-scores may be positive or negative, with a positive value indicating the score is above the mean and a negative score indicating it is below the mean.
The concept of Z-score was introduced by statistician Carl Friedrich Gauss as part of his "method of the least squares," which was an important step in the development of the normal distribution and Z-score tables. It's a key concept in statistics and is used in various statistical tests.
In financial analysis, Z-scores are used to determine whether a data point is usual or unusual. You can think of it as a measure of how many standard deviations an element is from the mean. For instance, a Z-score of 1.0 would denote a value that is one standard deviation from the mean. Z-scores are also used to predict probabilities, with Z-scores having a distribution that is expected to be normal.
In trading, a Z-score is used to determine how often a trading system may produce a string of winners or losers. It can help a trader to understand whether the losses or profits they see are something that the system would most likely produce, or if it's a once in a blue moon situation. This helps traders make decisions about when to start or stop a system.
I just wanted to play a bit with the Z-score I guess.
Feel free to share your findings if you discover additional applications for this strategy or identify timeframes where it appears to perform more optimally.
How it works:
This strategy is based on a statistical concept called Z-score, which measures the number of standard deviations a data point is from the mean. In other words, it helps determine how unusual or usual a data point is.
In the context of this strategy, Z-score is applied to a 10-period EMA (Exponential Moving Average) of Heikin-Ashi candlestick close prices. The Z-score is calculated over a look-back period of 25 bars.
The EMA of the Z-score is then calculated over a 20-bar period, and the upper and lower thresholds (bounds for buy and sell signals) are defined using the 90th and 10th percentiles of this EMA score.
Long positions are taken when the Z-score crosses above the lower threshold or crosses above the mid-line (50th percentile). An additional long entry is made when the Z-score crosses above the highest value the EMA has been in the past 100 periods.
Short positions are initiated when the EMA crosses below the upper threshold, lower threshold or the highest value the EMA has been in the past 100 periods.
Positions are closed when opposing entry conditions are met, for example, a long position is closed when the short entry condition is true, and vice versa.
Set your desired start date for the strategy. This can be modified in the timestamp("YYYY MM DD") function at the top of the script.
Machine Learning : Torben's Moving Median KNN BandsWhat is Median Filtering ?
Median filtering is a non-linear digital filtering technique, often used to remove noise from an image or signal. Such noise reduction is a typical pre-processing step to improve the results of later processing (for example, edge detection on an image). Median filtering is very widely used in digital image processing because, under certain conditions, it preserves edges while removing noise (but see the discussion below), also having applications in signal processing.
The main idea of the median filter is to run through the signal entry by entry, replacing each entry with the median of neighboring entries. The pattern of neighbors is called the "window", which slides, entry by entry, over the entire signal. For one-dimensional signals, the most obvious window is just the first few preceding and following entries, whereas for two-dimensional (or higher-dimensional) data the window must include all entries within a given radius or ellipsoidal region (i.e. the median filter is not a separable filter).
The median filter works by taking the median of all the pixels in a neighborhood around the current pixel. The median is the middle value in a sorted list of numbers. This means that the median filter is not sensitive to the order of the pixels in the neighborhood, and it is not affected by outliers (very high or very low values).
The median filter is a very effective way to remove noise from images. It can remove both salt and pepper noise (random white and black pixels) and Gaussian noise (randomly distributed pixels with a Gaussian distribution). The median filter is also very good at preserving edges, which is why it is often used as a pre-processing step for edge detection.
However, the median filter can also blur images. This is because the median filter replaces each pixel with the value of the median of its neighbors. This can cause the edges of objects in the image to be smoothed out. The amount of blurring depends on the size of the window used by the median filter. A larger window will blur more than a smaller window.
The median filter is a very versatile tool that can be used for a variety of tasks in image processing. It is a good choice for removing noise and preserving edges, but it can also blur images. The best way to use the median filter is to experiment with different window sizes to find the setting that produces the desired results.
What is this Indicator ?
K-nearest neighbors (KNN) is a simple, non-parametric machine learning algorithm that can be used for both classification and regression tasks. The basic idea behind KNN is to find the K most similar data points to a new data point and then use the labels of those K data points to predict the label of the new data point.
Torben's moving median is a variation of the median filter that is used to remove noise from images. The median filter works by replacing each pixel in an image with the median of its neighbors. Torben's moving median works in a similar way, but it also averages the values of the neighbors. This helps to reduce the amount of blurring that can occur with the median filter.
KNN over Torben's moving median is a hybrid algorithm that combines the strengths of both KNN and Torben's moving median. KNN is able to learn the underlying distribution of the data, while Torben's moving median is able to remove noise from the data. This combination can lead to better performance than either algorithm on its own.
To implement KNN over Torben's moving median, we first need to choose a value for K. The value of K controls how many neighbors are used to predict the label of a new data point. A larger value of K will make the algorithm more robust to noise, but it will also make the algorithm less sensitive to local variations in the data.
Once we have chosen a value for K, we need to train the algorithm on a dataset of labeled data points. The training dataset will be used to learn the underlying distribution of the data.
Once the algorithm is trained, we can use it to predict the labels of new data points. To do this, we first need to find the K most similar data points to the new data point. We can then use the labels of those K data points to predict the label of the new data point.
KNN over Torben's moving median is a simple, yet powerful algorithm that can be used for a variety of tasks. It is particularly well-suited for tasks where the data is noisy or where the underlying distribution of the data is unknown.
Here are some of the advantages of using KNN over Torben's moving median:
KNN is able to learn the underlying distribution of the data.
KNN is robust to noise.
KNN is not sensitive to local variations in the data.
Here are some of the disadvantages of using KNN over Torben's moving median:
KNN can be computationally expensive for large datasets.
KNN can be sensitive to the choice of K.
KNN can be slow to train.
Multi Timeframe Control (Enomai)This indicator is called "Multi Timeframe Control" and has the following features:
1. Table settings:
- selection of different timeframes (1m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, D, W, M) for displaying closing prices;
- choice of table orientation (horizontal or vertical);
- selection of the position for the table on the chart (top right, middle right, bottom right, top center, middle center, bottom center, top left, middle left, bottom left);
- table size selection (automatic, large, medium, normal, small, tiny);
- text color customization (positive closing value color and negative closing value color);
- display or hide closing prices in the table.
2. Line settings:
- selection of different timeframes for displaying lines (similar to table settings);
- for each time frame (1m, 5m, 15m, etc.) you can choose whether to place a line on the chart;
- individual color selection for each line.
- choice of line display type on the chart (circle, cross, step line, diamond);
- show or hide lines on the chart.
3. Other settings:
- offset the length of price lines to the left by a certain number of bars (default is 0, maximum is 300 bars);
- offset of bars for displaying the closing price from previous periods (default is 1, maximum is 500 bars).
The indicator allows you to display closing prices for different timeframes simultaneously both in the table and on the chart with the corresponding colors for each timeframe. You can also set up which previous bar and, accordingly, its closing price to display in the table and on the chart. For example, if you set 3 in the bar offset setting for displaying the closing price of previous periods, then for the D timeframe will be displayed the closing price of the bar 3 days ago.
-----
Данный индикатор называется "Multi Timeframe Control" и имеет следующие возможности:
1. Настройка таблицы:
- выбор различных временных рамок (1m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, D, W, M) для отображения цен закрытия;
- выбор ориентации таблицы (горизонтальная или вертикальная);
- выбор положения таблицы на графике (верхний правый, средний правый, нижний правый, верхний центр, средний центр, нижний центр, верхний левый, средний левый, нижний левый);
- выбор размера таблицы (автоматический, большой, средний, нормальный, малый, мелкий);
- настройка цвета текста, цвета положительных значений закрытия цены и цвета отрицательных значений закрытия цены;
- отображение или сокрытие цен закрытия в таблице.
2. Настройка линий:
- выбор различных временных рамок для отображения линий (аналогичны настройкам таблицы);
- для каждой временной рамки (1m, 5m, 15m и т.д.) вы можете выбрать, нужно ли размещать линию на графике;
- вы можете выбрать цвет для каждой линии в отдельности.
- выбор типа отображения линий на графике (круг, крестик, ступенчатая линия, ромб);
- отображение или сокрытие линий на графике.
3. Другие настройки:
- смещение длины линий цены влево на определенное количество баров (по умолчанию 0, максимум 300 баров);
- смещение баров для отображения цены закрытия предыдущих периодов (по умолчанию 1, максимум 500 баров).
Индикатор позволяет отображать цены закрытия для разных таймфреймов одновременно как в таблице, так и на графике с соответствующими цветами для каждого таймфрейма. Также Вы можете настроить какой именно предыдущий бар и, соответственно, его цену закрытия отображать в таблице и на графике. Например, если в настройке смещения баров для отображения цены закрытия предыдущих периодов установить 3, то для таймфрейма D будет отображаться цена закрытия бара 3 дня назад.
Ratio To Average - The Quant ScienceRatio To Average - The Quant Science is a quantitative indicator that calculates the percentage ratio of the market price in relation to a reference average. The indicator allows the calculation of the ratio using four different types of averages: SMA, EMA, WMA, and HMA. The ratio is represented by a series of histograms that highlight periods when the ratio is positive (in green) and periods when the ratio is negative (in red).
What is the Ratio to Average?
The Ratio to Average is a measure that tracks the price movements with one of its averages, calculating how much the price is above or below its own average, in percentage terms.
USER INTERFACE
Lenght: it adjusts the number of bars to include in the calculation of the average.
Moving Average: it allows you to choose the type of average to use.
Color Up/Color Down : it allows you to choose the color of the indicator for positive and negative ratios.
Currency ConverterWhat it is?
It's a Currency converter/Exchange rate Viewer.
How it works?
You put the main currency and the other currency in setting then it will show the converted rate in chart.
Daily data infoThis indicator can:
- Indicate on which day of the week created the High or Low
- Based on the bars you set, sum the times in which (The day of the week you want to test makes the Weekly High or Low)
- Has the option to Sum or calculate the %
Position Size Calculator (EzAlgo)Upon adding the indicator to the chart, you will be prompted to place entry price lines, stop loss price line, and multiple take profit price lines by clicking at the desired price level on the chart.
Section Summaries
Table Settings: Allows users to select position and font size from drop-down menus. Displays current settings and potential profit/loss values.
Price Points: Users can set their Entry and select whether they want to include a DCA entry, Stop Loss price, Liquidation Buffer %, Take Profit levels and the amount of position to close at each level.
Risk Management: Users fill out their Account Size, set their Risk % (or fixed $ amount) for each Entry, set Manual Leverage, or allow the indicator to automatically choose the leverage based on the Stop Loss price distance from Entry and the Risk % per Entry.
User-Input Descriptions
DCA Price: The price at which users initiate their second, equally sized and leveraged position when using a Dollar-Cost Averaging (DCA) strategy. Upon reaching the DCA Price, the Entry Price adjusts to the Avg Price, calculated as the midpoint between initial and DCA entries.
Liquidation Buffer: A pre-set percentage that determines how close to the Stop Loss a position can get before it's liquidated. This assists the Auto Leverage feature in optimizing the leverage amount according to risk tolerance.
Risk per Entry: The proportion of the account, in % or a fixed dollar amount, that users are willing to risk for each trading position. If DCA is checked, this will assume users are entering with half of the total position size per entry.
Automatic Leverage: Auto Leverage automatically determines the optimal leverage level for a trade based on the user's Stop Loss price distance from the Entry point and the user-defined risk percentage per Entry. It also considers a user-defined Liquidation Buffer, which is a preset percentage determining how close to the Stop Loss a position can get before it's liquidated. This tool allows traders to optimize their leverage amount according to their risk tolerance.
Max Leverage: The highest leverage level users are willing to use, even if the exchange permits higher. This limit applies when the Auto Leverage feature is enabled.
Seasonal Performance for Stocks & CryptoThe Seasonal Performance indicator quickly allows you to see if you are in a bullish or bearish time of year for an underlying security and where the current performance stacks up compared to the same time of year historically. Table is fully customizable from colors to what data to see.
Table Displays
Average Performance
Best Performance
Worst Performance
Last Performance
Current Performance
Note this indicator will only work with Stocks, ETF's, Index's or Crypto.
Central Bank Balance SheetsDisplay FED, China, Europe and Japan Central Bank Assets over time in USD.
Display FED, China, Europe and Japan Central Bank Assets as % of their country's GDP over time.
Display the sum of all of the central bank assets over time.
Autocorrelation - The Quant ScienceAutocorrelation - The Quant Science it is an indicator developed to quickly calculate the autocorrelation of a historical series. The objective of this indicator is to plot the autocorrelation values and highlight market moments where the value is positive and exceeds the attention threshold.
This indicator can be used for manual analysis when a trader needs to search for new price patterns within the historical series or to create complex formulas in estimating future prices.
What is autocorrelation?
Autocorrelation in trading is a statistical measure used to determine the presence of a relationship or pattern of dependence between values in a financial time series over time. It represents the correlation of past values in a series with its future values. In other words, autocorrelation in trading aims to identify if there are systematic relationships between the past prices or returns of a security or market and its future prices or returns. This analysis can be helpful in identifying patterns or trends that can be leveraged for informed trading decisions. The presence of autocorrelation may suggest that market prices or returns follow a certain pattern or trend over time.
Limitations of the model
It is important to note that autocorrelation does not necessarily imply a causal relationship between past and future values. Other variables or market factors may influence the dynamics of prices or returns, and therefore autocorrelation could be merely a random coincidence. Therefore, it is essential to carefully evaluate the results of autocorrelation analysis along with other information and trading strategies to make informed decisions.
How to use
The usage is very simple, you just need to add it to the current chart to activate the indicator.
From the user interface, you can manage two important features:
1. Lenght: the delay period applied to the historical series during the autocorrelation calculation can be managed from the user interface. By default, it is set to 20, which means that the autocorrelation ratio within the historical series is calculated with a delay of 20 bars.
2. Threshold: the threshold value that the autocorrelation level must meet can be managed from the user interface. By default, it is set to 0.50, which means that the autocorrelation value must be higher than this threshold to be considered valid and displayed on the chart.
3. Bar color: the color used to display the autocorrelation data and highlight the bars when autocorrelation is valid can be managed from the user interface.
To set up the chart
We recommend disabling the 'wick' and 'border' of the candlesticks from the chart settings for a high-quality user experience.
Z-Score Retracement Indicator Releasing the Z-Score Retracement Indicator
What it does:
The Z-Score retracement indicator operates similarly to Fibonacci retracements. It calculates the average, standard deviation and Z-Scores of a user defined period and will plot out the various Standard Deviation levels and price targets based on the period under analysis.
It will visually display the distance from the mean and which price targets correspond to which standard deviation. It is intended to aid traders in determining where the mean is and to calculate the probability of price targets and the probability of a regression to the mean.
How do you use it?
When you launch the indicator, it will ask you to identify the start period. I always try to identify periods where the most recent uptrend or downtrend has started, and then start the analysis from that point. When you plot it, the indicator will display the current strength of the trend in the same way that a regression or log-linear regression indicator would, by displaying the Pearson Correlation Coefficient:
Unlike with linear regression or log-linear regression, you don't necessarily need to have a strong up or downtrend to use the indicator, however it is ideal to find an area with a clear trend.
From there, you can clearly see the standard deviation zones:
The indicator will also display the current Standard Deviation of the last close price.
The centre line (a Z-Score of 0) corresponds to absolute neutrality and would be a regression to the mean. The price target for this area is also listed.
If you want to calculate the price of a specific Standard Deviation, you can! Launch the settings and select the input you would like:
Simply select whether you want to convert a Standard Deviation Z-Score to price or price to Z-Score. Then input the variable into the appropriate field. The indicator will then display the results in a table at the top right of the chart:
In the above image, you can see that a Z-Score of 0 (indicating absolute neutrality) on QQQ is equivalent to a price of 299.
Calculating Probability:
You can calculate probability by reference a Z-Score Table. I have discussed this in my previous Z-Score based indicators, but essentially, the rule of thumb is this:
Anything over + 2 standard deviations corresponds with roughly less than a 5 to 10% chance of continuation higher. I encourage you to check out the writeup on my Z-Score Probability Indicator for more information on the price use of Z-Score for probability determinations.
Concluding remarks:
And that is the indicator! Its pretty straight forward and its intended to be an added tool for regression and log-linear regression based traders to help visualize the actual distance from the mean a ticker is currently trading at.
Another thing to keep in mind is you can use this on the very small time frames as well. I have used this for day trading on the 5 and 1 minute timeframe to determine "regressions to the mean" on a much smaller level. Like here:
That's the indicator!
Hope you enjoy, leave your questions, comments and suggestions below, safe trades everyone!
Annualized Spot-Future DifferenceThe "Annualized Spot-Future Difference" indicator (ASFD) compares the closing prices of a futures contract and its underlying spot asset. It calculates the price difference between the two instruments and annualizes this difference to provide a standardized measure for comparison.
The indicator takes inputs for the futures ticker symbol and the spot ticker symbol, allowing flexibility in selecting the specific assets for analysis. Additionally, it allows the user to input the contract date, which represents the expiration date of the futures contract.
The ASFD indicator plots the annualized difference between the futures and spot prices. It calculates the price difference by subtracting the spot price from the futures price. To annualize this difference, it considers the remaining days to the contract expiration and scales the difference accordingly.
The annualized difference can provide insights into market expectations, as it reflects the market's perception of the future price movement of the underlying asset. A positive value indicates that the futures price is higher than the spot price, potentially suggesting bullish sentiment. Conversely, a negative value suggests bearish sentiment, with the futures price lower than the spot price.
Traders and analysts can utilize the ASFD indicator to identify potential opportunities for arbitrage or evaluate market sentiment regarding the underlying asset. By monitoring changes in the annualized difference over time, they can gain insights into market dynamics and make informed trading decisions.
It's important to note that the ASFD indicator relies on accurate and up-to-date pricing data for both the futures and spot assets. Traders should verify that the selected ticker symbols correspond to the desired instruments and ensure that the contract date aligns with the relevant futures contract expiration.
Overall, the ASFD indicator provides a quantitative measure of the annualized price difference between futures and spot assets, enabling traders and analysts to assess market expectations and identify potential trading opportunities.