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."
Testing
ANTEYA ProfilingThis script allows to compare which code is more efficient by running it inside a loop for a certain time or a certain number of iterations.
Just paste your pieces of code as Option 1 and Option 2 inside the loop (see comments in the script).
Parabolic SAR Heikin Ashi MTF Candle ScalperThis is scalper strategy designed around parabolic sar indicator, where as an input candle value it uses the heikinashi from a higher timeframe.
This example has been adapted to SPY/SPX chart
In this case ,we are using a 5 min chart, but the calculations are made on a 15 min heikin ashi chart for the PSAR and then on 5 min chart we plot the results.
At the same time we are conditioning the entry to be base on a time/session for daytrading/scalper mentality
In this case we only enter within the first 30 min of SPY opening session , and then we exit after 3-4 hours of staying in the position ( unless we hit a reverse condition).
For long condition we enter when the mtf ha candle close is above the mtf psar and for short condition we enter when the mtf ha candle close is below the mtf psar
This script is made with an educational purpose to show the power of multiple time frame approach compared to a single chart.
If you have any questions, let me know !
matrixautotableLibrary "matrixautotable"
Automatic Table from Matrixes with pseudo correction for na values and default color override for missing values. uses overloads in cases of cheap float only, with additional addon for strings next, then cell colors, then text colors, and tooltips last.. basic size and location are auto, include the template to speed this up...
TODO : make bools version
var string group_table = ' Table'
var int _tblssizedemo = input.int ( 10 )
string tableYpos = input.string ( 'middle' , '↕' , inline = 'place' , group = group_table, options= )
string tableXpos = input.string ( 'center' , '↔' , inline = 'place' , group = group_table, options= , tooltip='Position on the chart.')
int _textSize = input.int ( 1 , 'Table Text Size' , inline = 'place' , group = group_table)
var matrix _floatmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 0 )
var matrix _stringmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 'test' )
var matrix _bgcolormatrix = matrix.new (_tblssizedemo, _tblssizedemo, color.white )
var matrix _textcolormatrix = matrix.new (_tblssizedemo, _tblssizedemo, color.black )
var matrix _tooltipmatrix = matrix.new (_tblssizedemo, _tblssizedemo, 'tool' )
// basic table ready to go with the aboec matrixes (replace in your code)
// for demo purpose, random colors, random nums, random na vals
if barstate.islast
varip _xsize = matrix.rows (_floatmatrix) -1
varip _ysize = matrix.columns (_floatmatrix) -1
for _xis = 0 to _xsize -1 by 1
for _yis = 0 to _ysize -1 by 1
_randomr = int(math.random(50,250))
_randomg = int(math.random(50,250))
_randomb = int(math.random(50,250))
_randomt = int(math.random(10,90 ))
bgcolor = color.rgb(250 - _randomr, 250 - _randomg, 250 - _randomb, 100 - _randomt )
txtcolor = color.rgb(_randomr, _randomg, _randomb, _randomt )
matrix.set(_bgcolormatrix ,_yis,_xis, bgcolor )
matrix.set(_textcolormatrix ,_yis,_xis, txtcolor)
matrix.set(_floatmatrix ,_yis,_xis, _randomr)
// random na
_ymiss = math.floor(math.random(0, _yis))
_xmiss = math.floor(math.random(0, _xis))
matrix.set( _floatmatrix ,_ymiss, _xis, na)
matrix.set( _stringmatrix ,_ymiss, _xis, na)
matrix.set( _bgcolormatrix ,_ymiss, _xis, na)
matrix.set( _textcolormatrix ,_ymiss, _xis, na)
matrix.set( _tooltipmatrix ,_ymiss, _xis, na)
// import here
import kaigouthro/matrixautotable/1 as mtxtbl
// and render table..
mtxtbl.matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos)
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_textcolormatrix : color
_tooltipmatrix : string
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_textcolormatrix : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _txtdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_bgcolormatrix : color
_txtdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _stringmatrix, _txtdefcol, _bgdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_stringmatrix : string
_txtdefcol : color
_bgdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
matrixtable(_floatmatrix, _txtdefcol, _bgdefcol, _textSize, tableYpos, tableXpos) matrixtable
Parameters:
_floatmatrix : float vals
_txtdefcol : color
_bgdefcol : color
_textSize : int
tableYpos : string
tableXpos : string
debuggerDEBUGGER is a library to help print debug messages to a console.
This library provides an easy-to-use interface to print your debugging messages to a console in the chart. Special attention has been given to printing series and arrays easily.
A debugger is a valuable tool when working on scripts and getting into trouble. Unfortunately, TradingView does not provide an interactive debugger, and does not provide a console to use the oldest trick in the debugging book: print statements. This library provides you with the latter tool, print statements.
As a bonus, the library also provides a way to show labels in the chart next to the pricing action.
For more information and examples of usage, check the description in the header comments.
[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.
Cosmic BB SRThis script is based on Bollinger Bands/Bandwidth data and displays support and resistance levels (thick horizontal lines), the direction/volatility of the levels (thin dynamic lines), and the testing of the levels (cross markers).
Supertrend V1.0 - Buy or Sell SignalTesting a concept to get a TP and SL based on the ATR at the time of the position entry.
Manual Back Test LinesI created this indicator to primarily manually test other indicators in replay mode.
To use this indicator generally you will:
Select trade type: long or short
Enter your ATR (enter the actual ATR). The indicator will then calculate and plot your SL and targets based on your values
Default Stop Loss is ATR * 1.5
Default Target 1 is ATR * 1.5
Default Target 2 is ATR * 3
Using this indicator on Replay mode is great. What you do is go back in time. Hit play and as the indicator(s) you use provide signals pause.
Pull up options:
Select trade type
Update ATR value
Change date to entry date. Typically if you are trading off the daily timeframe you are going to wait for your current day candle to close to provide signal. That would mean your entry would be on the next day.
Click play and watch, track and record how trade unfolds.
Future updates:
I'd like to be able to have some way to click one button and have it fire that enter trade right now on chart. Also I'm working on figuring out how to calculate the ATR on the entry date so that isn't required to be entered.
Finally, I'd like to have some auto calculation on when targets and SL are hit. I have this partially done but it's more important that I use this indicator than spend time or funds to update it to do that. But I do plan on updating.
ACM22 not repaintedДелал данный скрипт для FORTS.Идеально подойдет тем,кто использует трейлинг стопы.В основе стратегии лежит RSI.Как по мне,хорошая вещь для проверки стратегии и ее оптимизиации.На скрине 50 контрактов,так что не сильно радуйтесь,а просто делите на 50 и получите показатели на 1 контракт.
Script make for futures on MICEX.U can change paramets of RSI,traling stop and stop loss .On a ps 50 futures USDollar-russian ruble.Use for testing and optimisation.
C320up Strategy Tester Start TimeC320up Strategy Tester Start Time
This is a little snippet you can paste into your Strategy to set the testing start date and time.
It is not a Strategy per se, though is an example with the timestamp script included.
Instructions are fairly straight forward, and are listed in the script.
If for some reason you also wanted an end date, that too is possible. Just leave a note in the comments.
Disclaimer: We searched for a similar script on TV, and could not find anything at this point in time.
You can set your preferred date and time in the input section of the settings.
Enjoy!
Binary Options Strategy Testing ScriptThis is a script for testing binary options trading strategies. To test a strategy, modify the 'go_down' or 'go_up' booleans. These SHOULD NOT access any current values (for example, 'ohlc4' or 'close '), or the backtesting will not be an accurate representation of the forward values.
Modify the fraction_return input to be the return rate of the option on success. This is assumed to be a true 100 or 0 option- i.e. if the choice is not correct, there is a 100% loss.
The strategy in place is merely an example, and as you can see, has a very negative rate of return when implemented as a strategy.
Please comment in your code if you use this in any future posts. Thanks!