MM Chop Filter Range BoxesMatch with the MM Chop Filter
This draw Non repainting range boxes when the oscillator see a range.
-Breakout Buy/Sell Signals and Exit signals when prices enters a range just in case you did get into a trade. .
-Alarms to match the signals
How to use
Match with the oscillator and always trade the trend with your strategy confirmation and the breakout this indicator provides
Pine utilities
Ultimate Time Filter V1The only time filter that you will ever need.
Easily filter for:
--> Start/End Dates
--> Weekdays
--> 1 or 2 Daily Trade Sessions.
This is open source on purpose so you can enjoy ease of use on your own codes. Simply copy the code and use the variable "inTime" to filter bars that fit your time constraints.
I spent a lot more time on this than I'd like to admit but so be it. Any comments for improvements, or questions on how to use the script is appreciated. Or if you wanna chat about trading / pine script hit me up on Discord.
Cheers
Template Trailing Strategy (Backtester)💭 Overview
💢 What is the "Template Trailing Strategy” ❓
The "Template Trailing Strategy" (TTS) is a back-tester orchestration framework. It supercharges the implementation-test-evaluation lifecycle of new trading strategies, by making it possible to plug in your own trading idea.
While TTS offers a vast number of configuration settings, it primarily allows the trader to:
Test and evaluate your own trading logic that is described in terms of entry, exit, and cancellation conditions.
Define the entry and exit order types as well as their target prices when the limit, stop, or stop-limit order types are used.
Utilize a variety of options regarding the placement of the stop-loss and take-profit target(s) prices and support for well-known techniques like moving to breakeven and trailing.
Provide well-known quantity calculation methods to properly handle risk management and easily evaluate trading strategies and compare them.
Alert on each trading event or any related change through a robust and fully customizable messaging system.
All the above, build a robust tool that, once learned, significant and repetitive work that strategy developers often implement individually on every strategy script is eliminated. Taking advantage of TradingView’s built-in backtesting engine the evaluation of the trading ideas feels natural.
By utilizing the TTS one can easily swap “trading logic” by testing, evaluating, and comparing each trading idea and/or individual component of a strategy.
Finally, TTS, through its per-event alert management (and debugging) system, provides a fully automated solution that supports automated trading with real brokers via webhooks.
NOTE: The “Template Trailing Strategy” does not dictate the way you can combine different (types of) indicators or how you should combine them. Thus, it should not be confused as a “Trading System”, because it gives its user full flexibility on that end (for better or worse).
💢 What is a “Signal Indicator” ❓
“Signal Indicator” (SI) is an indicator that can output a “signal” that follows a specific convention so that the “Template Trailing Strategy” can “understand” and execute the orders accordingly. The SI realizes the core trading logic signaling to the TTS when to enter, exit, or cancel an order. A SI instructs the TTS “when” to enter or exit, and the TTS determines “how” to enter and exit the position once the Signal Indicator generates a signal.
A very simple example of a Signal Indicator might be a 200-day Simple Moving Average Signal. When the price of the security closes above the 200-day SMA, a SI would provide TTS with a “long entry signal”. Once TTS receives the “long entry signal”, the TTS will open a long position and send an alert or automated trade message via webhook to a broker, based on the Entry settings defined in TTS. If the TTS Entry settings specify a “Market” order type, then the open long position will be executed by TTS immediately. But if the TTS Entry settings specify a “Stop” order type with a 1% Stop Distance, then when the price of the security rises by 1% after the “long entry signal” occurs, the TTS will open a long position and the Long Entry alert or webhook to the broker will be sent.
🤔 How to Guide
💢 How to connect a “signal” from a “Signal Indicator” ❓
The “Template Trailing Strategy” was designed to receive external signals from a “Signal Indicator”. In this way, a “new trading idea” can be developed, configured, and evaluated separately from the TTS. Similarly, the SI can be held constant, and the trading mechanics can change in the TTS settings and back-tested to answer questions such as, “Am I better with a different stop loss placement method, what if I used a limit order instead of a stop order to enter, what if I used 25% margin instead of trading spot market?”
To make that possible by connecting an external signal indicator to TTS, you should:
Add in the same chart, the “Signal Indicator” of your choice (e.g. “Two MA Signal Indicator” , “Click Signal Indicator” , “Signal Adapter” , “Signal Composer” ) and the “Template Trailing Strategy”.
Go to the “Settings/Inputs” tab in the “🛠️ STRATEGY” group of the TTS and change the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" to “🔨External”
Go to the “🔨 STRATEGY – EXTERNAL” group settings of the TTS and change the “🔌𝐒𝐢𝐠𝐧𝐚𝐥 🛈➡” to the output signal of the “Signal Indicator” you want to connect. The selected combo box option should look like “:🔌Signal to TTS” where should correspond to the short title of your “Signal Indicator”
💢 How to create a Custom Trading logic ❓
The “Template Trailing Strategy” provides two ways to plug in your custom trading logic. Both of them have their advantages and disadvantages.
✍️ Develop your own Customized “Signal Indicator” 💥
The first approach is meant to be used for relatively more complex trading logic. The advantages of this approach are the full control and customization you have over the trading logic and the relatively simple configuration setup by having two scripts only. The downsides are that you have to have some experience with pinescript or you are willing to learn and experiment. You should also know the exact formula for every indicator you will use since you have to write it by yourself. Copy-pasting from existing open-source indicators will get you started quite fast though.
The idea here is either to create a new indicator script from scratch or to copy an existing non-signal indicator and make it a “Signal Indicator”. To create a new script, press the “Pine Editor” button below the chart to open the “Pine Editor” and then press the “Open” button to open the drop-down menu with the templates. Select the “New Indicator” option. Add it to your chart to copy an existing indicator and press the source code {} button. Its source code will be shown in the “Pine Editor” with a warning on top stating that this is a read-only script. Press the “create a working copy”. Now you can give a descriptive title and a short title to your script, and you can work on (or copy-paste) the (other) indicators of your interest. Having all the information needed to make your decision the only thing you should do is define a DealConditions object and plot it like this:
import jason5480/tts_convention/4 as conv
// Calculate the start, end, cancel start, cancel end conditions
dealConditions = conv.DealConditions.new(
startLongDeal = ,
startShortDeal = ,
endLongDeal = ,
endShortDeal = ,
cnlStartLongDeal = ,
cnlStartShortDeal = ,
cnlEndLongDeal = ,
cnlEndShortDeal = )
// Use this signal in scripts like "Template Trailing Strategy" and "Signal Composer" that can use its value
// Emit the current signal value according to the "two channels mod div" convention
plot(series = conv.getSignal(dealConditions), title = '🔌Signal to TTS', color = color.olive, display = display.data_window + display.status_line, precision = 0)
You should write your deal conditions appropriately based on your trading logic and put them in the code section shown above by replacing the “…” part after “=”. You can omit the conditions that are not relevant to your logic. For example, if you use only market orders for entering and exiting your positions the cnlStartLongDeal, cnlStartShortDeal, cnlEndLongDeal, and cnlEndShortDeal are irrelevant to your case and can be safely omitted from the DealConditions object. After successfully compiling your new custom SI script add it to the same chart with the TTS by pressing the “Add to chart” button. If all goes well, you will be able to connect your “signal” to the TTS as described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
🧩 Adapt and Combine existing non-signal indicators 💥
The second approach is meant to be used for relatively simple trading logic. The advantages of this approach are the lack of pine script and coding experience needed and the fact that it can be used with closed-source indicators as long as the decision-making part is displayed as a line in the chart. The drawback is that you have to have a subscription that supports the “indicator on indicator” feature so you can connect the output of one indicator as an input to another indicator. Please check if your plan supports that feature here
To plug in your own logic that way you have to add your indicator(s) of preference in the chart and then add the “Signal Adapter” script in the same chart as well. This script is a “Signal Indicator” that can be used as a proxy to define your custom logic in the CONDITIONS group of the “Settings/Inputs” tab after defining your inputs from your preferred indicators in the VARIABLES group. Then a “signal” will be produced, if your logic is simple enough it can be directly connected to the TTS that is also added to the same chart for execution. Check the “How to connect a “signal” from a “Signal Indicator”?” in the “🤔 How to Guide“ for more information.
If your logic is slightly more complicated, you can add a second “Signal Adapter” in your chart. Then you should add the “Signal Composer” in the same chart, go to the SIGNALS group of the “Settings/Inputs” tab, and connect the “signals” from the “Signal Adapters”. “Signal Composer” is also a SI so its composed “signal” can be connected to the TTS the same way it is described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
At this point, due to the composability of the framework, you can add an arbitrary number (bounded by your subscription of course) of “Signal Adapters” and “Signal Composers” before connecting the final “signal” to the TTS.
💢 How to set up ⏰Alerts ❓
The “Template Trailing Strategy” provides a fully customizable per-even alert mechanism. This means that you may have an entirely different message for entering and exiting into a position, hitting a stop-loss or a take-profit target, changing trailing targets, etc. There are no restrictions, and this gives you great flexibility.
First of all, you have to enable the alerts of the events that interest you. Go to the “🔔 ALERT MESSAGES” module of the TTS settings and check the “Enable…” checkbox of the events you are interested in. For each specific event, you will find a text area where you can type the exact message you want to receive when the event occurs. What’s more, there are placeholders you can use that will be replaced by the TTS with the actual values before the message is sent. The placeholder categories are the following and the placeholder names are self-explanatory.
Chart info: {{ticker}}, {{base_currency}}, {{quote_currency}}
Quantities and percentages: {{base_quantity}}, {{quote_quantity}}, {{quote_quantity_perc}},
{{take_profit_base_quantity}}, {{remaining_quantity_perc}}, {{remaining_base_quantity}}, {{risk_perc}}
Target prices: {{stop_loss_price}}, {{entry_price}}, {{entry+_price}}, {{entry-_price}},
{{exit_price}}, {{exit+_price}}, {{exit-_price}}, {{take_profit_price_1}},
{{take_profit_price_2}}, {{take_profit_price_3}}, {{take_profit_price_4}}, {{take_profit_price_5}}
❗ To get the message on the other side you have to set a strategy alert as described here and use the {{strategy.order.alert_message}} placeholder as text in the “Message Box” that contains the message that came from the TTS.
💢 How to execute my orders in a broker ❓
To execute your orders in a broker that supports webhook integration, you should enable the appropriate alerts in the “Template Trailing Strategy” first (see the “How to set up Alerts?” guide above). Then you should go to the “Create Alert/Notifications” tab check the “Webhook URL” and paste the URL provided by your broker. You have to read the documentation of your broker for more information on what messages are expected.
Keep in mind that some brokers have deep integration with TradingView so a per-event alert approach might be overkill.
📑 Definitions
This section tries to give some definitions in terms that appear in the “Settings/Inputs" tab of the “Template Trailing Strategy”
💢 What is Trailing ❓
Trailing is a technique where a price target follows another “barrier” price (usually high or low) by trying to keep a maximum distance from the “barrier” when it moves in only one direction (up or down). When the “barrier” moves in the other direction the price target will not change. There are as many types of trailing as price targets, which means that there are entry trailing, exit trailing, stop-loss trailing, and take-profit trailing techniques.
💢 What is a Moonbag ❓
A Moonbag in a trade is the quantity of the position that is reserved and will not be exited even if all take-profit targets defined in the strategy are hit, the quantity will be exited only if the stop-loss is hit or a close signal is received. This makes the stop-loss trailing technique in a trend-following strategy a good candidate to take advantage of a Moonbag.
💢 What is Distance ❓
Distance is the difference between two prices.
💢 What is Bias ❓
Bias is a psychological phenomenon where you make decisions based on market sentiment. For example, when you want to enter a long position you have a long bias, and when you want to exit from the long position you have a short bias. It is the other way around for the short position.
💢 What is the Margin Distance of a price target ❓
The Margin Distance of a price target is the distance that the target will deviate from its initial price. The direction of this deviation depends on the bias of the market. For example, suppose you are in a long position, and you set a take-profit target to the local high (HHLL). In that case, adding a margin of five ticks will place your take-profit target 5 ticks below this local high because you have a short bias when exiting a long position. When the bias is long the margin will be added resulting in a higher target price and when you have a short bias the margin will be subtracted.
⚙️ Settings
In the “Settings/Inputs” tab of the “Template Trailing Strategy”, you can find all the customizable settings that are provided by the framework. The variety of those settings is vast; hence we will only scratch the surface here. However, for every setting, there is an information icon 🛈 where you can learn more if you mouse over it. The “Settings/Inputs” tab is divided into ten main groups. Each one of them is responsible for one module of the framework. Every setting is part of a group that is named after the module it represents. So, to spot the module of a setting find the title that appears above it comes with an emoji and uppercase letters. Some settings might have the same name but belong to different modules e.g. “Distance Method”. Some settings are indented, which means that are closely related to the non-indented setting above. Usually, intended settings provide further configuration for one or more options of the non-intended setting. The groups that correspond to each module of the framework are the following:
📆 FILTERS
In this module time filters are implemented. You can define a DateTime window for your strategy to run. You can also specify a session by selecting the days of the week and the time range you want to operate.
🛠️ STRATEGY
This module contains the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" that defines if the “Template Trailing Strategy” will operate using the Internal or the External (“Signal Indicator”) conditions. Some general settings can be applied regardless of the mode.
🔨 STRATEGY – EXTERNAL
This sub-module makes the connection between the external signal of the “Signal Indicator” and the “Template Trailing Strategy”. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔨External”.
🔧 STRATEGY – INTERNAL
This sub-module defines the internal strategy logic and it's used as an example to demonstrate this framework. It should produce the same results as if the “Two MA Signal Indicator” was used as a “signal” in external mode. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔧Internal”.
🎢 VOLATILITY
This module defines the volatility parameters that are used in various other settings like average true range and standard deviation. It also makes it clear whether their values are updated during a trade (DYNAMIC) or not (STATIC).
🔷 ENTRY
This module defines how the start deal conditions will be executed by defining the order type of your entry and all necessary parameters to execute them.
🎯 TAKE PROFIT
This module defines the take-profit targets placement logic. The number of the take-profit targets to use, their distance from the entry price, and the distance from each other are only some of the features that can be configured.
🛑 STOP LOSS
This module defines the stop-loss target placement logic. The distance from the entry price, move to break even, and start trailing after a take-profit target is hit are only some of the features that can be configured.
🟪 EXIT
This module defines how the end deal conditions will be executed by defining the order type of your exit and all necessary parameters to execute them.
💰 QUANTITY/RISK MANAGEMENT
This module defines the method that calculates the amount of money you will put into each trade. Also, the percentage of the Moonbag quantity can be configured.
📊 ANALYTICS
This module can visualize some extra analytics of the strategy in the chart and calculate some metrics to measure the overall performance.
🔔 ALERT MESSAGES
This module defines all the messages that can be emitted per event during the strategy execution.
😲 Caveats
💢 Does “Template Trailing Strategy” has a repainting behavior ❓
The answer is that the “Template Trailing Strategy” does not repaint as long as the “Signal Indicator” that is connected also does not repaint. If you developed your own SI make sure that you understand and know how to prevent this behavior. The publication by @PineCoders here will give you a good idea on how to avoid most of the repainting cases.
⚠️There is an exception though, when the “Enable Trail⚠️💹” checkbox is checked, the Take Profit trailing feature is enabled, and a tick-based approach is used, meaning that after a while, when the TradingView discards all the real-time data, assumptions will be made by the backtesting engine that will cause a form of repainting. To avoid making false assumptions please disable this feature in the early stages and evaluate its usefulness in your strategy later on, after first confirming the success of the logic without this feature. In this case, consider turning on the bar magnifier feature. This way you will get more accurate backtest results when the Take Profit trailing feature is enabled.
💢 Can “Template Trailing Strategy” satisfy all my trading strategies ❓
While this framework can satisfy quite a large number of trading strategies there are cases where it cannot do so. For example, if you have a custom logic for your stop-loss or take-profit placement, or if you want to dollar cost average, then it might be better to start a new strategy script from scratch.
⚠️ It is not recommended to copy the official TTS code and start developing unless you are a pine wizard! Even in that case, there is a stiff learning curve that might not be worth your time. Last, you must consider that I do not offer support for customized versions of the TTS script and if something goes wrong in the process you are all alone.
🤗 Thanks
Special thanks to @upslidedown and @metadimensional, who regularly gave feedback all those years and helped me to shape the framework as it is today! Thanks to @EltAlt, @PlusUltraTrading, and everyone else who contributed by either filing a “defect report” or asking questions that helped me to understand what improvements were necessary.
Enjoy!
Jason
Nifty_Price_Movement_BuildUPDashboard to see Price Momentum Build-Up at Nifty.
It cumulates all prices and their respective weightage.
During initial of a candle, we are not aware of volume is High or Not, we only get it in later buildup. But Price buildup will display it at the same instant that what is going with the price of all stocks.
The logic used here is that
1) If a stock close > open at a particular instant it will add that stock multiplied with its weightage in Nifty to the list of stocks that are positive.
2) If a stock close < open at a particular instant it will add that stock multiplied with its weightage in Nifty to the list of stocks that are negative.
3) Above two will give you data that how many of them are positive and are negative at a particular instant and how they are going to affect Nifty.
In one of the many possible ways, it is superior than that of Volume buildup is that, to determine volume is higher than previous volume, we have to wait for first few seconds/minutes/hours (depending on timeframe you are in) to see volume buildup. The Volume buildup function based indicator is kind of lagging, though volume itself being instant.
Close Combination Lock Style - Visual AppealThis creates a combination style closing price change on each tick.
It has two theme options, one as silver dials for Dark Theme and the other as black dials for White Theme.
We get fixated to watching closing prices on charts and it gets visually daunting. This creates a combination style price change which updates on each tick, which is quite pleasing to the eye.
When new price is above current center line, it shift the above prices showing ▲ arrow, and if new price is lower, it will shift the bottom prices showing ▼ arrow. If there is no change in price between the ticks, it will show =.
Candles HTF on Heikin Ashi ChartThis script enables calling and/or plotting of traditional Candles sources while loaded on Heikin Ashi charts.
Thanks to @PineCoders for rounding method: www.pinecoders.com
Thanks to @BeeHolder for method to regex normalize syminfo.tickerid.
NOTICE: While this script is meant to be utilized on Heikin Ashi charts it does NOT enable ability to backtest!
NOTICE: For more info on why non standard charts cannot be reliably backtested please see:
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!
Filter impulse & step responsesA simple utility tool to examine a filter's step & impulse responses.
By default you can see LSMA's responses.
How to use:
1. Insert your filter to "f(input)" function inside the code;
2. Let this tool help you to make your own filters.
I been seeing people dropping snaps with this stuff but NEVER, NO1 actually dropped the tool itself (4 real?).
Well here is it, for you.
Almost forgot, adjust "Position" parameter to make plots seen. Try to zoom out, and +-100
How To Identify Argument Type Of Number Using OverloadsExample overload functions accept loading of _value for types float, int, or string, then positively identifies the actual argument type of that specific loaded _value.
How To Identify Type Of NumberExample function accepts loading of _value for types float, int, or string, then identifies whether the loaded _value is a string number, string, or number.
STRATEGY R18-F-BTCHi, I'm @SenatorVonShaft
Just finished the strategy "STRATEGY R18-F-BTC" for trading on #bitcoin and other cryptocurrencies.
As any strategy on TradingView, R18 opens Long/Short positions (with no leverage) on certain price points for assets in the chart. But I intentionally make this strategy for Bitcoin . Strategy is effective with 1h chart and it has %36 winning trade ratio for #bitcoin trade. As strategy uses approximately 1/3 ratio of SL/TP levels, gross profit for 1 year backtest is above %200 (I mean above 3x for only BTC )
Strategy is built on combination of:
- MACD
- RSI
- FIBONACCI levels
- BTCUSDT price itself as indicator (for different crypto assets and BTCUSDTPERP trading. You can select different assets you like for indicator (it's BTCUSDT:Binance by default))
I fine-tuned all levels of indicators above accordingly (it has more than 10 variables that effects strategy itself).
You can find out your own strategy levels by adjusting long/short tp&sl variables as well as initial capital ratio variable.
Reverse option open reverse positions of the strategy
Backtest EngineThis is a simple backtest engine for your trading strategies. The idea behind this script is to make testing new strategies as easy as possible. Parameters such as take profit/stop loss and time period are built into the script and are customisable by the user via the settings interface. The only coding is to set the entry and exit conditions. Users need not touch any code beyond line 30.
For this post, I have used a 50/200 SMA crossover to demonstrate the ease of use for this script.
The features of this script include:
Backtest period start
Number of days until backtest period end
Take profit and stop loss % (via settings)
Programmable long and short entry/exit
Anti duplicate system (for entry conditions that are continuously satisfied, the engine will only make 1 trade until the is exit condition is satisfied).
DISCLAIMER: The strategy in this post is only a placeholder. The TP/SL levels are set to showcase the functionality of the engine and are in no means optimal settings.
Hope this helps! Feel free to ask any questions about the engine and happy coding!
How To Count DecimalsCustom f_nDecimals() function returns precision of decimal numbers of the following forms:
const, input, simple, and series of the following types: float, integer, and string.
Error checking is performed for valid numbers and invalid values return NaN.
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!
Oscillator EdgesAnother simple script to be added on top of other indicators. Simply provides a symbol of varying color depending on the value of the oscillator. Allows up to 4 different colors in each direction. Includes alerts conditions. Demonstration is the indicator being applied to the RSI (purple) included in Market Cipher B.
To use, simply add it to your indicator, and choose and oscillator of your choice in the Input Settings. Alternatively, you can just keep it on 'close' and use the built in RSI. Or, you can use the RSI formula on top of something else (if that's your thing).
The names are silly, so I hope this is okay with all of you.
Let me know what you think, and if there are any problems, questions, or concerns!
Percentile Nearest Rank Using Arrays [LuxAlgo]The new array feature is extremely powerful, as it will allow pinescript users to do more complex things, or compute existing calculations more efficiently, it will also be possible to shine some light to some already existing functions, one of them being percentile_nearest_rank .
We have been working on this new feature with our pal alexgrover, and made this script which computes a rolling percentile using the nearest rank method.
Settings
Length: Window of the rolling percentile, determine the number of past data to be used.
Percentage: Return the current value if Percentage % of the data fall below that value, the setting is in a range (0,100).
Src: Input source of the indicator.
Usage
A rolling percentile can have many usages when it comes to technical analysis, this is due to its ability to return the value of three common rolling statistics, the rolling median, which can be obtained using a percentage equal to 50, the rolling maximum, obtained with a percentage equal to 100, and the rolling minimum, obtained with a percentage equal to 0.
When we use our rolling percentile as a rolling median, we can obtain a robust estimation of the underlying trend in the price, while using it as a rolling maximum/minimum can allow us to determine if the market is trending, and at which direction. The rolling maximum/minimum is a rolling statistic used to calculate the well known stochastic oscillator and Donchian channel indicator.
We can also compute rolling quartiles, which can be obtained using a percentage of 25 or 75, with one of 25 returning the lower quartile and 75 the upper quartile.
In blue the upper rolling quartile (%75), in orange the lower rolling quartile (%25), both using a window size of 100.
Details
In order to compute a rolling percentile nearest rank, we must first take the most recent length closing prices, then order them in ascending order, we then return the value of the ordered observations at index (percentage/100*length) - 1 (we use - 1 because our array index starts at 0).