Machine Learning Cross-Validation Split & Batch HighlighterThis indicator is designed for traders and analysts who employ Machine Learning (ML) techniques for cross-validation in financial markets.
The script visually segments a selected range of historical price data into splits and batches, helping in the assessment of model performance over different market conditions.
User
Theory
In ML, cross-validation is a technique to assess the generalizability of a model, typically by partitioning the data into a set of "folds" or "splits." Each split acts as a validation set, while the others form the training set. This script takes a unique approach by considering the sequential nature of financial time series data, where random shuffling of data (as in traditional cross-validation) can disrupt the temporal order, leading to misleading results.
Chronological Integrity of Splits
Even if the order of the splits is shuffled for cross-validation purposes, the data within each split remains in its original chronological sequence. This feature is crucial for time series analysis, as it respects the inherent order-dependency of financial markets. Thus, each split can be considered a microcosm of market behavior, maintaining the integrity of trends, cycles, and patterns that could be disrupted by random sampling.
The script allows users to define the number of splits and the size of each batch within a split. By doing so, it maintains the chronological sequence of the data, ensuring that the validation set is representative of a future time period that the model would predict.
www.tradingview.com
Parameters
Number of Splits: Defines how many segments the selected data range will be divided into. Each split serves as a standalone testing ground for the ML model. (Up to 24)
Batch Size: Determines the number of bars (candles) in each batch within a split. Smaller batches can help pinpoint overfitting at a finer granularity.
Start Index: The bar index from where the historical data range begins. It sets the starting point for data analysis.
End Index: The bar index where the historical data range ends. It marks the cutoff for data to be included in the model assessment.
Usage
To use this script effectively:
1 - Input the Start Index and End Index to define the historical data range you wish to analyze.
2 - Adjust the Number of Splits to create multiple validation sets for cross-validation.
3 - Set the Batch Size to control the granularity of each validation set within the splits.
4 - The script will highlight the background of each batch within the splits using alternating shades, allowing for a clear visual distinction of the data segmentation.
By maintaining the temporal sequence and allowing for adjustable granularity, the "ML Split and Batch Highlighter" aids in creating a robust validation framework for time series forecasting models in finance.
Pine utilities
Backtest any Indicator v5Happy Trade,
here you get the opportunity to backtest any of your indicators like a strategy without converting them into a strategy. You can choose to go long or go short and detailed time filters. Further more you can set the take profit and stop loss, initial capital, quantity per trade and set the exchange fees. You get an overall result table and even a detailed, scroll-able table with all trades. In the Image 1 you see the provided info tables about all Trades and the Result Summary. Further more every trade is marked by a background color, Labels and Levels. An opening Label with the trade direction and trade number. A closing Label again with the trade number, the trades profit in % and the total amount of $ after all past trades. A green line for the take profit level and a red line for the stop loss.
Image 1
Example
For this description we choose the Stochastic RSI indicator from TradingView as it is. In Image 2 is shown the performance of it with decent settings.
Timeframe=45, BTCUSD, 2023-08-01 - 2023-10-20
Stoch RSI: k=30, d=40, RSI-length=140, stoch-length=140
Backtest any Indicator: input signal=Stoch RSI, goLong, take profit=9.1%, stop loss=2.5%, start capital=1000$, qty=5%, fee=0.1%, no Session Filter
Image 2
Usage
1) You need to know the name of the boolean (or integer) variable of your indicator which hold the buy condition. Lets say that this boolean variable is called BUY. If this BUY variable is not plotted on the chart you simply add the following code line at the end of your pine script.
For boolean (true/false) BUY variables use this:
plot(BUY ? 1:0,'Your buy condition hold in that variable BUY',display = display.data_window)
And in case your script's BUY variable is an integer or float then use instate the following code line:
plot(BUY ,'Your buy condition hold in that variable BUY',display = display.data_window)
2) Probably the name of this BUY variable in your indicator is not BUY. Simply replace in the code line above the BUY with the name of your script's trade condition variable.
3) Save your changed Indicator script.
4) Then add this 'Backtest any Indicator' script to the chart ...
5) and go to the settings of it. Choose under "Settings -> Buy Signal" your Indicator. So in the example above choose .
The form is usually: ' : BUY'. Then you see something like Image 2
6) Decide which trade direction the BUY signal should trigger. A go Long or a go Short by set the hook or not.
Now you have a backtest of your Indicator without converting it into a strategy. You may change the setting of your Indicator to the best results and setup the following strategy settings like Time- and Session Filter, Stop Loss, Take Profit etc. More of it below in the section Settings Menu.
Appereance
In the Image 2 you see on the right side the List of Trades . To scroll down you go into the settings again and decrease the scroll value. So you can see all trades that have happened before. In case there is an open trade you will find it at the last position of the list.
Every Long trade is green back grounded while Short trades are red.
Every trade begins with a label that show goLong or goShort and its number. And ends with another label again with its number, Profit in % and the resulting total amount of cash.
If activated you further see the Take Profit as a green line and the Stop Loss as a orange line. In the settings you can set their percentage above or below the entry price.
You also see the Result Summary below. Here you find the usual stats of a strategy of all closed trades. The profit after total amount of fees , amount of trades, Profit Factor and the total amount of fees .
Settings Menu
In the settings menu you will find the following high-lighted sections. Most of the settings have a question mark on their right side. Move over it with the cursor to read specific explanation.
Input Signal of your Indicator: Under Buy you set the trade signal of your Indicator. And under Target you set the value when a trade should happen. In the Example with the Stochastic RSI above we used 20. Below you can set the trade direction, let it be go short when hooked or go long when unhooked.
Trade Settings & List of Trades: Take Profit set the target price of any trade. Stop Loss set the price to step out when a trade goes the wrong direction. Check mark the List of Trades to see any single trade with their stats. In case that there are more trades as fits in the list you can scroll down the list by decrease the value Scroll .
Time Filter: You can set a Start Time or deactivate it by leave it unhooked. The same with End Time .
Session Filter: here you can choose to activate it on weekly base. Which days of the week should be trading and those without. And also on daily base from which time on and until trade are possible. Outside of all times and sessions there will be no new trades if activated.
Invest Settings: here you can choose the amount of cash to start with. The Quantity percentage define for every trade how much of the cash should be invested and the Fee percentage which have to be payed every trade. Open position and closing position.
Other Announcements
This Backtest script don't use the strategy functions of TradingView. It is programmed as an indicator. All trades get executed at candle closing. This script use the functionality "Indicator-on-Indicator" from TradingView.
Conclusion
So now it is your turn, take your promising indicators and connect it to that Backtest script. With it you get a fast impression of how successful your indicator will trade. You don't have to relay on coders who maybe add cheating code lines. Further more you can check with the Time Filter under which market condition you indicator perform the best or not so well. Also with the Session Filter you can sort out repeating good market conditions for your indicator. Even you can check with the GoShort XOR GoLong check mark the trade signals of you indicator in opposite trade direction with one click. And compare your indicators under the same conditions and get the results just after 2 clicks. Thanks to the in-build fee setting you get an impression how much a 0.1% fee cost you in total.
Cheers
Position TrackerUse this tool to plot a trading position on the chart, using the guided confirmation prompts after adding to the chart.
To use this tool, after adding to the chart it will prompt for entry and exit time and entry price selection which will require using a mouse or touch screen to complete the action; the prompts appear at the bottom of the chart and are a blue bubble/box looking object :)
It will provide a readout of the live profit and loss, run-up and drawdown of a trade as well as present notes if added.
Visuals provide an easy look at periods of drawdown, and a anchored vwap is included as a simple guide for trade management.
Setting the symbol will allow many instances of the tool on the same layout and each instance will hide it's display while not on the matching symbol chart.
Once the end time for the trade is met, the label with trade breakdown thoughtfully moves away from active price and can be seen by scrolling to trade entry area.
If there's enough interest I will add some additional features but wanted to start simple. Or feel free to copy and make it your own!
Thanks and happy trading.
Monitor XThe Monitor X Indicator is a dynamic tool designed for any trading symbol, providing a quick and intuitive snapshot of price action relative to the latest closing level. With a user-friendly interface, this indicator allows traders to effortlessly gauge price movement and key levels.
Key Features:
1. Symbol Agnosticism:
Universally applicable to any trading symbol, the Monitor X Indicator ensures versatility and adaptability across various financial instruments.
2. Instant Price Insight:
Obtain immediate clarity on current market dynamics with a single glance. The indicator prominently displays the price line, facilitating swift analysis.
3. Last Close Comparison:
Easily assess the price's relationship to the most recent closing level. This feature provides valuable context for understanding market sentiment and potential support/resistance areas.
4. Customizable Display:
Tailor the indicator to your preferences with adjustable settings for line color, width, and opacity. This customization empowers traders to align the indicator with their unique trading strategies.
5. Intuitive Interface:
The clean and intuitive interface ensures a seamless user experience. Access crucial information effortlessly, allowing for quick decision-making.
How to Use:
1. Symbol Selection:
Apply the Monitor X Indicator to any trading symbol of your choice, ensuring a versatile tool for your entire portfolio.
2. Last Close Analysis:
Quickly assess how the current price relates to the previous close. This instant comparison aids in identifying potential entry and exit points.
3. Customization for Precision:
Fine-tune the indicator's appearance to suit your preferences. Adjust line colors, widths, and opacity settings for a personalized and efficient trading experience.
4. Swift Decision-Making:
Utilize the Monitor X Indicator for rapid decision-making. Gain insights into market movements at a glance, allowing you to stay ahead in dynamic trading environments.
Leveraged Share Decay Tracker [SS]Releasing this utility tool for leveraged share traders and investors.
It is very difficult to track the amount of decay and efficiency that is associated with leveraged shares and since not all leveraged shares are created equally, I developed this tool to help investors/traders ascertain:
1. The general risk, in $$, per share associated with investing in a particular leveraged ETF
2. The ability of a leveraged share to match what it purports to do (i.e. if it is a 3X Bull share, is it actually returning consistently 3X the underlying or is there a large variance?)
3. The general decay at various timepoints expressed in $$$
How to use:
You need to be opened on the chart of the underlying. In the example above, the chart is on DIA, the leveraged share being tracked is UDOW (3X bull share of the DOW).
Once you are on the chart of the underlying, you then put in the leveraged share of interest. The indicator will perform two major assessments:
1. An analysis of the standard error between the underlying and the leveraged share. This is accomplished through linear regression, but instead of creating a linreg equation, it simply uses the results to ascertain the degree of error associated at various time points (the time points are 10, 20, 30, 40, 50, 100, 252).
2. An analysis of the variance of returns. The indicator requires you to put in the leverage amount. So if the leverage amount is 3% (i.e. SPXL or UPRO is 3 X SPY), be sure that you are putting that factor in the settings. It will then modify the underlying to match the leverage amount, and perform an assessment of variance over 10, 20, 30, 40, 50, 100, 252 days to ensure stability. This will verify whether the leveraged ETF is actually consistently performing how it purports to perform.
Here are some examples, and some tales of caution so you can see, for yourself, how not all leveraged shares are created equal.
SPY and SPXL:
SPY and UPRO:
XBI and LABU (3 x bull share):
XBI and LABD (3 x bear share):
SOX and SOXL:
AAPL and AAPU:
It is VERY pivotal you remember to check and adjust the Leveraged % factor.
For example, AAPU is leveraged 1.5%. You can see above it tracks this well. However, if you accidently leave it at 3%, you will get an erroneous result:
You can also see how some can fail to track the quoted leveraged amount, but still produce relatively lower risk decay.
And, as a final example, let's take a look at the worst leveraged share of life, BOIL:
Trainwreck that one. Stay far away from it!
The chart:
The chart will show you the drift (money value over time) and the variance (% variance between the expected and actual returns) over time. From here, you can ascertain the general length you feel comfortable holding a leveraged share. In general, for most stable shares, <= 50 trading days tends to be the sweet spot, but always check the chart.
There are also options to plot the variances and the drifts so you can see them visually.
And that is the indicator! Kind of boring, but there are absolutely 0 resources out there for doing this job, so hopefully you see the use for it!
Safe trades everyone!
Christmas Toolkit [LuxAlgo]It's that time of the year... and what would be more appropriate than displaying Christmas-themed elements on your chart?
The Christmas Toolkit displays a tree containing elements affected by various technical indicators. If you're lucky, you just might also find a precious reindeer trotting toward the tree, how fancy!
🔶 USAGE
Each of the 7 X-mas balls is associated with a specific condition.
Each ball has a color indicating:
lime: very bullish
green: bullish
blue: holding the same position or sideline
red: bearish
darkRed: very bearish
From top to bottom:
🔹 RSI (length 14)
rsi < 20 - lime (+2 points)
rsi < 30 - green (+1 point)
rsi > 80 - darkRed (-2 points)
rsi > 70 - red (-1 point)
else - blue
🔹 Stoch (length 14)
stoch < 20 - lime (+2 points)
stoch < 30 - green (+1 point)
stoch > 80 - darkRed (-2 points)
stoch > 70 - red (-1 point)
else - blue
🔹 close vs. ema (length 20)
close > ema 20 - green (+1 point)
else - red (-1 point)
🔹 ema (length 20)
ema 20 rises - green (+1 point)
else - red (-1 point)
🔹 ema (length 50)
ema 50 rises - green (+1 point)
else - red (-1 point)
🔹 ema (length 100)
ema 100 rises - green (+1 point)
else - red (-1 point)
🔹 ema (length 200)
ema 200 rises - green (+1 point)
else - red (-1 point)
The above information can also be found on the right side of the tree.
You'll see the conditions associated with the specific X-mas ball and the meaning of color changes. This can also be visualized by hovering over the labels.
All values are added together, this result is used to color the star at the top of the tree, with a specific color indicating:
lime: very bullish (> 6 points)
green: bullish (6 points)
blue: holding the same position or sideline
red: bearish (-6 points)
darkRed: very bearish (< -6 points)
Switches to green/lime or red/dark red can be seen by the fallen stars at the bottom.
The Last Switch indicates the latest green/lime or red/dark red color (not blue)
🔶 ANIMATION
Randomly moving snowflakes are added to give it a wintry character.
There are also randomly moving stars in the tree.
Garland rotations, style, and color can be adjusted, together with the width and offset of the tree, put your tree anywhere on your chart!
Disabling the "static tree" setting will make the needles 'move'.
Have you happened to see the precious reindeer on the right? This proud reindeer moves towards the most recent candle. Who knows what this reindeer might be bringing to the tree?
🔶 SETTINGS
Width: Width of tree.
Offset: Offset of the tree.
Garland rotations: Amount of rotations, a high number gives other styles.
Color/Style: sets the color & style of garland stars.
Needles: sets the needle color.
Static Tree: Allows the tree needles to 'move' with each tick.
Reindeer Speed: Controls how fast the deer moves toward the most recent bar.
🔶 MESSAGE FROM THE LUXALGO TEAM
It has been an honor to contribute to the TradingView community and we are always so happy to see your supportive messages on our scripts.
We have posted a total of 78 script publications this year, which is no small feat & was only possible thanks to our team of Wizard developers @alexgrover + @dgtrd + @fikira , the development team behind Pine Script, and of course to the support of our legendary community.
Happy Holidays to you all, and we'll see ya next year! ☃️
Momentum Candle
bar’s open price (open) from its close price (close). That gives the size of the bar’s body.
The difference between the open and closed is the candle’s body range.
The colour of a candle’s body shows the direction of prices.
if Close > Open then it's Bullish Body Candle & if close < open then it's Bearish Body Candle.
Stronger the interest of buyers or sellers is reflected in the formation of the Body of Candle.
When the body is indeed more than 50% bigger than the average size of a candle
then it will show Momentum on the chart.
we can see the Colour of the candle Changes When it is Stronger than the Average candle & Body size is Bigger than the Average Candle size.
Depending upon Bullish or Bearish the candle Colour Changes to Indicate the Strong Presence of the Buyer or Seller
The Candle which strong but not solid and above Average then it will show Normal Colour Of Candle and the Candle which is Below Average will have no colour on Volume Like Bars on the Chart & chart no effect on the candle colour.
Buyer or Seller's Activity is always reflected in Candle. This helps us to make Trade Decisions.
If Solid Candle at Support or Resistance give or add more Conviction. If Found At Support or resistance will act as Reversal. If found at Swing Low or Retracement, it will help to take trade accordingly with the main trend.
Solid Candle Helps in Good Risk to Reward. Mark the High and Low Of the Strong Candle and observe the Price Action.
as long as the candle is trading below average helps us to take action for Range Breakout & saves us from Taking Entry in Range.
The Distribution at the Top and consolidation at the Bottom can be Observed by the Behaviour of Candles on the Chart.
The candle is always a little first step of price action, Whatever Happens in the market is always first printed in a candle,
The Leader Candle or Momentum Candle with Follow always Decides the Trend.
It's Simple But useful in Day Trading as well as in Swing Trading or Positional Trading too
Opening/Closing Highs and LowsDescription:
This indicator tracks the daily, monthly, and yearly opening, closing, highs, and lows in the stock market. It's designed to display crucial price points within different time frames, aiding traders in assessing significant market movements.
Features:
Daily View: Shows the opening, closing, highest, and lowest prices within each trading day.
Monthly Overview: Highlights the monthly opening, closing, highs, and lows to offer insights into broader market trends.
Yearly Perspective: Presents the annual opening, closing, highs, and lows, aiding in long-term market analysis.
How to Use:
Daily Analysis: Monitor daily fluctuations and spot intraday trends by observing the daily opening/closing ranges.
Monthly Trends: Identify monthly patterns by reviewing the monthly opening/closing levels.
Yearly Insights: Gain a broader perspective on yearly market movements by analyzing the annual highs and lows
Backtesting ModuleDo you often find yourself creating new 'strategy()' scripts for each trading system? Are you unable to focus on generating new systems due to fatigue and time loss incurred in the process? Here's a potential solution: the 'Backtesting Module' :)
INTRODUCTION
Every trading system is based on four basic conditions: long entry, long exit, short entry and short exit (which are typically defined as boolean series in Pine Script).
If you can define the conditions generated by your trading system as a series of integers, it becomes possible to use these variables in different scripts in efficient ways. (Pine Script is a convenient language that allows you to use the integer output of one indicator as a source in another.)
The 'Backtesting Module' is a dynamic strategy script designed to adapt to your signals. It boasts two notable features:
⮞ It produces a backtest report using the entry and exit variables you define.
⮞ It not only serves for system testing but also to combine independent signals into a single system. (This functionality enables to create complex strategies and report on their success!)
The module tests Golden and Death cross signals by default, when you enter your own conditions the default signals will be neutralized. The methodology is described below.
PREPARATION
There are three simple steps to connect your own indicator to the Module.
STEP 1
Firstly, you must define entry and exit variables in your own script. Let's elucidate it with a straightforward example. Consider a system generating long and short signals based on the intersections of two moving averages. Consequently, our conditions would be as follows:
// Signals
long = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
short = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
Now, the question is: How can we convert boolean variables into integer variables? The answer is conditional ternary block, defined as follows:
// Entry & Exit
long_entry = long ? 1 : 0
long_exit = short ? 1 : 0
short_entry = short ? 1 : 0
short_exit = long ? 1 : 0
The mechanics of the Entry & Exit variables are simple. The variable takes on a value of 1 when your trading system generates the signal and if your system does not produce any signal, variable returns 0. In this example, you see how exit signals can be generated in a trading system that only contains entry signals. If you have a system with original exit signals, you can also use them directly. (Please mind the NOTES section below).
STEP 2
To utilize the Entry & Exit variables as source in another script, they must be plotted on the chart. Therefore, the final detail to include in the script containing your trading system would be as follows:
// Plot The Output
plot(long_entry, "Long Entry", display=display.data_window, editable=false)
plot(long_exit, "Long Exit", display=display.data_window, editable=false)
plot(short_entry, "Short Entry", display=display.data_window, editable=false)
plot(short_exit, "Short Exit", display=display.data_window, editable=false)
STEP 3
Now, we are ready to test the system! Load the Backtesting Module indicator onto the chart along with your trading system/indicator. Then set the outputs of your system (Long Entry, Long Exit, Short Entry, Short Exit) as source in the module. That's it.
FEATURES & ORIGINALITY
⮞ Primarily, this script has been created to provide you with an easy and practical method when testing your trading system.
⮞ I thought it might be nice to visualize a few useful results. The Backtesting Module provides insights into the outcomes of both long and short trades by computing the number of trades and the success percentage.
⮞ Through the 'Trade' parameter, users can specify the market direction in which the indicator is permitted to initiate positions.
⮞ Users have the flexibility to define the date range for the test.
⮞ There are optional features allowing users to plot entry prices on the chart and customize bar colors.
⮞ The report and the test date range are presented in a table on the chart screen. The entry price can be monitored in the data window.
⮞ Note that results are based on realized returns, and the open trade is not included in the displayed results. (The only exception is the 'Unrealized PNL' result in the table.)
STRATEGY SETTINGS
The default parameters are as follows:
⮞ Initial Balance : 10000 (in units of currency)
⮞ Quantity : 10% of equity
⮞ Commission : 0.04%
⮞ Slippage : 0
⮞ Dataset : All bars in the chart
For a realistic backtest result, you should size trades to only risk sustainable amounts of equity. Do not risk more than 5-10% on a trade. And ALWAYS configure your commission and slippage parameters according to pessimistic scenarios!
NOTES
⮞ This script is intended solely for development purposes. And it'll will be available for all the indicators I publish.
⮞ In this version of the module, all order types are designed as market orders. The exit size is the sum of the entry size.
⮞ As your trading conditions grow more intricate, you might need to define the outputs of your system in alternative ways. The method outlined in this description is tailored for straightforward signal structures.
⮞ Additionally, depending on the structure of your trading system, the backtest module may require further development. This encompasses stop-loss, take-profit, specific exit orders, quantity, margin and risk management calculations. I am considering releasing improvements that consider these options in future versions.
⮞ An example of how complex trading signals can be generated is the OTT Collection. If you're interested in seeing how the signals are constructed, you can use the link below.
THANKS
Special thanks to PineCoders for their valuable moderation efforts.
I hope this will be a useful example for the TradingView community...
DISCLAIMER
This is just an indicator, nothing more. It is provided for informational and educational purposes exclusively. The utilization of this script does not constitute professional or financial advice. The user solely bears the responsibility for risks associated with script usage. Do not forget to manage your risk. And trade as safely as possible. Best of luck!
Backtester UtilityLook ahead bias is the most evil bias responsible for overestimation of the performance of the trading system.
As the Bar replay feature is only available to paid users which is a great tool for manual testing of the trading system. Leaving other users prone to the evil of Look ahead bias.
So that I have developed this indicator which will help users to manually backtest the strategies.
This indicator hides the price action after specified date and time.
Here are the steps for using the indicator.
1) Hide your chart manually.
2) Plot the indicator.
3) Change the input of time and date after which you want to hide price action.
4) Change the script according to your trading strategy.
5) Enjoy the free of cost manual backtesting.
Good trading buddies !
Note : This post is only for educational purpose , it does not contain any financial advise.
Customizable Vertical LinesCustomizable Vertical Lines (CVL) Indicator
Version 2.0 (November 2023)
Description:
The Customizable Vertical Lines (CVL) indicator is a powerful tool for traders who want to mark specific times on their charts with vertical lines. This indicator allows users to customize the appearance of these lines, including their color, line style, and width, providing a flexible and visually intuitive way to highlight key time points.
Key Features:
User-Friendly Inputs: Easily set up to five distinct times, each associated with a unique color for the vertical lines.
Color Customization: Choose from a wide range of colors for each vertical line, allowing for clear differentiation.
Line Style Options: Tailor the appearance of the lines with three selectable styles: solid, dotted, or dashed.
Adjustable Line Width: Modify the thickness of the lines to suit your preferred visual style.
Timezone Offset: Account for different time zones by adjusting the timezone offset parameter.
How to Use:
Simply input the desired times, colors, and other parameters in the script settings. The CVL indicator will then automatically plot vertical lines at the specified times on the chart with the chosen customization.
SuperTrend ToolkitThe SuperTrend Toolkit (Super Kit) introduces a versatile approach to trend analysis by extending the application of the SuperTrend indicator to a wide array of @TradingView's built-in or Community Scripts . This tool facilitates the integration of the SuperTrend algorithm with various indicators, including oscillators, moving averages, overlays, and channels.
Methodology:
The SuperTrend, at its core, calculates a trend-following indicator based on the Average-True-Range (ATR) and price action. It creates dynamic support and resistance levels, adjusting to changing market conditions, and aiding in trend identification.
pine_st(simple float factor = 3., simple int length = 10) =>
float atr = ta.atr(length)
float up = hl2 + factor * atr
up := up < nz(up ) or close > nz(up ) ? up : nz(up )
float lo = hl2 - factor * atr
lo := lo > nz(lo ) or close < nz(lo ) ? lo : nz(lo )
int dir = na
float st = na
if na(atr )
dir := 1
else if st == nz(up )
dir := close > up ? -1 : 1
else
dir := close < lo ? 1 : -1
st := dir == -1 ? lo : up
@TradingView's native SuperTrend lacks the flexibility to incorporate different price sources into its calculation.
Community scripts, addressed the limitation by implementing the option to input different price sources, for example, one of the most popular publications, @KivancOzbilgic's SuperTrend script.
In May 2023, @TradingView introduced an update allowing the passing of another indicator's plot as a source value via the input.source() function. However, the built-in ta.atr function still relied on the chart's price data, limiting the formerly mentioned scripts to the chart's price data alone.
Unique Approach -
This script addresses the aforementioned limitations by processing the data differently.
Firstly we create a User-Defined-Type (UDT) replicating a bar's open, high, low, close (OHLC) values.
type bar
float o = open
float h = high
float l = low
float c = close
We then use this type to store the external input data.
src = input.source(close, "External Source")
bar b = bar.new(
nz(src ) , open 𝘷𝘢𝘭𝘶𝘦
math.max(nz(src ), src), high 𝘷𝘢𝘭𝘶𝘦
math.min(nz(src ), src), low 𝘷𝘢𝘭𝘶𝘦
src ) close 𝘷𝘢𝘭𝘶𝘦
Finally, we pass the data into our custom built SuperTrend with ATR functions to derive the external source's version of the SuperTrend indicator.
supertrend st = b.st(mlt, len)
- Setup Guide -
Utility and Use Cases:
Universal Compatibility - Apply SuperTrend to any built-in indicator or script, expanding its use beyond traditional price data.
- A simple example on one of my own public scripts -
Trend Analysis - Gain additional trend insights into otherwise mainly mean reverting or volume indicators.
- Alerts Setup Guide -
The Super Kit empowers traders and analysts with a tool that adapts the robust SuperTrend algorithm to a myriad of indicators, allowing comprehensive trend analysis and strategy development.
Data from dataThe "Data from Data" indicator, developed by OmegaTools, is a sophisticated and versatile tool designed to offer a nuanced analysis of various market dynamics, catering to traders and investors seeking a comprehensive understanding of price movements considering a large amount of data and variables.
The uses of this indicator are nonconventional. You can use the indicator as a stand-alone tool on the chart, hiding the current symbol price data, to be able to analyze the price action with the Semaphore visualization method, you can also hide the indicator and choose from your favorite indicators and oscillator one of the data output as a source to have additional insight on the asset.
The last use of this indicator, which depends on the X Value that you set in the settings, is to have a possible scenario for the future outcomes of the markets. Remember that there is no tool that can really predict what the market will do in the future, this tool applies a large amount of formulas to use past prices as an indication that aims to be as close as possible to the future prices. The X Value not only changes the lookback of the formulas but also changes the number of future scenarios that the indicator will plot on the chart.
Key Features:
1. Rate of Change Analysis:
The indicator evaluates the rate of change variations in closing prices, providing insights into the current rate of change and expected rate of change variation.
2. Momentum Analysis:
Momentum is analyzed through calculations involving simple moving averages, offering expected values derived from momentum and momentum variation.
3. High/Low Variation:
The expected market behavior is assessed based on the average variation between high and low prices, contributing to a more holistic analysis.
4. Liquidity Targets:
Liquidity targets can be found by analyzing the highs and lows in the direction of the current fair price.
5. Regression Sequence:
Linear regression analysis is applied to closing prices, assessing momentum and providing expected values based on regression sequences.
6. Volume Presence:
The indicator evaluates the Rate of Change (ROC) by volume presence, offering insights into price movements influenced by trading volume.
7. Liquidity Grabs:
Expected market behavior is determined based on liquidity grabs, considering both current and historical price levels.
8. Fair Value Analysis:
Expected values are derived from fair value closes and fair value highs and lows, contributing to a more nuanced analysis of market conditions.
9. STT (Sequential Trend Test):
The Sequential Trend Test is employed to analyze market trends, providing expected values for a more informed decision-making process.
Visualization:
The indicator shows a "Semaphore" on the chart, visually representing all of the data extrapolated from the script. The visualization can be more minimalistic or more complex, to let the user decide that, in the settings, it's possible to decide if to show all of the data or only the average.
Additionally, the user can choose to display bars on the chart, that visualize the standard high and low of the price data, with the difference between the expected forecasted value and the actual closing price.
My suggestion is to try to change the colors of the data to fit best your eye and the data that you find more useful, and also to try to change some parameters from circle to line as a visualization method to catch with more ease some price patterns.
Error Analysis:
The indicator provides a detailed error analysis, including historical error, average error, and present error. This information is presented in a user-friendly table for quick reference. This table can be used to analyze the margin of error of the expected future price.
KNN Regression [SS]Another indicator release, I know.
But note, this isn't intended to be a stand-alone indicator, this is just a functional addition for those who program Machine Learning algorithms in Pinescript! There isn't enough content here to merit creating a library for (it's only 1 function), but it's a really useful function for those who like machine learning and Nearest Known Neighbour Algos (or KNN).
About the indicator:
This indicator creates a function to perform KNN-based regression.
In contrast to traditional linear regression, KNN-based regression has the following advantages over linear regression:
Advantages of KNN Regression vs. Linear Regression:
🎯 Non-linearity: KNN is a non-parametric method, meaning it makes no assumptions about the underlying data distribution. This allows it to capture non-linear relationships between features and the target variable.
🎯Simple Implementation: KNN is conceptually simple and easy to understand. It doesn't require the estimation of parameters, making it straightforward to implement.
🎯Robust to Outliers: KNN is less sensitive to outliers compared to linear regression. Outliers can have a significant impact on linear regression models, but KNN tends to be less affected.
Disadvantages of KNN Regression vs. Linear Regression:
🎯 Resource Intensive for Computation: Because KNN operates on identifying the nearest neighbors in a dataset, each new instance has to be searched for and identified within the dataset, vs. linear regression which can create a coefficient-based model and draw from the coefficient for each new data point.
🎯Curse of Dimensionality: KNN performance can degrade with an increasing number of features, leading to a "curse of dimensionality." This is because, in high-dimensional spaces, the concept of proximity becomes less meaningful.
🎯Sensitive to Noise: KNN can be sensitive to noisy data, as it relies on the local neighborhood for predictions. Noisy or irrelevant features may affect its performance.
Which is better?
I am very biased, coming from a statistics background. I will always love linear regression and will always prefer it over KNN. But depending on what you want to accomplish, KNN makes sense. If you are using highly skewed data or data that you cannot identify linearity in, KNN is probably preferable.
However, if you require precise estimations of ranges and outliers, such as creating co-integration models, I would advise sticking with linear regression. However, out of curiosity, I exported the function into a separate dummy indicator and pulled in data from QQQ to predict SPY close, and the results are actually very admirable:
And plotted with showing the standard error variance:
Pretty impressive, I must say I was a little shocked, it's really giving linear regression a run for its money. In school I was taught LinReg is the gold standard for modeling, nothing else compares. So as with most things in trading, this is challenging some biases of mine ;).
Functionality of the function
I have permitted 3 types of KNN regression. Traditional KNN regression, as I understand it, revolves around clustering. ( Clustering refers to identifying a cluster, normally 3, of identical cases and averaging out the Dependent variable in each of those cases) . Clustering is great, but when you are working with a finite dataset, identifying exact matches for 2 or 3 clusters can be challenging when you are only looking back at 500 candles or 1000 candles, etc.
So to accommodate this, I have added a functionality to clustering called "Tolerance". And it allows you to set a tolerance level for your Euclidean distance parameters. As a default, I have tested this with a default of 0.5 and it has worked great and no need to change even when working with large numbers such as NQ and ES1!.
However, I have added 2 additional regression types that can be done with KNN.
#1 One is a regression by the last IDENTICAL instance, which will find the most recent instance of a similar Independent variable and pull the Dependent variable from that instance. Or
#2 Average from all IDENTICAL instances.
Using the function
The code has the instructions for integrating the function into your own code, the parameters, and such, so I won't exhaust you with the boring details about that here.
But essentially, it exports 3, float variables, the Result, the Correlation, and the simplified R2.
As this is KNN regression, there are no coefficients, slopes, or intercepts and you do not need to test for linearity before applying it.
Also, the output can be a bit choppy, so I tend to like to throw in a bit of smoothing using the ta.sma function at a deault of 14.
For example, here is SPY from QQQ smoothed as a 14 SMA:
And it is unsmoothed:
It seems relatively similar but it does make a bit of an aesthetic difference. And if you are doing it over 14, there is no data loss and it is still quite reactive to changes in data.
And that's it! Hopefully you enjoy and find some interesting uses for this function in your own scripts :-).
Safe trades everyone!
Intersection Value FunctionsWinning entry for the first Pinefest contest. The challenge required providing three functions returning the intersection value between two series source1 and source2 in the event of a cross, crossunder, and crossover.
Feel free to use the code however you like.
🔶 CHALLENGE FUNCTIONS
🔹 crossValue()
//@function Finds intersection value of 2 lines/values if any cross occurs - First function of challenge -> crossValue(source1, source2)
//@param source1 (float) source value 1
//@param source2 (float) source value 2
//@returns Intersection value
example:
value = crossValue(close, close )
🔹 crossoverValue()
//@function Finds intersection value of 2 lines/values if crossover occurs - Second function of challenge -> crossoverValue(source1, source2)
//@param source1 (float) source value 1
//@param source2 (float) source value 2
//@returns Intersection value
example:
value = crossoverValue(close, close )
🔹 crossunderValue()
//@function Finds intersect of 2 lines/values if crossunder occurs - Third function of challenge -> crossunderValue(source1, source2)
//@param source1 (float) source value 1
//@param source2 (float) source value 2
//@returns Intersection value
example:
value = crossunderValue(close, close )
🔶 DETAILS
A series of values can be displayed as a series of points, where the point location highlights its value, however, it is more common to connect each point with a line to have a continuous aspect.
A line is a geometrical object connecting two points, each having y and x coordinates. A line has a slope controlling its steepness and an intercept indicating where the line crosses an axis. With these elements, we can describe a line as follows:
slope × x + intercept
A cross between two series of values occurs when one series is greater or lower than the other while its previous value isn't.
We are interested in finding the "intersection value", that is the value where two crossing lines are equal. This problem can be approached via linear interpolation.
A simple and direct approach to finding our intersection value is to find the common scaling factor of the slopes of the lines, that is the multiplicative factor that multiplies both lines slopes such that the resulting points are equal.
Given:
A = Point A1 + m1 × scaling_factor
B = Point B1 + m2 × scaling_factor
where scaling_factor is the common scaling factor, and m1 and m2 the slopes:
m1 = Point A2 - Point A1
m2 = Point B2 - Point B1
In our cases, since the horizontal distance between two points is simply 1, our lines slopes are equal to their vertical distance (rise).
Under the event of a cross, there exists a scaling_factor satisfying A = B , which allows us to directly compute our intersection value. The solution is given by:
scaling_factor = (B1 - A1)/(m1 - m2)
As such our intersection value can be given by the following equivalent calculations:
(1) A1 + m1 × (B1 - A1)/(m1 - m2)
(2) B1 + m2 × (B1 - A1)/(m1 - m2)
(3) A2 - m2 × (A2 - B2)/(m1 - m2)
(4) B2 - m2 × (A2 - B2)/(m1 - m2)
The proposed functions use the third calculation.
This approach is equivalent to expressions using the classical line equation, with:
slope1 × x + intercept1 = slope2 × x + intercept2
By solving for x , the intersection point is obtained by evaluating any of the line equations for the obtained x solution.
🔶 APPLICATIONS
The intersection point of two crossing lines might lead to interesting applications and creations, in this section various information/tools derived from the proposed calculations are presented.
This supplementary material is available within the script.
🔹 Intersections As Support/Resistances
The script allows extending the lines of the intersection value when a cross is detected, these extended lines could have applications as support/resistance lines.
🔹 Using The Scaling Factor
The core of the proposed calculation method is the common scaling factor, which can be used to return useful information, such as the position of the cross relative to the x coordinates of a line.
The above image highlights two moving averages (in green and red), the cross-interval areas are highlighted in blue, and the intersection point is highlighted as a blue line.
The pane below shows a bar plot displaying:
1 - scaling factor = 1 -
Values closer to 1 indicate that the cross location is closer to x2 (the right coordinate of the lines), while values closer to 0 indicate that the cross location is closer to x1 .
🔹 Intersection Matrix
The main proposed functions of this challenge focus on the crossings between two series of values, however, we might be interested in applying this over a collection of series.
We can see in the image above how the lines connecting two points intersect with each other, we can construct a matrix populated with the intersection value of two corresponding lines. If (X, Y) represents the intersection value between lines X and Y we have the following matrix:
| Line A | Line B | Line C | Line D |
-------|--------|--------|--------|--------|
Line A | | (A, B) | (A, C) | (A, D) |
Line B | (B, A) | | (B, C) | (B, D) |
Line C | (C, A) | (C, B) | | (C, D) |
Line D | (D, A) | (D, B) | (D, C) | |
We can see that the upper triangular part of this matrix is redundant, which is why the script does not compute it. This function is provided in the script as intersectionMatrix :
//@function Return the N * N intersection matrix from an array of values
//@param array_series (array) array of values, requires an array supporting historical referencing
//@returns (matrix) Intersection matrix showing intersection values between all array entries
In the script, we create an intersection matrix from an array containing the outputs of simple moving averages with a period in a specific user set range and can highlight if a simple moving average of a certain period crosses with another moving average with a different period, as well as the intersection value.
🔹 Magnification Glass
Crosses on a chart can be quite small and might require zooming in significantly to see a detailed picture of them. Using the obtained scaling factor allows reconstructing crossing events with an higher resolution.
A simple supplementary zoomIn function is provided to this effect:
//@function Display an higher resolution representation of intersecting lines
//@param source1 (float) source value 1
//@param source2 (float) source value 2
//@param css1 (color) color of source 1 line
//@param css2 (color) color of source 2 line
//@param intersec_css (color) color of intersection line
//@param area_css (color) color of box area
Users can obtain a higher resolution by modifying the provided "Resolution" setting.
The function returns a higher resolution representation of the most recent crosses between two input series, the intersection value is also provided.
Trend Line XrossTrend Line Xross (TLX) Uses User Input Points to draw trendlines and displays the exact intersection point of those trendlines.
This is the public indicator of the practical application for this intersection method included in my entry for Pinefest #1.
To determine the exact intersection point I am using the y-intercept method as seen below.
The code is notated for more information on the technical workings.
One difference to note between this version and the pinefest version is that I had to change the line drawings to use bar_index values so that I can use line.get_price() to grab the current value of the line to make alerts from.
Additionally, there are alerts built-in to this version for every type of cross on all of the visible lines.
Enjoy!
TUE Renko Box/Time TesterThe TUE Renko Box/Time Tester is a technical indicator designed to quantify the frequency of consecutive duplicate timestamps within Renko charts on the TradingView platform. It serves the critical purpose of assessing the prevalence of identical timestamps, a crucial factor for the accurate automation of trading strategies.
The presence of duplicate timestamps can impede the reliability of automated trading systems. This indicator systematically examines Renko bars and identifies instances where successive bars share the same timestamp. The quantified data aids traders and developers in evaluating the quality and suitability of their Renko chart data for algorithmic trading purposes.
To ensure proper speed and precision in automation, traders are advised to run Renko charts on either 1-second or 5-second timeframes. Adjusting the box sizes of Renko charts based on these timeframes is essential.
The objective is to maintain the incidence of duplicate timestamps at levels below 20%, ensuring the robustness and consistency of automated trading strategies. By providing a quantitative analysis of timestamp duplication, this indicator supports traders in optimizing their trading systems for enhanced accuracy and efficiency.
The script will automatically collate only the last two days' worth of data, in order to maintain timestamp integrity. You should be able to view individual seconds on your timestamps, and if they're all reading :00 at the end, then you have ran out of seconds-level data. This is only done with a Premium or higher subscription.
Get start of previous day on any timeframeUseful on pine scripts which need to identify the start of the previous trading day i.e. from the perspective of today's date - not the previous day on each bar calculation.
Works on any timeframe - which is the whole point as on a daily chart you can simply do time .
VWAP (Any Anchor)Hello Traders,
Introduction:
The Volume Weighted Average Price (VWAP) is a powerful trading indicator used to gauge the average price at which an asset has traded, weighted by volume, over a specific period.
One of the key factors that can significantly impact the effectiveness of VWAP is the concept of "anchoring." In this TradingView indicator script description, we'll explore the concept of anchoring and how it's integrated into a customizable VWAP indicator.
Understanding Anchoring:
Anchoring in VWAP refers to selecting a specific point in time from which the VWAP calculation begins.
This "anchor point" serves as the starting reference for VWAP, and it can substantially impact the indicator's behavior and interpretation.
Anchoring allows traders to adapt VWAP to different trading strategies and scenarios.
Here are some common anchor points used in the script and their significance:
1. Time-Based Anchors: Traders often anchor VWAP to specific times of the trading day, such as the market open (e.g., 9:30 am EST) or close (e.g., 4:00 pm EST).
You could add in the script any time-based anchor you think is relevant for your trading.
2. Event-Based Anchors: Anchoring can also be based on specific market events.
For example, some traders anchor VWAP to events like "3 Consecutive Green Candles" or "Supertrend" direction changes.
Feel free to adapt the script here and add the relevant events-based anchor for your trading.
3. Multi-Timeframe Anchoring: Traders can anchor VWAP on different timeframes, allowing them to analyze price and volume interactions across various horizons.
This flexibility is especially valuable for swing traders adapting to longer-term trends.
Anchor Selection
Traders can choose from various anchor points, including time-based, event-based, and even an "External Connector" for flexibility in adapting VWAP to specific scenarios.
The External connector is the output from another script used in this VWAP script.
Your script may have a condition being “true” whenever a signal is printed - you can use this signal as the anchor for the VWAP.
Conclusion:
Understanding anchoring in VWAP is essential for traders using this indicator effectively.
Choosing and customizing anchor points empowers traders to adapt VWAP to their specific trading styles and strategies.
Whether focused on intraday precision or analyzing longer-term trends, a customizable VWAP indicator with flexible anchoring options can be valuable to your trading toolkit.
Tailor your VWAP to your unique needs and gain deeper insights into market trends and price action.
Made with love
Dave
syminfo tableThis is nothing special, and it is not an indicator for investments.
I build this for my programming layout, so I can see all the output of the syminfo command.
Simply put...
It shows the commands on the left side,
and related outputs are on the right side.
TradingView.To Strategy Template (with Dyanmic Alerts)Hello traders,
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
This Pine Script v5 template facilitates the dynamic construction of TradingView.TO alerts, sparing users the time and effort of mastering the TradingView.TO syntax and manually create alert commands.
This powerful tool gives much power to those who don't know how to code in Pinescript and want to automate their indicators' signals via TradingView.TO bot.
IMPORTANT NOTES
TradingView.TO is a trading bot software that forwards TradingView alerts to your brokers (examples: Binance, Oanda, Coinbase, Bybit, Metatrader 4/5, ...) for automating trading.
Many traders don't know how to create TradingView.TO dynamically-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create TradingView.TO alerts dynamically.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for BTC/USDT on the 5 minutes chart, 1 alert for BTC/USDT on the 15-minute chart (assuming you want your bot to trade the BTC/USDT on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) TradingView.TO uses webhook technology - setting a webhook URL from the alerts notifications tab is required.
KEY FEATURES
I) Modular Indicator Connection
* plug your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether a MACD , ZigZag, Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) BOT Risk Management:
- Max Drawdown:
Mode: Select whether the max drawdown is calculated in percentage (%) or USD.
Value: If the max drawdown reaches this specified value, set a value to halt the bot.
- Max Consecutive Days:
Use Max Consecutive Days BOT Halt: Enable/Disable halting the bot if the max consecutive losing days value is reached.
- Max Consecutive Days: Set the maximum number of consecutive losing days allowed before halting the bot.
- Max Losing Streak:
Use Max Losing Streak: Enable/Disable a feature to prevent the bot from taking too many losses in a row.
- Max Losing Streak Length: Set the maximum length of a losing streak allowed.
Margin Call:
- Use Margin Call: Enable/Disable a feature to exit when a specified percentage away from a margin call to prevent it.
Margin Call (%): Set the percentage value to trigger this feature.
- Close BOT Total Loss:
Use Close BOT Total Loss: Enable/Disable a feature to close all trades and halt the bot if the total loss is reached.
- Total Loss ($): Set the total loss value in USD to trigger this feature.
Intraday BOT Risk Management:
- Intraday Losses:
Use Intraday Losses BOT Halt: Enable/Disable halting the bot on reaching specified intraday losses.
Mode: Select whether the intraday loss is calculated in percentage (%) or USD.
- Max Intraday Losses (%): Set the value for maximum intraday losses.
Limit Intraday Trades:
- Use Limit Intraday Trades: Enable/Disable a feature to limit the number of intraday trades.
- Max Intraday Trades: Set the maximum number of intraday trades allowed.
Restart Intraday EA:
III) Order Types and Position Sizing
- Choose between market or limit orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
I know it's redundant. - the template needs this value from the "Inputs" tab to build the alerts, and the Backtester needs it from the "Properties" tab.
IV) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either USD or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in USD for “risk-free” trades.
V) Miscellaneous:
Retry order openings if they fail.
Order Types:
Select and specify order type and price settings.
Position Size:
Define the type and size of positions.
Leverage:
Leverage settings, including margin type and hedge mode.
Session:
Limit trades to specific sessions.
Dates:
Limit trades to a specific date range.
Trades Direction:
Direction: Specify the market direction for opening positions.
VI) Logger
The TradingView.TO commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a TradingView.TO trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for TradingView.TO.
I tested them all and checked with the support team what could/couldn’t be done.
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your TradingView.TO account
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with TradingView.TO.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1%
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used
Multiple Vertical LinesThis script allows you to have multiple vertical lines on your chart (for seeing how price action performs around certain times of interest to you.
You can adjust the code to add new lines or colours as you wish (or comment out any that are there if they don't suit you.
There is also a shaded area, so you can use that for delineating an amount of time.
The indicator is currently set to New York time, but you can adjust this to suit you.