TUF_LOGICThe TUF_LOGIC library incorporates three-valued logic (also known as trilean logic) into Pine Script, enabling the representation of states beyond the binary True and False to include an 'Uncertain' state. This addition is particularly apt for financial market contexts where information may not always be black or white, accommodating scenarios of partial or ambiguous data.
Key Features:
Trilean Data Type: Defines a tri type, facilitating the representation of True (1), Uncertain (0), and False (-1) states, thus accommodating a more nuanced approach to logical evaluation.
Validation and Conversion: Includes methods like validate, to ensure trilean variables conform to expected states, and to_bool, for converting trilean to boolean values, enhancing interoperability with binary logic systems.
Core Logical Operations: Extends traditional logical operators (AND, OR, NOT, XOR, EQUALITY) to work within the trilean domain, enabling complex conditionals that reflect real-world uncertainties.
Specialized Logical Operations:
Implication Operators: Features IMP_K (Kleene's), IMP_L (Łukasiewicz's), and IMP_RM3, offering varied approaches to logical implication within the trilean framework.
Possibility, Necessity, and Contingency Operators: Implements MA ("it is possible that..."), LA ("it is necessary that..."), and IA ("it is unknown/contingent that..."), derived from Tarski-Łukasiewicz's modal logic attempts, enriching the library with modal logic capabilities.
Unanimity Functions: The UNANIMOUS operator assesses complete agreement among trilean values, useful for scenarios requiring consensus or uniformity across multiple indicators or conditions.
This library is developed to support scenarios in financial trading and analysis where decisions might hinge on more than binary outcomes. By incorporating modal logic aspects and providing a framework for handling uncertainty through the MA, LA, and IA operations, TUF_LOGIC bridges the gap between classical binary logic and the realities of uncertain information, making it a valuable tool for developing sophisticated trading strategies and analytical models.
Library "TUF_LOGIC"
3VL Implementation (TUF stands for True, Uncertain, False.)
method validate(self)
Ensures a valid trilean variable. This works by clamping the variable to the range associated with the trilean type.
Namespace types: tri
Parameters:
self (tri)
Returns: Validated trilean object.
method to_bool(self)
Converts a trilean object into a boolean object. True -> True, Uncertain -> na, False -> False.
Namespace types: tri
Parameters:
self (tri)
Returns: A boolean variable.
method NOT(self)
Negates the trilean object. True -> False, Uncertain -> Uncertain, False -> True
Namespace types: tri
Parameters:
self (tri)
Returns: Negated trilean object.
method AND(self, comparator)
Logical AND operation for trilean objects.
Namespace types: tri
Parameters:
self (tri) : The first trilean object.
comparator (tri) : The second trilean object to compare with.
Returns: `tri` Result of the AND operation as a trilean object.
method OR(self, comparator)
Logical OR operation for trilean objects.
Namespace types: tri
Parameters:
self (tri) : The first trilean object.
comparator (tri) : The second trilean object to compare with.
Returns: `tri` Result of the OR operation as a trilean object.
method EQUALITY(self, comparator)
Logical EQUALITY operation for trilean objects.
Namespace types: tri
Parameters:
self (tri) : The first trilean object.
comparator (tri) : The second trilean object to compare with.
Returns: `tri` Result of the EQUALITY operation as a trilean object, True if both are equal, False otherwise.
method XOR(self, comparator)
Logical XOR (Exclusive OR) operation for trilean objects.
Namespace types: tri
Parameters:
self (tri) : The first trilean object.
comparator (tri) : The second trilean object to compare with.
Returns: `tri` Result of the XOR operation as a trilean object.
method IMP_K(self, comparator)
Material implication using Kleene's logic for trilean objects.
Namespace types: tri
Parameters:
self (tri) : The antecedent trilean object.
comparator (tri) : The consequent trilean object.
Returns: `tri` Result of the implication operation as a trilean object.
method IMP_L(self, comparator)
Logical implication using Łukasiewicz's logic for trilean objects.
Namespace types: tri
Parameters:
self (tri) : The antecedent trilean object.
comparator (tri) : The consequent trilean object.
Returns: `tri` Result of the implication operation as a trilean object.
method IMP_RM3(self, comparator)
Logical implication using RM3 logic for trilean objects.
Namespace types: tri
Parameters:
self (tri) : The antecedent trilean object.
comparator (tri) : The consequent trilean object.
Returns: `tri` Result of the RM3 implication as a trilean object.
method MA(self)
Evaluates to True if the trilean object is either True or Uncertain, False otherwise.
Namespace types: tri
Parameters:
self (tri) : The trilean object to evaluate.
Returns: `tri` Result of the operation as a trilean object.
method LA(self)
Evaluates to True if the trilean object is True, False otherwise.
Namespace types: tri
Parameters:
self (tri) : The trilean object to evaluate.
Returns: `tri` Result of the operation as a trilean object.
method IA(self)
Evaluates to True if the trilean object is Uncertain, False otherwise.
Namespace types: tri
Parameters:
self (tri) : The trilean object to evaluate.
Returns: `tri` Result of the operation as a trilean object.
UNANIMOUS(self, comparator)
Evaluates the unanimity between two trilean values.
Parameters:
self (tri) : The first trilean value.
comparator (tri) : The second trilean value.
Returns: `tri` Returns True if both values are True, False if both are False, and Uncertain otherwise.
method UNANIMOUS(self)
Evaluates the unanimity among an array of trilean values.
Namespace types: array
Parameters:
self (array) : The array of trilean values.
Returns: `tri` Returns True if all values are True, False if all are False, and Uncertain otherwise.
tri
Three Value Logic (T.U.F.), or trilean. Can be True (1), Uncertain (0), or False (-1).
Fields:
v (series int) : Value of the trilean variable. Can be True (1), Uncertain (0), or False (-1).
Udt
Simple Ultimate Oscillator█ OVERVIEW
This indicator as an educational and showcase the usage of user-defined types (UDT) or objects for Ultimate Oscillator.
█ CREDITS
TradingView
█ FEATURES
1. Color of plot is based on contrast color of chart background.
2. Plot fill of overbought and oversold.
3. Support Multi Timeframe.
Simple Ichimoku Kinko Hyo Cloud█ OVERVIEW
This indicator as an educational and showcase the usage of user-defined types or objects (UDT) for Ichimoku Kinko Hyo or Ichimoku Cloud.
█ CREDITS
TradingView
RGB Color Codes Chart█ OVERVIEW
This indicator is an educational indicator to make pine coders easier to input color code.
Color code displayed either in hex or rgb code or both.
█ INSPIRATIONS
RGB Color Codes Chart
Table Color For Pairing Black And White
█ FEATURES
Hover table cell to see all properties of color such as Hex code and RGB code via tooltip.
Cell can be show either Full, HEX, RGB, R, G, B or na.
█ LIMITATION
This code does not consider usage of color.new()
█ CONSIDERATION
Code consideration to be used such as color.r(), color.g(), color.b() and color.rgb()
█ EXAMPLE OF USAGE / EXPLAINATION
Simple Zigzag UDT█ OVERVIEW
This indicator displays zigzag based on high and low, which is using user-defined types (UDT) or objects .
█ CREDITS
LonesomeTheBlue
█ FEATURES
1. Label can be resized.
2. Label can be display either short (Eg : HH, LL, H, L, etc) and long (Eg : Higher Low, etc)
3. Color can be customized either contrast color of chart background, trend color or customized color.
█ EXAMPLES / USAGES
Motion▮ FEATURES
Now as library version :)
String-based transition-effects
Performance optimization. Reduced memory consumption up to >90% by kicking the output to the "stdout".
Use marquee- or loader-effect on any possible string location.
Example: UI Price-Ticker
----------------------------------------------------------------------------
Library "Motion"
_getStringMono(_len, _str, _sep)
Parameters:
_len
_str
_sep
marquee(this, _extern, _ws, _subLen, _subStart)
Parameters:
this
_extern
_ws
_subLen
_subStart
transition(this, _subLen, _subStart)
Parameters:
this
_subLen
_subStart
hold(this)
Parameters:
this
keyframe
keyframe A keyframe object.
Fields:
seq
intv
step
length
update_no
frame_no
ltr
hold
Sort array alphabetically - educational🔶 OVERVIEW
• This educational script will sort an array of tickers alphabetically and place these values in an table , together with the according current price value next to each ticker .
🔶 SORT ALPHABETICALLY
🔹 I. We make a User Defined Type (UDT) obj , with:
· ticker - the string name of the ticker
· price - the current price (close)
• From this UDT we make an object obj.new() for each ticker
🔹 II. 2 array's are made:
• array of objects aObj , containing obj type obj.new() for every ticker
• array of strings sort , the ticker part of each object obj.new()
🔹 III. Now we make an object of each ticker with the createObject(sym ) function
object_1 = createObject("TICKER")
• the object object_1 consists off:
· ticker -> "TICKER"
· price -> current Daily close through request.security("TICKER") (non-repainting)
• object_1 will be added to the aObj array
• "TICKER" ( string ticker part of object ) will be added to the sort array
🔹 IV. The latter array is sorted alphabetically by using array.sort_indices()
EXAMPLE
originalArray = array.from("B", "A", "C")
indicesArray = // sorted indices
array.get(originalArray, 1) -> "A"
array.get(originalArray, 0) -> "B"
array.get(originalArray, 2) -> "C"
IMPORTANT
Alphabetically sorting is case sensitive , just like Java compareTo(String anotherString) !
• The comparison is based on the Unicode value of each character in the string, the lowest "Dec" values are sorted first in line.
• Comparing the "Dec" values at unicodelookup explains why default CAPITAL lettres will be sorted first,
• Default you would get this (A= 65, B= 66, a= 97, b= 98)
Aa
Ba
ab
bb
• Adding str.lower(string) in the toLowerCase() function will result to the following:
Aa
ab
Ba
bb
• (A= 65 is transformed to a= 97, ...)
• As a side note, should you write "AMZN" as "ÀMZN" this would be placed at the end, even after transforming to lower case the "Dec" values are higher (À= 192, à= 224).
• You can toggle "To Lower Case" to verify.
🔹 V. Values are placed in a table , using these sorted indices.
• With the usage of UDTs and objects , the current price has the same index in the aObj as their ticker ,
giving the advantage it is fairly easy to place every value correctly next to each other.
• The same can be done by make 2 separate arrays , 1 for the current price , the other for "TICKER" .
🔶 OTHER TECHNIQUES USED
• Alternative technique for adding comment
Instead of
// this is a comment
You can also do this:
_=" this is a comment "
• Alternate colour
· During a loop , alternate colour when i is even or odd , using the modulo operation (%) .
· This is the remainder when dividing.
EXAMPLE
· 3 % 2 = 1 -> 3 / 2 -> 1 * 2, 1 left (remainder)
· 4 % 2 = 0 -> 4 / 2 -> 2 * 2, 0 left (remainder)
· 5 % 2 = 1 -> 5 / 2 -> 2 * 2, 1 left (remainder)
for i = 0 to 10
even = i % 2 == 0
col = even ? thisColor : otherColor
• Adjust colour in script by using colour picker
Cheers!
Multiple Divergences (UDTs - objects) - Educational█ OVERVIEW
This script highlights the usage of User-defined Types (UDTs) and objects , and bullish /bearish divergences.
Pivotpoints are used to find divergences, the result of this script will be different against other public multiple divergences scripts.
FOR Pine Script™ CODERS
Besides the information found in CONCEPTS , the comments in the script will, hopefully ), guide you through my thought process.
█ CONCEPTS
The main principle of this script are bullish /bearish divergences, this with 3 different oscillators ( RSI , CCI , MFI )
If you want to know more about divergences, have a look at some Education and Research idea's .
On every bar, an object HLs is made, containing bar_index , high , low , and 2 bool variables ( isPh , isPl ).
On every bar, an object Osc is made, containing bar_index , o (oscillator value), and 2 bool variables ( isPh , isPl ).
If a pivothigh (ph ) is found, isPh will be true on that bar, false otherwise.
If a pivotlow (pl) is found, isPl will be true on that bar, false otherwise.
These objects are added to an array, with limited size.
If a ph is found, the script draws a testline from that ph to every previous ph , found in the array.
Then every high in between these 2 points are checked if they don't pierce the testline .
If the testline isn't broken, the Reg_Div_Piv() function will give 4 values, 1 check (not pierced) variable and the 4 points of the line.
The testline is deleted.
Once a positive check is found, the script will perform the same, but now with the Osc objects.
The script will ONLY compare Osc pivots which are maximum 1 bar away from the high/low pivot .
If everything is confirmed, a line is drawn, visible on the chart.
█ REMARKS
A label will be visible with a number, this is the amount of divergences found with the according oscillator .
EXAMPLE
Div with RSI and CCI -> 2
Div with MFI alone -> 1
Div with RSI and CCI and MFI -> 3
...
Divergences should only be used when confirmed, this is after bar close .
As an aid, lines that are not confirmed will be dotted , if confirmed, they will be solid .
The divergence check start when a ph/pl is found, after which oscillator pivot are checked.
Optionally the same can be done, when a oscillator pivot is found and then check the ph/pl ,
this should give more results, although it can make the script slower.
█ SETTINGS
Left - amount of bars at the left which needs to be lower/higher
Right - amount of bars at the right which needs to be lower/higher
Max values - maximum values in array of objects
3 oscillator settings with
• ON/OFF
• Length
• color bullish divergence
• color bearish divergence
Have FUN !
WelcomeUDT█ OVERVIEW
This is a simplest example of user-defined types (UDT) or objects , which simplify as alternative to hello world.
█ CREDITS
Tradingview
█ USAGE
These are the types used during initializations, commonly variables.
export type Settings
int bar
float price
string phrase
...
Example of library function to print out label.
export printLabel(Settings setup) =>
if setup.variable
var label lab = na
label.delete(lab)
lab := label.new(setup.bar, setup.price, setup.phrase, color = setup.bg)
else
label.new(setup.bar, setup.price, setup.phrase, color = setup.bg)
Usage of types
Settings setup = Settings.new(bar_index , priceInput, phraseInput, colorInput, variableInput)
Alternative way to write types
Settings setup = Settings.new(
bar = bar_index ,
price = priceInput,
phrase = phraseInput,
variable = variableInput)
Usage of types into custom function / library function.
printLabel(setup)
printLabel(Settings)
Print out label
Parameters:
Settings : types
Returns: Label object
Settings
Initialize type values
Fields:
bar : X position for label
price : Y position for label
phrase : Text for label
bg : Color for label
variable : Boolean for enable new line and delete line