obvFilterThis library comes with everything you need to add an On Balance Volume (OBV) filter to your strategy.
getOnBalanceVolumeFilter(source, maType, fastMaLength, fastMaLength)
Get the fast and slow moving average for on balance volume
Parameters:
source : hook this up to an 'input.source' input
maType : Choose from EMA, SMA, RMA, or WMA
fastMaLength : int smoothing length for fast moving average
fastMaLength : int smoothing length for fast moving average int smoothing length for slow moving average
Returns: Tuple with fast obv moving average and slow obv moving average
Add this to your strategy
▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾
import jordanfray/obvFilter/1 as obv
obvSource = input.source(defval=close, title="OBV Source", group="On Balance Volume Filter")
obvMaType = input.string(defval="EMA", title="OBV Smoothing Type", options = , group="On Balance Volume Filter")
fastMaLength = input.int(title = "Fast OBV MA Length", defval = 9, minval = 2, maxval = 200, group="On Balance Volume Filter")
slowMaLength = input.int(title = "Slow OBV MA Length", defval = 21, minval = 1, maxval = 200, group="On Balance Volume Filter")
= obv.getOnBalanceVolumeFilter(obvSource, obvMaType, fastMaLength, slowMaLength)
Strategies
PlurexSignalLibrary "PlurexSignal"
Provides functions that wrap the built in TradingView strategy functions so you can seemlessly integrate with Plurex Signal automation.
NOTE: Be sure to set your strategy close_entries_rule="ANY" and pyramiding=20 or some other amount appropriate to your strategy in order to have multiple entries.
plurexMarket()
Build a Plurex market string from a base and quote asset symbol.
Returns: A market string that can be used in Plurex Signal messages.
tickerToPlurexMarket()
Builds Plurex market string from the syminfo
Returns: A market string that can be used in Plurex Signal messages.
simpleMessage(secret, action, marketOverride)
Builds Plurex Signal Message json to be sent to a Signal webhook
Parameters:
secret : The secret for your Signal on plurex
action : The action of the message. One of .
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
long(secret, marketOverride, qty)
Open a new long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
qty : Corresponds to strategy.entry qty
short(secret, marketOverride, qty)
Open a new short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
qty : Corresponds to strategy.entry qty
closeAll(secret, marketOverride)
Close all positions. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLongs(secret, marketOverride)
Close all longs. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeShorts(secret, marketOverride)
Close all shorts. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLastLong(secret, marketOverride)
Close last long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeFirstLong(secret, marketOverride)
Close first long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLastShort(secret, marketOverride)
Close last short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeFirstShort(secret, marketOverride)
Close first short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
CalulateWinLossLibrary "CalulateWinLoss"
TODO: add library description here
colorwhitered(x)
TODO: add function description here
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
colorredwhite()
cal()
LibBacktestingDayRangeLibrary "LibBacktestingDayRange"
TODO: add library description here
import Nut_Satit/CalulateWinLoss/version as backtest
rangdate(startDate, finishDate)
TODO: add function description here
Parameters:
startDate : TODO: add parameter startDate description here
finishDate : TODO: add parameter finishDate description here
Returns: TODO: add what function returns
time_cond : TODO: insert variable and buy or sell condition
Binance_Min_Limit_Order_amount_libraryLibrary "Binance_Min_Limit_Order_amount_library"
TODO: This library give us the minimum Limit Order amount for the contract in Binance.
m_qty(n_v, m_fee, t_fee, cost, m_t)
TODO: it give us the Minimum Qty for the trading in Binance
Parameters:
n_v : TODO: min_notional_value. 5 dollar is the minimum notional amount in Binance at the moment.
m_fee : TODO: maker_fee %
t_fee : TODO: taker_fee %
cost : TODO: your investing money
m_t : TODO: if you want Limit_Order, put the "T", if you want Market_Order, put the "M" defval="M"
Returns: TODO: for the coin of binance on your chart,
Reference: www.binance.com
LevelsManagerLibrary "LevelsManager"
TODO: Track up to 6 TakeProfits and 1 StopLoss achievement for one or many of your buy/sell conditions.
manageTrade(bool, bool, bool, string, string, float, float, bool, bool, bool, bool, bool, bool, float, float, float, float, float, float, float)
Track TakeProfits and StopLoss achievement for one or many of your buy/sell conditions. CHECK the commented section: "Function @manageTrade" for Description
Parameters:
bool : useSignal.
bool : b_gameOVer.
bool : b_gameOVer.
string : bName.
string : sName.
float : buyEntrySource.
float : sellEntrySource.
bool : useTp1.
bool : useTp2.
bool : useTp3.
bool : useTp4.
bool : useTp5.
bool : useTp6.
float : tp1x.
float : tp2x.
float : tp3x.
float : tp4x.
float : tp5x.
float : tp6x.
float : slx.
Returns: check commented section: "Function @manageTrade".
showOnlyFirstOccurence(booleanInput)
Single out the occurence of a bool series between to 2 bool series.
Parameters:
booleanInput : to activate or deactivate occurences filtering.
Returns: filterred or not bool series.
FunctionKellyCriterionLibrary "FunctionKellyCriterion"
Kelly criterion methods.
the kelly criterion helps with the decision of how much one should invest in
a asset as long as you know the odds and expected return of said asset.
simplified(win_p, rr)
simplified version of the kelly criterion formula.
Parameters:
win_p : float, probability of winning.
rr : float, reward to risk rate.
Returns: float, optimal fraction to risk.
usage:
simplified(0.55, 1.0)
partial(win_p, loss_p, win_rr, loss_rr)
general form of the kelly criterion formula.
Parameters:
win_p : float, probability of the investment returns a positive outcome.
loss_p : float, probability of the investment returns a negative outcome.
win_rr : float, reward on a positive outcome.
loss_rr : float, reward on a negative outcome.
Returns: float, optimal fraction to risk.
usage:
partial(0.6, 0.4, 0.6, 0.1)
from_returns(returns)
Calculate the fraction to invest from a array of returns.
Parameters:
returns : array trade/asset/strategy returns.
Returns: float, optimal fraction to risk.
usage:
from_returns(array.from(0.1,0.2,0.1,-0.1,-0.05,0.05))
final_f(fraction, max_expected_loss)
Final fraction, eg. if fraction is 0.2 and expected max loss is 10%
then you should size your position as 0.2/0.1=2 (leverage, 200% position size).
Parameters:
fraction : float, aproximate percent fraction invested.
max_expected_loss : float, maximum expected percent on a loss (ex 10% = 0.1).
Returns: float, final fraction to invest.
usage:
final_f(0.2, 0.5)
hpr(fraction, trade, biggest_loss)
Holding Period Return function
Parameters:
fraction : float, aproximate percent fraction invested.
trade : float, profit or loss in a trade.
biggest_loss : float, value of the biggest loss on record.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
hpr(fraction=0.05, trade=0.1, biggest_loss=-0.2)
twr(returns, rr, eps)
Terminal Wealth Relative, returns a multiplier that can be applied
to the initial capital that leadds to the final balance.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, optimal fraction to invest.
usage:
twr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
ghpr(returns, rr, eps)
Geometric mean Holding Period Return, represents the average multiple made on the stake.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
ghpr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
run_coin_simulation(fraction, initial_capital, n_series, n_periods)
run multiple coin flipping (binary outcome) simulations.
Parameters:
fraction : float, fraction of capital to bet.
initial_capital : float, capital at the start of simulation.
n_series : int , number of simulation series.
n_periods : int , number of periods in each simulation series.
Returns: matrix(n_series, n_periods), matrix with simulation results per row.
usage:
run_coin_simulation(fraction=0.1)
run_asset_simulation(returns, fraction, initial_capital)
run a simulation over provided returns.
Parameters:
returns : array, trade, asset or strategy percent returns.
fraction : float , fraction of capital to bet.
initial_capital : float , capital at the start of simulation.
Returns: array, array with simulation results.
usage:
run_asset_simulation(returns=array.from(0.1,-0.2,0.-3,0.4), fraction=0.1)
strategy_win_probability()
calculate strategy() current probability of positive outcome in a trade.
strategy_avg_won()
calculate strategy() current average won on a trade with positive outcome.
strategy_avg_loss()
calculate strategy() current average lost on a trade with negative outcome.
threengine_global_automation_libraryLibrary "threengine_global_automation_library"
A collection of functions used for trade automation
getBaseCurrency()
Gets the base currency for the chart's ticker. Supported trade pairs are USD, USDT, USDC, BTC, and PERP.
Returns: Base currency as a string
getChartSymbol()
Get the current chart's symbol without the base currency appended to it. Supported trade paris are USD, USDT, USDC, BTC, and PERP.
Returns: Ssymbol and base currency
getDecimals()
Calculates how many decimals are on the quote price of the current market
Returns: The current deimal places on the market quote price
checkVar()
Plot a string as a label on the chart to test variable value. Use str.tostring() for any variable that isn't a string.
Returns: Label with stringified variable
getStrategyAlertMessage()
Generates stringified JSON for a limit order that can be passed to the strategy alert_message for a long entry.
Returns: Stringifed JSON for a long entry
taGetAdx()
Calculates the Average Directional Index
Returns: The value of ADX as a float
taGetEma()
Calculates the EMA based on a type, source, and length. Supported types are EMA, SMA, RMA, and WMA.
Returns: The value of the selected EMA
isBetweenTwoTimes()
Checks to see if within a rage based on two times
@retunrs true/false boolean
getAllTradeIDs()
This gets all closed trades and open trades
@retunrs an array of all open and closed trade ID's
getOpenTradeIDs()
This gets all open trades
@retunrs an array of all open trade ID's
orderAlreadyExists()
This checks to see if a provided order id uses the getAllTradeIDs() function to check
@retunrs an array of all open and closed trade ID's
orderCurrentlyExists()
This checks to see if a provided order id uses the getAllTradeIDs() function to check
Returns: an array of all open and closed trade ID's
getContractCount()
calulates the number of contracts you can buy with a set amount of capital and a limit price
Returns: number of contracts you can buy based on amount of capital you want to use and a price
getLadderSteps()
Returns: array of ladder entry prices and amounts based on total amount you want to invest across all ladder rungs and either a range between ladderStart and LadderStop based on specificed number of ladderRungs OR ladderStart, ladderRungs, and LadderSpacingPercent
PlurexSignalIntegrationLibrary "PlurexSignalIntegration"
Provides tools for integrating Strategies and Alerts into plurex.io signals.
plurexMarket() Build a Plurex market from a base and quote asset symbol.
Returns: A market string that can be used in Plurex Signal messages.
tickerToPlurexMarket() Builds simple Plurex market string from the syminfo
Returns: A market string that can be used in Plurex Signal messages.
simpleMessage(secret, action, marketOverride) Builds simple Plurex Signal Messages
Parameters:
secret : The secret for your Signal on plurex
action : The action of the message. One of .
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
executeStrategy(secret, openLong, openShort, closeLongs, closeShorts, marketOverride) Executes strategy actions with Plurex Signal messages
Parameters:
secret : The secret for your Signal on plurex
openLong : Strategy should open long if true, aggregated with other boolean values
openShort : Strategy should open short if true, aggregated with other boolean values
closeLongs : Strategy should close longs if true, aggregated with other boolean values
closeShorts : Strategy should close shorts if true, aggregated with other boolean values
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
fontilabLibrary "fontilab"
Provides function's indicators for pivot - trend - resistance.
pivots(src, lenght, isHigh) Detecting pivot points (and returning price + bar index.
Parameters:
src : The chart we analyse.
lenght : Used for the calcul.
isHigh : lookging for high if true, low otherwise.
Returns: The bar index and the price of the pivot.
calcDevThreshold(tresholdMultiplier, closePrice) Calculate deviation threshold for identifying major swings.
Parameters:
tresholdMultiplier : Usefull to equilibrate the calculate.
closePrice : Close price of the chart wanted.
Returns: The deviation threshold.
calcDev(basePrice, price) Custom function for calculating price deviation for validating large moves.
Parameters:
basePrice : The reference price.
price : The price tested.
Returns: The deviation.
pivotFoundWithLines(dev, isHigh, index, price, dev_threshold, isHighLast, pLast, iLast, lineLast) Detecting pivots that meet our deviation criteria.
Parameters:
dev : The deviation wanted.
isHigh : The type of pivot tested (high or low).
index : The Index of the pivot tested.
price : The chart price wanted.
dev_threshold : The deviation treshold.
isHighLast : The type of last pivot.
pLast : The pivot price last.
iLast : Index of the last pivot.
lineLast : The lst line.
Returns: The Line and bool is pivot High.
getDeviationPivots(thresholdMultiplier, depth, lineLast, isHighLast, iLast, pLast, deleteLines, closePrice, highPrice, lowPrice) Get pivot that meet our deviation criteria.
Parameters:
thresholdMultiplier : The treshold multiplier.
depth : The depth to calculate pivot.
lineLast : The last line.
isHighLast : The type of last pivot
iLast : Index of the last pivot.
pLast : The pivot price last.
deleteLines : If the line are draw or not.
closePrice : The chart close price.
highPrice : The chart high price.
lowPrice : The chart low price.
Returns: All pivot the informations.
getElIntArrayFromEnd() Get the last element of an int array.
getElFloatArrayFromEnd() Get the last element of an float array.
getElBoolArrayFromEnd() Get the last element of a bool array.
isTrendContinuation(isTrendUp, arrayBounds, lastPrice, precision) Check if last price is between bounds array.
Parameters:
isTrendUp : Is actual trend up.
arrayBounds : The trend array.
lastPrice : The pivot Price that just be found.
precision : The percent we add to actual bounds to validate a move.
Returns: na if price is between bounds, true if continuation, false if not.
getTrendPivots(trendBarIndexes, trendPrices, trendPricesIsHigh, interBarIndexes, interPrices, interPricesIsHigh, isTrendHesitate, isTrendUp, trendPrecision, pLast, iLast, isHighLast) Function to update array and trend related to pivot trend interpretation.
Parameters:
trendBarIndexes : The array trend bar index.
trendPrices : The array trend price.
trendPricesIsHigh : The array trend is high.
interBarIndexes : The array inter bar index.
interPrices : The array inter price.
interPricesIsHigh : The array inter ishigh.
isTrendHesitate : The actual status of is trend hesitate.
isTrendUp : The actual status of is trend up.
trendPrecision : The var precision to add in "iscontinuation" function.
pLast : The last pivot price.
iLast : The last pivot bar index.
isHighLast : The last pivot "isHigh".
Returns: trend & inter arrays, is trend hesitate, is trend up.
drawBoundLines(startIndex, startPrice, endIndex, endPrice, breakingPivotIndex, breakingPivotPrice, isTrendUp) Draw bounds and breaking line of the trend.
Parameters:
startIndex : Index of the first bound line.
startPrice : Price of first bound line.
endIndex : Index of second bound line.
endPrice : price of second bound line.
breakingPivotIndex : The breaking line index.
breakingPivotPrice : The breaking line price.
isTrendUp : The actual status of the trend.
Returns: The lines bounds and breaking line.
Strategy Table LibraryLibrary "table_library"
TODO: With this library, you can add tables to your strategies.
strategy_table()
Returns: Strategy Profit Table
Adds a table to the graph of the strategy for which you are calling the function. You can see data such as net profit in this table.
No parameters. Just call the function inside the strategy.
Example Code :
import only_fibonacci/table_lib/1 as st
st.strategy_table()
MonthlyReturnsVsMarketLibrary "MonthlyReturnsVsMarket" is a repackaging of the script here
Credits to @QuantNomad for orginal script
Now you can avoid to pollute your own strategy's code with the monthly returns table code and just import the library and call displayMonthlyPnL(int precision) function
To be used in strategy scripts.
RicardoLibraryLibrary "RicardoLibrary"
Ricardo's personal Library
GetPipValue() GetPipValue
Returns: Pip value of Symbol
Calculate_SL(IsLong) Calculate_SL: Calcultes Stop Loss
Parameters:
IsLong : If true, then I am going to enter a long position, if false then Short position
Returns: Stop loss Price
poStrategyLibraryLibrary "poStrategyLibrary"
essential function for export
isFlat()
isLongShort()
pipProfit()
pipLoss()
Strategy█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing a variety of strategy-related functions to assist in calculations like profit and loss, stop losses and limits. It also includes several useful functions one can use to convert between units in ticks, price, currency or a percentage of the position's size.
█ CONCEPTS
The library contains three types of functions:
1 — Functions beginning with `percent` take either a portion of a price, or the current position's entry price and convert it to the value outlined in the function's documentation.
Example: Converting a percent of the current position entry price to ticks, or calculating a percent profit at a given level for the position.
2 — Functions beginning with `tick` convert a tick value to another form.
These are useful for calculating a price or currency value from a specified number of ticks.
3 — Functions containing `Level` are used to calculate a stop or take profit level using an offset in ticks from the current entry price.
These functions can be used to plot stop or take profit levels on the chart, or as arguments to the `limit` and `stop` parameters in strategy.exit() function calls.
Note that these calculated levels flip automatically with the position's bias.
For example, using `ticksToStopLevel()` will calculate a stop level under the entry price for a long position, and above the entry price for a short position.
There are also two functions to assist in calculating a position size using the entry's stop and a fixed risk expressed as a percentage of the current account's equity. By varying the position size this way, you ensure that entries with different stop levels risk the same proportion of equity.
█ NOTES
Example code using some of the library's functions is included at the end of the library. To see it in action, copy the library's code to a new script in the Pine Editor, and “Add to chart”.
For each trade, the code displays:
• The entry level in orange.
• The stop level in fuchsia.
• The take profit level in green.
The stop and take profit levels automatically flip sides based on whether the current position is long or short.
Labels near the last trade's levels display the percentages used to calculate them, which can be changed in the script's inputs.
We plot markers for entries and exits because strategy code in libraries does not display the usual markers for them.
Look first. Then leap.
█ FUNCTIONS
percentToTicks(percent) Converts a percentage of the average entry price to ticks.
Parameters:
percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to ticks. 50 is 50% of the entry price.
Returns: (float) A value in ticks.
percentToPrice(percent) Converts a percentage of the average entry price to a price.
Parameters:
percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to price. 50 is 50% of the entry price.
Returns: (float) A value in the symbol's quote currency (USD for BTCUSD).
percentToCurrency(price, percent) Converts the percentage of a price to money.
Parameters:
price : (series int/float) The symbol's price.
percent : (series int/float) The percentage of `price` to calculate.
Returns: (float) A value in the symbol's currency.
percentProfit(exitPrice) Calculates the profit (as a percentage of the position's `strategy.position_avg_price` entry price) if the trade is closed at `exitPrice`.
Parameters:
exitPrice : (series int/float) The potential price to close the position.
Returns: (float) Percentage profit for the current position if closed at the `exitPrice`.
priceToTicks(price) Converts a price to ticks.
Parameters:
price : (series int/float) Price to convert to ticks.
Returns: (float) A quantity of ticks.
ticksToPrice(price) Converts ticks to a price offset from the average entry price.
Parameters:
price : (series int/float) Ticks to convert to a price.
Returns: (float) A price level that has a distance from the entry price equal to the specified number of ticks.
ticksToCurrency(ticks) Converts ticks to money.
Parameters:
ticks : (series int/float) Number of ticks.
Returns: (float) Money amount in the symbol's currency.
ticksToStopLevel(ticks) Calculates a stop loss level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `stop` parameter of a `strategy.exit()` call. NOTE: The stop level automatically flips based on whether the position is long or short.
Parameters:
ticks : (series int/float) The distance in ticks from the entry price to the stop loss level.
Returns: (float) A stop loss level for the current position.
ticksToTpLevel(ticks) Calculates a take profit level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `limit` parameter of a `strategy.exit()` call. NOTE: The take profit level automatically flips based on whether the position is long or short.
Parameters:
ticks : (series int/float) The distance in ticks from the entry price to the take profit level.
Returns: (float) A take profit level for the current position.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent) Calculates the position size needed to implement a given stop loss (in ticks) corresponding to `riskPercent` of equity.
Parameters:
stopLossTicks : (series int) The stop loss (in ticks) that will be used to protect the position.
riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
Returns: (int) A quantity of contracts.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice) Calculates the position size needed to implement a given stop loss (%) corresponding to `riskPercent` of equity.
Parameters:
stopLossPercent : (series int/float) The stop loss in percent that will be used to protect the position.
riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
entryPrice : (series int/float) The entry price of the position.
Returns: (int) A quantity of contracts.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, when, alertMessage) A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit in as a value in percent. NOTE: this function may work incorrectly with pyramiding turned on due to the use of `strategy.position_avg_price` in its calculations of stop loss and take profit offsets.
Parameters:
id : (series string) The order identifier of the `strategy.exit()` call.
lossPercent : (series int/float) Stop loss as a percent of the entry price.
profitPercent : (series int/float) Take profit as a percent of the entry price.
qty : (series int/float) Number of contracts/shares/lots/units to exit a trade with. The default value is `na`.
qtyPercent : (series int/float) The percent of the position's size to exit a trade with. If `qty` is `na`, the default value of `qty_percent` is 100.
comment : (series string) Optional. Additional notes on the order.
when : (series bool) Condition of the order. The order is placed if it is true.
alertMessage : (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
Adaptive_LengthLibrary "Adaptive_Length"
This library contains functions to calculate Adaptive dynamic length which can be used in Moving Averages and other indicators.
Two Exponential Moving Averages (EMA) are plotted. Coloring in plot is derived from Chikou filter and Dynamic length of MA1 is adapted using Signal output from Chikou library.
dynamic(para, adapt_Pct, minLength, maxLength) Adaptive dynamic length based on boolean parameter
Parameters:
para : Boolean parameter; if true then length would decrease and would increase if its false
adapt_Pct : Percentage adaption based on parameter
minLength : Minimum allowable length
maxLength : Maximum allowable length
Returns: Adaptive Dynamic Length based on Boolean Parameter
auto_alpha(src, a) Adaptive length based on automatic alpha calculations from source input
Parameters:
src : Price source for alpha calculations
a : Input Alpha value
Returns: Adaptive Length calculated from input price Source and Alpha
ChikouLibrary "Chikou"
This library contains Chikou Filter function to enhances functionality of Chikou-Span from Ichimoku Cloud using a simple trend filter.
Chikou is basically close value of ticker offset to close and it is a good for indicating if close value has crossed potential Support/Resistance zone from past. Chikou is usually used with 26 period.
Chikou filter uses a lookback length calculated from provided lookback percentage and checks if trend was bullish or bearish within that lookback period.
Bullish : Trend is bullish if Chikou span is above high values of all candles within defined lookback period. Bull color shows bullish trend .
Bearish : Trend is bearish if Chikou span is below low values of all candles within defined lookback period. This is indicated by Bearish color.
Reversal / Choppiness : Reversal color indicates that Chikou are swinging around candles within defined lookback period which is an indication of consolidation or trend reversal.
chikou(src, len, perc, _high, _low, bull_col, bear_col, r_col) Chikou Filter for Ichimoku Cloud with Color and Signal Output
Parameters:
src : Price Source (better to use (OHLC4+high+low/3 instead of default close value)
len : Chikou Legth (displaced source value)
perc : Percentage lookback period for Chikou Filter with defined how much candels of total length should be considered for backward filteration
_high : Ticker High Value
_low : Ticker Low Value
bull_col : Color to be returned if source value is greater than all candels within provided lookback percentage.
bear_col : Color to be returned if source value is lower than all candels within provided lookback percentage.
r_col : Color to be returned if source value is swinging around candles within defined lookback period which is an indication of consolidation or trend reversal.
Returns: Color based on trend. 'bull_col' if trend is bullish, 'bear_col' if trend is bearish. 'r_col' if no prominent trend. Integer Signal is also returned as 1 for Bullish, -1 for Bearish and 0 for no prominent trend.
eStrategyLibrary "eStrategy"
Library contains methods which can help build custom strategy for continuous investment plans and also compare it with systematic buy and hold.
sip(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice) Depicts systematic buy and hold over period of time
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalEquity - Present equity
customStrategy(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice, sellPrice, initialInvestmentPercent, recurringInvestmentPercent, signal, tradePercent) Allows users to define custom strategy and enhance systematic buy and hold by adding take profit and reloads
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
sellPrice : Indicatinve sell price. Use low to be conservative. high, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
initialInvestmentPercent : percent of amount to invest from the initial depost. Keep rest of them as cash
recurringInvestmentPercent : percent of amount to invest from recurring deposit. Keep rest of them as cash
signal : can be 1, -1 or 0. 1 means buy/reload. -1 means take profit and 0 means neither.
tradePercent : percent of amount to trade when signal is not 0. If taking profit, it will sell the percent from existing position. If reloading, it will buy with percent from cash reserve
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalCash = Amount of cash held
totalEquity - Overall equity = totalQty*close + totalCash
BjCandlePatternsLibrary "BjCandlePatterns"
Patterns is a Japanese candlestick pattern recognition Library for developers. Functions here within detect viable setups in a variety of popular patterns. Please note some patterns are without filters such as comparisons to average candle sizing, or trend detection to allow the author more freedom.
doji(dojiSize, dojiWickSize) Detects "Doji" candle patterns
Parameters:
dojiSize : (float) The relationship of body to candle size (ie. body is 5% of total candle size). Default is 5.0 (5%)
dojiWickSize : (float) Maximum wick size comparative to the opposite wick. (eg. 2 = bottom wick must be less than or equal to 2x the top wick). Default is 2
Returns: (series bool) True when pattern detected
dLab(showLabel, labelColor, textColor) Produces "Doji" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bullEngulf(maxRejectWick, mustEngulfWick) Detects "Bullish Engulfing" candle patterns
Parameters:
maxRejectWick : (float) Maximum rejection wick size.
The maximum wick size as a percentge of body size allowable for a top wick on the resolution candle of the pattern. 0.0 disables the filter.
eg. 50 allows a top wick half the size of the body. Default is 0% (Disables wick detection).
mustEngulfWick : (bool) input to only detect setups that close above the high prior effectively engulfing the candle in its entirety. Default is false
Returns: (series bool) True when pattern detected
bewLab(showLabel, labelColor, textColor) Produces "Bullish Engulfing" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bearEngulf(maxRejectWick, mustEngulfWick) Detects "Bearish Engulfing" candle patterns
Parameters:
maxRejectWick : (float) Maximum rejection wick size.
The maximum wick size as a percentge of body size allowable for a bottom wick on the resolution candle of the pattern. 0.0 disables the filter.
eg. 50 allows a botom wick half the size of the body. Default is 0% (Disables wick detection).
mustEngulfWick : (bool) Input to only detect setups that close below the low prior effectively engulfing the candle in its entirety. Default is false
Returns: (series bool) True when pattern detected
bebLab(showLabel, labelColor, textColor) Produces "Bearish Engulfing" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
hammer(ratio, shadowPercent) Detects "Hammer" candle patterns
Parameters:
ratio : (float) The relationship of body to candle size (ie. body is 33% of total candle size). Default is 33%.
shadowPercent : (float) The maximum allowable top wick size as a percentage of body size. Default is 5%.
Returns: (series bool) True when pattern detected
hLab(showLabel, labelColor, textColor) Produces "Hammer" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
star(ratio, shadowPercent) Detects "Star" candle patterns
Parameters:
ratio : (float) The relationship of body to candle size (ie. body is 33% of total candle size). Default is 33%.
shadowPercent : (float) The maximum allowable bottom wick size as a percentage of body size. Default is 5%.
Returns: (series bool) True when pattern detected
ssLab(showLabel, labelColor, textColor) Produces "Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
dragonflyDoji() Detects "Dragonfly Doji" candle patterns
Returns: (series bool) True when pattern detected
ddLab(showLabel, labelColor) Produces "Dragonfly Doji" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
Returns: (series label) A label visible at the chart level intended for the title pattern
gravestoneDoji() Detects "Gravestone Doji" candle patterns
Returns: (series bool) True when pattern detected
gdLab(showLabel, labelColor, textColor) Produces "Gravestone Doji" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tweezerBottom(closeUpperHalf) Detects "Tweezer Bottom" candle patterns
Parameters:
closeUpperHalf : (bool) input to only detect setups that close above the mid-point of the candle prior increasing its bullish tendancy. Default is false
Returns: (series bool) True when pattern detected
tbLab(showLabel, labelColor, textColor) Produces "Tweezer Bottom" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tweezerTop(closeLowerHalf) Detects "TweezerTop" candle patterns
Parameters:
closeLowerHalf : (bool) input to only detect setups that close below the mid-point of the candle prior increasing its bearish tendancy. Default is false
Returns: (series bool) True when pattern detected
ttLab(showLabel, labelColor, textColor) Produces "TweezerTop" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
spinningTopBull(wickSize) Detects "Bullish Spinning Top" candle patterns
Parameters:
wickSize : (float) input to adjust detection of the size of the top wick/ bottom wick as a percent of total candle size. Default is 34%, which ensures the wicks are both larger than the body.
Returns: (series bool) True when pattern detected
stwLab(showLabel, labelColor, textColor) Produces "Bullish Spinning Top" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
spinningTopBear(wickSize) Detects "Bearish Spinning Top" candle patterns
Parameters:
wickSize : (float) input to adjust detection of the size of the top wick/ bottom wick as a percent of total candle size. Default is 34%, which ensures the wicks are both larger than the body.
Returns: (series bool) True when pattern detected
stbLab(showLabel, labelColor, textColor) Produces "Bearish Spinning Top" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
spinningTop(wickSize) Detects "Spinning Top" candle patterns
Parameters:
wickSize : (float) input to adjust detection of the size of the top wick/ bottom wick as a percent of total candle size. Default is 34%, which ensures the wicks are both larger than the body.
Returns: (series bool) True when pattern detected
stLab(showLabel, labelColor, textColor) Produces "Spinning Top" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
morningStar() Detects "Bullish Morning Star" candle patterns
Returns: (series bool) True when pattern detected
msLab(showLabel, labelColor, textColor) Produces "Bullish Morning Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
eveningStar() Detects "Bearish Evening Star" candle patterns
Returns: (series bool) True when pattern detected
esLab(showLabel, labelColor, textColor) Produces "Bearish Evening Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBull() Detects "Bullish Harami" candle patterns
Returns: (series bool) True when pattern detected
hwLab(showLabel, labelColor, textColor) Produces "Bullish Harami" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBear() Detects "Bearish Harami" candle patterns
Returns: (series bool) True when pattern detected
hbLab(showLabel, labelColor, textColor) Produces "Bearish Harami" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBullCross() Detects "Bullish Harami Cross" candle patterns
Returns: (series bool) True when pattern detected
hcwLab(showLabel, labelColor, textColor) Produces "Bullish Harami Cross" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
haramiBearCross() Detects "Bearish Harami Cross" candle patterns
Returns: (series bool) True when pattern detected
hcbLab(showLabel, labelColor) Produces "Bearish Harami Cross" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
Returns: (series label) A label visible at the chart level intended for the title pattern
marubullzu() Detects "Bullish Marubozu" candle patterns
Returns: (series bool) True when pattern detected
mwLab(showLabel, labelColor, textColor) Produces "Bullish Marubozu" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
marubearzu() Detects "Bearish Marubozu" candle patterns
Returns: (series bool) True when pattern detected
mbLab(showLabel, labelColor, textColor) Produces "Bearish Marubozu" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
abandonedBull() Detects "Bullish Abandoned Baby" candle patterns
Returns: (series bool) True when pattern detected
abwLab(showLabel, labelColor, textColor) Produces "Bullish Abandoned Baby" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
abandonedBear() Detects "Bearish Abandoned Baby" candle patterns
Returns: (series bool) True when pattern detected
abbLab(showLabel, labelColor, textColor) Produces "Bearish Abandoned Baby" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
piercing() Detects "Piercing" candle patterns
Returns: (series bool) True when pattern detected
pLab(showLabel, labelColor, textColor) Produces "Piercing" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
darkCloudCover() Detects "Dark Cloud Cover" candle patterns
Returns: (series bool) True when pattern detected
dccLab(showLabel, labelColor, textColor) Produces "Dark Cloud Cover" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tasukiBull() Detects "Upside Tasuki Gap" candle patterns
Returns: (series bool) True when pattern detected
utgLab(showLabel, labelColor, textColor) Produces "Upside Tasuki Gap" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
tasukiBear() Detects "Downside Tasuki Gap" candle patterns
Returns: (series bool) True when pattern detected
dtgLab(showLabel, labelColor, textColor) Produces "Downside Tasuki Gap" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
risingThree() Detects "Rising Three Methods" candle patterns
Returns: (series bool) True when pattern detected
rtmLab(showLabel, labelColor, textColor) Produces "Rising Three Methods" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
fallingThree() Detects "Falling Three Methods" candle patterns
Returns: (series bool) True when pattern detected
ftmLab(showLabel, labelColor, textColor) Produces "Falling Three Methods" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
risingWindow() Detects "Rising Window" candle patterns
Returns: (series bool) True when pattern detected
rwLab(showLabel, labelColor, textColor) Produces "Rising Window" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
fallingWindow() Detects "Falling Window" candle patterns
Returns: (series bool) True when pattern detected
fwLab(showLabel, labelColor, textColor) Produces "Falling Window" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
kickingBull() Detects "Bullish Kicking" candle patterns
Returns: (series bool) True when pattern detected
kwLab(showLabel, labelColor, textColor) Produces "Bullish Kicking" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
kickingBear() Detects "Bearish Kicking" candle patterns
Returns: (series bool) True when pattern detected
kbLab(showLabel, labelColor, textColor) Produces "Bearish Kicking" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
lls(ratio) Detects "Long Lower Shadow" candle patterns
Parameters:
ratio : (float) A relationship of the lower wick to the overall candle size expressed as a percent. Default is 75%
Returns: (series bool) True when pattern detected
llsLab(showLabel, labelColor, textColor) Produces "Long Lower Shadow" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
lus(ratio) Detects "Long Upper Shadow" candle patterns
Parameters:
ratio : (float) A relationship of the upper wick to the overall candle size expressed as a percent. Default is 75%
Returns: (series bool) True when pattern detected
lusLab(showLabel, labelColor, textColor) Produces "Long Upper Shadow" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bullNeck() Detects "Bullish On Neck" candle patterns
Returns: (series bool) True when pattern detected
nwLab(showLabel, labelColor, textColor) Produces "Bullish On Neck" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
bearNeck() Detects "Bearish On Neck" candle patterns
Returns: (series bool) True when pattern detected
nbLab(showLabel, labelColor, textColor) Produces "Bearish On Neck" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
soldiers(wickSize) Detects "Three White Soldiers" candle patterns
Parameters:
wickSize : (float) Maximum allowable top wick size throughout pattern expressed as a percent of total candle height. Default is 5%
Returns: (series bool) True when pattern detected
wsLab(showLabel, labelColor, textColor) Produces "Three White Soldiers" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
crows(wickSize) Detects "Three Black Crows" candle patterns
Parameters:
wickSize : (float) Maximum allowable bottom wick size throughout pattern expressed as a percent of total candle height. Default is 5%
Returns: (series bool) True when pattern detected
bcLab(showLabel, labelColor, textColor) Produces "Three Black Crows" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
triStarBull() Detects "Bullish Tri-Star" candle patterns
Returns: (series bool) True when pattern detected
tswLab(showLabel, labelColor, textColor) Produces "Bullish Tri-Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
triStarBear() Detects "Bearish Tri-Star" candle patterns
Returns: (series bool) True when pattern detected
tsbLab(showLabel, labelColor, textColor) Produces "Bearish Tri-Star" identifier label
Parameters:
showLabel : (bool) Shows label when input is true. Default is false
labelColor : (series color) Color of the label border and arrow
textColor : (series color) Text color
Returns: (series label) A label visible at the chart level intended for the title pattern
wrap(cond, barsBack, borderColor, bgcolor) Produces a box wrapping the highs and lows over the look back.
Parameters:
cond : (series bool) Condition under which to draw the box.
barsBack : (series int) the number of bars back to begin drawing the box.
borderColor : (series color) Color of the four borders. Optional. The default is color.gray.
bgcolor : (series color) Background color of the box. Optional. The default is color.gray.
Returns: (series box) A box who's top and bottom are above and below the highest and lowest points over the lookback
topWick() returns the top wick size of the current candle
Returns: (series float) A value equivelent to the distance from the top of the candle body to its high
bottomWick() returns the bottom wick size of the current candle
Returns: (series float) A value equivelent to the distance from the bottom of the candle body to its low
body() returns the body size of the current candle
Returns: (series float) A value equivelent to the distance between the top and the bottom of the candle body
highestBody() returns the highest body of the current candle
Returns: (series float) A value equivelent to the highest body, whether it is the open or the close
lowestBody() returns the lowest body of the current candle
Returns: (series float) A value equivelent to the highest body, whether it is the open or the close
barRange() returns the height of the current candle
Returns: (series float) A value equivelent to the distance between the high and the low of the candle
bodyPct() returns the body size as a percent
Returns: (series float) A value equivelent to the percentage of body size to the overall candle size
midBody() returns the price of the mid-point of the candle body
Returns: (series float) A value equivelent to the center point of the distance bewteen the body low and the body high
bodyupGap() returns true if there is a gap up between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap up and no overlap in the real bodies of the current candle and the preceding candle
bodydwnGap() returns true if there is a gap down between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap down and no overlap in the real bodies of the current candle and the preceding candle
gapUp() returns true if there is a gap down between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap down and no overlap in the real bodies of the current candle and the preceding candle
gapDwn() returns true if there is a gap down between the real body of the current candle in relation to the candle prior
Returns: (series bool) true if there is a gap down and no overlap in the real bodies of the current candle and the preceding candle
dojiBody() returns true if the candle body is a doji
Returns: (series bool) true if the candle body is a doji. Defined by a body that is 5% of total candle size
StocksDeveloper_AutoTraderWebLibrary "StocksDeveloper_AutoTraderWeb"
AutoTrader Web trading API functions implementation for Trading View.
preparePlaceOrderJson(account, symbol, group, variety) Prepare a place order json
Parameters:
account : Pseudo or group account number
symbol : AutoTrader Web's stock/derivative symbol
group : Set it to true to use group account (Default: false)
variety : Variety (Default: REGULAR)
Returns: A json message for the given order data
preparePlaceOrderAlertUsingOrderJson(orderJsonArray) Prepare a place order alert message using order json array
Parameters:
orderJsonArray : Order json can contain one or more orders
Returns: A complete alert message to place orders
preparePlaceOrderAlertMessage(account, symbol, group, variety, validity) Prepare a place order alert json message
Parameters:
account : Pseudo or group account number
symbol : AutoTrader Web's stock/derivative symbol
group : Set it to true to use group account (Default: false)
variety : Variety (Default: REGULAR)
validity : Validity (Default: DAY)
Returns: A complete alert message to place orders
Woodwind VaultLibrary "WoodwindVault"
Woodwind Vault provides reusable functions to support Thange Woodwind Playbook execution.
getHighestHighAndLowestLow(period) determines the highest-high and lowest-low for the specified time interval.
Parameters:
period : int, the time interval for finding the highest-high and lowest-low.
Returns: float, the highest-high and lowest-low of the candles in the specified period.
findEquilibrium() projects a one glance view of the entire resistance net faced by the price. It does so by computing different equilibrium points for the price.
Returns: longTermEquilibriumB float, the midpoint of highest-high and lowest-low of the candles in last longTermPeriod.
getGlance(fast, slow) glances over the 2 equilibrium points from moving averages and establishes whether its bullish or bearish.
Parameters:
fast : float, the fast moving point.
slow : float, the slow moving point.
Returns: string, it is "bullish" if fast moving point is over the slow moving point o/w returns "bearish".
positionRelativeToLevel(point, level) determines first point's position w.r.t a specified level.
Parameters:
point : float, the first point (typically a fast moving average).
level : float, the second point acting as a level (typically a slow moving average).
Returns: string, the above/below/at position w.r.t level.
positionRelativeToRange(point, fromLevel, toLevel) determines first point's position w.r.t a range (typically a resistance band).
Parameters:
point : float, the first point.
fromLevel : float, the from-range which is typically a fast moving line.
toLevel : float, the to-range which is typically a slow moving line.
Returns: string, the above/below/within range.
The Divergent LibraryLibrary "TheDivergentLibrary"
The Divergent Library is only useful when combined with the Pro version of The Divergent - Advanced divergence indicator . This is because the Basic (free) version of The Divergent does not expose the "Divergence Signal" value.
Usage instructions:
1. Create a new chart
2. Add The Divergent (Pro) indicator to your chart
3. Create a new strategy, import this library, add a "source" input, link it to "The Divergent: Divergence Signal", and use the library to decode the divergence signals from The Divergent (You can find example strategy code published in our profile)
4. Act on the divergences signalled by The Divergent
---
isRegularBullishEnabled(context) Returns a boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
isHiddenBullishEnabled(context) Returns a boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
isRegularBearishEnabled(context) Returns a boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
isHiddenBearishEnabled(context) Returns a boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
getPivotDetectionSource(context) Returns the 'Pivot Detection Source' setting of The Divergent. The returned value can be either "Oscillator" or "Price".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Oscillator" or "Price".
getPivotDetectionMode(context) Returns the 'Pivot Detection Mode' setting of The Divergent. The returned value can be either "Bodies" or "Wicks".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Bodies" or "Wicks".
isLinked(context) Returns a boolean value indicating the link status to The Divergent indicator.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating the link status to The Divergent indicator.
init(firstBarSignal, displayLinkStatus, debug) Initialises The Divergent Library's context with the signal produced by The Divergent on the first bar. The value returned from this function is called the "context of The Divergent Library". Some of the other functions of this library requires you to pass in this context.
Parameters:
firstBarSignal : The signal from The Divergent indicator on the first bar.
displayLinkStatus : A boolean value indicating whether the Link Status window should be displayed in the bottom left corner of the chart. Defaults to true.
debug : A boolean value indicating whether the Link Status window should display debug information. Defaults to false.
Returns: A bool array containing the context of The Divergent Library.
processSignal(signal) Processes a signal from The Divergent and returns a 5-tuple with the decoded signal: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd]. `divergenceType` can be one of the following values: na → No divergence was detected, 1 → Regular Bullish, 2 → Regular Bullish early, 3 → Hidden Bullish, 4 → Hidden Bullish early, 5 → Regular Bearish, 6 → Regular Bearish early, 7 → Hidden Bearish, 8 → Hidden Bearish early.
Parameters:
signal : The signal from The Divergent indicator.
Returns: A 5-tuple with the following values: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd].
TradingPortfolioLibrary "TradingPortfolio"
Simple functions for portfolio management. A portfolio is essentially
a float array with 3 positions that gets passed around
into these functions that ensure it gets properly updated as trading ensues.
An example usage:
import hugodanielcom/TradingPortfolio/XXXX as portfolio
var float my_portfolio = portfolio.init(0.0, strategy.initial_capital) // Initialize the portfolio with the strategy capital
if close < 10.0
portfolio.buy(my_portfolio, 10.0, close) // Buy when the close is below 10.0
plot(portfolio.total(my_portfolio), title = "Total portfolio value")
get_balance(portfolio) Gets the number of tokens and fiat available in the supplied portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The tokens and fiat in a tuple
set_balance(portfolio, new_crypto, new_fiat) Sets the portfolio number of tokens and fiat amounts. This function overrides the current values in the portfolio and sets the provided ones as the new portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
new_crypto : The new amount of tokens in the portfolio.
new_fiat : The new amount of fiat in the portfolio
Returns: The tokens and fiat in a tuple
init(crypto, fiat) This function returns a clean portfolio. Start by calling this function and pass its return value as an argument to the other functions in this library.
Parameters:
crypto : The initial amount of tokens in the portfolio (defaults to 0.0).
fiat : The initial amount of fiat in the portfolio (defaults to 0.0).
Returns: The portfolio (a float )
crypto(portfolio) Gets the number of tokens in the portfolio
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of tokens in the portfolio
fiat(portfolio) Gets the fiat in the portfolio
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of fiat in the portfolio
retained(portfolio) Gets the amount of reatined fiat in the portfolio. Retained fiat is not considered as part of the balance when buying/selling, but it is considered as part of the total of the portfolio.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
Returns: The amount of retained fiat in the portfolio
retain(portfolio, fiat_to_retain) Sets the amount of fiat to retain. It removes the amount from the current fiat in the portfolio and marks it as retained.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
fiat_to_retain : The amount of fiat to remove and mark as retained.
Returns: void
total(portfolio, token_value) Calculates the total fiat value of the portfolio. It multiplies the amount of tokens by the supplied value and adds to the result the current fiat and retained amount.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
token_value : The fiat value of a unit (1) of token
Returns: A float that corresponds to the total fiat value of the portfolio (retained amount included)
ratio(portfolio, token_value) Calculates the ratio of tokens / fiat. The retained amount of fiat is not considered, only the active fiat being considered for trading.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
token_value : The fiat value of a unit (1) of token
Returns: A float between 1.0 and 0.0 that corresponds to the portfolio ratio of token / fiat (i.e. 0.6 corresponds to a portfolio whose value is made by 60% tokens and 40% fiat)
can_buy(portfolio, amount, token_value) Asserts that there is enough balance to buy the requested amount of tokens.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to assert that can be bought
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true if there is capacity to buy the amount of tokens provided.
can_sell(portfolio, amount) Asserts that there is enough token balance to sell the requested amount of tokens.
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to assert that can be sold
Returns: A boolean value, true if there is capacity to sold the amount of tokens provided.
buy(portfolio, amount, token_value) Adjusts the portfolio state to perform the equivalent of a buy operation (as in, buy the requested amount of tokens at the provided value and set the portfolio accordingly).
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to buy
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true the requested amount of tokens was "bought" and the portfolio updated. False if nothing was changed.
sell(portfolio, amount, token_value) Adjusts the portfolio state to perform the equivalent of a sell operation (as in, sell the requested amount of tokens at the provided value and set the portfolio accordingly).
Parameters:
portfolio : A portfolio float array as created by the `init()` function.
amount : The amount of tokens to sell
token_value : The fiat value of a unit (1) of token
Returns: A boolean value, true the requested amount of tokens was "sold" and the portfolio updated. False if nothing was changed.