Breakouts with Tests & Retests [LuxAlgo]The Breakouts Tests & Retests indicator highlights tests and retests of levels constructed from detected swing points. A swing area of interest switches colors when a breakout occurs.
Users can control the sensitivity of the swing point detection and the width of the swing areas.
🔶 USAGE
When a Swing point is detected, an area of interest is drawn, colored green for a bullish swing and red when bearish.
A test is confirmed when the opening price is situated in the area of interest, and the closing price is above or below the area, depending on whether it is a bullish or bearish swing. Tests are highlighted with a solid-colored triangle.
A breakout is confirmed when the price closes in the opposite position, below or above the area, in which case the area will switch colors.
If the opening price is located within the area and the closing price closes outside the area, in the same direction as the breakout, this is considered a retest . Retests are highlighted with a hollow-colored triangle.
Note that tests/retests do not act on wicks. The main factor is that the opening price is in the area of interest, while the closing price is outside.
🔹 Area Of Interest Width
The user can adjust the width of the swing areas. Changing the " Width " is a fast and easy way to find different areas of interest.
A higher "Multiple" setting would return a wider area, allowing price to develop within it for a longer period of time and potentially provide later test signals.
When a swing area is broken, a higher "Width" setting can make it more complicated for the price to break it again, allowing a swing area to remain valid for a longer period of time thus potentially providing more retest signals.
🔶 DETAILS
Generally, only one bullish/bearish pattern can be active at a time. This means that no more than 1 bullish or bearish area will be active.
The " Display " settings, however, can help control how areas of different types are displayed.
Bullish AND Bearish: Both, bullish and bearish patterns can be drawn at the same time
Bullish OR Bearish: Only 1 bullish or 1 bearish pattern is drawn at a time
Bullish: Only bullish patterns
Bearish: Only bearish patterns
🔹 Test/Retest Labels
The user can adjust the settings so only the latest test/retest label is shown or set a minimum number of bars until the next test/retest can be drawn.
🔹 Maximum Bars
Users can set a limit of bars for when there is no test/retest in that period; the area of interest won't be updated anymore and will be available and ready for the next Swing.
An option for pulling the area back to the last retest is included.
🔶 SETTINGS
Display: Determines which swing areas are displayed by the indicator. See the "DETAILS" section for more information
Multiple: Adjusts the width of the areas of interest
Maximum Bars: Limit of bars for when there is no test/retest
Display Test/Retest Labels: Show all labels or just the last test/retest label associated with a swing area
Minimum Bars: Minimum bars required for a subsequent test/retest label are allowed to be displayed
Set Back To Last Retest: When after "Maximum Bars" no test/retest is found, place the right side of the area at the last test/retest
🔹 Swings
Left: x amount of wicks on the left of a potential Swing need to be higher/lower for a Swing to be confirmed.
Right: The number of wicks on the right of a potential swing needs to be higher/lower for a Swing to be confirmed.
🔹 Style
Bullish: color for test period (before a breakout) / retest period (after a breakout)
Bearish: color for test period (before a breakout) / retest period (after a breakout)
Label Size
Test
FreedX Backtest Plus█ Our new FreedX Backtest PLUS template enhances TradingView backtesting with smart features like Mean Reversion, Flexible Volatility, Liquidation Filter, and Better Trend Filtering, making strategies more effective. It lets users set up automated alerts easily. This guide explains how to make the most of these improved features.
The Trading Date Settings feature in our TradingView script allows you to refine their backtesting parameters by specifying trading dates and hours. This feature enhances the accuracy of the backtest by aligning it with specific time frames and days, ensuring that the strategy is tested under relevant market conditions.
Features:
⚙️ Enable Trading Between Specific Dates:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific date range.
💡 How to Use:
→ Input the Start Date and End Date for the backtest period.
→ The script will execute the strategy only within this specified date range.
⚙️ Enable Trading Between Specific Hours:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific hour range.
💡 How to Use:
→ Input the start and end hour for in Trading Session section.
→ The script will execute the strategy only within this specified hour range.
⚙️ Enable Trading on Specified Days of the Week:
🎯 Purpose:
→ Gives you the option to conduct backtesting on selected days of the week, tailoring the strategy to particular market behaviours that may occur on these days.
💡 How to Use:
→ Select the days of the week for the backtest.
→ The script will activate the trading strategy only on these chosen days.
█ BUY/SELL TRIGGER SETTINGS
The Buy/Sell Trigger Settings feature is designed to provide users with flexibility in defining the conditions for 'LONG' and 'SHORT' signals based on various indicator types. This customization is crucial for tailoring strategies to different trading styles and market conditions.
Features:
⚙️ Single-Line Plotted Indicators :
🎯 Purpose:
→ Enables you to select a single-line plotted indicator as a source for backtesting. You can define specific levels to trigger 'LONG' or 'SHORT' signals.
💡 How to Use:
→ Choose a Single-Line Plotted indicator as the source.
→ Set the top and bottom levels for the indicator.
→ The script triggers 'LONG' signals at the bottom level and 'SHORT' signals at the top level.
⚙️ Two-Line Plotted Indicators :
🎯 Purpose:
→ Allows backtesting with two-line cross plot sources. Signals are generated based on the crossover of these lines.
💡 How to Use:
→ Select two lines as 'Source 1' and 'Source 2' for the indicator.
→ The script triggers a 'LONG' signal when 'Source 1' crosses above 'Source 2'.
→ Conversely, a 'SHORT' signal is triggered when 'Source 2' crosses above 'Source 1'.
⚙️ Custom Signals :
🎯 Purpose:
→ This setting enables users to define their own criteria for LONG, SHORT, and CLOSE signals based on custom indicator outputs.
💡 How to Use:
→ Select the custom source for your signals.
→ Define the output values that correspond to each signal type (e.g., “1” for 'LONG', “-1” for SHORT, and “0” for CLOSE).
→ The script will trigger signals according to these custom-defined values.
█ TP/SL SETTINGS
The TP/SL (Take Profit/Stop Loss) Settings feature is designed to give users control over their profit securing and risk mitigation strategies. This feature allows for setting custom TP and SL levels, which can be critical in managing trades effectively.
Features:
Custom TP/SL Levels for Long/Short Signals:
🎯 Purpose:
→ Enables users to set specific percentage levels for Take Profit and Stop Loss on long and short signals.
💡 How to Use:
→ In the TP/SL Settings, input the desired percentage for Take Profit (TP) and Stop Loss (SL).
→ For example, to secure a profit at a 10% price increase on LONG signals, set the “Long TP Percentage” to “10”.
█ STRATEGY SETTINGS
Strategy Settings provide a range of options to customize the trading strategy. These settings include leverage, position direction changes, and more, allowing users to tailor their strategy to their risk tolerance and market view.
Features:
⚙️ Enable Reverse Position:
🎯 Purpose:
→ Automatically closes a current position and opens a new one in the opposite direction upon detecting a signal for a market trend change.
🎯 Example:
→ If a LONG signal is received while in a SHORT position, the script will close the SHORT position and open a LONG position.
💡 How to Use:
→ Activate this feature in the Strategy Settings.
⚙️ Enable Spot Mode:
🎯 Purpose:
→ Disables short orders, using short signals only for closing long positions.
💡 How to Use:
→ Select the 'Spot Mode' option in the Strategy Settings.
⚙️ Enable Invert Signals:
🎯 Purpose:
→ Inverts all indicator signals, changing LONG signals to SHORT and vice versa.
💡 How to Use:
→ Opt for the 'Invert Signals' feature in the Strategy Settings.
⚙️ Enable Trailing Stop:
🎯 Purpose:
→ Triggers a trailing stop order on the exchange instead of a standard stop market order.
☢️ Caution:
→ The backtesting of this feature on TradingView may not accurately reflect actual strategy performance due to discrepancies between TradingView and exchange mechanisms.
💡 How to Use:
→ Select 'Trailing Stop' in the Strategy Settings.
⚙️ Enable Realistic TP & SL:
🎯 Purpose:
→ Goal is protect the user from unrealistic stop loss and take profit prices in live exchange trading conditions.
→ That feature continuously checks the take profit, stop loss and move stop loss prices to prevent unrealistic values. It changes their values according to (minimum realistic percent %)
💡 How to Use:
→ Select 'Enable Realistic TP & SL' in the Strategy Settings. Write min allowed percents.
█ LIMITER SETTINGS
Limiter Settings provide a range of options to customize the trading strategy. These settings include drawdown limits,contract limit, tradable ratio, for allowing users to tailor their strategy to their risk tolerance and market view.
⚙️ Leverage :
🎯 Purpose:
→ Allows users to apply leverage to their trades.
☢️ Caution:
→ High leverage can significantly increase the risk of liquidation.
→ High leverage and a high stop-loss price may override your fixed stoploss percentage, adjusting the stop-loss to the liquidation price.
💡 How to Use:
→ Set the desired leverage ratio in the Strategy Settings.
⚙️ Drawdown Limit:
🎯 Purpose:
→ Sets a maximum drawdown limit, automatically halting the strategy if this limit is reached, thereby controlling risk.
💡 How to Use:
→ Input the maximum drawdown limit (default: 100, min: 0, max: 100).
⚙️ Contract Limit:
🎯 Purpose:
→ Sets a maximum contract limit, beyond which the compound effect cannot be used. This is important to prevent market manipulation through large-volume orders.
💡 How to Use:
→ Input the maximum contract limit (min: 0).
⚙️ Tradable Ratio:
🎯 Purpose:
→ Sets a tradable ratio, it uses that ratio calculating entry cost for position. Main purpose is cash-out and cash-in according to balance change.
💡 How to Use:
→ Input the tradable ratio percent (default: 98, min: 0.1, max: 100).
█ CASH-OUT SETTINGS
Cash-Out Settings offer a money-saving mechanism that prevents entering positions with the entire balance due to cashed-out funds. It functions with a webhook alerts, but the 'Override Allocation %' option must be enabled.
⚙️ Cash-out Threshold %:
🎯 Purpose:
→ It is cash-out mechanism, it saves money with a target threshold.
💡 How to Use:
→ Input the threshold (min: 0).
⚙️ Cash-out Per Profitable Trades %:
🎯 Purpose:
→ It is cash-out mechanism, it saves money from every trade with a percent like commission.
💡 How to Use:
→ Input save percent% (min: 0).
█ ADAPTIVE VOLATILITY STRATEGY SETTINGS
Advanced Strategy Settings offer sophisticated methods for managing Stop Loss (SL) and Take Profit (TP) using the Average True Range (ATR). These settings are ideal for traders who want to incorporate volatility into their exit strategies.
Features:
⚙️ Enable ATR Stop Loss:
🎯 Purpose:
→ Automatically sets the Stop Loss price using the Average True Range at the time of entry.
💡 How to Use:
→ Activate 'ATR Stop Loss' to have the SL price calculated based on the current ATR.
⛓ Enable ATR Trailing Stop:
→ Dynamically updates the Stop Loss price with each new bar, according to the Average True Range.
→ Activate 'ATR Trailing Stop'.
→ Set the ATR Period to define the number of bars for ATR calculation.
→ Adjust the ATR SL Multiplier to determine the stop loss distance.
→ Modify the ATR TP Multiplier for setting the take profit distance.
⚙️ Enable ATR Take Profit:
🎯 Purpose:
→ Sets the Take Profit price based on the Average True Range at the time of entry.
💡 How to Use:
→ Choose 'ATR Take Profit' for TP price determination using ATR.
⚙️ Enable ATR Limit Entry:
🎯 Purpose:
→ Trade can not open in candle close price. Price should hit target price that based on average true range value.
💡 How to Use:
→ Choose 'ATR Limit Entry' for entry price determination using ATR.
⛓ Enable ATR Limit Entry Trailing Price:
→ Dynamically updates the entry price with each new bar, according to the Average True Range.
→ Activate 'ATR Limit Entry Trailing Price'.
→ Set the ATR Period to define the number of bars for ATR calculation.
→ Adjust the ATR SL Multiplier to determine the stop loss distance.
→ Modify the ATR TP Multiplier for setting the take profit distance.
█ TREND FILTERING SETTINGS
Trend Filtering Settings are designed to align trading strategies with the prevailing market trend, enhancing the precision of trade entries and exits. These settings utilize moving averages for trend analysis and decision-making.
Features:
⚙️ Enable Moving Average Filtering:
🎯 Purpose:
→ Limits trades based on moving average trends, blocking short trades in an uptrend and vice versa.
💡 How to Use:
→ Enable 'Trend Filtering'.
→ Set Fast and Slow MA Lengths for trend analysis.
→ Select the Timeframe for moving averages.
→ Choose the Moving Average Type for trend filtering.
🎯 Note:
→ Be cautious with timeframe selections; lower timeframes than the base may cause inconsistencies.
⛓ Exit on Trend Reversal:
→ Automatically closes a position when a market trend reversal is detected.
→ Turn on 'Exit on Trend Reversal' in the settings.
⛓ Ignore Counter Signals:
→ Ignores counter signals during trending market way.
→ If the trend way is long. All short signals will ignore and vice versa.
⛓ Enable Drawing On Chart:
→ Visually represents the trend filter directly on the chart for easy reference.
→ Activate 'Drawing On Chart' to see the trend filter overlaid on the trading chart.
⚙️ Enable Adx Filtering:
🎯 Purpose:
→ Limits trades based on adx value, blocking trades if trend strength is not enough or vice versa for invert mode.
💡 How to Use:
→ Enable 'Adx Filtering'.
→ Set Smoothing and Lengths for adx trend analysis.
→ Select level barrier for trend strength.
⚙️ Enable Custom Filtering:
🎯 Purpose:
→ Limits trades based on custom sources, blocking trades according to custom trades.
💡 How to Use:
→ Enable 'Custom Filtering'.
→ Select fast source.
→ Select slow source.
→ Enable lag mode.
█ MEAN REVERSION FILTERING SETTINGS
Mean Reversion Filtering Settings are designed to align trading strategies during accumulation market conditions. They set a distance from a line to permit trading. The purpose is to ensure that when the price strays too far from the mean line, it should revert back. In accumulation markets, price movements are generally horizontal. In such situations, mean reversion will operate like a grid, enabling profitable trades with low drawdown. However, when the market structure begins to trend, mean reversion filters may not be as profitable as in accumulation markets. For instance, let's say the price is rising and we are shorting the market until it reaches the mean price line. As the price goes up and the mean also rises, we will end up closing the position at a higher price, rendering the mean reversion system non-profitable. Therefore, consider this filter wisely; greater distances might work better in trending markets.
Features:
⚙️ Enable Kairi Filter:
🎯 Purpose:
→ Blocks trades based on distance percent between price and moving average.
💡 How to Use:
→ Enable 'Kairi Filter'.
→ Set Length and Distance Percent.
⛓ Enable Trend Drawing On Chart:
→ Visually represents the trend filter directly on the chart for easy reference.
→ Enable 'Drawing On Chart' to see the allowed regions overlaid on the trading chart with arrows.
⚙️ Enable VWAP Filter:
🎯 Purpose:
→ Blocks trades based on distance percent between price and volume weighted average price.
💡 How to Use:
→ Enable 'VWAP Filter'.
→ Set Timeframe as minutes and distance as percent.
⛓ Exit on Crossing with VWAP:
→ Automatically closes a position when the closing price of a candle crosses the VWAP.
→ Choose "Enable", 'Exit on Crossing with VWAP' in the settings.
⛓ Enable Drawing On Chart:
→ Visually represents the trend filter directly on the chart for easy reference.
→ Enable 'Drawing On Chart' to see the allowed regions overlaid on the trading chart with arrows.
█ LIQUIDATION FILTER SETTINGS
Liquidation filter compares the volume data of futures and spot markets.
Large differences in volume indicate unexpected market conditions, such as massive trading activities, which may signal liquidations.
Features:
⚙️ Enable Liquidation Filter:
🎯 Purpose:
→ Blocks trades based on extra ordinary volume differences in spot and futures market.
💡 How to Use:
→ Enable 'Liquidation Filter'.
→ Set behavior to react during that market conditions.
→ Set base amount to filter volume. This amount changes according to timeframe, you should find right amounts.
→ Liquidation candle count means, it is sum of liquidated candle count in last 20 bars.If you set 0, it means feature is disabled.
→ Detection, try to select the spot and perpetual symbols automatically, symbol names varies, it do not support all symbols, you should choose manually in that situation.
█ AUTOMATED ALERT SETTINGS
Automated Alert Settings are designed to integrate your TradingView script with webhook alerts. These settings allow for enhanced strategy execution and management.
Features:
Enable Webhook Alerts:
🎯 Purpose:
→ Trigger BUY, SELL, CHANGE_DIRECTION or MOVE_STOP_LOSS .
💡 How to Use:
→ Enable 'Webhook Alerts' in the settings.
→ Enter your Strategy Key.
→ Optionally, activate 'Override Allocation Percentage' to bypass the preset allocation percentage.
☢️ Caution:
→ Overriding the allocation percentage may result in trade entry errors due to misalignment between entry cost and available balance.
Enable Custom Alerts:
🎯 Purpose:
→ User can produce unique messages for different purposes.
💡 How to Use:
→ Enable 'Custom Alerts' in the settings.
→ Enter your message format type.
█ DEBUGGING SETTINGS
Debugging Settings are crucial for users who want to analyze and optimize their strategies. These settings provide tools for visualizing alerts on charts and accessing detailed data outputs.
Features:
⚙️ Enable Alert Plotting:
🎯 Purpose:
→ Allows users to visualize trading alerts directly on the chart, aiding in strategy analysis and refinement.
💡 How to Use:
→ Activate 'Alert Plotting' to draw alerts on the chart.
☢️ Caution:
→ It is recommended to disable this feature when creating actual trading alerts, as it can cause latency in signal processing.
⚙️ Enable Debugger Mode:
🎯 Purpose:
→ Facilitates strategy debugging by providing detailed data output in the TradingView Data Window.
💡 How to Use:
→ Turn on 'Debugger Mode' to access real-time data and metrics relevant to your strategy.
⚙️ Enable Table:
🎯 Purpose:
→ Facilitates strategy debugging by providing detailed data output in the TradingView Table on chart.
💡 How to Use:
→ Turn on 'Table' to access last closed candle data and metrics relevant to your strategy.
█ ADDITIONAL SETTINGS
⚙️ Enable Bar Magnifier
⚙️ Enable Using standard OHLC
PineUnitPineUnit by Guardian667
A comprehensive testing framework for Pine Script on TradingView. Built with well-known testing paradigms like Assertions, Units and Suites. It offers the ability to log test results in TradingView's built-in Pine Protocol view, as well as displaying them in a compact table directly on your chart, ensuring your scripts are both robust and reliable.
Unit testing Pine Script indicators, libraries, and strategies becomes seamless, ensuring the precision and dependability of your TradingView scripts. Beyond standard function testing based on predefined input values, PineUnit supports series value testing. This means a test can run on every bar, taking into account its specific values. Moreover, you can specify the exact conditions under which a test should execute, allowing for series-based testing only on bars fitting a designated scenario.
Detailed Guide & Source Code
Quick Start
To get started swiftly with PineUnit, follow this minimalistic example.
import Guardian667/PineUnit/1 as PineUnit
var testSession = PineUnit.createTestSession()
var trueTest = testSession.createSimpleTest("True is always True")
trueTest.assertTrue(true)
testSession.report()
After running your script, you'll notice a table on your chart displaying the test results. For a detailed log output, you can also utilize the Pine Protocol view in TradingView.
--------------------------------------------------------------
T E S T S
--------------------------------------------------------------
Running Default Unit
Tests run: 1, Failures: 0, Not executed: 0, Skipped: 0
To further illustrate, let's introduce a test that's destined to fail:
var bullTest = testSession.createSeriesTest("It's allways Bull Market")
bullTest.assertTrue(close > open, "Uhoh... it's not always bullish")
After executing, the test results will reflect this intentional discrepancy:
--------------------------------------------------------------
T E S T S
--------------------------------------------------------------
Running Default Unit
Tests run: 2, Failures: 1, Not executed: 0, Skipped: 0 <<< FAILURE! - in
It's allways Bull Market
Uhoh... it's not always bullish ==> expected: , but was
This shows how PineUnit efficiently captures and reports discrepancies in test expectations.
It's important to recognise the difference between `createSimpleTest()` and `createSeriesTest()`. In contrast to a simple test, a series-based test is executed on each bar, making assertions on series values.
License
This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
@ Guardian667
A Personal Note
As a software developer experienced in OO-based languages, diving into Pine Script is a unique journey. While many aspects of it are smooth and efficient, there are also notable gaps, particularly in the realm of testing. We've all been there: using `plotchar()` for debugging, trying to pinpoint those elusive issues in our scripts. I've come to appreciate the value of writing tests, which often obviates the need for such debugging. My hope is that this Testing Framework serves you well and saves you a significant amount of time, more that I invested into developing this "baby."
Test - Symbiotic Exiton Measure Enthropic Nexus indicatorThe Symbiotic Exiton Measure Enthropic Nexus (SEMEN) Indicator is a technical analysis tool used in trading and investing. It's name might sound complex, but its function is quite simple - to help traders make informed decisions about buying or selling stocks by predicting market trends.
The SEMEN indicator uses a combination of various factors such as volume, price action, moving averages, and other indicators to generate a single numerical value that represents the overall health of the market. A high reading indicates a strong uptrend, while a low one suggests a downtrend.
Traders can use this information to enter or exit positions with confidence.
In essence, the SEMEN indicator provides a comprehensive view of the market's sentiment and direction, making it an essential tool for any trader or investor looking to make profitable decisions in today's volatile stock markets.
~description generated with Airoboros7b
- The indicator is experimental so use at your own discretion..
Ema ScalpThis is another simple strategy based on ema
Entry Buy - 1) when close crossover ema then buy and only open one trade till it not close
2) if previous buy trade is profitable open another trade and check again trade is profitable or not
3)if trade is not profitable reset and wait for sell condition...
Entry Sell -1) when close crossunder ema then sell and only open one trade till it not close
2) if previous sell trade is profitable open another trade and check again trade is profitable or not
3) if trade is not profitable reset and wait for buy condition.....
stop loss and take profit is percentage based ...
MathSpecialFunctionsTestFunctionsLibrary "MathSpecialFunctionsTestFunctions"
Methods for test functions.
rosenbrock(input_x, input_y) Valley-shaped Rosenbrock function for 2 dimensions: (x,y) -> (1-x)^2 + 100*(y-x^2)^2.
Parameters:
input_x : float, common range within (-5.0, 10.0) or (-2.048, 2.048).
input_y : float, common range within (-5.0, 10.0) or (-2.048, 2.048).
Returns: float
rosenbrock_mdim(samples) Valley-shaped Rosenbrock function for 2 or more dimensions.
Parameters:
samples : float array, common range within (-5.0, 10.0) or (-2.048, 2.048).
Returns: float
himmelblau(input_x, input_y) Himmelblau, a multi-modal function: (x,y) -> (x^2+y-11)^2 + (x+y^2-7)^2
Parameters:
input_x : float, common range within (-6.0, 6.0 ).
input_y : float, common range within (-6.0, 6.0 ).
Returns: float
rastrigin(samples) Rastrigin, a highly multi-modal function with many local minima.
Parameters:
samples : float array, common range within (-5.12, 5.12 ).
Returns: float
drop_wave(input_x, input_y) Drop-Wave, a multi-modal and highly complex function with many local minima.
Parameters:
input_x : float, common range within (-5.12, 5.12 ).
input_y : float, common range within (-5.12, 5.12 ).
Returns: float
ackley(input_x) Ackley, a function with many local minima. It is nearly flat in outer regions but has a large hole at the center.
Parameters:
input_x : float array, common range within (-32.768, 32.768 ).
Returns: float
bohachevsky1(input_x, input_y) Bowl-shaped first Bohachevsky function.
Parameters:
input_x : float, common range within (-100.0, 100.0 ).
input_y : float, common range within (-100.0, 100.0 ).
Returns: float
matyas(input_x, input_y) Plate-shaped Matyas function.
Parameters:
input_x : float, common range within (-10.0, 10.0 ).
input_y : float, common range within (-10.0, 10.0 ).
Returns: float
six_hump_camel(input_x, input_y) Valley-shaped six-hump camel back function.
Parameters:
input_x : float, common range within (-3.0, 3.0 ).
input_y : float, common range within (-2.0, 2.0 ).
Returns: float
[UTILS] Unit Testing FrameworkTL;DR
This script doesn't provide any buy/sell signals.
This script won't make you profitable implicitly.
This script is intended for utility function testing, library testing, custom assertions.
It is free and open-source.
Introduction
About the idea: is not exclusive, programmers tend to use this method a lot and for a long time.
The point is to ensure that parts of a software, "units" (i.e modules, functions, procedures, class methods etc), work as they should, meet they design and behave as intended. That's why we use the term "Unit testing".
In PineScript we don't have a lot of entities mentioned above yet. What we have are functions. For example, a function that sums numbers should return a number, a particular sum. Or a professor wrote a function that calculates something or whatever. He and you want to be sure that the function works as expected and further code changes (refactoring) won't break its behaviour. What the professor needs to do is to write unit tests for his function/library of functions. And what you need to do is to check if the professor wrote tests or not.
No tests = No code
- Total test-driven development
Ok, it is not so serious, but very important in software development. And I created a tool for that.
I tried to follow the APIs of testing tools/libs/frameworks I worked or work with: Jasmine (Javascript), Mocha/Chai (Javascript), Jest (Javascript), RSpec (Ruby), unittest (Python), pytest (Python) and others. Got something workable but it would be much easier to implement (and it would look much better) if PineScript had a higher-order functions feature.
API
_describe(suiteName: string)
A function to declare a test suite. Each suite with tests may have 2 statuses:
✔️ Passed
❌ Failed
A suite is considered to be failed if at least one of the specs in it has failed.
_it(specName: string, actual: any, expected: any)
A function to run a test. Each test may have 3 statuses:
✔️ Passed
❌ Failed
⛔ Skipped
Some examples:
_it("is a falsey value", 1 != 2, true)
_it("is not a number", na(something), true)
_it("should sum two integers", _sum(1, 2), 1)
_it("arrays are equal", _isEqual(array.from(1, 2), array.from(1, 2)), true)
Remember that both the 'actual' and 'expected' arguments must be of the same type.
And a group of _it() functions must be preceded by a _describe() declaration (see in the code).
_test(specName: string, actual: any, expected: any)
An alias for _it . Does the same thing.
_xit(specName: string, actual: any, expected: any)
A function to skip a particular test for a while. Doesn't make any comparisons, but the test will appear in the results as skipped.
This feature is unstable and may be removed in the future releases.
_xtest(specName: string, actual: any, expected: any)
An alias for _xit . Does the same thing.
_isEqual(id_1: array, id_2: array)
A function to compare two arrays for equality. Both arrays must be of the same type.
This function doesn't take into account the order of elements in each array. So arrays like (1, 2, 3) and (3, 2, 1) will be equal.
_isStrictEqual(id_1: array, id_2: array)
A function to compare two arrays for equality. Both arrays must be of the same type.
This function is a stricter version of _isEqual because it takes into account the order of elements in each array. So arrays like (1, 2, 3) and (3, 2, 1) won't be equal.
Usage
To use this script to test your library you need to do the following steps:
1) Copy all the code you see between line #5 and #282 (Unit Testing Framework Core)
2) Place the copied code at the very beginning of your script (but below study())
3) Start to write suites and tests where your code ends. That's it.
NOTE
The current version is 0.0.1 which means that a lot of things may be changed on the way to 1.0.0 - the first stable version.
Cointegration Matrix (Indices)This indicator plots a cointegration matrix for pairings of most major stock indices. The matrix is populated with ADF t-stats (from an ADF-test with 1 lag). An ADF-test (Augmented Dickey-Fuller test) tests the null hypothesis that an AR process has a unit root. If rejected, the alternative hypothesis is usually that the AR process is either stationary or trend-stationary.
Technically what we're doing is running an ADF-test on the residuals (spread) of each pairing (i.e. a cointegration test). So we're testing if there is a unit root in the spread between the two assets of a pairing. A unit root being present in the spread essentially means the spread varies randomly over time, and any mean reversion in the spread is very hard to predict, or may never happen. If there is no evidence of a unit root, the spread (distance between the assets) should remain more or less constant over time, or rise/fall in close to the same rate over time (if it can be modelled as an AR process). The more negative the number, the stronger the rejection of the idea that the spread has a unit root. So in statistics we choose a critical value that corresponds to a confidence level of the test. In this case, -3.238 equals a confidence level of 90%, -3.589 equals a confidence level of 95% and -4.375 equals a confidence level of 99%. So the colors are based on the confidence level of the test statistic (the t-stat, i.e. the number of the pairing in the matrix). So if the number is greater than -3.238 it is green, if it's between -3.238 and -3.589 it's yellow, if it's between -3.589 and -4.375 it's orange, and if its lower than -4.375 it's red.
There are multiple ways to interpret the results. A strong rejection of the presence of a unit root (i.e. a value of -4.375 or below) is not a guarantee that there is no unit root, or that any of the two alternative hypotheses (that the spread is stationary or trend-stationary) are correct. It only means that in 99% of the cases, if the spread is an AR process, the test is right, and there is no unit root in the spread. Therefore, the results of this test is no guarantee that the result proves one of the alternative solutions. Green therefore means that a unit root cannot be ruled out (which can be interpreted as "the two indices probably don't move together over time"), and red means that a unit root is likely not present (which can be interpreted as "the two indices may move together over time").
NOTE: The indicator can take a while to load since it is loading data from 20 stock indices and calculating the ADF t-stat for 380 pairings.
Test - Gramian Angular FieldExperimental:
The Gramian Angular Field is usually used in machine learning for machine vision, it allows the encoding of data as a visual queue / matrix.
Cointegration Matrix (FX)This indicator plots a cointegration matrix for pairings of all 28 major forex pairs. The matrix is populated with ADF t-stats (from an ADF-test with 1 lag). An ADF-test (Augmented Dickey-Fuller test) tests the null hypothesis that an AR process has a unit root. If rejected, the alternative hypothesis is usually that the AR process is either stationary or trend-stationary.
Technically what we're doing is running an ADF-test on the residuals (spread) of each pairing (i.e. a cointegration test). So we're testing if there is a unit root in the spread between the two assets of a pairing. A unit root being present in the spread essentially means the spread varies randomly over time, and any mean reversion in the spread is very hard to predict, or may never happen. If there is no evidence of a unit root, the spread (distance between the assets) should remain more or less constant over time, or rise/fall in close to the same rate over time (if it can be modelled as an AR process). The more negative the number, the stronger the rejection of the idea that the spread has a unit root. So in statistics we choose a critical value that corresponds to a confidence level of the test. In this case, -3.238 equals a confidence level of 90%, -3.589 equals a confidence level of 95% and -4.375 equals a confidence level of 99%. So the colors are based on the confidence level of the test statistic (the t-stat, i.e. the number of the pairing in the matrix). So if the number is greater than -3.238 it is green, if it's between -3.238 and -3.589 it's yellow, if it's between -3.589 and -4.375 it's orange, and if its lower than -4.375 it's red.
There are multiple ways to interpret the results. A strong rejection of the presence of a unit root (i.e. a value of -4.375 or below) is not a guarantee that there is no unit root, or that any of the two alternative hypotheses (that the spread is stationary or trend-stationary) are correct. It only means that in 99% of the cases, if the spread is an AR process, the test is right, and there is no unit root in the spread. Therefore, the results of this test is no guarantee that the result proves one of the alternative solutions. Green therefore means that a unit root cannot be ruled out (which can be interpreted as "the two forex pairs probably don't move together over time"), and red means that a unit root is likely not present (which can be interpreted as "the two forex pairs may move together over time").
One possible way to use this indicator is to make sure you don't trade two pairs that move together at the same time. So basically the idea is that if you already have a trade open in one of the currency pairs of the pairing, only enter a trade in the other currency pair of that pairing if the color is green, or you may be doubling your risk.
NOTE: The indicator can take a while to load since it is loading data from 28 pairs and calculating the ADF t-stat for 756 pairings.
Multiple Regression Polynomial ForecastEXPERIMENTAL:
Forecasting using a polynomial regression over the estimates of multiple linear regression forecasts.
note: on low data the estimates are skewd away of initial value, i added the i_min_estimate option in to try curve this issue with limited success "o_o.
test - autocorrelation distributionexperimental:
shows the distribution for each shift in a autocorrelation.
test - delta distributiona test case for the KDE function on price delta.
the KDE function can be used to quickly check or confirm edge cases of the trading systems conditionals.
test - autocorrelationExperimental:
finds and displays the wavelength index's of the autocorrelation wavelengths..
Test: Pattern RecognitionEXPERIMENTAL:
a test on how to compare price at different frequency's with static patterns.
Test: Chain casting functions performanceExperimental:
A simple test to check performance impact of chaining functions in pinescript.
CC - PVT CloudsReleasing this test script for PVT ratios using sub-interval harmonics at a 1D, 4H, 1H, 45M, 15M and 5M level.
It basically takes the PVT values for a rolling periodic interval and gets the (avg - min)/max for that interval (the ratio).
Then it colors it based on the subinterval next to it. Just think of it as rolling Ichimoku clouds, but in real-time using PVT.
I'm not saying much more than that, as this is an experimental indicator. Feel free to use it and give me feedback.
Drop a like if this helps you trade, but please do not use these indicators as a DIVINING ROD for your trades.
However, I will possibly release a paid version with TEXTUAL take profit/stoploss indicators.
*DISCLAIMER*
No amount of technical indicators will safe you from a lapse in Due Diligence or Market/Industry Judgement.
I am not responsible for lost equity due to trades caused my relying on this indicator.
Silicone Re-calibrate ATRInspired by @bitmexstorm study Volatility-calibrated ATR
This study features two different ATR trail derivative concepts-Default one is called- "Silicone", and the alternative is called- "Mercurial. To decrease confusion during backtesting, trails plots with distinct color palette.
Options include the ability to apply a smoothening filter that affects both modes as well as an adaptive/fixed mode for the "Silicone" trail.
Parameters for trail dynamics/behavior is unlocked(!Parameters in publish version is far from optimized! Need serious testing! )
Candle Coloring reflects trail direction.
Feedback on optimal periods and multipliers is needed and appreciated