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.
Statistics
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!
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.
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.
Z-Score Candles with ReversalsIn the process of releasing some of my Z-Score based indicators. This is the Z-Score Candle indicator.
What it does:
This converts the current candles into a z-score based candle over a 14 period lookback (adjustable but recommended to leave at 14).
It plots out the overbought/oversold areas using colours and will lookback over a user defined period of time to identify previous areas of bullish and bearish reversals.
Why Z-Score Candles?
Before we get into how to use it, I think its important to discuss why converting candles to a Z-Score is advantageous.
When we convert candlesticks to Z-Score, we have the ability to view areas of natural mathematical support and resistance (I want to clarify, when I saw mathematical support and resistance, it is kind of a misnomer, it is not the same as technical support and resistance. Its a measure of the natural tendency of things to revert to their mean and not deviate to extreme poles of their mean for prolonged period of time, I use the term mathematical support and resistance as it is something most traders are familiar with and operates similarly).
This is particularly helpful during trends. For example, if we take a look at the following BA chart:
In the chart above, you can see that despite BA not being on technical support (that red line), the indicator identified math support (the support was identified by the indicator looking at BA's natural deviations from its mean and seeing that, at that particular point in time, BA had deviated to an area that traditionally leads to reversals to the upside).
If we look at another example:
We can see in the chart above that, despite BA making a new high on the day and "breaking out" of previous resistance, BA was at math resistance being 3.0 Standard Deviations from its trading mean at the time. Thus, necessitating the pullback you see in the chart.
How to use it:
The indicator can be used similar to RSI and Stochastics or any other oscillator based indicator. The difference is, you can actually see the price action in terms of its relationship to its mean. What the means, is the indicator displays the current price action in terms of the ticker's relationship to its current mean and average. This permits us to see areas of rejection and support in relation to its current distance from neutrality. We can also see the various positions of each of the ticker's values from the mean. For example, we can see where the open is in relation to the average, the high and the low vs simply looking at a single variable (usually the close price).
The indicator will also highlight areas where the ticker has deviated to extreme ends of its mean (defined at a Z-Score of +/- 3.0). The picture below is an example of a bearish extreme:
And a bullish extreme:
You can see in both cases a reversal resulted almost immediately.
Inputs:
In the chart above, you can see the 3 main input sections.
Z-Score Lookback: This determines the lookback length for the Z-Score. The recommendation is to leave at 14, especially if you are a day trader.
SMA Inputs: The SMA (The white line) can be toggled off and on. You can also change the source to the High, Low, Close and Open Z-Score. You can adjust the lookback length of the SMA to your liking to assess trends. It does not need to be the same input as the Z-Score.
Reversal Inputs: The reversal inputs determines the length of lookback for the indicator to determine the most extreme bearish and bullish deviation from its mean. It is defaulted at 75 but can be adjusted based on preference. For more frequent signals, you can reduce the lookback length but be prepared for false signals in that case. You can also toggle off the reversal labels if you do not want them.
Concluding remarks:
And that is the Z-Score Candle indicator in a nutshell. Pretty self explanatory otherwise. It is more tailored to day traders. It is not a tool I would necessarily use for longer-term outlooks. I would use a simple Z-Score based indicator for that. But for active day trading, this is very helpful. That said, it can be used to look at longer term outlooks as well, but there are more powerful Z-Score based indicators for that (you can check out my own Z-Score indicator or my recently released Z-Score Probability Indicator which is more tailored for bigger picture outlooks).
Hope you enjoy, as always leave your comments, suggestions and questions below!
Safe trades to all!
Z-Score Probability IndicatorThis is the Z-Score Probability indicator. As many people like my original Z-Score indicator and have expressed more interest in the powers of the Z, I decided to make this indicator which shows additional powers of the Z-Score.
Z-Score is not only useful for measuring a ticker or any other variable’s distance from the mean, it is also useful to calculate general probability in a normal distribution set. Not only can it calculate probability in a dataset, but it can also calculate the variables within said dataset by using the Standard Deviation and the Mean of the dataset.
Using these 2 aspects of the Z-Score, you can, In principle, have an indicator that operates similar to Fibonacci retracement levels with the added bonus of being able to actually ascertain the realistic probability of said retracement.
Let’s take a look at an example:
This is a chart showing SPY on the daily timeframe. If we look at the current Z-Score level, we can see that SPY is pushing into the 2 to 3 Z-Score range. We can see two things from this:
1. We can see that a retracement to a Z-Score of 2 would correspond to a price of 425.26 based on the current dataset. And
2. We can see that the probability that SPY retraces to a Z-Score of 2 is around 0.9800 or 98%.
To take it one step further, we can look at the various other variables in the distribution. If we were to bet on SPY retracing back to -1 SDs, that would correspond to a price of around 397.15, with a probability of around 0.1600 or 16% (see image below):
Let’s say, we thought SPY would go to $440. Well, we can see that the probability SPY goes to 434.64 currently is pretty low. How do we know? Because the Z-Score table shows us the probability of values falling BELOW that Z-score level in the current distribution. So if we look at this example below:
We can see that 0.9998 or roughly 99% of values in the current SPY distribution will fall below 434.64. Thus, it may be unrealistic, at this point in time, to target said value.
So what is a Z-Score Table?
Well, I need to disclose/clarify that the Z-Score Table being displayed in this indicator does Z-Score probability a HUGE injustice. However, with the constraints what is realistic to fit into an indicator, I had to make it far more succinct. Let’s take a look at an actual Z-Score Table below:
Above is a look an the actual Z-Score table. How it works is you first identify you’re Z-Score and then find the corresponding value that relates to your score. The number displayed in the dataset represents the number of variables in the dataset/density distribution that fall BELOW that particular Z-score.
So, for example, if we have a Z-Score of -2.31, we can consult that table, go to the -2.3 then scroll across to the 0.01 to represent -2.31. We would see that this Z-Score corresponds to a 0.0104 probability zone (or essentially 1%) indicating that the majority of the variables in the distribution fall below that mean Z-score. In terms of tickers and stocks, that would mean it would theoretically be “overbought”.
So what does the indicator Z-Table tell us?
I have averaged out the data for the purposes of this indicator. However, you can also reference a manual Z-Table to get the exact probability for the current precise Z-Score. However, the reality is it doesn’t necessarily matter to be exact when it comes to tickers. The reason being, ticker’s are in constant flux, and by the time you identify that probability, the ticker will already be at a different level. So generalizations are okay in these circumstances, you just need to get the “gist” of where the distribution lies.
So how do I use the indicator?
Using the indicator is pretty straightforward. Once launched, you will see the current Z-Score of the ticker, the current levels based on the distribution and the summarized Z-Table.
The Z-Table will turn gray to indicate the zone the ticker is currently in. In this case, we can see that SPY currently is in the 2 SD Zone, meaning that 0.98 or 98% of the current dataset being shown falls below the price we are at:
When we launch the settings, we can see a few inputs.
Lookback Length: This determines the number of candles back we want to calculate the distribution for. It is defaulted to 75, but you can adjust it to whichever length you want.
SMA Length: The SMA is optional but defaults to on. If you want to see the smoothed trend of the Z-Score, this will do the trick. It does not need to be set to the same
length as the Z-Score lookback. Thus, if you want a more or less responsive SMA with, say, a larger dataset, then you can reduce the SMA length yourself.
Distribution Probability Fills: This simply colour codes the distribution zones / probability zones on the indicator.
Show Z-Table: This will display the summarized Z-Table.
Show SMA: As I indicated, the SMA is optional, you can toggle it on or off to see the overall Z-Score trend.
Concluding Remarks:
And that my friends is the Z-Score Probability Indicator.
I hope you all enjoy it and find it helpful. As always leave your comments, questions and suggestions below.
Safe trades to all and take care!