Range Detect SystemTechnical analysis indicator designed to identify potential significant price ranges and the distribution of volume within those ranges. The system helps traders calculate POC and show volume history. Also detecting breakouts or potential reversals. System identifies ranges with a high probability of price consolidation and helps screen out extreme price moves or ranges that do not meet certain volatility thresholds.
⭕️ Key Features
Range Detection — identifies price ranges where consolidation is occurring.
Volume Profile Calculation — indicator calculates the Point of Control (POC) based on volume distribution within the identified range, enhancing the analysis of market structure.
Volume History — shows where the largest volume was traded from the center of the range. If the volume is greater in the upper part of the range, the color will be green. If the volume is greater in the lower part, the color will be red.
Range Filtering — Includes multi-level filtering options to avoid ranges that are too volatile or outside normal ranges.
Visual Customization — Shows graphical indicators for potential bullish or bearish crossovers at the upper and lower range boundaries. Users can choose the style and color of the lines, making it easier to visualize ranges and important levels on the chart.
Alerts — system will notify you when a range has been created and also when the price leaves the range.
⭕️ How it works
Extremes (Pivot Points) are taken as a basis, after confirming the relevance of the extremes we take the upper and lower extremes and form a range. We check if it does not violate a number of rules and filters, perform volume calculations, and only then is the range displayed.
Pivot points is a built-in feature that shows an extremum if it has not been updated N bars to the left and N bars to the right. Therefore, there is a delay depending on the bars specified to check, which allows for a more accurate range. This approach allows not to make unnecessary recalculations, which completely eliminates the possibility of redrawing or range changes.
⭕️ Settings
Left Bars and Right Bars — Allows you to define the point that is the highest among the specified number of bars to the left and right of this point.
Range Logic — Select from which point to draw the range. Maximums only, Minimums only or both.
Use Wick — Option to consider the wick of the candles when identifying Range.
Breakout Confirmation — The number of bars required to confirm a breakout, after which the range will close.
Minimum Range Length — Sets the minimum number of candles needed for a range to be considered valid.
Row Size — Number of levels to calculate POC. *Larger values increase the script load.
% Range Filter — Dont Show Range is than more N% of Average Range.
Multi Filter — Allows use of Bollinger Bands, ATR, SMA, or Highest-Lowest range channels for filtering ranges based on volatility.
Range Hit — Shows graphical labels when price hits the upper or lower boundaries of the range, signaling potential reversal or breakout points.
Range Start — Show points where Range was created.
System
Ultra Moving AverageThe Ultra Moving Average is a versatile technical indicator that combines various types of moving averages to analyze trends, providing multi-timeframe insights for traders. It offers four customizable moving averages and a trend strength table for enhanced decision-making.
Introduction
The Ultra Moving Average indicator is a powerful tool designed to help traders track market trends by offering a combination of four distinct moving averages. With flexible customization options, users can apply different types of moving averages like SMA, EMA, TEMA, and many more, across various timeframes. Additionally, it provides trend strength analysis through an intuitive visual table, helping traders quickly identify market conditions.
Detailed Description
.........
Moving Averages
Each of the four moving averages is independently configurable. You can select the timeframe, type, length, color, and width to match your trading strategy.
The types of moving averages range from traditional ones like the Simple Moving Average (SMA) to advanced ones like the Double Expotential Moving Average (DEMA) or the Triple Exponential Moving Average (TEMA) or the Recursive Moving Average (RMA) or the Weigthend Moving Average (WMA) or the Volume Weigthend Moving Average (VWMA) or Hull Moving Average (HMA).
Very Special ones are the Triple Weigthend Moving Average (TWMA) wich created RedKTrader .
I created the Multi Weigthend Moving Average (MWMA) wich is a simple signal line to the TWMA.
.....
Trend Visualization
The indicator uses color-coding to visually represent whether the price is in an uptrend or downtrend. Bullish trends are highlighted in one color, while bearish trends appear in another, making it easy to interpret.
.....
Trend Strength Table
One of the unique features of the Ultra Moving Average is the trend strength table at the bottom of the chart. This table breaks down the strength of the fast, mid, and slow moving averages, displaying them as percentages. It also shows the overall "trend power," which helps assess how strong or weak the current trend is.
You have the option to calculate trends using live data or the previous bar's data, offering flexibility in how the indicator reacts to market changes. This can help traders make more responsive decisions based on real-time trends.
The table displays trend strength across three timeframes Fast, Mid, and Slow by calculating the percentage difference between the price and each of the moving averages (MA1, MA3, MA4).
The Power row shows the average of these percentages, representing overall trend strength.
The percentages are calculated relative to their maximum values in history (limited by TradingView subscription), providing insight into the trend's strength for each timeframe.
.........
Overall, the Ultra Moving Average indicator is a comprehensive tool that combines multiple moving average types and advanced trend analysis, helping traders identify market direction and strength at a glance. With its intuitive visualization and flexible settings, it's suited for both beginner and experienced traders.
Special Thanks
I use the TWMA-Function created from RedKTrader to smooth the values.
Special thanks to him for creating and sharing this function!
Dual SMA/EMA BandsThe Dual SMA/EMA Bands indicator provides a clear view of market trends, combining Simple Moving Averages (SMA) and Exponential Moving Averages (EMA) in one customizable tool. Designed for any timeframe, it features Aqua and Purple Bands for 50-period and 200-period averages , respectively, aiding in trend analysis and volatility insights.
Features:
Adaptive Timeframes : Automatically aligns with the chart’s timeframe or can be manually set for cross-timeframe analysis.
Customization : Offers easy adjustments for colors, line thickness, and opacity to suit personal preferences and enhance readability.
Insights : Facilitates trend confirmation and volatility assessment, essential for informed trading decisions.
Usage Tips:
Use the bands to gauge market direction; above the bands suggests bullish conditions, below them indicates bearish trends.
The gap between EMA and SMA within each band can signal market volatility.
Apply customizable timeframes for a comprehensive market overview.
Conclusion:
With its straightforward setup and versatile application, the Dual SMA/EMA Bands indicator is a valuable tool for traders looking to deepen their market analysis and uncover trading opportunities.
Bitcoin Momentum StrategyThis is a very simple long-only strategy I've used since December 2022 to manage my Bitcoin position.
I'm sharing it as an open-source script for other traders to learn from the code and adapt it to their liking if they find the system concept interesting.
General Overview
Always do your own research and backtesting - this script is not intended to be traded blindly (no script should be) and I've done limited testing on other markets beyond Ethereum and BTC, it's just a template to tweak and play with and make into one's own.
The results shown in the strategy tester are from Bitcoin's inception so as to get a large sample size of trades, and potential returns have diminished significantly as BTC has grown to become a mega cap asset, but the script includes a date filter for backtesting and it has still performed solidly in recent years (speaking from personal experience using it myself - DYOR with the date filter).
The main advantage of this system in my opinion is in limiting the max drawdown significantly versus buy & hodl. Theoretically much better returns can be made by just holding, but that's also a good way to lose 70%+ of your capital in the inevitable bear markets (also speaking from experience).
In saying all of that, the future is fundamentally unknowable and past results in no way guarantee future performance.
System Concept:
Capture as much Bitcoin upside volatility as possible while side-stepping downside volatility as quickly as possible.
The system uses a simple but clever momentum-style trailing stop technique I learned from one of my trading mentors who uses this approach on momentum/trend-following stock market systems.
Basically, the system "ratchets" up the stop-loss to be much tighter during high bearish volatility to protect open profits from downside moves, but loosens the stop loss during sustained bullish momentum to let the position ride.
It is invested most of the time, unless BTC is trading below its 20-week EMA in which case it stays in cash/USDT to avoid holding through bear markets. It only trades one position (no pyramiding) and does not trade short, but can easily be tweaked to do whatever you like if you know what you're doing in Pine.
Default parameters:
HTF: Weekly Chart
EMA: 20-Period
ATR: 5-period
Bar Lookback: 7
Entry Rule #1:
Bitcoin's current price must be trading above its higher-timeframe EMA (Weekly 20 EMA).
Entry Rule #2:
Bitcoin must not be in 'caution' condition (no large bearish volatility swings recently).
Enter at next bar's open if conditions are met and we are not already involved in a trade.
"Caution" Condition:
Defined as true if BTC's recent 7-bar swing high minus current bar's low is > 1.5x ATR, or Daily close < Daily 20-EMA.
Trailing Stop:
Stop is trailed 1 ATR from recent swing high, or 20% of ATR if in caution condition (ie. 0.2 ATR).
Exit on next bar open upon a close below stop loss.
I typically use a limit order to open & exit trades as close to the open price as possible to reduce slippage, but the strategy script uses market orders.
I've never had any issues getting filled on limit orders close to the market price with BTC on the Daily timeframe, but if the exchange has relatively low slippage I've found market orders work fine too without much impact on the results particularly since BTC has consistently remained above $20k and highly liquid.
Cost of Trading:
The script uses no leverage and a default total round-trip commission of 0.3% which is what I pay on my exchange based on their tier structure, but this can vary widely from exchange to exchange and higher commission fees will have a significantly negative impact on realized gains so make sure to always input the correct theoretical commission cost when backtesting any script.
Static slippage is difficult to estimate in the strategy tester given the wide range of prices & liquidity BTC has experienced over the years and it largely depends on position size, I set it to 150 points per buy or sell as BTC is currently very liquid on the exchange I trade and I use limit orders where possible to enter/exit positions as close as possible to the market's open price as it significantly limits my slippage.
But again, this can vary a lot from exchange to exchange (for better or worse) and if BTC volatility is high at the time of execution this can have a negative impact on slippage and therefore real performance, so make sure to adjust it according to your exchange's tendencies.
Tax considerations should also be made based on short-term trade frequency if crypto profits are treated as a CGT event in your region.
Summary:
A simple, but effective and fairly robust system that achieves the goals I set for it.
From my preliminary testing it appears it may also work on altcoins but it might need a bit of tweaking/loosening with the trailing stop distance as the default parameters are designed to work with Bitcoin which obviously behaves very differently to smaller cap assets.
Good luck out there!
LNL Trend SystemLNL Trend System is an ATR based day trading system specifically designed for intra-day traders and scalpers. The System works on any chart time frame & can be applied to any market. The study consist of two components - the Trend Line and the Stop Line. Trend System is based on a special ATR calculation that is achieved by combining the previous values of the 13 EMA in relation to the ATR which creates a line of deviations that visually look similar to the basic moving average but actually produce very different results ESPECIALLY in sideways market.
Trend Line:
Trend Line is a simple line which is basically a fast gauge represented by the 13 EMA that can change the color based on the current trend structure defined by multiple averages (8,13,21,34 EMAs). Trend Line is there to simply add the confluence for the current trend. Colors of the line are pretty much self-explanatory. Whenever the line turns red it states that the current structure is bearish. Vice versa for green line. Gray line represents neutral market structure.
Stop Line:
Stop Line is an ATR deviaton line with special calculation based on the previous bar ATRs and position of the price in relation to the current and previous values of 13 EMA. As already stated, this creates an ATR deviation marker either above or below the price that trails the price up or down until they touch. Whenever the price comes into the Stop Line it means it is making an ATR expansion move up or down .This touch will usually resolve into a reaction (a bounce) which provides trade opportunities.
Trend Bars:
When turned ON, Trend Bars can provide additional confulence of the current trend alongside with the Trend Line color. Trend Bars are based on the DMI and ADX indicators. Whenever the DMI is bearish and ADX is above 20 the candles paint themselfs red. And vice versa applies for the green candles and bullish DMI. Whenever the ADX falls below the 20, candles are netural (Gray) which means there is no real trend in place at the moment.
Trend Mode:
There are total of 5 different trend modes available. Each mode is visualizing different ATR settings which provides either aggressive or more conservative approach. The more tigher the mode, the more closer the distance between the price and the Stop Line. First two modes were designed for slower markets, whereas the "Loose" and "FOMC" modes are more suitable for products with high volatility.
Trend Modes:
1. Tight
Ideal for the slowest markets. Slowest market can be any market with unusually small average true range values or just simply a market that does have a personality of a "sleeper". Tight Mode can be also used for aggresive entries in the most ridiculous trends. Sometimes price will barely pullback to the Trend Line not even the Stop Line.
2. Normal
Normal Mode is the golden mean between the modes. "Normal" provides the ideal ATR lengths for the most used markets such as S&P Futures (ES) or SPY, AAPL and plenty of other highly popular stocks. More often than not, the length of this mode is respected considering there is no breaking news or high impact market event scheduled.
3. Loose
The "Loose" mode is basically a normal mode but a little bit more loose. This mode is useful whenever the ATRs jump higher than usual or during the days of highly anticipated news events. This mode is also better suited for more active markets such as NQ futures.
4. FOMC
The FOMC mode is called FOMC for a reason. This mode provides the maximum amount of wiggle room between the price and the Stop Line. This mode was designed for the extreme volatility, breaking news events or post-FOMC trading. If the market quiets down, this mode will not get the Stop Line touch as frequently as othete modes, thus it is not very useful to run this on markets with the average volatlity. Although never properly tested, perhaps the FOMC mode can find its value in the crypto market?
5. The Net
The net mode is basically a combination of all modes into one stop line system which creates "the net" effect. The Net provides the widest Stop Line zone which can be mainly appreciated by traders that like to use scale-in scale-out methods for their trading. Not to mention the visual side of the indicator which looks pretty great with the net mode on.
HTF (Higher Time Frame) Trend System:
The system also includes additional higher time frame (HTF) trend system. This can be set to any time frame by manual HTF mode. HTF mode set to "auto" will automatically choose the best suitable higher time frame trend system based on how appropriate the aggregation is. For everything below 5min the HTF Trend System will stay on 5min. Anything between 5-15min = 30min. 30min - 120min will turn on the 240min. 180min and higher will result in Daily time frame. Anything above the Daily will result in Weekly HTF aggregation, above W = Monthly, above M = Quarterly.
Background Clouds:
In terms of visualization, each trend system is fully customizable through the inputs settings. There is also an option to turn on/off the background clouds behind the stop lines. These clouds can make the charts more clean & visible.
Tips & Tricks:
1. Different Trend Modes
Try out different modes in different markets. There is no one single mode that will fit to everyone on the same type of market. I myself actually prefer more Loose than the Normal.
2. Stop Line Mirroring
Whenever the Stop Lines start to mirror each other (there is one above the price and one below) this means the price is entering a ranging sideways market. It does not matter which Stop Line will the price touch first. They can both be faded until one of them flips.
3. Signs of the Ranging Market
Watch out for signs of ranging market. Whenever the Trend System looses its colors whether on trend line or trend bars, if everything turns neutral (gray) that is usually a solid indication of a range type action for the following moments. Also as already stated before, the Stop Line mirroring is a good sign of the range market.
4. Trailing Tool, Trend System as an Additional Study?
In case you are not a fan of the colorful green / red charts & candles. You can switch all of them off and just leave the Stop Line on. This way you can use the benefits of the trend system and still use other studies on top of that. Similarly as the Parabolic SAR is often used.
5. The Flip Setup
One of my favorite trades is the Flip Setup on the 5min charts. Whenever the Stop Line is broken , the very first opposing touch after the Trend System flips is a usually a highly participated touch. If there is a strong reaction, this means this is likely a beginning of a new trend. Once I am in the position i like to trail the Stop Line on the 1min charts.
Hope it helps.
Hobbiecode - RSI + Close previous dayThis is a simple strategy that is working well on SPY but also well performing on Mini Futures SP500. The strategy is composed by the followin rules:
1. If RSI(2) is less than 15, then enter at the close.
2. Exit on close if today’s close is higher than yesterday’s high.
If you backtest it on Mini Futures SP500 you will be able to track data from 1993. It is important to select D1 as timeframe.
Please share any comment or idea below.
Have a good trading,
Ramón.
Adaptive Candlestick Pattern Recognition System█ INTRODUCTION
Nearly three years in the making, intermittently worked on in the few spare hours of weekends and time off, this is a passion project I undertook to flesh out my skills as a computer programmer. This script currently recognizes 85 different candlestick patterns ranging from one to five candles in length. It also performs statistical analysis on those patterns to determine prior performance and changes the coloration of those patterns based on that performance. In searching TradingView's script library for scripts similar to this one, I had found a handful. However, when I reviewed the ones which were open source, I did not see many that truly captured the power of PineScrypt or leveraged the way it works to create efficient and reliable code; one of the main driving factors for releasing this 5,000+ line behemoth open sourced.
Please take the time to review this description and source code to utilize this script to its fullest potential.
█ CONCEPTS
This script covers the following topics: Candlestick Theory, Trend Direction, Higher Timeframes, Price Analysis, Statistic Analysis, and Code Design.
Candlestick Theory - This script focuses solely on the concept of Candlestick Theory: arrangements of candlesticks may form certain patterns that can potentially influence the future price action of assets which experience those patterns. A full list of patterns (grouped by pattern length) will be in its own section of this description. This script contains two modes of operation for identifying candlestick patterns, 'CLASSIC' and 'BREAKOUT'.
CLASSIC: In this mode, candlestick patterns will be identified whenever they appear. The user has a wide variety of inputs to manipulate that can change how certain patterns are identified and even enable alerts to notify themselves when these patterns appear. Each pattern selected to appear will have their Profit or Loss (P/L) calculated starting from the first candle open succeeding the pattern to a candle close specified some number of candles ahead. These P/L calculations are then collected for each pattern, and split among partitions of prior price action of the asset the script is currently applied to (more on that in Higher Timeframes ).
BREAKOUT: In this mode, P/L calculations are held off until a breakout direction has been confirmed. The user may specify the number of candles ahead of a pattern's appearance (from one to five) that a pattern has to confirm a breakout in either an upward or downward direction. A breakout is constituted when there is a candle following the appearance of the pattern that closes above/at the highest high of the pattern, or below/at its lowest low. Only then will percent return calculations be performed for the pattern that's been identified, and these percent returns are broken up not only by the partition they had appeared in but also by the breakout direction itself. Patterns which do not breakout in either direction will be ignored, along with having their labels deleted.
In both of these modes, patterns may be overridden. Overrides occur when a smaller pattern has been detected and ends up becoming one (or more) of the candles of a larger pattern. A key example of this would be the Bearish Engulfing and the Three Outside Down patterns. A Three Outside Down necessitates a Bearish Engulfing as the first two candles in it, while the third candle closes lower. When a pattern is overridden, the return for that pattern will no longer be tracked. Overrides will not occur if the tail end of a larger pattern occurs at the beginning of a smaller pattern (Ex: a Bullish Engulfing occurs on the third candle of a Three Outside Down and the candle immediately following that pattern, the Three Outside Down pattern will not be overridden).
Important Functionality Note: These patterns are only searched for at the most recently closed candle, not on the currently closing candle, which creates an offset of one for this script's execution. (SEE LIMITATIONS)
Trend Direction - Many of the patterns require a trend direction prior to their appearance. Noting TradingView's own publication of candlestick patterns, I utilize a similar method for determining trend direction. Moving Averages are used to determine which trend is currently taking place for candlestick patterns to be sought out. The user has access to two Moving Averages which they may individually modify the following for each: Moving Average type (list of 9), their length, width, source values, and all variables associated with two special Moving Averages (Least Squares and Arnaud Legoux).
There are 3 settings for these Moving Averages, the first two switch between the two Moving Averages, and the third uses both. When using individual Moving Averages, the user may select a 'price point' to compare against the Moving Average (default is close). This price point is compared to the Moving Average at the candles prior to the appearance of candle patterns. Meaning: The close compared to the Moving Average two candles behind determines the trend direction used for Candlestick Analysis of one candle patterns; three candles behind for two candle patterns and so on. If the selected price point is above the Moving Average, then the current trend is an 'uptrend', 'downtrend' otherwise.
The third setting using both Moving Averages will compare the lengths of each, and trend direction is determined by the shorter Moving Average compared to the longer one. If the shorter Moving Average is above the longer, then the current trend is an 'uptrend', 'downtrend' otherwise. If the lengths of the Moving Averages are the same, or both Moving Averages are Symmetrical, then MA1 will be used by default. (SEE LIMITATIONS)
Higher Timeframes - This script employs the use of Higher Timeframes with a few request.security calls. The purpose of these calls is strictly for the partitioning of an asset's chart, splitting the returns of patterns into three separate groups. The four inputs in control of this partitioning split the chart based on: A given resolution to grab values from, the length of time in that resolution, and 'Upper' and 'Lower Limits' which split the trading range provided by that length of time in that resolution that forms three separate groups. The default values for these four inputs will partition the current chart by the yearly high-low range where: the 'Upper' partition is the top 20% of that trading range, the 'Middle' partition is 80% to 33% of the trading range, and the 'Lower' partition covers the trading range within 33% of the yearly low.
Patterns which are identified by this script will have their returns grouped together based on which partition they had appeared in. For example, a Bullish Engulfing which occurs within a third of the yearly low will have its return placed separately from a Bullish Engulfing that occurred within 20% of the yearly high. The idea is that certain patterns may perform better or worse depending on when they had occurred during an asset's trading range.
Price Analysis - Price Analysis is a major part of this script's functionality as it can fundamentally change how patterns are shown to the user. The settings related to Price Analysis include setting the number of candles ahead of a pattern's appearance to determine the return of that pattern. In 'BREAKOUT' mode, an additional setting allows the user to specify where the P/L calculation will begin for a pattern that had appeared and confirmed. (SEE LIMITATIONS)
The calculation for percent returns of patterns is illustrated with the following pseudo-code (CLASSIC mode, this is a simplified version of the actual code):
type patternObj
int ID
int partition
type returnsArray
float returns
// No pattern found = na returned
patternObj TEST_VAL = f_FindPattern()
priorTestVal = TEST_VAL
if not na( priorTestVal )
pnlMatrixRow = priorTestVal.ID
pnlMatrixCol = priorTestVal.partition
matrixReturn = matrix.get(PERCENT_RETURNS, pnlMatrixRow, pnlMatrixCol)
percentReturn = ( (close - open ) / open ) * 100%
array.push(matrixReturn.returns, percentReturn)
Statistic Analysis - This script uses Pine's built-in array functions to conduct the Statistic Analysis for patterns. When a pattern is found and its P/L calculation is complete, its return is added to a 'Return Array' User-Defined-Type that contains numerous fields which retain information on a pattern's prior performance. The actual UDT is as follows:
type returnArray
float returns = na
int size = 0
float avg = 0
float median = 0
float stdDev = 0
int polarities = na
All values within this UDT will be updated when a return is added to it (some based on user input). The array.avg , array.median and array.stdev will be ran and saved into their respective fields after a return is placed in the 'returns' array. The 'polarities' integer array is what will be changed based on user input. The user specifies two different percentages that declare 'Positive' and 'Negative' returns for patterns. When a pattern returns above, below, or in between these two values, different indices of this array will be incremented to reflect the kind of return that pattern had just experienced.
These values (plus the full name, partition the pattern occurred in, and a 95% confidence interval of expected returns) will be displayed to the user on the tooltip of the labels that identify patterns. Simply scroll over the pattern label to view each of these values.
Code Design - Overall this script is as much of an art piece as it is functional. Its design features numerous depictions of ASCII Art that illustrate what is being attempted by the functions that identify patterns, and an incalculable amount of time was spent rewriting portions of code to improve its efficiency. Admittedly, this final version is nearly 1,000 lines shorter than a previous version (one which took nearly 30 seconds after compilation to run, and didn't do nearly half of what this version does). The use of UDTs, especially the 'patternObj' one crafted and redesigned from the Hikkake Hunter 2.0 I published last month, played a significant role in making this script run efficiently. There is a slight rigidity in some of this code mainly around pattern IDs which are responsible for displaying the abbreviation for patterns (as well as the full names under the tooltips, and the matrix row position for holding returns), as each is hard-coded to correspond to that pattern.
However, one thing I would like to mention is the extensive use of global variables for pattern detection. Many scripts I had looked over for ideas on how to identify candlestick patterns had the same idea; break the pattern into a set of logical 'true/false' statements derived from historically referencing candle OHLC values. Some scripts which identified upwards of 20 to 30 patterns would reference Pine's built-in OHLC values for each pattern individually, potentially requesting information from TradingView's servers numerous times that could easily be saved into a variable for re-use and only requested once per candle (what this script does).
█ FEATURES
This script features a massive amount of switches, options, floating point values, detection settings, and methods for identifying/tailoring pattern appearances. All modifiable inputs for patterns are grouped together based on the number of candles they contain. Other inputs (like those for statistics settings and coloration) are grouped separately and presented in a way I believe makes the most sense.
Not mentioned above is the coloration settings. One of the aims of this script was to make patterns visually signify their behavior to the user when they are identified. Each pattern has its own collection of returns which are analyzed and compared to the inputs of the user. The user may choose the colors for bullish, neutral, and bearish patterns. They may also choose the minimum number of patterns needed to occur before assigning a color to that pattern based on its behavior; a color for patterns that have not met this minimum number of occurrences yet, and a color for patterns that are still processing in BREAKOUT mode.
There are also an additional three settings which alter the color scheme for patterns: Statistic Point-of-Reference, Adaptive coloring, and Hard Limiting. The Statistic Point-of-Reference decides which value (average or median) will be compared against the 'Negative' and 'Positive Return Tolerance'(s) to guide the coloration of the patterns (or for Adaptive Coloring, the generation of a color gradient).
Adaptive Coloring will have this script produce a gradient that patterns will be colored along. The more bullish or bearish a pattern is, the further along the gradient those patterns will be colored starting from the 'Neutral' color (hard lined at the value of 0%: values above this will be colored bullish, bearish otherwise). When Adaptive Coloring is enabled, this script will request the highest and lowest values (these being the Statistic Point-of-Reference) from the matrix containing all returns and rewrite global variables tied to the negative and positive return tolerances. This means that all patterns identified will be compared with each other to determine bullish/bearishness in Adaptive Coloring.
Hard Limiting will prevent these global variables from being rewritten, so patterns whose Statistic Point-of-Reference exceed the return tolerances will be fully colored the bullish or bearish colors instead of a generated gradient color. (SEE LIMITATIONS)
Apart from the Candle Detection Modes (CLASSIC and BREAKOUT), there's an additional two inputs which modify how this script behaves grouped under a "MASTER DETECTION SETTINGS" tab. These two "Pattern Detection Settings" are 'SWITCHBOARD' and 'TARGET MODE'.
SWITCHBOARD: Every single pattern has a switch that is associated with its detection. When a switch is enabled, the code which searches for that pattern will be run. With the Pattern Detection Setting set to this, all patterns that have their switches enabled will be sought out and shown.
TARGET MODE: There is an additional setting which operates on top of 'SWITCHBOARD' that singles out an individual pattern the user specifies through a drop down list. The names of every pattern recognized by this script will be present along with an identifier that shows the number of candles in that pattern (Ex: " (# candles)"). All patterns enabled in the switchboard will still have their returns measured, but only the pattern selected from the "Target Pattern" list will be shown. (SEE LIMITATIONS)
The vast majority of other features are held in the one, two, and three candle pattern sections.
For one-candle patterns, there are:
3 — Settings related to defining 'Tall' candles:
The number of candles to sample for previous candle-size averages.
The type of comparison done for 'Tall' Candles: Settings are 'RANGE' and 'BODY'.
The 'Tolerance' for tall candles, specifying what percent of the 'average' size candles must exceed to be considered 'Tall'.
When 'Tall Candle Setting' is set to RANGE, the high-low ranges are what the current candle range will be compared against to determine if a candle is 'Tall'. Otherwise the candle bodies (absolute value of the close - open) will be compared instead. (SEE LIMITATIONS)
Hammer Tolerance - How large a 'discarded wick' may be before it disqualifies a candle from being a 'Hammer'.
Discarded wicks are compared to the size of the Hammer's candle body and are dependent upon the body's center position. Hammer bodies closer to the high of the candle will have the upper wick used as its 'discarded wick', otherwise the lower wick is used.
9 — Doji Settings, some pulled from an old Doji Hunter I made a while back:
Doji Tolerance - How large the body of a candle may be compared to the range to be considered a 'Doji'.
Ignore N/S Dojis - Turns off Trend Direction for non-special Dojis.
GS/DF Doji Settings - 2 Inputs that enable and specify how large wicks that typically disqualify Dojis from being 'Gravestone' or 'Dragonfly' Dojis may be.
4 Settings related to 'Long Wick Doji' candles detailed below.
A Tolerance for 'Rickshaw Man' Dojis specifying how close the center of the body must be to the range to be valid.
The 4 settings the user may modify for 'Long Legged' Dojis are: A Sample Base for determining the previous average of wicks, a Sample Length specifying how far back to look for these averages, a Behavior Setting to define how 'Long Legged' Dojis are recognized, and a tolerance to specify how large in comparison to the prior wicks a Doji's wicks must be to be considered 'Long Legged'.
The 'Sample Base' list has two settings:
RANGE: The wicks of prior candles are compared to their candle ranges and the 'wick averages' will be what the average percent of ranges were in the sample.
WICKS: The size of the wicks themselves are averaged and returned for comparing against the current wicks of a Doji.
The 'Behavior' list has three settings:
ONE: Only one wick length needs to exceed the average by the tolerance for a Doji to be considered 'Long Legged'.
BOTH: Both wick lengths need to exceed the average of the tolerance of their respective wicks (upper wicks are compared to upper wicks, lower wicks compared to lower) to be considered 'Long Legged'.
AVG: Both wicks and the averages of the previous wicks are added together, divided by two, and compared. If the 'average' of the current wicks exceeds this combined average of prior wicks by the tolerance, then this would constitute a valid 'Long Legged' Doji. (For Dojis in general - SEE LIMITATIONS)
The final input is one related to candle patterns which require a Marubozu candle in them. The two settings for this input are 'INCLUSIVE' and 'EXCLUSIVE'. If INCLUSIVE is selected, any opening/closing variant of Marubozu candles will be allowed in the patterns that require them.
For two-candle patterns, there are:
2 — Settings which define 'Engulfing' parameters:
Engulfing Setting - Two options, RANGE or BODY which sets up how one candle may 'engulf' the previous.
Inclusive Engulfing - Boolean which enables if 'engulfing' candles can be equal to the values needed to 'engulf' the prior candle.
For the 'Engulfing Setting':
RANGE: If the second candle's high-low range completely covers the high-low range of the prior candle, this is recognized as 'engulfing'.
BODY: If the second candle's open-close completely covers the open-close of the previous candle, this is recognized as 'engulfing'. (SEE LIMITATIONS)
4 — Booleans specifying different settings for a few patterns:
One which allows for 'opens within body' patterns to let the second candle's open/close values match the prior candles' open/close.
One which forces 'Kicking' patterns to have a gap if the Marubozu setting is set to 'INCLUSIVE'.
And Two which dictate if the individual candles in 'Stomach' patterns need to be 'Tall'.
8 — Floating point values which affect 11 different patterns:
One which determines the distance the close of the first candle in a 'Hammer Inverted' pattern must be to the low to be considered valid.
One which affects how close the opens/closes need to be for all 'Lines' patterns (Bull/Bear Meeting/Separating Lines).
One that allows some leeway with the 'Matching Low' pattern (gives a small range the second candle close may be within instead of needing to match the previous close).
Three tolerances for On Neck/In Neck patterns (2 and 1 respectively).
A tolerance for the Thrusting pattern which give a range the close the second candle may be between the midpoint and close of the first to be considered 'valid'.
A tolerance for the two Tweezers patterns that specifies how close the highs and lows of the patterns need to be to each other to be 'valid'.
The first On Neck tolerance specifies how large the lower wick of the first candle may be (as a % of that candle's range) before the pattern is invalidated. The second tolerance specifies how far up the lower wick to the close the second candle's close may be for this pattern. The third tolerance for the In Neck pattern determines how far into the body of the first candle the second may close to be 'valid'.
For the remaining patterns (3, 4, and 5 candles), there are:
3 — Settings for the Deliberation pattern:
A boolean which forces the open of the third candle to gap above the close of the second.
A tolerance which changes the proximity of the third candle's open to the second candle's close in this pattern.
A tolerance that sets the maximum size the third candle may be compared to the average of the first two candles.
One boolean value for the Two Crows patterns (standard and Upside Gapping) that forces the first two candles in the patterns to completely gap if disabled (candle 1's close < candle 2's low).
10 — Floating point values for the remaining patterns:
One tolerance for defining how much the size of each candle in the Identical Black Crows pattern may deviate from the average of themselves to be considered valid.
One tolerance for setting how close the opens/closes of certain three candle patterns may be to each other's opens/closes.*
Three floating point values that affect the Three Stars in the South pattern.
One tolerance for the Side-by-Side patterns - looks at the second and third candle closes.
One tolerance for the Stick Sandwich pattern - looks at the first and third candle closes.
A floating value that sizes the Concealing Baby Swallow pattern's 3rd candle wick.
Two values for the Ladder Bottom pattern which define a range that the third candle's wick size may be.
* This affects the Three Black Crows (non-identical) and Three White Soldiers patterns, each require the opens and closes of every candle to be near each other.
The first tolerance of the Three Stars in the South pattern affects the first candle body's center position, and defines where it must be above to be considered valid. The second tolerance specifies how close the second candle must be to this same position, as well as the deviation the ratio the candle body to its range may be in comparison to the first candle. The third restricts how large the second candle range may be in comparison to the first (prevents this pattern from being recognized if the second candle is similar to the first but larger).
The last two floating point values define upper and lower limits to the wick size of a Ladder Bottom's fourth candle to be considered valid.
█ HOW TO USE
While there are many moving parts to this script, I attempted to set the default values with what I believed may help identify the most patterns within reasonable definitions. When this script is applied to a chart, the Candle Detection Mode (along with the BREAKOUT settings) and all candle switches must be confirmed before patterns are displayed. All switches are on by default, so this gives the user an opportunity to pick which patterns to identify first before playing around in the settings.
All of the settings/inputs described above are meant for experimentation. I encourage the user to tweak these values at will to find which set ups work best for whichever charts they decide to apply these patterns to.
Refer to the patterns themselves during experimentation. The statistic information provided on the tooltips of the patterns are meant to help guide input decisions. The breadth of candlestick theory is deep, and this was an attempt at capturing what I could in its sea of information.
█ LIMITATIONS
DISCLAIMER: While it may seem a bit paradoxical that this script aims to use past performance to potentially measure future results, past performance is not indicative of future results . Markets are highly adaptive and often unpredictable. This script is meant as an informational tool to show how patterns may behave. There is no guarantee that confidence intervals (or any other metric measured with this script) are accurate to the performance of patterns; caution must be exercised with all patterns identified regardless of how much information regarding prior performance is available.
Candlestick Theory - In the name, Candlestick Theory is a theory , and all theories come with their own limits. Some patterns identified by this script may be completely useless/unprofitable/unpredictable regardless of whatever combination of settings are used to identify them. However, if I truly believed this theory had no merit, this script would not exist. It is important to understand that this is a tool meant to be utilized with an array of others to procure positive (or negative, looking at you, short sellers ) results when navigating the complex world of finance.
To address the functionality note however, this script has an offset of 1 by default. Patterns will not be identified on the currently closing candle, only on the candle which has most recently closed. Attempting to have this script do both (offset by one or identify on close) lead to more trouble than it was worth. I personally just want users to be aware that patterns will not be identified immediately when they appear.
Trend Direction - Moving Averages - There is a small quirk with how MA settings will be adjusted if the user inputs two moving averages of the same length when the "MA Setting" is set to 'BOTH'. If Moving Averages have the same length, this script will default to only using MA 1 regardless of if the types of Moving Averages are different . I will experiment in the future to alleviate/reduce this restriction.
Price Analysis - BREAKOUT mode - With how identifying patterns with a look-ahead confirmation works, the percent returns for patterns that break out in either direction will be calculated on the same candle regardless of if P/L Offset is set to 'FROM CONFIRMATION' or 'FROM APPEARANCE'. This same issue is present in the Hikkake Hunter script mentioned earlier. This does not mean the P/L calculations are incorrect , the offset for the calculation is set by the number of candles required to confirm the pattern if 'FROM APPEARANCE' is selected. It just means that these two different P/L calculations will complete at the same time independent of the setting that's been selected.
Adaptive Coloring/Hard Limiting - Hard Limiting is only used with Adaptive Coloring and has no effect outside of it. If Hard Limiting is used, it is recommended to increase the 'Positive' and 'Negative' return tolerance values as a pattern's bullish/bearishness may be disproportionately represented with the gradient generated under a hard limit.
TARGET MODE - This mode will break rules regarding patterns that are overridden on purpose. If a pattern selected in TARGET mode would have otherwise been absorbed by a larger pattern, it will have that pattern's percent return calculated; potentially leading to duplicate returns being included in the matrix of all returns recognized by this script.
'Tall' Candle Setting - This is a wide-reaching setting, as approximately 30 different patterns or so rely on defining 'Tall' candles. Changing how 'Tall' candles are defined whether by the tolerance value those candles need to exceed or by the values of the candle used for the baseline comparison (RANGE/BODY) can wildly affect how this script functions under certain conditions. Refer to the tooltip of these settings for more information on which specific patterns are affected by this.
Doji Settings - There are roughly 10 or so two to three candle patterns which have Dojis as a part of them. If all Dojis are disabled, it will prevent some of these larger patterns from being recognized. This is a dependency issue that I may address in the future.
'Engulfing' Setting - Functionally, the two 'Engulfing' settings are quite different. Because of this, the 'RANGE' setting may cause certain patterns that would otherwise be valid under textbook and online references/definitions to not be recognized as such (like the Upside Gap Two Crows or Three Outside down).
█ PATTERN LIST
This script recognizes 85 patterns upon initial release. I am open to adding additional patterns to it in the future and any comments/suggestions are appreciated. It recognizes:
15 — 1 Candle Patterns
4 Hammer type patterns: Regular Hammer, Takuri Line, Shooting Star, and Hanging Man
9 Doji Candles: Regular Dojis, Northern/Southern Dojis, Gravestone/Dragonfly Dojis, Gapping Up/Down Dojis, and Long-Legged/Rickshaw Man Dojis
White/Black Long Days
32 — 2 Candle Patterns
4 Engulfing type patterns: Bullish/Bearish Engulfing and Last Engulfing Top/Bottom
Dark Cloud Cover
Bullish/Bearish Doji Star patterns
Hammer Inverted
Bullish/Bearish Haramis + Cross variants
Homing Pigeon
Bullish/Bearish Kicking
4 Lines type patterns: Bullish/Bearish Meeting/Separating Lines
Matching Low
On/In Neck patterns
Piercing pattern
Shooting Star (2 Lines)
Above/Below Stomach patterns
Thrusting
Tweezers Top/Bottom patterns
Two Black Gapping
Rising/Falling Window patterns
29 — 3 Candle Patterns
Bullish/Bearish Abandoned Baby patterns
Advance Block
Collapsing Doji Star
Deliberation
Upside/Downside Gap Three Methods patterns
Three Inside/Outside Up/Down patterns (4 total)
Bullish/Bearish Side-by-Side patterns
Morning/Evening Star patterns + Doji variants
Stick Sandwich
Downside/Upside Tasuki Gap patterns
Three Black Crows + Identical variation
Three White Soldiers
Three Stars in the South
Bullish/Bearish Tri-Star patterns
Two Crows + Upside Gap variant
Unique Three River Bottom
3 — 4 Candle Patterns
Concealing Baby Swallow
Bullish/Bearish Three Line Strike patterns
6 — 5 Candle Patterns
Bullish/Bearish Breakaway patterns
Ladder Bottom
Mat Hold
Rising/Falling Three Methods patterns
█ WORKS CITED
Because of the amount of time needed to complete this script, I am unable to provide exact dates for when some of these references were used. I will also not provide every single reference, as citing a reference for each individual pattern and the place it was reviewed would lead to a bibliography larger than this script and its description combined. There were five major resources I used when building this script, one book, two websites (for various different reasons including patterns, moving averages, and various other articles of information), various scripts from TradingView's public library (including TradingView's own source code for *all* candle patterns ), and PineScrypt's reference manual.
Bulkowski, Thomas N. Encyclopedia of Candlestick Patterns . Hoboken, New Jersey: John Wiley & Sons Inc., 2008. E-book (google books).
Various. Numerous webpages. CandleScanner . 2023. online. Accessed 2020 - 2023.
Various. Numerous webpages. Investopedia . 2023. online. Accessed 2020 - 2023.
█ AKNOWLEDGEMENTS
I want to take the time here to thank all of my friends and family, both online and in real life, for the support they've given me over the last few years in this endeavor. My pets who tried their hardest to keep me from completing it. And work for the grit to continue pushing through until this script's completion.
This belongs to me just as much as it does anyone else. Whether you are an institutional trader, gold bug hedging against the dollar, retail ape who got in on a squeeze, or just parents trying to grow their retirement/save for the kids. This belongs to everyone.
Private Beta for new features to be tested can be found here .
Vires In Numeris
*Backtesting System ⚉ OVERVIEW ⚉
One of the best Systems for Backtesting your Strategies.
Incredibly flexible, simple, fast and feature-rich system — will solve most of your queries without much effort.
Many systems for setting StopLoss, TakeProfit, Risk Management and advanced Filters.
All you need to do is plug in your indicator and start Backtesting .
I intentionally left the option to use my System on Full Power before you load your indicator into it.
The system uses the built-in simple and popular moving average crossover signal for this purpose. (EMA 50 & 200).
Also Highly Recommend that you Fully use ALL of the features of this system so that you understand how they work before you ask questions.
Also tried to leave TIPS for each feature everywhere, read Tips, activate them and see how they work.
But before you use this system, I Recommend you to read the following description in Full.
—————— How to connect your indicator in 2 steps:
Adapt your indicator by adding only 2 lines of code and then connect it to this Backtesting System.
Step 1 — Create your connector, For doing so:
• 1 — Find or create in your indicator where are the conditions printing 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 wether it's a MACD, RSI , Pivots, or whatever indicator with Clear Buy and Sell conditions.
//@version=5
indicator('Moving Average Cross', overlay = true)
MA200 = ta.𝚎𝚖𝚊(close, 200)
MA50 = ta.𝚎𝚖𝚊(close, 50)
// Generate Buy and Sell conditions
buy = ta.crossover (MA200, MA50)
sell = ta.crossunder (MA200, MA50)
plot(MA200, color=color.green)
plot(MA50 , color=color.red )
bgcolor(color = buy ? color.green : sell ? color.red : na, title='SIGNALS')
// ———————————————— SIGNAL FOR SYSTEM ————————————————
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, title='🔌Connector🔌', display = display.none)
// —————— 🔥 The Backtesting System expects the value to be exactly +1 for the 𝚋𝚞𝚕𝚕𝚒𝚜𝚑 signal, and -1 for the 𝚋𝚎𝚊𝚛𝚒𝚜𝚑 signal
Basically, I identified my Buy & Sell conditions in the code and added this at the bottom of my indicator code
Now you can connect your indicator to the Backtesting System using the Step 2
Step 2 — Connect the connector
• 1 — Add your updated indicator to a TradingView chart and Add the Backtesting System as well to the SAME chart
• 2 — Open the Backtesting System settings and in the External Source field select your 🔌Connector🔌 (which comes from your indicator)
_______________________________
⚉ MAIN SETTINGS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 — Select your indicator. Add your indicator by following the 2 steps described above and select it in the menu. To familiarize yourself with the system until you select your indicator, you will have an in-built strategy of crossing the two moving EMA's of 50 and 200.
Long Deals — Enable/Disable Long Deals.
Short Deals — Enable/Disable Short Deals.
Wait End Deal — Enable/Disable waiting for a trade to close at Stop Loss/Take Profit. Until the trade closes on the Stop Loss or Take Profit, no new trade will open.
Reverse Deals — To force the opening of a trade in the opposite direction.
ReEntry Deal — Automatically open the same new deal after the deal is closed.
ReOpen Deal — Reopen the trade if the same signal is received. For example, if you are already in the long and a new signal is received in the long, the trade will reopen. * Does not work if Wait End Deal is enabled.
𝐓𝐚𝐤𝐞 𝐏𝐫𝐨𝐟𝐢𝐭:
None — Disables take profit. Useful if you only want to use dynamic stoplosses such as MA, Fast-Trailing, ATR Trail.
FIXED % — Fixed take profit in percent.
FIXED $ — Fixed Take in Money.
ATR — Fixed Take based on ATR.
R:R — Fixed Take based on the size of your stop loss. For example, if your stop is 10% and R:R=1, then the Take would be 10%. R:R=3 Take would be 30%, etc.
HH / LL — Fixed Take based on the previous maximum/minimum (extremum).
𝐒𝐭𝐨𝐩 𝐋𝐨𝐬𝐬:
None — Disables Stop Loss. Useful if you want to work without a stop loss. *Be careful if Wait End Deal is enabled, the trade may not close for a long time until it reaches the Take.
FIXED % — Fixed Stop in percent.
FIXED $ — Fixed Stop in Money.
TRAILING — Dynamic Trailing Stop like on the stock exchanges.
FAST TRAIL — Dynamic Fast Trailing Stop moves immediately in profit and stays in place if the price stands still or the price moves in loss.
ATR — Fixed Stop based on the ATR.
ATR TRAIL — Dynamic Trailing Stop based on the ATR.
LO / HI — A Fixed Stop based on the last Maximum/Minimum extemum. Allows you to place a stop just behind or above the low/high candle.
MA — Dynamic Stop based on selected Moving Average. * You will have 8 types of MA (EMA, SMA, HMA, etc.) to choose from, but you can easily add dozens of other MAs, which makes this type of stop incredibly flexible.
Add % — If true, then with the "𝗦𝘁𝗼𝗽 %" parameter you can add percentages to any of the current SL. Can be especially useful when using Stop - 𝗔𝗧𝗥 or 𝗠𝗔 or 𝗟𝗢/𝗛𝗜. For example with 𝗟𝗢/𝗛𝗜 to put a stop for the last High/Low and add 0.5% additional Stoploss.
Fixed R:R — If the stop loss is Dynamic (Trailing or MA) then if R:R true can also be made Dynamic * Use it carefully, the function is experimental.
_________________________________________
⚉ TAKE PROFIT LEVELS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
A unique method of constructing intermediate Take Profit Levels will allow you to select up to 5 intermediate Take Profit Levels and one intermediate Stop Loss.
Intermediate Take Profit Levels are perfectly calculated into 5 equal parts in the form of levels from the entry point to the final Take Profit target.
All you need to do is to choose the necessary levels for fixing and how much you want to fix at each level as a percentage. For example, TP 3 will always be exactly between the entry point and the Take Profit target. And the value of TP 3 = 50 will close 50% of the amount of the remaining size of the position.
Note: all intermediate SL/TP are closed from the remaining position amount and not from the initial position size, as TV does by default.
SL 0 Position — works in the same way as TP 1-5 but it's Stop. With this parameter you can set the position where the intermediate stop will be set.
Breakeven on TP — When activated, it allows you to put the stop loss at Breakeven after the selected TP is reached. For this function to work as it should - you need to activate an intermediate Take. For example, if TP 3 is activated and Breakeven on TP = 3, then after the price reaches this level, the Stop loss will go to Breakeven.
* This function will not work with Dynamic Stoplosses, because it simply does not make sense.
CoolDown # Bars — When activated, allows you to add a delay before a new trade is opened. A new trade after CoolDown will not be opened until # bars pass and a new signal appears.
_____________________________
⚉ TIME FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Powerful time filter code that allows you to filter data based on specific time zones, dates, and session days. This code is ideal for those who need to analyze data from different time zones and weed out irrelevant data.
With Time Filter, you can easily set the starting and ending time zones by which you want to filter the data.
You can also set a start and end date for your data and choose which days of the week to include in the analysis. In addition, you can specify start and end times for a specific session, allowing you to focus your analysis on specific time periods.
_________________________________
⚉ SIGNAL FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Signal Filters — allows you to easily customize and optimize your trading strategies based on 10 filters.
Each filter is designed to help you weed out inaccurate signals to minimize your risks.
Let's take a look at their features:
__________________________________
⚉ RISK MANAGEMENT ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Risk management tools that allow you to set the maximum number of losing trades in a row, a limit on the number of trades per day or week and other filters.
Loss Streak — Set Max number of consecutive loss trades.
Win Streak — Max Winning Streak Length.
Row Loss InDay — Max of consecutive days with a loss in a row.
DrawDown % — Max DrawDown (in % of strategy equity).
InDay Loss % — Set Max Intraday Loss.
Daily Trades — Limit the number of MAX trades per day.
Weekly Trades — Limit the number of MAX trades per week.
* 🡅 I would Not Recommend using these functions without understanding how they work.
Order Size — Position Size
• NONE — Use the default position size settings in Tab "Properties".
• EQUITY — The amount of the allowed position as a percentage of the initial capital.
• Use Net Profit — On/Off the use of profit in the following trades. *Only works if the type is EQUITY.
• SIZE — The size of the allowed position in monetary terms.
• Contracts — The size of the allowed position in the contracts. 1 Сontract = Сurrent price.
________________
⚉ NOTES ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
It is important to note that I have never worked with Backtesting and the functions associated with them before.
It took me about a month of slow work to build this system.
I want to say Big Thanks:
• The PineScripters🌲 group in Telegram , the guys suggested how to implement some features. Especially @allanster
• Thanks to all those people who share their developments for free on TV and not only.
• I also thank myself for not giving up and finishing the project, and not trying to monetize the system by selling it. * Although I really want the money :)
I tried hard to make it as fast and convenient as possible for everyone who will use my code.
That's why I didn't use any libraries and dozens of heavy functions, and I managed to fit in 8+-functions for the whole code.
Absolutely every block of code I tried to make full-fledged modular, that it was easy to import/edit for myself (you).
I have abused the Ternary Pine operator a little (a lot) so that the code was as compact as possible.
Nevertheless, I tried very hard to keep my code very understandable even for beginners.
At last I managed to write 500 lines of code, making it one of the fastest and most feature-rich systems out there.
I hope everyone enjoys my work.
Put comments and write likes.
FBMAEN:
TradingView indicator for FBMA strategy
People oftem ask: “Dmitry, BABA, TSLA, AAPL flies like a rocket! Well, what are we buying!?” - And I say no, the price does not act like a straight rocket upwards or downwards, instead it breathes, inhales moving away from the moving average and exhales returning to it, so we will wait for the first pullback and buy exactly at the value of the moving average.
Your new paradigm: wait for the stock to pull back to the moving average rather than chasing the price
And one more thing... Remember, you don't want to buy a stock when it's going down, you'll start to have doubts. it's against human nature to go long when the price is falling, but that's why this strategy works so well. We buy on the price rollback (pullback to the moving average), but we DO IT WHILE FOLLOWING THE TREND.
The biggest consequence of this strategy, my author's FBMA strategy and this is a game changer (results are in the comments).
So, let's dive into FBMA indicator settings:
Main settings
ATR Period — Period of intergrated ATR Indicator(shows ATR in a small dashboard);
Settings of Moving Averages
Sign Moving Averages? — shows values of moving averages near their lines on the chart;
Fix MAs' signatures overlapping? — automatically MAs' signatures overlapping (specifically for SMAs and EMAs!) ;
Fix MAs' signatures overlapping between SMAs and EMAs? — automatically group overlapping between EMAs' and SMAs' signatures;
Min distance between MAs' signatures (in % of ATR) — minimal distance between MAs' signatures that indicator will push away MAs' signatures from each other if they are overlapped;
Dashboard
Dashboard position — position of dashboard on the chart ( 9 options ).
Settings of MAs
Source;
Period;
Option for showing EMA and/or SMA of chosen period and source;
Line colour ;
Signature colour .
Addons
Show data by selected timeframe? — shows difference of current price opening and opening a "timeframe" time ago;
Shows MAs only if asset has grown by selected growth % in selected timeframe?
Growth, % — percent, which asset has to gain in order for MAs to be plotted;
Timeframe — frequency with which price's current and previous opening are being will be compared;
Show analog MAs' signatures? — shows MAs' value in a small table;
Show cloud between 1st and 2nd MAs? — shows cloud for both EMAs and SMAs simultaneously).
Price Action
This settings are intuitively understandable
Feel free to leave your questions or suggestions in the comments!
* Price Action-section was taken from ChrisMoody's CM_Price_Action and rebuilt.
RU:
Индикатор TradingView для стратегии ПООС
Мне часто пишут в личку: “Дмитрий, BABA, TSLA , AAPL летит ракетой! Ну что покупаем!?”- А я говорю нет, цена не летит по прямой ракетой вверх, она дышит, делает вдохи отдаляясь от скользящей и выдохи возвращаясь к ней, поэтому мы дождёмся первого пуллбэка и купим точно на значении скользящей
Ваша новая парадигма: ждать акцию на пуллбэке к скользящей по тренду, а не гнаться за ценой
И ещё… Помните, вы не захотите покупать акцию в момент, когда она падает, вы начнете сомневаться т.к. это против человеческой природы заходить в лонг при падении цены, но именно поэтому эта стратегия работает так эффективно, т.к. мы покупаем на откате цены (пуллбэке к скользящей), но ПО ТРЕНДУ
Самое большее следствие из этой стратегии, моя авторская стратегия ПООС и это гейм-чейнджер (результаты в комментариях).
Итак, давайте посмотрим сами настройки индикатора:
Основные настройки
ATR Period — период интегрированного индикатора ATR (показывает ATR на небольшой панели);
Настройки скользящих средних
Sign Moving Averages? — показывает значения скользящих средних рядом с их линиями на графике;
Исправить перекрытие сигнатур МА? — автоматически сигнатуры СС перекрываются (специально для SMA и EMA!) ;
Исправить перекрытие сигнатур МА между SMA и EMA? — автоматически группировать перекрытие между сигнатурами EMA и SMA;
Минимальное расстояние между сигнатурами скользящих средних (в % от ATR) — минимальное расстояние между сигнатурами скользящих средних, при котором индикатор будет отталкивать сигнатуры скользящих средних друг от друга, если они перекрываются;
Панель управления
Dashboard position — положение таблицы на графике ( 9 вариантов ).
Настройки МА
Source;
Период;
Опция отображения EMA и/или SMA выбранного периода и source;
Цвет линии ;
Цвет подписи .
Дополнения
Показать данные по выбранному таймфрейму? — показывает разницу текущей цены открытия и цены открытия в прошлом, по времени равному величины параметра "Таймфрейм";
Показывает MA только в том случае, если актив вырос на выбранный % роста за выбранный период времени?
Прирост, % — процент, на который актив должен набраться, чтобы скользящие средние были построены;
Таймфрейм — частота, с которой будет сравниваться текущее и предыдущее открытие цены;
Показать сигнатуры аналоговых МА? — показывает значение МА в небольшой таблице;
Показать облако между 1-й и 2-й скользящими средними? — показывает облако для EMA и SMA одновременно).
Price Action
Эти настройки будут интуитивно понятны
Оставляете свои вопросы и предложения в комментариях, всё учтём!
* Price Action-section was taken from ChrisMoody's CM_Price_Action and rebuilt.
Extreme Volume Support Resistance LevelsExtreme Volume Support Resistance Levels are S/R levels(zones, basically), based on extreme volume .
Settings:
Lookback -- number of bars, which algorithm will be using;
Volume Threshold Period -- period of MA (Volume MA), which smoothers volume in order to find the extremes;
Volume Threshold Multiplier -- multiplier for Volume MA, which "lift" Volume MA and thus will provide the algorithm with more accurate extreme volume ;
Number of zones to show -- number of last S/R zones, which will be shown on the chart.
RU:
Extreme Volume Support Resistance Levels — это уровни S/R (зоны, в основном), основанные на избыточном объеме.
Параметры:
Lookback -- число баров, которое алгоритм будет использовать для расчётов;
Volume Threshold Period -- период MA (Volume MA), которая сглаживает объем для нахождения экстремумов объёма;
Volume Threshold Multiplier -- множитель для Volume MA, который "поднимает" Volume MA и тем самым обеспечивает алгоритм более точными значениями экстремального объёма;
Количество зон для отображения -- количество оставшихся зон S/R, которые отображаются на графике.
ATR Trend FollowingThe script filters stocks on the basis of ATR. If the stock has moved above 7 times the ATR from the lows, the system generates buy signal and continues till the stock drops by 2 ATR. It is a good system in trending markets however in sideways consolidating markets, the system must be avoided. In trending markets it can generate good returns with significant Risk to Reward Ratio. Use it in confirmation with other trend depicting indicators is expected to generate better results.
Key Performance IndicatorWe are happy to introduce the Key Performance Indicator by Detlev Matthes. This is an amazing tool to quantify the efficiency of a trading system and identify potential spots of improvement.
Abstract
A key performance indicator with high explanatory value for the quality of trading systems is introduced. Quality is expressed as an indicator and comprises the individual values of qualitative aspects. The work developing the KPI was submitted for the 2017 VTAD Award and won first prize.
Introduction
Imagine that you have a variety of stock trading systems from which to select. During backtesting, each trading system will deliver different results with regard to its indicators (depending on, inter alia, its parameters and the stock used). You will also get different forms of progression for profit development. It requires great experience to select the “best” trading system from this variety of information (provided by several indicators) and significantly varying equity progression forms. In this paper, an indicator will be introduced that expresses the quality of a trading system in just one figure. With such an indicator, you can view the results of one backtest at a glance and also more easily compare a variety of backtesting results with one another.
If you are interested in learning more about the calculations behind this indicator then I have included a link to the english version of his research paper.
Along with this, we now offer indicator development services. If you are interested in learning more then feel free to reach out to get a quote for your project.
**Please note that we have NOT inputted any real strategy into the code and therefore it is not producing any real value. Feel free to change the code as desired to test any strategy!**
drive.google.com
VWAP/EMA50/EMA200We script this one for combining VWAP , EMA50 and EMA200. The tool is fantastic if traders know how VWAP , EMA work? Just adding this script in your favorite and work like charm:
VWAP: How to trade with that
- One of the simplest uses of the VWAP is gauging support and/or resistance.
- A trader who is long a stock can use the VWAP as a target exit if its trading below.
- A stock trading over intraday VWAP may be bullish , while a stock trading under may be bearish .
EMA 50/EMA200: How to trade with that timeframe 50-day or 200-day period
- Identify the trend of market in longterm
- Golden-cross (short term EMA cross above longterm EMA ) is call golden-cross signals. It is opportunity for buying.
- Deal-cross ( short term EMA cross below longterm EMA ) is call dead-cross signals. It is opportunity for selling.
- Identify support levels
- Identify resistance levels
Let me know if you see anything else that should be added/changed.
ConsensioThis indicator is based on Consensio strategy.
Green = 100% Bullish,
Yellow = 75%-90% Bullish,
Orange = 30%-75% Bullish,
Red = 100% Cash Position
1-4 Green candles = Bullish trend momentum (4 is stronger)
1-4 Red candles = Bearish trend momentum (4 is stronger)
INDIGO - Cloud System ©INDIGO Cloud System ©
This script shows the monthly dip and peak zones and the daily highs & lows.
The green zone is the dip zone. It's the place to enter a long position if you think there is or will be a reversal.
The red zone is the peak zone. It's the place to enter a short position if you think there is or will be a reversal.
The script uses the INDIGO Cloud System ©, the Ultimate RSI and the Market Direction Indicator to find an entry at the most optimal point in space and time.
The exit for the long trade is on the purple line and the exit for the short trade is on the blue line.
It also has an RSI exit to minimize the risk of a sudden reversal in the wrong direction while in trade.
You can set TP and SL to see the effects of it on the chart. Be aware that these change a lot of trades so use it wisely.
The labels are connected to alerts to notify you of a possible entry or exit.
This script uses the Ultimate RSI by ChrisMoody, thanks for creating this Chris !
This script also uses the Market Direction Indicator by LazyBear, great script !
You can use the MD Filter to filter out some bad trades. It decreases losses but also some profits.
Experiment with the settings, each pairing needs different settings.
--> Use this script at your own risk. Do your own research, never invest money you're not willing to lose and never put your trust in one indicator !
To my best knowledge this script doesn't repaint. I never use the close and only use high/low when value can't be untrue again. If you find repainting in this script PLEASE let me know !
Feel free to contact me for questions or feedback.
Enjoy the script :)
HPH's SuperKeltnerThis indicator combines the Supertrend (to determine the main trend direction) with two Keltner channels (used for add and take profit signals) to construct a trend trading system.
These are the available settings:
General
UseTrendChange ➞ toggle trend change alerts and labels
UseAdds ➞ toggle add to position alerts and labels
UseTakeProfits ➞ toggle take profit alerts and labels
PrematureAdds ➞ toggle adding to position as soon as the add channels are left (default is false, so the add signal will only fire once the channels are re-entered)
PrematureTakeProfits ➞ toggle taking profit as soon as the tp channels are left (default is false, so the tp signal will only fire once the channels are re-entered)
Visualization
Show Add Keltner ➞ toggle display of the channels used for adding to the position
Show TP Keltner ➞ toggle display of the channels used for taking profit
Show SuperTrend ➞ toggle display of the Supertrend
Keltner
Standard Keltner channels settings except for the fact that there are two different multipliers. The Keltner TP Multiplier should generally be bigger than the Keltner Add Multiplier , as the channels are hit differently in trending markets. I recommend you to use the visualization settings to show the channels and adjust the settings to your liking.
Supertrend
Standard Supertrend settings, nothing to add here.
Alerts
Use the alert messages to customize what alert text the indicator will send. This makes it possible to use the script to automate trading bots.
By default, the alerts are sent after the candle has closed. This ensures that no repainting is happening. If you like the risk, you can toggle the corresponding WaitFor Confirmation if you wish to receive the signals earlier (max. once per bar).
Enjoy!
Basic SMA 200 StrategyThe SMA 200 basic strategy will be more than familiar to most traders.
This strategy is to stay with the programming language so to say the "Hello World" of trading.
The SMA 200 basic strategy is also one of the simplest strategies in trading. All that is required is the price and a 200 period moving average. Usually the strategy is used in the daily chart.
The rules are as follows:
Entry: A position is opened when the price crosses the moving average 200 from the bottom to the top.
Exit: The position is closed when the price crosses the moving average from top to bottom.
This is a trend following system and was originally used for trading stocks.
In my opinion, trading with the strategy is recommended to every beginner. There are strategies with better performance, but they are much more complicated to implement. And that's where the big advantage of the strategy can be seen.
Beginners are more than overwhelmed at the beginning of their trading career. Often beginners trade in the 5 min chart with 6 different indicators some signals that they have seen in a Youtube video.
Comparable to a beginner driver who immediately gets into a Porsche as his first car.
Beginners should follow simple rules and avoid intraday charts. Above all, you should do the actual work of a trader.A trader does not just press the mouse twenty times a day and then has easily earned 2000 $. A trader tests systems down to the smallest detail, optimizes and tests again, until he has found an almost " waterproof " trading system. The 200 SMA basic strategy is excellent for gaining experience, learning to follow the rules of a system and not to burn your money right away.
With this script you can test how successful the "simplest strategy in the world" would have been in the past.
Small tip: Do not trade Forex with it it will never work. The strategy is made for long trends and you can find them for example in the stock market.
Have fun with it! About a positive feedback I would be very happy of course.
Full strategy AllinOne with risk management MACD RSI PSAR ATR MAHey, I am glad to present you one of the strategies where I put a lot of time in it.
This strategy can be adapted to all type of timecharts like scalping, daytrading or swing.
The context is the next one :
First we have the ATR to calculate our TP/SL points. At the same time we have another rule once we enter(we enter based on % risk from total equity, in this example 1%, at the same time, lowest ammount for this example is 0.1 lots, but can be modified to 0.01), so we can exit both by tp/sl points, or by losing 1% of our equity or winning 1% of our total equity. It's dinamic.
The strategy is made from
Trend direction :
PSAR
First confirmation point :
Crossover between 10EMA and Bollinger bands middle point
Second confirmation
MACD histogram
Third confirmation
RSI overbought/oversold levels
For entries : we check trend with psar, then once ema cross bb middle point, we confirm together with rsi level for overbought/oversold and macd histogram ( > 0 or <0).
We exit, when we have opposite sign, like from buy to sell or sell to buy, or when we reach tp/sl points, or when we reach % basaed equity points.
It can be changed to be fixed lots, or fixed tp/sl , you just have to uncomment the size from entries, and tp/sl lines.
At the same time, it has the possibility if one desires, to trade only concrete forex session like european, asian and so on for intraday trading.
Hope you enjoy it.
Let me know how it goes.
Elder's Impulse System with weekly EMA Filter - ValenteThis indicator was based on the Elders Impulse System by astraloverflow.
The only difference is that I included the weekly EMA26 as a filter and you can plot it on the graph if you want (unchecking the Weekly EMA26 won't turn the filter off, will only stop plotting it).
The indicator works this way:
When the MACD Histogram is growing UP, the EMA13 is pointing UP AND the Weekly EMA26 is pointing UP, the bar is Green
When the opposite is true, the bar is Red.
When any condition from both green and red is not true, the bar is blue.
In my opinion, this particular indicator works better on the D1 time frame. I recommended using the original one, by astraloverflow for other time frames.
I hope it is useful!
Chaloke System StrategyChaloke System Strategy
This is a trend indicator
Atr and 3 moving averages are used
Short 9-day moving average,Medium 15-day moving average,Calculated with a long 24-day moving average.
Atr period : 5
Sht,Mid,Lng calculation method is different
Buying Strategy
long = crossover(Sht,Mid) and close > Sht
Selling Strategy
short = crossunder(Sht, Lng ) or close < Lng
Buy should be done when the barcolor turns green
Sell should be done when barcolor is red
When the barcolor is black, there may be change.
Leverage Strategy and a few words on risk/opportunityHello traders,
I started this script as a joke for someone... finally appears it could be used for educational content
Let's talk about leverage and margin call
Margin Call
A margin call is the broker's demand that an investor deposit additional money or securities so that the account is brought up to the minimum value, known as the maintenance margin.
A margin call usually means that one or more of the securities held in the margin account has decreased in value below a certain point.
Leverage
A leverage is a system which allows the trader to open positions much larger than his own capital. ... “Leverage” usually refers to the ratio between the position value and the investment needed,
Strat
The strategy simulates long/short positions on a 4h high/low breakout based on the chart candle close.
The panel below shows the strategy equity curve. Activating the margin call option will show when the account would be margin called giving the settings
Casino
I'm not doing any financial recommendation here.
I made this strategy so that people include more risk management metrics into their strategy.
From the code, we see it's fairly easy to calculate a leveraged position size and a margin call flag - when that flag is hit, the system stops trading.
I simplified things to the extreme here but my point is that the leverage is a double-edge sword gift.
Assuming we always take the same position sizing, increasing the leverage speed up how fast a margin could be ..... called. (bad joke? feel free to tell me). Not saying it will, saying it introduces more risk by design.
Then one could say "I'll just turn off that stupid margin call option". And that's when someone starts backtesting with unrealistic market conditions.
Finally...
When I backtest I always assume the worst in every scenario possible (because I'm French), I always try to minimize the risk first (also because I'm French), keeping as close from 0 as possible (French again)
Then I add the "opportunity" component, looking to catch the maximum of opportunity while keeping the risk low.
It's like a Rubix cube puzzle - decreasing the risk is one side of the equation but whenever I try to catch more opportunity... my risks increases.
Then I update my risk... and now the opportunity decreases... (#wut #wen #simple)
Completely removing the risk from a trading strategy isn't something I wouldn't dare doing.
Trading involves risk. Being obsessed by decreasing the risk is what I do BEST :)
Dave