Consecutive count backtester / quantifytools- Overview
Consecutive counting is a simple method to mechanically define trending states to the upside and downside. Consecutive counts are calculated by taking reference price level (e.g. close 4 candles ago) and count closes above/below it up to a maximum count that resets the consecutive count back to 1. This tool provides the means to backtest each count by measuring % change in price after each count (e.g. % gain 2 candles after a given count).
Users can define reference source that starts the consecutive count (e.g. close 4 candles ago), maximum count where counter resets (e.g. after 9th count) and backtesting period (e.g. price change 2 candles after count).
Filters add extra conditions that must be met on the consecutive count to qualify as valid, which are also reflected on the backtest metrics. The counts can be refined using the following filters:
- RSI above/below X
- Price above/below/at moving average of choice
- Relative volume above/below X
Average gain corresponding to each count as they occur can be toggled off for less clutter. Average price change can also be visualized using candle color. Colors, gradient and table/label sizes are fully customizable.
- Practical guide
Example #1: Identify reversal potential
Consecutive counting is a simple yet effective method to for detecting reversals, for which 7-9 counts are traditionally used. Whether that holds true or not can now be put through a test with different variations of the method as well as using additional filters to improve the probability of a turn.
Example #2: Identify trend following potential
Consecutive counts can also have utility value for trend following. When historical short term change is to the downside, expect downside, when to the upside, expect upside.
Counter
Threshold counterOVERVIEW
The "Threshold Counter" is a tool for quantifying occurrences of closing prices of an asset that align with specified criteria and is a flexible and visual approach to studying price action.
A user-definable target threshold can be set and a comparator (<, =, >, and so on) can be selected. The indicator counts values on the main chart meeting these conditions, over a user-defined `lookback` period.
KEY FEATURES
User definable threshold: target value with optional upper bound can be specified
Versatile Comparisons: Choose from "=", ">=", ">", "<=", "<", "between", and "between (inclusive)" for diverse analysis.
Historical Analysis: Assess occurrences over a customisable period.
Visual Representation: Displays instances graphically on the chart with customisable colours.
Summary: Provides a summary label for a quick understanding of the analysed data.
USE-CASES
Pattern Recognition: Identify patterns or trends based on user-defined price criteria.
Threshold Analysis: Quantify occurrences of prices crossing or staying within a specified range.
Strategy Testing: Evaluate historical performance of strategies relying on specific price conditions.
Behavioural Insights: Gain insights into price behaviour by counting occurrences of interest.
The "Threshold Counter" indicator offers a flexible and visual approach to studying price action, which may aid in making decisions based on historical data.
IMPORTANT CONSIDERATIONS
Period selection: The effectiveness of the analysis may be influenced by the choice of the lookback period. Consider an appropriate duration based on the strategy or pattern being analysed.
Comparator Selection: Comparison operator selection will obviously affect the results. There are two range operators of `between` and `between (inclusive)`. The latter will add closing prices that exactly meet the threshold and upper bound. The former does not.
Visualisation: Interpretation of the visual representation is colour-coded.
Red is threshold condition is not met.
Green is threshold condition is met.
Aqua is outside of the lookback period.
User Discretion: This script relies on historical data and should be used with caution. Past performance is not indicative of future results.
Supplementary Analysis: Trading decisions should not rely solely on this script. Users should exercise judgment and consider market conditions.
Period Candle CounterThis is a very simple utility indicator.
Shockingly nothing similar was available and I really needed something to quickly count period lengths by candles (to make adjustments to indicators based on a desired lookback timeframe), so I created this.
I thought I would share it because chances are if I needed something like this, other people may need it, too.
What it does:
Its really simple and this really truly is just a utility indicator that gives you raw information to make adjustments to other indicators. It just counts the number of candles in a user defined period of time.
It will count the number of red candles, green candles and then display the total candle count.
It will also display in percent (i.e. 52% green candles vs 48% red candles, etc.).
Its point and click, so once launched you just click the area you want to start the count and click the area you want to end the count.
Purpose:
Personally, I use it to make adjustments to timeframe lengths on indicators that look at averages and also on my time series indicator. If I want the price average or range for a specific period in time (say, the past 1.5 days of an uptrend), I will use this to count the candles in that period so that I can manually adjust whichever indicator to the correct lookback length, as most indicators are adjusted by candle length (i.e. 1 candle, 2 candles, 3 candles, etc.)
And that's it, pretty straight forward. Honestly pretty boring but its actually really pivotal for me to make adjustments to certain indicators.
Hope you find it helpful, too!
Safe trades!
Pip CrosshairsThis is a simple tool designed to help you visualize your stop loss and take profit levels before entering a trade. The tool plots two lines on the chart - a green dotted line for take profit and a red dotted line for stop loss (similar to the price line) - with a simulated default spread of one pip factored in. The indicator has the option to toggle between long and short positions.
Please note that the spread used in the tool is not based on your actual spread and should be adjusted accordingly. As, to the best of my knowledge Pine Script does not have the ability to automatically include spread in an indicator, so you will need to input your spread manually. (if you can please let me know cause that would be a game changer).
Overall, should help save you a bit of time by not having to manually measure stop loss and take profit levels for each trade.
Happy hunting :)
Highest/Lowest value since X time ago, various indicatorsThis script will count the bars back since the last time the current bar indicator value was either this low or this high.
It will provide the time in either, seconds, minutes, hours, days, weeks, months, or years.
please note:
There are currently no alerts setup for this script.
the length options only apply to the sources that have the "(MA)" in their name.
There is a horizontal line display issue which corrects once you adjust the amount of sources you want to use.
Once you select the amount of sources you would like to use, align the indicator so the horizontal lines match up with the table lines.
If find any bugs in the script, let me know.
VPT Timeleft v.10Timeleft counter for candle in minutes. It will countdown the time left for a candle to close and display near the running candle.
FunctionPatternFrequencyLibrary "FunctionPatternFrequency"
Counts the word or integer number pattern frequency on a array.
reference:
rosettacode.org
count(pattern)
counts the number a pattern is repeated.
Parameters:
pattern : : array : array with patterns to be counted.
Returns:
array : list of unique patterns.
array : list of counters per pattern.
usage:
count(array.from('a','b','c','a','b','a'))
count(pattern)
counts the number a pattern is repeated.
Parameters:
pattern : : array : array with patterns to be counted.
Returns:
array : list of unique patterns.
array : list of counters per pattern.
usage:
count(array.from(1,2,3,1,2,1))
EMA bands + leledc + bollinger bands trend following strategy v2The basics:
In its simplest form, this strategy is a positional trend following strategy which enters long when price breaks out above "middle" EMA bands and closes or flips short when price breaks down below "middle" EMA bands. The top and bottom of the middle EMA bands are calculated from the EMA of candle highs and lows, respectively.
The idea is that entering trades on breakouts of the high EMAs and low EMAs rather than the typical EMA based on candle closes gives a bit more confirmation of trend strength and minimizes getting chopped up. To further reduce getting chopped up, the strategy defaults to close on crossing the opposite EMA band (ie. long on break above high EMA middle band and close below low EMA middle band).
This strategy works on all markets on all timeframes, but as a trend following strategy it works best on markets prone to trending such as crypto and tech stocks. On lower timeframes, longer EMAs tend to work best (I've found good results on EMA lengths even has high up to 1000), while 4H charts and above tend to work better with EMA lengths 21 and below.
As an added filter to confirm the trend, a second EMA can be used. Inputting a slower EMA filter can ensure trades are entered in accordance with longer term trends, inputting a faster EMA filter can act as confirmation of breakout strength.
Bar coloring can be enabled to quickly visually identify a trend's direction for confluence with other indicators or strategies.
The goods:
Waiting for the trend to flip before closing a trade (especially when a longer base EMA is used) often leaves money on the table. This script combines a number of ways to identify when a trend is exhausted for backtesting the best early exits.
"Delayed bars inside middle bands" - When a number of candle's in a row open and close between the middle EMA bands, it could be a sign the trend is weak, or that the breakout was not the start of a new trend. Selecting this will close out positions after a number of bars has passed
"Leledc bars" - Originally introduced by glaz, this is a price action indicator that highlights a candle after a number of bars in a row close the same direction and result in greatest high/low over a period. It often triggers when a strong trend has paused before further continuation, or it marks the end of a trend. To mitigate closing on false Leledc signals, this strategy has two options: 1. Introducing requirement for increased volume on the Leledc bars can help filter out Leledc signals that happen mid trend. 2. Closing after a number of Leledc bars appear after position opens. These two options work great in isolation but don't perform well together in my testing.
"Bollinger Bands exhaustion bars" - These bars are highlighted when price closes back inside the Bollinger Bands and RSI is within specified overbought/sold zones. The idea is that a trend is overextended when price trades beyond the Bollinger Bands. When price closes back inside the bands it's likely due for mean reversion back to the base EMA in which this strategy will ideally re-enter a position. Since the added RSI requirements often make this indicator too strict to trigger a large enough sample size to backtest, I've found it best to use "non-standard" settings for both the bands and the RSI as seen in the default settings.
"Buy/Sell zones" - Similar to the idea behind using Bollinger Bands exhaustion bars as a closing signal. Instead of calculating off of standard deviations, the Buy/Sell zones are calculated off multiples of the middle EMA bands. When trading beyond these zones and subsequently failing back inside, price may be due for mean reversion back to the base EMA. No RSI filter is used for Buy/Sell zones.
If any early close conditions are selected, it's often worth enabling trade re-entry on "middle EMA band bounce". Instead of waiting for a candle to close back inside the middle EMA bands, this feature will re-enter position on only a wick back into the middle bands as will sometimes happen when the trend is strong.
Any and all of the early close conditions can be combined. Experimenting with these, I've found can result in less net profit but higher win-rates and sharpe ratios as less time is spent in trades.
The deadly:
The trend is your friend. But wouldn't it be nice to catch the trends early? In ranging markets (or when using slower base EMAs in this strategy), waiting for confirmation of a breakout of the EMA bands at best will cause you to miss half the move, at worst will result in getting consistently chopped up. Enabling "counter-trend" trades on this strategy will allow the strategy to enter positions on the opposite side of the EMA bands on either a Leledc bar or Bollinger Bands exhaustion bar. There is a filter requiring either a high/low (for Leledc) or open (for BB bars) outside the selected inner or outer Buy/Sell zone. There are also a number of different close conditions for the counter-trend trades to experiment with and backtest.
There are two ways I've found best to use counter-trend trades
1. Mean reverting scalp trades when a trend is clearly overextended. Selecting from the first 5 counter-trend closing conditions on the dropdown list will usually close the trades out quickly, with less profit but less risk.
2. Trying to catch trends early. Selecting any of the close conditions below the first 5 can cause the strategy to behave as if it's entering into a new trend (from the wrong side).
This feature can be deadly effective in profiting from every move price makes, or deadly to the strategy's PnL if not set correctly. Since counter-trend trades open opposite the middle bands, a stop-loss is recommended to reduce risk. If stop-losses for counter-trend trades are disabled, the strategy will hold a position open often until liquidation in a trending market if th trade is offsides. Note that using a slower base EMA makes counter-trend stop-losses even more necessary as it can reduce the effectiveness of the Buy/Sell zone filter for opening the trades as price can spend a long time trending outside the zones. If faster EMAs (34 and below) are used with "Inner" Buy/Zone filter selected, the first few closing conditions will often trigger almost immediately closing the trade at a loss.
The niche:
I've added a feature to default into longs or shorts. Enabling these with other features (aside from the basic long/short on EMA middle band breakout) tends to break the strategy one way or another. Enabling default long works to simulate trying to acquire more of the asset rather than the base currency. Enabling default short can have positive results for those high FDV, high inflation coins that go down-only for months at a time. Otherwise, I use default short as a hedge for coins that I hold and stake spot. I gain the utility and APR of staking while reducing the risk of holding the underlying asset by maintaining a net neutral position *most* of the time.
Disclaimer:
This script is intended for experimenting and backtesting different strategies around EMA bands. Use this script for your live trading at your own risk. I am a rookie coder, as such there may be errors in the code that cause the strategy to behave not as intended. As far as I can tell it doesn't repaint, but I cannot guarantee that it does not. That being said if there's any question, improvements, or errors you've found, drop a comment below!
[PS] Mini-Meter psRSIThis single oscillator, the cyclic RSI, is being measured for weakness in the underlying trend over a period of time and will identify divergences in price and the oscillator.
Two lines are drawn on the oscillator when a potential correction is detected.
Crossing the red line signifies invalidation of the potential correction and trend continuation.
Crossing the green line signals the potential counter-trend move.
Three symbols also appear on the oscillator.
Dots indicate the beginning of the diverging period.
X's indicate invalidation and trend continuation.
Triangles indicate the confirmation of the counter-trend move.
Alerts are integrated for each condition and are available to select individually as needed.
I will typically use alerts on a Bullish Setup to notify me of a chart preparing for a bullish correction.
I'll look at the chart and identify relevant support and resistance levels.
Upon a Bullish Trigger alert I'll return to the chart and evaluate my risk according to the current price level in relation to support/resistance.
I'll also look for a confirming price action signal for entry into a bullish trade.
Sometimes Bullish Triggers at support and Bearish Triggers at resistance can show those price levels potentially holding up.
In open positions triggers can be used as market-dictated take profit points as they are showing weakness in the directionality of price.
This script does not make use of the pivot function to identify lower/higher lows/highs, but there IS a 5 bar buffer in pivot points. Backtesting of methods show this has more statistical validity in the signal.
@theprivacysmurf
*The MM psRSI is a constituent of the PrivacySmurf Correction Strength Meter*
Close Counter HistogramAn interesting experiment to make an indicator act as a counter. I call it CCH - Close Counter Histogram.
It adds 1 when current close is higher than previous close and reduces -1 when current close is lower than previous close.
In the CCH settings you set how many bars to look back and use EMA to smooth the results or disable EMA smoothing.
Disable the EMA smoothing and you'll see the real deal (pure counter).
The higher the GREEN columns the more higher closes and the lower the RED columns the more lower closes.
In case columns are declining above 0 a more darker green will appear.
In case columns are declining below 0 a more darker red will appear.
Supports bar coloring (disabled by default).
Feel free to comment and Like if you like.
Enjoy :)
Advancing Declining OscillatorYet another Array indicator, simple, but efficient which i call ADO. The indicator acts as a COUNTER of when CLOSE closes above OPEN and vice versa based on specified look back period in settings.
If we have more Closes above Opens, obviously the indicator will be above ZERO and GREEN, otherwise RED.
Optional to smooth it by EMA (true by default).
Like if you Like and Enjoy!
Candle counterI've created a simple red/green candle counting script with a custom number of candles to look back on.
Let me know if any bugs, issues, or suggestions.
How To Limit n Round Trips Per Day [Alerts]Example how to limit the number of round trips per day. If entry condition is never met logic will force a round trip at end of day. Set chart to a timeframe that is lower than 1 Day period.
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!
Momentum fader 1.0The strategy is based on a momentum gauge designed for lower timeframes. In the current iteration, trades are very conservative and closed quickly.
In a future version, I've planned to implement dynamic take profit and stoploss levels for ultimate accuracy and maximized profit:drawdown ratio.
The strategy is specifically made for ETH and works best on the 3-minute timeframe.
Enjoy!
Katana Gaps Bounty Hunter (Show Gaps Counter) by RRBKatana Gaps Bounty Hunter (KGB_Hunter) by RagingRocketBull 2018
Version 1.0
This indicator shows/counts/filters gaps on a chart
There are several versions: Simple, Pro and Zones. This is the Simple version. The Differences are listed below.
- Simple: shows/counts gaps, changes color based on gap dir (2 colors), filters out price gaps within session, large gaps, and high volume gaps
- Pro: +shows all types of gaps, multi color, more filters (time gaps, doji, etc)
- Zones: +shows gaps as dynamic horiz zones
Features:
- highlights gaps using barcolor and plotchar chars (2 colors x 2 dirs)
- can show/hide gaps/chars based on gap dir
- changes color of gaps/chars based on gap dir
- displays chars above/below bar based on gap dir
- can filter out price gaps, large gaps, and high volume gaps
- counts all filtered gaps
Good Luck! Feel free to reuse the code and make it your own
Impulse Reverse HitMark the limits that should be used to star a Impulse Reverse trade. A Impulse Reverse trade is a counter-trend type of trading that uses the rubber-band concept.
A rubber-band trade is a type of trade that looks for strong directional price movement. Every stock has its unique combination of parameters that best fit a rubber-band trade, the default parameters of this script is the best fit for the WIN1! and WDO! when used on the 15m timeframe
Refined CandleCounter Strategy A while ago I published a Candle Counter strategy that got quite some attention. Unfortunately it didn't work for all charts for some reason, so I decided to rewrite it. The result is, to me, astonishing. Judge for yourselves!
CandleCounter - Amazingly simple strategyThis might sound like a crazy idea, but actually seems to work, on all time scales nonetheless!
tradingsignal.counter-trendCounter trend script to be used across all market instruments and timeframes. It will be available for testing and subscription soon.
FriendlyTrend Signal//FriendlyTrend Signal//
Our Tradingview representation of our strategy. Trend-Following techniques combining analysis of buying and selling on fractals, entering low-risk positions at counter-trend points, and trailing-stop orders along moving averages.
//Strategy//
Red/Green circles indicate counter-trend entry positions. These are not lagging and form on the closing of the corresponding bar. Best opportunities for a credit, debit, or other defined-risk options spreads and closed if the trade goes against us directionally with the stop loss above the high or below the low of the previous bar on market close.
Lines represent fractal support and resistance. We execute a buy if the moving average cloud is green and the green line is broken and the price closes above. Reverse for selling.
Cloud represents long or short opportunities. If the top cloud and bottom cloud are intertwined we are sidelined & wait for a large move in one direction or the other. The middle moving average is our trailing stop & another counter-trend entry point if a major support level is broken at the moving average itself.
//Still refining the code into a Tradingview Strategy form. More to come...//
[RS]Swing Charts V0 Trend Counter V0EXPERIMENTAL:
wave counting using swing charts, use at your own discretion.
[NM] Reversal Candles v01Reversal candles are a very easy way to identify a turn in trend, this indicator has some specific additional conditions for the reversal candle.
BUY Signal reversal candle
Low of current candle exceeds low of previous candle
Low of current candle is lowest for last 7 candles
High of current candle exceeds high of previous candle
Close of current candle is in the upper 50% of the range of this candle
SELL Signal reversal candle
High of current candle exceeds high of previous candle
High of current candle is Highest for last 7 candles
Low of current candle exceeds low of previous candle
Close of current candle is in the lower 50% of the range of this candle
How do I trade it ? (example buy signal)
Wait for close of the candle and the BUY signal
Put a buy stop entry 5 pips above the high of the candle
Put a stop loss 5 pips below the low of the candle
Calculate difference between entry and stop loss and set your target that number of pips above the entry for a 1:1 RR trade*
Wait for your your target or stop loss to be triggered
* Alternatively, you can take 50% of the profit at the 1st (1:1 RR) profit target, move your stop to break even and let the rest of the position run for a higher potential profit.
Further advice on use
Personally I always look for some additional confirmation like a support or resistance level, a bounce of the EMA or a fibonacci level, but please feel free to add additional filters to make the strategy even more effective. I would strongly advise to backtest your strategy first so you can fine tune it and have confidence in trading it. Forward testing on a demo account before going live, although it takes longer, can be a worthy alternative. Works better on higher time frames.
How do you use it ?
Please leave a note in the comment section below to let me know if you use the indicator and how. There's definitely not just one way to use the indicator so I'm curious about your feedback.
To apply the script to your chart, just add it to your favourites so you can easily find it in the Indicators list.
Kindly leave me a thumbs up if you like this indicator or support my work, and do not hesitate to visit my other indicators. Thanks for your visit
[RS]Price Linear Sequence CounterSimple green/red sequence counter, also gives current highest achieved sequence(black lines).