Milvetti_Pineconnector_LibraryLibrary "Milvetti_Pineconnector_Library"
This library has methods that provide practical signal transmission for Pineconnector.Developed By Milvetti
buy(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
sell(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
buyLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy limit order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
buyStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a buy stop order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
sellLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a sell limit order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
sellStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
Create a sell stop order message
Parameters:
licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
symbol (string) : Symbol. Default is syminfo.ticker
pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
risk (float) : Risk. Function depends on the “Volume Type” selected in the EA
sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
atrPeriod (int) : ATR averaging period. Default is 0
atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
secret (string)
comment (string) : Comment. Add a string into the order’s comment section. Default is "Symbol+Timeframe"
Display
PineTraderOT_V5Are you tired of the complexities of creating properly formatted order tickets in TradingView? We’ve got you covered! The PineTrader Order Ticket Generator library is here to simplify the process and help you automate your trading strategies with ease.
Why This Library?
Currently, TradingView doesn’t support JSON formatting natively. This means creating order tickets for automation often involves tedious string manipulations to build a message that services like PineTrader can understand. Our library takes care of all that for you by providing an easy-to-use method to generate correctly formatted JSON order tickets.
What Does It Do?
This library is your shortcut to creating automated trades using TradingView and PineTrader. It lets you build buy, sell, and pending orders with all the parameters you need, such as:
Take Profit (TP)
Stop Loss (SL)
Trailing Stops
And more!
Once your order ticket is ready, you can send it to the PineTrader webhook URL:
👉 webhook.pinetrader.io
The webhook communicates with your broker (like MT5) to execute trades based on the order ticket.
How to Use It?
Import the Library
Add this library to your Pine Script™ project.
Use CreateOrderTicket Method
Call the CreateOrderTicket function in your script and define the parameters for your trade, such as size, price, order type, and more.
Set Up Alerts
Create an alert in TradingView.
Use the webhook URL (webhook.pinetrader.io) for the alert notification.
Set the alert message to {{strategy.order.message}} (make sure to include alert_message in your strategy.entry or strategy.exit methods).
Enjoy Automation
Once the alert is triggered, the order ticket is sent to PineTrader, and your trades are executed automatically.
Example Workflow
Here’s how simple it is:
Define your trading parameters using CreateOrderTicket.
Add an alert linked to the PineTrader webhook.
Watch as your TradingView strategy seamlessly interacts with your broker!
Why Choose PineTrader Order Ticket Generator?
This library:
Saves time by automating the formatting of order tickets.
Reduces errors in creating JSON strings manually.
Simplifies integration between TradingView and brokers like MT5.
Automate your strategies today with the PineTrader Order Ticket Generator—the bridge between TradingView and effortless trading automation!
BacktestLibraryLibrary "BacktestLibrary"
A library providing functions for equity calculation and performance metrics.
since(date, active)
: Calculates the number of candles since a specified date.
Parameters:
date (simple float) : (simple float): The starting date in timestamp format (e.g., input.time(timestamp()))
active (simple bool) : (simple bool): If true, counts the number of candles since the date; if false, returns 0.
Returns: (int): The number of candles since the specified date.
buy_and_hold(r, startDate)
: Calculates the Buy and Hold Equity from a specified date.
Parameters:
r (float) : (series float): Daily returns of the asset (e.g., 0.02 for 2% move).
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
Returns: (float): Buy and Hold Equity of the asset from the specified date.
equity(sig, threshold, r, startDate, signals)
: Calculates the strategy's equity on a candle-by-candle basis.
Parameters:
sig (float) : (series float): Signal values; positive for long, negative for short.
threshold (simple float) : (simple float): Signal threshold for entering trades.
r (float) : (series float): Daily returns of the asset (e.g., 0.02 for 2% move).
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
signals (simple string) : (simple string): Type of signals to backtest ("Long & Short", "Long Only", "Short Only").
Returns: (float): Strategy equity on a candle-by-candle basis.
PerformanceMetrics(base, Lookback, startDate)
: Calculates performance metrics of a strategy from a specified date.
Parameters:
base (float) : (series float): Equity values of the strategy or Buy and Hold equity.
Lookback (int) : (series int): Number of periods since the start date; recommended to use the 'since' function.
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
Returns: (float ): Array of performance metrics.
PerfMetricTable(buy_and_hold, strategy)
: Plots a table comparing performance metrics of Buy and Hold and Strategy equity.
Parameters:
buy_and_hold (array) : (float ): Metrics from the PerformanceMetrics() function for Buy and Hold.
strategy (array) : (float ): Metrics from the PerformanceMetrics() function for the strategy.
Returns: : Table displaying the performance metrics comparison.
hinton_map█ HINTON MAP
This library provides functions to create and display a Hinton Map visualization. A Hinton map uses squares to represent the magnitude and direction of values in a matrix. This library allows you to display multiple ticker/timeframe/indicator combinations on a single chart, using color/boxsize/bnordersize to represent the values used. The values must be from -1.0 to 1.0 in value. 3 different values can be input per square.
Example Usage:
The example below demonstrates how to create a Hinton Map for two symbols (AAPL and MSFT) across three timeframes (1 minute, 5 minutes, and 1 day).
var hintonData = hinton_map.initHintonData(2, 3)
tickers = array.from("AAPL", "MSFT")
timeframes = array.from("1", "5", "1D")
for i = 0 to array.size(tickers) - 1
for j = 0 to array.size(timeframes) - 1
ticker = array.get(tickers, i)
timeframe = array.get(timeframes, j)
= request.security(ticker, timeframe, [close, close , ta.rsi(close, 14)], lookahead = barmerge.lookahead_on)
percent_change = (close_current - close_previous) / close_previous * 100
rsi_deviation = rsi_current - 50
hintonData.unitMatrix.set(i, j, hinton_map.createHintonUnit(
fillValue = percent_change,
borderValue = rsi_deviation,
innerValue = percent_change * rsi_deviation,
boxText = dv.from_string(str.tostring(math.round(percent_change, 2)) + "%"),
tooltipText = dv.from_string(syminfo.ticker + ", " + timeframe + ": " + str.tostring(math.round(percent_change, 2)) + "%, RSI: " + str.tostring(math.round(rsi_current, 2)))
))
hinton_map.drawHintonMap(hintonData)
█ createHintonUnit
Creates a Hinton unit.
• fillValue
Value to determine the fill color hue.
Type: float
Default Value: 0.0
• borderValue
Value to determine the border color hue and width.
Type: float
Default Value: 0.0
• innerValue
Value to determine the inner box color hue.
Type: float
Default Value: 0.0
• boxText
Text to display in the inner box.
Type: dv.DisplayValue
Default Value: na
• tooltipText
Tooltip text for the inner box.
Type: dv.DisplayValue
Default Value: na
Returns: HintonUnit
█ initHintonData
Initializes Hinton map data structure.
• rows
Number of rows.
Type: int
• columns
Number of columns.
Type: int
Returns: HintonData
█ drawHintonMap
Draws a Hinton map.
• hintonData
Hinton map data.
Type: HintonData
• unitSize
Size of each unit in bars.
Type: int
Default Value: 10
• borderWidth
Base width of the inner box border.
Type: int
Default Value: 5
• plusHue
Hue value for positive values (0-360).
Type: float
Default Value: 180
• minusHue
Hue value for negative values (0-360).
Type: float
Default Value: -30
█ HintonUnit
Data for a Hinton unit.
• fillValue
Value to determine the fill color hue.
Type: float
• borderValue
Value to determine the border color hue and width.
Type: float
• innerValue
Value to determine the inner box color hue.
Type: float
• boxText
Text to display in the inner box.
Type: dv.DisplayValue
• tooltipText
Tooltip text for the inner box.
Type: dv.DisplayValue
█ HintonData
Structure to store Hinton map data.
• unitMatrix
Matrix of Hinton units.
Type: matrix
• lineMatrix
Matrix of lines.
Type: matrix
• labelMatrix
Matrix of labels.
Type: matrix
• boxMatrix
Matrix of boxes.
Type: matrix
• fillMatrix
Matrix of line fills.
Type: matrix
MarketStructureLibrary "MarketStructure"
Will draw out the market structure for the disired pivot length. The code is from my indicator "Marker structure" ().
Create(type, length, source, equalPivotsFactor, extendEqualPivotsZones, equalPivotsStyle, equalPivotsColor, alertFrequency)
Call on each bar. Will create a Structure object.
Parameters:
type (int) : the type of the Structure to create. 0 = internal, 1 = swing.
length (int) : The lenghts (left and right) for pivots to use.
source (string) : The source to be used for structural changes ('Close', 'High/low (aggresive)' (low in an uptrend) or 'High/low (passive)' (high in an uptrend)).
equalPivotsFactor (float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
extendEqualPivotsZones (bool) : Set to true if you want the equal pivots zones to be extended.
equalPivotsStyle (string) : Set the style of equal pivot zones.
equalPivotsColor (color) : Set the color of equal pivot zones.
alertFrequency (string)
Returns: The 'structure' object.
Pivot(structure)
Sets the pivots in the structure.
Parameters:
structure (Structure)
Returns: The 'structure' object.
PivotLabels(structure)
Draws labels for the pivots found.
Parameters:
structure (Structure)
Returns: The 'structure' object.
EqualHighOrLow(structure)
Draws the boxsa for equal highs/lows. Also creates labels for the pivots included.
Parameters:
structure (Structure)
Returns: The 'structure' object.
BreakOfStructure(structure)
Will create lines when a break of strycture occures.
Parameters:
structure (Structure)
Returns: The 'structure' object.
ChangeOfCharacter(structure)
Will create lines when a change of character occures.
Parameters:
structure (Structure)
Returns: The 'structure' object.
StructureBreak
Holds drawings for a structure break.
Fields:
Line (series line) : The line object.
Label (series label) : The label object.
Pivot
Holds all the values for a found pivot.
Fields:
Price (series float) : The price of the pivot.
BarIndex (series int) : The bar_index where the pivot occured.
Type (series int) : The type of the pivot (-1 = low, 1 = high).
ChangeOfCharacterBroken (series bool) : Sets to true if a change of character has happened.
BreakOfStructureBroken (series bool) : Sets to true if a break of structure has happened.
Structure
Holds all the values for the market structure.
Fields:
Length (series int) : Define the left and right lengths of the pivots used.
Type (series int) : Set the type of the market structure. Two types can be used, 'internal' and 'swing' (0 = internal, 1 = swing).
Trend (series int) : This will be set internally and can be -1 = downtrend, 1 = uptrend.
Source (series string) : Set the source for structural chandeg. Can be 'Close', 'High/low (aggresive)' (low in an uptrend) or 'High/low (passive)' (high in an uptrend).
EqualPivotsFactor (series float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
ExtendEqualPivotsZones (series bool) : Set to true if you want the equal pivots zones to be extended.
ExtendEqualPivotsStyle (series string) : Set the style of equal pivot zones.
ExtendEqualPivotsColor (series color) : Set the color of equal pivot zones.
EqualHighs (array) : Holds the boxes for zones that contains equal highs.
EqualLows (array) : Holds the boxes for zones that contains equal lows.
BreakOfStructures (array) : Holds all the break of structures within the trend (before a change of character).
Pivots (array) : All the pivots in the current trend, added with the latest first, this is cleared when the trend changes.
AlertFrequency (series string) : set the frequency for alerts.
OrderBlocksLibrary "OrderBlocks"
This is a library I created that creates order blocks. It's originated from my indicator "Order blocks" (). It will return a Zone object that can be used to draw an order block. If you want to see how that is done you can check out my indicar that uses the same logic.
Create(settings)
Creates an order block if one is found according to the settings parameter.
Parameters:
settings (Settings) : set all values in this parameter to define the settings for the order block creation.
Returns: a Zone object if an order block is found, na otherwise
Zone
Fields:
Time (series int)
TimeClose (series int)
High (series float)
Low (series float)
ReactionLimit (series float)
TouchedZone (Zone type from mickes/Touched/14)
Type (series int)
Zones
Fields:
Index (series int)
Maximum (series int)
Zones (array)
Remove (Zone)
Settings
Fields:
TakeOut (series bool)
ReactionFactor (series float)
Type (series string)
ConsecutiveRisingOrFalling (series bool)
FairValueGap (series bool)
MonthlyReturnsTableLibrary "MonthlyReturnsTable"
showMonthlyReturns(show)
显示月度和年度收益率表格
Parameters:
show (bool) : (bool) 是否显示表格
Returns: 返回一个数组,包含是否显示表格的状态和当前月度收益率
DRKMetricsLibrary "DRKMetrics"
TODO: add library description here
curve(disp_ind)
Call function to get a certain curve of your strategy.
Parameters:
disp_ind (string)
Returns: Returns type of curve plot.
cleaner(disp_ind, plot)
Call function to filter out your Strategy plots
Parameters:
disp_ind (string)
plot (float)
cobraTable(option, position)
Assign this function to a random variable to get the "Performance Table"
Parameters:
option (simple string)
position (simple string)
UtilityLibrary "Utility"
A utility library for various trading tools such as signal generation, custom indicators, and multi-condition crossovers.
multiCrossover(source1, source2, threshold1, threshold2)
multiCrossover
@description Detects multi-condition crossovers between two sources with threshold filters.
Parameters:
source1 (float) : The first data series to compare.
source2 (float) : The second data series to compare.
threshold1 (float) : A value that source1 must exceed to trigger the crossover.
threshold2 (float) : A value that source2 must exceed to trigger the crossunder.
Returns: A tuple: (crossUp, crossDown) where crossUp is a boolean for upward crossover, and crossDown is for downward crossover.
macdCustom(source, fastLength, slowLength, signalLength, macdThresh)
macdCustom
@description Calculates custom MACD signals based on thresholds.
Parameters:
source (float) : The price data or input series.
fastLength (simple int) : The length of the fast EMA.
slowLength (simple int) : The length of the slow EMA.
signalLength (simple int) : The signal line length.
macdThresh (float) : A threshold for the MACD line to confirm buy/sell signals.
Returns: A tuple: (macdBuySignal, macdSellSignal) where macdBuySignal is true when MACD crosses above, and macdSellSignal is true when MACD crosses below the signal line.
combinedMacdRsi(source, fastLength, slowLength, signalLength, rsiLength, macdThresh, rsiThresh)
combinedMacdRsi
@description Generates combined signals from MACD and RSI indicators.
Parameters:
source (float) : The price data or input series.
fastLength (simple int) : The length of the fast EMA for MACD.
slowLength (simple int) : The length of the slow EMA for MACD.
signalLength (simple int) : The signal line length for MACD.
rsiLength (simple int) : The length of the RSI calculation.
macdThresh (float) : The threshold for MACD signals.
rsiThresh (float) : The threshold for RSI signals.
Returns: A tuple: (buySignal, sellSignal) where buySignal is generated when MACD is positive and RSI is below the threshold, and sellSignal when MACD is negative and RSI is above the threshold.
movingAverageCrossover(source, shortLength, longLength)
movingAverageCrossover
@description Detects crossovers between short-term and long-term moving averages.
Parameters:
source (float) : The price data or input series.
shortLength (int) : The length of the short-term moving average.
longLength (int) : The length of the long-term moving average.
Returns: A tuple: (crossUp, crossDown) where crossUp is true when the short-term MA crosses above the long-term MA, and crossDown when the reverse occurs.
Autotable█ OVERVIEW
The library allows to automatically draw a table based on a string or float matrix (or both) controlling all of the parameters of the table (including merging cells) with parameter matrices (like, e.g. matrix of cell colors).
All things you would normally do with table.new() and table.cell() are now possible using respective parameters of library's main function, autotable() (as explained further below).
Headers can be supplied as arrays.
Merging of the cells is controlled with a special matrix of "L" and "U" values which instruct a cell to merged with the cell to the left or upwards (please see examples in the script and in this description).
█ USAGE EXAMPLES
The simplest and most straightforward:
mxF = matrix.new(3,3, 3.14)
mxF.autotable(bgcolor = color.rgb(249, 209, 29)) // displays float matrix as a table in the top right corner with defalult settings
mxS = matrix.new(3,3,"PI")
// displays string matrix as a table in the top right corner with defalult settings
mxS.autotable(Ypos = "bottom", Xpos = "right", bgcolor = #b4d400)
// displays matrix displaying a string value over a float value in each cell
mxS.autotable(mxF, Ypos = "middle", Xpos = "center", bgcolor = color.gray, text_color = #86f62a)
Draws this:
Tables with headers:
if barstate.islast
mxF = matrix.new(3,3, 3.14)
mxS = matrix.new(3,3,"PI")
arColHeaders = array.from("Col1", "Col2", "Col3")
arRowHeaders = array.from("Row1", "Row2", "Row3")
// float matrix with col headers
mxF.autotable(
bgcolor = #fdfd6b
, arColHeaders = arColHeaders
)
// string matrix with row headers
mxS.autotable(arRowHeaders = arRowHeaders, Ypos = "bottom", Xpos = "right", bgcolor = #b4d400)
// string/float matrix with both row and column headers
mxS.autotable(mxF
, Ypos = "middle", Xpos = "center"
, arRowHeaders = arRowHeaders
, arColHeaders = arColHeaders
, cornerBgClr = #707070, cornerTitle = "Corner cell", cornerTxtClr = #ffdc13
, bgcolor = color.gray, text_color = #86f62a
)
Draws this:
█ FUNCTIONS
One main function is autotable() which has only one required argument mxValS, a string matrix.
Please see below the description of all of the function parameters:
The table:
tbl (table) (Optional) If supplied, this table will be deleted.
The data:
mxValS (matrix ) (Required) Cell text values
mxValF (matrix) (Optional) Numerical part of cell text values. Is concatenated to the mxValS values via `string_float_separator` string (default " ")
Table properties, have same effect as in table.new() :
defaultBgColor (color) (Optional) bgcolor to be used if mxBgColor is not supplied
Ypos (string) (Optional) "top", "bottom" or "center"
Xpos (string) (Optional) "left", "right", or "center"
frame_color (color) (Optional) frame_color like in table.new()
frame_width (int) (Optional) frame_width like in table.new()
border_color (color) (Optional) border_color like in table.new()
border_width (int) (Optional) border_width like in table.new()
force_overlay (simple bool) (Optional) If true draws table on main pane.
Cell parameters, have same effect as in table.cell() ):
mxBgColor (matrix) (Optional) like bgcolor argument in table.cell()
mxTextColor (matrix) (Optional) like text_color argument in table.cell()
mxTt (matrix) (Optional) like tooltip argument in table.cell()
mxWidth (matrix) (Optional) like width argument in table.cell()
mxHeight (matrix) (Optional) like height argument in table.cell()
mxHalign (matrix) (Optional) like text_halign argument in table.cell()
mxValign (matrix) (Optional) like text_valign argument in table.cell()
mxTextSize (matrix) (Optional) like text_size argument in table.cell()
mxFontFamily (matrix) (Optional) like text_font_family argument in table.cell()
Other table properties:
tableWidth (float) (Optional) Overrides table width if cell widths are non zero. E.g. if there are four columns and cell widths are 20 (either as set via cellW or via mxWidth) then if tableWidth is set to e.g. 50 then cell widths will be 50 * (20 / 80), where 80 is 20*4 = total width of all cells. Works simialar for widths set via mxWidth - determines max sum of widths across all cloumns of mxWidth and adjusts cell widths proportionally to it. If cell widths are 0 (i.e. auto-adjust) tableWidth has no effect.
tableHeight (float) (Optional) Overrides table height if cell heights are non zero. E.g. if there are four rows and cell heights are 20 (either as set via cellH or via mxHeight) then if tableHeigh is set to e.g. 50 then cell heights will be 50 * (20 / 80), where 80 is 20*4 = total height of all cells. Works simialar for heights set via mxHeight - determines max sum of heights across all cloumns of mxHeight and adjusts cell heights proportionally to it. If cell heights are 0 (i.e. auto-adjust) tableHeight has no effect.
defaultTxtColor (color) (Optional) text_color to be used if mxTextColor is not supplied
text_size (string) (Optional) text_size to be used if mxTextSize is not supplied
font_family (string) (Optional) cell text_font_family value to be used if a value in mxFontFamily is no supplied
cellW (float) (Optional) cell width to be used if a value in mxWidth is no supplied
cellH (float) (Optional) cell height to be used if a value in mxHeight is no supplied
halign (string) (Optional) cell text_halign value to be used if a value in mxHalign is no supplied
valign (string) (Optional) cell text_valign value to be used if a value in mxValign is no supplied
Headers parameters:
arColTitles (array) (Optional) Array of column titles. If not na a header row is added.
arRowTitles (array) (Optional) Array of row titles. If not na a header column is added.
cornerTitle (string) (Optional) If both row and column titles are supplied allows to set the value of the corner cell.
colTitlesBgColor (color) (Optional) bgcolor for header row
colTitlesTxtColor (color) (Optional) text_color for header row
rowTitlesBgColor (color) (Optional) bgcolor for header column
rowTitlesTxtColor (color) (Optional) text_color for header column
cornerBgClr (color) (Optional) bgcolor for the corner cell
cornerTxtClr (color) (Optional) text_color for the corner cell
Cell merge parameters:
mxMerge (matrix) (Optional) A matrix determining how cells will be merged. "L" - cell merges to the left, "U" - upwards.
mergeAllColTitles (bool) (Optional) Allows to print a table title instead of column headers, merging all header row cells and leaving just the value of the first cell. For more flexible options use matrix arguments leaving header/row arguments na.
mergeAllRowTitles (bool) (Optional) Allows to print one text value merging all header row cells and leaving just the value of the first cell. For more flexible options use matrix arguments leaving header/row arguments na.
Format:
string_float_separator (string) (Optional) A string used to separate string and float parts of cell values (mxValS and mxValF). Default is " "
format (string) (Optional) format string like in str.format() used to format numerical values
nz (string) (Optional) Determines how na numerical values are displayed.
The only other available function is autotable(string,... ) with a string parameter instead of string and float matrices which draws a one cell table.
█ SAMPLE USE
E.g., CSVParser library demo uses Autotable's for generating complex tables with merged cells.
█ CREDITS
The library was inspired by @kaigouthro's matrixautotable . A true master. Many thanks to him for his creative, beautiful and very helpful libraries.
display_valueOVERVIEW
This script is a tinny library for creating and displaying formatted values in TradingView scripts. It provides a structured way to present key information like titles, percentages, currency values, decimals, and integers with clear formatting. This allows you to coordinate your strings in advance and hold one item to use for calling your string to a label, box, table.. Made for day to day use of most typical use cases, more advanced techniques should be used for complicated scenarios.
Building Blocks
User Defined Types (UDTs)
The script defines a UDT called `DisplayValue` to encapsulate the components of a display value:
* title : The title or label of the value.
* format_string : The string used to format the value (e.g., "{0} - 1,number,percent}").
* value : The actual value to be displayed.
* format : An enum value specifying the desired format (percent, currency, etc.).
Enums
The `DisplayFormat` enum provides predefined constants for various formatting options, making the code more readable and less prone to errors.
Functions
* create() : This function creates a new `DisplayValue` instance. It takes the title, value, and desired format as arguments and generates the appropriate format string.
* to_string() : This function converts a `DisplayValue` instance into a formatted string ready for display on the chart.
How to Use
1. Import the library:
import kaigouthro/display_value/1as dv
2. Create a DisplayValue instance:
myValue = dv.create("My Percentage", 0.5, dv.DisplayFormat.percent)
3. Convert it to a string:
formattedString = dv.to_string(myValue)
4. Display the formatted string:
label.new(bar_index, high, formattedString)
Example
//@version=5
import kaigouthro/display_value/1 as dv
myValue = dv.create("Profit", 0.15, dv.DisplayFormat.percent)
formattedString = dv.to_string(myValue)
label.new(bar_index, high, formattedString)
This will display a label on the chart with the text "Profit - 15%".
### Notes
* The library handles the formatting details, making it easier to display values consistently in your scripts.
* The use of enums and UDTs improves code organization and readability.
--------
Library "display_value"
create(display_name, display_value, display_format)
Gets the appropriate format string based on the display format.
Parameters:
display_name (string) : (string) The name of the display value. Default is na.
display_value (float)
display_format (series DisplayFormat)
Returns: (DisplayValue) A new DisplayValue instance with the formatted value.
to_string(item)
Converts the display value to a string with the specified format.
Parameters:
item (DisplayValue) : (DisplayValue) The display value to convert to a string.
Returns: (string) The string representation of the display value.
DisplayValue
Structure representing a display value.
Fields:
title (series string) : (string) The title of the display value.
format_string (series string) : (string) The format string to use for display.
value (series float) : (float) The value to display.
format (series DisplayFormat) : (DisplayFormat) The format to use.
analytics_tablesLibrary "analytics_tables"
📝 Description
This library provides the implementation of several performance-related statistics and metrics, presented in the form of tables.
The metrics shown in the afforementioned tables where developed during the past years of my in-depth analalysis of various strategies in an atempt to reason about the performance of each strategy.
The visualization and some statistics where inspired by the existing implementations of the "Seasonality" script, and the performance matrix implementations of @QuantNomad and @ZenAndTheArtOfTrading scripts.
While this library is meant to be used by my strategy framework "Template Trailing Strategy (Backtester)" script, I wrapped it in a library hoping this can be usefull for other community strategy scripts that will be released in the future.
🤔 How to Guide
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
import jason5480/analytics_tables/1 as ant
There are three types of tables provided by this library in the initial release. The stats table the metrics table and the seasonality table.
Each one shows different kinds of performance statistics.
The table UDT shall be initialized once using the `init()` method.
They can be updated using the `update()` method where the updated data UDT object shall be passed.
The data UDT can also initialized and get updated on demend depending on the use case
A code example for the StatsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(SideStats.new(), SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var statsTable = ant.StatsTable.new().init(ant.getTablePos('TOP', 'RIGHT'))
statsTable.update(statsData)
A code example for the MetricsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(ant.SideStats.new(), ant.SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var metricsTable = ant.MetricsTable.new().init(ant.getTablePos('BOTTOM', 'RIGHT'))
metricsTable.update(statsData, 10)
A code example for the SeasonalityTable is the following:
var ant.SeasonalData seasonalData = ant.SeasonalData.new().init(Seasonality.monthOfYear)
seasonalData.update()
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var seasonalTable = ant.SeasonalTable.new().init(seasonalData, ant.getTablePos('BOTTOM', 'LEFT'))
seasonalTable.update(seasonalData)
🏋️♂️ Please refer to the "EXAMPLE" regions of the script for more advanced and up to date code examples!
Special thanks to @Mrcrbw for the proposal to develop this library and @DCNeu for the constructive feedback 🏆.
getTablePos(ypos, xpos)
Get table position compatible string
Parameters:
ypos (simple string) : The position on y axise
xpos (simple string) : The position on x axise
Returns: The position to be passed to the table
method init(this, pos, height, width, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor)
Initialize the stats table object with the given colors in the given position
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts height. By default, 0 auto-adjusts the width based on the text inside the cells
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, pos, height, width, neutralBgColor)
Initialize the metrics table object with the given colors in the given position
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, seas)
Initialize the seasonal data
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
seas (simple Seasonality) : The seasonality of the matrix data
method init(this, data, pos, maxNumOfYears, height, width, extended, neutralTxtColor, neutralBgColor)
Initialize the seasonal table object with the given colors in the given position
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonality data of the table
pos (simple string) : The table position string
maxNumOfYears (simple int) : The maximum number of years that fit into the table
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
extended (simple bool) : The seasonal table with extended columns for performance
neutralTxtColor (simple color) : The text color when neutral
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, wins, losses, numOfInconclusiveExits)
Update the strategy info data of the strategy
Namespace types: StatsData
Parameters:
this (StatsData) : The strategy statistics object
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (int) : The number of inconclusive trades
method update(this, stats, positiveTxtColor, negativeTxtColor, negativeBgColor, neutralBgColor)
Update the stats table object with the given data
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
stats (StatsData) : The stats data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, stats, buyAndHoldPerc, positiveTxtColor, negativeTxtColor, positiveBgColor, negativeBgColor)
Update the metrics table object with the given data
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
stats (StatsData) : The stats data to update the table
buyAndHoldPerc (float) : The buy and hold percetage
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
method update(this)
Update the seasonal data based on the season and eon timeframe
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
method update(this, data, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor, timeBgColor)
Update the seasonal table object with the given data
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonal cell data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
timeBgColor (simple color) : The background color of the time gradient
SideStats
Object that represents the strategy statistics data of one side win or lose
Fields:
numOf (series int)
sumFreeProfit (series float)
freeProfitStDev (series float)
sumProfit (series float)
profitStDev (series float)
sumGain (series float)
gainStDev (series float)
avgQuantityPerc (series float)
avgCapitalRiskPerc (series float)
avgTPExecutedCount (series float)
avgRiskRewardRatio (series float)
maxStreak (series int)
StatsTable
Object that represents the stats table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
StatsData
Object that represents the statistics data of the strategy
Fields:
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (series int)
avgFreeProfitStr (series string)
freeProfitStDevStr (series string)
lossFreeProfitStDevStr (series string)
avgProfitStr (series string)
profitStDevStr (series string)
lossProfitStDevStr (series string)
avgQuantityStr (series string)
MetricsTable
Object that represents the metrics table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
SeasonalData
Object that represents the seasonal table dynamic data
Fields:
seasonality (series Seasonality)
eonToMatrixRow (map)
numOfEons (series int)
mostRecentMatrixRow (series int)
balances (matrix)
returnPercs (matrix)
maxDDs (matrix)
eonReturnPercs (array)
eonCAGRs (array)
eonMaxDDs (array)
SeasonalTable
Object that represents the seasonal table
Fields:
table (series table) : The actual table
headRows (series int) : The number of head rows of the table
headColumns (series int) : The number of head columns of the table
eonRows (series int) : The number of eon rows of the table
seasonColumns (series int) : The number of season columns of the table
statsRows (series int)
statsColumns (series int) : The number of stats columns of the table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
extended (series bool) : Whether the table has additional performance statistics
dataTableUtilitiesLibrary "dataTableUtilities"
generate_dataTable(dataTable_map, title, tableYpos, tableXpos)
: Generates and shows a data table.
Parameters:
dataTable_map (map)
title (string) : (string): Title of the table
tableYpos (string) : (string): Vertical position of the table
tableXpos (string) : (string): Horizontal position of the table
Returns: : None
DrawingLibrary "Drawing"
User Defined types and methods for basic drawing structure. Consolidated from the earlier libraries - DrawingTypes and DrawingMethods
method get_price(this, bar)
get line price based on bar
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
bar (int) : (series/int) bar at which line price need to be calculated
Returns: line price at given bar.
method init(this)
Namespace types: PolyLine
Parameters:
this (PolyLine)
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Point object to string representation
Namespace types: chart.point
Parameters:
this (chart.point) : DrawingTypes/Point object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Point
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LineProperties object to string representation
Namespace types: LineProperties
Parameters:
this (LineProperties) : DrawingTypes/LineProperties object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LineProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Line object to string representation
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Line
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LabelProperties object to string representation
Namespace types: LabelProperties
Parameters:
this (LabelProperties) : DrawingTypes/LabelProperties object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LabelProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Label object to string representation
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Label
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Linefill object to string representation
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Linefill
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxProperties object to string representation
Namespace types: BoxProperties
Parameters:
this (BoxProperties) : DrawingTypes/BoxProperties object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxText object to string representation
Namespace types: BoxText
Parameters:
this (BoxText) : DrawingTypes/BoxText object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxText
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Box object to string representation
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Box
method delete(this)
Deletes line from DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
Returns: Line object deleted
method delete(this)
Deletes label from DrawingTypes/Label object
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
Returns: Label object deleted
method delete(this)
Deletes Linefill from DrawingTypes/Linefill object
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill object
Returns: Linefill object deleted
method delete(this)
Deletes box from DrawingTypes/Box object
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
Returns: DrawingTypes/Box object deleted
method delete(this)
Deletes lines from array of DrawingTypes/Line objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
method delete(this)
Deletes labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method delete(this)
Deletes linefill from array of DrawingTypes/Linefill objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill objects
method delete(this)
Deletes boxes from array of DrawingTypes/Box objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Box objects
Returns: Array of DrawingTypes/Box objects
method clear(this)
clear items from array of DrawingTypes/Line while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Label while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Linefill while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Box while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method draw(this)
Creates line from DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
Returns: line created from DrawingTypes/Line object
method draw(this)
Creates lines from array of DrawingTypes/Line objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
method draw(this)
Creates label from DrawingTypes/Label object
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
Returns: label created from DrawingTypes/Label object
method draw(this)
Creates labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method draw(this)
Creates linefill object from DrawingTypes/Linefill
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill objects
Returns: linefill object created
method draw(this)
Creates linefill objects from array of DrawingTypes/Linefill objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill used for creating linefills
method draw(this)
Creates box from DrawingTypes/Box object
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
Returns: box created from DrawingTypes/Box object
method draw(this)
Creates labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method createLabel(this, lblText, tooltip, properties)
Creates DrawingTypes/Label object from DrawingTypes/Point
Namespace types: chart.point
Parameters:
this (chart.point) : DrawingTypes/Point object
lblText (string) : Label text
tooltip (string) : Tooltip text. Default is na
properties (LabelProperties) : DrawingTypes/LabelProperties object. Default is na - meaning default values are used.
Returns: DrawingTypes/Label object
method createLine(this, other, properties)
Creates DrawingTypes/Line object from one DrawingTypes/Point to other
Namespace types: chart.point
Parameters:
this (chart.point) : First DrawingTypes/Point object
other (chart.point) : Second DrawingTypes/Point object
properties (LineProperties) : DrawingTypes/LineProperties object. Default set to na - meaning default values are used.
Returns: DrawingTypes/Line object
method createLinefill(this, other, fillColor, transparency)
Creates DrawingTypes/Linefill object from DrawingTypes/Line object to other DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : First DrawingTypes/Line object
other (Line) : Other DrawingTypes/Line object
fillColor (color) : fill color of linefill. Default is color.blue
transparency (int) : fill transparency for linefill. Default is 80
Returns: Array of DrawingTypes/Linefill object
method createBox(this, other, properties, textProperties)
Creates DrawingTypes/Box object from one DrawingTypes/Point to other
Namespace types: chart.point
Parameters:
this (chart.point) : First DrawingTypes/Point object
other (chart.point) : Second DrawingTypes/Point object
properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
method createBox(this, properties, textProperties)
Creates DrawingTypes/Box object from DrawingTypes/Line as diagonal line
Namespace types: Line
Parameters:
this (Line) : Diagonal DrawingTypes/PoLineint object
properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
LineProperties
Properties of line object
Fields:
xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
extend (series string) : Property which sets line to extend towards either right or left or both. Valid values are extend.right, extend.left, extend.both, extend.none. Default is extend.none
color (series color) : Line color
style (series string) : Line style, valid values are line.style_solid, line.style_dashed, line.style_dotted, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Default is line.style_solid
width (series int) : Line width. Default is 1
Line
Line object created from points
Fields:
start (chart.point) : Starting point of the line
end (chart.point) : Ending point of the line
properties (LineProperties) : LineProperties object which defines the style of line
object (series line) : Derived line object
LabelProperties
Properties of label object
Fields:
xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
yloc (series string) : Y reference - can be yloc.price, yloc.abovebar, yloc.belowbar. Default is yloc.price
color (series color) : Label fill color
style (series string) : Label style as defined in Tradingview Documentation. Default is label.style_none
textcolor (series color) : text color. Default is color.black
size (series string) : Label text size. Default is size.normal. Other values are size.auto, size.tiny, size.small, size.normal, size.large, size.huge
textalign (series string) : Label text alignment. Default if text.align_center. Other allowed values - text.align_right, text.align_left, text.align_top, text.align_bottom
text_font_family (series string) : The font family of the text. Default value is font.family_default. Other available option is font.family_monospace
Label
Label object
Fields:
point (chart.point) : Point where label is drawn
lblText (series string) : label text
tooltip (series string) : Tooltip text. Default is na
properties (LabelProperties) : LabelProperties object
object (series label) : Pine label object
Linefill
Linefill object
Fields:
line1 (Line) : First line to create linefill
line2 (Line) : Second line to create linefill
fillColor (series color) : Fill color
transparency (series int) : Fill transparency range from 0 to 100
object (series linefill) : linefill object created from wrapper
BoxProperties
BoxProperties object
Fields:
border_color (series color) : Box border color. Default is color.blue
bgcolor (series color) : box background color
border_width (series int) : Box border width. Default is 1
border_style (series string) : Box border style. Default is line.style_solid
extend (series string) : Extend property of box. default is extend.none
xloc (series string) : defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
BoxText
Box Text properties.
Fields:
boxText (series string) : Text to be printed on the box
text_size (series string) : Text size. Default is size.auto
text_color (series color) : Box text color. Default is color.yellow.
text_halign (series string) : horizontal align style - default is text.align_center
text_valign (series string) : vertical align style - default is text.align_center
text_wrap (series string) : text wrap style - default is text.wrap_auto
text_font_family (series string) : Text font. Default is
Box
Box object
Fields:
p1 (chart.point) : Diagonal point one
p2 (chart.point) : Diagonal point two
properties (BoxProperties) : Box properties
textProperties (BoxText) : Box text properties
object (series box) : Box object created
PolyLineProperties
Fields:
curved (series bool)
closed (series bool)
xloc (series string)
lineColor (series color)
fillColor (series color)
lineStyle (series string)
lineWidth (series int)
PolyLine
Fields:
points (array)
properties (PolyLineProperties)
object (series polyline)
Order Block Overlapping Drawing [TradingFinder]🔵 Introduction
Technical analysis is a fundamental tool in financial markets, helping traders identify key areas on price charts to make informed trading decisions. The ICT (Inner Circle Trader) style, developed by Michael Huddleston, is one of the most advanced methods in this field.
It enables traders to precisely identify and exploit critical zones such as Order Blocks, Breaker Blocks, Fair Value Gaps (FVGs), and Inversion Fair Value Gaps (IFVGs).
To streamline and simplify the use of these key areas, a library has been developed in Pine Script, the scripting language for the TradingView platform. This library allows you to automatically detect overlapping zones between Order Blocks and other similar areas, and visually display them on your chart.
This tool is particularly useful for creating indicators like Balanced Price Range (BPR) and ICT Unicorn Model.
🔵 How to Use
This section explains how to use the Pine Script library. This library assists you in easily identifying and analyzing overlapping areas between Order Blocks and other zones, such as Breaker Blocks and Fair Value Gaps.
To add "Order Block Overlapping Drawing", you must first add the following code to your script.
import TFlab/OrderBlockOverlappingDrawing/1
🟣 Inputs
The library includes the "OBOverlappingDrawing" function, which you can use to detect and display overlapping zones. This function identifies and draws overlapping zones based on the Order Block type, trigger conditions, previous and current prices, and other relevant parameters.
🟣 Parameters
OBOverlappingDrawing(OBType , TriggerConditionOrigin, distalPrice_Pre, proximalPrice_Pre , distalPrice_Curr, proximalPrice_Curr, Index_Curr , OBValidGlobal, OBValidDis, MitigationLvL, ShowAll, Show, ColorZone) =>
OBType (string)
TriggerConditionOrigin (bool)
distalPrice_Pre (float)
proximalPrice_Pre (float)
distalPrice_Curr (float)
proximalPrice_Curr (float)
Index_Curr (int)
OBValidGlobal (bool)
OBValidDis (int)
MitigationLvL (string)
ShowAll (bool)
Show (bool)
ColorZone (color)
In this example, various parameters are defined to detect overlapping zones and draw them on the chart. Based on these settings, the overlapping areas will be automatically drawn on the chart.
OBType : All order blocks are summarized into two types: "Supply" and "Demand." You should input your Current order block type in this parameter. Enter "Demand" for drawing demand zones and "Supply" for drawing supply zones.
TriggerConditionOrigin : Input the condition under which you want the Current order block to be drawn in this parameter.
distalPrice_Pre : Generally, if each zone is formed by two lines, the farthest line from the price is termed Pervious "Distal." This input receives the price of the "Distal" line.
proximalPrice_Pre : Generally, if each zone is formed by two lines, the nearest line to the price is termed Previous "Proximal" line.
distalPrice_Curr : Generally, if each zone is formed by two lines, the farthest line from the price is termed Current "Distal." This input receives the price of the "Distal" line.
proximalPrice_Curr : Generally, if each zone is formed by two lines, the nearest line to the price is termed Current "Proximal" line.
Index_Curr : This input receives the value of the "bar_index" at the beginning of the order block. You should store the "bar_index" value at the occurrence of the condition for the Current order block to be drawn and input it here.
OBValidGlobal : This parameter is a boolean in which you can enter the condition that you want to execute to stop drawing the block order. If you do not have a special condition, you should set it to True.
OBValidDis : Order blocks continue to be drawn until a new order block is drawn or the order block is "Mitigate." You can specify how many candles after their initiation order blocks should continue. If you want no limitation, enter the number 4998.
MitigationLvL : This parameter is a string. Its inputs are one of "Proximal", "Distal" or "50 % OB" modes, which you can enter according to your needs. The "50 % OB" line is the middle line between distal and proximal.
ShowAll : This is a boolean parameter, if it is "true" the entire order of blocks will be displayed, and if it is "false" only the last block order will be displayed.
Show : You may need to manage whether to display or hide order blocks. When this input is "On", order blocks are displayed, and when it's "Off", order blocks are not displayed.
ColorZone : You can input your preferred color for drawing order blocks.
🟣 Output
Mitigation Alerts : This library allows you to leverage Mitigation Alerts to detect specific conditions that could lead to trend reversals. These alerts help you react promptly in your trades, ensuring better management of market shifts.
🔵 Conclusion
The Pine Script library provided is a powerful tool for technical analysis, especially in the ICT style. It enables you to detect overlapping zones between Order Blocks and other significant areas like Breaker Blocks and Fair Value Gaps, improving your trading strategies. By utilizing this tool, you can perform more precise analysis and manage risks effectively in your trades.
PubLibUtilityLibrary "PubLibUtility"
utilities for indicator and strategy development
size(size)
size to string conversion
Parameters:
size (string)
Returns: const string
tab_pos(tab_pos)
table position to string conversion
Parameters:
tab_pos (string)
Returns: const string
time_string(time_in)
time to string conversion
Parameters:
time_in (int)
Returns: literal string
lib_datesLibrary "lib_dates"
TODO: add library description here
inDateRange(from, thru)
inDateRange: Checks if the time `t` is in range between `from` to `thru`
Parameters:
from (int)
thru (int)
Returns: bool: true if time is in range false otherwise
Dark & Light Theme [TradingFinder] Switching Colors Library🔵 Introduction
One of the challenges of script users is matching the colors used in indicators or strategies. By default, colors are chosen to display based on either the dark theme or the light theme.
In scripts with a large number of colors used, changing all colors to better display in dark mode or light mode can be a difficult and tedious process.
This library provides developers with the ability to adjust the colors used in their scripts based on the theme of the display.
🔵 Logic
To categorize the color spectrum, the range from 0 to 255 of all three main colors red, green and blue was divided into smaller ranges.
Blue color, which is more effective in darkening or lightening colors, is divided into 8 categories, red color into 5 categories, and green color into 3 categories, because it has little effect on darkening or brightening colors.
The combination of these categories creates 120 different modes for the color range, which leads to a more accurate identification of the color and its brightness, and helps to decide how to change it.
Except for these 120 modes, there are 2 other modes that are related to colors almost white or black, which makes a total of 122 modes.
🔵 How to Use
First, you can add the library to your code as shown in the example below.
import TFlab/Dark_Light_Theme_TradingFinder_Switching_Colors_Library/1 as SC
🟣 Parameters
SwitchingColorMode(Color, Mode) =>
Parameters:
Color (color)
Mode (string)
Color : In this parameter, enter the color you want to adjust based on light mode and dark mode.
Mode : Three modes "Off", "Light" and "Dark" are included in this parameter. "Light" mode is for color adjustment for use in "Light Mode".
"Dark" mode is for color adjustment for use in "Dark Mode" and "Off" mode turns off the color adjustment function and the input color to the function is the same as the output color.
🔵 Function Outputs
OriginalColor = input.color(color.red)
= SC.SwitchingColorMode(OriginalColor, Mode)
ChartUtilsLibrary "ChartUtils"
Library for chart utilities, including managing tables
initTable(rows, cols, bgcolor)
Initializes a table with specific dimensions and color
Parameters:
rows (int) : (int) Number of rows in the table
cols (int) : (int) Number of columns in the table
bgcolor (color) : (color) Background color of the table
Returns: (table) The initialized table
updateTable(tbl, is_price_below_avg, current_investment_USD, strategy_position_size, strategy_position_avg_price, strategy_openprofit, strategy_opentrades, isBullishRate, isBearishRate, mlRSIOverSold, mlRSIOverBought)
Updates the trading table
Parameters:
tbl (table) : (table) The table to update
is_price_below_avg (bool) : (bool) If the current price is below the average price
current_investment_USD (float) : (float) The current investment in USD
strategy_position_size (float) : (float) The size of the current position
strategy_position_avg_price (float) : (float) The average price of the current position
strategy_openprofit (float) : (float) The current open profit
strategy_opentrades (int) : (int) The number of open trades
isBullishRate (bool) : (bool) If the current rate is bullish
isBearishRate (bool) : (bool) If the current rate is bearish
mlRSIOverSold (bool) : (bool) If the ML RSI is oversold
mlRSIOverBought (bool) : (bool) If the ML RSI is overbought
updateTableNoPosition(tbl)
Updates the table when there is no position
Parameters:
tbl (table) : (table) The table to update
SessionBoxLibrary "SessionBox"
This library provides functions to manage and visualize session boxes and labels on chart. A session box is a visual representation of a trading session with properties like time, name, color and the ability to track the high and low price within that session.
SessionBox
SessionBox: stores session data and provides methods to manage that data and visualize it on the chart.
Fields:
session_time (series bool)
session_name (series string)
session_color (series color)
[ALGOA+] AutofiboLibrary "Autofibo"
fibonacci(up, down, calculate, log, color1, color2, plot)
Creates an array with fibbonaci levels and plots lines.
Parameters:
up (float)
down (float)
calculate (bool)
log (bool)
color1 (color)
color2 (color)
plot (bool)
Returns: --> var float tupple.
fibonacciExtension(up, down, direction, log, calculate, color1, plot)
Fibonacci extension.
@description up (float) Up level.
@description down (float) Down level.
@description direction (string) Options "up" or "down".
Parameters:
up (float)
down (float)
direction (string)
log (bool)
calculate (bool)
color1 (color)
plot (bool)
Returns: -> var float, var float
trendFibo(uptrend, downtrend, log_option, color1, color2, plot)
Calculates automatic fibo values based on trends, returning a tupple with most important values.
Parameters:
uptrend (bool)
downtrend (bool)
log_option (bool)
color1 (color)
color2 (color)
plot (bool)
Returns:
signalLib_yashgode9Signal Generation Library = "signalLib_yashgode9"
This library, named "signalLib_yashgode9", is designed to generate buy and sell signals based on the price action of a financial instrument. It utilizes various technical indicators and parameters to determine the market direction and provide actionable signals for traders.
Key Features:-
1.Trend Direction Identification: The library calculates the trend direction by comparing the number of bars since the highest and lowest prices within a specified depth. This allows the library to determine the overall market direction, whether it's bullish or bearish.
2.Dynamic Price Tracking: The library maintains two chart points, zee1 and zee2, which dynamically track the price levels based on the identified market direction. These points serve as reference levels for generating buy and sell signals.
3.Customizable Parameters: The library allows users to adjust several parameters, including the depth of the price analysis, the deviation threshold, and the number of bars to consider for the trend direction. This flexibility enables users to fine-tune the library's behavior to suit their trading strategies.
4.Visual Representation: The library provides a visual representation of the buy and sell signals by drawing a line between the zee1 and zee2 chart points. The line's color changes based on the identified market direction, with red indicating a bearish signal and green indicating a bullish signal.
Usage and Integration:
To use this library, you can call the "signalLib_yashgode9" function and pass in the necessary parameters, such as the lower and higher prices, the depth of the analysis, the deviation threshold, and the number of bars to consider for the trend direction. The function will return the direction of the market (1 for bullish, -1 for bearish), as well as the zee1 and zee2 chart points.You can then use these values to generate buy and sell signals in your trading strategy. For example, you could use the direction value to determine when to enter or exit a trade, and the zee1 and zee2 chart points to set stop-loss or take-profit levels.
Potential Use Cases:
This library can be particularly useful for traders who:
1.Trend-following Strategies: The library's ability to identify the market direction can be beneficial for traders who employ trend-following strategies, as it can help them identify the dominant trend and time their entries and exits accordingly.
2.Swing Trading: The dynamic price tracking provided by the zee1 and zee2 chart points can be useful for swing traders, who aim to capture medium-term price movements.
3.Automated Trading Systems: The library's functionality can be integrated into automated trading systems, allowing for the development of more sophisticated and rule-based trading strategies.
4.Educational Purposes: The library can also be used for educational purposes, as it provides a clear and concise way to demonstrate the application of technical analysis concepts in a trading context.
Important Notice:- This library effectively work on timeframe of 5-minute and 15-minute.
ColourUtilitiesLibrary "ColourUtilities"
Utility functions for colour manipulation
adjust_colour(rgb, desaturation_amount, transparency_amount)
to reduce saturation or increase transparency of an RGB colour
Parameters:
rgb (color)
desaturation_amount (float) : 0 means no desaturation (colours remains as-is), and 1 means full desaturation (colour turns grey). Can also be used inversely with negative numbers
transparency_amount (float) : How much more transparent the default transparency should become. E.g. with a value of 0.5, a transparency of 0 becomes 50 and 40 becomes 70. A value of 1 makes it fully transparent, en -1 fully opaque.
Returns: color with adjusted saturation and transparency
method apply_default_palette(self, palette_name)
Some nice looking colour palettes, consisting of 6 gradient colours, are already defined here and can be quickly applied to the Palette class
Namespace types: Palette
Parameters:
self (Palette)
palette_name (string) : Currently there are 4 6-coloured palettes available: "GYTS flux signal", "GYTS purple", "GYTS flux filter" and "GYTS maroon"
Returns: None, as it populates the Palette class with pre-defined colours
method get_colour(self, colour_no, transparency)
Retrieves colour from the palette and possibly changes transparency if set
Namespace types: Palette
Parameters:
self (Palette)
colour_no (int) : from the palette
transparency (int) : to possibly change the default transparency of the palette
Returns: colour
method get_dynamic_colour(self, x, mid_point, colour_lb, colour_ub, trend_lookback, use_rate)
Retrieves a colour based on strength and direction of the passed series
Namespace types: Palette
Parameters:
self (Palette)
x (float) : the input data series
mid_point (float) : value as a cutoff point where the bullish/bearish colour scenario
colour_lb (float) : value (lower bound) where to apply the bearish colour at full strength
colour_ub (float) : value (upper bound) where to apply the bullish colour at full strength
trend_lookback (int) : how much bars back to check if there was a consistent move into a certain direction, otherwise a the neutral colour from the centre of the palette will be used.
use_rate (bool) : whether to use the rate (proportional difference with previous `x` value) or the input series `x` directly
Returns: colour
Palette
Fields:
transparency (series__integer)
palette (array__color)