name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
FunctionMatrixCovariance | https://www.tradingview.com/script/5MOmhPwf-FunctionMatrixCovariance/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 14 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description In probability theory and statistics, a covariance matrix (also known as auto-covariance matrix, dispersion matrix, variance matrix, or variance–covariance matrix) is a square matrix giving the covariance between each pair of elements of a given random vector.
// Intuitively, the covariance matrix generalizes the notion of variance to multiple dimensions. As an example, the variation in a collection of random points in two-dimensional space cannot be characterized fully by a single number, nor would the variances in the `x` and `y` directions contain all of the necessary information; a `2 × 2` matrix would be necessary to fully characterize the two-dimensional variation.
// Any covariance matrix is symmetric and positive semi-definite and its main diagonal contains variances (i.e., the covariance of each element with itself).
// The covariance matrix of a random vector `X` is typically denoted by `Kxx`, `Σ` or `S`.
// ~wikipedia.
library("FunctionMatrixCovariance")
// @function Estimate Covariance matrix with provided data.
// @param M `matrix<float>` Matrix with vectors in column order.
// @returns Covariance matrix of provided vectors.
//
// ---
// https://en.wikipedia.org/wiki/Covariance_matrix
// https://numpy.org/doc/stable/reference/generated/numpy.cov.html
export method cov (matrix<float> M, bool bias = false) =>
int _rows = M.rows()
int _cols = M.columns()
switch
_rows <= 0 => runtime.error('Data vectors are empty.')
_cols < 1 => runtime.error('Need atleast one data vector.')
matrix<float> _S = matrix.new<float>(_cols, _cols, na)
for _col = 0 to _cols - 1
_Mcol = M.col(_col)
for _i = _col to _cols - 1
_c = _Mcol.covariance(M.col(_i), bias)
_S.set(_col, _i, _c)
_S.set(_i, _col, _c)
_S.set(_col, _col, _Mcol.variance(bias))
_S
// TEST 20230828 RS
// if barstate.islastconfirmedhistory
// iv = matrix.new<float>(3, 0, 0.0)
// iv.add_col(0, array.from(1.0, 0.5, 0.5))
// iv.add_col(1, array.from(0.5, 1.0, 0.5))
// iv.add_col(2, array.from(0.5, 0.5, 1.0))
// // [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
// a = matrix.new<float>(5, 0, 0.0)
// a.add_col(0, array.from(1.0,2,3,4,5))
// a.add_col(1, array.from(6.0,7,8,9,40))
// b = matrix.new<float>(3, 0, 0.0)
// b.add_col(0, array.from(1.0,1,3))
// b.add_col(1, array.from(2.0,2,3))
// log.info('\n{0}', cov(iv))
// log.info('\n{0}', cov(a))
// log.info('\n{0}', cov(b))
|
RiskTools | https://www.tradingview.com/script/5ycLwXOM-RiskTools/ | smikeyp | https://www.tradingview.com/u/smikeyp/ | 6 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © smikeyp
//@version=5
// @description Provides functions for calculating risk metrics
library("RiskTools", true)
// @function Calculates what is the percentage drop from a reference price
// @param start Starting price before the drop occurred
// @param result Resulting price to which the percentage drop occurred
// @returns Percentage drop from "start" to "result"
export pctDrop(float start, float result) =>
100 * (1 - (result / start))
// @function Calculates a starting price given a resulting price and a percentage drop to that price
// @param pctdrop Percentage drop
// @param result Resulting price to which the percentage drop occurred
// @returns The starting price from which a percentage drop "pctDrop" gave a "result"
export priceBeforeDrop(float pctdrop, float result) =>
result / (1 - pctdrop/100)
// @function Calculates drop zone as an integer representing some multiple of the "zoning size"
// @param price The current price from which you want to calculate the drop zone
// @param masource The source series used in the SMA calculation from which the floor price is determined
// @param malength_days The length (in days) used in the SMA calculation from which the floor price is determined
// @param window_days The lookback period (in days) from which to calculate the floor price
// @param zonesize The increment by which each new zone is larger than the next
// @param minuszone The zone number to use if price is below the floor price. If ommitted it defaults to zero (0)
// @param firstzone The first valid zone number. If ommitted it defaults to the first zonesize increment
// @param lastzone The last zone number where price is above the final zone.
// @returns The zone identifier as a multiple of the zone size in string format
export dropzone(float price, float masource=close, simple int malength_days=50, simple int window_days=800, simple int zonesize=20, simple int minuszone=0, simple int firstzone=0, simple int lastzone=80, simple int overzone=80) =>
_timemult = 86400 / timeframe.in_seconds(timeframe.period)
var float[] _afloorWindow = array.new_float()
if array.size(_afloorWindow) >= int(_timemult*window_days)
array.pop(_afloorWindow)
array.unshift(_afloorWindow, ta.sma(masource, int(_timemult*malength_days)))
_floor = array.min(_afloorWindow)
_dropDistance = pctDrop(start=price, result=_floor)
_zone = _dropDistance == 0 ? zonesize : math.ceil(_dropDistance/zonesize)*zonesize
_zone := switch
firstzone >=0 and _dropDistance <= 0 => minuszone
firstzone >=0 and _zone < firstzone => firstzone
overzone >0 and _zone > lastzone => lastzone
=> _zone
str.tostring(_zone)
|
TradeTrackerv2 | https://www.tradingview.com/script/kbj90boB-TradeTrackerv2/ | pauls0101 | https://www.tradingview.com/u/pauls0101/ | 15 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © pauls0101
//@version=5
// @description TODO: add library description here
library("TradeTrackerv2")
export type Trade
int id = na
bool isOpen = false
bool isClosed = false // only true when it's been closed by hitting TP/SL
bool isBuy = false
float priceOpen = na
float priceTp = na
float priceSl = na
float rTP = na // take profit in R instead of absolute price; will be calculated
float profit = na
float r = na // the calculated R
float resultR = na // profit in R
line lineOpen = na
line lineTp = na
line lineSl = na
label labelStats = na
export method MakeTradeLines(Trade t, int barIdx) =>
// open line
line.new(chart.point.from_index(barIdx, t.priceOpen), chart.point.from_index(barIdx + 1, t.priceOpen), xloc = xloc.bar_index, extend = extend.right, color = color.new(color.aqua, 50), style = line.style_dotted, width = 1)
// sl line
line.new(chart.point.from_index(barIdx, t.priceSl), chart.point.from_index(barIdx + 1, t.priceSl), xloc = xloc.bar_index, extend = extend.right, color = color.new(color.red, 50), style = line.style_dotted, width = 1)
// tp line
line.new(chart.point.from_index(barIdx, t.priceTp), chart.point.from_index(barIdx + 1, t.priceTp), xloc = xloc.bar_index, extend = extend.right, color = color.new(color.blue, 50), style = line.style_dotted, width = 1)
export method UpdateLabel(Trade t) =>
t.labelStats.set_color(color.new(color.black, 0))
t.labelStats.set_tooltip(str.tostring(t.profit, "#.##") + " (" + str.tostring(t.resultR, "#.#") + "R)")
t.labelStats.set_text(t.profit > 0 ? "+" : "-")
export method MakeLabel(Trade t, int barIdx) =>
if t.isBuy
t.labelStats := label.new(chart.point.from_index(barIdx, t.priceSl), "", xloc = xloc.bar_index, yloc = yloc.belowbar, color = color.new(color.black, 0), textcolor = color.new(color.white, 0), style = label.style_label_up)
else
t.labelStats := label.new(chart.point.from_index(barIdx, t.priceSl), "", xloc = xloc.bar_index, yloc = yloc.abovebar, color = color.new(color.black, 0), textcolor = color.new(color.white, 0), style = label.style_label_down)
export method CloseTrade(Trade t) =>
t.lineOpen.delete()
t.lineSl.delete()
t.lineTp.delete()
t.isOpen := false
t.isClosed := true
export method OpenTrade(Trade t) =>
t.isOpen := true
export method OpenCloseTrade(Trade t, float _close) =>
// see if our trades need to open or close
if not t.isOpen
if (_close < t.priceOpen and t.isBuy) or (_close > t.priceOpen and not t.isBuy)
// open trade
t.OpenTrade()
else
// it's open, see if it should close on SL or TP
// SL or TP
if ((_close < t.priceSl and t.isBuy) or (_close > t.priceSl and not t.isBuy)) or ((_close > t.priceTp and t.isBuy) or (_close < t.priceTp and not t.isBuy))
t.CloseTrade()
// @function Calculates profits/losses for the Trade, given _close price
export method CalculateProfits(Trade t, float _close) =>
if t.isBuy
t.profit := math.max(_close, t.priceSl) - t.priceOpen
else
t.profit := t.priceOpen - math.min(_close, t.priceSl)
t.resultR := t.profit / t.r
export method UpdateTrade(Trade t, float _close) =>
if not t.isClosed
t.OpenCloseTrade(_close)
if t.isOpen
t.CalculateProfits(_close)
t.UpdateLabel()
export method SetInitialValues(Trade t, int barIdx) =>
t.r := math.abs(t.priceOpen - t.priceSl)
t.isBuy := t.priceSl < t.priceOpen
if na(t.priceTp) and not na(t.rTP)
if t.isBuy
t.priceTp := t.priceOpen + (t.r * t.rTP)
else
t.priceTp := t.priceOpen - (t.r * t.rTP)
t.MakeLabel(barIdx)
t.MakeTradeLines(barIdx)
export method UpdateAllTrades(Trade[] trades, float _close) =>
for [index, value] in trades
value.UpdateTrade(_close)
export method TrackTrade(Trade t, int barIdx) =>
t.SetInitialValues(barIdx) |
SimilarityMeasures | https://www.tradingview.com/script/CugEjEJk-SimilarityMeasures/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 28 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Similarity measures are statistical methods used to quantify the distance between different data sets
// or strings. There are various types of similarity measures, including those that compare:
// - data points (SSD, Euclidean, Manhattan, Minkowski, Chebyshev, Correlation, Cosine, Camberra, MAE, MSE, Lorentzian, Intersection, Penrose Shape, Meehl),
// - strings (Edit(Levenshtein), Lee, Hamming, Jaro),
// - probability distributions (Mahalanobis, Fidelity, Bhattacharyya, Hellinger),
// - sets (Kumar Hassebrook, Jaccard, Sorensen, Chi Square).
// ---
// These measures are used in various fields such as data analysis, machine learning, and pattern recognition. They
// help to compare and analyze similarities and differences between different data sets or strings, which
// can be useful for making predictions, classifications, and decisions.
// ---
// References:
// https://en.wikipedia.org/wiki/Similarity_measure
// https://cran.r-project.org/web/packages/SimilarityMeasures/index.html
// https://numerics.mathdotnet.com/Distance
// https://github.com/ngmarchant/comparator
// https://github.com/drostlab/philentropy/blob/7bdefc99f6a7016ad3f90f963d784608edfe74fb/src/distances.h
// https://github.com/scipy/scipy/blob/v1.11.2/scipy/spatial/distance.py
// Encyclopedia of Distances, https://doi.org/10.1007/978-3-662-52844-0
library('SimilarityMeasures')
// <-- 101 Character spaces. -->|
// 3456789 123456789 123456789 123456789 123456789|123456789 123456789 123456789 123456789 123456789|
// | | | | | | | | | | | | | |
//#region 00 Pre loading and module dependencies.
//#region 00.00 Imports:
//#endregion 00.00
//#region 00.01 Constants:
string __MODNAME__ = 'SimilarityMeasures'
var array<string> __ALPHA__ = array.from(' ', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z')
var map<string, int> __AINDEX = map.new<string, int>()
if barstate.isfirst
for [_i, _l] in __ALPHA__
__AINDEX.put(_l, _i)
//#endregion 00.01
//#region 00.02 Helpers:
//#region 00.02.01 () err_valid_size.
// @function Template error function to compare two arrays size and if any is empty.
errif_array_invalid_size (int x, int y, string src_function='') =>
switch
x < 1 => runtime.error(__MODNAME__ + ' -> ' + src_function + '(): invalid array size.')
x != y => runtime.error(__MODNAME__ + ' -> ' + src_function + '(): invalid array size.')
//#endregion 00.02.01
//#region 00.02.02 () alpha_to_index.
alpha_to_index (string s) =>
_tokens = str.split(s, '')
_indexed = array.new<int>(_tokens.size())
for [_i, _char] in _tokens
_indexed.set(_i, __AINDEX.get(_char))
_indexed
//#endregion 00.02.02
//#endregion 00.02
//#endregion 00
//#region 01 Distance between data points:
//#region 01.01 () Sum of Squared difference (SSD).
// @function Sum of squared difference for N dimensions.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Measure of distance that calculates the squared euclidean distance.
export ssd (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'ssd')
float _dist = 0.0
for [_i, _pi] in p
_dist += math.pow(_pi - q.get(_i), 2.0)
_dist
//#endregion 01.01
//#region 01.02 () Euclidean.
// @function Euclidean distance for N dimensions.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Measure of distance that calculates the straight-line (or Euclidean).
export euclidean (array<float> p, array<float> q) =>
math.sqrt(ssd(p, q))
//#endregion 01.02
//#region 01.03 () Manhattan.
// @function Manhattan distance for N dimensions.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Measure of absolute differences between both points.
export manhattan (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'manhatan')
float _dist = 0.0
for [_i, _pi] in p
_dist += math.abs(_pi - q.get(_i))
_dist
//#endregion 01.03
//#region 01.04 () Minkowski.
// @function Minkowsky Distance for N dimensions.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @param p_value `float` P value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
// @returns Measure of similarity in the normed vector space.
export minkowski (array<float> p, array<float> q, float p_value=1.0) =>
errif_array_invalid_size(p.size(), q.size(), 'minkowski')
//sum the vector diference:
float _dist = 0.0
for [_i, _pi] in p
_dist += math.pow(math.abs(_pi - q.get(_i)), p_value)
//root it:
math.pow(_dist, (1.0 / p_value))
//#endregion 01.04
//#region 01.05 () Chebyshev.
// @function Chebyshev distance for N dimensions.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Measure of maximum absolute difference.
export chebyshev (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'chebychev')
float _maxd = 0.0
for [_i, _pi] in p
float _di = math.abs(_pi - q.get(_i))
if _di >= _maxd
_maxd := _di
_maxd
//#endregion 01.05
//#region 01.06 () Correlation.
// @function Correlation distance for N dimensions.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Measure of maximum absolute difference.
export correlation (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'correlation')
float _pmean = p.avg()
float _qmean = q.avg()
float _p_square = 0.0
float _q_square = 0.0
float _top = 0.0
for [_i, _pi] in p
float _pm = math.abs(_pi - _pmean)
float _qm = math.abs(q.get(_i) - _qmean)
_p_square += _pm * _pm
_q_square += _qm * _qm
_top += _pm * _qm
// calculate pearsons correlation:
float _s = _top / math.sqrt(_p_square * _q_square)
// and its dissimilarity:
math.sqrt(2.0 * (1.0 - _s))
//#endregion 01.06
//#region 01.07 () Cosine.
// @function Cosine distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Cosine distance between vectors `p` and `q`.
//
// ---
// https://angiogenesis.dkfz.de/oncoexpress/software/cs_clust/cluster.htm
export cosine (array<float> p, array<float> q) =>
int _n = p.size()
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
float _d1 = 0.0
float _p_square = 0.0
float _q_square = 0.0
for _i = 0 to _n - 1
float _pi = p.get(_i)
float _qi = q.get(_i)
_p_square += math.pow(_pi, 2.0)
_q_square += math.pow(_qi, 2.0)
_d1 += _pi * _qi
float _d2 = math.sqrt(_p_square) * math.sqrt(_q_square)
if _d2 == 0.0
0.0 // division by 0
else
_d1 / _d2
//#endregion 01.07
//#region 01.08 () Camberra.
// @function Camberra distance for N dimensions.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Weighted measure of absolute differences between both points.
export camberra (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'manhatan')
float _dist = 0.0
for [_i, _pi] in p
float _qi = q.get(_i)
_dist += math.abs(_pi - _qi) / (math.abs(_pi) + math.abs(_qi))
_dist
//#endregion 01.08
//#region 01.09 () Mean Absolute Error.
// @function Mean absolute error is a normalized version of the sum of absolute difference (manhattan).
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Mean absolute error of vectors `p` and `q`.
export mae (array<float> p, array<float> q) =>
manhattan(p, q) / p.size()
//#endregion 01.09
//#region 01.10 () Mean Squared Error.
// @function Mean squared error is a normalized version of the sum of squared difference.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Mean squared error of vectors `p` and `q`.
export mse (array<float> p, array<float> q) =>
ssd(p, q) / p.size()
//#endregion 01.10
//#region 01.11 () Lorentzian.
// @function Lorentzian distance between provided vectors.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Lorentzian distance of vectors `p` and `q`.
//
// ---
// https://angiogenesis.dkfz.de/oncoexpress/software/cs_clust/cluster.htm
export lorentzian (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'manhatan')
float _dist = 0.0
for [_i, _pi] in p
float _qi = q.get(_i)
_dist += math.log(1.0 + math.abs(_pi - _qi))
_dist
//#endregion 01.11
//#region 01.12 () Intersection.
// @function Intersection distance between provided vectors.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Intersection distance of vectors `p` and `q`.
//
// ---
// https://angiogenesis.dkfz.de/oncoexpress/software/cs_clust/cluster.htm
export intersection (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'manhatan')
float _smin = 0.0
for [_i, _pi] in p
float _qi = q.get(_i)
_smin += math.min(_pi, _qi)
1.0 - _smin / math.min(p.sum(), q.sum())
//#endregion 01.12
//#region 01.13 () Penrose Shape.
// @function Penrose Shape distance between provided vectors.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Penrose shape distance of vectors `p` and `q`.
//
// ---
// https://angiogenesis.dkfz.de/oncoexpress/software/cs_clust/cluster.htm
export penrose (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'manhatan')
float _dist = 0.0
float _p_mean = p.avg()
float _q_mean = q.avg()
for [_i, _pi] in p
float _qi = q.get(_i)
_dist += math.pow((_pi - _p_mean) - (_qi - _q_mean), 2.0)
math.sqrt(_dist)
//#endregion 01.13
//#region 01.14 () Meehl.
// @function Meehl distance between provided vectors.
// @param p `array<float>` Vector with first numeric distribution.
// @param q `array<float>` Vector with second numeric distribution.
// @returns Meehl distance of vectors `p` and `q`.
//
// ---
// https://angiogenesis.dkfz.de/oncoexpress/software/cs_clust/cluster.htm
export meehl (array<float> p, array<float> q) =>
errif_array_invalid_size(p.size(), q.size(), 'manhatan')
float _dist = 0.0
for _i = 0 to p.size() - 2
_dist += math.pow((p.get(_i) - q.get(_i)) - (p.get(_i + 1) - q.get(_i + 1)), 2.0)
_dist
//#endregion 01.14
//#endregion 01
//#region 02 Distance between Strings:
//#region 02.01 () Edit.
// @function Edit (aka Levenshtein) distance for indexed strings.
// @param x `array<int>` Indexed array.
// @param y `array<int>` Indexed array.
// @returns Number of deletions, insertions, or substitutions required to transform source string into target string.
//
// ---
// generated description:
// The Edit distance is a measure of similarity used to compare two strings. It is defined as the minimum number of
// operations (insertions, deletions, or substitutions) required to transform one string into another. The operations
// are performed on the characters of the strings, and the cost of each operation depends on the specific algorithm
// used.
// The Edit distance is widely used in various applications such as spell checking, text similarity, and machine
// translation. It can also be used for other purposes like finding the closest match between two strings or
// identifying the common prefixes or suffixes between them.
//
// ---
// https://github.com/disha2sinha/Data-Structures-and-Algorithms/blob/master/Dynamic%20Programming/EditDistance.cpp
// https://www.red-gate.com/simple-talk/blogs/string-comparisons-in-sql-edit-distance-and-the-levenshtein-algorithm/
// https://planetcalc.com/1721/
export edit (array<int> x, array<int> y) =>
int _size_x = x.size()
int _size_y = y.size()
_table = matrix.new<int>(_size_x+1, _size_y+1, 0)
for _i = 0 to _size_x
for _j = 0 to _size_y
switch
_i == 0 => _table.set(_i, _j, _j)
_j == 0 => _table.set(_i, _j, _i)
x.get(_i-1) == y.get(_j-1) => _table.set(_i, _j, _table.get(_i-1, _j-1))
=> _table.set(_i, _j, 1 + math.min( _table.get(_i , _j-1),
_table.get(_i-1, _j ),
_table.get(_i-1, _j-1)))
_table.get(_size_x, _size_y)
// TEST 20230822 RS
// if barstate.islastconfirmedhistory
// log.warning('{0}', edit(alpha_to_index('hello'), alpha_to_index('relevant'))) // 6
// log.warning('{0}', edit(alpha_to_index('elephant'), alpha_to_index('relevant'))) // 3
// log.warning('{0}', edit(alpha_to_index('statistics'), alpha_to_index('mathematics'))) // 6
// log.warning('{0}', edit(alpha_to_index('numpy'), alpha_to_index('alexa'))) // 5
//#endregion 02.01
//#region 02.02 () Lee.
//@function Distance between two indexed strings of equal length.
// @param x `array<int>` Indexed array.
// @param y `array<int>` Indexed array.
// @param dsize `int` Dictionary size.
// @returns Distance between two strings by accounting for dictionary size.
//
// ---
// https://www.johndcook.com/blog/2020/03/29/lee-distance-codes-and-music/
export lee (array<int> x, array<int> y, int dsize) =>
int _size = x.size()
errif_array_invalid_size(_size, y.size(), 'lee')
int _sum = 0
for _i = 0 to _size-1
_d = math.abs(x.get(_i) - y.get(_i))
_sum += math.min(_d, dsize - _d)
_sum
// TEST 20230822 RS
// if barstate.islastconfirmedhistory
// log.info('{0}', lee(alpha_to_index('hamming'), alpha_to_index('hanning'), __AINDEX.size())) // 2
// log.info('{0}', lee(alpha_to_index('hamming'), alpha_to_index('farming'), __AINDEX.size())) // 7
//#endregion 02.02
//#region 02.03 () Hamming.
//@function Distance between two indexed strings of equal length.
// @param x `array<int>` Indexed array.
// @param y `array<int>` Indexed array.
// @returns Length of different components on both sequences.
//
// ---
// https://en.wikipedia.org/wiki/Hamming_distance
export hamming (array<int> x, array<int> y) =>
errif_array_invalid_size(x.size(), y.size(), 'hamming')
int _sum = 0
for [_i, _xi] in x
if _xi != y.get(_i)
_sum += 1
_sum
//#endregion 02.03
//#region 02.04 () Jaro.
//@function Distance between two indexed strings.
// @param x `array<int>` Indexed array.
// @param y `array<int>` Indexed array.
// @returns Measure of two strings' similarity: the higher the value, the more similar the strings are.
// The score is normalized such that `0` equates to no similarities and `1` is an exact match.
//
// ---
// https://rosettacode.org/wiki/Jaro_similarity
export jaro (array<int> x, array<int> y) =>
int _size_x = x.size()
int _size_y = y.size()
if _size_x == 0
_size_y == 0 ? 1.0 : 0.0
else
float _matches = 0.0
float _transpositions = 0.0
array<bool> _match_x = array.new<bool>(_size_x, false)
array<bool> _match_y = array.new<bool>(_size_y, false)
int _match_distance = (math.max(_size_x, _size_y) / 2) - 1
for _i = 0 to _size_x-1
int _start = math.max(0, _i - _match_distance)
int _end = math.min(_i + _match_distance, _size_y-1)
for _k = _start to _end
if (not _match_y.get(_k)) and x.get(_i) == y.get(_k)
_match_x.set(_i, true)
_match_y.set(_k, true)
_matches += 1
break
if _matches == 0
0.0
else
int _k = 0
for _i = 0 to _size_x-1
if _match_x.get(_i)
while not _match_y.get(_k)
_k += 1
if x.get(_i) != y.get(_k)
_transpositions += 0.5
_k += 1
((_matches / _size_x) + (_matches / _size_y) + ((_matches - _transpositions) / _matches)) / 3.0
// TEST 20230822 RS
// if barstate.islastconfirmedhistory
// log.info('{0,number,0.000000}', jaro(alpha_to_index('dwayne'), alpha_to_index('duane'))) // 0.822222
// log.info('{0,number,0.000000}', jaro(alpha_to_index('martha'), alpha_to_index('marhta'))) // 0.944444
// log.info('{0,number,0.000000}', jaro(alpha_to_index('dixon'), alpha_to_index('dicksonx'))) // 0.766667
// log.info('{0,number,0.000000}', jaro(alpha_to_index('jellyfish'), alpha_to_index('smellyfish'))) // 0.896296
//#endregion 02.04
//#endregion 02
//#region 03 Distance between probability distributions:
//#region 03.01 () Mahalanobis.
// @function Mahalanobis distance between two vectors with population inverse covariance matrix.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @param VI `matrix<float>` Inverse of the covariance matrix.
// @returns The mahalanobis distance between vectors `p` and `q`.
//
// ---
// https://people.revoledu.com/kardi/tutorial/Similarity/MahalanobisDistance.html
// https://stat.ethz.ch/R-manual/R-devel/library/stats/html/mahalanobis.html
// https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.mahalanobis.html
export mahalanobis (array<float> p, array<float> q, matrix<float> VI) =>
int _n = p.size()
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
_X = matrix.new<float>(_n, 0, na)
_X.add_col(0, p)
_X.add_col(0, q)
float _p_mean = p.avg()
float _q_mean = q.avg()
// reuse _X to hold deltas
for [_i, _pi] in p
_X.set(_i, 0, _pi - q.get(_i))
// product ((delta.T, VI), delta)
_M = matrix.mult(matrix.mult(_X.transpose(), VI), _X) // can be optimized?
for _i = 0 to _M.rows() - 1
for _j = 0 to _M.columns() - 1
_M.set(_i, _j, math.sqrt(_M.get(_i, _j)))
_M // output _M.get(0, 0) instead of matrix?
// math.sqrt(_M.get(0, 0))
// TEST 20230829 RS: Matches scipy output.
// if barstate.islastconfirmedhistory
// iv = matrix.new<float>(0, 3, 0.0)
// iv.add_row(0, array.from(1.0, 0.5, 0.5))
// iv.add_row(1, array.from(0.5, 1.0, 0.5))
// iv.add_row(2, array.from(0.5, 0.5, 1.0))
// // [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
// log.info('{0}', mahalanobis(array.from(1.0, 0.0, 0.0), array.from(0.0, 1.0, 0.0), iv)) // 1.0
// log.info('{0}', mahalanobis(array.from(0.0, 2.0, 0.0), array.from(0.0, 1.0, 0.0), iv)) // 1.0
// log.info('{0}', mahalanobis(array.from(2.0, 0.0, 0.0), array.from(0.0, 1.0, 0.0), iv)) // 1.7320508075688772
//#endregion 03.01
//#region 03.02 () Fidelity (Bhattacharyya Coefficient).
// @function Fidelity distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Bhattacharyya Coefficient between vectors `p` and `q`.
//
// ---
// https://en.wikipedia.org/wiki/Fidelity_of_quantum_states
export fidelity (array<float> p, array<float> q) =>
int _n = p.size()
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
float _d1 = 0.0
for _i = 0 to _n - 1
_d1 += math.sqrt(p.get(_i) * q.get(_i))
_d1
//#endregion 03.02
//#region 03.03 () Bhattacharyya.
// @function Bhattacharyya distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Bhattacharyya distance between vectors `p` and `q`.
//
// ---
// https://en.wikipedia.org/wiki/Bhattacharyya_distance
export bhattacharyya (array<float> p, array<float> q) =>
-math.log(fidelity(p, q))
//TEST -------- RS
// if barstate.islastconfirmedhistory
// p0 = array.from(1.0, 2, 3, 4, 5)
// q0 = array.from(4.0, 5, 6, 7, 8)
// p1 = array.from(0.36, 0.48, 0.16)
// q1 = array.from(0.33, 0.33, 0.33)
// log.info('{0}', bhattacharyya(p0, q0)) //
// log.info('{0}', bhattacharyya(p1, q1)) //
//#endregion 03.03
//#region 03.04 () Hellinger.
// @function Hellinger distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The hellinger distance between vectors `p` and `q`.
//
// ---
// https://en.wikipedia.org/wiki/Hellinger_distance#Discrete_distributions
// https://jamesmccaffrey.wordpress.com/2021/06/07/the-hellinger-distance-between-two-probability-distributions-using-python/
export hellinger (array<float> p, array<float> q) =>
int _n = p.size()
float _1n = 1.0 / _n
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
float _sum = 0.0
for _i = 0 to _n - 1
_sum += math.pow(math.sqrt(p.get(_i)) - math.sqrt(q.get(_i)), 2.0)
// (1.0 / math.sqrt(2.0)) * math.sqrt(_sum)
math.sqrt(_sum) / math.sqrt(2.0)
// math.sqrt(1.0 - fidelity(p, q))
// 2.0 * math.sqrt(1.0 - fidelity(p, q)) // alternative does not match
//TEST 20230829 RS
// if barstate.islastconfirmedhistory
// p0 = array.from(1.0, 2, 3, 4, 5)
// q0 = array.from(4.0, 5, 6, 7, 8)
// p1 = array.from(0.36, 0.48, 0.16) //
// float _13 = 1.0 / 3.0
// q1 = array.from(_13, _13, _13) // 0.150498
// log.info('{0}', hellinger(p0, q0)) //
// log.info('{0,number,0.000000}', hellinger(p1, q1)) //
//#endregion 03.04
//#endregion 03
//#region 04 Distance between sets:
//#region 04.01 () Kumar Hassebrook.
// @function Kumar Hassebrook distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Kumar Hassebrook distance between vectors `p` and `q`.
//
// ---
// https://github.com/drostlab/philentropy/blob/7bdefc99f6a7016ad3f90f963d784608edfe74fb/src/distances.h#L962
export kumar_hassebrook (array<float> p, array<float> q) =>
int _n = p.size()
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
float _d1 = 0.0
float _p_square = 0.0
float _q_square = 0.0
for _i = 0 to _n - 1
float _pi = p.get(_i)
float _qi = q.get(_i)
_p_square += math.pow(_pi, 2.0)
_q_square += math.pow(_qi, 2.0)
_d1 += _pi * _qi
float _d2 = _p_square + _q_square - _d1
if _d2 == 0.0 // division by 0
0.0
else
_d1 / _d2
//#endregion 04.01
//#region 04.02 () Jaccard.
// @function Jaccard distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Jaccard distance between vectors `p` and `q`.
//
// ---
// https://github.com/drostlab/philentropy/blob/7bdefc99f6a7016ad3f90f963d784608edfe74fb/src/distances.h#L1010
export jaccard (array<float> p, array<float> q) =>
1.0 - kumar_hassebrook(p, q)
//#endregion 04.02
//#region 04.03 () Sorensen (Bray Curtis).
// @function Sorensen distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Sorensen distance between vectors `p` and `q`.
//
// ---
// https://people.revoledu.com/kardi/tutorial/Similarity/BrayCurtisDistance.html
export sorensen (array<float> p, array<float> q) =>
int _n = p.size()
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
float _d1 = 0.0
float _d2 = 0.0
for _i = 0 to _n - 1
float _pi = p.get(_i)
float _qi = q.get(_i)
_d1 += math.abs(_pi - _qi)
_d2 += _pi + _qi
if _d2 == 0.0 // division by 0
float(na)
else
_d1 / _d2
//#endregion 04.03
//#region 04.03 () Chi Square.
// @function Chi Square distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Chi Square distance between vectors `p` and `q`.
//
// ---
// https://uw.pressbooks.pub/appliedmultivariatestatistics/chapter/distance-measures/
// https://stats.stackexchange.com/questions/184101/comparing-two-histograms-using-chi-square-distance
// https://www.itl.nist.gov/div898/handbook/eda/section3/eda35f.htm
export chi_square (array<float> p, array<float> q, float eps=1.0e-6) =>
int _n = p.size()
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
float _d = 0.0
for _i = 0 to _n - 1
float _pi = p.get(_i)
float _qi = q.get(_i)
if _qi == 0.0 // division by 0
_d += math.pow(_pi - _qi, 2.0) / eps
else
_d += math.pow(_pi - _qi, 2.0) / _qi
_d
//#endregion 04.03
//#region 04.04 () Kulczynsky.
// @function Kulczynsky distance between provided vectors.
// @param p `array<float>` 1D Vector.
// @param q `array<float>` 1D Vector.
// @returns The Kulczynsky distance between vectors `p` and `q`.
//
// ---
// https://github.com/drostlab/philentropy/blob/7bdefc99f6a7016ad3f90f963d784608edfe74fb/src/distances.h#L398
export kulczynsky (array<float> p, array<float> q, float eps=1.0e-6) =>
int _n = p.size()
if _n != q.size()
runtime.error('Size of vectors `p` `q` do not match!')
float _d1 = 0.0
float _d2 = 0.0
for _i = 0 to _n - 1
float _pi = p.get(_i)
float _qi = q.get(_i)
float _diff = math.abs(_pi - _qi)
float _min_p = _pi <= _qi ? _pi : _qi
_d1 += _diff
if _min_p == 0.0
_d2 += eps
else
_d2 += _min_p
if _d2 == 0.0 // division by 0
float(na)
else
_d1 / _d2
//#endregion 04.04
//#endregion 04
|
utils | https://www.tradingview.com/script/oljlh1MF-utils/ | facejungle | https://www.tradingview.com/u/facejungle/ | 4 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © facejungle
//@version=5
// @description TODO: add library description here
library("utils", true)
pine_ema(src, length) =>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
pine_sma(x, y) =>
sum = 0.0
for i = 0 to y - 1
sum := sum + x[i] / y
sum
pine_rma(src, length) =>
alpha = 1/length
sum = 0.0
sma = pine_sma(src, length)
sum := na(sum[1]) ? sma : alpha * src + (1 - alpha) * nz(sum[1])
pine_wma(x, y) =>
norm = 0.0
sum = 0.0
for i = 0 to y - 1
weight = (y - i) * y
norm := norm + weight
sum := sum + x[i] * weight
sum / norm
pine_hma(src, length) =>
pine_wma(2 * pine_wma(src, length / 2) - pine_wma(src, length), math.round(math.sqrt(length)))
pine_vwma(x, y) =>
pine_sma(x * volume, y) / pine_sma(volume, y)
pine_swma(x) =>
x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6
pine_alma(series, windowsize, offset, sigma) =>
m = math.floor(offset * (windowsize - 1))
s = windowsize / sigma
norm = 0.0
sum = 0.0
for i = 0 to windowsize - 1
weight = math.exp(-1 * math.pow(i - m, 2) / (2 * math.pow(s, 2)))
norm := norm + weight
sum := sum + series[windowsize - i - 1] * weight
sum / norm
pine_dema(src, length) =>
ema = pine_ema(src, length)
2 * ema - pine_ema(ema, length)
pine_tema(src, length) =>
ema = pine_ema(src, length)
3 * (ema - pine_ema(ema, length)) + pine_ema(pine_ema(ema, length), length)
pine_smma(src, length) =>
sum = 0.0
sma = pine_sma(src, length)
na(sum[1]) ? sma : (sum[1] * (length - 1) + src) / length
pine_ssma(src, length) =>
a1 = math.exp(-1.414*3.14159 / length)
b1 = 2*a1*math.cos(1.414*3.14159 / length)
c2 = b1
c3 = (-a1)*a1
c1 = 1 - c2 - c3
sum = 0.0
sum := c1*(src + nz(src[1])) / 2 + c2*nz(sum[1]) + c3*nz(sum[2])
export maCustomseries(float source=close, simple string typeMa="sma", series int length, simple float offset=0.85, simple int sigma=6) =>
switch typeMa
"alma" => pine_alma(source, length, offset, sigma)
"ema" => pine_ema(source, length)
"tema" => pine_dema(source, length)
"dema" => pine_tema(source, length)
"sma" => pine_sma(source, length)
"smma" => pine_smma(source, length)
"ssma" => pine_ssma(source, length)
"rma" => pine_rma(source, length)
"hma" => pine_hma(source, length)
"wma" => pine_wma(source, length)
"vwma" => pine_vwma(source, length)
"swma" => pine_swma(source)
"linreg" => ta.linreg(source, length, sigma)
"median" => ta.median(source, length)
"mom" => ta.mom(source, length)
"high" => ta.highest(source, length)
"low" => ta.lowest(source, length)
"medianHigh" => ta.median(ta.highest(source, length), length)
"medianLow" => ta.median(ta.lowest(source, length), length)
"percentrank" => ta.percentrank(source, length)
=> (ta.highest(length) + ta.lowest(length))/2
export fj_stdev(float src, int length, float mult, string middleType) =>
float basis = maCustomseries(src, middleType, length)
float dev = mult * ta.stdev(src, length)
float dev2 = (mult * ta.stdev(src, length)) * 0.618
float dev3 = (mult * ta.stdev(src, length)) * 1.618
float dev4 = (mult * ta.stdev(src, length)) * 2.618
[basis, basis + dev2, basis + dev, basis + dev3, basis + dev4, basis - dev2, basis - dev, basis - dev3, basis - dev4]
// COUNTERS
export counterEvent(bool enent, bool enent2) =>
int scount = 0
scount := enent and enent2 ? nz(scount[1]) + 1 : 0
export barCrossoverCounter(float signalPrice, float basePrice) =>
bool bcond = signalPrice > basePrice
int bcount = 0
bcount := bcond ? nz(bcount[1]) + 1 : 0
export barCrossunderCounter(float signalPrice, float basePrice) =>
bool scond = signalPrice < basePrice
int scount = 0
scount := scond ? nz(scount[1]) + 1 : 0
export avgOpenPositionPrice() =>
sumOpenPositionPrice = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenPositionPrice += strategy.opentrades.entry_price(tradeNo) * strategy.opentrades.size(tradeNo) / strategy.position_size
result = nz(sumOpenPositionPrice / strategy.opentrades)
// Messages
export okxAlertMsg(string action, string signalToken, string orderType, string orderPriceOffset, string investmentType, string amount) =>
str = '{'
str := str + '"action": "' + action + '", '
str := str + '"instrument": "' + syminfo.ticker + '", '
str := str + '"signalToken": "' + signalToken + '", '
// str := str + '"timestamp": "' + str.format_time(time_close, "yyyy-MM-dd'T'HH:mm:ssZ", "UTC+0") + '", '
str := str + '"timestamp": "{{timenow}}", '
str := str + '"maxLag": "500", '
str := str + '"orderType": "' + orderType + '", '
str := str + '"orderPriceOffset": "' + str.tostring(orderPriceOffset) + '", '
str := str + '"investmentType": "' + investmentType + '", '
str := str + '"amount": "' + str.tostring(amount) + '"'
str := str + '}'
str
export commentTriggerCustomseries(string trigger) =>
switch trigger
'supertrend' => 'SuperTrend change direction'
'bbUpper' => 'price crossing BB upper'
'bbUpper2' => 'price crossing BB upper 2'
'bbUpper3' => 'price crossing BB upper 3'
'bbLower' => 'price crossing BB lower'
'bbLower2' => 'price crossing BB lower 2'
'bbLower3' => 'price crossing BB lower 3'
'maBasis' => 'price crossing MA basis'
'maSignal' => 'price crossing MA signal'
'maCross' => 'MA signal crossing MA basis'
'stop' => 'price crossing stop line'
=> trigger
export commentOrderCustomseries(string reason, string trigger=na, int tradeNo=na, float qty=na) =>
msg = ''
// market entry
if reason == 'enter_long'
msg += '↗️[Entry] Long'
msg += na(tradeNo) == false ? ' #' + str.tostring(tradeNo) : na
msg += na(trigger) == false ? ', ' + commentTriggerCustomseries(trigger) : na
if reason == 'enter_short'
msg += '↘️[Entry] Short'
msg += na(tradeNo) == false ? ' #' + str.tostring(tradeNo) : na
msg += na(trigger) == false ? ', ' + commentTriggerCustomseries(trigger) : na
// take profit
if reason == 'take_long'
msg += '💲[TP] Long'
msg += na(qty) == false ? ' ' + str.tostring(qty, '#.###') + '%': na
msg += na(trigger) == false ? ', ' + commentTriggerCustomseries(trigger) : na
if reason == 'take_short'
msg += '💲[TP] Short'
msg += na(qty) == false ? ' ' + str.tostring(qty, '#.###') + '%': na
msg += na(trigger) == false ? ', ' + commentTriggerCustomseries(trigger) : na
// stop loss
if reason == 'stop_long'
msg += '✖️[SL] Long'
msg += na(trigger) == false ? ', ' + commentTriggerCustomseries(trigger) : na
if reason == 'stop_short'
msg += '✖️[SL] Short'
msg += na(trigger) == false ? ', ' + commentTriggerCustomseries(trigger) : na
result = msg |
CommonTypesMapUtil | https://www.tradingview.com/script/iw1kRatx-CommonTypesMapUtil/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 27 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Common type Container library, for central usage across other reference libraries.
library("CommonTypesMapUtil")
//#region Arrays:
// @type Object containing a array.
// @field v list of values.
export type ArrayBool
array<bool> v
// @type Object containing a array.
// @field v list of values.
export type ArrayBox
array<box> v
// @type Object containing a array.
// @field v list of values.
export type ArrayPoint
array<chart.point> v
// @type Object containing a array.
// @field v list of values.
export type ArrayColor
array<color> v
// @type Object containing a array.
// @field v list of values.
export type ArrayFloat
array<float> v
// @type Object containing a array.
// @field v list of values.
export type ArrayInt
array<int> v
// @type Object containing a array.
// @field v list of values.
export type ArrayLabel
array<label> v
// @type Object containing a array.
// @field v list of values.
export type ArrayLine
array<line> v
// @type Object containing a array.
// @field v list of values.
export type ArrayLinefill
array<linefill> v
// @type Object containing a array.
// @field v list of values.
export type ArrayString
array<string> v
// @type Object containing a array.
// @field v list of values.
export type ArrayTable
array<table> v
//#endregion
//#region Matrices:
// @type Object containing a array.
// @field m Matrix with values.
export type MatrixBool
matrix<bool> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixBox
matrix<box> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixPoint
matrix<chart.point> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixColor
matrix<color> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixFloat
matrix<float> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixInt
matrix<int> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixLabel
matrix<label> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixLine
matrix<line> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixLinefill
matrix<linefill> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixString
matrix<string> m
// @type Object containing a matrix.
// @field m Matrix with values.
export type MatrixTable
matrix<table> m
//#endregion |
Ichimoku Oscillator With Divergences [ChartPrime] | https://www.tradingview.com/script/y3NTW7he-Ichimoku-Oscillator-With-Divergences-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 1,083 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Ichimoku Oscillator [ChartPrime]", max_lines_count = 500, max_labels_count = 500)
source = input.source(close, "Signal Source", group = "Settings")
conversion_periods = input.int(9, "Conversion Line Length", minval = 1, group = "Settings")
base_periods = input.int(26, "Base Line Length", minval = 1, group = "Settings")
lagging_span_periods = input.int(52, "Leading Span B Length", minval = 1, group = "Settings")
displacement = input.int(26, "Lagging Span", minval = 1, group = "Settings")
ma_length = input.int(12, "Moving Average Length", minval = 1, group = "Settings")
smoothing_length = input.int(3, "Smoothing", minval = 1, inline = "signal smoothing", group = "Smoothing")
extra_smoothing = input.bool(true, "", inline = "signal smoothing", tooltip = "Enable for extra smoothing.", group = "Smoothing")
normalize = input.string("Window", "Normalize", ["All", "Window", "Disabled"], group = "Normalization", inline = "Normalize")
window_size = input.int(20, "", minval = 5, tooltip = "When enabled it will scale from 100 to -100. If Normalize is set to 'All' it will take into account the whole series. If its set to 'Window', it use a window of data to normalize.", group = "Normalization", inline = "Normalize")
clamp = input.bool(true, "Clamp to Range", group = "Normalization")
top_band = input.float(2, "Max Bandwidth", minval = 0, step = 0.25, group = "Normalization")
mid_band = input.float(1.5, "Mid Bandwidth", minval = 0, step = 0.25, group = "Normalization")
right = input.int(10, "Divergence Look Right", minval = 0, group = "Divergence")
left = input.int(15, "Divergence Look Left", minval = 0, group = "Divergence")
upper_range = input.int(100, "Maximum Lookback", minval = 0, group = "Divergence")
lower_range = input.int(5, "Minimum Lookback", minval = 0, group = "Divergence")
labels = input.string("Symbol", "Show Labels", ["Disabled", "Symbol", "Text"], group = "Divergence")
enable_regular_bullish = input.bool(true, "Regular Bullish", group = "Divergence", inline = "Bld")
enable_hidden_bullish = input.bool(false, "Hidden Bullish", group = "Divergence", inline = "Bld")
enable_regular_bearish = input.bool(true, "Regular Bearish", group = "Divergence", inline = "Brd")
enable_hidden_bearish = input.bool(false, "Hidden Bearish", group = "Divergence", inline = "Brd")
show_signal = input.bool(true, "Show Signal", group = "Visibility")
show_chikou = input.bool(false, "Show Chikou", group = "Visibility")
show_conversion_base = input.bool(false, "Show Conversion and Base", group = "Visibility")
show_ma = input.bool(false, "Show Moving Average", group = "Visibility")
show_min_max = input.bool(true, "Show Min/Max", group = "Visibility")
show_kumo = input.string("Full", "Show Kumo", ["Full", "Current", "Disabled"], group = "Visibility")
show_kumo_lines = input.bool(false, "Show Kumbo Lines", group = "Visibility")
color_on_conversion = input.bool(true, "Color Signal by Conversion Cross", group = "Color")
signal_color = input.color(#F36B16, "Signal Color", group = "Color", inline = "Signal")
signal_width = input.int(2, "", minval = 1, maxval = 5, group = "Color", inline = "Signal")
kumo_bullish_color = input.color(#22EA70, "Kumo Color", group = "Color", inline = "Kumo")
kumo_bearish_color = input.color(#FF2F1C, "", group = "Color", inline = "Kumo")
kumo_alpha = 100 - input.int(10, "", minval = 0, maxval = 100, group = "Color", inline = "Kumo")
chikou_color = input.color(color.gray, "Chikou Color", group = "Color")
conversion_color = input.color(#79D8E0, "Conversion/Base Color", group = "Color", inline = "CB")
base_color = input.color(#E462B2, "", group = "Color", inline = "CB")
conversion_color_bullish = input.color(#1c7a24, "Bullish CB Color", group = "Color", inline = "SC")
base_color_bullish = input.color(#64a568, "", group = "Color", inline = "SC")
conversion_color_bearish = input.color(#df8c8c, "Bearish CB Color", group = "Color", inline = "BC")
base_color_bearish = input.color(#ff4444, "", group = "Color", inline = "BC")
n_color = input.color(#F2DB2E, "Neutral Color", group = "Color")
cb_alpha = 100 - input.int(10, "", minval = 0, maxval = 100, group = "Color", inline = "CB")
ma_color = input.color(color.rgb(83, 152, 255), "Moving Average Color", group = "Color")
max_color = input.color(#5C9970, "Top Colors", group = "Color", inline = "Top")
high_color = input.color(#32533D, "", group = "Color", inline = "Top")
top_alpha = 100 - input.int(10, "", minval = 0, maxval = 100, group = "Color", inline = "Top")
min_color = input.color(#DD6055, "Bottom Colors", group = "Color", inline = "Bottom")
low_color = input.color(#CF3729, "", group = "Color", inline = "Bottom")
low_alpha = 100 - input.int(10, "", minval = 0, maxval = 100, group = "Color", inline = "Bottom")
text_color = input.color(#111122, "Text Color", group = "Color")
regular_bullish_color = input.color(color.rgb(70, 196, 122), "Bullish Colors", group = "Color", inline = "BD")
hidden_bullish_color = input.color(color.rgb(128, 42, 199), "", group = "Color", inline = "BD")
regular_bearish_color = input.color(color.rgb(248, 46, 46), "Bearish Colors", group = "Color", inline = "bD")
hidden_bearish_color = input.color(color.rgb(49, 118, 245), "", group = "Color", inline = "bD")
in_range(cond, lower_range, upper_range) =>
bars = ta.barssince(cond == true)
lower_range <= bars and bars <= upper_range
divergence(
float source,
int right,
int left,
int upper_range,
int lower_range,
bool enable_regular_bullish,
color regular_bullish_color,
bool enable_hidden_bullish,
color hidden_bullish_color,
bool enable_regular_bearish,
color regular_bearish_color,
bool enable_hidden_bearish,
color hidden_bearish_color,
string labels,
color text_color) =>
repaint = barstate.ishistory or barstate.isconfirmed
pl = na(ta.pivotlow(source, left, right)) ? false : true
ph = na(ta.pivothigh(source, left, right)) ? false : true
source_hl = source[right] > ta.valuewhen(pl, source[right], 1) and in_range(pl[1], lower_range, upper_range)
price_ll = low[right] < ta.valuewhen(pl, low[right], 1)
bullish_condition = enable_regular_bullish and price_ll and source_hl and pl and repaint
oscLL = source[right] < ta.valuewhen(pl, source[right], 1) and in_range(pl[1], lower_range, upper_range)
priceHL = low[right] > ta.valuewhen(pl, low[right], 1)
hidden_bullish_condition = enable_hidden_bullish and priceHL and oscLL and pl and repaint
oscLH = source[right] < ta.valuewhen(ph, source[right], 1) and in_range(ph[1], lower_range, upper_range)
priceHH = high[right] > ta.valuewhen(ph, high[right], 1)
bearish_condition = enable_regular_bearish and priceHH and oscLH and ph and repaint
oscHH = source[right] > ta.valuewhen(ph, source[right], 1) and in_range(ph[1], lower_range, upper_range)
priceLH = high[right] < ta.valuewhen(ph, high[right], 1)
hidden_bearish_condition = enable_hidden_bearish and priceLH and oscHH and ph and repaint
offset = -right
var float current_bullish_value = 0
var int current_bull_idx = 0
var float last_bullish_value = 0
var int last_bullish_idx = 0
var float current_hidden_bullish_value = 0
var int current_hidden_bullish_idx = 0
var float last_hidden_bullish_value = 0
var int last_hidden_bullish_idx = 0
var float current_bearish_value = 0
var int current_bearish_idx = 0
var float last_bearish_value = 0
var int last_bearish_idx = 0
var float current_hidden_bearish_value = 0
var int current_hidden_bearish_idx = 0
var float last_hidden_bearish_idx = 0
var int last_hidden_bearish_value = 0
if pl
last_bullish_value := current_bullish_value
last_bullish_idx := current_bull_idx
current_bullish_value := source[right]
current_bull_idx := bar_index - right
last_hidden_bullish_value := current_hidden_bullish_value
last_hidden_bullish_idx := current_hidden_bullish_idx
current_hidden_bullish_value := source[right]
current_hidden_bullish_idx := bar_index - right
if ph
last_bearish_value := current_bearish_value
last_bearish_idx := current_bearish_idx
current_bearish_value := source[right]
current_bearish_idx := bar_index - right
last_hidden_bearish_idx := current_hidden_bearish_value
last_hidden_bearish_value := current_hidden_bearish_idx
current_hidden_bearish_value := source[right]
current_hidden_bearish_idx := bar_index - right
label_style_bullish = switch labels
"Text" => label.style_label_up
"Symbol" => label.style_triangleup
=> label.style_none
label_style_bearish = switch labels
"Text" => label.style_label_down
"Symbol" => label.style_triangledown
=> label.style_none
size = switch labels
"Text" => size.small
"Symbol" => size.tiny
=> size.auto
source_atr = ta.sma(ta.rma(ta.highest(source, 10) - ta.lowest(source, 10), 50) / (labels == "Text" ? 4 : 1), 10)
if bullish_condition
line.new(last_bullish_idx, last_bullish_value, current_bull_idx, current_bullish_value, width = 2, color = regular_bullish_color)
if labels != "Disabled"
label.new(bar_index - right, source[right] - source_atr, labels == "Text" ? "Bullish" : "", color = regular_bullish_color, textcolor = text_color, style = label_style_bullish, size = size)
if hidden_bullish_condition
line.new(last_hidden_bullish_idx, last_hidden_bullish_value, current_hidden_bullish_idx, current_hidden_bullish_value, width = 2, color = hidden_bullish_color)
if labels != "Disabled"
label.new(bar_index - right, source[right] - source_atr, labels == "Text" ? "Hidden Bullish" : "", color = hidden_bullish_color, textcolor = text_color, style = label_style_bullish, size = size)
if bearish_condition
line.new(last_bearish_idx, last_bearish_value, current_bearish_idx, current_bearish_value, width = 2, color = regular_bearish_color)
if labels != "Disabled"
label.new(bar_index - right, source[right] + source_atr, labels == "Text" ? "Bearish" : "", color = regular_bearish_color, textcolor = text_color, style = label_style_bearish, size = size)
if hidden_bearish_condition
line.new(last_hidden_bearish_value, last_hidden_bearish_idx, current_hidden_bearish_idx, current_hidden_bearish_value, width = 2, color = hidden_bearish_color)
if labels != "Disabled"
label.new(bar_index - right, source[right] + source_atr, labels == "Text" ? "Hidden Bearish" : "", color = hidden_bearish_color, textcolor = text_color, style = label_style_bearish, size = size)
[bullish_condition
, hidden_bullish_condition
, bearish_condition
, hidden_bearish_condition]
min_max(source, min, max, enable, clamp)=>
if enable != "Disabled"
if clamp
(math.max(math.min(1, (source - min)/(max - min)), 0) - 0.5) * 200
else
((source - min)/(max - min) - 0.5) * 200
else
source
donchian(len) => math.avg(ta.lowest(len), ta.highest(len))
// Custom cosh function
cosh(float x) =>
(math.exp(x) + math.exp(-x)) / 2
// Custom acosh function
acosh(float x) =>
x < 1 ? na : math.log(x + math.sqrt(x * x - 1))
// Custom sinh function
sinh(float x) =>
(math.exp(x) - math.exp(-x)) / 2
// Custom asinh function
asinh(float x) =>
math.log(x + math.sqrt(x * x + 1))
// Chebyshev Type I Moving Average
chebyshevI(float src, float len = 8, float ripple = 0.05) =>
a = 0.
b = 0.
c = 0.
chebyshev = 0.
a := cosh(1 / len * acosh(1 / (1 - ripple)))
b := sinh(1 / len * asinh(1 / ripple))
c := (a - b) / (a + b)
chebyshev := (1 - c) * src + c * nz(chebyshev[1])
chebyshev
gaussian(source, bandwidth) =>
math.exp(-math.pow(source / bandwidth, 2) / 2) / math.sqrt(2 * math.pi)
gaussian_kernel(source, size = 64, h = 4, r = 0.5) =>
float weight = 0
float weight_sum = 0
for i = 0 to size
src = source[i]
k = math.pow(i, 2) / (math.pow(h, 2) * r)
w = gaussian(k, r)
weight := weight + src * w
weight_sum := weight_sum + w
weight / weight_sum
smoothing(float source, float length, bool extra)=>
extra
? gaussian_kernel(chebyshevI(source, length, 0.5), 4, 2, 1)
: chebyshevI(source, length, 0.5)
alpha = color.new(color.black, 100)
start = bar_index >= lagging_span_periods + displacement - 1
conversion = donchian(conversion_periods)
base = donchian(base_periods)
kumo_a = smoothing(math.avg(conversion, base), smoothing_length, extra_smoothing)
kumo_b = smoothing(donchian(lagging_span_periods), smoothing_length, extra_smoothing)
kumo_a_offset = kumo_a[displacement - 1]
kumo_b_offset = kumo_b[displacement - 1]
kumo_condition = kumo_a > kumo_b
kumo_offset_condition = kumo_a_offset > kumo_b_offset
kumo_center = math.avg(kumo_a, kumo_b)
kumo_center_offset = kumo_center[displacement - 1]
kumo_a_centered = kumo_a - kumo_center
kumo_b_centered = kumo_b - kumo_center
kumo_a_offset_centered = kumo_a_offset - kumo_center_offset
kumo_b_offset_centered = kumo_b_offset - kumo_center_offset
future_kumo_a = kumo_a - kumo_center_offset
future_kumo_b = kumo_b - kumo_center_offset
chikou = source[displacement + 1]
chikou_centered = smoothing(source - chikou, smoothing_length, extra_smoothing)
conversion_base_condition = conversion > base
conversion_centered = smoothing(conversion - kumo_center_offset, smoothing_length, extra_smoothing)
base_centered = smoothing(base - kumo_center_offset, smoothing_length, extra_smoothing)
signal = smoothing(source - kumo_center_offset, smoothing_length, extra_smoothing)
ma = ta.wma(signal, ma_length)
kumo_color = kumo_condition ? kumo_bullish_color : kumo_bearish_color
kumo_offset_color = kumo_offset_condition ? kumo_bullish_color : kumo_bearish_color
var float dev = 0
if normalize == "All" and not na(kumo_a_offset)
dev := math.sqrt(ta.cum(math.pow(signal, 2)) /ta.cum(1))
else if normalize == "Window"
dev := math.sqrt(math.sum(math.pow(signal, 2), window_size) / (window_size - 1))
else
dev := 0
max_level = dev * top_band
min_level = -dev * top_band
high_level = dev * mid_band
low_level = -dev * mid_band
hline(0)
// Define conditions
bool show_kumo_full = show_kumo == "Current"
bool show_kumo_current = show_kumo == "Full"
// Define the sources and offsets for the plots based on the condition
plot_source_a = show_kumo_full ? kumo_a_offset_centered : show_kumo_current ? kumo_a_centered : na
plot_source_b = show_kumo_full ? kumo_b_offset_centered : show_kumo_current ? kumo_b_centered : na
offset_val = show_kumo_full ? 0 : displacement - 1
color_val = show_kumo_full ? kumo_offset_color : show_kumo_current ? kumo_color : na
normal_plot_source_a = min_max(plot_source_a, min_level[show_kumo_full ? displacement - 1 : 0], max_level[show_kumo_full ? displacement - 1 : 0], normalize[show_kumo_full ? displacement - 1 : 0], clamp)
normal_plot_source_b = min_max(plot_source_b, min_level[show_kumo_full ? displacement - 1 : 0], max_level[show_kumo_full ? displacement - 1 : 0], normalize[show_kumo_full ? displacement - 1 : 0], clamp)
normal_max_level = min_max(max_level, min_level, max_level, normalize, clamp)
normal_high_level = min_max(high_level, min_level, max_level, normalize, clamp)
normal_min_level = min_max(min_level, min_level, max_level, normalize, clamp)
normal_low_level = min_max(low_level, min_level, max_level, normalize, clamp)
normal_conversion_centered = min_max(conversion_centered, min_level, max_level, normalize, clamp)
normal_base_centered = min_max(base_centered, min_level, max_level, normalize, clamp)
normal_chikou_centered = min_max(chikou_centered, min_level, max_level, normalize, clamp)
normal_ma = min_max(ma, min_level, max_level, normalize, clamp)
normal_signal = min_max(signal, min_level, max_level, normalize, clamp)
normal_kumo_a_offset_centered = min_max(kumo_a_offset_centered, min_level[displacement - 1], max_level[displacement - 1], normalize[displacement - 1], clamp)
normal_kumo_b_offset_centered = min_max(kumo_b_offset_centered, min_level[displacement - 1], max_level[displacement - 1], normalize[displacement - 1], clamp)
kumo_max = math.max(normal_kumo_a_offset_centered, normal_kumo_b_offset_centered)
kumo_min = math.min(normal_kumo_a_offset_centered, normal_kumo_b_offset_centered)
conversion_base_max = math.max(normal_conversion_centered, normal_base_centered)
conversion_base_min = math.min(normal_conversion_centered, normal_base_centered)
conversion_base_color =
normal_signal >= kumo_max ?
conversion_base_condition ?
conversion_color_bullish :
base_color_bullish :
normal_signal <= kumo_min ?
conversion_base_condition ?
conversion_color_bearish :
base_color_bearish :
n_color
main_color = color_on_conversion ? conversion_base_color : signal_color
var bounce_flag = 0
bounce_up = false
bounce_down = false
if ta.crossunder(normal_signal, kumo_max) and bounce_flag == 0
bounce_flag := 1
if ta.crossunder(normal_signal, kumo_min) and bounce_flag == 1
bounce_flag := 0
if ta.crossover(normal_signal, kumo_min) and bounce_flag == 0
bounce_flag := -1
if ta.crossover(normal_signal, kumo_min) and bounce_flag == -1
bounce_flag := 0
if ta.crossover(normal_signal, kumo_max) and bounce_flag == 1
bounce_up := true
bounce_flag := 0
if ta.crossunder(normal_signal, kumo_min) and bounce_flag == -1
bounce_down := true
bounce_flag := 0
// Plotting kumo
fill_top_plot = plot(normal_plot_source_a, "Kumo Upper", show_kumo_lines ? kumo_bullish_color : alpha, offset = offset_val)
fill_bottom_plot = plot(normal_plot_source_b, "Kumo Lower", show_kumo_lines ? kumo_bearish_color : alpha, offset = offset_val)
fill(fill_top_plot, fill_bottom_plot, color.new(color_val, kumo_alpha))
max_plot = plot(show_min_max and normalize != "Disabled" ? normal_max_level : na, "Top Range", max_color)
high_plot = plot(show_min_max and normalize != "Disabled" ? normal_high_level : na, "High Range", high_color)
min_plot = plot(show_min_max and normalize != "Disabled" ? normal_min_level : na, "Bottom Range", min_color)
low_plot = plot(show_min_max and normalize != "Disabled" ? normal_low_level : na, "Low Range", low_color)
fill(max_plot, high_plot, color.new(max_color, top_alpha), "Top Fill")
fill(min_plot, low_plot, color.new(min_color, low_alpha), "Bottom Fill")
conversion_plot = plot(show_conversion_base ? normal_conversion_centered : na, "Conversion", conversion_color)
base_plot = plot(show_conversion_base ? normal_base_centered : na, "Base", base_color)
fill(conversion_plot, base_plot, color.new(conversion_base_color, cb_alpha), "Conversion and Base Fill")
plot(show_chikou and start ? normal_chikou_centered : na, "Chikou", chikou_color, 1)
plot(show_ma ? normal_ma : na, "Moving Average", ma_color, 2)
plot(show_signal ? normal_signal : na, "Signal", main_color, signal_width)
[regular_bullish
, hidden_bullish
, regular_bearish
, hidden_bearish] = divergence(
min_max(signal, min_level, max_level, normalize, clamp)
, right
, left
, upper_range
, lower_range
, enable_regular_bullish
, regular_bullish_color
, enable_hidden_bullish
, hidden_bullish_color
, enable_regular_bearish
, regular_bearish_color
, enable_hidden_bearish
, hidden_bearish_color
, labels
, text_color
)
inside_of_cloud = ta.crossover(normal_signal, kumo_min) or ta.crossunder(normal_signal, kumo_max)
up_out_of_cloud = ta.crossover(normal_signal, kumo_max)
down_out_of_cloud = ta.crossunder(normal_signal, kumo_min)
kumo_cross_bullish = ta.crossover(kumo_a, kumo_b)
kumo_cross_bearish = ta.crossunder(kumo_a, kumo_b)
kumo_offset_cross_bullish = ta.crossover(kumo_a_offset, kumo_b_offset)
kumo_offset_cross_bearish = ta.crossunder(kumo_a_offset, kumo_b_offset)
conversion_base_bullish = ta.crossover(normal_conversion_centered, normal_base_centered)
conversion_base_bearish = ta.crossunder(normal_conversion_centered, normal_base_centered)
signal_bullish_conversion_base = ta.crossover(normal_signal, conversion_base_max)
signal_bearish_conversion_base = ta.crossunder(normal_signal, conversion_base_min)
chikou_bullish = ta.crossover(normal_chikou_centered, 0)
chikou_bearish = ta.crossunder(normal_chikou_centered, 0)
signal_over_max = ta.crossover(normal_signal, normal_max_level)
signal_over_high = ta.crossover(normal_signal, normal_high_level)
signal_under_min = ta.crossunder(normal_signal, normal_min_level)
signal_under_low = ta.crossunder(normal_signal, normal_low_level)
chikou_over_max = ta.crossover(normal_chikou_centered, normal_max_level)
chikou_over_high = ta.crossover(normal_chikou_centered, normal_high_level)
chikou_under_min = ta.crossunder(normal_chikou_centered, normal_min_level)
chikou_under_low = ta.crossunder(normal_chikou_centered, normal_low_level)
ma_cross_up = ta.crossover(normal_signal, normal_ma)
ma_cross_down = ta.crossunder(normal_signal, normal_ma)
alertcondition(inside_of_cloud, "Inside Cloud", "The signal line is inside the cloud!")
alertcondition(up_out_of_cloud, "Up Out of Cloud", "The signal line crossed above the cloud!")
alertcondition(down_out_of_cloud, "Down Out of Cloud", "The signal line crossed below the cloud!")
alertcondition(kumo_cross_bullish, "Future Kumo Cross Bullish", "The future Kumo lines have crossed in a bullish manner!")
alertcondition(kumo_cross_bearish, "Future Kumo Cross Bearish", "The future Kumo lines have crossed in a bearish manner!")
alertcondition(kumo_offset_cross_bullish, "Current Kumo Cross Bullish", "The current Kumo lines have crossed in a bullish manner!")
alertcondition(kumo_offset_cross_bearish, "Current Kumo Cross Bearish", "The current Kumo lines have crossed in a bearish manner!")
alertcondition(conversion_base_bullish, "Conversion Base Bullish", "The conversion line crossed above the base line!")
alertcondition(conversion_base_bearish, "Conversion Base Bearish", "The conversion line crossed below the base line!")
alertcondition(signal_bullish_conversion_base, "Signal Bullish on Conversion Base", "The signal line crossed above the maximum of conversion and base lines!")
alertcondition(signal_bearish_conversion_base, "Signal Bearish on Conversion Base", "The signal line crossed below the minimum of conversion and base lines!")
alertcondition(chikou_bullish, "Chikou Bullish", "The Chikou line crossed above zero!")
alertcondition(chikou_bearish, "Chikou Bearish", "The Chikou line crossed below zero!")
alertcondition(signal_over_max, "Signal Over Max", "The signal line crossed above the max level!")
alertcondition(signal_over_high, "Signal Over High", "The signal line crossed above the high level!")
alertcondition(signal_under_min, "Signal Under Min", "The signal line crossed below the min level!")
alertcondition(signal_under_low, "Signal Under Low", "The signal line crossed below the low level!")
alertcondition(chikou_over_max, "Chikou Over Max", "The Chikou line crossed above the max level!")
alertcondition(chikou_over_high, "Chikou Over High", "The Chikou line crossed above the high level!")
alertcondition(chikou_under_min, "Chikou Under Min", "The Chikou line crossed below the min level!")
alertcondition(chikou_under_low, "Chikou Under Low", "The Chikou line crossed below the low level!")
alertcondition(ma_cross_up, "Signal Crossover MA", "The signal line crossed over the moving average!")
alertcondition(ma_cross_down, "Signal Crossunder MA", "The signal line crossed under the moving average!")
alertcondition(regular_bullish, "Regular Bullish Divergence", "Regular bullish divergence detected!")
alertcondition(hidden_bullish, "Hidden Bullish Divergence", "Hidden bullish divergence detected!")
alertcondition(regular_bearish, "Regular Bearish Divergence", "Regular bearish divergence detected!")
alertcondition(hidden_bearish, "Hidden Bearish Divergence", "Hidden bearish divergence detected!")
alertcondition(bounce_up, "Bounce off of Kumo Up", "Bullish Bounce off of Kumo!")
alertcondition(bounce_down, "Bounce off of Kumo Down", "Bearish Bounce off of Kumo!") |
Liquidity Hunter [ChartPrime] | https://www.tradingview.com/script/E9z8Isgd-Liquidity-Hunter-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 869 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Liquidity Hunter [ChartPrime]",shorttitle = "Liquidity Hunter [ChartPrime]" ,overlay = true,max_lines_count = 500,max_labels_count = 500,max_bars_back = 500,max_boxes_count = 500)
string CORE = "➞ Core Settings 🔸"
var bool TradeisON = false
var bool ChochisON = false
var bool BOSisON = false
var int LongIndex = na
var float LongLow = low
var int ChoIndex = bar_index
var int Bosindex = bar_index
var float TP = 0.0
var float CHOCH = 0.0
var float BOS = 0.0
var float SL = 0.0
var line TPline = na
var line Choch = na
var label LAB = na
float body = input.float(30,"Body %",step = 0.1,maxval = 100,group = CORE ,inline = "001",tooltip = "Body Value will be lower than this ")
float Wick = input.float(60,"Wick %",step = 0.1,maxval = 100,group = CORE ,inline = "002",tooltip = "Wick Value will be higher than this ")
bool ShowTargets = input.bool(true,"Show Targets",group = CORE ,inline = "003")
float RR = input.float(1.5,"Target ",step = 0.1 , tooltip = "RR Target Multiplyer ",group = CORE)
atrPercent = (ta.atr(5)/close) * 100
method _Band(int len)=>
math.min(ta.atr(len) * 0.3, close * (0.3/100)) [20] /2
LowerWickRange() =>
math.min(open[1], close[1]) - low[1]
BodyPercantage() =>
math.abs(open[1] - close[1]) / math.abs(high[1] - low[1]) * 100
WickPercantage(data) =>
data / math.abs(high[1] - low[1]) * 100
plot(WickPercantage(LowerWickRange()), color=color.rgb(78, 255, 43), title="LOWER WICK % ",display = display.data_window)
plot(BodyPercantage(), color=color.rgb(64, 226, 251), title="Body % of the Bar",display = display.data_window)
LONGCondition()=>
var float Slope = 0
var int TIME = 1
var int LTIME = 1
TIME := time[5]
LTIME := TIME[1]
Slope := (close[1] - close[2]) / (TIME - LTIME)
CON = BodyPercantage() <= body and WickPercantage(LowerWickRange()) >= Wick and (Slope * time > 0) and _Band(5) >= _Band(5)[1]//(ta.atr(5) >= ta.atr(5)[1] or ta.atr(5) <= ta.atr(5)[1])
CON
Long = LONGCondition()
x2 = low - ta.rma(ta.tr(true), 14) * 1.5
longDiffSL = math.abs(close - x2)
Zband = _Band(30)
if true
if Long and (not TradeisON)
LongIndex:= bar_index
LongLow:= low
TP:= close + (RR * longDiffSL)
CHOCH:= close + (RR/2 * longDiffSL)
SL:= close - longDiffSL
BOS:= low - (Zband *15)
Message = str.tostring(math.round(WickPercantage(LowerWickRange()),2))+" %"
Message+= ""
box.new(
bar_index-1,
high + (Zband *0.5),
bar_index+1,
low - (Zband *0.5),
border_color= color.new(#bdf71d, 50),
bgcolor=color.new(#bdf71d,80)
)
box.new(
bar_index-2,
low - (Zband *0.5),
bar_index+2,
low - (Zband *2.5),
border_color= color.new(#bdf71d, 50),
bgcolor=color.new(#bdf71d,80),
text = Message,
text_color = color.white,
text_size = size.auto
)
if ShowTargets
line.new(
bar_index,
high,
bar_index,
TP,
width=2,
color = #047b88,
style= line.style_dashed
)
TPline:= line.new(
bar_index,
TP,
bar_index+2,
TP,
style= line.style_dashed,
color = #047b88
)
LAB:=label.new(
bar_index,
TP,
"Target",
color = color.rgb(102, 102, 100),
style= label.style_label_left,
size=size.small,
textcolor = color.white
)
TradeisON:= true
ChochisON:= false
BOSisON:= false
if TradeisON
line.set_x2(TPline,bar_index)
label.set_x(LAB,bar_index+1)
// lets draw the CHOCH
if close >= CHOCH and not (ChochisON)
ChoIndex:= bar_index
line.new(LongIndex,
CHOCH,
ChoIndex,
CHOCH,
width=1,
color =#185d04,
style= line.style_dashed)
label.new(math.floor((LongIndex+ChoIndex)/2),
CHOCH + (Zband*1.1),
"CHOCH",
style = label.style_label_center,
color = color.new(color.black,100),
textcolor = color.white,
size = size.small)
ChochisON:=true
// lets draw the BOS
if close <= BOS and not (BOSisON)
Bosindex:= bar_index
line.new(LongIndex,
BOS,
Bosindex,
BOS,
width=1,
color = #890303,
style= line.style_dashed)
label.new(math.floor((LongIndex+Bosindex)/2),
BOS - (Zband*1.1),
"BOS",
style = label.style_label_center,
color = color.new(color.black,100),
textcolor = color.white,
size = size.small)
line.new(LongIndex,
LongLow - (Zband *2.5),
LongIndex,
BOS,
width=1,
color = #890303,
style= line.style_dashed)
BOSisON:= true
if high >= TP
label.set_color(LAB,color.rgb(6, 128, 10, 37))
TradeisON:=false
if close <= SL
label.set_color(LAB,color.new(color.rgb(246, 7, 7),70))
TradeisON:=false
barcolor(TradeisON ? color.rgb(6, 249, 71) : na) |
Machine Learning: VWAP [YinYangAlgorithms] | https://www.tradingview.com/script/vhEiWwdk-Machine-Learning-VWAP-YinYangAlgorithms/ | YinYangAlgorithms | https://www.tradingview.com/u/YinYangAlgorithms/ | 260 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// © YinYangAlgorithms
//@version=5
indicator("Machine Learning: VWAP [YinYangAlgorithms]", overlay=true)
// ~~~~~~~~~~~~ INPUTS ~~~~~~~~~~~~ //
//VWAP
vwapType = input.string("Bullish", "VWAP Type", options=["Bullish", "Bearish", "Neutral"], group="VWAP Zones", tooltip="Type of VWAP. You can favor specific direction changes or let it be Neutral where there is even weight to both. Please note, these do not apply to the Machine Learning VWAP.")
src = input.source(ohlc4, "Source", group="VWAP Zones", tooltip="VWAP Source. By default VWAP usually uses HLC3; however OHLC4 may help by providing more data.")
length = input.int(100, "Lookback Length", group="VWAP Zones", tooltip="The Length of this VWAP when it comes to seeing if the current High > Highest of this length; or if the current Low is < Lowest of this length.")
vwmaRegularMult = input.float(2.0, "Standard VWAP Multiplier", group="VWAP Zones", tooltip="This multiplier is applied only to the Standard VWMA. This is when 'Machine Learning Type' is set to 'None'.")
//Machine Learning
useRationalQuadratics = input.bool(true, "Use Rational Quadratics", group="Machine Learning", tooltip="Rationalizing our source may be beneficial for usage within ML calculations.")
showSignals = input.string("High / Low", "Signal Type", group="Machine Learning", options=["High / Low", "Close", "None"], tooltip="Bullish and Bearish Signals are when the price crosses over/under the basis, as well as the Upper and Lower levels. These may act as indicators to where price movement may occur.")
useMachineLearning = input.string("Simple Average", "Machine Learning Type", options=["KNN Average", "KNN Exponential Average", "Simple Average", "None"], group="Machine Learning", tooltip="Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?")
distanceType = input.string("Both", "KNN Distance Type", options=["Both", "Max", "Min"], group="Machine Learning", tooltip="We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.")
mlLength = input.int(10, "Machine Learning Length", group="Machine Learning", tooltip="How far back is our Machine Learning going to keep data for.")
knnLength = input.int(3, "k-Nearest Neighbour (KNN) Length", group="Machine Learning", tooltip="How many k-Nearest Neighbours will we account for?")
fastLength = input.int(1, "Fast ML Data Length", group="Machine Learning", tooltip="What is our Fast ML Length?? This is used with our Slow Length to create our KNN Distance.")
slowLength = input.int(5, "Slow ML Data Length", group="Machine Learning", tooltip="What is our Slow ML Length?? This is used with our Fast Length to create our KNN Distance.")
vwmaMult = input.float(3.236, "ML VWAP Multiplier", group="Machine Learning", tooltip="This multiplier is applied only to the Machine Learning VWMA")
// ~~~~~~~~~~~~ VARIABLES ~~~~~~~~~~~~ //
distanceTypeMin = distanceType == "Min" or distanceType == "Both"
distanceTypeMax = distanceType == "Max" or distanceType == "Both"
// ~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~ //
//@jdehorty Kernel Function
//used to turn a source into a rational quadratic which performs better in ML calculations
rationalQuadratic(series float _src, simple int _lookback, simple float _relativeWeight, simple int startAtBar) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
_size = array.size(array.from(_src))
for i = 0 to _size + startAtBar
y = _src[i]
w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_lookback, 2) * 2 * _relativeWeight))), -_relativeWeight)
_currentWeight += y*w
_cumulativeWeight += w
yhat = _currentWeight / _cumulativeWeight
yhat
//Get the exponential average of an array, where the exponential weight is focused on the first value of this array (current source)
getExponentialDataAverage(_data, _length) =>
avg = 0.
maxLen = math.min(_data.size(), _length)
if maxLen > 0
for i = 0 to maxLen - 1
curData = _data.get(i)
tempAvg = curData
if i > 0
for a = 0 to i
tempAvg += array.get(_data, a)
tempAvg := math.avg(_data.get(0), tempAvg / i)
avg += math.avg(_data.get(0), math.avg(curData, tempAvg))
avg / _length
else
avg
//Uses KNN to sort distances with our ML fast and slow data
//This is a modified version that sorts distances but rather than saving and outputting the distance average it outputs the mean of the valid distance and averages the total
knnAverage_fromDistance(_dataFast, _dataSlow, _minDist, _maxDist) =>
//failsafe we need at least 1 distance
maxDist = not _minDist ? true : _maxDist
//Calculate the distance between slow and fast moving ML Data
distances = array.new_float(0)
for i = 0 to _dataSlow.size() - 1
distance = _dataSlow.get(i) - _dataFast.get(i)
distances.push(distance)
//clone the array so it doesn't modify it
clonedDistances = distances.copy()
//slice the length from the array and calculate the max value from this slice
splicedDistances = clonedDistances.slice(0, math.min(knnLength, clonedDistances.size()))
maxDistanceAllowed = splicedDistances.max()
minDistanceAllowed = splicedDistances.min()
//scan all distances and add any that are less than max distance
validDistances = array.new_float(0)
for i = 0 to distances.size() - 1
if (not maxDist or distances.get(i) <= maxDistanceAllowed) and (not _minDist or distances.get(i) >= minDistanceAllowed)
distAvg = (_dataSlow.get(i) + _dataFast.get(i)) / 2
validDistances.push(distAvg)
// Get exponential or regular average
if useMachineLearning == "KNN Exponential Average"
getExponentialDataAverage(validDistances, 1)
else
validDistances.avg()
// ~~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~~ //
//variable to save starting position of VWAPs
float start = na
// changeVwap = high > ta.highest(length)[1] or close < start[1]// or
changeVwap = low < ta.lowest(length)[1] or close < start[1]// or high > ta.highest(length)[1]
// changeVwap = low < ta.lowest(length)[1] or high > ta.highest(length)[1]//close < start[1]// or high > ta.highest(length)[1]
changeVwapBear = high > ta.highest(length)[1] or close > start[1]
//Calculate Bullish and Bearish VWAP
[basis, upper, lower] = ta.vwap(src, changeVwap, vwmaRegularMult)
[basisBear, upperBear, lowerBear] = ta.vwap(src, changeVwapBear, vwmaRegularMult)
//Calculate start based on the VWAP Type
if vwapType == "Bullish"
start := changeVwap or changeVwapBear ? basis : start[1]
else if vwapType == "Bearish"
start := changeVwap or changeVwapBear ? basisBear : start[1]
else
start := changeVwap ? basis : changeVwapBear ? basisBear : start[1]
//Define if Bearish or Bullish on this VWAP Change
isBear = start < start[1]
//Define Machine Learning VWAP Anchor Variable
bool basisChange = false
//This is used for all forms of Machine Learning, it is used to check if the ML VWAP anchor has changed
if useMachineLearning != "None"
//potentially rationalize our source
if useRationalQuadratics
src := rationalQuadratic(src, 8, 8., 25)
//define our storage arrays for ML
basisData = array.new_float(0)
upperData = array.new_float(0)
lowerData = array.new_float(0)
mlStart = array.new_float(mlLength)
//Calculate VWAPS with a length of ML
for i = 0 to mlLength - 1
//check for ml change
mlChange_bull = low[i] < ta.lowest(length + i)[1]
mlChange_bear = high[i] > ta.highest(length + i)[1]
//calculate vwap if there has been change
[ml_basis_bull, ml_upper_bull, ml_lower_bull] = ta.vwap(src[i], mlChange_bull, vwmaMult)
[ml_basis_bear, ml_upper_bear, ml_lower_bear] = ta.vwap(src[i], mlChange_bear, vwmaMult)
//update start
float mlStartTemp = na
if vwapType == "Bullish"
mlStartTemp := mlChange_bull or mlChange_bear ? ml_basis_bull : mlStart.get(i)[1]
else if vwapType == "Bearish"
mlStartTemp := mlChange_bull or mlChange_bear ? ml_basis_bear : mlStart.get(i)[1]
else
mlStartTemp := mlChange_bull ? ml_basis_bull : mlChange_bear ? ml_basis_bear : mlStart.get(i)[1]
mlStart.set(i, mlStartTemp)
//check if it is bullish or bearish
mlIsBear = mlStart.get(i) < mlStart.get(i)[1]
//populate ml data based on bullish/bearish direction
basisData.push(mlIsBear ? ml_basis_bear : ml_basis_bull)
upperData.push(mlIsBear ? ml_upper_bear : ml_upper_bull)
lowerData.push(mlIsBear ? ml_lower_bear : ml_lower_bull)
//create the locations based on the average
basis := basisData.avg()
upper := upperData.avg()
lower := lowerData.avg()
//check if the basis has changed (the VWAP anchor)
basisChange := basis != basis[1] or not na(basis)
//Calculate the ML VWAP
[mlBasis, mlUpper, mlLower] = ta.vwap(src, basisChange, vwmaMult)
//Use our previous Simple ML VWAP and convert it into a KNN or KNN Exponential VWAP
if useMachineLearning == "KNN Average" or useMachineLearning == "KNN Exponential Average"
// -- A still simple but more complex approach to Machine Learning using KNN to sort validDistances
//Calculate our fast and slow MA's based on the current Simple Average ML data
float vwapFast_basis = ta.sma(mlBasis, fastLength)
float vwapSlow_basis = ta.sma(mlBasis, slowLength)
float vwapFast_upper = ta.sma(mlUpper, fastLength)
float vwapSlow_upper = ta.sma(mlUpper, slowLength)
float vwapFast_lower = ta.sma(mlLower, fastLength)
float vwapSlow_lower = ta.sma(mlLower, slowLength)
//create storage data for ML lookbacks
vwapFastData_basis = array.new_float(mlLength)
vwapSlowData_basis = array.new_float(mlLength)
vwapFastData_upper = array.new_float(mlLength)
vwapSlowData_upper = array.new_float(mlLength)
vwapFastData_lower = array.new_float(mlLength)
vwapSlowData_lower = array.new_float(mlLength)
//populate our ML storage with lookbacks at our Fast and Slow vwapSlow_lower
for i = 0 to mlLength - 1
vwapFastData_basis.set(i, vwapFast_basis[i])
vwapSlowData_basis.set(i, vwapSlow_basis[i])
vwapFastData_upper.set(i, vwapFast_upper[i])
vwapSlowData_upper.set(i, vwapSlow_upper[i])
vwapFastData_lower.set(i, vwapFast_lower[i])
vwapSlowData_lower.set(i, vwapSlow_lower[i])
//calculate our new ML VWAP using KNN by using distances within KNN min/max and filtering by direction
mlBasis := knnAverage_fromDistance(vwapFastData_basis, vwapSlowData_basis, distanceTypeMin, distanceTypeMax)
mlUpper := knnAverage_fromDistance(vwapFastData_upper, vwapSlowData_upper, distanceTypeMin, distanceTypeMax)
mlLower := knnAverage_fromDistance(vwapFastData_lower, vwapSlowData_lower, distanceTypeMin, distanceTypeMax)
//calculate VWAP color
vwapColor = (useMachineLearning != "None" and mlBasis > mlBasis[1]) or (not isBear and useMachineLearning == "None") ? color.green : color.red
//calculate our Bull and Bear signals
basis_bullSignal = showSignals == "High / Low" ? ta.crossover(low, mlBasis) : ta.crossover(close, mlBasis)
basis_bearSignal = showSignals == "High / Low" ? ta.crossunder(high, mlBasis) : ta.crossunder(close, mlBasis)
upper_bearSignal = showSignals == "High / Low" ? ta.crossunder(high, mlUpper) : ta.crossunder(close, mlUpper)
lower_bullSignal = showSignals == "High / Low" ? ta.crossover(low, mlLower) : ta.crossover(close, mlLower)
// ~~~~~~~~~~~~ PLOTS ~~~~~~~~~~~~ //
//Plot Bull and Bear signals
plotshape(showSignals != "None" and basis_bullSignal, title="Basis Bull", color=color.green, style=shape.triangleup, location=location.belowbar, size=size.tiny)
plotshape(showSignals != "None" and lower_bullSignal, title="Lower Bull", color=color.green, style=shape.triangleup, location=location.belowbar, size=size.tiny)
plotshape(showSignals != "None" and basis_bearSignal, title="Basis Bear", color=color.red, style=shape.triangledown, location=location.abovebar, size=size.tiny)
plotshape(showSignals != "None" and upper_bearSignal, title="Upper Bear", color=color.red, style=shape.triangledown, location=location.abovebar, size=size.tiny)
//Plot Machine Learning VWAP
plot(useMachineLearning != "None" ? mlBasis : na, "Basis", color=#FF6D00)
p1 = plot(useMachineLearning != "None" ? mlUpper : na, "Upper", color=vwapColor)
p2 = plot(useMachineLearning != "None" ? mlLower : na, "Lower", color=vwapColor)
fill(p1, p2, title = "Background", color=color.new(vwapColor, 97))
//Plot regular VWAP based on if it is Bullish or Bearish
plot(useMachineLearning == "None" ? isBear ? basisBear : basis : na, "Basis", color=#FF6D00)
p3 = plot(useMachineLearning == "None" ? isBear ? upperBear : upper : na, "Upper", color=vwapColor)
p4 = plot(useMachineLearning == "None" ? isBear ? lowerBear : lower : na, "Lower", color=vwapColor)
fill(p3, p4, title = "Background", color=color.new(vwapColor, 97))
// ~~~~~~~~~~~~ ALERTS ~~~~~~~~~~~~ //
//alerts based on Bull and Bear cross'
alertcondition(basis_bullSignal, title="Basis Bull Signal", message="Basis Bull Signal")
alertcondition(lower_bullSignal, title="Lower Bull Signal", message="Lower Bull Signal")
alertcondition(basis_bearSignal, title="Basis Bear Signal", message="Basis Bear Signal")
alertcondition(upper_bearSignal, title="Upper Bear Signal", message="Upper Bear Signal")
// ~~~~~~~~~~~~ END ~~~~~~~~~~~~ // |
Market Structure [TFO] | https://www.tradingview.com/script/DBH1Alls-Market-Structure-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,146 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeforopp
//@version=5
indicator("Market Structure [TFO]", "Market Structure [TFO]", true, max_labels_count = 500, max_lines_count = 500)
pivot_strength = input.int(3, "Pivot Strength", 1)
show_pivots = input.bool(false, "Show Pivots", inline = "PIV")
highs = input.color(color.blue, "", inline = "PIV")
lows = input.color(#f23645, "", inline = "PIV")
show_bos = input.bool(false, "Show BOS/MSS")
style = input.string("Dashed", "Line Style", options = ['Solid', 'Dashed', 'Dotted'])
type swing
int _index = na
float _val = na
method set_val(swing s, int i, float v) =>
s._index := i
s._val := v
method set_na(swing s) =>
s._index := na
s._val := na
var swing_high = swing.new()
var swing_low = swing.new()
var temp_hi = swing.new()
var temp_lo = swing.new()
var bool bull = na
sh = false
sl = false
bull_bos = false
bull_mss = false
bear_bos = false
bear_mss = false
var line_style = switch style
"Solid" => line.style_solid
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
if not na(ta.pivothigh(high, pivot_strength, pivot_strength))
swing_high.set_val(bar_index - pivot_strength, high[pivot_strength])
sh := true
if not na(ta.pivotlow(low, pivot_strength, pivot_strength))
swing_low.set_val(bar_index - pivot_strength, low[pivot_strength])
sl := true
if not na(swing_high._val)
if close > swing_high._val
mss = (bull == false or na(bull))
if mss
bull_mss := true
temp_hi.set_val(swing_high._index, swing_high._val)
else
bull_bos := true
temp_hi.set_val(swing_high._index, swing_high._val)
bull := true
swing_high.set_na()
if not na(swing_low._val)
if close < swing_low._val
mss = (bull == true or na(bull))
if mss
bear_mss := true
temp_lo.set_val(swing_low._index, swing_low._val)
else
bear_bos := true
temp_lo.set_val(swing_low._index, swing_low._val)
bull := false
swing_low.set_na()
if show_bos
if bull_mss[1] or bull_bos[1]
line.new(temp_hi._index, temp_hi._val, bar_index - 1, temp_hi._val, style = line_style, color = highs)
label.new(math.floor(math.avg(temp_hi._index, bar_index - 1)), temp_hi._val, bull_mss[1] ? "MSS" : "BOS", textcolor = highs, color = #ffffff00, style = label.style_label_down)
if bear_mss[1] or bear_bos[1]
line.new(temp_lo._index, temp_lo._val, bar_index - 1, temp_lo._val, style = line_style, color = lows)
label.new(math.floor(math.avg(temp_lo._index, bar_index - 1)), temp_lo._val, bear_mss[1] ? "MSS" : "BOS", textcolor = lows, color = #ffffff00, style = label.style_label_up)
plotshape(show_pivots and sh, style = shape.triangledown, location = location.abovebar, color = highs, offset = -pivot_strength, size = size.tiny)
plotshape(show_pivots and sl, style = shape.triangleup, location = location.belowbar, color = lows, offset = -pivot_strength, size = size.tiny)
any_mss = bull_mss or bear_mss
any_bos = bull_bos or bear_bos
alertcondition(any_mss[1], "Any MSS")
alertcondition(any_bos[1], "Any BOS")
alertcondition(bull_mss[1], "Bull MSS")
alertcondition(bull_bos[1], "Bull BOS")
alertcondition(bear_mss[1], "Bear MSS")
alertcondition(bear_bos[1], "Bear BOS") |
Zig-Zag Volume Profile (Bull vs. Bear) [Kioseff Trading] | https://www.tradingview.com/script/L2LxYayS-Zig-Zag-Volume-Profile-Bull-vs-Bear-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 422 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Zig-Zag Volume Profile [Kioseff Trading]", max_lines_count = 500, max_labels_count = 500, overlay= true, max_polylines_count = 100, max_boxes_count = 500)
import TradingView/ZigZag/6 as ZigZagLib
import RicardoSantos/MathOperator/2
ROWS = input.int (defval = 2000, maxval = 9998, minval = 10, step = 10, title = "Profile Rows", group = "Profile Settings")
factor = input.float (defval = 2.5, minval = 1.1, step = 0.1, title = "Scaling Factor", group = "Profile Settings")
offset = input.int (defval = 1, title = "Offset Placement", minval = 1, group = "Profile Settings")
curve = input.bool (defval = false, title = "Curved Profiles", group = "Profile Settings")
same = input.string(defval = "Middle", title = "VP Plot Type", options = ["Middle", "Same Side", "Opposing Side"], group = "Profile Settings")
upCol = input.color (defval = #14D990, title = "Bull Color", group = "Profile Settings")
dnCol = input.color (defval = #F24968, title = "Bear Color", group = "Profile Settings")
transp = input.int (defval = 90, minval = 0, maxval = 100, group = "Profile Settings", title = "Pofile Fill Transparency")
transp2 = input.int (defval = 0 , minval = 0, maxval = 100, group = "Profile Settings", title = "Pofile Line Transparency")
delta = input.bool (defval = false, title = "Show Delta", group = "Delta Settings")
deltaRows = input.int (defval = 20, minval = 5, title = "Delta Rows", group = "Delta Settings")
deltaSz = input.string(defval = "Tiny", title = "Delta Text Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = "Delta Settings")
poc = input.bool (defval = false, title = "Show POC", group = "POC Settings")
delet = input.bool (defval = false, title = "Delete Violated POCs", group = "POC Settings")
poctype = input.string(defval = "Bull & Bear POC", title = "POC Type", options = ["Bull & Bear POC", "Regular POC"], group = "POC Settings")
show = input.int (defval = 20, title = "Historical POCs To Show", maxval = 250, minval = 1, group = "POC Settings")
livepoc = input.bool (defval = false, title = "Live POC Only", group = "POC Settings")
transp3 = input.int (defval = 15, minval = 0, maxval = 100, group = "POC Settings", title = "POC Line Transparency")
generalPOCcol = input.color (defval = color.yellow, title = "Regular POC Col", group = "POC Settings")
showVA = input.bool (defval = false, title = "Show Value Area Lines", group = "Value Area Settings")
vaCumu = input.float (defval = 70, title = "Value Area %", group = "Value Area Settings", minval = 5, maxval = 95) / 100
transp4 = input.int (defval = 66, title = "VA Lines Transparency", group = "Value Area Settings", minval = 0, maxval = 100)
vatype = input.string(defval = "Bull & Bear VA", title = "Value Area Type", group = "Value Area Settings", options = ["Bull & Bear VA", "Regular VA"])
showVAS = input.int (defval = 20, title = "Historical Value Areas To Show", maxval = 250, minval = 1, group = "Value Area Settings")
liveVAS = input.bool (defval = false, title = "Live Value Areas Only", group = "Value Area Settings")
deletv = input.bool (defval = false, title = "Delete Violated VAs", group = "Value Area Settings")
generalVAcol = input.color (defval = color.white, title = "Regular VA Col", group = "Value Area Settings")
N = bar_index
show := switch poctype
"Regular POC" => show + 1
=> show * 2
showVAS := switch vatype
"Regular VA" => showVAS * 2 + 1
=> showVAS * 4 + 1
if curve
ROWS := 60
if same == "Middle"
offset := 0
// Create Zig Zag instance from user settings.
var zigZag = ZigZagLib.newInstance(
ZigZagLib.Settings.new(
input.float(0.00001, "Price deviation for reversals (%)", 0.00001, 100.0, 0.5, "0.00001 - 100", group = "Zig Zag Settings"),
input.int(100, "Pivot legs", 2, group = "Zig Zag Settings"),
input(color.new(color.white,50), "Line color", group = "Zig Zag Settings"),
false, // input(false, "Extend to last bar"),
input(false, "Display reversal price", group = "Zig Zag Settings"),
input(false, "Display cumulative volume", group = "Zig Zag Settings"),
input(false, "Display reversal price change", inline = "priceRev", group = "Zig Zag Settings"),
input.string("Absolute", "", ["Absolute", "Percent"], inline = "priceRev", group = "Zig Zag Settings"),
true)
), atr = ta.atr(14)
zigZag.update()
type dataStore
matrix <float> timeVolMat
matrix <float> HLmat
array <int> retArr
array <box> pocs
matrix <float> tickLevels
array <label> deltaLabels
map <float, float> mappedLevel
array <box> vas
var data = dataStore.new(matrix.new<float>(2, 0), matrix.new<float>(2, 0), array.new_int(), array.new_box(), vas = array.new_box()), //kioseff
tLevels = dataStore.new(tickLevels = matrix.new<float>(3, ROWS, 0.0))
determine( a, b, c) =>
result = switch same
"Opposing Side" => a
"Same Side" => b
"Middle" => c
method double_binary_search_leftmost(array <float> id, i) =>
n = id .binary_search_leftmost (data.HLmat.get(0, i))
n1 = id .binary_search_leftmost (data.HLmat.get(1, i))
[n, n1]
method double_binary_search_leftmost_delta(array <float> id, top, btm) =>
n = id .binary_search_leftmost (top)
n1 = id .binary_search_leftmost (btm)
[n, n1]
method effSwitch(matrix<float> id, i, x, div, subtract) =>
switch data.retArr.get(i)
1 => id.set(1, x, id.get(1, x) + data.timeVolMat.get(1, i - subtract) / div)
-1 => id.set(2, x, id.get(2, x) + data.timeVolMat.get(1, i - subtract) / div)
method keyLevelsCheck(array<box> id, array<float> timeRow, getx2, usePOC) =>
for i = 0 to timeRow.indexof(getx2) - 1
if data.HLmat.get(0, i) >= id.last().get_top() and data.HLmat.get(1, i) <= id.last().get_top()
id.last().set_right(N - i)
if usePOC
if poctype == "Bull & Bear POC"
if data.HLmat.get(0, i) >= id.get(id.size() - 2).get_top() and data.HLmat.get(1, i) <= id.get(id.size() - 2).get_top()
id.get(id.size() - 2).set_right(N - i)
else
if vatype == "Bull & Bear VA"
for x = 2 to 4
if data.HLmat.get(0, i) >= id.get(id.size() - x).get_top() and data.HLmat.get(1, i) <= id.get(id.size() - x).get_top()
id.get(id.size() - x).set_right(N - i)
else
if data.HLmat.get(0, i) >= id.get(id.size() - 2).get_top() and data.HLmat.get(1, i) <= id.get(id.size() - 2).get_top()
id.get(id.size() - 2).set_right(N - i)
method drawPOC(array<box> id, difference, idrow, check, newRowUp, newRowDn, remove, array<float> timeRow = na, int getx2 = na, int getx = na, cond1 = false) =>
if remove
if id.size() > 0
for i = 0 to id.size() - 1
id.shift().delete()
if poc
start = switch
same == "Middle" => cond1 ? math.round(math.avg(last_bar_index, last_bar_index - timeRow.indexof(line.all.last().get_x2()))) :
N - math.round(math.avg(timeRow.indexof(getx), timeRow.indexof(getx2))) + 1
=> difference + offset - 1
if poctype == "Bull & Bear POC"
id.push(box.new(start, idrow.get(newRowUp.indexof(newRowUp.max())), N, idrow.get(newRowUp.indexof(newRowUp.max())) ,
bgcolor = #00000000, border_color = color.new(upCol, transp3)))
id.push(box.new(start, idrow.get(newRowDn.indexof(newRowDn.max())), N, idrow.get(newRowDn.indexof(newRowDn.max())),
bgcolor = #00000000, border_color = color.new(dnCol, transp3)))
else
for i = 0 to newRowUp.size() - 1
newRowUp.set(i, newRowUp.get(i) + newRowDn.get(i))
id.push(box.new(start, idrow.get(newRowUp.indexof(newRowUp.max())), N, idrow.get(newRowUp.indexof(newRowUp.max())) ,
bgcolor = #00000000, border_color = color.new(generalPOCcol, transp3)))
if check
id.keyLevelsCheck(timeRow, getx2, true)
method setLevels(matrix<float> id, float gety, float gety2, cond) =>
rows = math.abs(gety2 - gety) / (ROWS - 1)
start = switch cond
false => math.min(gety, gety2)
=> gety
for i = 0 to ROWS - 1
id.set(0, i, start + rows * i)
method createPoly(matrix<chart.point> id, array<float> timeRow, int add, int getx2, int getx, bool cond, int difference,
array<float> idrow, array<float> lows, array<float> highs) =>
avg = switch cond
false => math.round(math.avg(timeRow.indexof(getx2), timeRow.indexof(getx)))
=> math.round(math.avg(last_bar_index, last_bar_index - timeRow.indexof(line.all.last().get_x2())))
add2 = determine(N - timeRow.indexof(getx2), N - avg, add)
oper = switch cond
false => determine(add2 - offset + 1, add + offset - 1, N - avg + 1)
=> determine(N - offset + 1, difference + offset - 1, avg)
[finx, finDn, finUp] = if same != "Middle"
switch cond
false => [add + offset - 1, idrow.min(), idrow.max()]
=> [difference + offset - 1, lows.min(), highs.max()]
else
switch cond
false => [N - avg + 1, idrow.min(), idrow.max()]
=> [avg, lows.min(), highs.max()]
id.add_col(0,
array.from(chart.point.from_index(finx, finDn) ,chart.point.from_index(oper, finDn)))
id.add_col(id.columns(),
array.from(chart.point.from_index(finx, finUp),chart.point.from_index(oper, finUp)))
polyline.new(id.row(0), fill_color = color.new(upCol, transp), line_color = color.new(upCol, transp2), curved = curve)
polyline.new(id.row(1), fill_color = color.new(dnCol, transp), line_color = color.new(dnCol, transp2), curved = curve)
norm(newRowUp, newRowDn, oldMin, oldMax, newRange, i) =>
calcUp = 1 + ((newRowUp.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
calcDn = 1 + ((newRowDn.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
[calcUp, calcDn]
method calcDelta(array<float> id, array<float> newRowUp, array<float> newRowDn, float getY, float getY2, int middle) =>
if delta
var dsz = switch deltaSz
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
db = dataStore.new(mappedLevel = map.new<float, float>(), deltaLabels = array.new_label())
var lastdb = dataStore.new(deltaLabels = array.new_label())
var liveBox = array.new_box()
if lastdb.deltaLabels.size() > 0
for i = lastdb.deltaLabels.size() - 1 to 0
lastdb.deltaLabels.remove(i).delete()
if liveBox.size() > 0
liveBox.remove(0).delete()
newSlice = (math.max(getY, getY2) - math.min(getY, getY2)) / deltaRows
idx = switch bar_index == last_bar_index
true => lastdb.deltaLabels
=> db.deltaLabels
for i = 0 to deltaRows - 1
db.mappedLevel.put(i, 0.0)
btm = math.min(getY, getY2) + (newSlice * i)
top = math.min(getY, getY2) + (newSlice * (i + 1))
idx.push(label.new(chart.point.from_index(middle, math.avg(top, btm)),
textcolor = color.white, style = label.style_none, color = #00000000, size = dsz))
[topCol, btmCol] = id.double_binary_search_leftmost_delta(top, btm)
for x = btmCol to topCol
db.mappedLevel.put(i, db.mappedLevel.get(i) + (newRowUp.get(x) - newRowDn.get(x)))
valArr = db.mappedLevel.values(), valArr.sort(order.ascending), array <float> pos = na, array <float> neg = na
if valArr.last ().over (0)
pos := valArr.slice( valArr.binary_search_rightmost(0), valArr.size())
if valArr.first().under(0)
neg := valArr.slice(0, valArr.binary_search_leftmost (0))
for i = 0 to deltaRows - 1
col = switch math.sign(db.mappedLevel.get(i))
1 => color.from_gradient(db.mappedLevel.get(i), pos.min(), pos.max(), color.new(upCol, 50), color.new(upCol, 10))
-1 => color.from_gradient(db.mappedLevel.get(i), neg.max(), neg.min(), color.new(dnCol, 10), color.new(dnCol, 50))
=> color.new(color.white, 75)
idx.get(i).set_textcolor (col),
idx.get(i).set_text(str.tostring(db.mappedLevel.get(i), format.volume))
sumCol = switch math.sign(newRowUp.sum() - newRowDn.sum())
1 => upCol
-1 => dnCol
=> color.white
if bar_index < last_bar_index
box.new(chart.point.from_index(middle - 5, math.max(getY, getY2) + atr * 2), chart.point.from_index(middle + 5, math.max(getY, getY2) + atr),
bgcolor = color.new(sumCol, 80),
text_color = color.white,
border_color = sumCol,
text = str.tostring(newRowUp.sum() - newRowDn.sum(), format.volume))
if bar_index == last_bar_index
liveBox.push(box.new(chart.point.from_index(middle - 5, math.max(getY, getY2) + atr * 2), chart.point.from_index(middle + 5, math.max(getY, getY2) + atr),
bgcolor = color.new(sumCol, 80),
text_color = color.white,
border_color = sumCol,
text = str.tostring(newRowUp.sum() - newRowDn.sum(), format.volume)))
method calcVA(array<box> id, id2, newRowUp, newRowDn, getx, getx2, timeRow, check, remove, cond = false) =>
if showVA
if remove
if id.size() > 0
for i = 0 to id.size() - 1
id.shift().delete()
maxU = newRowUp.indexof(newRowUp.max()), bottom = 0, top = 0
maxD = newRowDn.indexof(newRowDn.max()), bottomD = 0, topD = 0
if vatype == "Bull & Bear VA"
for i = 0 to newRowUp.size() - 1
slice = newRowUp.slice(math.max(maxU - i, 0), math.min(maxU + i + 1, newRowUp.size()))
if slice.sum() / newRowUp.sum() >= vaCumu
bottom := math.max(maxU - i, 0)
top := math.min(maxU + i + 1, newRowUp.size() - 1)
break
for i = 0 to newRowDn.size() - 1
slice = newRowDn.slice(math.max(maxD - i, 0), math.min(maxD + i + 1, newRowDn.size()))
if slice.sum() / newRowDn.sum() >= vaCumu
bottomD := math.max(maxD - i, 0)
topD := math.min(maxD + i + 1, newRowDn.size() - 1)
break
if vatype != "Bull & Bear VA"
newValues = array.new_float()
for i = 0 to newRowUp.size() - 1
newValues.push(newRowUp.get(i) + newRowDn.get(i))
max = newValues.indexof(newValues.max())
for i = 0 to newValues.size() - 1
slice = newValues.slice(math.max(max - i, 0), math.min(max + i + 1, newValues.size()))
if slice.sum() / newValues.sum() >= vaCumu
bottom := math.max(max - i, 0)
top := math.min(max + i + 1, newValues.size() - 1)
break
left = if not cond
switch same
"Middle" => math.round(N - math.avg(timeRow.indexof(getx), timeRow.indexof(getx2))) + 1
=> getx
else
switch same
"Middle" => math.round(math.avg(N, N - getx2))
=> N - getx2
if vatype == "Bull & Bear VA"
for i = 0 to 3
[yval, colval] = switch
i == 0 => [bottom , upCol]
i == 1 => [top , upCol]
i == 2 => [bottomD, dnCol]
i == 3 => [topD , dnCol]
id.push(box.new(chart.point.from_index(left, id2.get(yval)), chart.point.from_index(N, id2.get(yval)),
bgcolor = color.new(colval, transp4), border_color = color.new(colval, transp4))),
if vatype != "Bull & Bear VA"
id.push(box.new(chart.point.from_index(left, id2.get(bottom)), chart.point.from_index(N, id2.get(bottom)),
bgcolor = color.new(generalVAcol, transp4), border_color = color.new(generalVAcol, transp4))),
id.push(box.new(chart.point.from_index(left, id2.get(top)), chart.point.from_index(N, id2.get(top)),
bgcolor = color.new(generalVAcol, transp4), border_color = color.new(generalVAcol, transp4))),
if check
data.vas.keyLevelsCheck(timeRow, getx2, false)
id
method setCoordsHistory(matrix<chart.point> id, newRowUp, newRowDn, oldMin, oldMax, newRange, timeRow, getx, getx2, idrow) =>
avg = math.round(math.avg(timeRow.indexof(getx), timeRow.indexof(getx2)))
for i = 0 to newRowUp.size() - 1
[calcUp, calcDn] = norm(newRowUp, newRowDn, oldMin, oldMax, newRange, i)
newSwitchUp = switch same
"Middle" => N - avg + calcUp
=> N - timeRow.indexof(getx) + offset - calcUp
newXUp = switch same
"Middle" => math.min(newSwitchUp, N - avg)
=> math.max(newSwitchUp, N - timeRow.indexof(getx) + offset)
newSwitchDn = determine(N - timeRow.indexof(getx2) - offset + calcDn,
N - timeRow.indexof(getx ) + offset - calcDn,
N - avg - calcDn)
newXDn = determine(math.min(newSwitchDn, N - timeRow.indexof(getx2) - offset),
math.max(newSwitchDn, N - timeRow.indexof(getx ) + offset),
math.max(newSwitchDn, N - avg) + 2)
id.set(0, i, chart.point.from_index(math.round(newXUp), idrow.get(i)))
id.set(1, i, chart.point.from_index(math.round(newXDn), idrow.get(i)))
method setCoordsLive(matrix<chart.point> id, newRowUp, newRowDn, oldMin, oldMax, newRange, difference, newLevelsMat, timeRow) =>
avg = math.round(math.avg(last_bar_index, last_bar_index - timeRow.indexof(line.all.last().get_x2())))
for i = 0 to newRowUp.size() - 1
[calcUp, calcDn] = norm(newRowUp, newRowDn, oldMin, oldMax, newRange, i)
newSwitchUp = switch same
"Middle" => avg - calcUp
=> difference + offset + calcUp - 1
newXUp = switch same
"Middle" => math.min(newSwitchUp, avg - 1)
=> math.max(newSwitchUp, difference + offset)
newSwitchDn = determine( N - offset - calcDn,
difference + offset + calcDn - 1,
avg + calcDn - 1)
newXDn = determine( math.min(newSwitchDn, N - offset - 1),
math.max(newSwitchDn, difference + 1),
math.max(newSwitchDn, avg + 1))
id.add_col(id.columns(), array.from(
chart.point.from_index(math.round(newXUp), newLevelsMat.get(0, i)),
chart.point.from_index(math.round(newXDn), newLevelsMat.get(0, i))))
method update(matrix<float> id) =>
data.timeVolMat.add_col(0, array.from(time, volume))
data.HLmat .add_col(0, array.from(high, low))
data.retArr .unshift(int(math.sign(close - open)))
change = line.all.size() > line.all.size()[1] and line.all.size() > 2
if last_bar_index - N <= 10000
barCond = barstate.islastconfirmedhistory
[minus, minus1] = switch barCond
true => [2, 1]
=> [3, 2]
if change or barCond
all = line.all, allSize = all.size()
getx = all.get(allSize - minus) .get_x2(), gety = all.get(allSize - minus) .get_y2()
getx2 = all.get(allSize - minus1).get_x2(), gety2 = all.get(allSize - minus1).get_y2()
id.setLevels(gety, gety2, false)
timeRow = data.timeVolMat.row(0), idrow = id.row(0)
for i = timeRow.indexof(getx) to timeRow.indexof(getx2)
[l1, l2] = idrow.double_binary_search_leftmost(i)
div = math.abs(l1 - l2) + 1
for x = l1 to l2
id.effSwitch(i, x, div, 0)
newRange = math.floor((timeRow.indexof(getx2) - timeRow.indexof(getx)) / factor)
newRowUp = id.row(1), newRowDn = id.row(2)
oldMin = math.min(newRowUp.min(), newRowDn.min())
oldMax = math.max(newRowUp.max(), newRowDn.max())
coordinates = matrix.new<chart.point>(2, newRowUp.size())
add = N - timeRow.indexof(getx)
coordinates.setCoordsHistory(newRowUp, newRowDn, oldMin, oldMax, newRange, timeRow, getx, getx2, idrow)
coordinates.createPoly(timeRow, add, getx2, getx, false, na, idrow, na, na)
middle = N - math.round(math.avg(timeRow.indexof(getx), timeRow.indexof(getx2))) + 1
idrow.calcDelta(newRowUp, newRowDn, gety, gety2, middle)
if not livepoc
data.pocs .drawPOC(add, idrow, true, newRowUp, newRowDn, false, timeRow, getx2, getx)
if not liveVAS
data.vas.calcVA(idrow, newRowUp, newRowDn, getx, getx2, timeRow, true, false)
realtime () =>
if barstate.islast
var keyLevelsLive = dataStore.new(pocs = array.new_box(), vas = array.new_box())
var coordinates = matrix.new<chart.point>(2, 0)
if coordinates.columns() > 0
for i = 0 to 1
polyline.all.pop().delete()
for i = 0 to coordinates.columns() - 1
coordinates.remove_col()
timeRow = data.timeVolMat.row(0)
startIndex = timeRow.indexof(line.all.last().get_x2())
highs = data.HLmat.row(0).slice(0, startIndex + 1)
lows = data.HLmat.row(1).slice(0, startIndex + 1)
newLevelsMat = matrix.new<float>(3, ROWS, 0.0)
newLevelsMat.setLevels(lows.min(), highs.max(), true)
levelsArr = newLevelsMat.row(0)
for i = 0 to startIndex
[l1, l2] = levelsArr.double_binary_search_leftmost(i)
div = math.abs(l1 - l2) + 1
for x = l1 to l2
newLevelsMat.effSwitch(i, x, div, 0)
difference = N - startIndex
newRange = math.floor((N - difference) / factor)
newRowUp = newLevelsMat.row(1), newRowDn = newLevelsMat.row(2)
oldMin = math.min(newRowUp.min(), newRowDn.min())
oldMax = math.max(newRowUp.max(), newRowDn.max())
coordinates.setCoordsLive(newRowUp, newRowDn, oldMin, oldMax, newRange, difference, newLevelsMat, timeRow)
coordinates.createPoly(timeRow, na, na, na, true, difference, na, lows, highs)
keyLevelsLive.pocs.drawPOC(difference, levelsArr, false, newRowUp, newRowDn, true, timeRow = timeRow, cond1 = true)
levelsArr.calcDelta(newRowUp, newRowDn, lows.min(), highs.max(), math.round(math.avg(N, N - startIndex)))
keyLevelsLive.vas.calcVA(levelsArr, newRowUp, newRowDn, startIndex, startIndex, timeRow, false, true, true)
method keyLevelsUpdate(array<box> id, int limit, bool deletinput) =>
if id.size() > 0
for i = 0 to id.size() - 1
if high < id.get(i).get_top() or low > id.get(i).get_top()
if id.get(i).get_right() == N - 1
id.get(i).set_right(N)
else if deletinput
id.get(i).delete()
if deletinput
if id.get(i).get_right() != N
id.get(i).delete()
if barstate.islast
if id.size() > limit
for i = 0 to id.size() - limit
id.get(i).delete()
tLevels.tickLevels.update(), data.pocs.keyLevelsUpdate(show, delet), data.vas.keyLevelsUpdate(showVAS, deletv), realtime()
|
Machine Learning: Gaussian Process Regression [LuxAlgo] | https://www.tradingview.com/script/R5xWzGHS-Machine-Learning-Gaussian-Process-Regression-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,835 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Machine Learning: Gaussian Process Regression [LuxAlgo]", "LuxAlgo - Machine Learning: Gaussian Process Regression", overlay = true, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
window = input.int(100, 'Training Window ', minval = 0, inline = 'window')
fitCss = input(#2962ff, '', inline = 'window')
forecast = input.int(20, 'Forecasting Length', minval = 0, maxval = 500, inline = 'forecast')
fcastCss = input(#f23645, '', inline = 'forecast')
length = input.float(20., 'Smooth', minval = 1)
sigma = input.float(0.01, step = 0.1, minval = 0)
update = input.string('Lock Forecast', 'Update Mechanism'
, options = ['Lock Forecast', 'Update Once Reached', 'Continuously Update'])
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
rbf(x1, x2, l)=> math.exp(-math.pow(x1 - x2, 2) / (2.0 * math.pow(l, 2)))
kernel_matrix(X1, X2, l)=>
km = matrix.new<float>(X1.size(), X2.size())
i = 0
for x1 in X1
j = 0
for x2 in X2
rbf = rbf(x1, x2, l)
km.set(i, j, rbf)
j += 1
i += 1
km
//-----------------------------------------------------------------------------}
//Kernel matrix
//-----------------------------------------------------------------------------{
var identity = matrix.new<int>(window, window, 0)
var matrix<float> K_source = na
if barstate.isfirst
xtrain = array.new<int>(0)
xtest = array.new<int>(0)
//Build identity matrix
for i = 0 to window-1
for j = 0 to window-1
identity.set(i, j, i == j ? 1 : 0)
xtrain.push(i)
for i = 0 to window+forecast-1
xtest.push(i)
//Compute kernel matrices
s = identity.mult(sigma * sigma)
Ktrain = kernel_matrix(xtrain, xtrain, length).sum(s)
K_inv = Ktrain.pinv()
K_star = kernel_matrix(xtrain, xtest, length)
K_source := K_star.transpose().mult(K_inv)
//-----------------------------------------------------------------------------}
//Set forecast
//-----------------------------------------------------------------------------{
n = bar_index
mean = ta.sma(close, window)
//Model set condition
var step = 0
set_model = switch update
'Lock Forecast' => barstate.islastconfirmedhistory
'Update Once Reached' => barstate.islast and step == 0
'Continuously Update' => barstate.islast
if set_model
//Remove previous lines
if update != 'Lock'
for l in line.all
l.delete()
//Dataset
ytrain = array.new<float>(0)
for i = 0 to window-1
ytrain.unshift(close[i] - mean)
//Estimate
mu = K_source.mult(ytrain)
//Set forecast
float y1 = na
k = -window+2
points = array.new<chart.point>(0)
fcast = array.new<chart.point>(0)
for element in mu
if k == 1
fcast.push(chart.point.from_index(n+k, element + mean))
points.push(chart.point.from_index(n+k, element + mean))
else if k > 1
fcast.push(chart.point.from_index(n+k, element + mean))
else
points.push(chart.point.from_index(n+k, element + mean))
k += 1
polyline.delete(polyline.new(points, line_color = fitCss, line_width = 2)[1])
polyline.delete(polyline.new(fcast, line_color = fcastCss, line_width = 2)[1])
//Update forecast
if update == 'Update Once Reached'
if barstate.islast
step += 1
step := step == forecast ? 0 : step
//-----------------------------------------------------------------------------} |
Bollinger Bands (Nadaraya Smoothed) | Flux Charts | https://www.tradingview.com/script/LUoxSDKw-Bollinger-Bands-Nadaraya-Smoothed-Flux-Charts/ | fluxchart | https://www.tradingview.com/u/fluxchart/ | 301 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fluxchart
//@version=5
indicator("Bollinger Bands (Nadaraya Smoothed) | Flux Charts", overlay = true, max_lines_count = 500, max_bars_back = 500)
group_smoothing = "smoothing"
h = input.float(6, "Smoothing Factor", step = .5, tooltip = "The bandwith(h) used in the kernel of the Nadaraya-Watson estimator function." ,group = group_smoothing)
repaint = input.bool(false,"Repaint Smoothing", tooltip = "This setting allows for repainting of the estimation" , group = group_smoothing)
sens = 4
group_boll = "Bollinger Bands Settings (Short, Medium, Long)"
short_period = input.int(20, "Period", inline = "short", group = group_boll)
short_stdev = input.float(3, "Deviation", inline = "short", group = group_boll)
med_period = input.int(75, "Period", inline = "med", group = group_boll)
med_stdev = input.float(4, "Deviation", inline = "med", group = group_boll)
long_period = input.int(100, " Period", inline = "long", group = group_boll)
long_stdev = input.float(4.25, "Deviation", inline = "long", group = group_boll)
group_graphics = "Plots and Labels"
labels = input.bool(true, "Labels", inline = "label" , group = group_graphics)
plots = input.bool(true, "Plot Lines", group = group_graphics)
plot_thickness = input.int(2, "Line Width", group = group_graphics)
bands_lvl1 = input.bool(true, "Level 1 Bands", inline = "bands", group = group_graphics)
bands_lvl2 = input.bool(true, "Level 2 Bands", inline = "bands", group = group_graphics)
grp = "Color Theme"
pallete_bear = input.color(color.red, "Bearish", inline = "theme", group = grp)
pallete_bull = input.color(color.green, "Bullish", inline = "theme", group = grp)
alpha1 = input.float(.90, "Transparency: Level 1 ", minval = .1, maxval = 1,inline = "alpha", step = .1)
alpha2 = input.float(.85, "Level 2", minval = .1, maxval = 1, inline = "alpha", step = .1)
grp_n = "Notifications"
notifs = input.bool(false, "Band Breaks", group = grp_n, tooltip = "Recieve notifications when price goes above or below the first level.")
type pallete
color bear
color bull
color shade1_bear
color shade1_bull
color shade2_bear
color shade2_bull
create_pallete(color bear, color bull, float alpha1 = 1, float alpha2 = 2) =>
float shade1 = 100 * alpha1
float shade2 = 100 * alpha2
color shade1_bear = color.new(bear, shade1)
color shade1_bull = color.new(bull, shade1)
color shade2_bear = color.new(bear, shade2)
color shade2_bull = color.new(bull, shade2)
pallete.new(bear, bull, shade1_bear, shade1_bull, shade2_bear, shade2_bull)
theme = create_pallete(pallete_bear, pallete_bull, alpha1, alpha2)
const bool bollinger_bands_lvl1 = true
const bool bollinger_bands_lvl2 = true
float tp = (high + low + close) /3
int n_first = 20
int n_second = 75
int n_third = 100
guass_w(x, h) =>
math.exp (-1 *( (x*x) / (2*(h*h)) ))
bollingers(n, factor = 3) =>
bolu = ta.sma(tp, n) + (factor * ta.stdev(tp, n))
bold = ta.sma(tp, n) - (factor * ta.stdev(tp, n))
[bolu, bold]
[BOLU_FIRST, BOLD_FIRST] = bollingers(n_first, short_stdev)
float BOL_FIRST_GAP = BOLU_FIRST - BOLD_FIRST
[BOLU_SECOND, BOLD_SECOND] = bollingers(n_second, short_stdev)
float BOL_SECOND_GAP = BOLU_SECOND - BOLD_SECOND
[BOLU_THIRD, BOLD_THIRD] = bollingers(n_third, med_stdev)
float BOL_THIRD_GAP = BOLU_THIRD - BOLD_THIRD
[BOLU_FOURTH, BOLD_FOURTH] = bollingers(n_third, long_stdev)
var pivots = array.new<float>()
var pivots2 = array.new<float>()
pivot_rad = sens
float pivot_high = ta.pivothigh(high, pivot_rad, pivot_rad)
float pivot_low = ta.pivotlow(low, pivot_rad, pivot_rad)
add_cols(mat, h_n = 1) =>
sum_array = array.new<float>()
for i=0 to matrix.rows(mat)-1
array.push(sum_array, array.sum(matrix.row(mat, i))/h_n)
sum_array
nadaraya(src, color) =>
smoothed = array.new<float>()
if barstate.islast and repaint
for i=0 to 499
sum = 0.
gk = array.new<float>()
for y =0 to 499
gk.push(guass_w(y - i, h))
gk_sum = gk.sum()
for y =0 to 499
sum += src[y]*(gk.get(y)/gk_sum)
smoothed.push(sum)
if i%2 == 0 and i != 0
line.new(bar_index[i-1], smoothed.get(i-1), bar_index[i], smoothed.get(i), color = color, width = 2)
smoothed
running_nadaraya(src, n)=>
var gk = array.new<float>(0)
var gk_sum = 0.
var src_matrix = matrix.new<float>()
smoothed = 0.
if barstate.isfirst and not repaint
for i=0 to n
gk.push(guass_w(i, h))
gk_sum := gk.sum()
if not repaint
for i=n to 0
smoothed += src[i] * (gk.get(i)/gk_sum)
smoothed
n = 499
smoothed_bolu_1 = running_nadaraya(BOLU_FIRST, n)
smoothed_bold_1 = running_nadaraya(BOLD_FIRST, n)
smoothed_bolu_2 = running_nadaraya(BOLU_SECOND, n)
smoothed_bold_2 = running_nadaraya(BOLD_SECOND, n)
smoothed_bolu_3 = running_nadaraya(BOLU_THIRD, n)
smoothed_bold_3 = running_nadaraya(BOLD_THIRD, n)
smoothed_bolu_4 = running_nadaraya(BOLU_FOURTH, n)
smoothed_bold_4 = running_nadaraya(BOLD_FOURTH, n)
BOLU_FIRST_PLOT = plot(smoothed_bolu_1, display = display.none)
BOLD_FIRST_PLOT = plot(smoothed_bold_1, display = display.none)
BOLU_SECOND_PLOT = plot(smoothed_bolu_2, display = display.none)
BOLD_SECOND_PLOT = plot(smoothed_bold_2, display = display.none)
BOLU_THIRD_PLOT = plot(smoothed_bolu_3, display = display.none)
BOLD_THIRD_PLOT = plot(smoothed_bold_3, display = display.none)
BOLU_FOURTH_PLOT = plot(smoothed_bolu_4, display = display.none)
BOLD_FOURTH_PLOT = plot(smoothed_bold_4, display = display.none)
if repaint
nadaraya(BOLU_FIRST, theme.bear)
nadaraya(BOLD_FIRST, theme.bull)
spacing = ta.atr(300)
upper_band_test = pivot_high >= smoothed_bolu_1[sens] and not repaint ? pivot_high + spacing * 1.01 : na
lower_band_test = pivot_low <= smoothed_bold_1[sens] and not repaint ? pivot_low - spacing * 1.01 : na
if notifs and close > smoothed_bolu_1
alert("Upper Band Crossed on " + syminfo.ticker, alert.freq_once_per_bar_close)
else if notifs and close < smoothed_bold_1
alert("Lower Band Crossed on " + syminfo.ticker, alert.freq_once_per_bar_close)
plotshape(labels ? upper_band_test : na, style = shape.triangledown, location = location.absolute, color = theme.bear, offset = -1*sens, size = size.tiny)
plotshape(labels ? lower_band_test : na, style = shape.triangleup, location = location.absolute, color = theme.bull, offset = -1*sens, size = size.tiny)
plot(not repaint and plots ? smoothed_bolu_1 : na, linewidth = plot_thickness, color = theme.bear)
plot(not repaint and plots ? smoothed_bold_1 : na, linewidth = plot_thickness, color = theme.bull)
fill(BOLU_FIRST_PLOT, BOLU_SECOND_PLOT, theme.shade1_bear, display = bands_lvl1 ? display.all: display.none)
fill(BOLD_FIRST_PLOT, BOLD_SECOND_PLOT, theme.shade1_bull, display = bands_lvl1 ? display.all: display.none)
fill(BOLU_SECOND_PLOT, BOLU_THIRD_PLOT, theme.shade2_bear, display = bands_lvl2 ? display.all: display.none)
fill(BOLD_SECOND_PLOT, BOLD_THIRD_PLOT, theme.shade2_bull, display = bands_lvl2 ? display.all: display.none)
|
lib_profile | https://www.tradingview.com/script/OZ5Rqvrl-lib-profile/ | robbatt | https://www.tradingview.com/u/robbatt/ | 13 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © robbatt
// v354 (v1) feature complete, optimisation todo
// v453 (v5) fixed max_bars_back through not updating box left and line start x coordinates on re-draw, added lines to mark candle ranges used for profile
//@version=5
import robbatt/lib_plot_objects/34 as D
// @description a library with functions to calculate a volume profile for either a set of candles within the current chart, or a single candle from its lower timeframe security data. All you need is to feed the
library("lib_profile", overlay = true)
//@description this is a container for each bucket of the Profile. See Profile description for more info
//@field idx the index of this Bucket within the Profile starting with 0 for the lowest Bucket at the bottom of the Profile
//@field value the value of this Bucket, can be volume or time, for using time pass and array of 1s to the update function
//@field top the top of this Bucket's price range (for calculation)
//@field btm the bottom of this Bucket's price range (for calculation)
//@field center the center of this Bucket's price range (for plotting)
//@field fraction the fraction this Bucket's value is compared to the total of the Profile
//@field plot_bucket_line the line that resembles this bucket and it's valeu in the Profile
export type Bucket
int idx
float value
float top
float btm
float center
float fraction
D.Line plot_bucket_line
//@function deletes this bucket's plot from the chart
export method delete(Bucket this) =>
if na(this) ? false : not na(this.plot_bucket_line)
this.plot_bucket_line.delete()
this
//@function hides this bucket's plot from the chart by setting the line end to na
export method hide(Bucket this) =>
if na(this) ? false : not na(this.plot_bucket_line)
this.plot_bucket_line.hide()
this
//@function updates this bucket's data
export method update(Bucket this, float top, float bottom, float value, float fraction) =>
this.top := top
this.btm := bottom
this.center := math.avg(top, bottom)
this.value := value
this.fraction := fraction
this
//@function allows debug print of a bucket
export method tostring(Bucket this) =>
str.format('idx {0} - top: {1} - center: {2} - bottom: {3} - value: {4} - fraction: {5}', this.idx, this.top, this.center, this.btm, this.value, this.fraction)
//@function allows drawing a line in a Profile, representing this bucket and it's value + it's value's fraction of the Profile total value
//@param start_t the time x coordinate of the line's left end (depends on the Profile box)
//@param start_i the bar_index x coordinate of the line's left end (depends on the Profile box)
//@param end_t the time x coordinate of the line's right end (depends on the Profile box)
//@param end_i the bar_index x coordinate of the line's right end (depends on the Profile box)
//@param args the default arguments for the line style
//@param line_color the color override for POC/VAH/VAL lines
export method draw(Bucket this, int start_t, int start_i, int end_t, int end_i, D.LineArgs args, color line_color) =>
if na(this.plot_bucket_line)
this.plot_bucket_line := D.create_line(start_t, start_i, this.center, end_t, end_i, this.center, args)
// this.plot_bucket_line.start.update(start_t, start_i, this.center)
this.plot_bucket_line.end.update(end_t, end_i, this.center)
this.plot_bucket_line.draw()
if not na(line_color)
this.plot_bucket_line.plot.set_color(line_color)
this
//@description arguments for plotting a Profile
//@field show_poc whether to plot a POC line across the Profile Box (default: true)
//@field show_profile whether to plot a line for each Bucket in the Profile Box, indicating the value per Bucket (Price range), e.g. volume that occured in a certain time and price range (default: false)
//@field show_va whether to plot a VAH/VAL line across the Profile Box (default: false)
//@field show_va_fill whether to fill the 'value' area between VAH/VAL line (default: false)
//@field show_background whether to fill the Profile Box with a background color (default: false)
//@field show_labels whether to add labels to the right end of the POC/VAH/VAL line (default: false)
//@field show_price_levels whether add price values to the labels to the right end of the POC/VAH/VAL line (default: false)
//@field extend whether extend the Profile Box to the current candle (default: false)
//@field default_size the default min. width of the Profile Box (default: 30)
//@field args_poc_line arguments for the poc line plot
//@field args_va_line arguments for the va line plot
//@field args_poc_label arguments for the poc label plot
//@field args_va_label arguments for the va label plot
//@field args_profile_line arguments for the Bucket line plots
//@field va_fill_color color for the va area fill plot
export type ProfileArgs
bool show_poc = true
bool show_profile = false
bool show_va = false
bool show_va_fill = false
bool show_background = false
bool show_labels = false
bool show_price_levels = false
bool extend = false
int default_size = 30
D.LineArgs args_poc_line
D.LineArgs args_va_line
D.LabelArgs args_poc_label
D.LabelArgs args_va_label
D.LineArgs args_profile_line
D.BoxArgs args_profile_bg
color va_fill_color = color.yellow
//@description
//@field start left x coordinate for the Profile Box
//@field end right x coordinate for the Profile Box
//@field resolution the amount of buckets/price ranges the Profile will dissect the data into
//@field vah_threshold_pc the percentage of the total data value to mark the upper threshold for the main value area
//@field val_threshold_pc the percentage of the total data value to mark the lower threshold for the main value area
//@field args the style arguments for the Profile Box
//@field h the highest price of the data
//@field l the lowest price of the data
//@field total the total data value (e.g. volume of all candles, or just one each to analyse candle distribution over time)
//@field buckets the Bucket objects holding the data for each price range bucket
//@field poc_bucket_index the Bucket index in buckets, that holds the poc Bucket
//@field vah_bucket_index the Bucket index in buckets, that holds the vah Bucket
//@field val_bucket_index the Bucket index in buckets, that holds the val Bucket
//@field poc the according price level marking the Point Of Control
//@field vah the according price level marking the Value Area High
//@field val the according price level marking the Value Area Low
//@field plot_poc
//@field plot_vah
//@field plot_val
//@field plot_poc_label
//@field plot_vah_label
//@field plot_val_label
//@field plot_va_fill
//@field plot_profile_bg
export type Profile
// params
int start
int end
int resolution
float vah_threshold_pc
float val_threshold_pc
ProfileArgs args
// range data
float h
float l
float total
Bucket[] buckets
// value levels
int poc_bucket_index
int vah_bucket_index
int val_bucket_index
// price levels
float poc
float vah
float val
// plots
D.Line plot_poc
D.Line plot_vah
D.Line plot_val
D.Label plot_poc_label
D.Label plot_vah_label
D.Label plot_val_label
D.LineFill plot_va_fill
D.Box plot_profile_bg
export method apply_style(Profile this, ProfileArgs args) =>
if not na(this) and not na(args)
this.args := args
if not na(this.plot_poc)
this.plot_poc.apply_style(args.args_poc_line)
if not na(this.plot_vah)
this.plot_vah.apply_style(args.args_va_line)
if not na(this.plot_val)
this.plot_val.apply_style(args.args_va_line)
if not na(this.plot_poc_label)
this.plot_poc_label.apply_style(args.args_poc_label)
if not na(this.plot_vah_label)
this.plot_vah_label.apply_style(args.args_va_label)
if not na(this.plot_val_label)
this.plot_val_label.apply_style(args.args_va_label)
if not na(this.plot_va_fill)
this.plot_va_fill.plot.set_color(args.va_fill_color)
if not na(this.plot_profile_bg)
this.plot_profile_bg.apply_style(args.args_profile_bg, D.BoxTextArgs.new())
//@description deletes this Profile's and Buckets' plots
export method delete(Profile this) =>
if not na(this)
if not na(this.buckets)
for bucket in this.buckets
bucket.delete()
if not na(this.plot_poc)
this.plot_poc.delete()
if not na(this.plot_vah)
this.plot_vah.delete()
if not na(this.plot_val)
this.plot_val.delete()
if not na(this.plot_poc_label)
this.plot_poc_label.delete()
if not na(this.plot_vah_label)
this.plot_vah_label.delete()
if not na(this.plot_val_label)
this.plot_val_label.delete()
if not na(this.plot_va_fill)
this.plot_va_fill.delete()
if not na(this.plot_profile_bg)
this.plot_profile_bg.delete()
this
//@function hides this Profile's plot from the chart by setting the line end to na
export method hide(Profile this) =>
if not na(this)
if not na(this.buckets)
for bucket in this.buckets
bucket.hide()
if not na(this.plot_poc)
this.plot_poc.hide()
if not na(this.plot_vah)
this.plot_vah.hide()
if not na(this.plot_val)
this.plot_val.hide()
if not na(this.plot_poc_label)
this.plot_poc_label.hide()
if not na(this.plot_vah_label)
this.plot_vah_label.hide()
if not na(this.plot_val_label)
this.plot_val_label.hide()
if not na(this.plot_profile_bg)
this.plot_profile_bg.hide()
this
_delete_all(id) =>
if not na(id)
for item in id
item.delete()
id
//@description deletes a list of Buckets' plots
export method delete(Bucket[] this) => _delete_all(this)
//@description deletes a list of Profiles' plots
export method delete(Profile[] this) => _delete_all(this)
//@description initialises ProfileArgs with default values if not set, will be called by update() and draw() to ensure both functions can work properly
export method init(ProfileArgs this) =>
if not na(this)
if na(this.args_poc_line)
this.args_poc_line := D.LineArgs.new(color.orange, line.style_dotted, 1, xloc.bar_time)
if na(this.args_va_line)
this.args_va_line := D.LineArgs.new(color.yellow, line.style_dotted, 1, xloc.bar_time)
if na(this.args_poc_label)
this.args_poc_label := D.LabelArgs.new(color.orange, #00000000, style = label.style_label_lower_right, xloc = xloc.bar_time)
if na(this.args_va_label)
this.args_va_label := D.LabelArgs.new(color.yellow, #00000000, style = label.style_label_lower_right, xloc = xloc.bar_time)
if na(this.args_profile_line)
this.args_profile_line := D.LineArgs.new(color.rgb(120, 123, 134, 40), line.style_dotted, 1, xloc.bar_time)
if na(this.args_profile_bg)
this.args_profile_bg := D.BoxArgs.new(#00000000, bg_color = color.rgb(120, 123, 134, 92), xloc = xloc.bar_time)
this
//@description initialises Profile with default values if not set, will be called by update() and draw() to ensure both functions can work properly
export method init(Profile this) =>
if not na(this)
if na(this.buckets)
this.buckets := array.new<Bucket>(this.resolution)
for i = 0 to this.resolution - 1
this.buckets.set(i, Bucket.new(i))
if na(this.args)
this.args := ProfileArgs.new().init()
//@function split a chart/parent bar into 'resolution' sections, figure out in which section the most volume/time was spent, by analysing a given set of (intra)bars' top/bottom/volume values. Then return price center of the bin with the highest volume, essentially marking the point of control / highest volume (poc) in the chart/parent bar.
//@param tops array of range top/high values (either from ltf or chart candles using history() function
//@param bottoms array of range bottom/low values (either from ltf or chart candles using history() function
//@param values array of range volume/1 values (either from ltf or chart candles using history() function (1s can be used for analysing candles in bucket/price range over time)
//@param resolution amount of buckets/price ranges to sort the candle data into (analyse how much volume / time was spent in a certain bucket/price range) (default: 25)
//@param vah_pc a threshold percentage (of values' total) for the top end of the value area (default: 80)
//@param val_pc a threshold percentage (of values' total) for the bottom end of the value area (default: 20)
//@param bucket_buffer optional buffer of empty Buckets to fill, if omitted a new one is created and returned. The buffer length must match the resolution
//@returns poc (price level), vah (price level), val (price level), poc_index (idx in buckets), vah_index (idx in buckets), val_index (idx in buckets), buckets (filled buffer or new)
export profile(float[] tops, float[] bottoms, float[] values, int resolution = 25, float vah_pc = 80, float val_pc = 20, Bucket[] bucket_buffer = na) =>
// DATA
float h = tops.max()
float l = bottoms.min()
float total = values.sum()
int range_count = array.size(values)
float vah_threshold = total * (vah_pc / 100)
float val_threshold = total * (val_pc / 100)
float value_range = h - l
float bucket_size = value_range / resolution
// RESULTS
Bucket[] buckets = na(bucket_buffer) ? array.new<Bucket>(resolution) : bucket_buffer.size() != resolution ? array.new<Bucket>(resolution) : bucket_buffer
float poc = na
float vah = na
float val = na
int poc_index = 0
int vah_index = 0
int val_index = 0
if range_count > 0
float poc_volume = 0
float sum_volume = 0
for i = 0 to resolution - 1
float bucket_bottom = l + i * bucket_size
float bucket_top = bucket_bottom + bucket_size
float bucket_value = 0
// check all top-btm ranges, add the value (partly) to the bucket on overlap
for j = 0 to range_count - 1
float range_value = array.get(values, j)
float range_top = array.get(tops, j)
float range_btm = array.get(bottoms, j)
float range_size = range_top - range_btm
float range_value_fraction = 0
if range_top <= bucket_top and (range_btm > bucket_bottom or i == 0 and range_btm >= bucket_bottom)// inside bucket (also if range_size == 0 due to high == low)
range_value_fraction := 1
else if range_top > bucket_top and range_btm < bucket_bottom // around bucket
range_value_fraction := bucket_size / range_size
else if range_top > bucket_bottom and range_top <= bucket_top and range_btm < bucket_bottom // sticks into bucket from below (only count part in bucket)
range_value_fraction := (range_top - bucket_bottom) / range_size
else if range_btm < bucket_top and range_btm >= bucket_bottom and range_top > bucket_top // sticks into bucket from above (only count part in bucket)
range_value_fraction := (bucket_top - range_btm) / range_size
bucket_value += range_value_fraction * range_value
bucket = buckets.get(i).update(bucket_top, bucket_bottom, bucket_value, bucket_value / total)
// track highest value (POC) inside the profile AND it's index
if bucket_value > poc_volume
poc_volume := bucket_value
poc_index := i
// while going through the profile, accumulate the bucket values. As soon as we cross the value area thresholds with a bucket, we know where the value area starts / ends.
if sum_volume < val_threshold and val_threshold <= (sum_volume + bucket_value)
val_index := i
if sum_volume < vah_threshold and vah_threshold <= (sum_volume + bucket_value)
vah_index := i
sum_volume += bucket_value
poc := buckets.get(poc_index).center
vah := buckets.get(vah_index).center
val := buckets.get(val_index).center
[poc, vah, val, poc_index, vah_index, val_index, buckets]
//@function update this Profile's data (recalculates the whole profile and applies the result to this object) TODO optimisation to calculate this incremental to improve performance in realtime on high resolution
//@param tops array of range top/high values (either from ltf or chart candles using history() function
//@param bottoms array of range bottom/low values (either from ltf or chart candles using history() function
//@param values array of range volume/1 values (either from ltf or chart candles using history() function (1s can be used for analysing candles in bucket/price range over time)
export method update(Profile this, float[] tops, float[] bottoms, float[] values) =>
this.init()
[poc, vah, val, poc_index, vah_index, val_index, buckets] = profile(tops, bottoms, values, this.resolution, this.vah_threshold_pc, this.val_threshold_pc, this.buckets)
this.h := tops.max()
this.l := bottoms.min()
this.total := values.sum()
this.poc := poc
this.vah := vah
this.val := val
this.poc_bucket_index := poc_index
this.vah_bucket_index := vah_index
this.val_bucket_index := val_index
this
//@function split a chart/parent bar into 'resolution' sections, figure out in which section the most volume/time was spent, by analysing a given set of (intra)bars' top/bottom/volume values. Then return price center of the bin with the highest volume, essentially marking the point of control / highest volume (poc) in the chart/parent bar.
//@param start_idx the bar_index at which the Profile should start drawing
//@param tops array of range top/high values (either from ltf or chart candles using history() function
//@param bottoms array of range bottom/low values (either from ltf or chart candles using history() function
//@param values array of range volume/1 values (either from ltf or chart candles using history() function (1s can be used for analysing candles in bucket/price range over time)
//@param resolution amount of buckets/price ranges to sort the candle data into (analyse how much volume / time was spent in a certain bucket/price range) (default: 25)
//@param vah_pc a threshold percentage (of values' total) for the top end of the value area (default: 80)
//@param val_pc a threshold percentage (of values' total) for the bottom end of the value area (default: 20)
//@param bucket_buffer optional buffer of empty Buckets to fill, if omitted a new one is created and returned. The buffer length must match the resolution
//@returns poc (price level), vah (price level), val (price level), poc_index (idx in buckets), vah_index (idx in buckets), val_index (idx in buckets), buckets (filled buffer or new)
export create_profile(int start_idx, float[] tops, float[] bottoms, float[] values, int resolution = 25, float vah_pc = 80, float val_pc = 20, ProfileArgs args) =>
Profile.new(start_idx, start_idx + 1, resolution, vah_pc, val_pc, args).update(tops, bottoms, values)
//@function draw all components of this Profile (Box, Background, Bucket lines, POC/VAH/VAL overlay levels and labels)
//@param forced_width allows to force width of the Profile Box, overrides the ProfileArgs.default_size and ProfileArgs.extend arguments (default: na)
export method draw(Profile this, int forced_width = na) =>
this.init()
var tf_ms = timeframe.in_seconds() * 1000
if na(this) ? false : this.buckets.size() > 0
int bars_since_start = bar_index - this.start
int bars_since_end = bar_index - this.end
int start_t = time - bars_since_start * tf_ms
int len = not na(forced_width) ? forced_width : this.args.extend ? math.max(bars_since_start, this.args.default_size) : this.args.default_size
int ext_t = start_t + len * tf_ms
int ext_i = this.start + len
if this.args.show_background
if na(this.plot_profile_bg)
this.plot_profile_bg := D.Box.new(chart.point.new(start_t, this.start, this.h), chart.point.new(ext_t, ext_i, this.l), args = this.args.args_profile_bg, text_args = D.BoxTextArgs.new())
this.plot_profile_bg.left_top.update(start_t, this.start, this.h)
this.plot_profile_bg.right_bottom.update(ext_t, ext_i, this.l)
this.plot_profile_bg.draw()
if this.args.show_profile
poc_bucket = this.buckets.get(this.poc_bucket_index)
for bucket in this.buckets
if not na(bucket) and not na(poc_bucket)
int bucket_len = math.ceil(len * bucket.value / poc_bucket.value)
int bucket_end_i = this.start + bucket_len
int bucket_end_t = start_t + bucket_len * tf_ms
bucket_line_color =
bucket.idx == this.poc_bucket_index ? this.args.args_poc_line.line_color :
bucket.idx == this.vah_bucket_index or bucket.idx == this.val_bucket_index ? this.args.args_va_line.line_color :
this.args.args_profile_line.line_color
bucket.draw(start_t, this.start, bucket_end_t, bucket_end_i, this.args.args_profile_line, bucket_line_color)
if this.args.show_poc
if na(this.plot_poc)
this.plot_poc := D.Line.new(chart.point.new(start_t, this.start, this.poc), chart.point.new(ext_t, ext_i, this.poc), this.args.args_poc_line)
this.plot_poc.start.update(start_t, this.start, this.poc)
this.plot_poc.end.update(ext_t, ext_i, this.poc)
this.plot_poc.draw()
if this.args.show_labels
if na(this.plot_poc_label)
this.plot_poc_label := D.Label.new(this.plot_poc.end, 'POC', this.args.args_poc_label)
this.plot_poc_label.txt := this.args.show_price_levels ? str.format('POC ({0})', this.poc) : 'POC'
this.plot_poc_label.tooltip := str.format('POC ({0})', this.poc)
this.plot_poc_label.draw()
if this.args.show_va
if na(this.plot_vah)
this.plot_vah := D.Line.new(chart.point.new(start_t, this.start, this.vah), chart.point.new(ext_t, ext_i, this.vah), this.args.args_va_line)
if na(this.plot_val)
this.plot_val := D.Line.new(chart.point.new(start_t, this.start, this.val), chart.point.new(ext_t, ext_i, this.val), this.args.args_va_line)
this.plot_vah.start.update(start_t, this.start, this.vah)
this.plot_vah.end.update(ext_t, ext_i, this.vah)
this.plot_vah.draw()
this.plot_val.start.update(start_t, this.start, this.val)
this.plot_val.end.update(ext_t, ext_i, this.val)
this.plot_val.draw()
if this.args.show_labels
if na(this.plot_vah_label)
this.plot_vah_label := D.Label.new(this.plot_vah.end, 'VAH', this.args.args_va_label)
if na(this.plot_val_label)
this.plot_val_label := D.Label.new(this.plot_val.end, 'VAL', this.args.args_va_label)
this.plot_vah_label.txt := this.args.show_price_levels ? str.format('VAH ({0})', this.vah) : 'VAH'
this.plot_vah_label.tooltip := str.format('VAH ({0})', this.vah)
this.plot_vah_label.draw()
this.plot_val_label.txt := this.args.show_price_levels ? str.format('VAL ({0})', this.val) : 'VAL'
this.plot_val_label.tooltip := str.format('VAL ({0})', this.val)
this.plot_val_label.draw()
if this.args.show_va_fill
if na(this.plot_va_fill)
this.plot_va_fill := D.LineFill.new(this.plot_val, this.plot_vah, this.args.va_fill_color)
this.plot_va_fill.draw()
this
//////////////////////////////////////////////////////////////////////////////////
//#region DEMO
//////////////////////////////////////////////////////////////////////////////////
var resolution = input.int(30, 'resolution')
var vah_pc = input.float(80, 'VAH %')
var val_pc = input.float(20, 'VAL %')
ProfileArgs args = ProfileArgs.new(
show_poc = input.bool(true, 'show POC', inline = 'poc'),
args_poc_line = D.LineArgs.new(input.color(color.orange, '', inline = 'poc'), line.style_dashed, 1),
show_va = input.bool(true, 'Value Area', inline = 'va'),
args_va_line = D.LineArgs.new(input.color(color.yellow, '', inline = 'va'), line.style_dotted, 1),
show_va_fill = input.bool(true, 'fill', inline = 'va'),
va_fill_color = input.color(#ffeb3b0e, '', inline = 'va'),
show_labels = input.bool(true, 'Show labels', inline = 'labels'),
show_price_levels = input.bool(true, 'with price', inline = 'labels'),
args_poc_label = D.LabelArgs.new(input.color(color.orange, '', inline = 'labels'), #00000000, style = label.style_label_left, size = size.tiny),
args_va_label = D.LabelArgs.new(input.color(color.yellow, '', inline = 'labels'), #00000000, style = label.style_label_left, size = size.tiny),
show_profile = input.bool(true, 'show Profile', inline = 'profile'),
args_profile_line = D.LineArgs.new(input.color(#787b869e, '', inline = 'profile'), line.style_solid, 3),
show_background = input.bool(true, 'with background', inline = 'profile'),
args_profile_bg = D.BoxArgs.new(#00000000, bg_color = input.color(#787b860f, '', inline = 'profile')),
extend = input.bool(true, 'extend profile', inline = 'extend'),
default_size = input.int(20, 'min width', inline = 'extend')
)
var g_use_cases = 'DEMO'
var use_case = input.string('High Volume Candle + LTF Detail', 'Use Case', ['High Volume Candle + LTF Detail', 'High Volume Candle + Lookback Range', 'Current Candle Live', 'Current Range Live'], group = g_use_cases)
var use_case_LTF = str.contains(use_case, 'LTF')
var use_case_lookback = str.contains(use_case, 'Lookback')
var use_case_live = str.contains(use_case, 'Candle Live')
var use_case_live_range = str.contains(use_case, 'Range Live')
/////////////////////////////////////////////////////////////////////////////////////////////////////
// USE CASE (profile single high volume candle with ltf data)
/////////////////////////////////////////////////////////////////////////////////////////////////////
//@description returns a lower timeframe to get a reasonable amount of data for volume spread analysis (>1M -> 1D) / (>1W -> 1H) / (>5m -> 10S) / (else 1S)
//@param allow_seconds if true this will use second based timeframes for the volume data (only for premium users)
export get_ltf(simple bool allow_seconds = false) =>
tf_min = timeframe.in_seconds() / 60
// 10080 minutes == 7 days
// 43200 minutes == 30 days
ltf = tf_min >= 43200 ? '1D' : tf_min >= 10080 ? '60' : tf_min >= 1440 ? '15' : tf_min >= 60 or not allow_seconds ? '1' : tf_min >= 5 ? '10S' : '1S'
var ltf = get_ltf()
var tf_min = timeframe.in_seconds() / 60
var ltf_label = label.new(bar_index, 0, str.format('res: {0}min -> {1}',tf_min, ltf), color = #00000000, textcolor = chart.fg_color, style = label.style_label_lower_left, size = size.tiny )
[ltf_tops, ltf_bottoms, ltf_values] = request.security_lower_tf(syminfo.tickerid, ltf, [high, low, volume])
var volume_threshold_len = input.int(50, 'High volume candle - SMA len', inline = 'volume_threshold', group = g_use_cases)
var volume_threshold_mult = input.float(3, 'x', minval = 1, step =0.1, inline = 'volume_threshold', group = g_use_cases)
var Profile obj_prev = na
var Profile obj = na
volume_sma = ta.sma(volume, volume_threshold_len)
if use_case_LTF
if volume > volume_sma * volume_threshold_mult
if not na(obj)
if not na(obj_prev)
obj_prev.buckets.delete()
obj_prev.plot_profile_bg.delete()
obj_prev.plot_poc_label.delete()
obj_prev.plot_vah_label.delete()
obj_prev.plot_val_label.delete()
obj_prev := obj
obj := create_profile(bar_index, ltf_tops, ltf_bottoms, ltf_values, resolution, vah_pc, val_pc, args)
if ltf_values.size() == 0
label.new(bar_index, close, "ltf data empty\ncan't plot profile", yloc = yloc.abovebar, color = color.red, textcolor = color.white, size = size.normal)
if not na(obj.plot_profile_bg)
ltf_label.set_xy(obj.plot_profile_bg.left_top.index, obj.plot_profile_bg.left_top.price)
obj.draw()
/////////////////////////////////////////////////////////////////////////////////////////////////////
// USE CASE (profile timeframe from chart history candles)
/////////////////////////////////////////////////////////////////////////////////////////////////////
var ProfileArgs args2 = args.copy()
if barstate.isfirst
args2.va_fill_color := #fe84090e
args2.args_poc_line := D.LineArgs.new(color.red, line.style_solid, 2)
args2.args_va_line := D.LineArgs.new(color.orange, line.style_dotted, 2)
args2.args_poc_label := D.LabelArgs.new(color.red, #00000000, style = label.style_label_left, size = size.tiny)
args2.args_va_label := D.LabelArgs.new(color.orange, #00000000, style = label.style_label_left, size = size.tiny)
args2.args_profile_line := D.LineArgs.new(#787b869e, line.style_solid, 4)
_history(src, int len, int offset = 0) =>
start_idx = math.max(0, bar_index - len - offset)
end_idx = math.max(0, math.min(bar_index - offset, bar_index))
len_sanitized = end_idx - start_idx
var buffer = array.from(src)
if not barstate.isfirst
buffer.push(src)
if buffer.size() > len + offset
buffer.shift()
buffer.slice(0,len_sanitized)
//@function allows fetching an array of values from the history series with offset from current candle
export history(int src, int len, int offset = 0) => _history(src, len, offset)
//@function allows fetching an array of values from the history series with offset from current candle
export history(float src, int len, int offset = 0) => _history(src, len, offset)
//@function allows fetching an array of values from the history series with offset from current candle
export history(bool src, int len, int offset = 0) => _history(src, len, offset)
//@function allows fetching an array of values from the history series with offset from current candle
export history(string src, int len, int offset = 0) => _history(src, len, offset)
// direct source previous candles
var history_len = input.int(20, 'Range Candles', inline = 'range')
var history_offset = input.int(2, 'Range Offset', inline = 'range')
tops = history(high, history_len, history_offset)
bottoms = history(low, history_len, history_offset)
values_volume = history(volume, history_len, history_offset)
var Profile obj2_prev = na
var Profile obj2 = na
if use_case_lookback
if volume > volume_sma * volume_threshold_mult
if not na(obj2)
if bar_index - obj2.start < args2.default_size
if not na(obj2_prev)
obj2_prev.delete()
obj2_prev := obj2
else
obj2.buckets.delete()
obj2.plot_profile_bg.delete()
obj2 := create_profile(bar_index, tops, bottoms, values_volume, resolution, vah_pc, val_pc, args2)
range_size = values_volume.size()
if bar_index > range_size + history_offset
range2_line = line.new(bar_index - (range_size + history_offset), obj2.l, bar_index - history_offset, obj2.l, color = color.gray, width = 2)
obj2.draw()
/////////////////////////////////////////////////////////////////////////////////////////////////////
// USE CASE (profile timeframe from chart history candles)
/////////////////////////////////////////////////////////////////////////////////////////////////////
var Profile obj3 = na
if use_case_live
obj3 := create_profile(bar_index, ltf_tops, ltf_bottoms, ltf_values, resolution, vah_pc, val_pc, args).draw()
if barstate.isconfirmed
obj3.delete()
var Profile obj4 = na
var line range4_line = line.new(na, na, na, na, color = color.gray, width = 2)
if use_case_live_range
range_size = values_volume.size()
obj4 := create_profile(bar_index, tops, bottoms, values_volume, resolution, vah_pc, val_pc, args).draw()
if bar_index > range_size + history_offset
range4_line.set_xy1(bar_index - (range_size + history_offset), obj4.l)
range4_line.set_xy2(bar_index - history_offset, obj4.l)
if barstate.isconfirmed
obj4.delete()
plot(bar_index, 'bar index', display = display.data_window)
var bool show_ltf_bug_note = input.bool(true, 'show LTF bug note', tooltip = 'at the time of creating this, TV had a bug where no LTF data was available during Replay Stepping, causing the profile calculation to fail. When it is fixed this should not show anymore. The Jump to... tool works though')
plotshape(show_ltf_bug_note and (na(ltf_values) ? true : ltf_values.size() == 0), 'No LTF data available for this bar', shape.xcross, location.bottom, color.red, size = size.tiny)
|
Predictive Channels [LuxAlgo] | https://www.tradingview.com/script/U8SB8fWq-Predictive-Channels-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,581 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Predictive Channels [LuxAlgo]", "LuxAlgo - Predictive Channels", overlay = true)
//-----------------------------------------------------------------------------}
//Settings
//-----------------------------------------------------------------------------{
mult = input.float(5, 'Factor', minval = 0)
slope = input.float(50, minval = 0) * mult
//Style
r2Css = input(#f23645, 'Upper Resistance', inline = 'resistance', group = 'Colors')
r1Css = input(color.new(#f23645, 50), 'Lower', inline = 'resistance', group = 'Colors')
s1Css = input(color.new(#089981, 50), 'Upper Support ', inline = 'support', group = 'Colors')
s2Css = input(#089981, 'Lower', inline = 'support', group = 'Colors')
avgCss = input(#787b86, 'Average', group = 'Colors')
areaBull = input(color.new(#089981, 80), 'Fill', inline = 'area', group = 'Colors')
areaBear = input(color.new(#f23645, 80), '', inline = 'area', group = 'Colors')
//-----------------------------------------------------------------------------}
//Calculation
//-----------------------------------------------------------------------------{
var pc_avg = close
var os = 1
var hold_atr = 0.
atr = nz(ta.atr(200)) * mult
pc_avg := math.abs(close - pc_avg) > atr ? close
: pc_avg + os * hold_atr / slope
hold_atr := pc_avg == close ? atr / 2 : hold_atr
os := pc_avg > pc_avg[1] ? 1 : pc_avg < pc_avg[1] ? -1 : os
pc_R2 = pc_avg + hold_atr
pc_R1 = pc_avg + hold_atr/2
pc_S1 = pc_avg - hold_atr/2
pc_S2 = pc_avg - hold_atr
//-----------------------------------------------------------------------------}
//Plot
//-----------------------------------------------------------------------------{
plot_0 = plot(close, color = na, display = display.none, editable = false)
//SR PLots
plot(pc_R2, 'Upper Resistance', close == pc_avg ? na : r2Css)
plot(pc_R1, 'Lower Resistance', close == pc_avg ? na : r1Css)
plot_avg = plot(pc_avg, 'Average', close == pc_avg ? na : avgCss)
plot(pc_S1, 'Upper Support', close == pc_avg ? na : s1Css)
plot(pc_S2, 'Lower Support', close == pc_avg ? na : s2Css)
//Fill
topcss = close > pc_avg ? areaBull : color.new(chart.bg_color, 100)
btmcss = close < pc_avg ? areaBear : color.new(chart.bg_color, 100)
fill(plot_0, plot_avg, pc_R2, pc_S2, topcss, btmcss)
//-----------------------------------------------------------------------------} |
10x Bull Vs. Bear VP Intraday Sessions [Kioseff Trading] | https://www.tradingview.com/script/3mKewfnN-10x-Bull-Vs-Bear-VP-Intraday-Sessions-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 279 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Bull Vs. Bear Market Intraday Sessions [Kioseff Trading]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_polylines_count = 100, max_bars_back = 5000)
import RicardoSantos/MathOperator/2
import kaigouthro/hsvColor/15 as kai
import HeWhoMustNotBeNamed/arraymethods/1
timeTrue(string timeRange) =>
math.sign(time("1", timeRange, "UTC"))
//
showT1 = input.bool (defval = true , title = "", group = "Profiles to Show", inline = "T1"), t1 = input.string(defval = "Range 1" , title = "", inline = "T1", group = "Profiles to Show")
showT2 = input.bool (defval = true , title = "", group = "Profiles to Show", inline = "T2"), t2 = input.string(defval = "Range 2" , title = "", inline = "T2", group = "Profiles to Show")
showT3 = input.bool (defval = true , title = "", group = "Profiles to Show", inline = "T3"), t3 = input.string(defval = "Range 3 ", title = "", inline = "T3", group = "Profiles to Show")
showT4 = input.bool (defval = true , title = "", group = "Profiles to Show", inline = "T4"), t4 = input.string(defval = "Range 4" , title = "", inline = "T4", group = "Profiles to Show")
showT5 = input.bool (defval = false, title = "", group = "Profiles to Show", inline = "T5"), t5 = input.string(defval = "Range 5" , title = "", inline = "T5", group = "Profiles to Show")
showT6 = input.bool (defval = false, title = "", group = "Profiles to Show", inline = "T6"), t6 = input.string(defval = "Range 6" , title = "", inline = "T6", group = "Profiles to Show")
showT7 = input.bool (defval = false, title = "", group = "Profiles to Show", inline = "T7"), t7 = input.string(defval = "Range 7 ", title = "", inline = "T7", group = "Profiles to Show")
showT8 = input.bool (defval = false, title = "", group = "Profiles to Show", inline = "T8"), t8 = input.string(defval = "Range 8" , title = "", inline = "T8", group = "Profiles to Show")
showT9 = input.bool (defval = false, title = "", group = "Profiles to Show", inline = "T9"), t9 = input.string(defval = "Range 9" , title = "", inline = "T9", group = "Profiles to Show")
T1T = input.session ("0000-0600" , title = "" , inline = "T1", group = "Profiles to Show")
T2T = input.session ("0600-1200" , title = "" , inline = "T2", group = "Profiles to Show")
T3T = input.session ("1200-1800" , title = "" , inline = "T3", group = "Profiles to Show")
T4T = input.session ("1800-0000" , title = "" , inline = "T4", group = "Profiles to Show")
T5T = input.session ("0000-0600" , title = "" , inline = "T5", group = "Profiles to Show")
T6T = input.session ("0600-1200" , title = "" , inline = "T6", group = "Profiles to Show")
T7T = input.session ("1200-1800" , title = "" , inline = "T7", group = "Profiles to Show")
T8T = input.session ("1800-0000" , title = "" , inline = "T8", group = "Profiles to Show")
T9T = input.session ("0000-0600" , title = "" , inline = "T9", group = "Profiles to Show")
showLI = input.bool (defval = true, title = "Live", inline = "LI", group = "Profiles to Show")
LIT = input.timeframe("1D" , title = "" , inline = "LI", group = "Profiles to Show")
upColT1 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T1"), dnColT1 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T1")
upColT2 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T2"), dnColT2 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T2")
upColT3 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T3"), dnColT3 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T3")
upColT4 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T4"), dnColT4 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T4")
upColT5 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T5"), dnColT5 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T5")
upColT6 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T6"), dnColT6 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T6")
upColT7 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T7"), dnColT7 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T7")
upColT8 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T8"), dnColT8 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T8")
upColT9 = input.color (defval = #14D990 , title = "" , group = "Profiles to Show", inline = "T9"), dnColT9 = input.color (defval = #F24968 , title = "" , group = "Profiles to Show", inline = "T9")
upColLI = input.color (defval = color.lime , title = "" , group = "Profiles to Show", inline = "LI"), dnColLI = input.color (defval = color.red , title = "" , group = "Profiles to Show", inline = "LI"), atr = ta.atr(14)
boxed = input.bool (defval = true, title = "Boxed Sessions")
ROWS = input.int (defval = 100, maxval = 2000, minval = 10, step = 10, title = "Profile Rows", group = "Profile Settings")
factor = input.float (defval = 4, minval = 1.1, step = 0.1, title = "Scaling Factor", group = "Profile Settings")
same = input.string(defval = "Same Side", title = "VP Plot Type", options = ["Middle", "Same Side"], group = "Profile Settings")
showdel = input.bool (defval = false, title = "Show Delta", group = "Delta Settings")
deltaRows = input.int (defval = 20, minval = 5, title = "Delta Rows", group = "Delta Settings")
deltaSz = input.string(defval = "Tiny", title = "Delta Text Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = "Delta Settings")
poc = input.bool (defval = false, title = "Show POC", group = "POC Settings", inline = "1")
delet = input.bool (defval = false, title = "Delete Violated POCs", group = "POC Settings", inline = "1")
poctype = input.string(defval = "Regular POC", title = "POC Type", options = ["Bull & Bear POC", "Regular POC"], group = "POC Settings")
show = input.int (defval = 10, title = "POCs To Show", maxval = 500, minval = 1, group = "POC Settings")
wid = input.int (defval = 2, title = "POC Width", group = "POC Settings")
generalPOCcol = input.color (defval = color.yellow, title = "Normal POC Col", group = "POC Settings")
transp3 = input.int (defval = 25, minval = 0, maxval = 100, group = "POC Settings", title = "POC Line Transparency")
valines = input.bool (defval = false, title = "Show VA Lines", inline = "VA", group = "VA Settings"), vacol = input.color(defval = color.white, title = "", inline = "VA", group = "VA Settings")
cumu = input.float (defval = 70, title = "Value Area %", minval = 5, maxval = 95, group = "VA Settings")
vashow = input.int (defval = 20, title = "VA Lines To Show", maxval = 500, minval = 1, group = "VA Settings")
deletva = input.bool (defval = false, title = "Delete Violated VA Lines", group = "VA Settings")
transp = input.int (defval = 90, minval = 0, maxval = 100, group = "VA Settings", title = "VA Pofile Fill Transparency")
transp2 = input.int (defval = 0 , minval = 0, maxval = 100, group = "VA Settings", title = "VA Pofile Line Transparency")
transpv = input.int (defval = 95, minval = 0, maxval = 100, title = "NON VA Fill Transparency", group = "NON VA Settings")
transpv2 = input.int (defval = 70, minval = 0, maxval = 100, title = "NON VA Line Transparency", group = "NON VA Settings")
N = bar_index
show := switch poctype
"Regular POC" => show + 1
=> show * 2
type dataStore
matrix <float> timeVolMat
matrix <float> HLmat
array <int> retArr
array <line> pocs
array <line> valine
array <label> deltaLabels
map <float, float> mappedLevel
type profiles
matrix <float> tickLevelsT1
matrix <float> tickLevelsT2
matrix <float> tickLevelsT3
matrix <float> tickLevelsT4
matrix <float> tickLevelsT5
matrix <float> tickLevelsT6
matrix <float> tickLevelsT7
matrix <float> tickLevelsT8
matrix <float> tickLevelsT9
var data = dataStore.new(matrix.new<float>(2, 0), matrix.new<float>(2, 0), array.new_int(), array.new_line(), array.new_line()), //kioseff
tLevels = profiles.new( matrix.new<float>(3, ROWS, 0.0), matrix.new<float>(3, ROWS, 0.0),matrix.new<float>(3, ROWS, 0.0),matrix.new<float>(3, ROWS, 0.0),
matrix.new<float>(3, ROWS, 0.0), matrix.new<float>(3, ROWS, 0.0),matrix.new<float>(3, ROWS, 0.0),matrix.new<float>(3, ROWS, 0.0),
matrix.new<float>(3, ROWS, 0.0))
determine(a, b) =>
result = switch same
"Same Side" => a
"Middle" => b
determineLive(a, b, live) =>
result = switch live
false => a
=> b
method double_binary_search_leftmost(array <float> id, i) =>
n = id .binary_search_leftmost (data.HLmat.get(0, i))
n1 = id .binary_search_leftmost (data.HLmat.get(1, i))
[n, n1]
method double_binary_search_leftmost_delta(array <float> id, top, btm) =>
n = id .binary_search_leftmost (top)
n1 = id .binary_search_leftmost (btm)
[n, n1]
//
method effSwitch(matrix<float> id, i, x, div, subtract) =>
switch data.retArr.get(i)
1 => id.set(1, x, id.get(1, x) + data.timeVolMat.get(1, i - subtract) / div)
-1 => id.set(2, x, id.get(2, x) + data.timeVolMat.get(1, i - subtract) / div)
method drawPOC(array<line> id, startIndex, upCol, dnCol, idrow, newRowUp, newRowDn,
remove, array<float> timeRow = na, cond1 = false, int enterStart = na) =>
avg = math.round(math.avg(N, startIndex))
if remove
id.flush()
if poc
[start, end] = if not cond1
switch
same == "Middle" => [avg, N]
=> [math.max(startIndex, N - 999), N]
else
[math.max(enterStart, N - 999), N + 40]
if poctype == "Bull & Bear POC"
for i = 0 to 1
//
[arr, col] = switch
//
i == 0 => [newRowUp , upCol]
i == 1 => [newRowDn , dnCol]
y = math.avg(idrow.get(arr.indexof(arr.max())), idrow.get(math.min(arr.indexof(arr.max()) + 1, arr.size() - 1)))
id.push(line.new(x1 = start, y1 = y, x2 = end, y2 = y, color = color.new(col, transp3), width = wid))
else
for i = 0 to newRowUp.size() - 1
newRowUp.set(i, newRowUp.get(i) + newRowDn.get(i))
y = math.avg(idrow.get(newRowUp.indexof(newRowUp.max())), idrow.get(math.min(newRowUp.indexof(newRowUp.max()) + 1, idrow.size() - 1)))
id.push(line.new(x1 = start, y1 = y, x2 = end, y2 = y, color = color.new(generalPOCcol, transp3), width = wid))
method setLevels(matrix<float> id, float gety, float gety2) =>
rows = (gety2 - gety) / (ROWS - 1)
for i = 0 to ROWS - 1
id.set(0, i, gety + rows * i)
finalPoints = array.new_float(6), coordsUp = matrix.new<chart.point>(2, 0), coordsDn = matrix.new<chart.point>(2, 0)
method flushMat(matrix<chart.point> id) =>
if id.columns() > 0
for i = 0 to id.columns() - 1
id.remove_col()
method createPoly(matrix<chart.point> id, array<float> timeRow, int add, int getx2, int getx, bool cond,
array<float> idrow, array<float> lows, array<float> highs, startIndex,
color upCol, color dnCol, array<polyline> id2) =>
avg = switch cond
false => math.round(math.avg(N, startIndex))
=> N + 200
[finx, finDn, finUp] = if same != "Middle"
switch cond
false => [startIndex, idrow.min(), idrow.max()]
=> [N + 200, lows.min(), highs.max()]
else
switch cond
false => [avg, idrow.min(), idrow.max()]
=> [N + 100, lows.min(), highs.max()]
id.add_col(0,
array.from(chart.point.from_index(finx, finalPoints.get(4)) ,chart.point.from_index(finx, finalPoints.get(4))))
id.add_col(id.columns(),
array.from(chart.point.from_index(finx, finalPoints.get(5)) ,chart.point.from_index(finx, finalPoints.get(5))))
if coordsDn.columns() > 0
coordsDn.add_col(0,
array.from(chart.point.from_index(finx, finalPoints.first()) ,chart.point.from_index(finx, finalPoints.first())))
coordsDn.add_col(coordsDn.columns(),
array.from(chart.point.from_index(finx, finalPoints.get(1)) ,chart.point.from_index(finx, finalPoints.get(1))))
id2.push(polyline.new(coordsDn.row(1), fill_color = color.new(dnCol, transpv), line_color = color.new(dnCol, transpv2), curved = false))
id2.push(polyline.new(coordsDn.row(0), fill_color = color.new(upCol, transpv), line_color = color.new(upCol, transpv2), curved = false))
if coordsUp.columns() > 0
coordsUp.add_col(0,
array.from(chart.point.from_index(finx, finalPoints.get(2)) ,chart.point.from_index(finx, finalPoints.get(2))))
coordsUp.add_col(coordsUp.columns(),
array.from(chart.point.from_index(finx, finalPoints.get(3)) ,chart.point.from_index(finx, finalPoints.get(3))))
id2.push(polyline.new(coordsUp.row(1), fill_color = color.new(dnCol, transpv), line_color = color.new(dnCol, transpv2), curved = false))
id2.push(polyline.new(coordsUp.row(0), fill_color = color.new(upCol, transpv), line_color = color.new(upCol, transpv2), curved = false))
id2.push(polyline.new(id.row(1), fill_color = color.new(dnCol, transp), line_color = color.new(dnCol, transp2), curved = false))
id2.push(polyline.new(id.row(0), fill_color = color.new(upCol, transp), line_color = color.new(upCol, transp2), curved = false))
coordsDn.flushMat()
coordsUp.flushMat()
finalPoints.fill(na)
norm(newRowUp, newRowDn, oldMin, oldMax, newRange, i) =>
calcUp = 1 + ((newRowUp.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
calcDn = 1 + ((newRowDn.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
[calcUp, calcDn]
method calcDelta(array<float> id, array<float> newRowUp, array<float> newRowDn, float getY, float getY2, int middle, color upCol, color dnCol) =>
if showdel
var dsz = switch deltaSz
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
db = dataStore.new(mappedLevel = map.new<float, float>(), deltaLabels = array.new_label())
var lastdb = dataStore.new(deltaLabels = array.new_label())
var liveLab = array.new_label()
if lastdb.deltaLabels.size() > 0
for i = lastdb.deltaLabels.size() - 1 to 0
lastdb.deltaLabels.remove(i).delete()
if liveLab.size() > 0
liveLab.remove(0).delete()
newSlice = (math.max(getY, getY2) - math.min(getY, getY2)) / deltaRows
idx = switch bar_index == last_bar_index
true => lastdb.deltaLabels
=> db.deltaLabels
for i = 0 to deltaRows - 1
db.mappedLevel.put(i, 0.0)
btm = math.min(getY, getY2) + (newSlice * i)
top = math.min(getY, getY2) + (newSlice * (i + 1))
idx.push(label.new(chart.point.from_index(middle, math.avg(top, btm)),
textcolor = color.white, style = label.style_none, color = #00000000, size = dsz))
[topCol, btmCol] = id.double_binary_search_leftmost_delta(top, btm)
for x = btmCol to topCol
db.mappedLevel.put(i, db.mappedLevel.get(i) + (newRowUp.get(x) - newRowDn.get(x)))
valArr = db.mappedLevel.values(), valArr.sort(order.ascending), array <float> pos = na, array <float> neg = na
if valArr.last ().over (0)
pos := valArr.slice( valArr.binary_search_rightmost(0), valArr.size())
if valArr.first().under(0)
neg := valArr.slice(0, valArr.binary_search_leftmost (0))
for i = 0 to deltaRows - 1
col = switch math.sign(db.mappedLevel.get(i))
1 => color.from_gradient(db.mappedLevel.get(i), pos.min(), pos.max(), color.new(upCol, 50), color.new(upCol, 10))
-1 => color.from_gradient(db.mappedLevel.get(i), neg.max(), neg.min(), color.new(dnCol, 10), color.new(dnCol, 50))
=> color.new(color.white, 75)
idx.get(i).set_textcolor (col),
idx.get(i).set_text(str.tostring(db.mappedLevel.get(i), format.volume))
sumCol = switch math.sign(newRowUp.sum() - newRowDn.sum())
1 => upCol
-1 => dnCol
=> color.white
if N < last_bar_index
label.new(chart.point.from_index(middle, math.max(getY, getY2) + atr * 4),
color = #00000000,
textcolor = sumCol,
text = str.tostring(newRowUp.sum() - newRowDn.sum(), format.volume))
if N == last_bar_index
liveLab.push(label.new(chart.point.from_index(middle, math.max(getY, getY2) + atr * 4),
color = #00000000,
textcolor = sumCol,
text = str.tostring(newRowUp.sum() - newRowDn.sum(), format.volume)))
method findValue(array <float> id, id2, id3, start, idrow, id4, remove, manual) =>
copyArr = array.new_float()
for i = 0 to id2.size() - 1
copyArr.push(id2.get(i) + id3.get(i))
highest = copyArr.indexof(copyArr.max())
for i = 1 to id2.size() - 1
slice = id2.slice(math.max(highest - i, 0), math.min(highest + i + 1, id2.size()))
if slice.sum() / id2.sum() >= cumu / 100
id.set(0, math.max(highest - i, 0))
id.set(1, math.min(highest + i, id2.size() - 1))
break
if valines
if remove
id4.flush()
end = switch remove
false => N
=> manual
id4.push(
line.new(chart.point.from_index(start, idrow.get(int(id.first()))),
chart.point.from_index(end, idrow.get(int(id.first()))),
color = vacol, xloc = xloc.bar_index))
id4.push(
line.new(chart.point.from_index(start, idrow.get(int(math.min(id.get(1) + 1, idrow.size() - 1)))),
chart.point.from_index(end, idrow.get(int(math.min(id.get(1) + 1, idrow.size() - 1)))),
color = vacol, xloc = xloc.bar_index))
//
method addPoints(matrix<chart.point> id, newXUp, newXDn, startIndex, avg, i, idrow, subtract, live) =>
adjDn = switch same
"Same Side" => newXUp + (newXDn - (startIndex + 1))
=> newXDn
id.add_col(id.columns(), array.from( chart.point.from_index(math.round(newXUp), idrow.get(i)),
chart.point.from_index(math.round(adjDn), idrow.get(i) )))
id.add_col(id.columns(), array.from( chart.point.from_index(math.round(newXUp), nz(idrow.get(i + 1))),
chart.point.from_index(math.round(adjDn), nz(idrow.get(i + 1)))))
[newAvgU, newAvgD] = switch same
"Middle" => [avg - subtract, avg + subtract]
=> [startIndex + subtract, startIndex + subtract]
id.add_col(id.columns(), array.from( chart.point.from_index(newAvgU, nz(idrow.get(i + 1))),
chart.point.from_index(math.round(newXUp), nz(idrow.get(i + 1)))))
method setCoordsHistory(matrix<chart.point> id, newRowUp, newRowDn, oldMin, oldMax, newRange, timeRow, getx, getx2, idrow,
startIndex, subtract, live = false, id2, remove, manual) =>
avg = math.round(math.avg(N, startIndex)), detValue = array.from(-1, int(9e9))
start = switch same
"Same Side" => startIndex
=> avg
detValue.findValue(newRowUp, newRowDn, start, idrow, id2, remove, manual)
for i = 0 to newRowUp.size() - 2
[calcUp, calcDn] = norm(newRowUp, newRowDn, oldMin, oldMax, newRange, i)
newSwitchUp = switch same
"Middle" => avg - calcUp
=> determineLive(startIndex + calcUp, startIndex - calcUp, live)
newXUp = switch same
"Middle" => math.min(newSwitchUp, avg - 1)
=> determineLive(math.max(newSwitchUp, startIndex + 1), math.min(startIndex - 1, newSwitchUp), live)
newSwitchDn = determine(
determineLive(startIndex + calcDn, startIndex - calcDn, live),
avg + calcDn)
newXDn = determine(
determineLive(math.max(newSwitchDn, startIndex + 1), math.min(newSwitchDn, startIndex - 1), live),
math.max(newSwitchDn, avg + 1))
switch
i < detValue.first() => coordsDn.addPoints(newXUp, newXDn, startIndex, avg, i, idrow, subtract, live),
finalPoints.set(0, math.min(nz(finalPoints.first(), 9e9), idrow.get(i))),
finalPoints.set(1, math.max(nz(finalPoints.get (1), -1), idrow.get(i + 1)))
i > detValue.get(1) => coordsUp.addPoints(newXUp, newXDn, startIndex, avg, i, idrow, subtract, live),
finalPoints.set(2, math.min(nz(finalPoints.get(2), 9e9), idrow.get(i))),
finalPoints.set(3, math.max(nz(finalPoints.get(3), -1), idrow.get(i + 1)))
=> id .addPoints(newXUp, newXDn, startIndex, avg, i, idrow, subtract, live),
finalPoints.set(4, math.min(nz(finalPoints.get(4), 9e9), idrow.get(i))),
finalPoints.set(5, math.max(nz(finalPoints.get(5), -1) , idrow.get(i + 1)))
data.timeVolMat.add_col(0, array.from(time, volume))
data.HLmat .add_col(0, array.from(high, low))
data.retArr .unshift(int(math.sign(close - open)))
method update(matrix<float> id, string timeRange, bool cond, color upCol, color dnCol, string sess) =>
tim = timeTrue(timeRange), tim1 = tim[1]
if cond
change = na(tim) and tim1.equal(1)
var startIndex = 0
if tim.equal(1) and na(tim1)
startIndex := N
diff = N - startIndex
if not barstate.islast
if change
timeRow = data.timeVolMat.row(0)
highsArr = data.HLmat.row(0).slice(1, diff)
lowsArr = data.HLmat.row(1).slice(1, diff)
getx2 = N, getx = N - startIndex
gety = lowsArr.min(), gety2 = highsArr.max()
if boxed
box.new(startIndex, gety2, N - 1, gety, bgcolor = color.new(color.blue, 95), border_color = color.white,
border_style = line.style_dashed)
label.new(math.round(math.avg(startIndex, N - 1)), gety2, text = sess, textcolor = kai.hsv_gradient(0, -1, 1, upCol, dnCol),
color = #00000000, size = size.small)
id.setLevels(gety, gety2)
idrow = id.row(0)
for i = 1 to diff
[l1, l2] = idrow.double_binary_search_leftmost(i)
div = math.abs(l1 - l2) + 1
for x = l1 to l2
id.effSwitch(i, x, div, 0)
newRange = math.floor((N - startIndex) / factor)
newRowUp = id.row(1), newRowDn = id.row(2)
oldMin = math.min(newRowUp.min(), newRowDn.min())
oldMax = math.max(newRowUp.max(), newRowDn.max())
coordinates = matrix.new<chart.point>(2, 0), placeHolder = array.new<polyline>()
coordinates.setCoordsHistory(newRowUp, newRowDn, oldMin, oldMax, newRange, timeRow, getx, getx2, idrow, startIndex, 1, false, data.valine, false, int(na))
coordinates.createPoly(timeRow, diff, getx2, getx, false, idrow, na, na, startIndex, upCol, dnCol, placeHolder)
idrow .calcDelta(newRowUp, newRowDn, gety, gety2, math.round(math.avg(N, startIndex)), upCol, dnCol)
data.pocs .drawPOC(startIndex, upCol, dnCol, idrow, newRowUp, newRowDn, false, timeRow)
realtime () =>
if showLI
var timArr = array.new_int(1), var tBack = array.new_line()
//
if timeframe.change(LIT)
timArr.set(0, last_bar_index - N - 1)
tBack.flush()
tBack.push(line.new(chart.point.now(high + syminfo.mintick), chart.point.now(low), xloc = xloc.bar_time, color = #00000000, extend = extend.both))
//
if barstate.islast
timArr.set(0, timArr.first() + 1)
if tBack.size() > 1
tBack.pop().delete()
tBack.push(line.new(chart.point.now(high + syminfo.mintick), chart.point.now(low), xloc = xloc.bar_time, color = #00000000, extend = extend.both))
linefill.all.flush()
linefill.new(tBack.first(), tBack.last(), color.new(#6929F2, 95))
var pocsLive = dataStore.new(pocs = array.new_line(), valine = array.new_line())
var coordinates = matrix.new<chart.point>(2, 0), var livePoly = array.new<polyline>()
if coordinates.columns() > 0
for i = 0 to coordinates.columns() - 1
coordinates.remove_col()
if livePoly.size() > 0
for i = 0 to livePoly.size() - 1
livePoly.shift().delete()
startIndex = timArr.first()
timeRow = data.timeVolMat.row(0)
highs = data.HLmat.row(0).slice(0, startIndex + 1)
lows = data.HLmat.row(1).slice(0, startIndex + 1)
getx2 = N, getx = startIndex
newLevelsMat = matrix.new<float>(3, ROWS, 0.0)
newLevelsMat.setLevels(lows.min(), highs.max())
levelsArr = newLevelsMat.row(0)
for i = 0 to startIndex
[l1, l2] = levelsArr.double_binary_search_leftmost(i)
div = math.abs(l1 - l2) + 1
for x = l1 to l2
newLevelsMat.effSwitch(i, x, div, 0)
newRange = 80
newRowUp = newLevelsMat.row(1), newRowDn = newLevelsMat.row(2)
oldMin = math.min(newRowUp.min(), newRowDn.min())
oldMax = math.max(newRowUp.max(), newRowDn.max())
coordinates.setCoordsHistory(newRowUp, newRowDn, oldMin, oldMax, newRange, timeRow, getx, getx2, levelsArr,
N + 200, 0, true, pocsLive.valine, true, N - startIndex)
coordinates.createPoly(timeRow, na, na, na, true, na, lows, highs, N + 200, upColLI, dnColLI, livePoly)
levelsArr .calcDelta(newRowUp, newRowDn, lows.min(), highs.max(), N + 225, upColLI, dnColLI)
pocsLive.pocs.drawPOC(startIndex, upColLI, dnColLI, levelsArr, newRowUp, newRowDn, true, timeRow, true, N - timArr.first())
method keyLevelsUpdate(array<line> id, showtyp, deletyp) =>
if id.size() > 0
for i = 0 to id.size() - 1
if high < id.get(i).get_y1() or low > id.get(i).get_y1()
if id.get(i).get_x2() == N - 1
id.get(i).set_x2(N)
else if deletyp
id.get(i).delete()
if deletyp
if id.get(i).get_x2() != N
id.get(i).delete()
if barstate.islast
if id.size() > showtyp
for i = 0 to math.max(id.size() - showtyp - 1 , 0)
id.get(i).delete()
tLevels.tickLevelsT1.update(T1T, showT1, upColT1, dnColT1, t1), tLevels.tickLevelsT2.update(T2T, showT2, upColT2, dnColT2, t2)
tLevels.tickLevelsT4.update(T4T, showT4, upColT4, dnColT4, t4), tLevels.tickLevelsT3.update(T3T, showT3, upColT3, dnColT3, t3)
tLevels.tickLevelsT5.update(T5T, showT5, upColT5, dnColT5, t5), tLevels.tickLevelsT6.update(T6T, showT6, upColT6, dnColT6, t6)
tLevels.tickLevelsT4.update(T7T, showT7, upColT7, dnColT7, t7), tLevels.tickLevelsT3.update(T8T, showT8, upColT8, dnColT8, t8),
tLevels.tickLevelsT9.update(T9T, showT9, upColT9, dnColT9, t9)
realtime()
data.pocs.keyLevelsUpdate(show, delet), data.valine.keyLevelsUpdate(vashow, deletva)
|
Range Detector [LuxAlgo] | https://www.tradingview.com/script/QOuZIuvH-Range-Detector-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,432 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Range Detector [LuxAlgo]", "LuxAlgo - Range Detector", overlay = true, max_boxes_count = 500, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(20, 'Minimum Range Length', minval = 2)
mult = input.float(1., 'Range Width', minval = 0, step = 0.1)
atrLen = input.int(500, 'ATR Length', minval = 1)
//Style
upCss = input(#089981, 'Broken Upward', group = 'Style')
dnCss = input(#f23645, 'Broken Downward', group = 'Style')
unbrokenCss = input(#2157f3, 'Unbroken', group = 'Style')
//-----------------------------------------------------------------------------}
//Detect and highlight ranges
//-----------------------------------------------------------------------------{
//Ranges drawings
var box bx = na
var line lvl = na
//Extensions
var float max = na
var float min = na
var os = 0
color detect_css = na
n = bar_index
atr = ta.atr(atrLen) * mult
ma = ta.sma(close, length)
count = 0
for i = 0 to length-1
count += math.abs(close[i] - ma) > atr ? 1 : 0
if count == 0 and count[1] != count
//Test for overlap and change coordinates
if n[length] <= bx.get_right()
max := math.max(ma + atr, bx.get_top())
min := math.min(ma - atr, bx.get_bottom())
//Box new coordinates
bx.set_top(max)
bx.set_rightbottom(n, min)
bx.set_bgcolor(color.new(unbrokenCss, 80))
//Line new coordinates
avg = math.avg(max, min)
lvl.set_y1(avg)
lvl.set_xy2(n, avg)
lvl.set_color(unbrokenCss)
else
max := ma + atr
min := ma - atr
//Set new box and level
bx := box.new(n[length], ma + atr, n, ma - atr, na
, bgcolor = color.new(unbrokenCss, 80))
lvl := line.new(n[length], ma, n, ma
, color = unbrokenCss
, style = line.style_dotted)
detect_css := color.new(color.gray, 80)
os := 0
else if count == 0
bx.set_right(n)
lvl.set_x2(n)
//Set color
if close > bx.get_top()
bx.set_bgcolor(color.new(upCss, 80))
lvl.set_color(upCss)
os := 1
else if close < bx.get_bottom()
bx.set_bgcolor(color.new(dnCss, 80))
lvl.set_color(dnCss)
os := -1
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Range detection bgcolor
bgcolor(detect_css)
plot(max, 'Range Top'
, max != max[1] ? na : os == 0 ? unbrokenCss : os == 1 ? upCss : dnCss)
plot(min, 'Range Bottom'
, min != min[1] ? na : os == 0 ? unbrokenCss : os == 1 ? upCss : dnCss)
//-----------------------------------------------------------------------------} |
Gap Statistics (Zeiierman) | https://www.tradingview.com/script/O5tcQ17r-Gap-Statistics-Zeiierman/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 321 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman {
//@version=5
indicator("Gap Statistics (Zeiierman)",overlay=true,max_boxes_count=500)
//~~}
// ~~ Description {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Inputs {
// ~~ Tooltips {
var t1 = "All Gaps displays all the gaps that have been identified in historical data. This feature ensures that users can comprehensively view and analyze past occurrences of gaps, providing a complete picture of the data. \n\nActive Gaps, on the other hand, highlights only the gaps that are currently active, offering a focused view that helps users to easily identify and assess ongoing situations. \n\nSelecting None hides all gaps on the chart, creating a cleaner and more simplified visual representation of the data. This option is useful for users who prefer to analyze the chart without the visual distraction of the gap indicators."
var t2 = "Displays a label indicating the size of the gap, with customizable text color. This feature enhances the user's ability to quickly assess the magnitude of the gap, while also allowing for personalization of the display to suit individual preferences or to adhere to specific visual design standards."
//~~}
// ~~ Inputs {
// ~~ Gaps {
showGaps = input.string("Active Gaps","Display Gaps",["None","Active Gaps","All Gaps"],t1,group="Gaps")
showSize = input.bool(true,"Show Gap Size",inline="gap")
txtsize = input.string(size.small,"",[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],inline="gap")
gaptxt = input.color(color.gray,"",t2,"gap")
bullcol = input.color(color.new(#48834a, 80),"Bull Gap",inline="col")
bearcol = input.color(color.new(#cc2727, 80),"Bear Gap",inline="col")
//~~}
// ~~ Table {
pos = input.string(position.top_right, title="Position",options =[position.top_right,position.top_center,
position.top_left,position.bottom_right,position.bottom_center,position.bottom_left,position.middle_right,position.middle_left],inline="tbl")
TblSize = input.string(size.normal,title="",options=[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],inline="tbl")
frame = input.color(color.rgb(0, 0, 0),"Frame",inline="table")
bullbackgr = input.color(color.green,"BG",inline="table")
bearbackgr = input.color(color.red,"BG",inline="table")
textcol = input.color(color.black,"Text",inline="table")
//~~}
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables & Arrays {
// ~~ Variables {
b = bar_index
//~~}
// ~~ UDT's {
type Gaps
array<box> bull
array<box> bear
array<int> bullt
array<int> beart
array<int> bullbars
array<int> bearbars
array<int> bullfill
array<int> bearfill
int bulltot = 0
int beartot = 0
//~~}
// ~~ Arrays {
var g0 = Gaps.new(array.new<box>(),array.new<box>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>())
var g1 = Gaps.new(array.new<box>(),array.new<box>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>())
var g2 = Gaps.new(array.new<box>(),array.new<box>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>())
var g3 = Gaps.new(array.new<box>(),array.new<box>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>())
var g4 = Gaps.new(array.new<box>(),array.new<box>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>())
var g5 = Gaps.new(array.new<box>(),array.new<box>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>())
var gap = array.from(g0,g1,g2,g3,g4,g5)
// var gap = array.new<Gaps>(6,Gaps.new((array.new<box>(),array.new<box>(),
//array.new<int>(),array.new<int>(),array.new<int>(),array.new<int>(),
//array.new<int>(),array.new<int>()) //Doesn't work correctly
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Functions {
method NewBull(Gaps g,dist)=>
g.bulltot += 1
g.bull.unshift(box.new(b-1,open,b,close[1],showGaps!="None"?bullcol:na,
bgcolor=showGaps!="None"?bullcol:na,extend=extend.right,
text=str.tostring(dist,format.percent),text_color=showSize?gaptxt:na,text_size=txtsize,text_halign=text.align_left))
g.bullt.unshift(b)
method NewBear(Gaps g,dist)=>
g.beartot += 1
g.bear.unshift(box.new(b-1,close[1],b,open,showGaps!="None"?bearcol:na,
bgcolor=showGaps!="None"?bearcol:na,extend=extend.right,
text=str.tostring(dist,format.percent),text_color=showSize?gaptxt:na,text_size=txtsize,text_halign=text.align_left))
g.beart.unshift(b)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Main {
// ~~ Market Gaps & Storage & Alerts {
if close[1]!=open
size = math.abs(((close[1]-open)/close[1])*100)
pos = close[1]<open? 1 : -1
idx = size<0.1 ? 0 :
size >= 0.1 and size < 0.25 ? 1 :
size >= 0.25 and size < 0.5 ? 2 :
size >= 0.5 and size < 0.75 ? 3 :
size >= 0.75 and size < 1 ? 4 :
5
x = gap.get(idx)
if pos>0
x.NewBull(size)
else
x.NewBear(size)
filled = pos>0?(1-((x.bulltot-x.bullfill.sum())/x.bulltot))*100 : (1-((x.bulltot-x.bullfill.sum())/x.bulltot))*100
fillavg = pos>0?x.bullbars.avg():x.bearbars.avg()
alert("New "+(pos>0?"Bull gap ":"Bear gap (")+str.tostring(size,format.percent)+") on "+
str.tostring(syminfo.ticker)+", Filled: "+str.tostring(filled,format.percent)+
" of the time on average: "+str.tostring(math.round(fillavg))+" bars.",alert.freq_once_per_bar)
//~~}
// ~~ Check Gaps & Alerts {
for i=0 to 5
//Bullgaps
for [j,bull] in gap.get(i).bull
bot = bull.get_bottom()
if low<=bot and high>=bot
alert("Bull gap filled!",alert.freq_once_per_bar)
if showGaps=="Active Gaps"
bull.delete()
else
bull.set_right(b)
bull.set_extend(extend.none)
gap.get(i).bull.remove(j)
gap.get(i).bullfill.push(1)
getBar = gap.get(i).bullt.get(j)
gap.get(i).bullbars.unshift(b-getBar)
gap.get(i).bullt.remove(j)
//Beargaps
for [j,bear] in gap.get(i).bear
top = bear.get_top()
if high>=top and low<=top
alert("Bear gap filled!",alert.freq_once_per_bar)
if showGaps=="Active Gaps"
bear.delete()
else
bear.set_right(b)
bear.set_extend(extend.none)
gap.get(i).bear.remove(j)
gap.get(i).bearfill.push(1)
getBar = gap.get(i).beart.get(j)
gap.get(i).bearbars.unshift(b-getBar)
gap.get(i).beart.remove(j)
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plots & Outputs {
// ~~ Table {
if barstate.islast
var tbl = table.new(pos,9,7,color.gray,frame,3,frame,2)
txt = array.from("<0.1%","0.1-0.25%","0.25-0.50%","0.50-0.75%","0.75-1%",">1%")
head= array.from("","Bull Total","Bull Filled","Filled %","Bars","Bear Total","Bear Filled","Filled %","Bars")
for [i,h] in head
tbl.cell(i,0,h,text_color=color.white, text_size=TblSize, bgcolor = color.rgb(56, 80, 255))
for [i,gaps] in gap
tbl.cell(0,i+1,txt.get(i),text_color=color.white, text_size=TblSize, bgcolor = color.rgb(56, 80, 255))
bulltot = gaps.bulltot
bullfill= gaps.bullfill.sum()
tbl.cell(1,i+1,str.tostring(bulltot),text_color=textcol, text_size=TblSize, bgcolor = color.new(bullbackgr, 0))
tbl.cell(2,i+1,str.tostring(bullfill),text_color=textcol, text_size=TblSize, bgcolor = color.new(bullbackgr, 0))
tbl.cell(3,i+1,str.tostring((1-((bulltot-bullfill)/bulltot))*100,format.percent),text_size=TblSize, text_color=textcol, bgcolor = color.new(#4ad44f, 0))
tbl.cell(4,i+1,str.tostring(math.round(gaps.bullbars.avg())),text_color=textcol, text_size=TblSize, bgcolor = color.new(bullbackgr, 0))
beartot = gaps.beartot
bearfill= gaps.bearfill.sum()
tbl.cell(5,i+1,str.tostring(beartot),text_color=textcol, text_size=TblSize, bgcolor = color.new(bearbackgr,0))
tbl.cell(6,i+1,str.tostring(bearfill),text_color=textcol, text_size=TblSize, bgcolor = color.new(bearbackgr, 0))
tbl.cell(7,i+1,str.tostring((1-((beartot-bearfill)/beartot))*100,format.percent),text_size=TblSize, text_color=textcol, bgcolor = color.new(#fc6262, 0))
tbl.cell(8,i+1,str.tostring(math.round(gaps.bearbars.avg())),text_color=textcol, text_size=TblSize, bgcolor = color.new(bearbackgr, 0))
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
OTT Collection | https://www.tradingview.com/script/axJIItYE/ | dg_factor | https://www.tradingview.com/u/dg_factor/ | 314 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dg_factor [21.06.2023]
// ╠═══════════════════════════ Anıl Özekşi Library ═══════════════════════════╣
// 1) OTT [31.05.2019] Optimized Trend Tracker
// 2) TOTT [01.05.2020] Twin Ott (Ott Bands)
// 3) OTT CHANNEL [19.03.2021] Ott Channel (Half Channel & Fibonacci Channel)
// 4) RISOTTO [16.04.2021] Rsi-Ott
// 5) SOTT [18.04.2021] Stochastic Ott
// 6) HOTT-LOTT [06.03.2022] Highest-Lowest Ott & Sum Version [07.04.2022]
// 7) ROTT [19.05.2022] Relative Ott
// 8) FT [24.06.2022] "Fırsatçı Trend"
// 9) RTR [26.09.2022] Relative True Range
// "TOTTO" and "OTTO" are not included in the script.
// TOTTO and TOTT have the same calculations, the only difference is the length parameter.
// OTTO has been created by another (K. H. Alpay).
// Special thanks to Kıvanç Özbilgiç for Pine Script design and calculation examples of OTT.
//@version=5
indicator("OTT Collection", precision=2)
// ╠═════════════════════════════════ Inputs ══════════════════════════════════╣
gr_sys = "╠═══════════════ SYSTEM ══════════════╣"
system = input.string(title="System ", defval="OTT", group=gr_sys, options=
["OTT", "TOTT", "OTT CHANNEL", "RISOTTO", "SOTT", "HOTT-LOTT", "ROTT", "FT", "RTR"])
tt_p = "Enable repating signals.\n" +
"(This option allows you to display consecutive signals in the same direction for TOTT & HOTT-LOTT. " +
"It also effects the colour of bars.)"
tt_bars = "Bars option is available for :\nOTT, TOTT, OTT CHANNEL, HOTT-LOTT, FT."
pyr = input.bool(title="Pyramiding", defval=false, group=gr_sys, tooltip=tt_p)
gr_dis = "╠═══════════════ DISPLAY ══════════════╣"
sh_signal = input.bool(title="Signals ", defval=true, group=gr_dis, inline="1")
sh_bar_color = input.bool(title="Barcolor ", defval=true, group=gr_dis, inline="1")
sh_bar = input.bool(title="Bars", defval=true, group=gr_dis, inline="1", tooltip=tt_bars)
col_sup = #00bcd4
col_tar = #ff9800
col_l = #00ff00
col_s = #ff0000
col_n = #333333
// ╔═══════════════════════════════════════════════════════════════════════════╗
// ║ FUNCTIONS ║
// ╚═══════════════════════════════════════════════════════════════════════════╝
// ╠═══════════════════════════════════ VAR ═══════════════════════════════════╣
// Variable Index Dynamic Adaptive Moving Average - Tushar Chande
f_var(series float data, series int length) =>
a = ta.sma(data, length)
b = math.abs(ta.change(data, 9)) // Momentum
c = math.sum(math.abs(ta.change(data)), 9) // Volatility
d = c != 0 ? b / c : 0 // Efficiency Ratio
e = 2 / (length + 1)
r = 0.0, r := length == 1 ? data : na(r[1]) ? a : d * e * (data - nz(r[1])) + nz(r[1]) // Matriks design
// r = 0.0, r := d * e * (data - nz(r[1])) + nz(r[1]) // Output used in previously published versions on Tradingview
//
// ╠═══════════════════════════════════ OTT ═══════════════════════════════════╣
// Optimized Trend Tracker - Anıl Özekşi
f_ott(series float data, series float multiplier) =>
a = multiplier / 100
b = data * a, c = data - b, d = data + b
c := c > nz(c[1]) or data < nz(c[1]) ? c : nz(c[1])
d := d < nz(d[1]) or data > nz(d[1]) ? d : nz(d[1])
e = 0.0, e := data > nz(e[1]) ? c : data < nz(e[1]) ? d : nz(e[1]) // MOST - by Anıl Özekşi :)
f = 1 + a / 2
g = 1 - a / 2
h = data > e ? e * f : e * g
r = nz(h[2])
//
// ╔═══════════════════════════════════════════════════════════════════════════╗
// ║ CALCULATIONS ║
// ╚═══════════════════════════════════════════════════════════════════════════╝
// ╠═══════════════════════════════════ OTT ═══════════════════════════════════╣
// Inputs
string gr_ott = "╠═══════════════ OTT ════════════════╣"
ott_u = input.int(title="Length ", defval=20, step=5, group=gr_ott, tooltip="MA Length [20, 60]")
ott_k = input.float(title="Multiplier ", defval=1.5, step=0.1, group=gr_ott, tooltip="OTT Multiplier")
// Calcs
ott_support = f_var(close, ott_u)
ott_line = f_ott(ott_support, ott_k)
// Signals
ott_long = ott_support > ott_line // ta.crossover(ott_support, ott_line)
ott_short = ott_support < ott_line // ta.crossunder(ott_support, ott_line)
// ╠══════════════════════════════════ TOTT ═══════════════════════════════════╣
// Inputs
string gr_tott = "╠═══════════════ TOTT ═══════════════╣"
tott_u = input.int(title="Length ", defval=35, step=5, group=gr_tott, tooltip="MA Length [15, 45]")
tott_k1 = input.float(title="Multiplier ", defval=0.5, step=0.1, group=gr_tott, tooltip="OTT Multiplier [0.3, 0.6]")
tott_k2 = input.float(title="Band Multiplier ", defval=0.0006, step=0.0001, group=gr_tott, tooltip="[0.0004, 0.0006]")
// Calcs
tott_support = f_var(close, int(tott_u / 2))
tott_up = f_ott(f_var(tott_support, 2), tott_k1) * (1 + tott_k2)
tott_dn = f_ott(f_var(tott_support, 2), tott_k1) * (1 - tott_k2)
// Signals
tott_long = tott_support > tott_up // ta.crossover(tott_support, tott_up)
tott_short = tott_support < tott_dn // ta.crossunder(tott_support, tott_dn)
// ╠═══════════════════════════════ OTT CHANNEL ═══════════════════════════════╣
// Inputs
string gr_ottc = "╠════════════ OTT CHANNEL ════════════╣"
string ottc_t1 = "You can use this parameter to optimize '[Channel] Upper Line' manually."
string ottc_t2 = "You can use this parameter to optimize '[Channel] Lower Line' manually."
string ottc_t3 = "It is recommended to hide the channel levels to see the trends correctly while you're setting the manuel parameter optimization."
ottc_t = input.string(title="Channel Type", defval="Half Channel", options=["Half Channel", "Fibonacci Channel", "Both"], group=gr_ottc)
ottc_u = input.int(title="Length ", defval=2, group=gr_ottc, tooltip="MA Length")
ottc_k1 = input.float(title="Multiplier ", defval=1.4, group=gr_ottc, tooltip="OTT Multiplier")
ottc_k2 = input.float(title="Upper Line Multiplier", defval=0.01, step=0.01, group=gr_ottc, tooltip=ottc_t1)
ottc_k3 = input.float(title="Lower Line Multiplier", defval=0.01, step=0.01, group=gr_ottc, tooltip=ottc_t2)
ottc_h1 = input.bool(title="Hide Upper & Lower Lines", defval=false, group=gr_ottc)
ottc_h2 = input.bool(title="Hide Channel Lines", defval=false, group=gr_ottc, tooltip=ottc_t3)
// Ottc Mid Line
ottc_m = f_ott(f_var(close, ottc_u), ottc_k1)
// Channel Calcs
ottc_1 = ottc_m * (1 + ottc_k2)
ottc_2 = ottc_m * (1 + ottc_k2 * 0.618)
ottc_3 = ottc_m * (1 + ottc_k2 * 0.500)
ottc_4 = ottc_m * (1 + ottc_k2 * 0.382)
ottc_5 = ottc_m * (1 - ottc_k3 * 0.382)
ottc_6 = ottc_m * (1 - ottc_k3 * 0.500)
ottc_7 = ottc_m * (1 - ottc_k3 * 0.618)
ottc_8 = ottc_m * (1 - ottc_k3)
// Signals
// There're no any referenced conditions to generate signals for Ott Channel.
// It is recommended to use Channels as support and resistance levels.
// ╠═════════════════════════════════ RISOTTO ═════════════════════════════════╣
// Inputs
string gr_risotto = "╠═════════════ RISOTTO ═══════════════╣"
risotto_u1 = input.int(title="Length 1", defval=100, group=gr_risotto, tooltip="RSI Length")
risotto_u2 = input.int(title="Length 2", defval=50, group=gr_risotto, tooltip="MA Length")
risotto_k = input.float(title="Multiplier ", defval=0.2, group=gr_risotto, tooltip="OTT Multiplier")
// Calcs
risotto_support = f_var(ta.rsi(close, risotto_u1), risotto_u2) + 1000
risotto_line = f_ott(f_var(risotto_support, 2), risotto_k)
// Signals
risotto_long = risotto_support > risotto_line // ta.crossover(risotto_support, risotto_line)
risotto_short = risotto_support < risotto_line // ta.crossunder(risotto_support, risotto_line)
// ╠══════════════════════════════════ SOTT ═══════════════════════════════════╣
// Inputs
string gr_sott = "╠═══════════════ SOTT ═══════════════╣"
sott_u1 = input.int(title="Length 1", defval=500, group=gr_sott, tooltip="Stochastic %k Length")
sott_u2 = input.int(title="Length 2", defval=200, group=gr_sott, tooltip="Stochastic %d Length")
sott_k = input.float(title="Multiplier ", defval=0.5, group=gr_sott, tooltip="OTT Multiplier")
// Calcs
sott_support = f_var(ta.stoch(close, high, low, sott_u1), sott_u2) + 1000
sott_line = f_ott(f_var(sott_support, 2), sott_k)
// Signals
sott_long = sott_support > sott_line // ta.crossover(sott_support, sott_line)
sott_short = sott_support < sott_line // ta.crossunder(sott_support, sott_line)
// ╠═══════════════════════════════ HOTT & LOTT ═══════════════════════════════╣
// Inputs
string gr_hl = "╠════════════ HOTT & LOTT ═════════════╣"
string hl_t1 = "If you activate this option, signals will be generated according to the confirmation concept for N bars. \n\n" +
"Long : If the 'High' price is higher than Hott for N bars.\n\n" +
"Short : If the 'Low' price is lower than Lott for N bars."
hl_u = input.int(title="Length ", defval=10, step=5, group=gr_hl, tooltip="ta.highest() & ta.lowest() Length\n[10, 30]")
hl_k = input.float(title="Multiplier ", defval=0.6, step=0.1, group=gr_hl, tooltip="OTT Multiplier [0.3, 0.6]")
hl_sum = input.bool(title="Sum N bars", defval=false, group=gr_hl, inline="1")
hl_sum_n = input.int(title=" ", defval=3, group=gr_hl, inline="1", tooltip=hl_t1)
// Calcs
hott = f_ott(f_var(ta.highest(hl_u), 2), hl_k)
lott = f_ott(f_var(ta.lowest(hl_u), 2), hl_k)
// Signals
hl_long = not hl_sum ? high > hott : math.sum(high > hott ? 1 : 0, hl_sum_n) == hl_sum_n // ta.crossover(high, hott)
hl_short = not hl_sum ? low < lott : math.sum(low < lott ? 1 : 0, hl_sum_n) == hl_sum_n // ta.crossunder(low, lott)
// ╠══════════════════════════════════ ROTT ═══════════════════════════════════╣
// Inputs
string gr_rott = "╠═══════════════ ROTT ═══════════════╣"
rott_u = input.int(title="Length ", defval=200, group=gr_rott, tooltip="MA Length [100, 300]")
rott_k = input.float(title="Multiplier ", defval=1.0, group=gr_rott, tooltip="OTT Multiplier")
// Calcs
rott_support = f_var(close, rott_u) * 2
rott_line = f_ott(f_var(rott_support, 2), rott_k)
// Signals
rott_long = rott_support > rott_line // ta.crossover(rott_support, rott_line)
rott_short = rott_support < rott_line // ta.crossunder(rott_support, rott_line)
// ╠═══════════════════════════════════ FT ════════════════════════════════════╣
// Inputs
string gr_ft = "╠════════════════ FT ════════════════╣"
ft_u = input.int(title="Length ", defval=30, step=10, group=gr_ft, tooltip="MA Length [20, 40]")
ft_k1 = input.float(title="Major Multiplier", defval=3.6, group=gr_ft, tooltip="Major OTT Multiplier")
ft_k2 = input.float(title="Minor Multiplier", defval=1.8, group=gr_ft, tooltip="Minor OTT Multiplier")
// Calcs
ft_support = f_var(close, ft_u)
major_trend = f_ott(ft_support, ft_k1)
minor_trend = f_ott(ft_support, ft_k2)
ft_line = (minor_trend + (2 * minor_trend - major_trend)[100]) / 2
// Signals
ft_long = ft_support > ft_line // ta.crossover(ft_support, ft_line)
ft_short = ft_support < ft_line // ta.crossunder(ft_support, ft_line)
// ╠═══════════════════════════════════ RTR ═══════════════════════════════════╣
// Inputs
string gr_rtr = "╠═══════════════ RTR ════════════════╣"
rtr_u1 = input.int(title="Length 1", defval=10, group=gr_rtr, tooltip="ATR Length [10, 20]")
rtr_u2 = input.int(title="Length 2", defval=200, group=gr_rtr, tooltip="MA Length [200, 500]")
// Calcs
rtr_line = close / f_var(close / ta.atr(rtr_u1), rtr_u2)
// Signals
// There're no any referenced conditions to generate signals for Relative True Range.
// It is recommended to use RTR as a volatility indicator.
// ╔═══════════════════════════════════════════════════════════════════════════╗
// ║ RETURN ║
// ╚═══════════════════════════════════════════════════════════════════════════╝
// ╠═════════════════════════════ Support & Lines ═════════════════════════════╣
_support =
system == "OTT" ? ott_support :
system == "TOTT" ? tott_support :
system == "RISOTTO" ? risotto_support :
system == "SOTT" ? sott_support :
system == "ROTT" ? rott_support :
system == "FT" ? ft_support :
na
//
_target =
system == "OTT" ? ott_line :
system == "RISOTTO" ? risotto_line :
system == "SOTT" ? sott_line :
system == "ROTT" ? rott_line :
system == "FT" ? ft_line :
system == "RTR" ? rtr_line :
na
//
_line_up =
system == "TOTT" ? tott_up :
system == "HOTT-LOTT" ? hott :
na
//
_line_dn =
system == "TOTT" ? tott_dn :
system == "HOTT-LOTT" ? lott :
na
//
// ╠═════════════════════════════════ Signals ═════════════════════════════════╣
long =
system == "OTT" ? ott_long :
system == "TOTT" ? tott_long :
system == "RISOTTO" ? risotto_long :
system == "SOTT" ? sott_long :
system == "HOTT-LOTT" ? hl_long :
system == "ROTT" ? rott_long :
system == "FT" ? ft_long :
na
//
short =
system == "OTT" ? ott_short :
system == "TOTT" ? tott_short :
system == "RISOTTO" ? risotto_short :
system == "SOTT" ? sott_short :
system == "HOTT-LOTT" ? hl_short :
system == "ROTT" ? rott_short :
system == "FT" ? ft_short :
na
//
// Fix Signal
var bool l = na
var bool s = na
ls = not s and long
ss = not l and short
if ls
l := false
s := true
if ss
l := true
s := false
int dir = 0
dir := pyr ? long ? 1 : short ? -1 : 0 : ls ? 1 : ss ? -1 : nz(dir[1])
long_signal = pyr ? not long[1] and long : ls
short_signal = pyr ? not short[1] and short : ss
total_signals = ta.cum(long_signal or short_signal ? 1 : 0)
// ╠═══════════════════════════════ Plotshapes ════════════════════════════════╣
plotshape(sh_signal ? long_signal : na, "Long Signal", shape.triangleup, location.bottom, col_l, size=size.tiny)
plotshape(sh_signal ? short_signal : na, "Short Signal", shape.triangledown, location.top, col_s, size=size.tiny)
// ╠══════════════════════════ Plot Support & Lines ═══════════════════════════╣
plot(_support, color=col_sup, title="Support ")
plot(_target, color=col_tar, title="Target")
plot(_line_up, color=#00bb00, title="Upper Line")
plot(_line_dn, color=#fb0000, title="Lower Line")
// ╠══════════════════════════════ Plot Channels ══════════════════════════════╣
bool ottc_none = system != "OTT CHANNEL"
bool ottc_half = ottc_t == "Both" or ottc_t == "Half Channel"
bool ottc_fibo = ottc_t == "Both" or ottc_t == "Fibonacci Channel"
plot(ottc_none or ottc_h1 ? na : ottc_1, color=#00bb00, title="[Channel] Upper Line")
plot(ottc_none or ottc_h2 ? na : ottc_fibo ? ottc_2 : na, color=#8c00ff, title="[Channel] ⮝ 0.618")
plot(ottc_none or ottc_h2 ? na : ottc_half ? ottc_3 : na, color=#00bcd4, title="[Channel] ⮝ Half Line")
plot(ottc_none or ottc_h2 ? na : ottc_fibo ? ottc_4 : na, color=#1848cc, title="[Channel] ⮝ 0.382")
plot(ottc_none or ottc_h2 ? na : ottc_m, color=#787B86, title="[Channel] Mid Line")
plot(ottc_none or ottc_h2 ? na : ottc_fibo ? ottc_5 : na, color=#945100, title="[Channel] ⮟ 0.382")
plot(ottc_none or ottc_h2 ? na : ottc_half ? ottc_6 : na, color=#ff9800, title="[Channel] ⮟ Half Line")
plot(ottc_none or ottc_h2 ? na : ottc_fibo ? ottc_7 : na, color=#a4a600, title="[Channel] ⮟ 0.618")
plot(ottc_none or ottc_h1 ? na : ottc_8, color=#fb0000, title="[Channel] Lower Line")
// ╠════════════════════════════════ Barcolor ═════════════════════════════════╣
no_color = system == "OTT CHANNEL" or system == "RTR"
bar_color =
no_color ? na :
dir == 1 ? col_l : dir == -1 ? col_s : col_n
barcolor(sh_bar_color ? bar_color : na, title="Barcolor")
// ╠═══════════════════════════════ Plotcandle ════════════════════════════════╣
no_bars = system == "RISOTTO" or system == "SOTT" or system == "ROTT" or system == "RTR"
candle_color = close>open ? #08998175 : close<open ? #f2364575 : #33333375
plotshape(barstate.isfirst, title="╠═════ OHLC ═════╣", location=location.bottom, color=#00000000, editable=false)
plotcandle(
no_bars ? na : sh_bar ? open : na,
no_bars ? na : sh_bar ? high : na,
no_bars ? na : sh_bar ? low : na,
no_bars ? na : sh_bar ? close : na,
title="Bars", color=candle_color, bordercolor=candle_color, wickcolor=candle_color)
//
// ╠═══════════════════════════════ Parameters ════════════════════════════════╣
p_ott =
"Length : " + str.tostring(ott_u) + "\n\n" +
"Multiplier : " + str.tostring(ott_k)
p_tott =
"Length : " + str.tostring(tott_u) + "\n\n" +
"Multiplier : " + str.tostring(tott_k1) + "\n\n" +
"Band Multiplier : " + str.tostring(tott_k2)
p_ottc =
"Length : " + str.tostring(ottc_u) + "\n\n" +
"Multiplier : " + str.tostring(ottc_k1) + "\n\n" +
"Upper Line Multiplier : " + str.tostring(ottc_k2) + "\n\n" +
"Lower Line Multiplier : " + str.tostring(ottc_k3)
p_risotto =
"Rsi Length : " + str.tostring(risotto_u1) + "\n\n" +
"Ott Length : " + str.tostring(risotto_u2) + "\n\n" +
"Multplier : " + str.tostring(risotto_k)
p_sott =
"Stochastic %k Length : " + str.tostring(sott_u1) + "\n\n" +
"Stochastic %d Length : " + str.tostring(sott_u2) + "\n\n" +
"Multplier : " + str.tostring(sott_k)
pp_sum =
hl_sum ? "Sum Option : On" + "\n\n" + "Sum N Bars : " + str.tostring(hl_sum_n) : ""
p_hl =
"Length : " + str.tostring(hl_u) + "\n\n" +
"Multiplier : " + str.tostring(hl_k) + "\n\n" +
pp_sum
p_rott =
"Length : " + str.tostring(rott_u)+ "\n\n" +
"Multiplier : " + str.tostring(rott_k)
p_ft =
"Length : " + str.tostring(ft_u) + "\n\n" +
"Major Multiplier : " + str.tostring(ft_k1) + "\n\n" +
"Minor Multiplier : " + str.tostring(ft_k2)
p_rtr =
"Atr Length : " + str.tostring(rtr_u1) + "\n\n" +
"Var Length : " + str.tostring(rtr_u2)
//
parameter =
system == "OTT" ? p_ott :
system == "TOTT" ? p_tott :
system == "OTT CHANNEL" ? p_ottc :
system == "RISOTTO" ? p_risotto :
system == "SOTT" ? p_sott :
system == "HOTT-LOTT" ? p_hl :
system == "ROTT" ? p_rott :
system == "FT" ? p_ft :
system == "RTR" ? p_rtr :
na
//
// ╠══════════════════════════════════ Table ══════════════════════════════════╣
var tb = table.new(position.top_right, 1, 10)
if barstate.islast
table.cell(tb, 0, 0, ottc_none ? "\n\n" + system : "\n\n" + system + "\n\n[" + ottc_t + "]", text_color=color.blue, text_halign=text.align_left)
table.cell(tb, 0, 1, parameter, text_color=#686868, text_halign=text.align_left)
table.cell(tb, 0, 2, "\n\nChart Info", text_color=color.blue, text_halign=text.align_left)
table.cell(tb, 0, 3, "Bars : " + str.tostring(bar_index + 1), text_color=#686868, text_halign=text.align_left)
table.cell(tb, 0, 4, "Signals : " + str.tostring(total_signals), text_color=#686868, text_halign=text.align_left)
//
// Direction
plot(dir, title="Direction", display=display.data_window, editable=false)
// Bitti :)
plotshape(barstate.isfirst, title="@ dg_factor", location=location.bottom, color=#00000000, editable=false)
|
Opening Range Gaps [TFO] | https://www.tradingview.com/script/jAYmTrqZ-Opening-Range-Gaps-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 279 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeforopp
//@version=5
indicator("Opening Range Gaps [TFO]", "Opening Range Gaps [TFO]", true, max_boxes_count = 500, max_lines_count = 500)
var g_SET = "Settings"
session = input.session("1600-0930", "Gap Session", tooltip = "The window of time from which the gap will be derived", group = g_SET)
gap_up_color = input.color(color.new(color.blue, 80), "Gap Colors", inline = "RG", group = g_SET)
gap_dn_color = input.color(color.new(color.red, 80), "", inline = "RG", group = g_SET)
delineations = input.bool(true, "Show Session Delineations", inline = "SD", tooltip = "Vertical lines will mark the gap session start and end times", group = g_SET)
del_color = input.color(color.black, "", inline = "SD", group = g_SET)
track = input.bool(true, "Track Start Price", tooltip = "Track the price that indicates the beginning of a gap (previous session close)", group = g_SET)
ext = input.bool(false, "Extend Boxes", tooltip = "Extend gaps the right of the chart", group = g_SET)
keep_last = input.int(10, "Keep Last", 1, tooltip = "Delete drawings beyond this number of sessions ago", group = g_SET)
tf_limit = input.timeframe("30", "Timeframe Limit", tooltip = "Drawings will not show on timeframes greater than this", group = g_SET)
var box[] eth = array.new_box()
var line[] start = array.new_line()
var line[] q1 = array.new_line()
var line[] q2 = array.new_line()
var line[] q3 = array.new_line()
var line[] DL = array.new_line()
t = not na(time("", session, "America/New_York"))
if timeframe.in_seconds() <= timeframe.in_seconds(tf_limit)
if t and not t[1]
if eth.size() > 0
eth.get(0).set_right(time)
q1.get(0).set_x2(time)
q2.get(0).set_x2(time)
q3.get(0).set_x2(time)
eth.unshift(box.new(time, close[1], time, close[1], xloc = xloc.bar_time, bgcolor = na, border_color = na, extend = ext ? extend.right : extend.none))
start.unshift(line.new(time, close[1], time, close[1], xloc = xloc.bar_time, color = na, style = line.style_dotted, extend = ext ? extend.right : extend.none))
q1.unshift(line.new(time, close[1], time, close[1], xloc = xloc.bar_time, color = na, style = line.style_dashed, extend = ext ? extend.right : extend.none))
q2.unshift(line.new(time, close[1], time, close[1], xloc = xloc.bar_time, color = na, style = line.style_solid, extend = ext ? extend.right : extend.none))
q3.unshift(line.new(time, close[1], time, close[1], xloc = xloc.bar_time, color = na, style = line.style_dashed, extend = ext ? extend.right : extend.none))
if delineations
DL.unshift(line.new(time, high, time, low, xloc = xloc.bar_time, extend = extend.both, color = del_color, style = line.style_dotted))
else if not t and t[1]
eth.get(0).set_left(time)
if track
start.get(0).set_x2(time)
start.get(0).set_color(del_color)
q1.get(0).set_x1(time)
q2.get(0).set_x1(time)
q3.get(0).set_x1(time)
eth.get(0).set_top(open > eth.get(0).get_top() ? open : eth.get(0).get_top())
eth.get(0).set_bottom(open < eth.get(0).get_top() ? open : eth.get(0).get_bottom())
top = eth.get(0).get_top()
bottom = eth.get(0).get_bottom()
h = (top - bottom)
qr = h / 4
q1.get(0).set_y1(top - qr * 1)
q2.get(0).set_y1(top - qr * 2)
q3.get(0).set_y1(top - qr * 3)
q1.get(0).set_y2(top - qr * 1)
q2.get(0).set_y2(top - qr * 2)
q3.get(0).set_y2(top - qr * 3)
if delineations
DL.unshift(line.new(time, high, time, low, xloc = xloc.bar_time, extend = extend.both, color = del_color, style = line.style_dotted))
box_color = top > start.get(0).get_y1() ? gap_up_color : gap_dn_color
line_color = top > start.get(0).get_y1() ? color.new(gap_up_color, 0) : color.new(gap_dn_color, 0)
eth.get(0).set_bgcolor(box_color)
eth.get(0).set_border_color(box_color)
q1.get(0).set_color(line_color)
q2.get(0).set_color(line_color)
q3.get(0).set_color(line_color)
if eth.size() > keep_last
box.delete(eth.pop())
if track
line.delete(start.pop())
line.delete(q1.pop())
line.delete(q2.pop())
line.delete(q3.pop())
if delineations
line.delete(DL.pop())
line.delete(DL.pop())
if not t
if eth.size() > 0
eth.get(0).set_right(time)
q1.get(0).set_x2(time)
q2.get(0).set_x2(time)
q3.get(0).set_x2(time)
if t
if eth.size() > 0 and track
start.get(0).set_x2(time) |
Order Blocks W/ Realtime Fibs [QuantVue] | https://www.tradingview.com/script/JU3WaXGC-Order-Blocks-W-Realtime-Fibs-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 374 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © QuantVue
//@version=5
indicator("Order Blocks W/ Realtime Fibs [QuantVue]", overlay = true, max_lines_count = 500, max_labels_count = 500)
//----------settings----------//
var g0 = 'Order Block Settings'
barsReq = input.int(6, 'Consecutive Bars Required', group = g0, tooltip = 'The number of bars required after the last bullish or bearish bar to validate an order block')
percGain = input.float(0.0, 'Percent Gain Required', step = 0.1, group = g0, tooltip = 'The minimum percent gain or loss of the consecutive bars required to validate an order block')
opposites = input.bool(false, 'Require Opposite Order Block', group = g0, tooltip = 'Requires an order block in the opposite direction of the previous order block before a new order block is marked')
mitType = input.string('Wicks', 'Mitigation Type', ['Wicks', 'Close'])
irrOb = input.string('Length', 'Irrelevant Order Block ', ['Length', 'Distance'], group = g0, tooltip = 'Method for considering Order Blocks irrelevant. Either too long (length) or too far away from current price (distance)')
maxObLen = input.int(150, 'Max Ob Length or Distance', group = g0, tooltip = 'Maximum bar length or % distance away from Order Block to be considered irrelevant')
var g1 = 'Order Block Display Settings'
showOb = input.bool(true, 'Show Order Blocks', group = g1)
hideOld = input.bool(false, 'Remove Old or Irrelevant Order Blocks', group = g1)
bullCol = input.color(color.new(color.green,85), 'Bullish Color', group = g1)
bearCol = input.color(color.new(color.red,85), 'Bearish Color', group = g1)
var g2 = 'Fibs'
showFibs = input.bool(true, 'Show Fibs', group = g2)
retraceMax = input.bool(true,'Stop Fib Recalculation After Retracement', group = g2, tooltip = 'Will stop fibs from recalculating when a new high or low is made, if the retracement level has been hit')
retracelev = input.string('Order Block', 'Rectracement Level', ['Order Block', '.50', '.618', '.786'], group = g2)
fibStyle = input.string('Dashed', 'Line style ', options = ['Dashed', 'Dotted', 'Solid'], group = g2, inline = '2')
extLines = input.bool(false, 'Extend', group = g2, inline = '2')
textColor = input.color(color.rgb(255, 253, 253), 'Fib Label Color', group = g2)
show_236 = input.bool(true, '.236', inline = '3', group = g2)
color_236 = input.color(#c2c5ce, '', inline = '3', group = g2)
show_382 = input.bool(true, '.382', inline = '3', group = g2)
color_382 = input.color(#c2c5ce, '', inline = '3', group = g2)
show_50 = input.bool(true, '.50', inline = '3', group = g2)
color_50 = input.color(#c2c5ce, '', inline = '3', group = g2)
show_618 = input.bool(true, '.618', inline = '4', group = g2)
color_618 = input.color(#00ccff, '', inline = '4', group = g2)
show_786 = input.bool(true, '.786', inline = '4', group = g2)
color_786 = input.color(#c2c5ce, '', inline = '4', group = g2)
show_hl = input.bool(true, '0 & 1', inline = '4', group = g2)
color_hl = input.color(#c2c5ce, '', inline = '4', group = g2)
//----------types----------//
type obFibs
bool a = true
bool bull = true
int idx
float l
float h
float chl
bool ret = false
float [] levArr
line [] lineArr
label [] labArr
label retLab
type obBox
bool a = true
bool bull = true
float top
float bottom
box bx
//----------switch----------//
method switcher(string this) =>
switch this
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
//----------variables----------//
var obFibsArr = array.new<obFibs>()
var obBoxArr = array.new<obBox>()
var fibBoolArr = array.from(show_hl, show_hl, show_236, show_382, show_50, show_618, show_786)
var fibColArr = array.from(color_hl, color_hl, color_236, color_382, color_50, color_618, color_786)
var fibLevArr = array.from('0', '1', '.236', '.382', '.50', '.618', '.786')
var bu = false
var be = false
barsCount = 0
lines = line.all
labels = label.all
//----------calculations----------//
if irrOb == 'Distance'
maxObLen := maxObLen / 100
gainBull = ((math.abs(low[barsReq] - close))/low[barsReq]) * 100
gainBear = ((math.abs(high[barsReq] - close))/high[barsReq]) * 100
gainCheck = gainBull >= percGain or gainBear >= percGain
lastDown = close[barsReq] < open[barsReq]
lastUp = close[barsReq] > open[barsReq]
if lastDown
for i = 0 to barsReq
if close[i] > open[i]
barsCount += 1
if lastUp
for i = 0 to barsReq
if close[i] < open[i]
barsCount += 1
//----------conditions----------//
bullish = lastDown and barsCount >= barsReq and gainCheck and (opposites ? not bu : not bu or bu)
bearish = lastUp and barsCount >= barsReq and gainCheck and (opposites ? not be : not be or be)
if bullish
for l in lines
l.delete()
for l in labels
l.delete()
bu := true
be := false
fibTotal = high - low[barsReq]
lev236 = high - (fibTotal * .236)
lev382 = high - (fibTotal * .382)
lev50 = high - (fibTotal * .5)
lev618 = high - (fibTotal * .618)
lev786 = high - (fibTotal * .786)
newFibs = obFibs.new(true, true, bar_index[barsReq], low[barsReq], high[barsReq], high, false, array.from(high, low[barsReq], lev236, lev382, lev50, lev618, lev786), array.new<line>(), array.new<label>())
if showFibs
for i = 0 to newFibs.levArr.size()-1
if fibBoolArr.get(i) == true
newFibs.lineArr.unshift(line.new(newFibs.idx, newFibs.levArr.get(i), bar_index, newFibs.levArr.get(i), color = fibColArr.get(i), extend = extLines ? extend.right : extend.none, style = fibStyle.switcher()))
newFibs.labArr.unshift(label.new(newFibs.idx, newFibs.levArr.get(i), str.tostring(fibLevArr.get(i)) + ' ($' + str.tostring(newFibs.levArr.get(i), format.mintick) + ')', color=color.new(color.white,100), style = label.style_label_right, textcolor = textColor))
obFibsArr.unshift(newFibs)
if showOb
obBoxArr.unshift(obBox.new(true, true, high[barsCount], low[barsReq], box.new(bar_index[barsReq], high[barsReq], bar_index, low[barsReq], bullCol, bgcolor = bullCol)))
alert('New Bullish Order Block', alert.freq_once_per_bar_close)
if bearish
for l in lines
l.delete()
for l in labels
l.delete()
be := true
bu := false
fibTotal = high[barsReq] - low
lev236 = low + (fibTotal * .236)
lev382 = low + (fibTotal * .382)
lev50 = low +(fibTotal * .5)
lev618 = low + (fibTotal * .618)
lev786 = low + (fibTotal * .786)
newFibs = obFibs.new(true, false, bar_index[barsReq], low[barsReq], high[barsReq], low, false, array.from(low, high[barsReq], lev236, lev382, lev50, lev618, lev786), array.new<line>(), array.new<label>())
if showFibs
for i = 0 to newFibs.levArr.size()-1
if fibBoolArr.get(i) == true
newFibs.lineArr.unshift(line.new(newFibs.idx, newFibs.levArr.get(i), bar_index, newFibs.levArr.get(i), color = fibColArr.get(i), extend = extLines ? extend.right : extend.none, style = fibStyle.switcher()))
newFibs.labArr.unshift(label.new(newFibs.idx, newFibs.levArr.get(i), str.tostring(fibLevArr.get(i)) + ' ($' + str.tostring(newFibs.levArr.get(i), format.mintick) + ')', color=color.new(color.white,100), style = label.style_label_right, textcolor = textColor))
obFibsArr.unshift(newFibs)
if showOb
obBoxArr.unshift(obBox.new(true, false, high[barsCount], low[barsReq], box.new(bar_index[barsReq], high[barsReq], bar_index, low[barsReq], bearCol, bgcolor = bearCol)))
alert('New Bearish Order Block', alert.freq_once_per_bar_close)
//----------fib management----------//
if obFibsArr.size() > 0
for b in obFibsArr
if b.a
for l in b.lineArr
l.set_x2(bar_index)
if b.bull
retlev = retracelev == 'Order Block' ? b.h : retracelev == '.50' ? b.levArr.get(4) : retracelev == '.618' ? b.levArr.get(5) : b.levArr.get(6)
if low <= retlev and retraceMax and not b.ret
b.ret := true
b.retLab := label.new(bar_index,low,'🔺', style=label.style_none, yloc = yloc.belowbar)
alert('Retracement Level Hit', alert.freq_once_per_bar)
if high > b.chl and not b.ret
b.chl := high
fibTotal = b.chl - b.l
lev236 = b.chl - (fibTotal * .236)
lev382 = b.chl - (fibTotal * .382)
lev50 = b.chl - (fibTotal * .5)
lev618 = b.chl - (fibTotal * .618)
lev786 = b.chl - (fibTotal * .786)
b.levArr := array.from(b.chl, b.l, lev236, lev382, lev50, lev618, lev786)
for l in b.lineArr
l.delete()
for l in b.labArr
l.delete()
if showFibs
for i = 0 to b.levArr.size()-1
if fibBoolArr.get(i) == true
b.lineArr.unshift(line.new(b.idx, b.levArr.get(i), bar_index, b.levArr.get(i), color = fibColArr.get(i), extend = extLines ? extend.right : extend.none, style = fibStyle.switcher()))
b.labArr.unshift(label.new(b.idx, b.levArr.get(i), str.tostring(fibLevArr.get(i)) + ' ($' + str.tostring(b.levArr.get(i), format.mintick) + ')', color=color.new(color.white,100), style = label.style_label_right, textcolor = textColor))
if (be and not be[1] and opposites) or (close < b.l) or (bullish and bar_index > b.idx + barsReq and not opposites) or (retraceMax and high > b.chl)
b.a := false
if (bullish and bar_index > b.idx + barsReq and not opposites)
for l in b.lineArr
l.delete()
for l in b.labArr
l.delete()
if not b.bull
retlev = retracelev == 'Order Block' ? b.h : retracelev == '.50' ? b.levArr.get(4) : retracelev == '.618' ? b.levArr.get(5) : b.levArr.get(6)
if high >= retlev and retraceMax and not b.ret
b.ret := true
b.retLab := label.new(bar_index,low,'🔻', style=label.style_none, yloc = yloc.abovebar)
alert('Retracement Level Hit', alert.freq_once_per_bar)
if low < b.chl and not b.ret
b.chl := low
fibTotal = b.h - b.chl
lev236 = b.chl + (fibTotal * .236)
lev382 = b.chl + (fibTotal * .382)
lev50 = b.chl +(fibTotal * .5)
lev618 = b.chl + (fibTotal * .618)
lev786 = b.chl + (fibTotal * .786)
b.levArr := array.from(b.chl, b.h, lev236, lev382, lev50, lev618, lev786)
for l in b.lineArr
l.delete()
for l in b.labArr
l.delete()
if showFibs
for i = 0 to b.levArr.size()-1
if fibBoolArr.get(i) == true
b.lineArr.unshift(line.new(b.idx, b.levArr.get(i), bar_index, b.levArr.get(i), color = fibColArr.get(i), extend = extLines ? extend.right : extend.none, style = fibStyle.switcher()))
b.labArr.unshift(label.new(b.idx, b.levArr.get(i), str.tostring(fibLevArr.get(i)) + ' ($' + str.tostring(b.levArr.get(i), format.mintick) + ')', color=color.new(color.white,100), style = label.style_label_right, textcolor = textColor))
if (bu and not bu[1] and opposites) or (close > b.h) or (bearish and bar_index > b.idx + barsReq and not opposites) or (retraceMax and low < b.chl)
b.a := false
if (bearish and bar_index > b.idx + barsReq and not opposites)
for l in b.lineArr
l.delete()
for l in b.labArr
l.delete()
//----------order block management----------//
if obBoxArr.size() > 0
for bx in obBoxArr
if bx.a
bx.bx.set_right(bar_index)
if bx.bull
src = mitType == 'Wicks' ? low : close
if src <= bx.bx.get_top() or (irrOb == 'Length' and bar_index - bx.bx.get_left() > maxObLen-1 or irrOb == 'Distance' and low >= bx.bx.get_top()*(1+maxObLen))
bx.a := false
if hideOld
bx.bx.delete()
else if not bx.bull
src = mitType == 'Wicks' ? high : close
if src >= bx.bx.get_bottom() or (irrOb == 'Length' and bar_index - bx.bx.get_left() > maxObLen-1 or irrOb == 'Distance' and high <= bx.bx.get_bottom()*(1-maxObLen))
bx.a := false
if hideOld
bx.bx.delete()
|
ZigLib | https://www.tradingview.com/script/NC3cgEcT-ZigLib/ | DevLucem | https://www.tradingview.com/u/DevLucem/ | 14 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DevLucem
//@version=5
library("ZigLib", overlay=true)
export zigzag (float _low=low, float _high=high, int depth=12, int deviation=5, int backstep=2) =>
hr = ta.barssince(not (_high[-ta.highestbars(depth)] - _high > deviation*syminfo.mintick)[1])
lr = ta.barssince(not (_low - _low[-ta.lowestbars(depth)] > deviation*syminfo.mintick)[1])
direction = ta.barssince(not (hr > lr)) >= backstep? -1: 1
var chart.point z = chart.point.now(_low)
var chart.point z1 = chart.point.now(_low)
var chart.point z2 = chart.point.now(_high)
if ta.change(direction)
z1 := z2.copy()
z2 := z.copy()
if direction>0
if _high > z2.price
z2 := chart.point.now(_high)
z := chart.point.now(_low)
if _low < z.price
z := chart.point.now(_low)
if direction<0
if _low < z2.price
z2 := chart.point.now(_low)
z := chart.point.now(_high)
if _high > z.price
z := chart.point.now(_high)
[direction, z1, z2]
[direction, z1, z2] = request.security(syminfo.tickerid, input.timeframe("240", "Resolution"), zigzag())
bgcolor(direction<0? color.rgb(255, 82, 82, 80): color.rgb(0, 230, 119, 80))
line zz = line.new(z1.time, z1.price, z2.time, z2.price, xloc.bar_time, width=3)
if direction==direction[1]
line.delete(zz[1]) |
math | https://www.tradingview.com/script/Zl2T92EU-math/ | facejungle | https://www.tradingview.com/u/facejungle/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © facejungle
//@version=5
// @description TODO: add library description here
library("math", true)
export pine_ema(float src, int length) =>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
export pine_dema(float src, int length) =>
ema = pine_ema(src, length)
2 * ema - pine_ema(ema, length)
export pine_tema(float src, int length) =>
ema = pine_ema(src, length)
3 * (ema - pine_ema(ema, length)) + pine_ema(pine_ema(ema, length), length)
export pine_sma(float src, int length) =>
sum = 0.0
for i = 0 to length - 1
sum := sum + src[i] / length
sum
export pine_smma(float src, int length) =>
sum = 0.0
sma = pine_sma(src, length)
na(sum[1]) ? sma : (sum[1] * (length - 1) + src) / length
export pine_ssma(float src, int length) =>
a1 = math.exp(-1.414*3.14159 / length)
b1 = 2*a1*math.cos(1.414*3.14159 / length)
c2 = b1
c3 = (-a1)*a1
c1 = 1 - c2 - c3
sum = 0.0
sum := c1*(src + nz(src[1])) / 2 + c2*nz(sum[1]) + c3*nz(sum[2])
export pine_rma(float src, int length) =>
alpha = 1/length
sum = 0.0
sma = pine_sma(src, length)
sum := na(sum[1]) ? sma : alpha * src + (1 - alpha) * nz(sum[1])
export pine_wma(float x, int y) =>
norm = 0.0
sum = 0.0
for i = 0 to y - 1
weight = (y - i) * y
norm := norm + weight
sum := sum + x[i] * weight
sum / norm
export pine_hma(float src, int length) =>
pine_wma(2 * pine_wma(src, length / 2) - pine_wma(src, length), math.round(math.sqrt(length)))
export pine_vwma(float x, int y) =>
pine_sma(x * volume, y) / ta.sma(volume, y)
export pine_swma(float x) =>
x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6
export pine_alma(float src, int length, float offset, float sigma) =>
m = math.floor(offset * (length - 1))
s = length / sigma
norm = 0.0
sum = 0.0
for i = 0 to length - 1
weight = math.exp(-1 * math.pow(i - m, 2) / (2 * math.pow(s, 2)))
norm := norm + weight
sum := sum + src[length - i - 1] * weight
sum / norm
|
MTF_Drawings | https://www.tradingview.com/script/Z9h7F6nt-MTF-Drawings/ | Spacex_trader | https://www.tradingview.com/u/Spacex_trader/ | 3 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Spacex_trader
//@version=5
// @description This library helps with drawing indicators and candle charts on all timeframes.
library('MTF_Drawings', overlay = true)
//
// CANDLE DRAWING
//
// @function Populates two arrays with drawing data of the HTF candles.
// @param BarsBack Bars number to display.
// @param BodyBear Candle body bear color.
// @param BodyBull Candle body bull color.
// @param BordersBear Candle border bear color.
// @param BordersBull Candle border bull color.
// @param WickBear Candle wick bear color.
// @param WickBull Candle wick bull color.
// @param LineStyle Wick style (Solid-Dotted-Dashed).
// @param BoxStyle Border style (Solid-Dotted-Dashed).
// @param LineWidth Wick width.
// @param HTF_Open HTF open price.
// @param HTF_High HTF high price.
// @param HTF_Low HTF low price.
// @param HTF_Close HTF close price.
// @param HTF_Bar_Index HTF bar_index.
// @returns Two arrays with drawing data of the HTF candles.
export HTF_Candle(int BarsBack, color BodyBear, color BodyBull, color BordersBear, color BordersBull, color WickBear, color WickBull, string LineStyle, string BoxStyle, int LineWidth, float HTF_Open, float HTF_High, float HTF_Low, float HTF_Close, int HTF_Bar_Index) =>
var box[] Box = array.new<box>(0)
var line[] Line = array.new<line>(0)
[Body, Border, Wick] = if HTF_Close < HTF_Open
[BodyBear, BordersBear, WickBear]
else
[BodyBull, BordersBull, WickBull]
if HTF_Bar_Index[1] != HTF_Bar_Index
Box.unshift(box.new(na, HTF_Close, na, HTF_Open, Border, border_style = BoxStyle, bgcolor = Body))
Line.unshift(line.new(na, HTF_High, na, HTF_Low, color = Wick, style = LineStyle, width = LineWidth))
if Box.size() > 0
Box.get(0).set_top(HTF_Close)
Box.get(0).set_bottom(HTF_Open)
Line.get(0).set_y1(HTF_High)
Line.get(0).set_y2(HTF_Low)
if Box.size() > BarsBack
box.delete(Box.pop())
line.delete(Line.pop())
[Box, Line]
// @function Populates two arrays with drawing data of the LTF candles.
// @param BarsBack Bars number to display.
// @param BodyBear Candle body bear color.
// @param BodyBull Candle body bull color.
// @param BordersBear Candle border bear color.
// @param BordersBull Candle border bull color.
// @param WickBear Candle wick bear color.
// @param WickBull Candle wick bull color.
// @param LineStyle Wick style (Solid-Dotted-Dashed).
// @param BoxStyle Border style (Solid-Dotted-Dashed).
// @param LineWidth Wick width.
// @param LTF_Open LTF open price.
// @param LTF_High LTF high price.
// @param LTF_Low LTF low price.
// @param LTF_Close LTF close price.
// @returns Two arrays with drawing data of the LTF candles.
export LTF_Candle(int BarsBack, color BodyBear, color BodyBull, color BordersBear, color BordersBull, color WickBear, color WickBull, string LineStyle, string BoxStyle, int LineWidth, float[] LTF_Open, float[] LTF_High, float[] LTF_Low, float[] LTF_Close) =>
var box[] Box = array.new<box>(0)
var line[] Line = array.new<line>(0)
for i = 0 to LTF_Open.size() > 0 ? LTF_Open.size() - 1 : na by 1
[Body, Border, Wick] = if LTF_Close.get(i) < LTF_Open.get(i)
[BodyBear, BordersBear, WickBear]
else
[BodyBull, BordersBull, WickBull]
Box.unshift(box.new(na, LTF_Close.get(i), na, LTF_Open.get(i), Border, border_style = BoxStyle, bgcolor = Body))
Line.unshift(line.new(na, LTF_High.get(i), na, LTF_Low.get(i), color = Wick, style = LineStyle, width = LineWidth))
if Box.size() > BarsBack
box.delete(Box.pop())
line.delete(Line.pop())
[Box, Line]
// @function Draws HTF or LTF candles.
// @param Box Box array with drawing data.
// @param Line Line array with drawing data.
// @param Offset Offset of the candles.
// @returns Drawing of the candles.
export Draw_Candle(box[] Box, line [] Line, int Offset) =>
if barstate.islast
for i = 0 to Box.size() > 0 ? Box.size() - 1 : na by 1
Box.get(i).set_left(bar_index - i * 3 - 1 + Offset)
Box.get(i).set_right(bar_index - i * 3 + 1 + Offset)
Line.get(i).set_x1(bar_index - i * 3 + Offset)
Line.get(i).set_x2(bar_index - i * 3 + Offset)
[Box, Line]
//
// INDICATOR DRAWING
//
//
// SINGLE LINE
//
// @function Populates one array with drawing data of the HTF indicator.
// @param IndValue Indicator value.
// @param BarsBack Indicator lines to display.
// @param IndColor Indicator color.
// @param HTF_Bar_Index HTF bar_index.
// @returns An array with drawing data of the HTF indicator.
export Populate_HTF_Ind(float IndValue, int BarsBack, color IndColor, int HTF_Bar_Index) =>
var line[] Line = array.new<line>(0)
if HTF_Bar_Index[1] != HTF_Bar_Index
Line.unshift(line.new(na, na, na, IndValue, color = IndColor, width = 1))
if Line.size() > 0
Line.get(0).set_y2(IndValue)
if Line.size() > BarsBack + 1
line.delete(Line.pop())
Line
// @function Populates one array with drawing data of the LTF indicator.
// @param IndValue Indicator value.
// @param BarsBack Indicator lines to display.
// @param IndColor Indicator color.
// @returns An array with drawing data of the LTF indicator.
export Populate_LTF_Ind(float[] IndValue, int BarsBack, color IndColor) =>
var line[] Line = array.new<line>(0)
for i = 0 to IndValue.size() > 0 ? IndValue.size() - 1 : na by 1
Line.unshift(line.new(na, na, na, IndValue.get(i), color = IndColor, width = 1))
if Line.size() > BarsBack + 1
line.delete(Line.pop())
Line
// @function Draws one HTF or LTF indicator.
// @param Line Line array with drawing data.
// @param Mult Coordinates multiplier.
// @param Exe Display the indicator.
// @returns Drawing of the indicator.
export Draw_Ind(line[] Line, int Mult, bool Exe) =>
if Exe and barstate.islast
for i = 1 to Line.size() > 0 ? Line.size() - 1 : na by 1
Line.get(i).set_x1(bar_index - i * Mult + Mult)
Line.get(i).set_x2(bar_index - i * Mult)
Line.get(i).set_y1(Line.get(i - 1).get_y2())
Line
//
// DOUBLE LINE
//
// @function Populates two arrays with drawing data of the HTF indicators.
// @param IndValue_1 First indicator value.
// @param IndValue_2 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param IndColor_1 First indicator color.
// @param IndColor_2 Second indicator color.
// @param HTF_Bar_Index HTF bar_index.
// @returns Two arrays with drawing data of the HTF indicators.
export Populate_HTF_Ind_D(float IndValue_1, float IndValue_2, int BarsBack, color IndColor_1, color IndColor_2, int HTF_Bar_Index) =>
var line[] Line_1 = array.new<line>(0)
var line[] Line_2 = array.new<line>(0)
if HTF_Bar_Index[1] != HTF_Bar_Index
Line_1.unshift(line.new(na, na, na, IndValue_1, color = IndColor_1, width = 1))
Line_2.unshift(line.new(na, na, na, IndValue_2, color = IndColor_2, width = 1))
if Line_1.size() > 0
Line_1.get(0).set_y2(IndValue_1)
Line_2.get(0).set_y2(IndValue_2)
if Line_2.size() > BarsBack + 1
line.delete(Line_1.pop())
line.delete(Line_2.pop())
[Line_1, Line_2]
// @function Populates two arrays with drawing data of the LTF indicators.
// @param IndValue_1 First indicator value.
// @param IndValue_2 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param IndColor_1 First indicator color.
// @param IndColor_2 Second indicator color.
// @returns Two arrays with drawing data of the LTF indicators.
export Populate_LTF_Ind_D(float[] IndValue_1, float[] IndValue_2, int BarsBack, color IndColor_1, color IndColor_2) =>
var line[] Line_1 = array.new<line>(0)
var line[] Line_2 = array.new<line>(0)
for i = 0 to IndValue_1.size() > 0 ? IndValue_2.size() - 1 : na by 1
Line_1.unshift(line.new(na, na, na, IndValue_1.get(i), color = IndColor_1, width = 1))
Line_2.unshift(line.new(na, na, na, IndValue_2.get(i), color = IndColor_2, width = 1))
if Line_2.size() > BarsBack + 1
line.delete(Line_1.pop())
line.delete(Line_2.pop())
[Line_1, Line_2]
// @function Draws two LTF or HTF indicators.
// @param Line_1 First line array with drawing data.
// @param Line_2 Second line array with drawing data.
// @param Mult Coordinates multiplier.
// @param Exe_1 Display the first indicator.
// @param Exe_2 Display the second indicator.
// @returns Drawings of the indicators.
export Draw_Ind_D(line[] Line_1, line[] Line_2, int Mult, bool Exe_1, bool Exe_2) =>
if barstate.islast
for i = 1 to Line_1.size() > 0 ? Line_2.size() - 1 : na by 1
if Exe_1
Line_1.get(i).set_x1(bar_index - i * Mult + Mult)
Line_1.get(i).set_x2(bar_index - i * Mult)
Line_1.get(i).set_y1(Line_1.get(i - 1).get_y2())
if Exe_2
Line_2.get(i).set_x1(bar_index - i * Mult + Mult)
Line_2.get(i).set_x2(bar_index - i * Mult)
Line_2.get(i).set_y1(Line_2.get(i - 1).get_y2())
[Line_1, Line_2]
//
// CUSTOM COLOR
//
// @function Colors the candles based on indicators output.
// @param Box Candle box array.
// @param Line Candle line array.
// @param BarColor Indicator color array.
// @returns Colored candles.
export Barcolor(box[] Box, line[] Line, color[] BarColor) =>
for i = 0 to Line.size() > 0 ? Line.size() - 1 : na by 1
Box.get(i).set_bgcolor(BarColor.get(i))
Box.get(i).set_border_color(BarColor.get(i))
Line.get(i).set_color(BarColor.get(i))
// @function Populates two array with drawing data of the HTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
// @param IndValue_1 First indicator value.
// @param IndValue_2 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param BullColor Bull color.
// @param BearColor Bear color.
// @param IndColor_1 First indicator color.
// @param HTF_Bar_Index HTF bar_index.
// @returns Three arrays with drawing and color data of the HTF indicators.
export Populate_HTF_Ind_D_CC(float IndValue_1, float IndValue_2, int BarsBack, color BullColor, color BearColor, color IndColor_1, int HTF_Bar_Index) =>
var line[] Line_1 = array.new<line>(0)
var line[] Line_2 = array.new<line>(0)
var color[] IndColorAY = array.new<color>(0)
IndColor_0 = IndValue_1 >= IndValue_2 ? BullColor : BearColor
if HTF_Bar_Index[1] != HTF_Bar_Index
IndColorAY.unshift(IndColor_0)
Line_1.unshift(line.new(na, na, na, IndValue_1, color = IndColor_0, width = 1))
Line_2.unshift(line.new(na, na, na, IndValue_2, color = IndColor_1, width = 1))
if Line_1.size() > 0
Line_1.get(0).set_y2(IndValue_1)
Line_2.get(0).set_y2(IndValue_2)
if Line_2.size() > BarsBack + 1
line.delete(Line_1.pop())
line.delete(Line_2.pop())
IndColorAY.pop()
[Line_1, Line_2, IndColorAY]
// @function Populates two arrays with drawing data of the LTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
// @param IndValue_1 First indicator value.
// @param IndValue_2 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param BullColor Bull color.
// @param BearColor Bearcolor.
// @param IndColor_1 First indicator color.
// @returns Three arrays with drawing and color data of the LTF indicators.
export Populate_LTF_Ind_D_CC(float[] IndValue_1, float[] IndValue_2, int BarsBack, color BullColor, color BearColor, color IndColor_1) =>
var line[] Line_1 = array.new<line>(0)
var line[] Line_2 = array.new<line>(0)
var color[] IndColorAY = array.new<color>(0)
for i = 0 to IndValue_1.size() > 0 ? IndValue_2.size() - 1 : na by 1
IndColor_0 = IndValue_1.get(i) >= IndValue_2.get(i) ? BullColor : BearColor
IndColorAY.unshift(IndColor_0)
Line_1.unshift(line.new(na, na, na, IndValue_1.get(i), color = IndColor_0, width = 1))
Line_2.unshift(line.new(na, na, na, IndValue_2.get(i), color = IndColor_1, width = 1))
if Line_2.size() > BarsBack + 1
line.delete(Line_1.pop())
line.delete(Line_2.pop())
IndColorAY.pop()
[Line_1, Line_2, IndColorAY]
// @function Populates one array with drawing data of the HTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
// @param HistValue Indicator value.
// @param IndValue_1 First indicator value.
// @param IndValue_2 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param BullColor Bull color.
// @param BearColor Bearcolor.
// @param HTF_Bar_Index HTF bar_index
// @returns Two arrays with drawing and color data of the HTF histogram.
export Populate_HTF_Hist_CC(float HistValue, float IndValue_1, float IndValue_2, int BarsBack, color BullColor, color BearColor, int HTF_Bar_Index) =>
var box[] Box = array.new<box>(0)
var color[] IndColorAY = array.new<color>(0)
HistColor = IndValue_1 >= IndValue_2 ? BullColor : BearColor
if HTF_Bar_Index[1] != HTF_Bar_Index
IndColorAY.unshift(HistColor)
Box.unshift(box.new(na, HistValue, na, 0, HistColor, 3, border_style = line.style_solid, bgcolor = HistColor))
if Box.size() > 0
Box.get(0).set_top(HistValue)
Box.get(0).set_bottom(0)
if Box.size() > BarsBack + 1
box.delete(Box.pop())
IndColorAY.pop()
[Box, IndColorAY]
// @function Populates one array with drawing data of the LTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
// @param HistValue Indicator value.
// @param IndValue_1 First indicator value.
// @param IndValue_2 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param BullColor Bull color.
// @param BearColor Bearcolor.
// @returns Two array with drawing and color data of the LTF histogram.
export Populate_LTF_Hist_CC(float[] HistValue, float[] IndValue_1, float[] IndValue_2, int BarsBack, color BullColor, color BearColor) =>
var box[] Box = array.new<box>(0)
var color[] IndColorAY = array.new<color>(0)
for i = 0 to HistValue.size() > 0 ? HistValue.size() - 1 : na by 1
HistColor = IndValue_1.get(i) >= IndValue_2.get(i) ? BullColor : BearColor
IndColorAY.unshift(HistColor)
Box.unshift(box.new(na, HistValue.get(i), na, 0, HistColor, 3, border_style = line.style_solid, bgcolor = HistColor))
if Box.size() > BarsBack + 1
box.delete(Box.pop())
IndColorAY.pop()
[Box, IndColorAY]
// @function Populates one array with drawing data of the LTF histogram with color based on: HistValue >= Value ? BullColor : BearColor.
// @param HistValue Indicator value.
// @param Value First indicator value.
// @param BarsBack Indicator lines to display.
// @param BullColor Bull color.
// @param BearColor Bearcolor.
// @returns Two array with drawing and color data of the LTF histogram.
export Populate_LTF_Hist_CC_VA(float[] HistValue, float Value, int BarsBack, color BullColor, color BearColor) =>
var box[] Box = array.new<box>(0)
var color[] IndColorAY = array.new<color>(0)
for i = 0 to HistValue.size() > 0 ? HistValue.size() - 1 : na by 1
HistColor = HistValue.get(i) >= Value ? BullColor : BearColor
IndColorAY.unshift(HistColor)
Box.unshift(box.new(na, HistValue.get(i), na, 0, HistColor, 3, border_style = line.style_solid, bgcolor = HistColor))
if Box.size() > BarsBack + 1
box.delete(Box.pop())
IndColorAY.pop()
[Box, IndColorAY]
// @function Populates one array with drawing data of the HTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
// @param IndValue Indicator value.
// @param IndValue_1 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param BullColor Bull color.
// @param BearColor Bearcolor.
// @param HTF_Bar_Index HTF bar_index
// @returns Two arrays with drawing and color data of the HTF indicator.
export Populate_HTF_Ind_CC(float IndValue, float IndValue_1, int BarsBack, color BullColor, color BearColor, int HTF_Bar_Index) =>
var line[] Line = array.new<line>(0)
var color[] IndColorAY = array.new<color>(0)
if HTF_Bar_Index[1] != HTF_Bar_Index
IndColor_0 = IndValue >= IndValue_1 ? BullColor : BearColor
IndColorAY.unshift(IndColor_0)
Line.unshift(line.new(na, na, na, IndValue, color = IndColor_0, width = 1))
if Line.size() > 0
Line.get(0).set_y2(IndValue)
if Line.size() > BarsBack + 1
line.delete(Line.pop())
IndColorAY.pop()
[Line, IndColorAY]
// @function Populates one array with drawing data of the LTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
// @param IndValue Indicator value.
// @param IndValue_1 Second indicator value.
// @param BarsBack Indicator lines to display.
// @param BullColor Bull color.
// @param BearColor Bearcolor.
// @returns Two arrays with drawing and color data of the LTF indicator.
export Populate_LTF_Ind_CC(float[] IndValue, float[] IndValue_1, int BarsBack, color BullColor, color BearColor) =>
var line[] Line = array.new<line>(0)
var color[] IndColorAY = array.new<color>(0)
for i = 0 to IndValue.size() > 0 ? IndValue.size() - 1 : na by 1
IndColor_0 = IndValue.get(i) >= IndValue_1.get(i) ? BullColor : BearColor
IndColorAY.unshift(IndColor_0)
Line.unshift(line.new(na, na, na, IndValue.get(i), color = IndColor_0, width = 1))
if Line.size() > BarsBack + 1
line.delete(Line.pop())
IndColorAY.pop()
[Line, IndColorAY]
//
// LINES AND LINEFILLS
//
// @function Draws price lines on indicators.
// @param BarsBack Indicator lines to display.
// @param y1 Coordinates of the first line.
// @param y2 Coordinates of the second line.
// @param LineType Line type.
// @param Fill Fill color.
// @returns Drawing of the lines.
export Draw_Lines(int BarsBack, float y1, float y2, string LineType, color Fill) =>
if barstate.islast
L1 = line.new(bar_index - BarsBack, y1, bar_index, y1, xloc.bar_index, extend.right, color = color.white, style = LineType)
L2 = line.new(bar_index - BarsBack, y2, bar_index, y2, xloc.bar_index, extend.right, color = color.white, style = LineType)
L3 = linefill.new(L1, L2, color = Fill)
line.delete(L1[1]), line.delete(L2[1]), linefill.delete(L3[1])
// @function Fills two lines with linefill HTF or LTF.
// @param Upper Upper line.
// @param Lower Lower line.
// @param BarsBack Indicator lines to display.
// @param FillColor Fill color.
// @returns Linefill of the lines.
export LineFill(line[] Upper, line[] Lower, int BarsBack, color FillColor) =>
linefill[] LineFill = array.new<linefill>(0)
for i = 0 to Upper.size() > 0 ? Lower.size() - 1 : na by 1
LineFill.unshift(linefill.new(Upper.get(i), Lower.get(i), color = FillColor))
if LineFill.size() > BarsBack
linefill.delete(LineFill.pop())
//
// HISTOGRAM
//
// @function Populates one array with drawing data of the LTF histogram.
// @param HistValue Indicator value.
// @param BarsBack Indicator lines to display.
// @param HistColor Indicator color.
// @returns One array with drawing data of the LTF histogram.
export Populate_LTF_Hist(float[] HistValue, int BarsBack, color HistColor) =>
var box[] Box = array.new<box>(0)
for i = 0 to HistValue.size() > 0 ? HistValue.size() - 1 : na by 1
Box.unshift(box.new(na, HistValue.get(i), na, 0, HistColor, 3, border_style = line.style_solid, bgcolor = HistColor))
if Box.size() > BarsBack + 1
box.delete(Box.pop())
Box
// @function Populates one array with drawing data of the HTF histogram.
// @param HistValue Indicator value.
// @param BarsBack Indicator lines to display.
// @param HistColor Indicator color.
// @param HTF_Bar_Index HTF bar_index.
// @returns One array with drawing data of the HTF histogram.
export Populate_HTF_Hist(float HistValue, int BarsBack, color HistColor, int HTF_Bar_Index) =>
var box[] Box = array.new<box>(0)
if HTF_Bar_Index[1] != HTF_Bar_Index
Box.unshift(box.new(na, HistValue, na, 0, HistColor, 3, border_style = line.style_solid, bgcolor = HistColor))
if Box.size() > 0
Box.get(0).set_top(HistValue)
Box.get(0).set_bottom(0)
if Box.size() > BarsBack + 1
box.delete(Box.pop())
Box
// @function Draws HTF or LTF histogram.
// @param Box Box Array.
// @param Mult Coordinates multiplier.
// @param Exe Display the histogram.
// @returns Drawing of the histogram.
export Draw_Hist(box[] Box, int Mult, bool Exe) =>
if Exe and barstate.islast
for i = 0 to Box.size() > 0 ? Box.size() - 1 : na by 1
Box.get(i).set_left(bar_index - i * Mult)
Box.get(i).set_right(bar_index - i * Mult)
Box |
DBTV | https://www.tradingview.com/script/ThIJDq2O/ | atchart | https://www.tradingview.com/u/atchart/ | 0 | library | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © atchart
//@version=5
// @description TODO: add library description here
library("DBTV", overlay=true)
is_stock() =>
var stocks = array.from("KRX", "NASDAQ", "ARCA", "AMEX", "NYSE")
array.includes(stocks, syminfo.prefix)
is_korea_stock() =>
syminfo.prefix == "KRX"
is_us_stock() =>
var stocks = array.from("NASDAQ", "ARCA", "AMEX", "NYSE")
array.includes(stocks, syminfo.prefix)
is_crypto() =>
(syminfo.type == "crypto")
is_futures() =>
code = switch syminfo.prefix
"BINANCE" => ".P"
"BYBIT" => ".P"
"BITGET" => ".P"
"UPBIT" => "PERP"
"OKX" => ".P"
=>".P"
is_crypto() and str.endswith(syminfo.ticker, code)
is_spot() =>
is_crypto() and (not is_futures())
get_exchange_and_code() =>
is_stock = is_stock()
code = is_stock ? syminfo.currency : str.replace(syminfo.ticker, syminfo.basecurrency, "", 0)
[syminfo.prefix, code]
get_ordertype_and_orderqty_and_orderprice_and_ordername() =>
["{{strategy.order.action}}", "{{strategy.order.contracts}}", "{{strategy.order.price}}", "{{strategy.order.comment}}"]
// @function Create a buy order message for ATCT
// @param accnt_no (string) [Optional] The number of account.
// @param password (string) [Optional] The password of account.
// @param orderqty (float) [Optional] The orderqty for sell based on your wallet balance.
// @param orderkind (string) [Optional] The orderkind for order price.
// @returns (string) A string containing the formatted webhook message.
buy_order(string accnt_no = na, string password=na, int orderqty=na, string orderkind = "limit") =>
[exchange, code] = get_exchange_and_code()
[ordertype, strqty, orderprice, ordername] = get_ordertype_and_orderqty_and_orderprice_and_ordername()
//order_qty = str.tonumber(strqty)
if not na(orderqty)
strqty := str.tostring(orderqty)
json = '{'
+ str.format(
'
"accnt_no": "{0}",
"password":"{1}",
"ordername":"{2}",
"exchange":"{3}",
"code":"{4}",
"ordertype":"{5}",
"orderkind":"{6}",
"orderqty":"{7}",
"orderprice":"{8}"
', accnt_no, password, ordername, exchange, code, ordertype, orderkind, orderqty, orderprice)
+'}'
json
// @function Create a sell order message for ATCT
// @param accnt_no (string) [Optional] The number of account.
// @param password (string) [Optional] The password of account.
// @param orderqty (float) [Optional] The orderqty for sell based on your wallet balance.
// @param orderkind (string) [Optional] The orderkind for order price.
// @returns (string) A string containing the formatted webhook message.
sell_order(string accnt_no = na, string password=na, int orderqty=na, string orderkind = "limit") =>
[exchange, code] = get_exchange_and_code()
[ordertype, strqty, orderprice, ordername] = get_ordertype_and_orderqty_and_orderprice_and_ordername()
//order_qty = str.tonumber(strqty)
if not na(orderqty)
strqty := str.tostring(orderqty)
json = '{'
+ str.format(
'
"accnt_no": "{0}",
"password":"{1}",
"ordername":"{2}",
"exchange":"{3}",
"code":"{4}",
"ordertype":"{5}",
"orderkind":"{6}",
"orderqty":"{7}",
"orderprice":"{8}"
', accnt_no, password, ordername, exchange, code, ordertype, orderkind, orderqty, orderprice)
+'}'
json
// @function Create a entry order message for ATCT
// @param accnt_no (string) [Optional] The number of account.
// @param password (string) [Optional] The password of account.
// @param orderqty (float) [Optional] The orderqty for sell based on your wallet balance.
// @param orderkind (string) [Optional] The orderkind for order price.
// @returns (string) A string containing the formatted webhook message.
entry_order(string accnt_no = na, string password=na, int orderqty=na, string orderkind = "limit") =>
[exchange, code] = get_exchange_and_code()
[ordertype, strqty, orderprice, ordername] = get_ordertype_and_orderqty_and_orderprice_and_ordername()
//order_qty = str.tonumber(strqty)
if not na(orderqty)
strqty := str.tostring(orderqty)
username = '트레이딩뷰봇'
content = 'entry_order'
embedColor = "red"
timestamp = str.format_time(time, "yyyy-MM-dd HH:mm")
json = str.format('{{"username": "{0}", "content": "{1}", "embeds": [{{"title": "{2}", "color": "{3}", "timestamp": "{4}"" }}] }}', username, content, ordername, embedColor, timestamp)
///////////////////////// EXPORT //////////////////////////////////////
// @function Create a entry message for ATCHART
// @param password (string) [Optional] The password of your bot.
// @param percent (float) [Optional] The percent for entry based on your wallet balance.
// @param leverage (int) [Optional] The leverage of entry. If not set, your levereage doesn't change.
// @param margin_mode (string) [Optional] The margin mode for trade(only for OKX). "cross" or "isolated"
// @param accnt_no (string) [Optional] The number of security account. Default 1
// @returns (string) A json formatted string for webhook message.
export entry_msg(string accnt_no=na, string password=na, int orderqty = na, string orderkind = "limit") =>
is_buy = is_stock() or is_spot()
is_buy ? buy_order(accnt_no, password, orderqty, orderkind) : entry_order(accnt_no, password, orderqty, orderkind)
|
Touched | https://www.tradingview.com/script/6x0Ed1nM-Touched/ | mickes | https://www.tradingview.com/u/mickes/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mickes
//@version=5
library("Touched")
export type Zone
float High
float Low
int BaseTime
export type Touch
bool Up
bool Down
// @function Tells if the zone has been broken on the current bar.
// @param zone The definitiin of the zone.
// @param lookback How many bars to look back.
// @returns a Touch object that tells if the zone has been broken up or down.
export Breakout(Zone zone, int lookback) =>
breakout = Touch.new()
// /
if low > zone.High
and low[1] < zone.High
for i = 1 to lookback
if zone.BaseTime > time[i]
break
if low[i] > zone.High
break
if high[i] < zone.Low
breakout.Up := true
break
// \
if high < zone.Low
and high[1] > zone.Low
for i = 1 to lookback
if zone.BaseTime > time[i]
break
if high[i] < zone.Low
break
if low[i] > zone.High
breakout.Down := true
break
breakout
// @function Tells if the zone has a false breakout on the current bar.
// @param zone The definitiin of the zone.
// @param lookback How many bars to look back.
// @returns a Touch object that tells if the zone has had a false breakout up or down.
export FalseBreakout(Zone zone, int lookback) =>
falseBreakout = Touch.new()
// /'\ \
// / \ \ /'\
// / or \/ \
if high < zone.Low
and high[1] > zone.Low
higher = false
for i = 0 to lookback
if zone.BaseTime > time[i]
break
if low[i] > zone.High
higher := true
if higher
and high[i] < zone.Low
falseBreakout.Up := true
break
// \ /\ /
// \ / / \./
// \./ or /
if low > zone.High
and low[1] < zone.High
lower = false
for i = 0 to lookback
if zone.BaseTime > time[i]
break
if high[i] < zone.Low
lower := true
if lower
and low[i] > zone.High
falseBreakout.Down := true
break
falseBreakout
// @function Tells if the zone has been retested on the current bar.
// @param zone The definitiin of the zone.
// @param lookback How many bars to look back.
// @returns a Touch object that tells if the zone has been retested up or down.
export Retest(Zone zone, int lookback) =>
retest = Touch.new()
// \/
if low > zone.High
and low[1] < zone.High
for i = 1 to lookback
if zone.BaseTime > time[i]
break
if low[i] > zone.High
retest.Up := true
break
// /\
if high < zone.Low
and high[1] > zone.Low
for i = 1 to lookback
if zone.BaseTime > time[i]
break
if high[i] < zone.Low
retest.Down := true
break
retest |
lib_retracement_label | https://www.tradingview.com/script/mbtkdasw-lib-retracement-label/ | robbatt | https://www.tradingview.com/u/robbatt/ | 8 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © robbatt
//@version=5
import robbatt/lib_plot_objects/32 as D
import robbatt/lib_pivot/45 as P
import robbatt/lib_priceaction/6 as PA
// @description creates a retracement label between the origin and target of a retracement, updating it's position (via draw) when the target moves.
library("lib_retracement_label", overlay = true)
export type RetracementLabel
chart.point move_endpoint // start and retracement point inside center_label
D.CenterLabel center_label
export create_tooltip(string name = '', float min, float max, float tol_min, float tol_max) =>
var string tooltip_format_exact = "{0} {1}"
var string tooltip_format_range = "{0} {1} - {2}"
var string tolerance_format = "{0}\nTolerance ({1} - {2})"
tooltip = min == max
? str.format(tooltip_format_exact, name, min, tol_min, tol_max)
: str.format(tooltip_format_range, name, min, max, tol_min, tol_max)
if (tol_min != min or tol_max != max) and not na(tol_min) and not na(tol_max)
tooltip := str.format(tolerance_format, tooltip, tol_min, tol_max)
tooltip
export method update(RetracementLabel this) =>
ratio = math.round(PA.retracement_ratio(this.center_label.points.get(0).price, this.move_endpoint.price, this.center_label.points.get(1).price),3)
txt = str.tostring(ratio)
this.center_label.center_label.txt := txt
//@function Creates a new RetracementLabel object.
export method create_retracement_label(D.Line this, chart.point move_endpoint, D.LabelArgs args, string tooltip = na) =>
ratio = math.round(PA.retracement_ratio(this.start.price, move_endpoint.price, this.end.price),3)
txt = str.tostring(ratio)
RetracementLabel.new(move_endpoint, this.create_center_label(txt, args, tooltip))
//@function Creates a new RetracementLabel object.
export method create_retracement_label(D.Line this, P.Pivot move_end, D.LabelArgs args, string tooltip = na) =>
this.create_retracement_label(move_end.point, args, tooltip)
export method enqueue(RetracementLabel[] id, RetracementLabel item, int max = 0) =>
if not na(id) and not na(item)
id.unshift(item)
if max > 0 and id.size() > max
id.pop()
id
export method draw(RetracementLabel this) =>
if na(this) ? false : not na(this.center_label) and not na(this.move_endpoint)
cl = this.center_label
l = cl.center_label
l.txt := str.tostring(math.round(PA.retracement_ratio(cl.points.get(0).price, this.move_endpoint.price, cl.points.get(1).price), 3))
cl.draw()
this
export method draw(RetracementLabel[] this) =>
if not na(this)
for l in this
l.draw()
this
export method delete(RetracementLabel this) =>
if not na(this)
this.center_label.delete()
this
export method delete(RetracementLabel[] this) =>
if not na(this)
for l in this
l.delete()
this
highest_offset = -ta.highestbars(30)
prev_highest_offset = highest_offset[31] + 31
lowest_offset = -ta.lowestbars(30)
prev_lowest_offset = lowest_offset[31] + 31
if barstate.islast
var origin = chart.point.new(time[prev_highest_offset], bar_index[prev_highest_offset], high[prev_highest_offset])
var mid = chart.point.new(time[lowest_offset], bar_index[lowest_offset], high[lowest_offset])
var target = chart.point.new(time[highest_offset], bar_index[highest_offset], high[highest_offset])
var args = D.LineArgs.new(color.gray, line.style_dashed)
var retracement_line = origin.create_line(target, args).draw()
var retracement_tooltip = create_tooltip('name label', 50, 100, 45, 105)
var retracement_label_args = D.LabelArgs.new(color.white, #00000000, style = label.style_label_center, size = size.normal)
var retracement_label = retracement_line.create_retracement_label(mid, retracement_label_args, retracement_tooltip)
target.update(time, bar_index, close)
retracement_line.draw()
retracement_label.update()
retracement_label.draw()
|
NetLiquidityLibraryMacF | https://www.tradingview.com/script/aHqqBhuf-NetLiquidityLibraryMacF/ | macaronicheese63 | https://www.tradingview.com/u/macaronicheese63/ | 1 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © calebsandfort
//@version=5
// @description The Net Liquidity Library provides daily values for net liquidity. Net liquidity is measured as Fed Balance Sheet - Treasury General Account - Reverse Repo. Time series for each individual component included too.
library("NetLiquidityLibraryMacF", overlay = true)
get_net_liquidity_0(simple string component = "", int ts = 0) =>
float val = switch ts
1624320000000 => component == "fed" ? 8064257000000.0 : component == "tga" ? 744249000000.0 : component == "rrp" ? 791605000000.0 : 6528403000000.0
1624406400000 => component == "fed" ? 8064257000000.0 : component == "tga" ? 744249000000.0 : component == "rrp" ? 813650000000.0 : 6544046000000.0
1624492800000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 733877000000.0 : component == "rrp" ? 813048000000.0 : 6555020000000.0
1624579200000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 723946000000.0 : component == "rrp" ? 770830000000.0 : 6607169000000.0
1624838400000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 733226000000.0 : component == "rrp" ? 803019000000.0 : 6565700000000.0
1624924800000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 734915000000.0 : component == "rrp" ? 841246000000.0 : 6525784000000.0
1625011200000 => component == "fed" ? 8101945000000.0 : component == "tga" ? 711267000000.0 : component == "rrp" ? 991939000000.0 : 6375338000000.0
1625097600000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 851929000000.0 : component == "rrp" ? 742647000000.0 : 6483968000000.0
1625184000000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 784035000000.0 : component == "rrp" ? 731504000000.0 : 6563005000000.0
1625529600000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 757682000000.0 : component == "rrp" ? 772581000000.0 : 6548281000000.0
1625616000000 => component == "fed" ? 8078544000000.0 : component == "tga" ? 733889000000.0 : component == "rrp" ? 785720000000.0 : 6578164000000.0
1625702400000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 724898000000.0 : component == "rrp" ? 793399000000.0 : 6579476000000.0
1625788800000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 727336000000.0 : component == "rrp" ? 780596000000.0 : 6589841000000.0
1626048000000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 718092000000.0 : component == "rrp" ? 776472000000.0 : 6603209000000.0
1626134400000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 718474000000.0 : component == "rrp" ? 798267000000.0 : 6581032000000.0
1626220800000 => component == "fed" ? 8097773000000.0 : component == "tga" ? 676800000000.0 : component == "rrp" ? 859975000000.0 : 6664876000000.0
1626307200000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 657542000000.0 : component == "rrp" ? 776261000000.0 : 6767848000000.0
1626393600000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 690107000000.0 : component == "rrp" ? 817566000000.0 : 6693978000000.0
1626652800000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 697581000000.0 : component == "rrp" ? 860468000000.0 : 6643602000000.0
1626739200000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 700041000000.0 : component == "rrp" ? 848102000000.0 : 6653508000000.0
1626825600000 => component == "fed" ? 8201651000000.0 : component == "tga" ? 647533000000.0 : component == "rrp" ? 886206000000.0 : 6706791000000.0
1626912000000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 616294000000.0 : component == "rrp" ? 898197000000.0 : 6726039000000.0
1626998400000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 590042000000.0 : component == "rrp" ? 877251000000.0 : 6773237000000.0
1627257600000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 588083000000.0 : component == "rrp" ? 891203000000.0 : 6761244000000.0
1627344000000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 591368000000.0 : component == "rrp" ? 927419000000.0 : 6721743000000.0
1627430400000 => component == "fed" ? 8240530000000.0 : component == "tga" ? 564799000000.0 : component == "rrp" ? 965189000000.0 : 6691485000000.0
1627516800000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 536966000000.0 : component == "rrp" ? 987283000000.0 : 6697224000000.0
1627603200000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 501179000000.0 : component == "rrp" ? 1039394000000.0 : 6680900000000.0
1627862400000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 459402000000.0 : component == "rrp" ? 921317000000.0 : 6840754000000.0
1627948800000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 555569000000.0 : component == "rrp" ? 909442000000.0 : 6756462000000.0
1628035200000 => component == "fed" ? 8221473000000.0 : component == "tga" ? 507848000000.0 : component == "rrp" ? 931755000000.0 : 6795470000000.0
1628121600000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 505871000000.0 : component == "rrp" ? 944335000000.0 : 6784867000000.0
1628208000000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 466601000000.0 : component == "rrp" ? 952134000000.0 : 6816338000000.0
1628467200000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 442557000000.0 : component == "rrp" ? 981765000000.0 : 6810751000000.0
1628553600000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 444212000000.0 : component == "rrp" ? 998654000000.0 : 6792207000000.0
1628640000000 => component == "fed" ? 8235073000000.0 : component == "tga" ? 416199000000.0 : component == "rrp" ? 1000460000000.0 : 6840500000000.0
1628726400000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 389747000000.0 : component == "rrp" ? 1087342000000.0 : 6780070000000.0
1628812800000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 351572000000.0 : component == "rrp" ? 1050941000000.0 : 6854646000000.0
1629072000000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 335190000000.0 : component == "rrp" ? 1036418000000.0 : 6885551000000.0
1629158400000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 362012000000.0 : component == "rrp" ? 1053454000000.0 : 6841693000000.0
1629244800000 => component == "fed" ? 8257159000000.0 : component == "tga" ? 338853000000.0 : component == "rrp" ? 1115656000000.0 : 6888089000000.0
1629331200000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 313651000000.0 : component == "rrp" ? 1109938000000.0 : 6919009000000.0
1629417600000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 321137000000.0 : component == "rrp" ? 1111905000000.0 : 6909556000000.0
1629676800000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 309820000000.0 : component == "rrp" ? 1135697000000.0 : 6897081000000.0
1629763200000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 317103000000.0 : component == "rrp" ? 1129737000000.0 : 6895758000000.0
1629849600000 => component == "fed" ? 8342598000000.0 : component == "tga" ? 284110000000.0 : component == "rrp" ? 1147089000000.0 : 6901544000000.0
1629936000000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 258200000000.0 : component == "rrp" ? 1091792000000.0 : 6982751000000.0
1630022400000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 239304000000.0 : component == "rrp" ? 1120015000000.0 : 6973424000000.0
1630281600000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 262811000000.0 : component == "rrp" ? 1140711000000.0 : 6929221000000.0
1630368000000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 262895000000.0 : component == "rrp" ? 1189616000000.0 : 6880232000000.0
1630454400000 => component == "fed" ? 8332743000000.0 : component == "tga" ? 355984000000.0 : component == "rrp" ? 1084115000000.0 : 6909074000000.0
1630540800000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 296934000000.0 : component == "rrp" ? 1066987000000.0 : 6985252000000.0
1630627200000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 292163000000.0 : component == "rrp" ? 1074707000000.0 : 6982303000000.0
1630972800000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 262488000000.0 : component == "rrp" ? 1079945000000.0 : 7006740000000.0
1631059200000 => component == "fed" ? 8349173000000.0 : component == "tga" ? 231654000000.0 : component == "rrp" ? 1115229000000.0 : 7010431000000.0
1631145600000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 200702000000.0 : component == "rrp" ? 1107659000000.0 : 7048953000000.0
1631232000000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 207218000000.0 : component == "rrp" ? 1099323000000.0 : 7050773000000.0
1631491200000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 208035000000.0 : component == "rrp" ? 1087108000000.0 : 7062171000000.0
1631577600000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 225075000000.0 : component == "rrp" ? 1169280000000.0 : 6962959000000.0
1631664000000 => component == "fed" ? 8357314000000.0 : component == "tga" ? 211227000000.0 : component == "rrp" ? 1081342000000.0 : 7156201000000.0
1631750400000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 344668000000.0 : component == "rrp" ? 1147494000000.0 : 6956608000000.0
1631836800000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 317970000000.0 : component == "rrp" ? 1218303000000.0 : 6912497000000.0
1632096000000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 315003000000.0 : component == "rrp" ? 1224289000000.0 : 6909478000000.0
1632182400000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 324877000000.0 : component == "rrp" ? 1240494000000.0 : 6883399000000.0
1632268800000 => component == "fed" ? 8448770000000.0 : component == "tga" ? 295620000000.0 : component == "rrp" ? 1283281000000.0 : 6910923000000.0
1632355200000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 272679000000.0 : component == "rrp" ? 1352483000000.0 : 6864662000000.0
1632441600000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 173922000000.0 : component == "rrp" ? 1313657000000.0 : 7002245000000.0
1632700800000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 215533000000.0 : component == "rrp" ? 1297050000000.0 : 6977241000000.0
1632787200000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 217019000000.0 : component == "rrp" ? 1365185000000.0 : 6907620000000.0
1632873600000 => component == "fed" ? 8489824000000.0 : component == "tga" ? 172920000000.0 : component == "rrp" ? 1415840000000.0 : 6859221000000.0
1632960000000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 173745000000.0 : component == "rrp" ? 1604881000000.0 : 6669355000000.0
1633046400000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 215160000000.0 : component == "rrp" ? 1385991000000.0 : 6846830000000.0
1633305600000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 132452000000.0 : component == "rrp" ? 1399173000000.0 : 6916356000000.0
1633392000000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 141318000000.0 : component == "rrp" ? 1431180000000.0 : 6875483000000.0
1633478400000 => component == "fed" ? 8447981000000.0 : component == "tga" ? 99385000000.0 : component == "rrp" ? 1451175000000.0 : 6913472000000.0
1633564800000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 95854000000.0 : component == "rrp" ? 1375863000000.0 : 6992315000000.0
1633651200000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 86339000000.0 : component == "rrp" ? 1371958000000.0 : 7005735000000.0
1633910400000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 81803000000.0 : component == "rrp" ? 1371958000000.0 : 7010271000000.0
1633996800000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 81803000000.0 : component == "rrp" ? 1367051000000.0 : 7015178000000.0
1634083200000 => component == "fed" ? 8464032000000.0 : component == "tga" ? 58993000000.0 : component == "rrp" ? 1364701000000.0 : 7057248000000.0
1634169600000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 72460000000.0 : component == "rrp" ? 1445660000000.0 : 6962822000000.0
1634256000000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 46508000000.0 : component == "rrp" ? 1462297000000.0 : 6972137000000.0
1634515200000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 50846000000.0 : component == "rrp" ? 1477114000000.0 : 6952982000000.0
1634601600000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 134768000000.0 : component == "rrp" ? 1470739000000.0 : 6875435000000.0
1634688000000 => component == "fed" ? 8480942000000.0 : component == "tga" ? 132525000000.0 : component == "rrp" ? 1493961000000.0 : 6938457000000.0
1634774400000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 117364000000.0 : component == "rrp" ? 1458605000000.0 : 6988974000000.0
1634860800000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 149154000000.0 : component == "rrp" ? 1403020000000.0 : 7012769000000.0
1635120000000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 208815000000.0 : component == "rrp" ? 1413188000000.0 : 6942940000000.0
1635206400000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 219868000000.0 : component == "rrp" ? 1423198000000.0 : 6921877000000.0
1635292800000 => component == "fed" ? 8564943000000.0 : component == "tga" ? 261071000000.0 : component == "rrp" ? 1433370000000.0 : 6861740000000.0
1635379200000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 236495000000.0 : component == "rrp" ? 1384684000000.0 : 6935002000000.0
1635465600000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 259761000000.0 : component == "rrp" ? 1502296000000.0 : 6794124000000.0
1635724800000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 278023000000.0 : component == "rrp" ? 1358606000000.0 : 6919552000000.0
1635811200000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 269343000000.0 : component == "rrp" ? 1329913000000.0 : 6956925000000.0
1635897600000 => component == "fed" ? 8556181000000.0 : component == "tga" ? 311302000000.0 : component == "rrp" ? 1343985000000.0 : 6919584000000.0
1635984000000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 286959000000.0 : component == "rrp" ? 1348539000000.0 : 6939373000000.0
1636070400000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 268350000000.0 : component == "rrp" ? 1354059000000.0 : 6952462000000.0
1636329600000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 263023000000.0 : component == "rrp" ? 1354382000000.0 : 6957466000000.0
1636416000000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 270273000000.0 : component == "rrp" ? 1377197000000.0 : 6927401000000.0
1636502400000 => component == "fed" ? 8574871000000.0 : component == "tga" ? 255937000000.0 : component == "rrp" ? 1448623000000.0 : 6958557000000.0
=>
float(na)
val
get_net_liquidity_1(simple string component = "", int ts = 0) =>
float val = switch ts
1636588800000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 231421000000.0 : component == "rrp" ? 1448623000000.0 : 6983073000000.0
1636675200000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 231421000000.0 : component == "rrp" ? 1417643000000.0 : 7014053000000.0
1636934400000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 219793000000.0 : component == "rrp" ? 1391657000000.0 : 7051667000000.0
1637020800000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 211700000000.0 : component == "rrp" ? 1466857000000.0 : 6984560000000.0
1637107200000 => component == "fed" ? 8663117000000.0 : component == "tga" ? 198696000000.0 : component == "rrp" ? 1520000000000.0 : 6956274000000.0
1637193600000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 178972000000.0 : component == "rrp" ? 1584097000000.0 : 6911901000000.0
1637280000000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 168229000000.0 : component == "rrp" ? 1575384000000.0 : 6931357000000.0
1637539200000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 170311000000.0 : component == "rrp" ? 1573769000000.0 : 6930890000000.0
1637625600000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 163242000000.0 : component == "rrp" ? 1571980000000.0 : 6939748000000.0
1637712000000 => component == "fed" ? 8674970000000.0 : component == "tga" ? 165160000000.0 : component == "rrp" ? 1452897000000.0 : 7063714000000.0
1637884800000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 141042000000.0 : component == "rrp" ? 1451108000000.0 : 7089621000000.0
1638144000000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 137091000000.0 : component == "rrp" ? 1459339000000.0 : 7085341000000.0
1638230400000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 143941000000.0 : component == "rrp" ? 1517956000000.0 : 7019874000000.0
1638316800000 => component == "fed" ? 8681771000000.0 : component == "tga" ? 213153000000.0 : component == "rrp" ? 1427347000000.0 : 7009902000000.0
1638403200000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 159148000000.0 : component == "rrp" ? 1448585000000.0 : 7042669000000.0
1638489600000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 125195000000.0 : component == "rrp" ? 1475464000000.0 : 7049743000000.0
1638748800000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 101192000000.0 : component == "rrp" ? 1487996000000.0 : 7061214000000.0
1638835200000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 106980000000.0 : component == "rrp" ? 1455038000000.0 : 7088384000000.0
1638921600000 => component == "fed" ? 8650402000000.0 : component == "tga" ? 144924000000.0 : component == "rrp" ? 1484192000000.0 : 7035408000000.0
1639008000000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 125144000000.0 : component == "rrp" ? 1500027000000.0 : 7039353000000.0
1639094400000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 118145000000.0 : component == "rrp" ? 1507147000000.0 : 7039232000000.0
1639353600000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 114680000000.0 : component == "rrp" ? 1599768000000.0 : 6950076000000.0
1639440000000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 133605000000.0 : component == "rrp" ? 1584488000000.0 : 6946431000000.0
1639526400000 => component == "fed" ? 8664524000000.0 : component == "tga" ? 79505000000.0 : component == "rrp" ? 1621097000000.0 : 7056064000000.0
1639612800000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 58294000000.0 : component == "rrp" ? 1657626000000.0 : 7040746000000.0
1639699200000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 42111000000.0 : component == "rrp" ? 1704586000000.0 : 7009969000000.0
1639958400000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 47877000000.0 : component == "rrp" ? 1758041000000.0 : 6950748000000.0
1640044800000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 64905000000.0 : component == "rrp" ? 1748285000000.0 : 6943476000000.0
1640131200000 => component == "fed" ? 8756666000000.0 : component == "tga" ? 146518000000.0 : component == "rrp" ? 1699277000000.0 : 6944700000000.0
1640217600000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 197516000000.0 : component == "rrp" ? 1577780000000.0 : 7015199000000.0
1640563200000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 176914000000.0 : component == "rrp" ? 1580347000000.0 : 7033234000000.0
1640649600000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 202813000000.0 : component == "rrp" ? 1637064000000.0 : 6950618000000.0
1640736000000 => component == "fed" ? 8790495000000.0 : component == "tga" ? 268208000000.0 : component == "rrp" ? 1642506000000.0 : 6846746000000.0
1640822400000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 283995000000.0 : component == "rrp" ? 1696476000000.0 : 6776989000000.0
1640908800000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 284174000000.0 : component == "rrp" ? 1904582000000.0 : 6568704000000.0
1641168000000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 406108000000.0 : component == "rrp" ? 1579526000000.0 : 6771826000000.0
1641254400000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 366304000000.0 : component == "rrp" ? 1495692000000.0 : 6895464000000.0
1641340800000 => component == "fed" ? 8757460000000.0 : component == "tga" ? 424696000000.0 : component == "rrp" ? 1492787000000.0 : 6848238000000.0
1641427200000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 434757000000.0 : component == "rrp" ? 1510553000000.0 : 6820411000000.0
1641513600000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 440561000000.0 : component == "rrp" ? 1530096000000.0 : 6795064000000.0
1641772800000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 436443000000.0 : component == "rrp" ? 1560421000000.0 : 6768857000000.0
1641859200000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 447887000000.0 : component == "rrp" ? 1527020000000.0 : 6790814000000.0
1641945600000 => component == "fed" ? 8765721000000.0 : component == "tga" ? 507352000000.0 : component == "rrp" ? 1536981000000.0 : 6743945000000.0
1642032000000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 489679000000.0 : component == "rrp" ? 1636742000000.0 : 6661857000000.0
1642118400000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 441135000000.0 : component == "rrp" ? 1598887000000.0 : 6748256000000.0
1642464000000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 453239000000.0 : component == "rrp" ? 1597137000000.0 : 6737902000000.0
1642550400000 => component == "fed" ? 8788278000000.0 : component == "tga" ? 586619000000.0 : component == "rrp" ? 1656576000000.0 : 6624639000000.0
1642636800000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 580171000000.0 : component == "rrp" ? 1678931000000.0 : 6608732000000.0
1642723200000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 601115000000.0 : component == "rrp" ? 1706127000000.0 : 6560592000000.0
1642982400000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 598929000000.0 : component == "rrp" ? 1614002000000.0 : 6654903000000.0
1643068800000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 619699000000.0 : component == "rrp" ? 1599502000000.0 : 6648633000000.0
1643155200000 => component == "fed" ? 8867834000000.0 : component == "tga" ? 646920000000.0 : component == "rrp" ? 1613046000000.0 : 6600519000000.0
1643241600000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 639620000000.0 : component == "rrp" ? 1583895000000.0 : 6636970000000.0
1643328000000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 641597000000.0 : component == "rrp" ? 1615021000000.0 : 6603867000000.0
1643587200000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 642334000000.0 : component == "rrp" ? 1654850000000.0 : 6563301000000.0
1643673600000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 742843000000.0 : component == "rrp" ? 1584109000000.0 : 6533533000000.0
1643760000000 => component == "fed" ? 8860485000000.0 : component == "tga" ? 708705000000.0 : component == "rrp" ? 1626895000000.0 : 6537611000000.0
1643846400000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 710267000000.0 : component == "rrp" ? 1640397000000.0 : 6522547000000.0
1643932800000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 684721000000.0 : component == "rrp" ? 1642892000000.0 : 6545598000000.0
1644192000000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 682002000000.0 : component == "rrp" ? 1679932000000.0 : 6511277000000.0
1644278400000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 691711000000.0 : component == "rrp" ? 1674610000000.0 : 6506890000000.0
1644364800000 => component == "fed" ? 8873211000000.0 : component == "tga" ? 703228000000.0 : component == "rrp" ? 1653153000000.0 : 6521628000000.0
1644451200000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 679019000000.0 : component == "rrp" ? 1634146000000.0 : 6564844000000.0
1644537600000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 672004000000.0 : component == "rrp" ? 1635826000000.0 : 6570179000000.0
1644796800000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 682930000000.0 : component == "rrp" ? 1666232000000.0 : 6528847000000.0
1644883200000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 699135000000.0 : component == "rrp" ? 1608494000000.0 : 6570380000000.0
1644969600000 => component == "fed" ? 8878009000000.0 : component == "tga" ? 718597000000.0 : component == "rrp" ? 1644134000000.0 : 6548302000000.0
1645056000000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 709261000000.0 : component == "rrp" ? 1647202000000.0 : 6554570000000.0
1645142400000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 705359000000.0 : component == "rrp" ? 1674929000000.0 : 6530745000000.0
1645488000000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 702252000000.0 : component == "rrp" ? 1699432000000.0 : 6509349000000.0
1645574400000 => component == "fed" ? 8911033000000.0 : component == "tga" ? 695704000000.0 : component == "rrp" ? 1738322000000.0 : 6494103000000.0
1645660800000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 674797000000.0 : component == "rrp" ? 1650399000000.0 : 6602933000000.0
1645747200000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 640342000000.0 : component == "rrp" ? 1603349000000.0 : 6684438000000.0
1646006400000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 661184000000.0 : component == "rrp" ? 1596052000000.0 : 6670893000000.0
1646092800000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 771264000000.0 : component == "rrp" ? 1552950000000.0 : 6603915000000.0
1646179200000 => component == "fed" ? 8928129000000.0 : component == "tga" ? 699674000000.0 : component == "rrp" ? 1526211000000.0 : 6678570000000.0
1646265600000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 685491000000.0 : component == "rrp" ? 1533992000000.0 : 6684972000000.0
1646352000000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 661486000000.0 : component == "rrp" ? 1483061000000.0 : 6759908000000.0
1646611200000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 658241000000.0 : component == "rrp" ? 1461227000000.0 : 6784987000000.0
1646697600000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 673387000000.0 : component == "rrp" ? 1525099000000.0 : 6705969000000.0
1646784000000 => component == "fed" ? 8904455000000.0 : component == "tga" ? 645312000000.0 : component == "rrp" ? 1542504000000.0 : 6722932000000.0
1646870400000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 609369000000.0 : component == "rrp" ? 1568735000000.0 : 6732644000000.0
1646956800000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 541965000000.0 : component == "rrp" ? 1557823000000.0 : 6810960000000.0
1647216000000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 544592000000.0 : component == "rrp" ? 1608021000000.0 : 6758135000000.0
1647302400000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 567360000000.0 : component == "rrp" ? 1583471000000.0 : 6759917000000.0
1647388800000 => component == "fed" ? 8910748000000.0 : component == "tga" ? 629614000000.0 : component == "rrp" ? 1613637000000.0 : 6711055000000.0
1647475200000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 621527000000.0 : component == "rrp" ? 1659977000000.0 : 6672802000000.0
1647561600000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 624216000000.0 : component == "rrp" ? 1715148000000.0 : 6614942000000.0
1647820800000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 622418000000.0 : component == "rrp" ? 1728893000000.0 : 6602995000000.0
1647907200000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 626636000000.0 : component == "rrp" ? 1763183000000.0 : 6564487000000.0
1647993600000 => component == "fed" ? 8954306000000.0 : component == "tga" ? 607762000000.0 : component == "rrp" ? 1803186000000.0 : 6551526000000.0
1648080000000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 576442000000.0 : component == "rrp" ? 1707655000000.0 : 6678377000000.0
1648166400000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 563796000000.0 : component == "rrp" ? 1676974000000.0 : 6721704000000.0
1648425600000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 582578000000.0 : component == "rrp" ? 1688632000000.0 : 6691264000000.0
1648512000000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 596168000000.0 : component == "rrp" ? 1718870000000.0 : 6647436000000.0
1648598400000 => component == "fed" ? 8962474000000.0 : component == "tga" ? 560968000000.0 : component == "rrp" ? 1785939000000.0 : 6590235000000.0
1648684800000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 556791000000.0 : component == "rrp" ? 1871970000000.0 : 6508381000000.0
1648771200000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 651523000000.0 : component == "rrp" ? 1666063000000.0 : 6619556000000.0
1649030400000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 567423000000.0 : component == "rrp" ? 1692936000000.0 : 6676783000000.0
1649116800000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 579607000000.0 : component == "rrp" ? 1710834000000.0 : 6646701000000.0
=>
float(na)
val
get_net_liquidity_2(simple string component = "", int ts = 0) =>
float val = switch ts
1649203200000 => component == "fed" ? 8937142000000.0 : component == "tga" ? 542176000000.0 : component == "rrp" ? 1731472000000.0 : 6663944000000.0
1649289600000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 545584000000.0 : component == "rrp" ? 1734424000000.0 : 6657584000000.0
1649376000000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 542946000000.0 : component == "rrp" ? 1750498000000.0 : 6644148000000.0
1649635200000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 544736000000.0 : component == "rrp" ? 1758958000000.0 : 6633898000000.0
1649721600000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 564856000000.0 : component == "rrp" ? 1710414000000.0 : 6662322000000.0
1649808000000 => component == "fed" ? 8937592000000.0 : component == "tga" ? 545611000000.0 : component == "rrp" ? 1815555000000.0 : 6604321000000.0
1649894400000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 543536000000.0 : component == "rrp" ? 1706935000000.0 : 6715016000000.0
1650240000000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 602292000000.0 : component == "rrp" ? 1738379000000.0 : 6624816000000.0
1650326400000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 841253000000.0 : component == "rrp" ? 1817292000000.0 : 6306942000000.0
1650412800000 => component == "fed" ? 8965487000000.0 : component == "tga" ? 893351000000.0 : component == "rrp" ? 1866560000000.0 : 6195940000000.0
1650499200000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 907526000000.0 : component == "rrp" ? 1854700000000.0 : 6193625000000.0
1650585600000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 918877000000.0 : component == "rrp" ? 1765031000000.0 : 6271943000000.0
1650844800000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 934238000000.0 : component == "rrp" ? 1783609000000.0 : 6238004000000.0
1650931200000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 958291000000.0 : component == "rrp" ? 1819343000000.0 : 6178217000000.0
1651017600000 => component == "fed" ? 8955851000000.0 : component == "tga" ? 972993000000.0 : component == "rrp" ? 1803162000000.0 : 6163044000000.0
1651104000000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 957419000000.0 : component == "rrp" ? 1818416000000.0 : 6163364000000.0
1651190400000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 953933000000.0 : component == "rrp" ? 1906802000000.0 : 6078464000000.0
1651449600000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 923240000000.0 : component == "rrp" ? 1796302000000.0 : 6219657000000.0
1651536000000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 975018000000.0 : component == "rrp" ? 1796252000000.0 : 6167929000000.0
1651622400000 => component == "fed" ? 8939199000000.0 : component == "tga" ? 955262000000.0 : component == "rrp" ? 1815656000000.0 : 6169054000000.0
1651708800000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 964412000000.0 : component == "rrp" ? 1844762000000.0 : 6130798000000.0
1651795200000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 943481000000.0 : component == "rrp" ? 1861866000000.0 : 6134625000000.0
1652054400000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 950700000000.0 : component == "rrp" ? 1858995000000.0 : 6130277000000.0
1652140800000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 962928000000.0 : component == "rrp" ? 1864225000000.0 : 6112819000000.0
1652227200000 => component == "fed" ? 8939972000000.0 : component == "tga" ? 941766000000.0 : component == "rrp" ? 1876119000000.0 : 6124123000000.0
1652313600000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 919331000000.0 : component == "rrp" ? 1900069000000.0 : 6122608000000.0
1652400000000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 893803000000.0 : component == "rrp" ? 1865287000000.0 : 6182918000000.0
1652659200000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 880792000000.0 : component == "rrp" ? 1833152000000.0 : 6228064000000.0
1652745600000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 914571000000.0 : component == "rrp" ? 1877483000000.0 : 6149954000000.0
1652832000000 => component == "fed" ? 8942008000000.0 : component == "tga" ? 891271000000.0 : component == "rrp" ? 1973373000000.0 : 6081254000000.0
1652918400000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 866726000000.0 : component == "rrp" ? 1981005000000.0 : 6098167000000.0
1653004800000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 825182000000.0 : component == "rrp" ? 1987987000000.0 : 6132729000000.0
1653264000000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 822339000000.0 : component == "rrp" ? 2044658000000.0 : 6078901000000.0
1653350400000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 838141000000.0 : component == "rrp" ? 1987865000000.0 : 6119892000000.0
1653436800000 => component == "fed" ? 8945898000000.0 : component == "tga" ? 818688000000.0 : component == "rrp" ? 1995750000000.0 : 6099843000000.0
1653523200000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 801714000000.0 : component == "rrp" ? 2007702000000.0 : 6104865000000.0
1653609600000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 762674000000.0 : component == "rrp" ? 2006688000000.0 : 6144919000000.0
1653955200000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 782309000000.0 : component == "rrp" ? 1978538000000.0 : 6153434000000.0
1654041600000 => component == "fed" ? 8914281000000.0 : component == "tga" ? 854240000000.0 : component == "rrp" ? 1965015000000.0 : 6095795000000.0
1654128000000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 780575000000.0 : component == "rrp" ? 1985239000000.0 : 6149236000000.0
1654214400000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 757559000000.0 : component == "rrp" ? 2031228000000.0 : 6126263000000.0
1654473600000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 731781000000.0 : component == "rrp" ? 2040093000000.0 : 6143176000000.0
1654560000000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 724554000000.0 : component == "rrp" ? 2091395000000.0 : 6099101000000.0
1654646400000 => component == "fed" ? 8915050000000.0 : component == "tga" ? 702336000000.0 : component == "rrp" ? 2140277000000.0 : 6075641000000.0
1654732800000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 683892000000.0 : component == "rrp" ? 2142318000000.0 : 6092044000000.0
1654819200000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 631026000000.0 : component == "rrp" ? 2162885000000.0 : 6124343000000.0
1655078400000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 627393000000.0 : component == "rrp" ? 2212620000000.0 : 6078241000000.0
1655164800000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 653718000000.0 : component == "rrp" ? 2223857000000.0 : 6040679000000.0
1655251200000 => component == "fed" ? 8918254000000.0 : component == "tga" ? 661227000000.0 : component == "rrp" ? 2162924000000.0 : 6108269000000.0
1655337600000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 769937000000.0 : component == "rrp" ? 2178382000000.0 : 5984101000000.0
1655424000000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 755888000000.0 : component == "rrp" ? 2229279000000.0 : 5947253000000.0
1655769600000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 762327000000.0 : component == "rrp" ? 2188627000000.0 : 5981466000000.0
1655856000000 => component == "fed" ? 8932420000000.0 : component == "tga" ? 757733000000.0 : component == "rrp" ? 2259458000000.0 : 5917155000000.0
1655942400000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 745052000000.0 : component == "rrp" ? 2285442000000.0 : 5903852000000.0
1656028800000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 735139000000.0 : component == "rrp" ? 2180984000000.0 : 6018223000000.0
1656288000000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 758505000000.0 : component == "rrp" ? 2155942000000.0 : 6019899000000.0
1656374400000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 768652000000.0 : component == "rrp" ? 2213784000000.0 : 5951910000000.0
1656460800000 => component == "fed" ? 8934346000000.0 : component == "tga" ? 757242000000.0 : component == "rrp" ? 2226976000000.0 : 5929335000000.0
1656547200000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 759845000000.0 : component == "rrp" ? 2329743000000.0 : 5823965000000.0
1656633600000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 782406000000.0 : component == "rrp" ? 2167085000000.0 : 5964062000000.0
1656979200000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 685842000000.0 : component == "rrp" ? 2138280000000.0 : 6089431000000.0
1657065600000 => component == "fed" ? 8913553000000.0 : component == "tga" ? 689482000000.0 : component == "rrp" ? 2168026000000.0 : 6034343000000.0
1657152000000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 687943000000.0 : component == "rrp" ? 2172457000000.0 : 6031451000000.0
1657238400000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 666044000000.0 : component == "rrp" ? 2144921000000.0 : 6080886000000.0
1657497600000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 658096000000.0 : component == "rrp" ? 2164266000000.0 : 6069489000000.0
1657584000000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 665792000000.0 : component == "rrp" ? 2146132000000.0 : 6079927000000.0
1657670400000 => component == "fed" ? 8891851000000.0 : component == "tga" ? 643141000000.0 : component == "rrp" ? 2155290000000.0 : 6097436000000.0
1657756800000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 618740000000.0 : component == "rrp" ? 2207121000000.0 : 6070006000000.0
1657843200000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 595272000000.0 : component == "rrp" ? 2153750000000.0 : 6146845000000.0
1658102400000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 606834000000.0 : component == "rrp" ? 2190375000000.0 : 6098658000000.0
1658188800000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 628659000000.0 : component == "rrp" ? 2211821000000.0 : 6055387000000.0
1658275200000 => component == "fed" ? 8895867000000.0 : component == "tga" ? 636362000000.0 : component == "rrp" ? 2240204000000.0 : 6022647000000.0
1658361600000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 616348000000.0 : component == "rrp" ? 2271756000000.0 : 6011109000000.0
1658448000000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 594035000000.0 : component == "rrp" ? 2228959000000.0 : 6076219000000.0
1658707200000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 589322000000.0 : component == "rrp" ? 2192367000000.0 : 6117524000000.0
1658793600000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 605872000000.0 : component == "rrp" ? 2189474000000.0 : 6103867000000.0
1658880000000 => component == "fed" ? 8899213000000.0 : component == "tga" ? 637228000000.0 : component == "rrp" ? 2188994000000.0 : 6063782000000.0
1658966400000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 615515000000.0 : component == "rrp" ? 2239883000000.0 : 6034606000000.0
1659052800000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 597017000000.0 : component == "rrp" ? 2300200000000.0 : 5992787000000.0
1659312000000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 619273000000.0 : component == "rrp" ? 2161885000000.0 : 6108846000000.0
1659398400000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 551023000000.0 : component == "rrp" ? 2156013000000.0 : 6182968000000.0
1659484800000 => component == "fed" ? 8890004000000.0 : component == "tga" ? 586370000000.0 : component == "rrp" ? 2182238000000.0 : 6106012000000.0
1659571200000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 566577000000.0 : component == "rrp" ? 2191546000000.0 : 6116497000000.0
1659657600000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 554402000000.0 : component == "rrp" ? 2194927000000.0 : 6125291000000.0
1659916800000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 548849000000.0 : component == "rrp" ? 2195692000000.0 : 6130079000000.0
1660003200000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 555513000000.0 : component == "rrp" ? 2186568000000.0 : 6132539000000.0
1660089600000 => component == "fed" ? 8874620000000.0 : component == "tga" ? 583255000000.0 : component == "rrp" ? 2177646000000.0 : 6118237000000.0
1660176000000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 561140000000.0 : component == "rrp" ? 2199247000000.0 : 6118751000000.0
1660262400000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 546978000000.0 : component == "rrp" ? 2213193000000.0 : 6118967000000.0
1660521600000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 548414000000.0 : component == "rrp" ? 2175857000000.0 : 6154867000000.0
1660608000000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 525921000000.0 : component == "rrp" ? 2165332000000.0 : 6187885000000.0
1660694400000 => component == "fed" ? 8879138000000.0 : component == "tga" ? 559827000000.0 : component == "rrp" ? 2199631000000.0 : 6090304000000.0
1660780800000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 539278000000.0 : component == "rrp" ? 2218161000000.0 : 6092323000000.0
1660867200000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 530499000000.0 : component == "rrp" ? 2221680000000.0 : 6097583000000.0
1661126400000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 529281000000.0 : component == "rrp" ? 2235665000000.0 : 6084816000000.0
1661212800000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 543194000000.0 : component == "rrp" ? 2250718000000.0 : 6055850000000.0
1661299200000 => component == "fed" ? 8849762000000.0 : component == "tga" ? 555139000000.0 : component == "rrp" ? 2237072000000.0 : 6059225000000.0
1661385600000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 530196000000.0 : component == "rrp" ? 2187907000000.0 : 6133333000000.0
1661472000000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 580033000000.0 : component == "rrp" ? 2182452000000.0 : 6088951000000.0
1661731200000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 600109000000.0 : component == "rrp" ? 2205188000000.0 : 6046139000000.0
=>
float(na)
val
get_net_liquidity_3(simple string component = "", int ts = 0) =>
float val = switch ts
1661817600000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 610399000000.0 : component == "rrp" ? 2188975000000.0 : 6052062000000.0
1661904000000 => component == "fed" ? 8851436000000.0 : component == "tga" ? 627082000000.0 : component == "rrp" ? 2251025000000.0 : 5947986000000.0
1661990400000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 669911000000.0 : component == "rrp" ? 2173156000000.0 : 5983026000000.0
1662076800000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 598859000000.0 : component == "rrp" ? 2173413000000.0 : 6053821000000.0
1662422400000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 574423000000.0 : component == "rrp" ? 2188796000000.0 : 6062874000000.0
1662508800000 => component == "fed" ? 8826093000000.0 : component == "tga" ? 589596000000.0 : component == "rrp" ? 2206987000000.0 : 6025818000000.0
1662595200000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 582921000000.0 : component == "rrp" ? 2210466000000.0 : 6029014000000.0
1662681600000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 581785000000.0 : component == "rrp" ? 2209714000000.0 : 6030902000000.0
1662940800000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 585000000000.0 : component == "rrp" ? 2218546000000.0 : 6018855000000.0
1663027200000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 601944000000.0 : component == "rrp" ? 2202719000000.0 : 6017738000000.0
1663113600000 => component == "fed" ? 8822401000000.0 : component == "tga" ? 599932000000.0 : component == "rrp" ? 2225579000000.0 : 6007248000000.0
1663200000000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 617997000000.0 : component == "rrp" ? 2176188000000.0 : 6038574000000.0
1663286400000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 677452000000.0 : component == "rrp" ? 2186833000000.0 : 5968474000000.0
1663545600000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 692971000000.0 : component == "rrp" ? 2217542000000.0 : 5922246000000.0
1663632000000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 704998000000.0 : component == "rrp" ? 2238870000000.0 : 5888891000000.0
1663718400000 => component == "fed" ? 8832759000000.0 : component == "tga" ? 695823000000.0 : component == "rrp" ? 2315900000000.0 : 5805079000000.0
1663804800000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 690286000000.0 : component == "rrp" ? 2359227000000.0 : 5767289000000.0
1663891200000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 682027000000.0 : component == "rrp" ? 2319361000000.0 : 5815414000000.0
1664150400000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 697726000000.0 : component == "rrp" ? 2299011000000.0 : 5820065000000.0
1664236800000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 705918000000.0 : component == "rrp" ? 2327111000000.0 : 5783773000000.0
1664323200000 => component == "fed" ? 8816802000000.0 : component == "tga" ? 683943000000.0 : component == "rrp" ? 2366798000000.0 : 5744826000000.0
1664409600000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 661920000000.0 : component == "rrp" ? 2371763000000.0 : 5761884000000.0
1664496000000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 658634000000.0 : component == "rrp" ? 2425910000000.0 : 5711023000000.0
1664755200000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 635994000000.0 : component == "rrp" ? 2252523000000.0 : 5907050000000.0
1664841600000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 630975000000.0 : component == "rrp" ? 2233616000000.0 : 5930976000000.0
1664928000000 => component == "fed" ? 8795567000000.0 : component == "tga" ? 617850000000.0 : component == "rrp" ? 2230799000000.0 : 5910404000000.0
1665014400000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 622131000000.0 : component == "rrp" ? 2232801000000.0 : 5904121000000.0
1665100800000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 612400000000.0 : component == "rrp" ? 2226950000000.0 : 5919703000000.0
1665360000000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 611855000000.0 : component == "rrp" ? 2226950000000.0 : 5920248000000.0
1665446400000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 611855000000.0 : component == "rrp" ? 2222479000000.0 : 5924719000000.0
1665532800000 => component == "fed" ? 8759053000000.0 : component == "tga" ? 614781000000.0 : component == "rrp" ? 2247206000000.0 : 5896982000000.0
1665619200000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 583513000000.0 : component == "rrp" ? 2244100000000.0 : 5931356000000.0
1665705600000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 578283000000.0 : component == "rrp" ? 2222052000000.0 : 5958634000000.0
1665964800000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 574982000000.0 : component == "rrp" ? 2172301000000.0 : 6011686000000.0
1666051200000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 651318000000.0 : component == "rrp" ? 2226725000000.0 : 5880926000000.0
1666137600000 => component == "fed" ? 8758969000000.0 : component == "tga" ? 655230000000.0 : component == "rrp" ? 2241835000000.0 : 5846857000000.0
1666224000000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 640613000000.0 : component == "rrp" ? 2234071000000.0 : 5869238000000.0
1666310400000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 635492000000.0 : component == "rrp" ? 2265809000000.0 : 5842621000000.0
1666569600000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 624584000000.0 : component == "rrp" ? 2242044000000.0 : 5877294000000.0
1666656000000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 636785000000.0 : component == "rrp" ? 2195616000000.0 : 5911521000000.0
1666742400000 => component == "fed" ? 8743922000000.0 : component == "tga" ? 659483000000.0 : component == "rrp" ? 2186856000000.0 : 5876751000000.0
1666828800000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 636327000000.0 : component == "rrp" ? 2152485000000.0 : 5934278000000.0
1666915200000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 625362000000.0 : component == "rrp" ? 2183290000000.0 : 5914438000000.0
1667174400000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 621627000000.0 : component == "rrp" ? 2275459000000.0 : 5826004000000.0
1667260800000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 596470000000.0 : component == "rrp" ? 2200510000000.0 : 5926110000000.0
1667347200000 => component == "fed" ? 8723090000000.0 : component == "tga" ? 551009000000.0 : component == "rrp" ? 2229861000000.0 : 5896000000000.0
1667433600000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 552089000000.0 : component == "rrp" ? 2219791000000.0 : 5904990000000.0
1667520000000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 524883000000.0 : component == "rrp" ? 2230840000000.0 : 5921147000000.0
1667779200000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 524694000000.0 : component == "rrp" ? 2241317000000.0 : 5910859000000.0
1667865600000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 530764000000.0 : component == "rrp" ? 2232555000000.0 : 5913551000000.0
1667952000000 => component == "fed" ? 8676870000000.0 : component == "tga" ? 545285000000.0 : component == "rrp" ? 2237812000000.0 : 5895789000000.0
1668038400000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 517340000000.0 : component == "rrp" ? 2200586000000.0 : 5960960000000.0
1668124800000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 510550000000.0 : component == "rrp" ? 2200586000000.0 : 5967750000000.0
1668384000000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 510550000000.0 : component == "rrp" ? 2165018000000.0 : 6003318000000.0
1668470400000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 524136000000.0 : component == "rrp" ? 2086574000000.0 : 6068176000000.0
1668556800000 => component == "fed" ? 8678886000000.0 : component == "tga" ? 482354000000.0 : component == "rrp" ? 2099070000000.0 : 6044196000000.0
1668643200000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 472185000000.0 : component == "rrp" ? 2114439000000.0 : 6038996000000.0
1668729600000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 465368000000.0 : component == "rrp" ? 2113413000000.0 : 6046839000000.0
1668988800000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 469610000000.0 : component == "rrp" ? 2125426000000.0 : 6030584000000.0
1669075200000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 476764000000.0 : component == "rrp" ? 2103932000000.0 : 6044924000000.0
1669161600000 => component == "fed" ? 8625620000000.0 : component == "tga" ? 512602000000.0 : component == "rrp" ? 2069174000000.0 : 6039614000000.0
1669334400000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 492754000000.0 : component == "rrp" ? 2031066000000.0 : 6097570000000.0
1669593600000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 510532000000.0 : component == "rrp" ? 2054914000000.0 : 6055944000000.0
1669680000000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 517125000000.0 : component == "rrp" ? 2064377000000.0 : 6039888000000.0
1669766400000 => component == "fed" ? 8621390000000.0 : component == "tga" ? 506052000000.0 : component == "rrp" ? 2115913000000.0 : 5962611000000.0
1669852800000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 532791000000.0 : component == "rrp" ? 2050286000000.0 : 6001499000000.0
1669939200000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 458408000000.0 : component == "rrp" ? 2049763000000.0 : 6076405000000.0
1670198400000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 434939000000.0 : component == "rrp" ? 2093647000000.0 : 6055990000000.0
1670284800000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 440836000000.0 : component == "rrp" ? 2111465000000.0 : 6032275000000.0
1670371200000 => component == "fed" ? 8584576000000.0 : component == "tga" ? 411431000000.0 : component == "rrp" ? 2151549000000.0 : 6019755000000.0
1670457600000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 410853000000.0 : component == "rrp" ? 2175973000000.0 : 5995909000000.0
1670544000000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 358794000000.0 : component == "rrp" ? 2146748000000.0 : 6077193000000.0
1670803200000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 357709000000.0 : component == "rrp" ? 2158517000000.0 : 6066509000000.0
1670889600000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 370897000000.0 : component == "rrp" ? 2180676000000.0 : 6031162000000.0
1670976000000 => component == "fed" ? 8582735000000.0 : component == "tga" ? 343699000000.0 : component == "rrp" ? 2192864000000.0 : 6046850000000.0
1671062400000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 342104000000.0 : component == "rrp" ? 2123995000000.0 : 6117314000000.0
1671148800000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 448106000000.0 : component == "rrp" ? 2126540000000.0 : 6008767000000.0
1671408000000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 467544000000.0 : component == "rrp" ? 2134765000000.0 : 5981104000000.0
1671494400000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 482388000000.0 : component == "rrp" ? 2159408000000.0 : 5941617000000.0
1671580800000 => component == "fed" ? 8583413000000.0 : component == "tga" ? 450413000000.0 : component == "rrp" ? 2206965000000.0 : 5907033000000.0
1671667200000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 434922000000.0 : component == "rrp" ? 2222898000000.0 : 5906591000000.0
1671753600000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 429684000000.0 : component == "rrp" ? 2216348000000.0 : 5918379000000.0
1672099200000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 431253000000.0 : component == "rrp" ? 2221259000000.0 : 5911899000000.0
1672185600000 => component == "fed" ? 8564411000000.0 : component == "tga" ? 430977000000.0 : component == "rrp" ? 2293003000000.0 : 5827189000000.0
1672272000000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 409809000000.0 : component == "rrp" ? 2308319000000.0 : 5833041000000.0
1672358400000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 412900000000.0 : component == "rrp" ? 2553716000000.0 : 5584553000000.0
1672704000000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 446685000000.0 : component == "rrp" ? 2188272000000.0 : 5916212000000.0
1672790400000 => component == "fed" ? 8551169000000.0 : component == "tga" ? 386114000000.0 : component == "rrp" ? 2229542000000.0 : 5891773000000.0
1672876800000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 379620000000.0 : component == "rrp" ? 2242486000000.0 : 5885323000000.0
1672963200000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 379653000000.0 : component == "rrp" ? 2208265000000.0 : 5919511000000.0
1673222400000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 375694000000.0 : component == "rrp" ? 2199121000000.0 : 5932614000000.0
1673308800000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 385220000000.0 : component == "rrp" ? 2192942000000.0 : 5929267000000.0
1673395200000 => component == "fed" ? 8507429000000.0 : component == "tga" ? 368000000000.0 : component == "rrp" ? 2199170000000.0 : 5941417000000.0
1673481600000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 346426000000.0 : component == "rrp" ? 2202989000000.0 : 5959172000000.0
1673568000000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 310363000000.0 : component == "rrp" ? 2179781000000.0 : 6018443000000.0
1673913600000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 321572000000.0 : component == "rrp" ? 2093328000000.0 : 6093687000000.0
1674000000000 => component == "fed" ? 8508587000000.0 : component == "tga" ? 398974000000.0 : component == "rrp" ? 2131678000000.0 : 5958387000000.0
1674086400000 => component == "fed" ? 8489039000000.0 : component == "tga" ? 377500000000.0 : component == "rrp" ? 2110145000000.0 : 6001394000000.0
1674172800000 => component == "fed" ? 8489039000000.0 : component == "tga" ? 455623000000.0 : component == "rrp" ? 2090523000000.0 : 5942893000000.0
1674432000000 => component == "fed" ? 8489039000000.0 : component == "tga" ? 454615000000.0 : component == "rrp" ? 2135499000000.0 : 5898925000000.0
=>
float(na)
val
get_net_liquidity_4(simple string component = "", int ts = 0) =>
float val = switch ts
1674518400000 => component == "fed" ? 8489039000000.0 : component == "tga" ? 471005000000.0 : component == "rrp" ? 2048386000000.0 : 5969648000000.0
1674604800000 => component == "fed" ? 8470557000000.0 : component == "tga" ? 579841000000.0 : component == "rrp" ? 2031561000000.0 : 5859155000000.0
1674691200000 => component == "fed" ? 8470557000000.0 : component == "tga" ? 572622000000.0 : component == "rrp" ? 2024069000000.0 : 5873866000000.0
1674777600000 => component == "fed" ? 8470557000000.0 : component == "tga" ? 568553000000.0 : component == "rrp" ? 2003634000000.0 : 5898370000000.0
1675036800000 => component == "fed" ? 8470557000000.0 : component == "tga" ? 567827000000.0 : component == "rrp" ? 2048714000000.0 : 5854016000000.0
1675123200000 => component == "fed" ? 8470557000000.0 : component == "tga" ? 579826000000.0 : component == "rrp" ? 2061572000000.0 : 5829159000000.0
1675209600000 => component == "fed" ? 8433610000000.0 : component == "tga" ? 567908000000.0 : component == "rrp" ? 2038262000000.0 : 5827440000000.0
1675296000000 => component == "fed" ? 8433610000000.0 : component == "tga" ? 500852000000.0 : component == "rrp" ? 2050063000000.0 : 5882695000000.0
1675382400000 => component == "fed" ? 8433610000000.0 : component == "tga" ? 506179000000.0 : component == "rrp" ? 2041217000000.0 : 5886214000000.0
1675641600000 => component == "fed" ? 8433610000000.0 : component == "tga" ? 477618000000.0 : component == "rrp" ? 2072261000000.0 : 5883731000000.0
1675728000000 => component == "fed" ? 8433610000000.0 : component == "tga" ? 489948000000.0 : component == "rrp" ? 2057958000000.0 : 5885704000000.0
1675814400000 => component == "fed" ? 8435369000000.0 : component == "tga" ? 528118000000.0 : component == "rrp" ? 2059604000000.0 : 5847647000000.0
1675900800000 => component == "fed" ? 8435369000000.0 : component == "tga" ? 495838000000.0 : component == "rrp" ? 2058942000000.0 : 5880589000000.0
1675987200000 => component == "fed" ? 8435369000000.0 : component == "tga" ? 494252000000.0 : component == "rrp" ? 2042893000000.0 : 5898224000000.0
1676246400000 => component == "fed" ? 8435369000000.0 : component == "tga" ? 490201000000.0 : component == "rrp" ? 2107775000000.0 : 5837393000000.0
1676332800000 => component =="fed"? 8435369000000.0 :component == "tga"? 501103000000.0 :component == "rrp"? 2076548000000.0 : 5857718000000.0
1676419200000 => component =="fed"? 8384767000000.0 :component == "tga"? 526992000000.0 :component == "rrp"? 2011998000000.0 : 5845777000000.0
1676505600000 => component =="fed"? 8384767000000.0 :component == "tga"? 439703000000.0 :component == "rrp"? 2032457000000.0 : 5912607000000.0
1676592000000 => component=="fed"? 8384767000000.0 :component == "tga"? 479039000000.0 :component == "rrp"? 2059662000000.0 : 5846066000000.0
1676937600000 => component=="fed"? 8384767000000.0 :component == "tga"? 475675000000.0 :component == "rrp"? 2046064000000.0 : 5863028000000.0
1677024000000 => component=="fed"? 8382190000000.0 :component == "tga"? 508286000000.0 :component == "rrp"? 2113849000000.0 : 5760055000000.0
1677110400000 => component=="fed"? 8382190000000.0 :component == "tga"? 451307000000.0 :component == "rrp"? 2147417000000.0 : 5783466000000.0
1677196800000 => component=="fed"? 8382190000000.0 :component == "tga"? 363666000000.0 :component == "rrp"? 2142141000000.0 : 5876383000000.0
1677456000000 => component=="fed"? 8382190000000.0 :component == "tga"? 381671000000.0 :component == "rrp"? 2162435000000.0 : 5838084000000.0
1677542400000 => component=="fed"? 8382190000000.0 :component == "tga"? 394017000000.0 :component == "rrp"? 2188035000000.0 : 5800138000000.0
1677628800000 => component=="fed"? 8339684000000.0 :component == "tga"? 415005000000.0 :component == "rrp"? 213395000000.0 : 7711284000000.0
1677715200000 => component=="fed"? 8339684000000.0 :component == "tga"? 351015000000.0 :component == "rrp"? 2192355000000.0 : 5796314000000.0
1677801600000 => component=="fed"? 8339684000000.0 :component == "tga"? 355232000000.0 :component == "rrp"? 218615000000.0 : 7765837000000.0
1678060800000 => component=="fed"? 8339684000000.0 :component == "tga"? 327193000000.0 :component == "rrp"? 2190793000000.0 : 5821698000000.0
1678147200000 => component=="fed"? 8339684000000.0 :component == "tga"? 340182000000.0 :component == "rrp"? 2170195000000.0 : 5829307000000.0
1678233600000 => component=="fed"? 8342283000000.0 :component == "tga"? 344724000000.0 :component == "rrp"? 2193237000000.0 : 5804322000000.0
1678320000000 => component=="fed"? 8342283000000.0 :component == "tga"? 311731000000.0 :component == "rrp"? 2229623000000.0 : 5800929000000.0
1678406400000 => component=="fed"? 8342283000000.0 :component == "tga"? 246969000000.0 :component == "rrp"? 2188375000000.0 : 5906939000000.0
1678665600000 => component=="fed"? 8342283000000.0 :component == "tga"? 208074000000.0 :component == "rrp"? 2126677000000.0 : 6007532000000.0
1678752000000 => component=="fed"? 8342283000000.0 :component == "tga"? 227312000000.0 :component == "rrp"? 2042579000000.0 : 6072392000000.0
1678838400000 => component=="fed"? 8639300000000.0 :component == "tga"? 253921000000.0 :component == "rrp"? 2055823000000.0 : 6329556000000.0
1678924800000 => component=="fed"? 8639300000000.0 :component == "tga"? 277643000000.0 :component == "rrp"? 2066319000000.0 : 6295338000000.0
1679011200000 => component=="fed"? 8639300000000.0 :component == "tga"? 285108000000.0 :component == "rrp"? 2106166000000.0 : 6248026000000.0
1679270400000 => component=="fed"? 8639300000000.0 :component == "tga"? 280148000000.0 :component == "rrp"? 2098393000000.0 : 6260759000000.0
1679356800000 => component=="fed"? 8639300000000.0 :component == "tga"? 267101000000.0 :component == "rrp"? 2194631000000.0 : 6177568000000.0
1679443200000 => component=="fed"? 8733787000000.0 :component == "tga"? 224604000000.0 :component == "rrp"? 2279608000000.0 : 6229575000000.0
1679529600000 => component=="fed"? 8733787000000.0 :component == "tga"? 199856000000.0 :component == "rrp"? 2233956000000.0 : 6299975000000.0
1679616000000 => component=="fed"? 8733787000000.0 :component == "tga"? 192910000000.0 :component == "rrp"? 2218458000000.0 : 6322419000000.0
1679875200000 => component=="fed"? 8733787000000.0 :component == "tga"? 187365000000.0 :component == "rrp"? 2220131000000.0 : 6326291000000.0
1679961600000 => component=="fed"? 8733787000000.0 :component == "tga"? 200926000000.0 :component == "rrp"? 2231749000000.0 : 6301112000000.0
1680048000000 => component=="fed"? 8705942000000.0 :component == "tga"? 166348000000.0 :component == "rrp"? 2264862000000.0 : 6274732000000.0
1680134400000 => component=="fed"? 8705942000000.0 :component == "tga"? 162758000000.0 :component == "rrp"? 2271531000000.0 : 6271653000000.0
1680220800000 => component=="fed"? 8705942000000.0 :component == "tga"? 194336000000.0 :component == "rrp"? 2375171000000.0 : 6136435000000.0
1680480000000 => component=="fed"? 8705942000000.0 :component == "tga"? 177692000000.0 :component == "rrp"? 222101000000.0 : 8306149000000.0
1680566400000 => component=="fed"? 8705942000000.0 :component == "tga"? 173105000000.0 :component == "rrp"? 2219375000000.0 : 6313462000000.0
1680652800000 => component=="fed"? 8632384000000.0 :component == "tga"? 140347000000.0 :component == "rrp"? 2243011000000.0 : 6249026000000.0
1680739200000 => component=="fed"? 8632384000000.0 :component == "tga"? 140688000000.0 :component == "rrp"? 2173663000000.0 : 6318033000000.0
1681084800000 => component=="fed"? 8632384000000.0 :component == "tga"? 110822000000.0 :component == "rrp"? 2239655000000.0 : 6281907000000.0
1681171200000 => component=="fed"? 8632384000000.0 :component == "tga"? 125004000000.0 :component == "rrp"? 2297208000000.0 : 6210172000000.0
1681257600000 => component=="fed"? 8614797000000.0 :component == "tga"? 107469000000.0 :component == "rrp"? 2303862000000.0 : 6203466000000.0
1681344000000 => component=="fed"? 8614797000000.0 :component == "tga"? 86554000000.0 :component == "rrp"? 2321699000000.0 : 6206544000000.0
1681430400000 => component=="fed"? 8614797000000.0 :component == "tga"? 99488000000.0 :component == "rrp"? 2253786000000.0 : 6261523000000.0
1681689600000 => component=="fed"? 8614797000000.0 :component == "tga"? 134890000000.0 :component == "rrp"? 2256845000000.0 : 6223062000000.0
1681776000000 => component=="fed"? 8614797000000.0 :component == "tga"? 144079000000.0 :component == "rrp"? 2238994000000.0 : 6231724000000.0
1681862400000 => component=="fed"? 8593263000000.0 :component == "tga"? 252552000000.0 :component == "rrp"? 2294677000000.0 : 6046034000000.0
1681948800000 => component=="fed"? 8593263000000.0 :component == "tga"? 265095000000.0 :component == "rrp"? 2277259000000.0 : 6050909000000.0
1682035200000 => component=="fed"? 8593263000000.0 :component == "tga"? 279942000000.0 :component == "rrp"? 2290023000000.0 : 6023298000000.0
1682294400000 => component=="fed"? 8593263000000.0 :component == "tga"? 280912000000.0 :component == "rrp"? 2308538000000.0 : 6003813000000.0
1682380800000 => component=="fed"? 8593263000000.0 :component == "tga"? 307101000000.0 :component == "rrp"? 2275402000000.0 : 6010760000000.0
1682467200000 => component=="fed"? 8562768000000.0 :component == "tga"? 315930000000.0 :component == "rrp"? 2279561000000.0 : 5967277000000.0
1682553600000 => component=="fed"? 8562768000000.0 :component == "tga"? 296209000000.0 :component == "rrp"? 2273926000000.0 : 5992633000000.0
1682640000000 => component=="fed"? 8562768000000.0 :component == "tga"? 293717000000.0 :component == "rrp"? 2325479000000.0 : 5943572000000.0
1682899200000 => component=="fed"? 8562768000000.0 :component == "tga"? 316381000000.0 :component == "rrp"? 2239866000000.0 : 6006521000000.0
1682985600000 => component=="fed"? 8562768000000.0 :component == "tga"? 238463000000.0 :component == "rrp"? 226713000000.0 : 8097592000000.0
1683072000000 => component=="fed"? 8503994000000.0 :component == "tga"? 214882000000.0 :component == "rrp"? 2258222000000.0 : 6030890000000.0
1683158400000 => component=="fed"? 8503994000000.0 :component == "tga"? 188309000000.0 :component == "rrp"? 2242399000000.0 : 6073286000000.0
1683244800000 => component=="fed"? 8503994000000.0 :component == "tga"? 208666000000.0 :component == "rrp"? 2207415000000.0 : 6087913000000.0
1683504000000 => component=="fed"? 8503994000000.0 :component == "tga"? 206714000000.0 :component == "rrp"? 2217601000000.0 : 6079679000000.0
1683590400000 => component=="fed"? 8503994000000.0 :component == "tga"? 215133000000.0 :component == "rrp"? 2222864000000.0 : 6065997000000.0
1683676800000 => component=="fed"? 8503017000000.0 :component == "tga"? 184915000000.0 :component == "rrp"? 2233149000000.0 : 6084953000000.0
1683763200000 => component=="fed"? 8503017000000.0 :component == "tga"? 154808000000.0 :component == "rrp"? 2242243000000.0 : 6105966000000.0
1683849600000 => component=="fed"? 8503017000000.0 :component == "tga"? 143314000000.0 :component == "rrp"? 2229199000000.0 : 6130504000000.0
1684108800000 => component=="fed"? 8503017000000.0 :component == "tga"? 139944000000.0 :component == "rrp"? 2220927000000.0 : 6142146000000.0
1684195200000 => component=="fed"? 8503017000000.0 :component == "tga"? 87431000000.0 :component == "rrp"? 2203214000000.0 : 6212372000000.0
1684281600000 => component=="fed"? 8456760000000.0 :component == "tga"? 94629000000.0 :component == "rrp"? 2213676000000.0 : 6148455000000.0
1684368000000 => component=="fed"? 8456760000000.0 :component == "tga"? 68332000000.0 :component == "rrp"? 2238266000000.0 : 6150162000000.0
1684454400000 => component=="fed"? 8456760000000.0 :component == "tga"? 57341000000.0 :component == "rrp"? 227672000000.0 : 8171747000000.0
1684713600000 => component=="fed"? 8456760000000.0 :component == "tga"? 60656000000.0 :component == "rrp"? 2275311000000.0 : 6120793000000.0
1684800000000 => component=="fed"? 8456760000000.0 :component == "tga"? 68335000000.0 :component == "rrp"? 2256689000000.0 : 6131736000000.0
1684886400000 => component=="fed"? 8436255000000.0 :component == "tga"? 15890000000.0 :component == "rrp"? 2250709000000.0 : 6169656000000.0
1684972800000 => component=="fed"? 8436255000000.0 :component == "tga"? 164507000000.0 :component == "rrp"? 2197638000000.0 : 6074110000000.0
1685059200000 => component=="fed"? 8436255000000.0 :component == "tga"? 36958000000.0 :component == "rrp"? 2189681000000.0 : 6209616000000.0
1685404800000 => component=="fed"? 8436255000000.0 :component == "tga"? 143510000000.0 :component == "rrp"? 2200479000000.0 : 6092266000000.0
1685491200000 => component=="fed"? 8385854000000.0 :component == "tga"? 189427000000.0 :component == "rrp"? 2254859000000.0 : 5941568000000.0
1685577600000 => component=="fed"? 8385854000000.0 :component == "tga"? 207439000000.0 :component == "rrp"? 2160055000000.0 : 6018360000000.0
1685664000000 => component=="fed"? 8385854000000.0 :component == "tga"? 39315000000.0 :component == "rrp"? 2142102000000.0 : 6204437000000.0
1685923200000 => component=="fed"? 8385854000000.0 :component == "tga"? 105944000000.0 :component == "rrp"? 2131417000000.0 : 6148493000000.0
1686009600000 => component=="fed"? 8385854000000.0 :component == "tga"? 174089000000.0 :component == "rrp"? 2134638000000.0 : 6077127000000.0
1686096000000 => component=="fed"? 8389325000000.0 :component == "tga"? 18846000000.0 :component == "rrp"? 2161556000000.0 : 6208923000000.0
1686182400000 => component=="fed"? 8389325000000.0 :component == "tga"? 137524000000.0 :component == "rrp"? 2141798000000.0 : 6110003000000.0
1686268800000 => component=="fed"? 8389325000000.0 :component == "tga"? 14964000000.0 :component == "rrp"? 2127652000000.0 : 6246709000000.0
1686528000000 => component=="fed"? 8389325000000.0 :component == "tga"? 34315000000.0 :component == "rrp"? 212687000000.0 : 8142323000000.0
1686614400000 => component=="fed"? 8389325000000.0 :component == "tga"? 176961000000.0 :component == "rrp"? 207452000000.0 : 8004912000000.0
1686700800000 => component=="fed"? 8388323000000.0 :component == "tga"? 41989000000.0 :component == "rrp"? 2109105000000.0 : 6237229000000.0
1686787200000 => component=="fed"? 8388323000000.0 :component == "tga"? 370127000000.0 :component == "rrp"? 199214000000.0 : 7818982000000.0
1686873600000 => component=="fed"? 8388323000000.0 :component == "tga"? 30625000000.0 :component == "rrp"? 2011556000000.0 : 6346142000000.0
1687219200000 => component=="fed"? 8388323000000.0 :component == "tga"? 200092000000.0 :component == "rrp"? 1989489000000.0 : 6198742000000.0
1687305600000 => component=="fed"? 8362060000000.0 :component == "tga"? 15992000000.0 :component == "rrp"? 2037102000000.0 : 6308966000000.0
1687392000000 => component=="fed"? 8362060000000.0 :component == "tga"? 202337000000.0 :component == "rrp"? 1994711000000.0 : 6165012000000.0
=>
float(na)
val
get_net_liquidity_5(simple string component = "", int ts = 0) =>
float val = switch ts
1687478400000 => component=="fed"? 8362060000000.0 :component == "tga"? 30036000000.0 :component == "rrp"? 196938000000.0 : 8135086000000.0
1687737600000 => component=="fed"? 8362060000000.0 :component == "tga"? 29537000000.0 :component == "rrp"? 1961027000000.0 : 6371496000000.0
1687824000000 => component=="fed"? 8362060000000.0 :component == "tga"? 187036000000.0 :component == "rrp"? 1951098000000.0 : 6223926000000.0
1687910400000 => component=="fed"? 8340914000000.0 :component == "tga"? 16120000000.0 :component == "rrp"? 1945211000000.0 : 6379583000000.0
1687996800000 => component=="fed"? 8340914000000.0 :component == "tga"? 191011000000.0 :component == "rrp"? 1934684000000.0 : 6215219000000.0
1688083200000 => component=="fed"? 8340914000000.0 :component == "tga"? 192944000000.0 :component == "rrp"? 2034319000000.0 : 6113651000000.0
1688342400000 => component=="fed"? 8340914000000.0 :component == "tga"? 46919000000.0 :component == "rrp"? 1909639000000.0 : 6384356000000.0
1688515200000 => component=="fed"? 8298312000000.0 :component == "tga"? 189531000000.0 :component == "rrp"? 1867061000000.0 : 6241720000000.0
1688601600000 => component=="fed"? 8298312000000.0 :component == "tga"? 200190000000.0 :component == "rrp"? 1854256000000.0 : 6243866000000.0
1688688000000 => component=="fed"? 8298312000000.0 :component == "tga"? 12167000000.0 :component == "rrp"? 1822303000000.0 : 6463842000000.0
1688947200000 => component=="fed"? 8298312000000.0 :component == "tga"? 26137000000.0 :component == "rrp"? 1811981000000.0 : 6460194000000.0
1689033600000 => component=="fed"? 8298312000000.0 :component == "tga"? 186782000000.0 :component == "rrp"? 1775796000000.0 : 6335734000000.0
1689120000000 => component=="fed"? 8296923000000.0 :component == "tga"? 15782000000.0 :component == "rrp"? 1820146000000.0 : 6460995000000.0
1689206400000 => component=="fed"? 8296923000000.0 :component == "tga"? 229099000000.0 :component == "rrp"? 1767432000000.0 : 6300392000000.0
1689292800000 => component=="fed"? 8296923000000.0 :component == "tga"? 17310000000.0 :component == "rrp"? 1740777000000.0 : 6538836000000.0
1689552000000 => component=="fed"? 8296923000000.0 :component == "tga"? 133613000000.0 :component == "rrp"? 1728322000000.0 : 6434988000000.0
1689638400000 => component=="fed"? 8296923000000.0 :component == "tga"? 185523000000.0 :component == "rrp"? 1716862000000.0 : 6394538000000.0
1689724800000 => component=="fed"? 8274552000000.0 :component == "tga"? 16350000000.0 :component == "rrp"? 1732804000000.0 : 6525398000000.0
1689811200000 => component=="fed"? 8274552000000.0 :component == "tga"? 189941000000.0 :component == "rrp"? 1721001000000.0 : 6363610000000.0
1689897600000 => component=="fed"? 8274552000000.0 :component == "tga"? 12546000000.0 :component == "rrp"? 1770752000000.0 : 6491254000000.0
1690156800000 => component=="fed"? 8274552000000.0 :component == "tga"? 27763000000.0 :component == "rrp"? 1770867000000.0 : 6475922000000.0
1690243200000 => component=="fed"? 8274552000000.0 :component == "tga"? 190442000000.0 :component == "rrp"? 1720716000000.0 : 6363394000000.0
1690329600000 => component=="fed"? 8243344000000.0 :component == "tga"? 16309000000.0 :component == "rrp"? 1749733000000.0 : 6477302000000.0
1690416000000 => component=="fed"? 8243344000000.0 :component == "tga"? 189491000000.0 :component == "rrp"? 1735783000000.0 : 6318070000000.0
1690502400000 => component=="fed"? 8243344000000.0 :component == "tga"? 13512000000.0 :component == "rrp"? 1730227000000.0 : 6499605000000.0
1690761600000 => component=="fed"? 8243344000000.0 :component == "tga"? 204885000000.0 :component == "rrp"? 1821124000000.0 : 6217335000000.0
1690848000000 => component=="fed"? 8243344000000.0 :component == "tga"? 206208000000.0 :component == "rrp"? 1739554000000.0 : 6297582000000.0
1690934400000 => component=="fed"? 8206764000000.0 :component == "tga"? 18633000000.0 :component == "rrp"? 1770186000000.0 : 6417945000000.0
1691020800000 => component=="fed"? 8206764000000.0 :component == "tga"? 194530000000.0 :component == "rrp"? 1776774000000.0 : 6235460000000.0
1691107200000 => component=="fed"? 8206764000000.0 :component == "tga"? 14498000000.0 :component == "rrp"? 1793804000000.0 : 6398462000000.0
1691366400000 => component=="fed"? 8206764000000.0 :component == "tga"? 26597000000.0 :component == "rrp"? 1810583000000.0 : 6369584000000.0
1691452800000 => component=="fed"? 8206764000000.0 :component == "tga"? 187017000000.0 :component == "rrp"? 1778351000000.0 : 6241396000000.0
1691539200000 => component=="fed"? 8208241000000.0 :component == "tga"? 14522000000.0 :component == "rrp"? 1796519000000.0 : 6397200000000.0
1691625600000 => component=="fed"? 8208241000000.0 :component == "tga"? 242048000000.0 :component == "rrp"? 1759897000000.0 : 6206296000000.0
1691712000000 => component=="fed"? 8208241000000.0 :component == "tga"? 13758000000.0 :component == "rrp"? 1773236000000.0 : 6421247000000.0
1691971200000 => component=="fed"? 8208241000000.0 :component == "tga"? 26408000000.0 :component == "rrp"? 1799311000000.0 : 6382522000000.0
1692057600000 => component=="fed"? 8208241000000.0 :component == "tga"? 345371000000.0 :component == "rrp"? 1743784000000.0 : 6119086000000.0
1692144000000 => component=="fed"? 8145727000000.0 :component == "tga"? 27228000000.0 :component == "rrp"? 1796725000000.0 : 6321774000000.0
1692230400000 => component=="fed"? 8145727000000.0 :component == "tga"? 211427000000.0 :component == "rrp"? 179412000000.0 : 7754888000000.0
1692316800000 => component=="fed"? 8145727000000.0 :component == "tga"? 14386000000.0 :component == "rrp"? 1819201000000.0 : 6312140000000.0
1692576000000 => component=="fed"? 8145727000000.0 :component == "tga"? 27676000000.0 :component == "rrp"? 1824788000000.0 : 6293263000000.0
1692662400000 => component=="fed"? 8145727000000.0 :component == "tga"? 215253000000.0 :component == "rrp"? 1812294000000.0 : 6118180000000.0
1692748800000 => component=="fed"? 8139066000000.0 :component == "tga"? 15230000000.0 :component == "rrp"? 1816533000000.0 : 6307303000000.0
1692835200000 => component=="fed"? 8139066000000.0 :component == "tga"? 206522000000.0 :component == "rrp"? 1731623000000.0 : 6200921000000.0
1692921600000 => component=="fed"? 8139066000000.0 :component == "tga"? 36269000000.0 :component == "rrp"? 1687379000000.0 : 6415418000000.0
1693180800000 => component=="fed"? 8139066000000.0 :component == "tga"? 26789000000.0 :component == "rrp"? 1708605000000.0 : 6403672000000.0
1693267200000 => component=="fed"? 8139066000000.0 :component == "tga"? 214409000000.0 :component == "rrp"? 1693278000000.0 : 6231379000000.0
1693353600000 => component=="fed"? 8121316000000.0 :component == "tga"? 16731000000.0 :component == "rrp"? 1696819000000.0 : 6407766000000.0
1693440000000 => component=="fed"? 8121316000000.0 :component == "tga"? 377954000000.0 :component == "rrp"? 1651602000000.0 : 6091760000000.0
1693526400000 => component=="fed"? 8121316000000.0 :component == "tga"? 34087000000.0 :component == "rrp"? 1574065000000.0 : 6513164000000.0
1693872000000 => component=="fed"? 8121316000000.0 :component == "tga"? 234106000000.0 :component == "rrp"? 156849000000.0 : 7730361000000.0
1693958400000 => component=="fed"? 8101318000000.0 :component == "tga"? 11967000000.0 :component == "rrp"? 1606244000000.0 : 6483107000000.0
1694044800000 => component=="fed"? 8101318000000.0 :component == "tga"? 253752000000.0 :component == "rrp"? 1535289000000.0 : 6312277000000.0
1694131200000 => component=="fed"? 8101318000000.0 :component == "tga"? 14508000000.0 :component == "rrp"? 1525403000000.0 : 6561407000000.0
1694390400000 => component=="fed"? 8101318000000.0 :component == "tga"? 31306000000.0 :component == "rrp"? 1549111000000.0 : 6520901000000.0
1694476800000 => component=="fed"? 8101318000000.0 :component == "tga"? 220018000000.0 :component == "rrp"? 1493781000000.0 : 6387519000000.0
1694563200000 => component=="fed"? 8098779000000.0 :component == "tga"? 33541000000.0 :component == "rrp"? 1546225000000.0 : 6519013000000.0
1694649600000 => component=="fed"? 8098779000000.0 :component == "tga"? 234044000000.0 :component == "rrp"? 1492427000000.0 : 6372308000000.0
1694736000000 => component=="fed"? 8098779000000.0 :component == "tga"? 178711000000.0 :component == "rrp"? 1401403000000.0 : 6518665000000.0
1694995200000 => component=="fed"? 8098779000000.0 :component == "tga"? 48186000000.0 :component == "rrp"? 1452942000000.0 : 6597651000000.0
1695081600000 => component=="fed"? 8098779000000.0 :component == "tga"? 213643000000.0 :component == "rrp"? 1453324000000.0 : 6431812000000.0
1695168000000 => component=="fed"? 8024090000000.0 :component == "tga"? 29554000000.0 :component == "rrp"? 1486984000000.0 : 6507552000000.0
1695254400000 => component=="fed"? 8024090000000.0 :component == "tga"? 213146000000.0 :component == "rrp"? 1454115000000.0 : 6356829000000.0
1695340800000 => component=="fed"? 8024090000000.0 :component == "tga"? 18215000000.0 :component == "rrp"? 1427575000000.0 : 6578300000000.0
1695600000000 => component=="fed"? 8024090000000.0 :component == "tga"? 32732000000.0 :component == "rrp"? 143731000000.0 : 7847627000000.0
1695686400000 => component=="fed"? 8024090000000.0 :component == "tga"? 216065000000.0 :component == "rrp"? 1438301000000.0 : 6369724000000.0
1695772800000 => component=="fed"? 8002064000000.0 :component == "tga"? 17461000000.0 :component == "rrp"? 1442805000000.0 : 6541798000000.0
1695859200000 => component=="fed"? 8002064000000.0 :component == "tga"? 204916000000.0 :component == "rrp"? 1453366000000.0 : 6343782000000.0
1695945600000 => component=="fed"? 8002064000000.0 :component == "tga"? 76574000000.0 :component == "rrp"? 1557569000000.0 : 6367921000000.0
1696204800000 => component=="fed"? 8002064000000.0 :component == "tga"? 199672000000.0 :component == "rrp"? 1365739000000.0 : 6436653000000.0
1696291200000 => component=="fed"? 8002064000000.0 :component == "tga"? 225432000000.0 :component == "rrp"? 1348465000000.0 : 6428167000000.0
1696377600000 => component=="fed"? 7955782000000.0 :component == "tga"? 19915000000.0 :component == "rrp"? 1342031000000.0 : 6593836000000.0
1696464000000 => component=="fed"? 7955782000000.0 :component == "tga"? 263620000000.0 :component == "rrp"? 1265132000000.0 : 6427030000000.0
1696550400000 => component=="fed"? 7955782000000.0 :component == "tga"? 16050000000.0 :component == "rrp"? 1283461000000.0 : 6656271000000.0
1696896000000 => component=="fed"? 7955782000000.0 :component == "tga"? 255806000000.0 :component == "rrp"? 122244000000.0 : 7577732000000.0
1696982400000 => component=="fed"? 7952054000000.0 :component == "tga"? 16677000000.0 :component == "rrp"? 1239382000000.0 : 6695995000000.0
1697068800000 => component=="fed"? 7952054000000.0 :component == "tga"? 239937000000.0 :component == "rrp"? 1157319000000.0 : 6554798000000.0
1697155200000 => component=="fed"? 7952054000000.0 :component == "tga"? 30421000000.0 :component == "rrp"? 1151818000000.0 : 6769815000000.0
1697414400000 => component=="fed"? 7952054000000.0 :component == "tga"? 188042000000.0 :component == "rrp"? 1108819000000.0 : 6655193000000.0
1697500800000 => component=="fed"? 7952054000000.0 :component == "tga"? 256208000000.0 :component == "rrp"? 1082502000000.0 : 6613344000000.0
1697587200000 => component=="fed"? 7933162000000.0 :component == "tga"? 22481000000.0 :component == "rrp"? 1150781000000.0 : 6759900000000.0
1697673600000 => component=="fed"? 7933162000000.0 :component == "tga"? 236119000000.0 :component == "rrp"? 1114179000000.0 : 6582864000000.0
1697760000000 => component=="fed"? 7933162000000.0 :component == "tga"? 14343000000.0 :component == "rrp"? 1138756000000.0 : 6780063000000.0
1698019200000 => component=="fed"? 7933162000000.0 :component == "tga"? 29155000000.0 :component == "rrp"? 1157976000000.0 : 6746031000000.0
1698105600000 => component=="fed"? 7933162000000.0 :component == "tga"? 252656000000.0 :component == "rrp"? 1097875000000.0 : 6582631000000.0
1698192000000 => component=="fed"? 7907830000000.0 :component == "tga"? 20023000000.0 :component == "rrp"? 1100617000000.0 : 6787190000000.0
1698278400000 => component=="fed"? 7907830000000.0 :component == "tga"? 234988000000.0 :component == "rrp"? 108985000000.0 : 7563857000000.0
1698364800000 => component=="fed"? 7907830000000.0 :component == "tga"? 15280000000.0 :component == "rrp"? 1091858000000.0 : 6800692000000.0
1698624000000 => component=="fed"? 7907830000000.0 :component == "tga"? 28120000000.0 :component == "rrp"? 1138035000000.0 : 6741675000000.0
1698710400000 => component=="fed"? 7907830000000.0 :component == "tga"? 454211000000.0 :component == "rrp"? 1137697000000.0 : 6315922000000.0
1698796800000 => component=="fed"? 7866664000000.0 :component == "tga"? 36466000000.0 :component == "rrp"? 1079462000000.0 : 6750736000000.0
1698883200000 => component=="fed"? 7866664000000.0 :component == "tga"? 290379000000.0 :component == "rrp"? 1054986000000.0 : 6521299000000.0
1698969600000 => component=="fed"? 7866664000000.0 :component == "tga"? 14449000000.0 :component == "rrp"? 1071139000000.0 : 6781076000000.0
1699228800000 => component=="fed"? 7866664000000.0 :component == "tga"? 24573000000.0 :component == "rrp"? 1062878000000.0 : 6779213000000.0
1699315200000 => component=="fed"? 7866664000000.0 :component == "tga"? 246586000000.0 :component == "rrp"? 1008685000000.0 : 6611393000000.0
1699401600000 => component=="fed"? 7860691000000.0 :component == "tga"? 16181000000.0 :component == "rrp"? 1024451000000.0 : 6820059000000.0
1699488000000 => component=="fed"? 7860691000000.0 :component == "tga"? 236604000000.0 :component == "rrp"? 993314000000.0 : 6630773000000.0
1699574400000 => component=="fed"? 7860691000000.0 :component == "tga"? 10369000000.0 :component == "rrp"? 103272000000.0 : 7747050000000.0
1699833600000 => component=="fed"? 7860691000000.0 :component == "tga"? 29976000000.0 :component == "rrp"? 1020272000000.0 : 6810443000000.0
1699920000000 => component=="fed"? 7860691000000.0 :component == "tga"? 250280000000.0 :component == "rrp"? 988298000000.0 : 6622113000000.0
1700006400000 => component=="fed"? 7814991000000.0 :component == "tga"? 137685000000.0 :component == "rrp"? 944241000000.0 : 6733065000000.0
1700092800000 => component=="fed"? 7814991000000.0 :component == "tga"? 251278000000.0 :component == "rrp"? 91201000000.0 : 7472512000000.0
1700179200000 => component=="fed"? 7814991000000.0 :component == "tga"? 16317000000.0 :component == "rrp"? 935803000000.0 : 6862871000000.0
1700438400000 => component=="fed"? 7814991000000.0 :component == "tga"? 26042000000.0 :component == "rrp"? 953088000000.0 : 6835861000000.0
1700524800000 => component=="fed"? 7814991000000.0 :component == "tga"? 248491000000.0 :component == "rrp"? 931155000000.0 : 6635345000000.0
=>
float(na)
val
// @function Gets the Net Liquidity time series for the last 250 trading days. Dates that are not present are represented as na.
// @param component The component of the Net Liquidity function to return. Possible values: 'fed', 'tga', and 'rrp'. (`Net Liquidity` is returned if no argument is supplied).
// @returns The Net Liquidity time series or a component of the Net Liquidity function.
export get_net_liquidity(simple string component = "") =>
ts = timestamp("UTC-0", year, month, dayofmonth, 0, 0, 0)
float val = if ts >= 1649203200000 and ts <= 1661731200000
get_net_liquidity_2(component, ts)
else if ts >= 1661817600000 and ts <= 1674432000000
get_net_liquidity_3(component, ts)
else if ts >= 16745184000000 and ts <= 16873920000000
get_net_liquidity_4(component, ts)
else if ts >= 16874784000000 and ts <= 17005248000000
get_net_liquidity_5(component, ts)
else
float(na)
val
|
Utils | https://www.tradingview.com/script/KnCA8c6l-Utils/ | jmosullivan | https://www.tradingview.com/u/jmosullivan/ | 1 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jmosullivan
//@version=5
// @description A collection of convenience and helper functions for indicator and library authors on TradingView
library("Utils", overlay=true)
// @function My version of format number that doesn't have so many decimal places...
// @param num The number to be formatted
// @returns The formatted number
export formatNumber(float num) =>
var n = num
var ret = str.format("{0,number,#}", n)
if (num > 999)
n := num / 1000
ret := str.format("{0,number,#.#}", n) + "k"
if (num > 999999)
n := num / 1000000
ret := str.format("{0,number,#.#}", n) + "M"
ret
// @function Convenience function returns timestamp in yyyy/MM/dd format.
// @param timestamp The timestamp to stringify
// @returns The date string
export getDateString(int timestamp) =>
str.format('{0,date,yyyy/MM/dd}', timestamp)
// @function Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
// @param timestamp The timestamp to stringify
// @returns The date string
export getDateTimeString(int timestamp) =>
str.format('{0,date,yyyy/MM/dd hh:mm}', timestamp)
// @function Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
// @returns The # of inside bars on the chart right now.
export getInsideBarCount() =>
ibCount = 0
i = 0
maxLoops = 10
while i <= maxLoops
if (high[i+1] > high[i] and low[i+1] < low[i])
ibCount := ibCount + 1
i := i + 1
else
i := maxLoops + 1
ibCount
// @function Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: ["Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
// @param show styleString The plain english version of the string to convert back to the expected TradingView format.
// @param acceptGivenIfNoMatch If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
// @returns The string expected by tradingview functions
export getLabelStyleFromString(string styleString, bool acceptGivenIfNoMatch = true) =>
ret = switch styleString
"Down" => label.style_label_down
"Center" => label.style_label_center
"Left" => label.style_label_left
"Label" => label.style_label_left
"Lower Left" => label.style_label_lower_left
"Lower Right" => label.style_label_lower_right
"Right" => label.style_label_right
"Up" => label.style_label_up
"Upper Left" => label.style_label_upper_left
"Upper Right" => label.style_label_upper_right
"Plain Text" => label.style_none
=> acceptGivenIfNoMatch ? styleString : label.style_label_down
ret
// @function Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
// @param hourNumber The hour number
// @param minuteNumber The minute number
// @returns The sum of all the minutes
export getTime(int hourNumber, int minuteNumber) =>
(hourNumber * 60) + minuteNumber
// @function Given a start and end time, returns the high or low price during that time window.
// @param start The timestamp to start with (# of seconds)
// @param end The timestamp to end with (# of seconds)
// @returns The high or low value
export getHighAndLowBetweenTimes(int start, int end) =>
// ref: https://www.pinecoders.com/faq_and_code/
var float h = 0.
var float l = 10e10
var reset = true
minNow = getTime(hour, minute)
if minNow >= start and minNow <= end
if reset
h := high
l := low
reset := false
else
h := math.max(h, high)
l := math.min(l, low)
else
reset := true
[h, l]
// @function Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
// @returns (tuple) [premarketHigh, premarketLow]
export getPremarketHighsAndLows() =>
premarketStart = getTime(4, 0)
premarketEnd = getTime(9, 29)
getHighAndLowBetweenTimes(premarketStart, premarketEnd)
// @function Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
// @returns (tuple) [afterHoursHigh, afterHoursLow]
export getAfterHoursHighsAndLows() =>
afterHoursStart = getTime(16, 0)
afterHoursEnd = getTime(19, 59)
getHighAndLowBetweenTimes(afterHoursStart, afterHoursEnd)
// @function Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
// @returns (tuple) [overnightHigh, overnightLow]
export getOvernightHighsAndLows() =>
overnightStart = getTime(16, 0)
overnightEnd = getTime(9, 29)
getHighAndLowBetweenTimes(overnightStart, overnightEnd)
// @function Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
// @returns (tuple) [premarketHigh, premarketLow, afterHoursHigh, afterHoursLow, overnightHigh, overnightLow]
export getNonRthHighsAndLows() =>
[premarketHigh, premarketLow] = getPremarketHighsAndLows()
[afterHoursHigh, afterHoursLow] = getAfterHoursHighsAndLows()
overnightHigh = math.max(afterHoursHigh, premarketHigh)
overnightLow = math.min(afterHoursLow, premarketLow)
[premarketHigh, premarketLow, afterHoursHigh, afterHoursLow, overnightHigh, overnightLow]
// @function Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: ["Solid", "Dashed", "Dotted", "None/Hidden"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
// @param styleString Plain english (or TV Standard) version of the style string
// @param acceptGivenIfNoMatch If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
// @returns The string expected by tradingview functions
export getLineStyleFromString(string styleString, bool acceptGivenIfNoMatch = true) =>
ret = switch styleString
"Dotted" => line.style_dotted
"Dashed" => line.style_dashed
"Solid" => line.style_solid
=> acceptGivenIfNoMatch ? styleString : line.style_solid
ret
// @function Get the % the current price is away from the given price.
// @returns The % the current price is away from the given price.
export getPercentFromPrice(float price) =>
diff = price - close
(price < close ? diff / close : diff / price)
// @function Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
// @param position Plain english position string
// @returns The string expected by tradingview functions
export getPositionFromString(string position) =>
switch position
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
=> position
// @function Call request.security with this as the expression to get the average up/down values that can be used with getRsiPrice (below) to calculate the price level where the supplied RSI level would be reached.
// @param rsiLength The length of the RSI requested.
// @returns A tuple containing the avgUp and avgDown values required by the getRsiPrice function.
export getRsiAvgsExpression(int rsiLength) =>
ep = 2 * rsiLength - 1
avgUp = ta.ema(math.max(close - close[1], 0), ep)
avgDown = ta.ema(math.max(close[1] - close, 0), ep)
rsi = ta.rsi(close, rsiLength)
[rsi, avgUp, avgDown]
// @function use the values returned by getRsiAvgsExpression() to calculate the price level when the provided RSI level would be reached.
// @param rsiLevel The RSI level to find price at.
// @param rsiLength The length of the RSI to calculate.
// @param avgUp The average move up of RSI.
// @param avgDown The average move down of RSI.
// @returns The price level where the provided RSI level would be met.
export getRsiPrice(float rsiLevel, int rsiLength, float avgUp, float avgDown) =>
x = (rsiLength - 1) * (avgDown * rsiLevel / (100 - rsiLevel) - avgUp)
x >= 0 ? close + x : close + x * (100 - rsiLevel) / rsiLevel
// @function Tradingview doesn't give you a nice way to put the sizes into a dropdown for configuration settings. So, I specify them in the following format: ["Auto", "Huge", "Large", "Normal", "Small", "Tiny"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
// @param sizeString Plain english size string
// @returns The string expected by tradingview functions
export getSizeFromString(string sizeString) =>
switch sizeString
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Tiny" => size.tiny
=> size.small // Defaulting to small if size is unrecognized
// @function Get the timeframe of the current chart for display
// @returns The string of the current chart timeframe
export getTimeframeOfChart() =>
string rtf = str.tostring(timeframe.multiplier)
if (timeframe.isseconds)
rtf := rtf + "s"
if (timeframe.isminutes)
rtf := rtf + "m"
if (timeframe.isdaily)
rtf := rtf + "D"
if (timeframe.isweekly)
rtf := rtf + "W"
if (timeframe.ismonthly)
rtf := rtf + "M"
// @function Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
// @param candleOffset The number of items to find singular/plural for.
// @returns The future time
export getTimeNowPlusOffset(int candleOffset) =>
oneCandleInMS = timeframe.in_seconds() * 1000
time + (oneCandleInMS * candleOffset)
// @function Given a start and end time, returns the sum of all volume across bars during that time window.
// @param start The timestamp to start with (# of seconds)
// @param end The timestamp to end with (# of seconds)
// @returns The volume
export getVolumeBetweenTimes(int start, int end) =>
var float vol = 0
var reset = true
minNow = (hour * 60) + minute
if minNow >= start and minNow <= end
if reset
vol := volume
reset := false
else
vol += volume
else
reset := true
vol
// @function Returns true if the current bar occurs on today's date.
// @returns True if current bar is today
export isToday() =>
year(timenow) == year(time) and month(timenow) == month(time) and dayofmonth(timenow) == dayofmonth(time)
// @function Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
// @param labelText The string to be padded
// @param labelStyle The style of the label being padded for.
// @returns The padded string
export padLabelString(string labelText, string labelStyle) =>
SPACE = " "
returnString = labelText
_labelStyle = getLabelStyleFromString(labelStyle)
if _labelStyle == label.style_none
for i = 0 to str.length(labelText)
returnString := SPACE + returnString
else
returnString := returnString + SPACE
returnString
// @function Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
// @param num The number of items to find singular/plural for.
// @param singular The string to return if num is singular. Defaults to an empty string.
// @param plural The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
// @returns The singular or plural provided strings depending on the num provided.
export plural(int num, string singular = '', string plural = 's') =>
num != 1 ? plural : singular
// @function Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
// @param tf The timeframe to convert
// @returns The number of secondsof that timeframe
export timeframeInSeconds(string timeframe) =>
sMinute = 60
sHour = sMinute * 60
sDay = sHour * 24
sWeek = sDay * 7
sMonth = timeframe.in_seconds("M") // TV has a weird value for this, so I'm just using theirs
letter = str.substring(timeframe, str.length(timeframe) - 1)
multiplier = switch letter
"M" => sMonth
"W" => sWeek
"D" => sDay
"H" => sHour
=> sMinute
number = int(str.tonumber(timeframe))
increment = na(number) ? 1 : number
increment * multiplier
// @function Convert a timeframe string to a consistent standard.
// @param tf The timeframe string to convert
// @returns The standard format for the string, or the unchanged value if it is unknown.
export timeframeToString(string tf) =>
suffix = switch
timeframe.isseconds => 's'
timeframe.isminutes and timeframe.multiplier <= 60 => 'm'
timeframe.isseconds and timeframe.multiplier > 60 => 'h'
timeframe.isdaily => 'D'
timeframe.isweekly => 'W'
timeframe.ismonthly => 'M'
=> ''
multiplier = timeframe.multiplier
if suffix == 'h' and multiplier > 60
multiplier := math.floor(multiplier/60)
// If there are additional minutes unaccounted for, concatenate them in the suffix
if multiplier * 60 != timeframe.multiplier
minutes = timeframe.multiplier - (multiplier * 60)
suffix := str.format('h{0}m', minutes)
suffix == '' ? tf : str.format('{0}{1}', multiplier, suffix)
// Sample usage of the user-friendly input conversions
friendlyLineStyle = input.string('Solid', 'Line Style', ["Solid", "Dashed", "Dotted", "None/Hidden"])
lineStyle = getLineStyleFromString(friendlyLineStyle)
friendlyLabelStyle = input.string('Left', 'Label Position', ["Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels"])
labelStyle = getLabelStyleFromString(friendlyLabelStyle)
// Note: there are no tables in this library, but this example provided nonetheless...
friendlyPosition = input.string('Bottom Center', 'Table Position', ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])
position = getPositionFromString(friendlyPosition)
// Example of the various string & timeframe functions
// Variables
[premarketHigh, premarketLow] = request.security(syminfo.tickerid, timeframe.period, getPremarketHighsAndLows())
percentFromPremarketHigh = getPercentFromPrice(premarketHigh)*100
friendlyVolume = formatNumber(volume)
date = getDateString(time)
dateTime = getDateTimeString(time)
insideBarCount = getInsideBarCount()
fiveCandlesIntoTheFuture = getTimeNowPlusOffset(5)
numberOfDogs = 1
labelTemplate = 'Premarket High: {0,number,currency} ({1})'
+ '\nVolume: {2}'
+ '\nDate String: {3}'
+ '\nDateTime String: {4}'
+ '\nInside Bar Count: {5}'
+ '\nDogs: {6} dog{7}'
labelString = str.format(labelTemplate, premarketHigh, str.tostring(percentFromPremarketHigh, format.percent), friendlyVolume, date, dateTime, insideBarCount, numberOfDogs, plural(numberOfDogs))
var line exampleLine = na
var label exampleLabel = na
// Drawings
if lineStyle != "None/Hidden"
if na(exampleLine)
exampleLine := line.new(time[1], premarketHigh, time[0], premarketHigh, xloc.bar_time, extend.both, color.blue, lineStyle)
else
line.set_x2(exampleLine, fiveCandlesIntoTheFuture)
line.set_y1(exampleLine, premarketHigh)
line.set_y2(exampleLine, premarketHigh)
if labelStyle != "No Labels"
bgColor = labelStyle == label.style_none ? #ffffff00 : color.blue
textColor = labelStyle == label.style_none ? color.blue : color.white
if na(exampleLabel)
exampleLabel := label.new(time, premarketHigh, '', xloc.bar_time, yloc.price, bgColor, labelStyle, textColor, size.small)
else
label.set_xy(exampleLabel, fiveCandlesIntoTheFuture, premarketHigh)
label.set_text(exampleLabel, padLabelString(labelString, labelStyle))
// Example of how to get the price level associated with an RSI level
rsiLength = 14
[hourRsi, avgUp, avgDown] = request.security(syminfo.tickerid, '60', getRsiAvgsExpression(rsiLength), lookahead=barmerge.lookahead_on)
hourOverbought = getRsiPrice(70, rsiLength, avgUp, avgDown)
hourOversold = getRsiPrice(30, rsiLength, avgUp, avgDown)
plot(hourOverbought, 'Hourly RSI Overbought', color.red)
plot(hourOversold, 'Hourly RSI Oversold', color.green)
|
lib_math | https://www.tradingview.com/script/GOqbzhl4-lib-math/ | robbatt | https://www.tradingview.com/u/robbatt/ | 1 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © robbatt
// version history
//@version=5
library("lib_math", overlay=true)
//@description Calculates a mean value over time, with option to reset, this is not using the history operator, so won't trigger max_bars_back errors
//@param value series to track
//@param reset flag to reset tracking
//@return returns average/mean of value since last reset
export mean(float value, bool reset = false) =>
var sum = 0.0
var len = 0
var last = 0.0
if reset
sum := last
len := 1
len := len + 1
sum := sum + value
last := value
sum / len
//@description calculates the vwap manually, this is not using the history operator, so won't trigger max_bars_back errors
//@param value series to track
//@param reset flag to reset tracking
//@return returns vwap of value and volume since last reset
export vwap(float value, bool reset) =>
// Initialize cumulative price and volume
var cum_price_volume = 0.0
var cum_volume = 0.0
if reset
cum_price_volume := 0.0
cum_volume := 0.0
// Calculate conditional VWAP only when the session is active
cum_price_volume := cum_price_volume + (value * volume)
cum_volume := cum_volume + volume
vwap = cum_price_volume / cum_volume
vwap
//@description Calculates the variance of a value over time, with option to reset, this is not using the history operator, so won't trigger max_bars_back errors
//@param value series to track
//@param reset flag to reset tracking
//@return returns variance of value since last reset
export variance(float value, bool reset) =>
var avg = 0.0
var sum = 0.0
var len = 0
var last = 0.0
if reset
avg := last
sum := last
len := 1
last := value
len := len + 1
avg := mean(value, reset)
sum := sum + math.pow(value - avg, 2)
sum / len
//Get trendline coordinates
//@description Calculates the trend correlation, deviation and start and end coordinates of a trendline, this is not using the history operator, so won't trigger max_bars_back errors
//@param value series to track
//@param reset flag to reset tracking
//@return [slope, correlation, stddev, y1 , y2] where slope is the trend direction, correlation is a measurement for how well the values fit to the trendline (positive means ), stddev is how far the values deviate from the trend, x1 would be the time where reset is true and x2 would be the current time
export trend(float value, bool reset)=>
var len = 1
var last = value // modification, so we consider the session open as well
var float sum_wma = na
var float sum_sma = na
var float sum_sma2 = na
if reset
len := 1
sum_wma := last
sum_sma := last
sum_sma2 := last * last
last := value
len += 1
half_len = (len+1)/2
sum_sma += value
sum_sma2 += value * value
sum_wma += value * len // weighted MA => increased significance of recent price data => regression line slope
sma = sum_sma / len // simle moving average
sma2 = sum_sma2 / len
wma = sum_wma / len / half_len // weighted moving average, weight is time/bar_index, centered via division by half_len
cov = (wma - sma) * half_len // covariance (how well the averages align)
stddev = math.sqrt(sma2 - sma * sma) // stddev = root of [avg of (squared)value - (squared)avg of value]
// squared pearson correlation coefficient (r²) (adapted to bars as time representation)
// => correlation coefficient => indicates how well line fits the values 0-1, however 1 might be overfitting
correlation = cov / (stddev * (math.sqrt(len*len - 1) / (2 * math.sqrt(3))))
y1 = 4 * sma - 3 * wma
y2 = 3 * wma - 2 * sma
slope = (y2 - y1) / len
[slope, correlation, stddev, y1 , y2]
new_day = timeframe.change('D')
var last_start = bar_index
var day_start = bar_index
var last_y1 = open
var day_y1 = open
if new_day
last_y1 := day_y1
day_y1 := open
last_start := day_start
day_start := bar_index
mean = mean(close, new_day)
vwap = vwap(close, new_day)
variance = variance(close, new_day)
[slope, correlation, stddev, y1 , y2] = trend(close, new_day)
bars = day_start - last_start + 1
tv_stddev = ta.stdev(close, bars)
tv_mean = ta.sma(close, bars)
tv_vwap = ta.vwap(close, new_day)
tv_correlation = ta.correlation(close, bar_index, bars)
tv_y2 = ta.linreg(close, bars, 0)
tv_y1 = tv_mean + (tv_mean - tv_y2)
tv_slope = (tv_y2 - tv_y1) / bars
if new_day and bar_index > bars
line.new(bar_index, 0, bar_index, 1, extend = extend.both, style = line.style_dotted)
line.new(last_start, mean[1], day_start, mean[1])
// label.new(day_start, y2[1], str.format('mean: {0} | {6}\nslope: {1} | {8}\ncorrelation: {2} | {7}\nstddev: {3} | {4} | {5}', mean[1], slope[1], correlation[1], stddev[1], tv_stddev[1], tv_stddev_unbiased[1], tv_mean[1], tv_correlation[1], tv_slope[1]), textcolor = color.white, style = label.style_label_left)
label.new(day_start, y2[1], str.format('mean: {0} | {6}\nslope: {1} | {8}\ncorrelation: {2} | {7}\nstddev: {3} | {4} | {5}', mean[1], slope[1], correlation[1], stddev[1], tv_stddev[1], tv_stddev[1], tv_mean[1], tv_correlation[1], tv_slope[1]), textcolor = color.white, style = label.style_label_left)
var tv_trendline = line.new(na,na,na,na)
var trendline = line.new(na,na,na,na)
var x1 = bar_index
if not barstate.isfirst
if new_day
tv_trendline.copy()
trendline.copy()
x1 := bar_index
trendline.set_xy1(x1, y1)
trendline.set_xy2(bar_index, y2)
trendline.set_xy1(x1, tv_y1)
trendline.set_xy2(bar_index, tv_y2)
plot(tv_vwap, 'tv_vwap', color.blue, linewidth = 2, style = plot.style_linebr)
plot(vwap, 'vwap', color.red, linewidth = 2, style = plot.style_linebr) |
SuperTrend Polyfactor Oscillator [LuxAlgo] | https://www.tradingview.com/script/rmbjGFQy-SuperTrend-Polyfactor-Oscillator-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 905 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("SuperTrend Polyfactor Oscillator [LuxAlgo]", "LuxAlgo - SuperTrend Polyfactor Oscillator")
//-----------------------------------------------------------------------------}
//Settings
//-----------------------------------------------------------------------------{
length = input.int(10, minval = 2)
starting = input.float(1, 'Starting Factor', minval = 0)
increment = input.float(.5, minval = 0, step = .1)
normalize = input.string('None', options = ['None', 'Max-Min', 'Absolute Sum'])
//Style
mesh = input(true, inline = 'mesh', group = 'Style')
upCss = input.color(color.new(#089981, 90), '', inline = 'mesh', group = 'Style')
dnCss = input.color(color.new(#f23645, 90), '', inline = 'mesh', group = 'Style')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type supertrend
float upper = hl2
float lower = hl2
float output
float perf = 0
float factor
int trend = 0
//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
norm(value, diffs, den)=>
normalized = switch normalize
'Max-Min' => (value - diffs.min()) / diffs.range()
'Absolute Sum' => value / den
=> value
//-----------------------------------------------------------------------------}
//Supertrend
//-----------------------------------------------------------------------------{
var holder = array.new<supertrend>(0)
diffs = array.new<float>(0)
//Populate supertrend type array
if barstate.isfirst
for i = 0 to 19
holder.push(supertrend.new())
atr = ta.atr(length)
//Compute Supertrend for multiple factors
k = 0
den = 0.
factor = starting
for i = 0 to 19
get_spt = holder.get(k)
up = hl2 + atr * factor
dn = hl2 - atr * factor
get_spt.trend := close > get_spt.upper ? 1 : close < get_spt.lower ? 0 : get_spt.trend
get_spt.upper := close[1] < get_spt.upper ? math.min(up, get_spt.upper) : up
get_spt.lower := close[1] > get_spt.lower ? math.max(dn, get_spt.lower) : dn
get_spt.output := get_spt.trend == 1 ? get_spt.lower : get_spt.upper
diffs.push(close - get_spt.output)
k += 1
den += math.abs(close - get_spt.output)
factor += increment
//Outputs
median = norm(diffs.median(), diffs, den)
stdev = normalize != 'Max-Min' ? norm(diffs.stdev(), diffs, den) : na
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Mesh
plot(mesh ? norm(diffs.get(0), diffs, den) : na , color = diffs.get(0) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(1), diffs, den) : na , color = diffs.get(1) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(2), diffs, den) : na , color = diffs.get(2) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(3), diffs, den) : na , color = diffs.get(3) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(4), diffs, den) : na , color = diffs.get(4) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(5), diffs, den) : na , color = diffs.get(5) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(6), diffs, den) : na , color = diffs.get(6) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(7), diffs, den) : na , color = diffs.get(7) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(8), diffs, den) : na , color = diffs.get(8) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(9), diffs, den) : na , color = diffs.get(9) > 0 ? upCss : dnCss , style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(10), diffs, den) : na, color = diffs.get(10) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(11), diffs, den) : na, color = diffs.get(11) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(12), diffs, den) : na, color = diffs.get(12) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(13), diffs, den) : na, color = diffs.get(13) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(14), diffs, den) : na, color = diffs.get(14) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(15), diffs, den) : na, color = diffs.get(15) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(16), diffs, den) : na, color = diffs.get(16) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(17), diffs, den) : na, color = diffs.get(17) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(18), diffs, den) : na, color = diffs.get(18) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
plot(mesh ? norm(diffs.get(19), diffs, den) : na, color = diffs.get(19) > 0 ? upCss : dnCss, style = plot.style_histogram, display = display.all - display.status_line, editable = false)
//Median
plot(median, 'Median', median > (normalize == 'Max-Min' ? .5 : 0) ? #90bff9 : #ffcc80)
//Stdev Area
up = plot(stdev, color = na, editable = false)
dn = plot(-stdev, color = na, editable = false)
fill(up, dn, color.new(#90bff9, 80), title = 'Stdev Area')
//-----------------------------------------------------------------------------} |
Standardized SuperTrend Oscillator | https://www.tradingview.com/script/c9V7Ev22-Standardized-SuperTrend-Oscillator/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 570 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © EliCobra
//@version=5
indicator("Standardized SuperTrend Oscillator", "[Ʌ] - Super Osc.", false)
type bar
float o = open
float h = high
float l = low
float c = close
type supertrend
float s = na
int d = na
float u = na
float l = na
method src(bar b, simple string src) =>
float x = switch src
'oc2' => math.avg(b.o, b.c )
'hl2' => math.avg(b.h, b.l )
'hlc3' => math.avg(b.h, b.l, b.c )
'ohlc4' => math.avg(b.o, b.h, b.l, b.c)
'hlcc4' => math.avg(b.h, b.l, b.c, b.c)
x
method ha(bar b, simple bool p = true) =>
var bar x = bar.new( )
x.c := b .src('ohlc4')
x := bar.new(
na(x.o[1]) ?
b.src('oc2') : nz(x.src('oc2')[1]),
math.max(b.h, math.max(x.o, x.c)) ,
math.min(b.l, math.min(x.o, x.c)) ,
x.c )
p ? x : b
method atr(bar b, simple int len) =>
float tr =
na(b.h[1]) ?
b.h - b.l :
math.max(
math.max(
b.h - b.l,
math.abs(b.h - b.c[1])),
math.abs (b.l - b.c[1]))
len == 1 ? tr : ta.rma(tr, len)
method st(bar b, simple float factor, simple int len) =>
float atr = b.atr( len )
float up = b.src('hl2') + factor * atr
up := up < nz(up[1]) or b.c[1] > nz(up[1]) ? up : nz(up[1])
float dn = b.src('hl2') - factor * atr
dn := dn > nz(dn[1]) or b.c[1] < nz(dn[1]) ? dn : nz(dn[1])
float st = na
int dir = na
dir := switch
na(atr[1]) => 1
st[1] == nz(up[1]) => dir := b.c > up ? -1 : +1
=> dir := b.c < dn ? +1 : -1
st := dir == -1 ? dn : up
supertrend.new(st, dir, up, dn)
method sso(bar b, supertrend st, simple int len) =>
float std = ta .ema(st.u - st.l, len) / 100
bar x = bar.new(
(b.o - st.s) / std,
(b.h - st.s) / std,
(b.l - st.s) / std,
(b.c - st.s) / std)
x
var string tp = 'Source for SuperTrend -\n\n∙ On-> Heikin-Ashi candles\n∙ Off-> Regular candles'
var string g1 = "Oscillator Settings", var string g2 = "SuperTrend of Oscillator", var string gu = "UI Options"
base = input.bool (false , "Heikin-Ashi Source", tp , group = g1)
len1 = input.int (10 , "Length" , inline = '1', group = g1)
mlt1 = input.float (5. , "Factor" , 1, 10, 0.5 , inline = '1', group = g1)
len2 = input.int (10 , "Length" , inline = '2', group = g2)
mlt2 = input.float (3. , "Factor" , 1, 10, 0.5 , inline = '2', group = g2)
osc = input.string('Candles', "Oscillator Style" , ['Candles', 'Line'], group = gu)
d_st = input.bool (true , "SuperTrend Of Osc.", group = gu)
d_rt = input.bool (true , "Reversion Tracer" , group = gu)
rlbl = input.string('None' , "Reversion Signals", ['None', 'OB' , 'OS' , 'Both'], group = gu)
clbl = input.string('None' , "Contrarian Signals", ['None', 'Buy', 'Sell', 'Both'], group = gu)
bar b = bar.new( ).ha(base)
supertrend t1 = b .st (mlt1 , len1)
bar sso = b .sso(t1 , len1).ha( )
supertrend t2 = sso.st (mlt2 , len2)
float rvt = ta .rsi(-t1.d, len1) * 2 - 100
var color colup = #22ab94
var color coldn = #ffdab9
var color colvt = #daa520
var color colut = color.new(#22ab94 , 60 )
var color coldt = color.new(#f23645 , 60 )
var color trnsp = color.new(chart.bg_color, 100)
color col = switch
sso.c > sso.o => colup
sso.c < sso.o => coldn
color cst = switch t2.d
+1 => #ff4800
-1 => #1582ff
color cso = switch
sso.c > rvt and sso.c > 0 => #22ab94
sso.c < rvt and sso.c < 0 => #f23645
=> chart.fg_color
plotcandle(osc == 'Candles' ? sso.o : na ,
osc == 'Candles' ? sso.h : na ,
osc == 'Candles' ? sso.l : na ,
osc == 'Candles' ? sso.c : na ,
'SSO', col, col, bordercolor = col)
h = hline(0 , 'Mid-Line', chart.fg_color, hline.style_dotted)
o = plot (osc == 'Line' ? sso.c : na, 'SSO' , cso , 1, plot.style_line )
t = plot (d_st and t2.d > 0 ? t2.s : na, 'Bear ST' , cst , 1, plot.style_linebr )
d = plot (d_st and t2.d < 0 ? t2.s : na, 'Bull ST' , cst , 1, plot.style_linebr )
u = plot (d_rt and rvt > 0 ? rvt : na, 'Upper RT', colvt , 1, plot.style_linebr )
l = plot (d_rt and rvt < 0 ? rvt : na, 'Lower RT', colvt , 1, plot.style_linebr )
c = plot (osc == 'Candles' ? sso.src('oc2') : na, 'Filler' , display = display.none )
m = plot (0 , 'Filler' , display = display.none )
fill(m, o, 10 * mlt1, 10 , colut, trnsp)
fill(m, o, 10 , -10 * mlt1, trnsp, coldt)
fill(t, c, #ff480010)
fill(d, c, #1582ff10)
bool scon = (clbl == 'Sell' or clbl == 'Both') and math.sign (ta.change(t2.d)) == 1 ? true : false
bool bcon = (clbl == 'Buy' or clbl == 'Both') and math.sign (ta.change(t2.d)) == -1 ? true : false
bool ucon = (rlbl == 'OB' or rlbl == 'Both') and ta.crossover (sso.c, rvt < 0 ? rvt : na) ? true : false
bool dcon = (rlbl == 'OS' or rlbl == 'Both') and ta.crossunder(sso.c, rvt > 0 ? rvt : na) ? true : false
plotshape(scon ? t2.s + 5 : na, 'Sell Signal', shape.labeldown, location.absolute, #ff480075, 0, '𝓢' , chart.fg_color)
plotshape(bcon ? t2.s - 5 : na, 'Buy Signal' , shape.labelup , location.absolute, #1582ff75, 0, '𝓑' , chart.fg_color)
plotshape(dcon ? rvt + 15 : na, 'OB Signal' , shape.labeldown, location.absolute, #f2364575, 0, '𝓞𝓑', chart.fg_color)
plotshape(ucon ? rvt - 15 : na, 'OS Signal' , shape.labelup , location.absolute, #22ab9475, 0, '𝓞𝓢', chart.fg_color)
//Source Construction For Indicator\Strategy Exports
plot(osc == 'Candles' ? sso.o : na, "open" , editable = false, display = display.none)
plot(osc == 'Candles' ? sso.h : na, "high" , editable = false, display = display.none)
plot(osc == 'Candles' ? sso.l : na, "low" , editable = false, display = display.none)
plot(osc == 'Candles' ? sso.c : na, "close", editable = false, display = display.none)
plot(osc == 'Candles' ? sso.src('hl2' ) : na, "hl2" , editable = false, display = display.none)
plot(osc == 'Candles' ? sso.src('hlc3' ) : na, "hlc3" , editable = false, display = display.none)
plot(osc == 'Candles' ? sso.src('ohlc4') : na, "ohlc4", editable = false, display = display.none)
plot(osc == 'Candles' ? sso.src('hlcc4') : na, "hlcc4", editable = false, display = display.none) |
Liquidation Estimates (Real-Time) [LuxAlgo] | https://www.tradingview.com/script/EEh4gRsP-Liquidation-Estimates-Real-Time-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 665 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator('Liquidation Estimates (Real-Time) [LuxAlgo]', 'LuxAlgo - Liquidation Estimates (Real-Time)', false, format.volume)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
liqS1 = "Longs/Shorts Liquidations"
liqS2 = "Total Liquidations"
liqS3 = "Liquidations Dominance (Difference)"
liqS4 = "Cumulative Liquidations"
liqTT = "Mode Options:\n -" +
liqS1 + " : displays long and short liquidations individually\n -" +
liqS2 + " : displays sum of long and short liquidations\n -" +
liqS3 + " : displays difference between the long and short liquidations\n -" +
liqS4 + " : displays the cumulative sum of the difference between short and long liquidations"
liqSH = input.string(liqS1, "Mode", options = [liqS1, liqS3, liqS2, liqS4], tooltip = liqTT)
refPL = input.string("open", "Longs Reference Price", options = ["open", "close", "oc2", "hl2", "ooc3", "occ3", "hlc3", "ohlc4", "hlcc4"])
refPS = input.string("oc2", "Shorts Reference Price", options = ["open", "close", "oc2", "hl2", "ooc3", "occ3", "hlc3", "ohlc4", "hlcc4"])
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field v (float) volume of the bar
type bar
float h = high
float l = low
float v = volume
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
nzV = nz(b.v)
//-----------------------------------------------------------------------------}
// Functions/methods
//-----------------------------------------------------------------------------{
f_gSRC(_s) =>
switch _s
"open" => open
"close" => close
"oc2" => math.avg(open, close)
"hl2" => hl2
"ooc3" => math.avg(open, open, close)
"occ3" => math.avg(open, close, close)
"hlc3" => hlc3
"ohlc4" => ohlc4
"hlcc4" => hlcc4
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
rPS = f_gSRC(refPS)
rPL = f_gSRC(refPL)
lLQ = nzV / (rPL / (rPL - b.l))
sLQ = nzV / (rPS / (b.h - rPS))
plot(liqSH == liqS1 ? lLQ : na, 'Longs' , color.new(#26a69a, 17), style = plot.style_columns)
plot(liqSH == liqS1 ? -sLQ : na, 'Shorts', color.new(#ef5350, 17), style = plot.style_columns)
plot(liqSH == liqS2 ? lLQ + sLQ : na, 'Total', color.new(#9fafdd, 17), style = plot.style_columns)
plot(liqSH == liqS3 ? lLQ - sLQ : na, 'Dominance', lLQ > sLQ ? color.new(#26a69a, 17) : color.new(#ef5350, 17), style = plot.style_columns)
plot(liqSH == liqS4 ? ta.cum(sLQ - lLQ) : na, 'Cumulative', color.orange, 2)
//-----------------------------------------------------------------------------} |
lib_retracement_patterns | https://www.tradingview.com/script/6SqsFMUk-lib-retracement-patterns/ | robbatt | https://www.tradingview.com/u/robbatt/ | 10 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © robbatt
//@version=5
import robbatt/lib_plot_objects/32 as D
import robbatt/lib_pivot/45 as P
import robbatt/lib_retracement_label/2 as RL
import robbatt/lib_zig/16 as ZZ
import robbatt/lib_priceaction/6 as PA
import robbatt/lib_log/6 as LOG
//@description types and functions for XABCD pattern detection and plotting
library("lib_retracement_patterns", overlay = true)
//////////////////////////////////////////////////////////////////////////////////////
//#region HELPERS
//////////////////////////////////////////////////////////////////////////////////////
method replace_all(string source, string target, string replacement) =>
str.replace_all(source, target, replacement)
//////////////////////////////////////////////////////////////////////////////////////
//#endregion HELPERS
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//#region XABC SETUP
//////////////////////////////////////////////////////////////////////////////////////
type Setup
string id
P.Pivot X
P.Pivot A
P.Pivot B
P.Pivot C
setup_id(P.Pivot X, P.Pivot A, P.Pivot B, P.Pivot C) =>
str.format('X-{0}_A-{1}_B-{2}_C-{3}', X.point.index, A.point.index, B.point.index, C.point.index)
pattern_id(string name, Setup setup) =>
str.format('{0}_{1}_bi-{2}', name, setup.id, bar_index)
//////////////////////////////////////////////////////////////////////////////////////
//#endregion XABC SETUP
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//#region PATTERN
//////////////////////////////////////////////////////////////////////////////////////
//@type type to hold retracement ratios and tolerances for this pattern, as well as targets for trades
export type Pattern
string name
// setup
float XABmin = na
float XABmax = na
float ABCmin = na
float ABCmax = na
float BCDmin = na
float BCDmax = na
// D target ranges
float XBDmin = na
float XBDmax = na
float XADmin = na
float XADmax = na
float XCDmin = na
float XCDmax = na
// trade targets
float tp1 = na
float tp2 = na
float sl = na
// tolerances
float tolerance_Bmin = 0
float tolerance_Bmax = 0
float tolerance_Cmin = 0
float tolerance_Cmax = 0
float tolerance_Dmin = 0
float tolerance_Dmax = 0
// another pattern with tolerances applied
Pattern tolerances = na
//@function sets tolerances for B, C and D retracements. This creates another Pattern instance that is set as tolerances field on the original and will be used for detection instead of the original ratios.
export method set_tolerances(Pattern this, float tolerance_Bmin = 0, float tolerance_Bmax = 0, float tolerance_Cmin = 0, float tolerance_Cmax = 0, float tolerance_Dmin = 0, float tolerance_Dmax = 0) =>
if not na(this)
this.tolerance_Bmin := tolerance_Bmin
this.tolerance_Bmax := tolerance_Bmax
this.tolerance_Cmin := tolerance_Cmin
this.tolerance_Cmax := tolerance_Cmax
this.tolerance_Dmin := tolerance_Dmin
this.tolerance_Dmax := tolerance_Dmax
this.tolerances := Pattern.new(
XABmin = this.XABmin - tolerance_Bmin,
XABmax = this.XABmax + tolerance_Bmax,
ABCmin = this.ABCmin - tolerance_Cmin,
ABCmax = this.ABCmax + tolerance_Cmax,
BCDmin = this.BCDmin - tolerance_Dmin,
BCDmax = this.BCDmax + tolerance_Dmax,
XBDmin = this.XBDmin - tolerance_Dmin,
XBDmax = this.XBDmax + tolerance_Dmax,
XADmin = this.XADmin - tolerance_Dmin,
XADmax = this.XADmax + tolerance_Dmax,
XCDmin = this.XCDmin - tolerance_Dmin,
XCDmax = this.XCDmax + tolerance_Dmax
)
this
check_pattern_point(pivots, start_offset, offset, max_age_idx, float[] checked_starts_max_price_result, end_pivot) =>
P.Pivot pivot = na
string interrupt = na
float starts_max_price = checked_starts_max_price_result.get(0)
if offset >= pivots.size() // out of pivots
interrupt := 'out of pivots'
else
start_pivot = pivots.get(offset)
if start_pivot.point.index < max_age_idx // out of bar range
interrupt := 'out of bar range'
else if start_offset % 2 == offset % 2 // point in direction
if not na(starts_max_price) and start_pivot.exceeded_by(starts_max_price) // pattern broken by intermediate pivot
interrupt := na
// just skip
else
pivot := start_pivot
checked_starts_max_price_result.set(0,
na(starts_max_price) ? pivot.point.price
: pivot.direction() == 1 ? math.max(starts_max_price, pivot.point.price)
: math.min(starts_max_price, pivot.point.price)
)
else if not start_pivot.exceeded_by(end_pivot) // checking intermediate pivot, same direction as end (not start), if pattern broken by intermediate pivot
interrupt := 'pattern broken by intermediate pivot exceeded by endpoint'
[pivot, interrupt]
method check_target_ranges_overlap(Pattern this, float priceX, float priceA, float priceB, float priceC, int dir) =>
mins = array.new<float>()
maxs = array.new<float>()
if not na(this.BCDmin) and not na(this.BCDmax)
mins.push(PA.target_ratio_price(priceB, priceC, this.BCDmin))
maxs.push(PA.target_ratio_price(priceB, priceC, this.BCDmax))
if not na(this.XADmin) and not na(this.XADmax)
mins.push(PA.target_ratio_price(priceX, priceA, this.XADmin))
maxs.push(PA.target_ratio_price(priceX, priceA, this.XADmax))
if not na(this.XBDmin) and not na(this.XBDmax)
mins.push(PA.target_ratio_price(priceX, priceB, this.XBDmin))
maxs.push(PA.target_ratio_price(priceX, priceB, this.XBDmax))
if not na(this.XCDmin) and not na(this.XCDmax)
mins.push(PA.target_ratio_price(priceX, priceC, this.XCDmin))
maxs.push(PA.target_ratio_price(priceX, priceC, this.XCDmax))
// target area validation
min = dir == 1 ? mins.min() : mins.max()
max = dir == 1 ? maxs.max() : maxs.min()
targets_overlap = dir == 1 ? min >= max : min <= max
targets_overlap := targets_overlap and min > 0 // ensure we don't target values under 0
[targets_overlap, min, max, mins, maxs]
//////////////////////////////////////////////////////////////////////////////////////
//#endregion PATTERN
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//#region PATTERN CONFIG
//////////////////////////////////////////////////////////////////////////////////////
//@type allows control of pattern plotting shape and colors, as well as settings for hiding overlapped patterns etc.
export type Config
D.LineArgs line_bull
D.LineArgs line_bear
D.LineArgs line_bull_live
D.LineArgs line_bear_live
color fill_bull
color fill_bear
color fill_muted
color color_muted
D.LabelArgs label_args_name_up
D.LabelArgs label_args_name_down
D.LabelArgs label_args_xabcd_down
D.LabelArgs label_args_xabcd_up
D.LineArgs label_args_retrace_line
D.LabelArgs retrace_down
D.LabelArgs retrace_up
D.LineArgs line_Dtarget
D.LineArgs line_args_completion
D.LineArgs line_args_tp1
D.LineArgs line_args_tp2
D.LineArgs line_args_sl
D.LabelArgs label_args_completion
D.LabelArgs label_args_tp1
D.LabelArgs label_args_tp2
D.LabelArgs label_args_sl
D.LabelArgs label_args_terminal_bar_up
D.LabelArgs label_args_terminal_bar_down
string terminal_bar_up_char = '▲'
string terminal_bar_down_char = '▼'
bool draw_point_labels = true
bool draw_retracements = true
bool draw_target_range = true
bool draw_levels = true
bool hide_shorter_if_shared_legs_greater_than_max = true
bool hide_engulfed_pattern = false
bool hide_engulfed_pattern_of_same_type = false
bool hide_longer_pattern_with_same_X = false
bool mute_previous_pattern_when_next_overlaps = false
bool keep_failed_patterns = false
//@function generates a complete Config for Pattern plotting from minimal information and defaults.
//@param pattern_line_args (default: na)
//@param pattern_point_args (default: na)
//@param name_label_args (default: na)
//@param retracement_line_args (default: na)
//@param retracement_label_args (default: na)
//@param line_args_Dtarget (default: na)
//@param line_args_completion (default: na)
//@param line_args_tp1 (default: na)
//@param line_args_tp2 (default: na)
//@param line_args_sl (default: na)
//@param label_args_completion (default: na)
//@param label_args_tp1 (default: na)
//@param label_args_tp2 (default: na)
//@param label_args_sl (default: na)
//@param label_terminal (default: na)
//@param label_terminal_up_char (default: '▲',)
//@param label_terminal_down_char (default: '▼',)
//@param color_bull (default: color.green)
//@param color_bear (default: color.red)
//@param color_muted (default: color.gray)
//@param fill_opacity (default: 15)
//@param draw_point_labels (default: true)
//@param draw_retracements (default: true)
//@param draw_target_range (default: true)
//@param draw_levels (default: true)
//@param hide_shorter_if_shared_legs_greater_than_max (default: true)
//@param hide_engulfed_pattern (default: false)
//@param hide_engulfed_pattern_of_same_type (default: true)
//@param hide_longer_pattern_with_same_X (default: false)
//@param mute_previous_pattern_when_next_overlaps (default: false)
export create_config(D.LineArgs pattern_line_args = na, D.LabelArgs pattern_point_args = na, D.LabelArgs name_label_args = na, D.LineArgs retracement_line_args = na, D.LabelArgs retracement_label_args = na, D.LineArgs line_args_Dtarget = na, D.LineArgs line_args_completion = na, D.LineArgs line_args_tp1 = na, D.LineArgs line_args_tp2 = na, D.LineArgs line_args_sl = na, D.LabelArgs label_args_completion = na, D.LabelArgs label_args_tp1 = na, D.LabelArgs label_args_tp2 = na, D.LabelArgs label_args_sl = na, D.LabelArgs label_terminal = na, string label_terminal_up_char = '▲', string label_terminal_down_char = '▼', color color_bull = color.green, color color_bear = color.red, color color_muted = color.gray, int fill_opacity = 15, bool draw_point_labels = true, bool draw_retracements = true, bool draw_target_range = true, bool draw_levels = true, bool hide_shorter_if_shared_legs_greater_than_max = true, bool hide_engulfed_pattern = false, bool hide_engulfed_pattern_of_same_type = true, bool hide_longer_pattern_with_same_X = false, bool mute_previous_pattern_when_next_overlaps = false, bool keep_failed_patterns = false) =>
Config.new(
pattern_line_args.copy().set_line_color(color_bull),
pattern_line_args.copy().set_line_color(color_bear),
pattern_line_args.copy().set_line_color(color_bull).set_style(line.style_dashed),
pattern_line_args.copy().set_line_color(color_bear).set_style(line.style_dashed),
color.new(color_bull, 100 - fill_opacity),
color.new(color_bear, 100 - fill_opacity),
color.new(color_muted, 100 - 5), // muted fills
color.new(color_muted, 100 - 30), // muted lines
name_label_args.copy().set_style(label.style_label_up).set_text_color(color_bull),
name_label_args.copy().set_style(label.style_label_down).set_text_color(color_bear),
pattern_point_args.copy().set_style(label.style_label_down),
pattern_point_args.copy().set_style(label.style_label_up),
retracement_line_args,
retracement_label_args.copy().set_style(label.style_label_down),
retracement_label_args.copy().set_style(label.style_label_up),
line_args_Dtarget,
line_args_completion,
line_args_tp1,
line_args_tp2,
line_args_sl,
label_args_completion,
label_args_tp1,
label_args_tp2,
label_args_sl,
label_terminal.copy().set_text_color(color_bull),
label_terminal.copy().set_text_color(color_bear),
label_terminal_up_char,
label_terminal_down_char,
draw_point_labels,
draw_retracements,
draw_target_range,
draw_levels,
hide_shorter_if_shared_legs_greater_than_max,
hide_engulfed_pattern,
hide_engulfed_pattern_of_same_type,
hide_longer_pattern_with_same_X,
mute_previous_pattern_when_next_overlaps,
keep_failed_patterns
)
//////////////////////////////////////////////////////////////////////////////////////
//#endregion PATTERN CONFIG
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//#region PATTERN MATCH
//////////////////////////////////////////////////////////////////////////////////////
//@type holds all information on a Pattern and a successful match in the chart. Includes XABCD pivot points as well as all Line and Label objects to draw it
export type Match
Pattern pattern
string id
string name
P.Pivot X
P.Pivot A
P.Pivot B
P.Pivot C
float Dmin_price = na
float Dmax_price = na
P.Pivot D = na
P.Pivot Dmin = na
P.Pivot Dmax = na
D.Line[] static_lines = na
D.Line[] dynamic_lines = na // always update second point (idx:1)
RL.RetracementLabel[] static_labels = na
RL.RetracementLabel[] dynamic_labels = na // always update second point (idx:1)
D.Label[] dynamic_point_labels = na // always update second point (idx:1)
D.Label[] static_point_labels = na // 0:X , 1:A , 2:B , 3:C , 4:D , 5:Dmin , 6:Dmax // alwasy update last 3 as long as not is_complete / not is_expired / not is_invalidated
D.LineFill[] fills = na
D.Label name_label = na
float hhll = na
float price_offset_B = na
float tp1 = na
float tp2 = na
float sl = na // a.k.a HOP / LRP
int terminal_bar_idx = na
int terminal_bar_time = na
int length = 0
float height = 0
float XB_BD_ratio = 0
bool is_complete = false
bool is_expired = false
bool is_invalidated = false
bool is_hidden = false
bool is_muted = false
bool is_engulfed_by_completed = false // helps cut down plotting iterations
bool is_overlapped_by_shared_legs = false // hide due to overlap by longer/higher pattern with more than max allowed shared legs
bool is_overlapped_by_next = false // mute due to overlap by next pattern
//@function return the direction of this Match, determined by the C Point of this pattern
export method direction(Match this) =>
na(this) ? 0 : na(this.C) ? 0 : this.C.direction()
//@function return the length of this pattern, determined by the distance between X and D point
export method length(Match this) =>
na(this) ? 0 : na(this.X) or na (this.D) ? 0 : this.D.point.index - this.X.point.index
//@function return the height of this pattern, determined by the distance between the biggest distance between A/C and X/D
export method height(Match this) =>
na(this) ? 0 : na(this.X) or na (this.A) or na (this.C) or na (this.D) ? 0 :
this.direction() == 1
? math.max(this.A.point.price, this.C.point.price) - math.min(this.X.point.price, this.D.point.price)
: math.max(this.X.point.price, this.D.point.price) - math.min(this.A.point.price, this.C.point.price)
//@function returns true if not complete, not expired and not invalidated
export method is_forming(Match this) =>
na(this) ? false : not this.is_complete and not this.is_expired and not this.is_invalidated
//@function return a string representation of this Match
export method tostring(Match this) =>
na(this) ? 'null' : '{' + str.format('"id": "{0}", "Dmin_price": {1}, "Dmax_price": {2}, "is_complete": {3}, "is_expired": {4}, "is_invalidated": {5}', this.id, this.Dmin_price, this.Dmax_price, this.is_complete, this.is_expired, this.is_invalidated) + '}'
// na(this) ? 'null' : this.id // TODO change back
//@function return a string representation of all Matches in this map
export method tostring(map<string, Match> this) =>
if na(this)
'null'
else
result = array.new<string>()
for i in this.values()
result.push(i.tostring())
'[' + result.join(', ') + ']'
calc_XB_BD_ratio(idx_X, idx_B, idx_D) =>
(idx_D - idx_B) / (idx_B - idx_X)
method XB_BD_ratio(Match this) =>
na(this) ? 0 : calc_XB_BD_ratio (this.X.point.index, this.B.point.index, this.D.point.index)
//@function remove complete and expired Matches from this map
export remove_complete_and_expired(map<string, Match> this) =>
if na(this) ? false : this.size() > 0
for match_id in this.keys()
match = this.get(match_id)
if match.is_complete or match.is_expired
this.remove(match_id)
this
//@function add a match to this map, with it's id as key, silent skip if this or item is na
export method add(map<string, Match> this, Match item) =>
if not na(this) and not na(item)
this.put(item.id, item)
this
//@function remove Matches from this map that fit the parameter criteria
//@param when_pattern_len_exceeds (default: na) remove a pattern if it's longer than this value
//@param when_older_than_idx (default: na) remove a pattern if it's X bar_index is less than this value
//@param when_BD_becomes_unproportional_ratio (default: na) remove a pattern if it's BCD part becomes unproportionally bigger than its XAB part
//@param when_completed (default: false) remove a pattern if it is completed
//@param when_invalidated (default: false) remove a pattern if it is invalidated (by D exceeding C in direction of C)
//@param when_engulfed_by_completed (default: false) remove a pattern if it is engulfed by another completed pattern
//@param when_overlapped_by_shared_legs (default: false) remove a pattern if it is overlapped by another, that shares a certain amount of legs with it
//@param handled_matches_buffer (default: na) all patterns that were removed will be added to this buffer (if not passed from caller, nothing happens)
//@param handled_completed_buffer (default: na) completed patterns will also be added to this buffer (if not passed from caller, nothing happens)
//@param invalid_buffer (default: na) invalidated patterns will also be added to this buffer (if not passed from caller, nothing happens)
method cleanup(map<string, Match> matches, int when_pattern_len_exceeds = na, int when_older_than_idx = na, simple float when_BD_becomes_unproportional_ratio = na, simple bool when_completed = false, simple bool when_invalidated = false, simple bool when_engulfed_by_completed = false, simple bool when_overlapped_by_shared_legs = false, map<string, Match> handled_matches_buffer = na, map<string, Match> handled_completed_buffer = na, map<string, Match> invalid_buffer = na) =>
if not na(matches)
for match_id in matches.keys()
match = matches.get(match_id)
completed = when_completed and match.is_complete
expired = na(when_older_than_idx) ? false : match.X.point.index < when_older_than_idx
exceeded = na(when_pattern_len_exceeds) ? false : match.D.point.index - match.X.point.index > when_pattern_len_exceeds
unproportional_BD_ratio = na(when_BD_becomes_unproportional_ratio) ? false : (match.D.point.index - match.B.point.index) / (match.B.point.index - match.X.point.index) > when_BD_becomes_unproportional_ratio
invalidated = not when_invalidated ? false : match.direction() == 1 ? match.C.exceeded_by(high) or open < match.Dmax_price : match.C.exceeded_by(low) or open > match.Dmax_price
engulfed = when_engulfed_by_completed and match.is_engulfed_by_completed
overlapped_by_shared_legs = when_overlapped_by_shared_legs and match.is_overlapped_by_shared_legs
if completed
// if not na(handled_buffer)
// label.new(bar_index, low, str.format('c complete\n{0}', match.pattern.name), style = label.style_label_up, textcolor = color.white)
complete_match = matches.remove(match_id)
handled_completed_buffer.add(complete_match)
handled_matches_buffer.add(complete_match)
else if engulfed or overlapped_by_shared_legs
handled_matches_buffer.add(matches.remove(match_id))
else if expired or exceeded
exp = matches.remove(match_id)
exp.is_expired := true
// if not na(handled_buffer)
// label.new(bar_index, low, str.format('c expired\n{0}', match.pattern.name), style = label.style_label_up, textcolor = color.white)
handled_matches_buffer.add(exp)
invalid_buffer.add(exp)
else if invalidated or unproportional_BD_ratio
inv = matches.remove(match_id)
// label.new(bar_index, inv.B.point.price, str.format('invalidated\n{0}\ninvalid: {1}\nunproportional: {2}', inv.id, invalidated, unproportional_BD_ratio), style = label.style_label_up, textcolor = color.white, color = color.new(color.blue, 50))
inv.is_invalidated := true
handled_matches_buffer.add(inv)
invalid_buffer.add(inv)
matches
//@function checks if this Match is engulfed by the other
export method is_engulfed_by (Match this, Match other) =>
if na(this) or na(other)
false
else
within_other_pattern = other.X.point.index <= this.X.point.index and this.D.point.index <= other.D.point.index
same_start_and_end = other.X.point.index == this.X.point.index and this.D.point.index == other.D.point.index
BC_shorter = (this.C.point.index - this.B.point.index) < (other.C.point.index - other.B.point.index)
within_other_pattern and
(
not same_start_and_end
or this.height < other.height
or (this.height == other.height) and BC_shorter
)
method is_overlapped_by_shared_legs(Match this, Match other, int max_shared_legs = 1, string[] debug_log) =>
is_overlapped = false
if not na(this) and not na(other)
if this.id != other.id
shared_legs = 0
shared_legs += this.X.point.index == other.X.point.index and this.A.point.index == other.A.point.index ? 1 : 0
shared_legs += this.A.point.index == other.A.point.index and this.B.point.index == other.B.point.index ? 1 : 0
shared_legs += this.B.point.index == other.B.point.index and this.C.point.index == other.C.point.index ? 1 : 0
shared_legs += this.C.point.index == other.C.point.index and this.D.point.index == other.D.point.index ? 1 : 0
if shared_legs > max_shared_legs
is_overlapped := this.length < other.length
or this.length == other.length and
(
this.height < other.height
or this.height == other.height and this.price_offset_B > other.price_offset_B
)
if not na(debug_log)
debug_log.push(str.format('{0} has {1} shared legs with {2} | len: {3}, other: {4} | overlapped: {5}', this.id, shared_legs, other.id, this.length, other.length, is_overlapped))
is_overlapped
method is_overlapped_by_next(Match this, Match next) =>
na(this) or na(next) ? false : this.X.point.index < next.X.point.index and this.D.point.index < next.D.point.index
method update_overlapped(map<string, Match> this, Match just_completed, int max_shared_legs = 1, string[] debug_log) =>
if not na(this) and not na(just_completed)
for [other_id, other] in this
if just_completed.id != other_id
if other.is_engulfed_by(just_completed)
other.is_engulfed_by_completed := true
if not na(debug_log)
debug_log.push(str.format('{0} completed, engulfs {1}', just_completed.id, other.id))
if just_completed.is_engulfed_by(other)
just_completed.is_engulfed_by_completed := true
if not na(debug_log)
debug_log.push(str.format('{0} completed, engulfed by {1}', just_completed.id, other.id))
if other.is_overlapped_by_shared_legs(just_completed, max_shared_legs, debug_log)
other.is_overlapped_by_shared_legs := true
if not na(debug_log)
debug_log.push(str.format('{0} completed, overlaps (shared legs) {1}', just_completed.id, other.id))
if just_completed.is_overlapped_by_shared_legs(other, max_shared_legs, debug_log)
just_completed.is_overlapped_by_shared_legs := true
if not na(debug_log)
debug_log.push(str.format('{0} completed, overlapped by (shared legs) {1}', just_completed.id, other.id))
if other.is_overlapped_by_next(just_completed)
other.is_overlapped_by_next := true
if not na(debug_log)
debug_log.push(str.format('{0} completed, overlaps (previous) {1}', just_completed.id, other.id))
if just_completed.is_overlapped_by_next(other)
just_completed.is_overlapped_by_next := true
if not na(debug_log)
debug_log.push(str.format('{0} completed, overlapped by (next) {1}', just_completed.id, other.id))
method match(Pattern pattern, Setup setup, string[] debug_log) =>
Match match = na
P.Pivot X = setup.X
P.Pivot A = setup.A
P.Pivot B = setup.B
P.Pivot C = setup.C
int dir = C.direction()
string prefix = dir == 1 ? "Bullish" : "Bearish"
string name = prefix + ' ' + pattern.name
Pattern tolerances = na(pattern.tolerances) ? pattern : pattern.tolerances
float priceX = X.point.price
float priceA = A.point.price
float priceB = na
float priceC = na
bool XAB_price_inRange = false
bool ABC_price_inRange = false
float priceB_min = PA.target_ratio_price(priceX, priceA, tolerances.XABmin)
float priceB_max = PA.target_ratio_price(priceX, priceA, tolerances.XABmax)
if pattern.XABmin != pattern.XABmax // explicit retracement -> therefore price range for B
priceB := B.point.price
XAB_price_inRange := PA.in_range(priceB, priceB_min, priceB_max)
else // explicit retracement for B -> whole candle allowed +- tolerance above/below (OUR USE CASE)
priceB := PA.target_ratio_price(priceX, priceA, pattern.XABmin)
// XAB_price_inRange := PA.range_overlap(priceB_min, priceB_max, B.candle.l, B.candle.h)
XAB_price_inRange := PA.in_range(priceB, priceB_min, priceB_max) and PA.in_range(B.point.price, priceB_min, priceB_max)
float priceC_min = PA.target_ratio_price(priceA, B.point.price, tolerances.ABCmin)
float priceC_max = PA.target_ratio_price(priceA, B.point.price, tolerances.ABCmax)
float priceC_ideal_min = PA.target_ratio_price(priceA, priceB, tolerances.ABCmin)
float priceC_ideal_max = PA.target_ratio_price(priceA, priceB, tolerances.ABCmax)
if pattern.ABCmin != pattern.ABCmax // explicit retracement -> therefore price range for C (OUR USE CASE)
priceC := C.point.price
ABC_price_inRange := PA.in_range(priceC, priceC_min, priceC_max) and PA.in_range(priceC, priceC_ideal_min, priceC_ideal_max)
else // explicit retracement for C -> whole candle allowed +- tolerance above/below
priceC := PA.target_ratio_price(priceA, B.point.price, pattern.ABCmin)
// ABC_price_inRange := PA.range_overlap(priceC_min, priceC_max, C.candle.l, C.candle.h)
ABC_price_inRange := PA.in_range(priceC, priceC_min, priceC_max) and PA.in_range(priceC, priceC_ideal_min, priceC_ideal_max)
// retracements must be calculated here, as they might be off for different pattern types
float XAB = PA.retracement_ratio(X.point.price, A.point.price, priceB)
float ABC = PA.retracement_ratio(A.point.price, priceB, priceC)
bool XAB_inRange = PA.in_range(XAB, tolerances.XABmin, tolerances.XABmax)
bool ABC_inRange = PA.in_range(ABC, tolerances.ABCmin, tolerances.ABCmax)
// retracements must be calculated here, as they might be off for different pattern types
bool xabc_match = XAB_inRange and ABC_inRange and XAB_price_inRange and ABC_price_inRange// Design decision: using the ideal price level (priceB) as origin for allowed retracement range of C, not the actual price (B.point.price)
if xabc_match
// check possible D within all target ranges
[targets_overlap, Dmin_price, Dmax_price, mins, maxs] = tolerances.check_target_ranges_overlap(priceX, priceA, priceB, C.point.price, dir)
// PATTERN FOUND, CHECKS PASSED
if targets_overlap
match := Match.new(pattern, pattern_id(prefix+'_'+pattern.name,setup), name,
X.copy(),
A.copy(),
pattern.XABmin != pattern.XABmax ? B.copy() : P.Pivot.new(chart.point.new(B.point.time, B.point.index, priceB), candle = B.candle),
pattern.ABCmin != pattern.ABCmax ? C.copy() : P.Pivot.new(chart.point.new(C.point.time, C.point.index, priceC), candle = C.candle),
Dmin_price, Dmax_price)
match.A.update_relation(match.X)
match.B.update_relation(match.A)
match.C.update_relation(match.B)
match.D := C.create_next(time, bar_index, close)
match.Dmin := C.create_next(time, bar_index, Dmin_price)
match.Dmax := C.create_next(time, bar_index, Dmax_price)
match.hhll := (match.A.exceeded_by(match.C) ? match.C : match.A).point.price
match.price_offset_B := math.abs(B.point.price - priceB)
match.static_lines := array.new<D.Line>()
match.dynamic_lines := array.new<D.Line>()
match.static_labels := array.new<RL.RetracementLabel>()
match.dynamic_labels := array.new<RL.RetracementLabel>()
match.static_point_labels := array.new<D.Label>()
match.dynamic_point_labels := array.new<D.Label>()
match.fills := array.new<D.LineFill>()
if not na(debug_log)
label.new(bar_index, close, str.format('XABC\n{0}', match.id.replace_all('_','\n')), textcolor = color.white)
debug_log.push(str.format('XABC {0} | mins: {1} | maxs: {2} | Dmin_price: {3} | Dmax_price: {4}', match.id, mins, maxs, Dmin_price, Dmax_price))
else if not targets_overlap and not na(debug_log)
debug_log.push(str.format('{0} - target range check failed | mins: {1} | maxs: {2} | Dmin_price: {3} | Dmax_price: {4}', setup.id +' '+name, mins, maxs, Dmin_price, Dmax_price))
else if not na(debug_log)
msg = str.format('{0} - pattern match failed', setup.id +' '+name)
if not XAB_price_inRange
msg += str.format('| B price ({0}) not in range ({1}-{2}) for tolerance range({3}-{4})', B.point.price, priceB_min, priceB_max, tolerances.XABmin, tolerances.XABmax)
if not ABC_price_inRange
msg += str.format('| C price ({0}) not in range ({1}-{2})', C.point.price, priceC_min, priceC_max)
if not XAB_inRange
msg += str.format('| XAB ({0}) not in range ({1}-{2})', XAB, tolerances.XABmin, tolerances.XABmax)
if not ABC_inRange
msg += str.format('| ABC ({0}) not in range ({1}-{2})', ABC, tolerances.ABCmin, tolerances.ABCmax)
debug_log.push(msg)
// else if debug_enabled
// debug_log.push(str.format('{0} no XABC match for X:{1}, A:{2}, B:{3}, C:{4}', name, X.point.index, A.point.index, B.point.index, C.point.index))
match
find_xabc_patterns(P.Pivot[] pivots, Pattern[] patterns, int max_age_idx, simple int detect_dir = 0, simple int pattern_minlen = 30, simple int pattern_maxlen = 300, simple float max_XD_BD_ratio = 5, simple int max_sub_waves = 2, string[] debug_log) =>
map<string, Match> matches = map.new<string, Match>()
var max_sub_offset = 2 * max_sub_waves
debug = array.new<string>()
int count = pivots.size()
if count >= 5
bool interrupt = false
int offset_C = 1
P.Pivot C = pivots.get(offset_C)
int dir = C.direction()
if detect_dir == 0 or dir == detect_dir
var checked_Bs_max_price_result = array.new<float>(1,na)
var checked_As_max_price_result = array.new<float>(1,na)
var checked_Xs_max_price_result = array.new<float>(1,na)
checked_Bs_max_price_result.set(0,na)
checked_As_max_price_result.set(0,na)
checked_Xs_max_price_result.set(0,na)
possible_XABC_setups = array.new<Setup>()
// find all valid XABC Pattern setups that don't violate pattern rules
for offset_B = offset_C + 1 to offset_C + 1 + max_sub_offset // go through all Bs
[B, interrupt_B] = check_pattern_point(pivots, offset_C + 1, offset_B, max_age_idx, checked_Bs_max_price_result, C)
if not na(interrupt_B)
if not na(debug_log)
debug_log.push(str.format('found C at offset {0}({1})\ninterrupt B at offset {2}: {3}', offset_C, C.point.index, offset_B, interrupt_B))
break
if not na(B)
if not na(debug_log)
debug_log.push(str.format('found C at offset {0}({1})\nfound B at offset {2}({3})', offset_C, C.point.index, offset_B, B.point.index))
// checked_As.clear()
for offset_A = offset_B + 1 to offset_B + 1 + max_sub_offset // go through all As
[A, interrupt_A] = check_pattern_point(pivots, offset_B + 1, offset_A, max_age_idx, checked_As_max_price_result, B)
if not na(interrupt_A)
if not na(debug_log)
debug_log.push(str.format('interrupt A at offset {0}: {1}', offset_A, interrupt_A))
break
if not na(A)
if not na(debug_log)
debug_log.push(str.format('found A at offset {0}({1}) -> ABC:{2}', offset_A, A.point.index, PA.retracement_ratio(A.point.price, B.point.price, C.point.price)))
// checked_Xs.clear()
for offset_X = offset_A + 1 to offset_A + 1 + max_sub_offset // go through all Xs
[X, interrupt_X] = check_pattern_point(pivots, offset_A + 1, offset_X, max_age_idx, checked_Xs_max_price_result, A)
if not na(interrupt_X)
if not na(debug_log)
debug_log.push(str.format('interrupt X at offset {0}: {1}', offset_X, interrupt_X))
break
if not na(X)
if not na(debug_log)
debug_log.push(str.format('found X at offset {0}({1}) -> XAB:{2}', offset_X, X.point.index, PA.retracement_ratio(X.point.price, A.point.price, B.point.price)))
XD_Bbi_ratio = calc_XB_BD_ratio(X.point.index, B.point.index, bar_index)
if XD_Bbi_ratio <= max_XD_BD_ratio
possible_XABC_setups.push(Setup.new(setup_id(X,A,B,C),X,A,B,C))
else if not na(debug_log) // already too big
debug_log.push(str.format('XB/BD ratio {0} already too big (>{1})', XD_Bbi_ratio, max_XD_BD_ratio))
// check each of these setups for match with any of our patterns
for possible_XABC_setup in possible_XABC_setups
for pattern in patterns
match = pattern.match(possible_XABC_setup, debug_log)
if not na(match)
matches.put(match.id, match)
matches
//@function checks this map of tracking Matches if any of them was completed or invalidated in this iteration. This map is also updated with new XABC Setups as they appear.
//@param tracking_matches this map of tracking Matches
//@param zigzag the base ZigZag on which Pivot Points used for XABCD are based
//@param patterns the list of patterns to search for
//@param max_age_idx the oldest bar_index to consider for new Setups and to remove currently tracking matches respectively
//@param detect_dir setting to filter detection direction (-1: bearish only, 0: both, 1: bullish only)
//@param pattern_minlen minimum amount of bars per pattern
//@param pattern_maxlen maximum amount of bars per pattern
//@param max_sub_waves (default: 2) maximum up-down movements between two points of XABCD
//@param max_shared_legs (default: 1) maximum shared legs between two patterns before the shorter one is removed
//@param max_XB_BD_ratio (default: 5) maximum ratio of BCD compared to XAB part (XAB part should not drag on too long)
//@param debug_log (default : na) if not passed, no debug logs will be plotted
export method update(map<string, Match> tracking_matches, ZZ.Zigzag zigzag, Pattern[] patterns, int max_age_idx, simple int detect_dir, simple int pattern_minlen, simple int pattern_maxlen, simple int max_sub_waves = 2, simple int max_shared_legs = 1, simple float max_XB_BD_ratio = 5, string[] debug_log = na) =>
var map<string, Match> handled_matches = map.new<string, Match>() // holds all handled patterns up to max_age_idx that should be ignored when found again by find_xabc_patterns (skip that, now handled by XABC_Setups)
var map<string, Match> buffered_completed_matches = map.new<string, Match>() // holds matches completed, that need to be considered when hiding patterns due to being engulfed by patterns starting earlier
var map<string, Match> just_completed_matches = map.new<string, Match>() // holds matches completed this iteration, for return
var map<string, Match> invalidated_matches = map.new<string, Match>() // holds matches invalidated this iteration, for return
var min_XB_BD_ratio = 1/max_XB_BD_ratio
just_completed_matches.clear()
invalidated_matches.clear()
// clear the buffer of expired tracking_matches (they won't be added anymore and it saves us from iterating over them)
buffered_completed_matches.cleanup(when_older_than_idx = max_age_idx, when_engulfed_by_completed = true, handled_matches_buffer = handled_matches)
// remove completed / expired / invalidated (by pivot exceeding C in same direction)
if not na(tracking_matches)
tracking_matches.cleanup(when_pattern_len_exceeds = pattern_maxlen, when_older_than_idx = max_age_idx, when_BD_becomes_unproportional_ratio = max_XB_BD_ratio, when_completed = true, when_invalidated = true, handled_matches_buffer = handled_matches, handled_completed_buffer = buffered_completed_matches, invalid_buffer = invalidated_matches)
// find new XABC patterns
if zigzag.has_new_pivot()
// TODO tracking live pivot was confirmed, ignore as long as there's one that exceeds C??? or there are more than x subwaves in between, or X idx is > max_age_bars
new_matches = find_xabc_patterns(zigzag.pivots, patterns, max_age_idx, detect_dir, pattern_minlen, pattern_maxlen, max_XB_BD_ratio, max_sub_waves, debug_log)
for [new_match_id, new_match] in new_matches
if not tracking_matches.contains(new_match_id) and not handled_matches.contains(new_match_id)
tracking_matches.put(new_match_id, new_match)
// every iteration so target lines are drawn and updated as long as they are there
candle = D.create_candle(time, time_close, bar_index, open, high, low, close, volume)
for [match_id, match] in tracking_matches
if match.is_forming()
// pattern length validation
candle_in_target_range = PA.range_overlap(match.Dmin_price, match.Dmax_price, low, high)
close_in_target_range = PA.in_range(close, match.Dmin_price, match.Dmax_price)
just_completed = (candle_in_target_range or close_in_target_range)// and match.is_forming()
// update dynamic points
match.Dmin.point.index := bar_index
match.Dmax.point.index := bar_index
match.D.point.index := bar_index
match.Dmin.point.time := time
match.Dmax.point.time := time
match.D.point.time := time
match.D.point.price := not just_completed or close_in_target_range ? close : match.Dmin_price
match.D.candle := candle
match.length := match.length()
match.height := match.height()
match.XB_BD_ratio := match.XB_BD_ratio()
if just_completed
pattern_len_inRange = PA.in_range(match.length, pattern_minlen, pattern_maxlen)
XB_BD_ratio_inRange = PA.in_range(match.XB_BD_ratio, min_XB_BD_ratio, max_XB_BD_ratio)
// label.new(bar_index, match.B.point.price, str.format('completing\n{0}\xbbd_ratio: {1}\npatternlen: {2}', match.id, match.XB_BD_ratio, pattern_len), style = label.style_label_down, textcolor = color.white, color = color.new(color.green,50))
if pattern_len_inRange and XB_BD_ratio_inRange
match.is_complete := true
match.tp1 := PA.target_ratio_price(match.hhll, match.D.point.price, match.pattern.tp1)
match.tp2 := PA.target_ratio_price(match.hhll, match.D.point.price, match.pattern.tp2)
match.sl := PA.target_ratio_price(match.D.point.price, match.hhll, match.pattern.sl)
match.terminal_bar_idx := match.D.point.index
match.terminal_bar_time := match.D.point.time
// optimize drawing by marking this for removal from the buffered_completed_matches buffer (next round, needs to be hidden this iteration)
if not na(debug_log)
debug_log.push(str.format('update overlapped (buffered complete) {0}', buffered_completed_matches.tostring()))
buffered_completed_matches.update_overlapped(match, max_shared_legs, debug_log)
// in case other patterns finished simulteaneously, check them too, also allow them to overlap this match (wasn't in buffered_completed_matches before)
if not na(debug_log)
debug_log.push(str.format('update overlapped (just complete) {0}', just_completed_matches.tostring()))
just_completed_matches.update_overlapped(match, max_shared_legs, debug_log)
just_completed_matches.add(match)
// label.new(bar_index, low, str.format('complete\n{0}', match.pattern.name), style = label.style_label_up, textcolor = color.white)
else
match.is_invalidated := true
invalidated_matches.add(match)
if not na(debug_log)
msg = str.format('{0} invalidated on completion', match.id)
if not pattern_len_inRange
msg += str.format('| pattern_len {0} not in range ({1}-{2})', match.length, pattern_minlen, pattern_maxlen)
if not XB_BD_ratio_inRange
msg += str.format('| XB_BD_ratio {0} not in range ({1}-{2})', match.XB_BD_ratio, min_XB_BD_ratio, max_XB_BD_ratio)
debug_log.push(msg)
// cleanup expired matches to avoid memory overflow
handled_matches.cleanup(when_older_than_idx = max_age_idx)
[just_completed_matches, invalidated_matches, buffered_completed_matches, handled_matches]
//////////////////////////////////////////////////////////////////////////////////////
//#endregion PATTERN MATCH
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//#region DEMO
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//#region DRAW
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//@function mute this pattern by making it all one color (lines and labels, for pattern fill there's another)
export method mute(Match this, color mute_color, color mute_fill_color) =>
if not na(this)
for i in this.static_lines
i.plot.set_color(mute_color)
for i in this.dynamic_lines
i.plot.set_color(mute_color)
for i in this.static_labels
i.center_label.center_label.plot.set_textcolor(mute_color)
for i in this.dynamic_labels
i.center_label.center_label.plot.set_textcolor(mute_color)
for i in this.fills
i.plot.set_color(mute_fill_color)
for i in this.dynamic_point_labels
i.plot.set_textcolor(mute_color)
for i in this.static_point_labels
i.plot.set_textcolor(mute_color)
this.name_label.plot.set_textcolor(mute_color)
this.name_label.plot.set_color(#00000000)
//@function hide this pattern by muting it with a transparent color
export method hide(Match this) =>
this.mute(#00000000, #00000000)
//@function reset the style of a muted or hidden match back to the preset configuration
export method reset_styles(Match this) =>
if not na(this)
for i in this.static_lines
i.plot.set_color(i.args.line_color)
for i in this.dynamic_lines
i.plot.set_color(i.args.line_color)
for i in this.static_labels
i.center_label.center_label.plot.set_textcolor(i.center_label.center_label.args.text_color)
for i in this.dynamic_labels
i.center_label.center_label.plot.set_textcolor(i.center_label.center_label.args.text_color)
for i in this.fills
i.plot.set_color(i.fill_color)
for i in this.dynamic_point_labels
i.plot.set_textcolor(i.args.text_color)
for i in this.static_point_labels
i.plot.set_textcolor(i.args.text_color)
this.name_label.plot.set_textcolor(this.name_label.args.text_color)
//@function remove the plot of this Match from the chart
export method delete(Match this) =>
if not na(this)
this.static_lines.delete()
this.dynamic_lines.delete()
this.static_labels.delete()
this.dynamic_labels.delete()
this.static_point_labels.delete()
this.fills.delete()
this.dynamic_point_labels.delete()
this.static_point_labels.delete()
this.name_label.delete()
//@function mute all patterns in this map by making it all one color (lines and labels, for pattern fill there's another)
export method mute(map<string, Match> this, color mute_color, color mute_fill_color) =>
if not na(this)
for i in this.values()
i.mute(mute_color, mute_fill_color)
this
//@function remove all the plots of the Matches in this map from the chart
export method delete(map<string, Match> this) =>
if not na(this)
for i in this.values()
i.delete()
this
//@function draw this Match on the chart
//@param config configuration for plotting this Match
//@param hide set this Match's colors to transparent
//@param mute set this Match's colors to mute colors
//@param terminal_label_yoffset distance of terminal bar label from the terminal bar high/low
export method draw(Match this, Config config, bool hide = false, bool mute = false, float terminal_label_yoffset) =>
tf_ms = timeframe.in_seconds() * 1000
dir = this.direction()
line_args = dir == 1 ? config.line_bull : config.line_bear
line_args_live = dir == 1 ? config.line_bull_live : config.line_bear_live
fill_color = dir == 1 ? config.fill_bull : config.fill_bear
point_in_dir = dir == 1 ? config.label_args_xabcd_up : config.label_args_xabcd_down
point_opp_dir = dir == 1 ? config.label_args_xabcd_down : config.label_args_xabcd_up
retrace_in_dir = dir == 1 ? config.retrace_up : config.retrace_down
retrace_opp_dir = dir == 1 ? config.retrace_down : config.retrace_up
name_in_dir = dir == 1 ? config.label_args_name_up : config.label_args_name_down
terminal_args = dir == 1 ? config.label_args_terminal_bar_up : config.label_args_terminal_bar_down
terminal_char = dir == 1 ? config.terminal_bar_up_char : config.terminal_bar_down_char
// name_opp_dir = dir == 1 ? config.label_args_xabcd_down : config.label_args_xabcd_up
initial = this.static_lines.size() == 0
just_complete = this.is_complete and bar_index == this.terminal_bar_idx
prefix = dir == 1 ? "Bullish\n" : "Bearish\n"
if initial
// name label
center_points = array.from(this.A.point, this.B.point, this.C.point)
this.name_label := D.Label.new(this.B.point, this.pattern.name, name_in_dir)
// static
XA = this.X.point.create_line(this.A.point, line_args)
AB = this.A.point.create_line(this.B.point, line_args)
BC = this.B.point.create_line(this.C.point, line_args)
this.static_lines.enqueue(XA).enqueue(AB).enqueue(BC)
// dynamic
CD = this.C.point.create_line(this.D.point, this.is_complete ? line_args : line_args_live)
this.dynamic_lines.enqueue(CD)
// fills
this.fills
.enqueue(XA.create_fill(AB, fill_color))
.enqueue(BC.create_fill(CD, fill_color))
// prepare point labels
if config.draw_point_labels
// static
this.static_point_labels
.enqueue(this.X.point.create_label('X', point_in_dir))
.enqueue(this.A.point.create_label('A', point_opp_dir))
.enqueue(this.B.point.create_label('B', point_in_dir))
.enqueue(this.C.point.create_label('C', point_opp_dir))
// dynamic
this.dynamic_point_labels.enqueue(this.D.point.create_label('D', point_in_dir))
// prepare retracement lines and labels
if config.draw_retracements
XB = this.X.point.create_line(this.B.point, config.label_args_retrace_line)
AC = this.A.point.create_line(this.C.point, config.label_args_retrace_line)
this.static_lines.enqueue(XB).enqueue(AC)
this.static_labels
.enqueue(XB.create_retracement_label(this.A, retrace_in_dir)) //, 'XAB', this.pattern.XABmin, this.pattern.XABmax, this.pattern.tolerances.XABmin, this.pattern.tolerances.XABmax))
.enqueue(AC.create_retracement_label(this.B, retrace_opp_dir)) //, 'ABC', this.pattern.ABCmin, this.pattern.ABCmax, this.pattern.tolerances.ABCmin, this.pattern.tolerances.ABCmax))
if not na(this.pattern.BCDmin) and not na(this.pattern.BCDmax)
BD = this.B.point.create_line(this.D.point, config.label_args_retrace_line)
this.dynamic_lines.enqueue(BD)
this.dynamic_labels.enqueue(BD.create_retracement_label(this.C, retrace_in_dir)) //, 'BCD', this.pattern.BCDmin, this.pattern.BCDmax, this.pattern.tolerances.BCDmin, this.pattern.tolerances.BCDmax))
if not na(this.pattern.XADmin) or not na(this.pattern.XBDmin) or not na(this.pattern.XCDmin) or not na(this.pattern.XADmax) or not na(this.pattern.XBDmax) or not na(this.pattern.XCDmax)
XD = this.X.point.create_line(this.D.point, config.label_args_retrace_line)
this.dynamic_lines.enqueue(XD)
if not na(this.pattern.XADmin) and not na(this.pattern.XADmax)
this.dynamic_labels.enqueue(XD.create_retracement_label(this.A, retrace_in_dir)) //, 'XAD', this.pattern.XADmin, this.pattern.XADmax, this.pattern.tolerances.XADmin, this.pattern.tolerances.XADmax))
if not na(this.pattern.XBDmin) and not na(this.pattern.XBDmax)
this.dynamic_labels.enqueue(XD.create_retracement_label(this.B, retrace_in_dir)) //, 'XBD', this.pattern.XBDmin, this.pattern.XBDmax, this.pattern.tolerances.XBDmin, this.pattern.tolerances.XBDmax))
if not na(this.pattern.XCDmin) and not na(this.pattern.XCDmax)
this.dynamic_labels.enqueue(XD.create_retracement_label(this.C, retrace_in_dir)) //, 'XCD', this.pattern.XCDmin, this.pattern.XCDmax, this.pattern.tolerances.XCDmin, this.pattern.tolerances.XCDmax))
// prepare target range plot
if config.draw_target_range
this.dynamic_lines
.enqueue(this.C.point.create_line(this.Dmin.point, config.line_Dtarget))
.enqueue(this.C.point.create_line(this.Dmax.point, config.line_Dtarget))
if config.draw_point_labels
if this.Dmin_price == this.Dmax_price
this.dynamic_point_labels
.enqueue(this.Dmax.point.create_label(this.pattern.name + ' - Dtarget', point_in_dir)) //, str.format('{0}', this.Dmax_price)))
else
this.dynamic_point_labels
.enqueue(this.Dmin.point.create_label('Dmin', point_opp_dir)) //, str.format('{0}', this.Dmin_price)))
.enqueue(this.Dmax.point.create_label('Dmax', point_in_dir)) //, str.format('{0}', this.Dmax_price)))
// optional retracements
if not na(this.pattern.XADmin) or not na(this.pattern.XBDmin) or not na(this.pattern.XCDmin)
XDmin = this.X.point.create_line(this.Dmin.point, config.line_Dtarget)
this.dynamic_lines.enqueue(XDmin)
if not na(this.pattern.XADmax) or not na(this.pattern.XBDmax) or not na(this.pattern.XCDmax)
XDmax = this.X.point.create_line(this.Dmax.point, config.line_Dtarget)
this.dynamic_lines.enqueue(XDmax)
// no center label, this is only drawn on the retracement line
this.name_label.draw()
this.static_lines.draw(extend_only = false)
this.static_labels.draw()
this.static_point_labels.draw()
if just_complete
D_line = this.dynamic_lines.get(this.dynamic_lines.size() - 1).apply_style(line_args)
if config.draw_point_labels
D_label = this.dynamic_point_labels.remove(this.dynamic_point_labels.size() - 1)
this.dynamic_point_labels.delete().clear()
this.dynamic_point_labels.enqueue(D_label)
if config.draw_levels
from_idx = this.terminal_bar_idx
from_time = this.terminal_bar_time
until_idx = from_idx + 40
until_time = from_time + 40 * tf_ms
line_completion = D.Line.new(chart.point.new(from_time, from_idx, this.D.point.price), chart.point.new(until_time, until_idx, this.D.point.price), config.line_args_completion)
line_tp1 = D.Line.new(chart.point.new(from_time, from_idx, this.tp1), chart.point.new(until_time, until_idx, this.tp1), config.line_args_tp1)
line_tp2 = D.Line.new(chart.point.new(from_time, from_idx, this.tp2), chart.point.new(until_time, until_idx, this.tp2), config.line_args_tp2)
line_sl = D.Line.new(chart.point.new(from_time, from_idx, this.sl), chart.point.new(until_time, until_idx, this.sl), config.line_args_sl)
this.static_lines
.enqueue(line_completion)
.enqueue(line_tp1)
.enqueue(line_tp2)
.enqueue(line_sl)
this.static_point_labels
.enqueue(D.Label.new(line_completion.end, str.format('{0} complete ({1})', this.pattern.name, str.tostring(math.round_to_mintick(this.D.point.price))), config.label_args_completion))
.enqueue(D.Label.new(line_tp1.end, str.format('TP 1 ({0})', str.tostring(math.round_to_mintick(this.tp1))), config.label_args_tp1))
.enqueue(D.Label.new(line_tp2.end, str.format('TP 2 ({0})', str.tostring(math.round_to_mintick(this.tp2))), config.label_args_tp2))
.enqueue(D.Label.new(line_sl.end, str.format('LRP ({0})', str.tostring(math.round_to_mintick(this.sl))), config.label_args_sl))
if barstate.isconfirmed
terminal_point = this.D.point.copy()
terminal_point.price := dir == 1 ? this.D.candle.l - terminal_label_yoffset : this.D.candle.h + terminal_label_yoffset
this.static_point_labels.enqueue(D.Label.new(terminal_point, terminal_char, terminal_args))
this.static_point_labels.draw()
this.static_lines.draw(extend_only = false)
// in case this is currently engulfed, we have drawn new lines and labels, but need to hide them (until the engulfing pattern fails)
if this.is_hidden
this.hide()
else if this.is_muted
this.mute(config.color_muted, config.fill_muted)
// dynamic update (values of points are updated via update() method)
if initial or just_complete or this.is_forming()
this.dynamic_lines.draw(extend_only = false) // retracement and pattern lines
this.dynamic_labels.draw() // retracement labels
this.dynamic_point_labels.draw()
this.fills.draw()
// update hidden, muted matches
if this.is_engulfed_by_completed and config.hide_engulfed_pattern
this.delete()
this.is_hidden := true
else if hide and not this.is_hidden
this.hide()
this.is_hidden := true
else if mute and not this.is_muted
this.mute(config.color_muted, config.fill_muted)
this.is_muted := true
else if not hide and not mute and (this.is_hidden or this.is_muted)
this.reset_styles()
this.is_hidden := false
this.is_muted := false
this
//@function checks if this pattern needs to be hidden or muted based on other plotted patterns and given configuration
export method check_hide_or_mute(Match this, map<string, Match> all, Config config, string[] debug_log = na) =>
hide = false
mute = false
if na(this) ? false : this.is_complete or this.is_forming()
has_shorter_pattern_with_same_X = false
is_engulfed = false
is_engulfed_by_same_type = false
is_sharing_too_many_points_with_longer_pattern = false
for other in all.values()
if na(other) ? false : other.is_complete or other.is_forming()
if this.id != other.id
if config.hide_engulfed_pattern
is_engulfed := is_engulfed or this.is_engulfed_by_completed// ? true : this.is_engulfed_by(other)
// kind of a inverse 'hide engulfed', hiding follow up patterns that start from the same X
if config.hide_longer_pattern_with_same_X and not is_engulfed
if has_shorter_pattern_with_same_X or other.X.point.index == this.X.point.index and other.D.point.index < this.D.point.index // and not other.is_hidden
has_shorter_pattern_with_same_X := has_shorter_pattern_with_same_X ? true : not (config.hide_engulfed_pattern and other.is_engulfed_by_completed) // TODO put this result into the match object, and maybe only check if ... think of something
is_overlapped_by_shared_legs = config.hide_shorter_if_shared_legs_greater_than_max and this.is_overlapped_by_shared_legs
is_overlapped_by_next = config.mute_previous_pattern_when_next_overlaps and this.is_overlapped_by_next
hide := is_engulfed
or has_shorter_pattern_with_same_X
or is_overlapped_by_shared_legs
mute := not hide and is_overlapped_by_next
if not na(debug_log) and (hide or mute)
debug_log.push(str.format('{0} changing visibility - hide:{1}, mute: {2}, is_engulfed:{3} - by_completed:{4}, has_shorter_pattern_with_same_X:{5}, overlapped_by_shared_legs: {6}, overlapped_by_next: {7}', this.id, hide, mute, is_engulfed, this.is_engulfed_by_completed, has_shorter_pattern_with_same_X, is_overlapped_by_shared_legs, is_overlapped_by_next))
[hide, mute]
//@function draw all Matches in this map, considering all other patterns for engulfing and overlapping
export method draw(map<string, Match> this, Config config, map<string, Match> all_patterns, float terminal_label_yoffset = 0, string[] debug_log = na) =>
if not na(this) and not na(config)
for i in this.values()
if not na(i)
[hide, mute] = i.check_hide_or_mute(all_patterns, config, debug_log)
i.draw(config, hide, mute, terminal_label_yoffset)
this
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//#endregion DRAW
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// DEMO
//////////////////////////////////////////////////////////////////////////////////////
// Inputs
//@function convenience function to add a search pattern to a list, only if given condition (input.bool) is true
export method add_if(Pattern[] id, Pattern item, bool condition) =>
if not na(id) and condition
id.push(item)
id
to_style(style) =>
switch style
'dotted' => line.style_dotted
'dashed' => line.style_dashed
=> line.style_solid
var g_selection = 'Pattern Selection'
var string i_direction = input.string('Bullish & Bearish', 'Direction', ['Bullish & Bearish', 'Bullish', 'Bearish'], group = g_selection, inline = 'ld')
var detect_bullish = str.contains(i_direction,'Bullish')
var detect_bearish = str.contains(i_direction,'Bearish')
var detect_both = detect_bullish and detect_bearish
var detect_dir = detect_both ? 0 : detect_bearish ? -1 : 1
var Pattern[] patterns = array.new<Pattern>()
.add_if(Pattern.new('Bat', XABmin = 0.382, XABmax = 0.500, ABCmin = 0.382, ABCmax = 0.886, BCDmin = 1.618, BCDmax = 2.618, XADmin = 0.886, XADmax = 0.886, tp1 = 0.5, tp2 = 1.5, sl = 1.5).set_tolerances(0.03, 0.03, 0.03, 0 ), input.bool(true, 'Bat' , group = g_selection, inline = '1'))
.add_if(Pattern.new('Alt Bat', XABmin = 0.382, XABmax = 0.382, ABCmin = 0.382, ABCmax = 0.886, BCDmin = 2.000, BCDmax = 3.618, XADmin = 1.130, XADmax = 1.130, tp1 = 0.5, tp2 = 1.5, sl = 1.5).set_tolerances(0.03, 0.03, 0.03, 0 ), input.bool(true, 'Alt Bat' , group = g_selection, inline = '1'))
.add_if(Pattern.new('Crab', XABmin = 0.382, XABmax = 0.618, ABCmin = 0.382, ABCmax = 0.886, BCDmin = 2.618, BCDmax = 3.618, XADmin = 1.618, XADmax = 1.618, tp1 = 0.5, tp2 = 1.5, sl = 1.5).set_tolerances(0.03, 0.03, 0.03, 0 ), input.bool(true, 'Crab' , group = g_selection, inline = '2'))
.add_if(Pattern.new('Deep Crab', XABmin = 0.886, XABmax = 0.886, ABCmin = 0.382, ABCmax = 0.886, BCDmin = 2.000, BCDmax = 3.618, XADmin = 1.618, XADmax = 1.618, tp1 = 0.5, tp2 = 1.5, sl = 1.5).set_tolerances(0.03, 0.03, 0.03, 0 ), input.bool(true, 'Deep Crab' , group = g_selection, inline = '2'))
.add_if(Pattern.new('Butterfly', XABmin = 0.786, XABmax = 0.786, ABCmin = 0.382, ABCmax = 0.886, BCDmin = 1.618, BCDmax = 2.618, XADmin = 1.272, XADmax = 1.618, tp1 = 0.5, tp2 = 1.5, sl = 1.5).set_tolerances(0.03, 0.03, 0.03, 0 ), input.bool(true, 'Butterfly' , group = g_selection, inline = '3'))
.add_if(Pattern.new('Gartley', XABmin = 0.618, XABmax = 0.618, ABCmin = 0.382, ABCmax = 0.886, BCDmin = 1.272, BCDmax = 1.618, XADmin = 0.786, XADmax = 0.786, tp1 = 0.5, tp2 = 1.5, sl = 1.5).set_tolerances(0.03, 0.03, 0.03, 0 ), input.bool(true, 'Gartley' , group = g_selection, inline = '3'))
.add_if(Pattern.new('Shark', XABmin = 0.382, XABmax = 0.618, ABCmin = 1.130, ABCmax = 1.618, BCDmin = 1.618, BCDmax = 2.240, XCDmin = 0.886, XCDmax = 1.130, tp1 = 0.5, tp2 = 1.5, sl = 1.5).set_tolerances(0.03, 0.03, 0 , 0.03 ), input.bool(true, 'Shark' , group = g_selection, inline = '3'))
var g_debug = 'Debug'
var bool debug_detection = input.bool(false, 'detection', group = g_debug, inline = 'debug')
var bool debug_engulfing = input.bool(false, 'plotting', group = g_debug, inline = 'debug')
var bool debug_enabled = debug_detection or debug_engulfing
var bool log_completed_patterns = input.bool(false, 'log completed')
var g_patterns = 'Pattern Detection'
var bool live = false // input.bool(false, 'live (repainting)', group = g_patterns, inline = 'ld')
var bool keep_failed = false // input.bool(false, 'keep failed patterns', group = g_patterns, inline = 'ld')
var int length = 10 // input.int(10, 'Pivot confirmation bars', group = g_patterns)
var int pattern_minlen = 20 // input.int(30, 'Min length', group = g_patterns)
var int pattern_maxlen = 150 // input.int(300, 'Max length', group = g_patterns)
var int max_lookback = 244 // input.int(400, 'Lookback bars', group = g_patterns)
var float max_XB_BD_ratio = 5
var int tolerance_xabc_sub_waves = 2 // input.int(2, 'Max sub waves', 0, 20, group = g_patterns)
var g_filter = 'Pattern Filter'
var bool hide_engulfed_pattern = true // input.bool(true, 'hide engulfed patterns', group = g_filter, inline = 'engulf')
var bool hide_engulfed_pattern_of_same_type = false // input.bool(true, 'of same type', group = g_filter, inline = 'engulf') // TODO default: hide_engulfed_pattern = false
var bool hide_longer_pattern_with_same_X = false // input.bool(false, 'hide followup patterns with same origin', group = g_filter)
var bool mute_previous_pattern_when_next_overlaps = false // input.bool(false, 'mute previous patterns when next overlaps', group = g_filter)
var bool hide_shorter_if_shared_legs = false // input.bool(false, 'Hide shorter pattern where shared legs greater than', group = g_filter, tooltip = '(0-4) when overlap detected, longer pattern remains', inline = 'shared legs')
var int i_hide_shorter_if_shared_legs_greater_than = 1 // input.int(1, '', 0, 4, group = g_filter, inline = 'shared legs')
var int hide_shorter_if_shared_legs_greater_than = hide_shorter_if_shared_legs ? i_hide_shorter_if_shared_legs_greater_than : 5
var g_plot = 'Pattern Plot'
var color color_bull = color.green // input.color(color.green, 'Pattern: Bull', group = g_plot, inline = 'col')
var color color_bear = color.red // input.color(color.red, ' Bear', group = g_plot, inline = 'col')
var color color_muted = color.gray // input.color(color.gray, ' Fail/Mute', group = g_plot, inline = 'col')
var int fill_opacity = 10 // input.int(10, ' Fill %', group = g_plot, inline = 'col')
var bool draw_retracements = false // input.bool(true, 'Show retracements: ', group = g_plot, inline = 'color_retr')
var color color_retracment_label = color.gray // input.color(color.gray, 'Label', group = g_plot, inline = 'color_retr')
var color color_retracment_line = color.gray // input.color(color.gray, ' Line', group = g_plot, inline = 'color_retr')
var string style_retracment_line = line.style_dotted // to_style(input.string('dotted', ' Style', ['dotted', 'dashed', 'solid'], group = g_plot, inline = 'color_retr'))
var bool draw_point_labels = false // input.bool(false, 'Show XABCD: ', group = g_plot, inline = 'color_points')
var color color_point_labels = color.gray // input.color(color.gray, ' Label', group = g_plot, inline = 'color_points')
var bool draw_target_range = false // input.bool(false, 'Show D target (live): ', group = g_plot, inline = 'color_target')
var color color_target_range = color.gray // input.color(color.gray, 'Line ', group = g_plot, inline = 'color_target')
var string style_target_range = line.style_dotted // to_style(input.string('dotted', ' Style', ['dotted', 'dashed', 'solid'], group = g_plot, inline = 'color_target'))
var bool draw_levels = false // input.bool(true, 'Show trade zones: ', group = g_plot, inline = 'col_trade')
var color color_completion = color.gray // input.color(color.gray, ' Complete', group = g_plot, inline = 'col_trade')
var color color_tp1 = color.lime // input.color(color.lime, ' TP1', group = g_plot, inline = 'col_trade')
var color color_tp2 = color.green // input.color(color.green, ' TP2', group = g_plot, inline = 'col_trade')
var color color_sl = color.red // input.color(color.red, ' LRP', group = g_plot, inline = 'col_trade')
// Set up configuration
var D.LineArgs pattern_line_args = D.LineArgs.new(#00000000, width = 2)
var D.LabelArgs pattern_point_args = D.LabelArgs.new(color_point_labels)
var D.LabelArgs name_label_args = D.LabelArgs.new(#00000000, #00000000, size = size.large)
var D.LabelArgs retracement_label_args = D.LabelArgs.new(color_retracment_label)
var D.LineArgs retracement_line_args = D.LineArgs.new(color_retracment_line, style = style_retracment_line)
var D.LineArgs line_args_Dtarget = D.LineArgs.new(color_target_range, style = style_target_range)
var D.LineArgs line_args_completion = D.LineArgs.new(color_completion, style = line.style_dashed)
var D.LineArgs line_args_tp1 = D.LineArgs.new(color_tp1, style = line.style_dashed)
var D.LineArgs line_args_tp2 = D.LineArgs.new(color_tp2, style = line.style_dashed)
var D.LineArgs line_args_sl = D.LineArgs.new(color_sl, style = line.style_dashed)
var D.LabelArgs label_args_completion = D.LabelArgs.new(color_completion, #00000000, style = label.style_label_lower_right, size = size.small)
var D.LabelArgs label_args_tp1 = D.LabelArgs.new(color_tp1, #00000000, style = label.style_label_lower_right, size = size.small)
var D.LabelArgs label_args_tp2 = D.LabelArgs.new(color_tp2, #00000000, style = label.style_label_lower_right, size = size.small)
var D.LabelArgs label_args_sl = D.LabelArgs.new(color_sl, #00000000, style = label.style_label_lower_right, size = size.small)
var D.LabelArgs label_terminal = D.LabelArgs.new(#00000000, #00000000, style = label.style_label_center, size = size.huge)
var LOG.Logger logger = log_completed_patterns ? LOG.Logger.new(color_logs = false, display = LOG.LogDisplay.new(15, position.bottom_left)) : na
var LOG.Logger debug_logger = debug_enabled ? LOG.Logger.new(color_logs = false, display = LOG.LogDisplay.new(15, position.bottom_right)) : na
string[] debug_log = debug_enabled ? array.new<string>() : na
var Config config = create_config(pattern_line_args, pattern_point_args, name_label_args, retracement_line_args, retracement_label_args, line_args_Dtarget, line_args_completion, line_args_tp1, line_args_tp2, line_args_sl, label_args_completion, label_args_tp1, label_args_tp2, label_args_sl, label_terminal, '▲', '▼', color_bull, color_bear, color_muted, fill_opacity, draw_point_labels, draw_retracements, draw_target_range, draw_levels, hide_shorter_if_shared_legs, hide_engulfed_pattern, hide_engulfed_pattern_of_same_type, hide_longer_pattern_with_same_X, mute_previous_pattern_when_next_overlaps)
var map<string, Match> tracking_matches = map.new<string, Match>()
var ZZ.Zigzag zigzag = ZZ.Zigzag.new(max_lookback, P.HLData.new(length, xloc.bar_time))
zigzag.update()
max_age_idx = bar_index - max_lookback
[just_completed_matches, just_invalidated_setups, buffered_completed_matches, handled_matches] = tracking_matches.update(zigzag, patterns, max_age_idx, detect_dir, pattern_minlen, pattern_maxlen, tolerance_xabc_sub_waves, hide_shorter_if_shared_legs_greater_than) //,debug_detection ? debug_log : na)
all_patterns = buffered_completed_matches.copy()
all_patterns.put_all(just_completed_matches)
if live
all_patterns.put_all(tracking_matches)
terminal_label_yoffset = ta.atr(100)
all_patterns.draw(config, all_patterns, terminal_label_yoffset, debug_engulfing ? debug_log : na)
if keep_failed
just_invalidated_setups.mute(config.color_muted, config.fill_muted)
else
just_invalidated_setups.delete()
if log_completed_patterns
for match in just_completed_matches.values()
if match.is_complete and not match.is_hidden and not match.is_muted
logger.info(str.format('Completed {0}', debug_enabled ? match.id : match.name))
// DEBUG OUTPUT
if na(debug_log) ? false : debug_log.size() > 0
debug_logger.debug(debug_log.join('\n'))
// // for setup in xabc_setups
// // // enter position
// // for fail in invalidated_setups
// // // exit position
// // for match in just_completed_matches
// // re-entry or tp
// // alert(str.format('{0} completed', match.name), alert.freq_once_per_bar)
plot(bar_index, 'bar_index', display = display.data_window)
plot(tracking_matches.size(), 'Patterns active', display = display.data_window)
plotshape(ta.crossover(tracking_matches.size(), 0), 'Pattern new', shape.cross, location.bottom, color.gray, editable = false, size = size.tiny, display = display.data_window)
plotchar(tracking_matches.size() > 0, 'Pattern tracking', '_', location.bottom, color.gray, editable = false, size = size.tiny, display = display.data_window)
plotshape(just_completed_matches.size() > 0, 'Pattern complete', shape.square, location.bottom, color.gray, editable = false, size = size.tiny, display = display.data_window)
plotshape(just_invalidated_setups.size() > 0, 'Pattern invalid', shape.xcross, location.bottom, color.gray, editable = false, size = size.tiny, display = display.data_window)
plot(all_patterns.size(), 'Overlaps checked (complete, buffered)', display = display.data_window)
plot(buffered_completed_matches.size(), 'Patterns complete (buffered)', display = display.data_window)
//////////////////////////////////////////////////////////////////////////////////////
//#regionend DEMO
////////////////////////////////////////////////////////////////////////////////////// |
AR Forecast Scatterplot [SS] | https://www.tradingview.com/script/CQ5x2amE-AR-Forecast-Scatterplot-SS/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 504 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// ___________________
// / \
// / _____ _____ \
// / / \ / \ \
// __/__/ \____/ \__\_____
//| ___________ ____|
// \_________/ \_________/
// \ /////// /
// \/////////
// © Steversteves
//@version=5
indicator("AR Forecast Scatterplot [SS]", overlay=true, max_lines_count = 500, max_labels_count = 500)
import Steversteves/SPTS_StatsPakLib/1 as spts
t1 = "This will plot a line from the first Result to the last Result for the forecast length"
t2 = "Showing results and variances will plot both the results (blue) and the standard errors based on the variance in the dataset. Only plotting reuslts will only plot the most likely outcome without the variance."
// Inputs
src = input.source(close, "Forecast Source"), train = input.int(150, "Train Time"), len = input.int(14, "Forecast Length"),
typ = input.string("Scatter Plot", "Scatter Plot Type", ["Line Plot", "Scatter Plot"]), show_stats = input.bool(true, "Show Model Statistics")
line_bf = input.bool(true, "Show Trendline", tooltip = t1), show_others = input.string("Show Results and Variances","Show Results/Variance", ["Show Results and Variances", "Show Results Only"], tooltip = t2)
// Arrays
results = array.new_float()
ucl = array.new_float()
lcl = array.new_float()
// Forecast
[a, b, c] = spts.f_forecast(src, src[1], train, len, results, ucl, lcl)
// Model Statistics
cor = ta.correlation(src, src[len], train)
r2 = math.pow(cor,2)
max_val = array.max(ucl)
min_val = array.min(lcl)
// Plots
var table data = table.new(position.middle_right, 2, 6, bgcolor = color.blue, frame_color = color.rgb(0, 0, 0), frame_width = 4)
if show_stats
table.cell(data, 1, 1, text = "Model Data", bgcolor = color.blue, text_color = color.white)
table.cell(data, 1, 2, text = "Correlation: " + str.tostring(math.round(cor,2)), bgcolor = color.blue, text_color = color.white)
table.cell(data, 1, 3, text = "R2: " + str.tostring(math.round(r2, 3)), bgcolor = color.blue, text_color = color.white)
table.cell(data, 1, 4, text = "Max Forecasted Value: " + str.tostring(math.round(max_val, 2)), bgcolor = color.blue, text_color = color.white)
table.cell(data, 1, 5, text = "Min Forecasted Value: " + str.tostring(math.round(min_val, 2)), bgcolor = color.blue, text_color = color.white)
if barstate.islast and typ == "Line Plot"
for i = 0 to len
line.new(bar_index + i, y1 = array.get(results, i), x2 = bar_index + 1 + i, y2 = array.get(results, i), color = color.blue, width = 3)
if show_others == "Show Results and Variances"
line.new(bar_index + i, y1 = array.get(ucl, i), x2 = bar_index + 1 + i, y2 = array.get(ucl, i), color = color.lime, width = 3)
line.new(bar_index + i, y1 = array.get(lcl, i), x2 = bar_index + 1 + i, y2 = array.get(lcl, i), color = color.red, width = 3)
if barstate.islast and typ == "Scatter Plot"
for i = 0 to len
label.new(bar_index + i, array.get(results, i), text = "", color = color.blue, style = label.style_circle, size = size.tiny)
if show_others == "Show Results and Variances"
label.new(bar_index + i, array.get(ucl, i), text = "", color = color.lime, style = label.style_circle, size = size.tiny)
label.new(bar_index + i, array.get(lcl, i), text = "", color = color.red, style = label.style_circle, size = size.tiny)
var line trendline = na
if barstate.islast and line_bf
line.delete(trendline)
trendline := line.new(bar_index[1], y1 = array.get(results, 0), x2 = bar_index + array.size(results) - 1, y2 = array.get(results, array.size(results) - 1), color = color.purple, width = 3) |
Previous Day High and Low + Separators Daily/Weekly | https://www.tradingview.com/script/bwpBIBHM-Previous-Day-High-and-Low-Separators-Daily-Weekly/ | Algoryze | https://www.tradingview.com/u/Algoryze/ | 666 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Algoryze
//@version=5
indicator("Previous Day High and Low + Separators Daily/Weekly", overlay=true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)
// Function to check if a new day has started
_isNewDay(utcOffsetInMs) =>
dow = dayofweek(time + utcOffsetInMs)
dayChanged = dow != dow[1]
dayChanged
// Function to check if a new week has started
_isNewWeek(utcOffsetInMs) =>
woy = weekofyear(time + utcOffsetInMs)
weekChanged = woy != woy[1]
weekChanged
_bottomMarkText(barTime, utcOffsetInMs) =>
var monthShortNames = array.from('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
var weekdayShortNames = array.from('', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
weekdayShort = array.get(weekdayShortNames, dayofweek(barTime + utcOffsetInMs))
out = ''
+ weekdayShort
+ ' ' + str.tostring(dayofmonth(barTime + utcOffsetInMs))
+ ' ' + array.get(monthShortNames, month(barTime + utcOffsetInMs))
+ " '" + str.substring(str.tostring(year(barTime + utcOffsetInMs), '#'), 2)
+ ' ' + str.format_time(barTime, 'HH:mm')
// Function to get the highest and lowest prices of the previous day
_getPreviousDayHighLow(utcOffsetInMs) =>
dow = dayofweek(time + utcOffsetInMs)
var prevDayHigh = high
var prevDayHighTime = time
var prevDayLow = low
var prevDayLowTime = time
var dayHigh = high
var dayHighTime = time
var dayLow = low
var dayLowTime = time
if (dow != dow[1])
dayHigh := high
dayHighTime := time
dayLow := low
dayLowTime := time
prevDayHigh := dayHigh[1]
prevDayHighTime := dayHighTime[1]
prevDayLow := dayLow[1]
prevDayLowTime := dayLowTime[1]
else
if dayHigh < high
dayHigh := high
dayHighTime := time
if dayLow > low
dayLow := low
dayLowTime := time
[prevDayHigh, prevDayHighTime, prevDayLow, prevDayLowTime]
// Input for custom UTC offset
utcOffset = input.int(0, title="UTC Offset (in hours)", minval=-12, maxval=12)
utcOffsetInMs = utcOffset * 60 * 60 * 1000
// Daily separator inputs
var dailyGroup = 'Daily Separator'
dailySeparatorColor = input.color(color.orange, title='Color', group=dailyGroup)
dailySeparatorStyleInput = input.string('Solid', title='Style', options=['Solid', 'Dotted'], display=display.none, group=dailyGroup)
dailySeparatorWidthInput = input.int(1, title='Width', minval=1, display=display.none, group=dailyGroup)
dailySeparatorLabelTextColor = input.color(color.white, title='Label Text Color', group=dailyGroup)
dailySeparatorStyle = dailySeparatorStyleInput == 'Solid' ? line.style_solid : line.style_dotted
// Weekly separator inputs
var weeklyGroup = 'Weekly Separator'
weeklySeparatorColorInput = input.color(color.gray, title='Color', group=weeklyGroup)
weeklySeparatorStyleInput = input.string('Solid', title='Style', options=['Solid', 'Dotted'], display=display.none, group=weeklyGroup)
weeklySeparatorWidthInput = input.int(3, title='Width', minval=1, display=display.none, group=weeklyGroup)
weeklySeparatorStyle = weeklySeparatorStyleInput == 'Solid' ? line.style_solid : line.style_dotted
var prevDayHLGroup = 'Previous Day H&L'
prevDayHLColorInput = input.color(color.gray, title='Color', group=prevDayHLGroup)
prevDayHLTextColorInput = input.color(color.orange, title='Text Color', group=prevDayHLGroup)
prevDayHLStyleInput = input.string('Dotted', title='Style', options=['Solid', 'Dotted'], display=display.none, group=prevDayHLGroup)
prevDayHLWidthInput = input.int(3, title='Width', minval=1, display=display.none, group=prevDayHLGroup)
prevDayHLStyle = prevDayHLStyleInput == 'Solid' ? line.style_solid : line.style_dotted
var transpColor = color.new(color.white, 100)
var weekdayFullNames = array.from('', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
var box weekdayTopLabelBox = na
var box[] weekdayTopLabels = array.new_box(0)
var label[] weekdayBottomLabels = array.new_label(0)
var string periodD = "D"
var string periodW = "W"
var string periodM = "M"
var string periodY = "12M"
var int mult = timeframe.multiplier
var bool isHourly = timeframe.isminutes and mult % 60 == 0
var bool isMinuteLessThan30 = timeframe.isminutes and mult < 30
var string tfAuto =
timeframe.isseconds or isMinuteLessThan30 ? periodD :
isHourly ? periodW :
timeframe.isdaily ? periodM :
timeframe.isweekly or timeframe.ismonthly ? periodY :
periodW
pivotLevels = ta.pivot_point_levels('Traditional', timeframe.change(tfAuto))
pivot = array.get(pivotLevels, 0)
weekdayTopLabelBoxTop = array.get(pivotLevels, 5)
weekdayTopLabelBoxBottom = array.get(pivotLevels, 4)
weekdayBottomLabelLevel = array.get(pivotLevels, 6)
isNewPivot = pivot != pivot[1]
isNewDay = _isNewDay(utcOffsetInMs)
isNewWeek = _isNewWeek(utcOffsetInMs)
// Plot daily separator line
if isNewDay
weekdayFull = array.get(weekdayFullNames, dayofweek(time + utcOffsetInMs))
line.new(bar_index, low, bar_index, high, style=dailySeparatorStyle, width=dailySeparatorWidthInput, color=dailySeparatorColor, extend=extend.both)
weekdayTopLabelBox := box.new(bar_index, weekdayTopLabelBoxTop, bar_index, weekdayTopLabelBoxBottom, xloc=xloc.bar_index, bgcolor=transpColor, border_color=transpColor, text=weekdayFull, text_color=dailySeparatorColor, text_size=size.small, text_halign = text.align_center, text_valign = text.align_top)
array.push(weekdayTopLabels, weekdayTopLabelBox)
array.push(weekdayBottomLabels, label.new(bar_index, weekdayBottomLabelLevel, text=_bottomMarkText(time, utcOffsetInMs), color=dailySeparatorColor, textcolor=dailySeparatorLabelTextColor , style=label.style_label_up))
else
box.set_right(weekdayTopLabelBox, bar_index)
if isNewPivot and array.size(weekdayTopLabels) > 0
for i = 0 to array.size(weekdayTopLabels) - 1
box.set_top(array.get(weekdayTopLabels, i), weekdayTopLabelBoxTop)
box.set_bottom(array.get(weekdayTopLabels, i), weekdayTopLabelBoxBottom)
label.set_y(array.get(weekdayBottomLabels, i), weekdayBottomLabelLevel)
// Plot weekly separator line
if isNewWeek
line.new(bar_index, low, bar_index, high, color=weeklySeparatorColorInput, style=weeklySeparatorStyle, width=weeklySeparatorWidthInput, extend=extend.both)
// Plot highest and lowest prices of the previous day
[prevDayHigh, prevDayHighTime, prevDayLow, prevDayLowTime] = _getPreviousDayHighLow(utcOffsetInMs)
var line prevDayHighLine = line.new(time, prevDayHigh, time, prevDayHigh, xloc=xloc.bar_time, color=prevDayHLColorInput, width=1)
var label prevDayHighLabel = label.new(time, prevDayHigh, xloc=xloc.bar_time, text='HOD', color=transpColor, textcolor=prevDayHLTextColorInput, style=label.style_label_down)//, style=label.style_label_lower_left)
var line prevDayLowLine = line.new(time, prevDayLow, time, prevDayLow, xloc=xloc.bar_time, color=prevDayHLColorInput, width=1)
var label prevDayLowLabel = label.new(time, prevDayLow, xloc=xloc.bar_time, text='LOD', color=transpColor, textcolor=prevDayHLTextColorInput, style=label.style_label_up)//, style=label.style_label_upper_left)
if isNewDay
line.set_xy1(prevDayHighLine, prevDayHighTime, prevDayHigh)
line.set_xy2(prevDayHighLine, prevDayHighTime, prevDayHigh)
label.set_xy(prevDayHighLabel, prevDayHighTime, prevDayHigh)
line.set_xy1(prevDayLowLine, prevDayLowTime, prevDayLow)
line.set_xy2(prevDayLowLine, prevDayLowTime, prevDayLow)
label.set_xy(prevDayLowLabel, prevDayLowTime, prevDayLow)
else
t = time//chart.right_visible_bar_time
line.set_x2(prevDayHighLine, t)
label.set_x(prevDayHighLabel, t)
line.set_x2(prevDayLowLine, t)
label.set_x(prevDayLowLabel, t) |
Debugging Made Easy | https://www.tradingview.com/script/XTFagQ6m-Debugging-Made-Easy/ | DinGrogu | https://www.tradingview.com/u/DinGrogu/ | 1 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DinGrogu
//@version=5
library('debug')
// ############################################################
// # FUNCTIONS
// ############################################################
f_debug_label(_output, _delete=true, _position='') =>
position = _position == 'DOWN' ? label.style_label_down : _position == 'UP' ? label.style_label_up : label.style_label_left
bar = bar_index
if (position == label.style_label_left)
bar := bar_index + 2
debug_label = label.new(bar, close, color=color.blue, style=position, text=str.tostring(_output), textcolor=color.white)
if _delete
label.delete(debug_label[1])
f_debug_array(_items, _max=500, _reversed=false) =>
debug_array_list = ''
total = array.size(_items)
if (total)
if (_reversed)
array.reverse(_items)
for i = 0 to total - 1
if (i <= _max)
debug_array_list := debug_array_list + str.tostring(array.get(_items, i))
if (i != total - 1)
debug_array_list := debug_array_list + "\n"
response = debug_array_list
f_debug_array_table(_items, _max=500, _reversed=false) =>
table_margin = ' '
table_text_size = size.small
table_position = position.top_right
total = array.size(_items)
if (total > 0)
if (_reversed)
array.reverse(_items)
var debug_table = table.new(position=table_position, columns=2, rows=total + 1, border_width=3)
table.cell(debug_table, column=0, row=0, text='Results', bgcolor=color.blue, text_color=color.white, text_size=table_text_size)
table.cell(debug_table, column=1, row=0, text=table_margin, bgcolor=color.new(color.blue, 100), text_color=color.new(color.white, 100))
for i = 0 to total - 1
if (i <= (_max - 1))
table.cell(debug_table, column=0, row=i + 1, text=str.tostring(array.get(_items, i)), bgcolor=color.blue, text_color=color.white, text_size=table_text_size)
else
var debug_table = table.new(position=table_position, columns=2, rows=1, border_width=3)
table.cell(debug_table, column=0, row=0, text='Empty Array', bgcolor=color.blue, text_color=color.white, text_size=table_text_size)
table.cell(debug_table, column=1, row=0, text=table_margin, bgcolor=color.new(color.blue, 100), text_color=color.new(color.white, 100))
f_debug_message(_message, _type, _toggle) =>
alert_type = _type == 'error' ? color.red : _type == 'warning' ? color.orange : color.blue
var table alert_table = table.new(position.bottom_center, 1, 1, border_width=1)
if (_toggle and (barstate.islast or barstate.islastconfirmedhistory or barstate.isrealtime))
// We only populate the table on the last bar.
table.set_frame_color(alert_table, color.white)
table.set_frame_width(alert_table, 1)
table.cell(alert_table, 0, 0, ' ' + _message + ' ', bgcolor=alert_type, text_color=color.white, text_size=size.normal)
// ############################################################
// # EXPORT FUNCTIONS
// ############################################################
// @function - Debug label
// @param _output <string> Label output string
// @param _delete <bool> Delete all labels and only show the last one
export label(string _output, bool _delete=false, string _position='DOWN') =>
f_debug_label(_output, _delete, _position)
export label(float _output, bool _delete=false, string _position='DOWN') =>
f_debug_label(_output, _delete, _position)
export label(int _output, bool _delete=false, string _position='DOWN') =>
f_debug_label(_output, _delete, _position)
export label(bool _output, bool _delete=false, string _position='DOWN') =>
f_debug_label(_output, _delete, _position)
// @function - Debug label on last bar
// @param _output <string> Label output string
// @param _delete <bool> Delete all labels and only show the last one
export label_last(string _output, bool _delete=true, string _position='LEFT') =>
f_debug_label(_output, _delete, _position)
export label_last(float _output, bool _delete=true, string _position='LEFT') =>
f_debug_label(_output, _delete, _position)
export label_last(int _output, bool _delete=true, string _position='LEFT') =>
f_debug_label(_output, _delete, _position)
export label_last(bool _output, bool _delete=true, string _position='LEFT') =>
f_debug_label(_output, _delete, _position)
// @function - Debug label on last bar.
// @param _items <array float> array of items.
// @param _max <int> Maximum items to display
// @param _reversed <bool> Show reversed array
export label_array(array<float> _items, int _max=500, bool _reversed=false) =>
f_debug_label(f_debug_array(_items, _max, _reversed), true, 'LEFT')
export label_array(array<string> _items, int _max=500, bool _reversed=false) =>
f_debug_label(f_debug_array(_items, _max, _reversed), true, 'LEFT')
export label_array(array<int> _items, int _max=500, bool _reversed=false) =>
f_debug_label(f_debug_array(_items, _max, _reversed), true, 'LEFT')
// @function - Debug label on last bar.
// @param _items <array float> array of items.
// @param _max <int> Maximum items to display
// @param _reversed <bool> Show reversed array
export array(array<float> _items, int _max=500, bool _reversed=false) =>
f_debug_array_table(_items, _max, _reversed)
// @function - Debug error message.
// @param _message <string> Label output string
// @param _display <bool> Toggle to show hide the message.
export error(string _message, bool _display=true) =>
f_debug_message(_message, 'error', _display)
export error(float _message, bool _display=true) =>
f_debug_message(str.tostring(_message), 'error', _display)
export error(int _message, bool _display=true) =>
f_debug_message(str.tostring(_message), 'error', _display)
// @function - Debug warning message.
// @param _message <string> Label output string
// @param _display <bool> Toggle to show hide the message.
export warning(string _message, bool _display=true) =>
f_debug_message(_message, 'warning', _display)
export warning(float _message, bool _display=true) =>
f_debug_message(str.tostring(_message), 'warning', _display)
export warning(int _message, bool _display=true) =>
f_debug_message(str.tostring(_message), 'warning', _display)
// @function - Debug info message.
// @param _message <string> Label output string
// @param _display <bool> Toggle to show hide the message.
export info(string _message, bool _display=true) =>
f_debug_message(_message, 'info', _display)
export info(float _message, bool _display=true) =>
f_debug_message(str.tostring(_message), 'info', _display)
export info(int _message, bool _display=true) =>
f_debug_message(str.tostring(_message), 'info', _display)
|
Breakout Detector (Previous MTF High Low Levels) [LuxAlgo] | https://www.tradingview.com/script/27kn3NDw-Breakout-Detector-Previous-MTF-High-Low-Levels-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 806 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Breakout Detector (Previous MTF High Low Levels) [LuxAlgo]", 'LuxAlgo - Breakout Detector (Previous MTF High Low Levels)', max_lines_count=500, max_boxes_count=500, max_labels_count=500, max_bars_back=2000, overlay=true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
s5 = ' '
s7 = ' '
s10 = ' '
opt = input.string ( 'HTF' ,'Option: '+s10 , options= [ 'HTF' , 'Mult' ] , inline='a', group='Set Higher TimeFrame')
res = input.timeframe( 'D' , '• HTF' +s10+s5 , inline='b', group='Set Higher TimeFrame')
mlt = input.int ( 3 , '• Mult'+s10+s5, minval =1, maxval =20, tooltip='Multiple of Current TF', inline='c', group='Set Higher TimeFrame')
iTP = input.string ( 'W : L' , 'SL / TP ' , options= [ 'W : L' , 'W% : L%' ] , inline='1', group='Set Win / Loss Level')
w = input.int ( 2 , 'W : L'+s7 , minval = 0 , inline='3', group='Set Win / Loss Level')
l = input.int ( 1 , ':' , minval = 0 , tooltip='-> Loss Settings (L)' , inline='3', group='Set Win / Loss Level')
percW = input.float ( 5 , 'W% : L%' , minval = 0.01 , inline='2', group='Set Win / Loss Level') / 100
percL = input.float ( 2 , ':' , minval = 0.01 , inline='2', group='Set Win / Loss Level') / 100
loss = input.string ( 'RCM' , 'Base:'+s7+s10, options= ['RCM', 'ATR', 'Last Swing'] , inline='4', group= 'Loss Settings (L)' )
RcmAtrM = input.int ( 3 ,'• Multiple'+s10, minval =1, maxval =20 , tooltip= 'Multiple Of:\n• Average True Range\n• Range Cumulative Mean'
, inline='5', group= 'Loss Settings (L)' )
len = input.int ( 10 ,'• Swing Length', minval =1, maxval =20 , tooltip='Swing (Length Left)' , inline='6', group= 'Loss Settings (L)' )
INV = color.new (color.blue , 100)
cTP = input.color (#2157f3 ,'TP')
cSL = input.color (#ff5d00 ,'SL')
border = input.string (line.style_dotted, 'Borders', options=[line.style_solid, line.style_dashed, line.style_dotted], tooltip= "When TP/SL not reached")
bcol = input.bool ( true , 'Show Timeframe Change' , group= "Extra" )
falseOutBreak = input.bool ( true , 'Detect False Breakout' , inline = 'cFail', group= "Extra" ), x = falseOutBreak ? 2 : 0
cFail = input.color ( color.new(color.fuchsia, 80), '' , inline = 'cFail', group= "Extra" )
stopAtEndHTF = input.bool ( false , 'Cancel TP/SL at end of HTF' , group= "Extra" )
//Dashboard
showDash = input.bool ( true , 'Show Dashboard' , group= 'Dashboard' )
dashLoc = input.string ( 'Top Right' , 'Location' , options = ['Top Right', 'Bottom Right', 'Bottom Left'] , group= 'Dashboard' )
textSize = input.string ( 'Small' , 'Size' , options = ['Tiny', 'Small', 'Normal'] , group= 'Dashboard' )
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
n = bar_index
ph = fixnan(ta.pivothigh(len, 1))
pl = fixnan(ta.pivotlow (len, 1))
atr= ta.atr(200)
rcm= ta.cum(high - low) / (n+1) // RCM (range cumulative mean)
//-----------------------------------------------------------------------------}
//UDT
//-----------------------------------------------------------------------------{
type Tbreak
bool act
int idx
float prc
float stp
bool fail
float tp
bool prof
//-----------------------------------------------------------------------------}
//Methods/Functions
//-----------------------------------------------------------------------------{
p(int x, float y) => chart.point.from_index(x, y)
method box(string s, Tbreak obj) =>
// TP box
box.new(obj.idx, obj.prc, n, obj.tp , bgcolor= color.new(cTP, 85), border_color=
s == 'fail' ? INV : s == 'prof' or (obj.prc > obj.stp and close > obj.prc)
or (obj.prc < obj.stp and close < obj.prc) ? cTP : INV ,
border_style = s == 'none' and ((obj.prc > obj.stp and close > obj.prc and close < obj.tp and close > obj.stp)
or (obj.prc < obj.stp and close < obj.prc and close > obj.tp and close < obj.stp)) ? border : line.style_solid)
// SL box
box.new(obj.idx, obj.prc, n, obj.stp, bgcolor= color.new(cSL, 85), border_color=
s == 'prof' ? INV : s == 'fail' or (obj.prc > obj.stp and close < obj.prc)
or (obj.prc < obj.stp and close > obj.prc) ? cSL : INV ,
border_style = s == 'none' and ((obj.prc > obj.stp and close < obj.prc and close < obj.tp and close > obj.stp)
or (obj.prc < obj.stp and close > obj.prc and close > obj.tp and close < obj.stp)) ? border : line.style_solid)
method update(Tbreak br, bool a, int i, float p, float s, bool f, float t, bool w) => br.act := a, br.idx := i, br.prc := p, br.stp := s, br.fail := f, br.tp := t, br.prof := w
method lab(string s, string pos, color col, color txtcol) => label.new(
n , close
, yloc = pos == 'top' ? yloc.abovebar : yloc.belowbar
, style = pos == 'top' ? label.style_label_down : label.style_label_up
, color = col
, textcolor = txtcol
, size = size.small
, text = s
)
res() =>
M = timeframe.multiplier * mlt, strM = str.tostring(M)
opt == 'HTF' ? timeframe.in_seconds(timeframe.period)
>= timeframe.in_seconds(res)
? ''
: res
: timeframe.isdaily ? strM + 'D'
: timeframe.isweekly ? strM + 'W'
: timeframe.ismonthly ? strM + 'M'
: M >= 1440
? str.tostring(math.round(M / 1440)) + 'D'
: strM
formatRes(res) =>
out = res
if not str.contains(res, 'D') and not str.contains(res, 'W') and not str.contains(res, 'M')
nRes = str.tonumber(res)
if nRes % 60 == 0
out := str.format('{0}{1}', nRes / 60, 'h' )
else
out := str.format('{0}{1}', nRes , 'min')
out
//-----------------------------------------------------------------------------}
//Execution
//-----------------------------------------------------------------------------{
fres = res(), tfCh = timeframe.change(fres)
var line prevh = na, var crossph = false, var max = high, var max_x1 = 0
var line prevl = na, var crosspl = false, var min = low , var min_x1 = 0
var countBrOut_TT = 0, var count_F_BrOut_TT = 0, var countTP_TT = 0, var countSL_TT = 0, var countWn_TT = 0, var countLs_TT = 0
var countBrOut_Bl = 0, var count_F_BrOut_Bl = 0, var countTP_Bl = 0, var countSL_Bl = 0, var countWn_Bl = 0, var countLs_Bl = 0
var countBrOut_Br = 0, var count_F_BrOut_Br = 0, var countTP_Br = 0, var countSL_Br = 0, var countWn_Br = 0, var countLs_Br = 0
brOutBl = false, falseBl = false, prof_Bl = false, fail_Bl = false, brOutBr = false, falseBr = false, prof_Br = false, fail_Br = false
if tfCh
if not crossph
prevh.set_x2(max_x1)
if not crosspl
prevl.set_x2(min_x1)
prevh := line.new(max_x1, max, n, max, color = #f23645)
prevl := line.new(min_x1, min, n, min, color = #089981)
max := high, max_x1 := n, crossph := false
min := low , min_x1 := n, crosspl := false
else //Update max/min and anchoring points
max := math.max(high , max )
max_x1 := max == high ? n : max_x1
min := math.min(low , min )
min_x1 := min == low ? n : min_x1
if not crossph
prevh.set_x2(n)
if close > prevh.get_y2()
crossph := true
if not crosspl
prevl.set_x2(n)
if close < prevl.get_y2()
crosspl := true
var bxTopBreak = Tbreak.new(false, na, na, na, na, na, na)
var bxBtmBreak = Tbreak.new(false, na, na, na, na, na, na)
//Break-out
ATRok = iTP == 'W : L' and loss == 'ATR' ? n > 200 : true
top = prevh.get_y2(), breakTop = crossph and not crossph[1] and ATRok and not bxTopBreak.act
btm = prevl.get_y2(), breakBtm = crosspl and not crosspl[1] and ATRok and not bxBtmBreak.act
method poly(Tbreak T) =>
p = array.new<chart.point>()
p.unshift(chart.point.from_index( n , T.prc))
p.unshift(chart.point.from_index( n , T.tp ))
p.unshift(chart.point.from_index(T.idx, T.tp ))
p.unshift(chart.point.from_index(T.idx, T.prc))
polyline.new(p, line_color=INV
, fill_color=color.new(color.green, 75))
p := array.new<chart.point>()
p.unshift(chart.point.from_index( n , T.stp))
p.unshift(chart.point.from_index(T.idx, T.stp))
p.unshift(chart.point.from_index(T.idx, T.prc))
p.unshift(chart.point.from_index( n , T.prc))
polyline.new(p, line_color=INV
, fill_color=color.new(color.red , 75))
for poly in polyline.all
poly.delete()
// While already in position, there is a break in the same direction, this will be ignored
// example -> bullish position, bullish break -> ignored
switch
breakTop =>
brOutBl := true, countBrOut_TT += 1, countBrOut_Bl += 1, '▲'.lab('btm', color(na), #089981)
ls = iTP == 'W% : L%'
? close * (1 - percL)
: loss == 'ATR'
? close - (atr * RcmAtrM)
: loss == 'RCM'
? close - (rcm * RcmAtrM)
: pl
pf = iTP == 'W% : L%'
? close * (1 + percW)
: loss == 'ATR'
? close + ((atr * RcmAtrM) * (w/l))
: loss == 'RCM'
? close + ((rcm * RcmAtrM) * (w/l))
: close + (close - pl) * (w/l)
bxTopBreak.update(true , n , close, ls, false, pf, false)
bxTopBreak.poly()
bxTopBreak.act =>
switch
breakBtm or (stopAtEndHTF and tfCh) =>
switch
close >= bxTopBreak.prc =>
switch
close < bxTopBreak.tp => countWn_TT += 1, countWn_Bl += 1
=> countWn_TT += 1, countWn_Bl += 1
, countTP_TT += 1, countTP_Bl += 1
=>
switch
close > bxTopBreak.stp => countLs_TT += 1, countLs_Bl += 1
=> countLs_TT += 1, countLs_Bl += 1
, countSL_TT += 1, countSL_Bl += 1
bxTopBreak.act := false
'none'.box(bxTopBreak)
(n - bxTopBreak.idx < x and close < top) =>
falseBl := true
, 'F'.lab('top', cFail, color.white)
, count_F_BrOut_TT += 1
, count_F_BrOut_Bl += 1
, bxTopBreak.update(false, na, na, na, na, na, na)
high > bxTopBreak.tp and not bxTopBreak.prof =>
bxTopBreak.prof := true
, prof_Bl := true
, 'prof'.box(bxTopBreak)
, countWn_TT += 1, countWn_Bl += 1
, countTP_TT += 1, countTP_Bl += 1
, bxTopBreak.update(false, na, na, na, na, na, na)
close < bxTopBreak.stp and not bxTopBreak.fail =>
bxTopBreak.fail := true
, fail_Bl := true
, 'fail'.box(bxTopBreak)
, countLs_TT += 1, countLs_Bl += 1
, countSL_TT += 1, countSL_Bl += 1
, bxTopBreak.update(false, na, na, na, na, na, na)
bxTopBreak.poly()
(bxTopBreak.fail[1] or
bxTopBreak.prof[1]) => bxTopBreak.update(false, na, na, na, na, na, na)
switch
breakBtm =>
brOutBr := true, countBrOut_TT += 1, countBrOut_Br += 1, '▼'.lab('top', color(na), #f23645)
ls = iTP == 'W% : L%'
? close * (1 + percL)
: loss == 'ATR'
? close + (atr * RcmAtrM)
: loss == 'RCM'
? close + (rcm * RcmAtrM)
: ph
pf = iTP == 'W% : L%'
? close * (1 - percW)
: loss == 'ATR'
? close - ((atr * RcmAtrM) * (w/l))
: loss == 'RCM'
? close - ((rcm * RcmAtrM) * (w/l))
: close - (ph - close) * (w/l)
bxBtmBreak.update(true , n , close, ls, false, pf, false)
bxBtmBreak.poly()
bxBtmBreak.act =>
switch
breakTop or (stopAtEndHTF and tfCh) =>
switch
close <= bxBtmBreak.prc =>
switch
close > bxBtmBreak.tp => countWn_TT += 1, countWn_Br += 1
=> countWn_TT += 1, countWn_Br += 1
, countTP_TT += 1, countTP_Br += 1
=>
switch
close < bxBtmBreak.stp => countLs_TT += 1, countLs_Br += 1
=> countLs_TT += 1, countLs_Br += 1
, countSL_TT += 1, countSL_Br += 1
bxBtmBreak.act := false
'none'.box(bxBtmBreak)
(n - bxBtmBreak.idx < x and close > btm) =>
falseBr := true
, 'F'.lab('btm', cFail, color.white)
, count_F_BrOut_TT += 1, count_F_BrOut_Br += 1
, bxBtmBreak.update(false, na, na, na, na, na, na)
low < bxBtmBreak.tp and not bxBtmBreak.prof =>
bxBtmBreak.prof := true
, prof_Br := true
, 'prof'.box(bxBtmBreak)
, countWn_TT += 1, countWn_Br += 1
, countTP_TT += 1, countTP_Br += 1
, bxBtmBreak.update(false, na, na, na, na, na, na)
close > bxBtmBreak.stp and not bxBtmBreak.fail =>
bxBtmBreak.fail := true
, fail_Br := true
, 'fail'.box(bxBtmBreak)
, countLs_TT += 1, countLs_Br += 1
, countSL_TT += 1, countSL_Br += 1
, bxBtmBreak.update(false, na, na, na, na, na, na)
bxBtmBreak.poly()
(bxBtmBreak.fail[1] or
bxBtmBreak.prof[1]) => bxBtmBreak.update(false, na, na, na, na, na, na)
if breakTop[1]
bxBtmBreak.update(false, na, na, na, false, na, na)
if breakBtm[1]
bxTopBreak.update(false, na, na, na, false, na, na)
//-----------------------------------------------------------------------------}
//Plot
//-----------------------------------------------------------------------------{
t1 = plot(bxTopBreak.prc, style=plot.style_linebr, color=color.new(cTP, 50), display=display.none)
t2 = plot(bxTopBreak.stp, style=plot.style_linebr, color=color.new(cTP, 50), display=display.none)
b1 = plot(bxBtmBreak.prc, style=plot.style_linebr, color=color.new(cSL, 50), display=display.none)
b2 = plot(bxBtmBreak.stp, style=plot.style_linebr, color=color.new(cSL, 50), display=display.none)
//-----------------------------------------------------------------------------}
//Timeframe Change
//-----------------------------------------------------------------------------{
bgcolor(bcol and tfCh ? color.new(color.silver, 93) : na)
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, falseOutBreak ? 7 : 6, 5
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if showDash
if barstate.isfirst
tb .cell(0, 0, '' , text_color = color.white, text_size = table_size)
tb .cell(0, 1, '' , text_color = color.white, text_size = table_size)
tb .cell(1, 1, 'Breakouts' , text_color = color.white, text_size = table_size)
tb .cell(2, 1, 'Wins' , text_color = color.white, text_size = table_size)
tb .cell(3, 1, '-> TP hit' , text_color = color.white, text_size = table_size)
tb .cell(4, 1, 'Losses' , text_color = color.white, text_size = table_size)
tb .cell(5, 1, '-> SL hit' , text_color = color.white, text_size = table_size)
if falseOutBreak
tb.cell(6, 1, 'False\nBreakouts' , text_color = color.white, text_size = table_size)
tb .cell(0, 2, 'Bullish' , text_color = color.white, text_size = table_size)
tb .cell(0, 3, 'Bearish' , text_color = color.white, text_size = table_size)
tb .cell(0, 4, 'Total' , text_color = color.white, text_size = table_size)
tb .merge_cells
(0, 0, falseOutBreak ? 6 : 5, 0 )
if barstate.islast
tb .cell(0, 0, str.format('HTF = {0}'
, formatRes (fres) ), text_color = color.white, text_size = table_size)
tb .cell(1, 2, str.tostring(countBrOut_Bl ), text_color = color.white, text_size = table_size)
tb .cell(1, 3, str.tostring(countBrOut_Br ), text_color = color.white, text_size = table_size)
tb .cell(1, 4, str.tostring(countBrOut_TT ), text_color = color.white, text_size = table_size)
tb .cell(2, 2, str.tostring(countWn_Bl ), text_color = color.white, text_size = table_size)
tb .cell(2, 3, str.tostring(countWn_Br ), text_color = color.white, text_size = table_size)
tb .cell(2, 4, str.tostring(countWn_TT ), text_color = color.white, text_size = table_size)
tb .cell(3, 2, str.tostring(countTP_Bl ), text_color = color.white, text_size = table_size)
tb .cell(3, 3, str.tostring(countTP_Br ), text_color = color.white, text_size = table_size)
tb .cell(3, 4, str.tostring(countTP_TT ), text_color = color.white, text_size = table_size)
tb .cell(4, 2, str.tostring(countLs_Bl ), text_color = color.white, text_size = table_size)
tb .cell(4, 3, str.tostring(countLs_Br ), text_color = color.white, text_size = table_size)
tb .cell(4, 4, str.tostring(countLs_TT ), text_color = color.white, text_size = table_size)
tb .cell(5, 2, str.tostring(countSL_Bl ), text_color = color.white, text_size = table_size)
tb .cell(5, 3, str.tostring(countSL_Br ), text_color = color.white, text_size = table_size)
tb .cell(5, 4, str.tostring(countSL_TT ), text_color = color.white, text_size = table_size)
if falseOutBreak
tb.cell(6, 2, str.tostring(count_F_BrOut_Bl), text_color = color.white, text_size = table_size)
tb.cell(6, 3, str.tostring(count_F_BrOut_Br), text_color = color.white, text_size = table_size)
tb.cell(6, 4, str.tostring(count_F_BrOut_TT), text_color = color.white, text_size = table_size)
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
alertcondition(brOutBl,' Bullish Breakout' , 'Bullish Breakout' )
alertcondition(falseBl,' Bullish False Breakout', 'Bullish False Breakout')
alertcondition(prof_Bl,' Bullish TP' , 'Bullish TP' )
alertcondition(fail_Bl,' Bullish Fail' , 'Bullish Fail' )
alertcondition(brOutBr,' Bearish Breakout' , 'Bearish Breakout' )
alertcondition(falseBr,' Bearish False Breakout', 'Bearish False Breakout')
alertcondition(prof_Br,' Bearish TP' , 'Bearish TP' )
alertcondition(fail_Br,'Bearish Fail' , 'Bearish Fail' )
//-----------------------------------------------------------------------------} |
Ranges With Targets [ChartPrime] | https://www.tradingview.com/script/3swrxpw6-Ranges-With-Targets-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 966 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Ranges with Targets [ChartPrime]",overlay = true,max_lines_count = 500,max_labels_count = 500)
var float SCR = 0.
var ATR = 0.
var TradeOn = false
Shape = false
color GREEN = color.rgb(4, 191, 101)
color TAIL = color.rgb(20, 141, 154)
color RED = color.rgb(246, 7, 7)
color _Green = color.rgb(2, 106, 89)
color OFF = color.new(color.red,100)
string DYNAMICSLG = "➞ Risk To Reward Settings 🔸"
string CORE = "➞ Core Settings 🔸"
var array<int> score = array.new_int(2,0)
var bool ShortTrade = false
var bool TradeisON = false
var bool LongTrade = false
var line res = na
var line sup = na
var line tpLine = na
var line SLLine = na
var label LAB = na
var float TP = 0.0
var float SL = 0.0
var float Res = 0.
bool BUY = false
bool SELL = false
bool Filter = input.bool(false,"ATR Body Filter",group = CORE)
float Target = input.float(1.3,"Target",step = 0.1 , tooltip = "Target And stop Multiplyer",group = CORE)
bool SLType = input.string('Close',
'SL Type', ['Close', 'High/Low'],
group=CORE,tooltip = "Activate SL on candle close or high/low") == 'Close'
float Risk = input.float(100,"Risk Per Trade (USD)",group=CORE)
bool ShowSL = input.bool(false,"Show SL",group = CORE)
string Linestyle = input.string('Dashed',
'Line Style', ['Solid', 'Dashed', 'Dotted'], group=CORE,inline= "Line")
color Bull = input.color(GREEN,"",group=CORE,inline= "Line")
color Bear = input.color(RED,"",group=CORE,inline= "Line")
method volAdj(int len)=>
math.min(ta.atr(len) * 0.3, close * (0.3/100)) [20] /2
PF = volAdj(30)
BodyRange() =>
math.abs(close - open)
BodyCon = bar_index > 100
BodyCon1 = (Filter ? BodyRange() < ta.atr(5) * 1 : true)
if timeframe.change("1D") and not TradeisON
ATR := volAdj(30)
SCR:=hl2 - (ATR* 15)
TradeOn:= true
Res:= SCR + (ATR* 25)
res:=line.new(bar_index, Res,bar_index, Res,color = #5c439a,style = line.style_solid)
sup:=line.new(bar_index, SCR,bar_index, SCR,color = #5c439a,style = line.style_solid)
if TradeOn
res.set_x2(bar_index)
sup.set_x2(bar_index)
if ta.crossover(close[1],Res) and BodyCon and BodyCon1
BUY:=true
if ta.crossunder(close[1],SCR) and BodyCon and BodyCon1
SELL:=true
linefill.new(res,sup,color = color.new(color.from_gradient(close,ta.lowest(5),ta.highest(10), #3a6186,#89253e),80))
//----- { SL Calculation
x2 = low - ta.rma(ta.tr(true), 14) * 1.5
xz = ta.rma(ta.tr(true), 14) * 1.5 + high
longDiffSL2 = math.abs(close - Res)
longDiffSL = math.abs(close - SCR)
// }
Long = BUY and not TradeisON
Short = SELL and not TradeisON
TradeFire = Long or Short
if Long and not TradeisON
LongTrade:= true
ShortTrade:= false
if Short and not TradeisON
LongTrade:= false
ShortTrade:= true
if true
if TradeFire and not TradeisON
TP := switch
Long => close + (Target * longDiffSL)
Short => close - (Target * longDiffSL2)
SL := switch
Long => close - longDiffSL
Short => close + longDiffSL2
TradeisON:= true
if true
line.new(bar_index,
Long ? high : low,
bar_index,
TP,
width=2,
color = TAIL,
style= line.style_dashed)
tpLine:= line.new(bar_index,
TP,
bar_index+2,
TP,
style= line.style_dashed,
color = TAIL
)
if ShowSL
SLLine:= line.new(bar_index,
SL,
bar_index+2,
SL,
style= line.style_dashed,
color = RED
)
LAB:=label.new(bar_index,
TP,
"Target",
color = TAIL,
style= label.style_label_left,
size=size.small,
textcolor = color.white
)
if TradeisON
line.set_x2(tpLine,bar_index)
label.set_x(LAB,bar_index+1)
if ShowSL
line.set_x2(SLLine,bar_index)
if LongTrade and TradeisON
if high >= TP
label.set_color(LAB,GREEN)
score.set(0,score.get(0)+1)
TradeisON:=false
if (SLType ? close : low) <= SL
score.set(1,score.get(1)+1)
label.set_color(LAB,color.new(RED,70))
label.set_tooltip(LAB,"Stoploss Hit : "+ str.tostring(math.round_to_mintick(SL)))
TradeisON:=false
else if ShortTrade and TradeisON
if low <= TP
label.set_color(LAB,GREEN)
score.set(0,score.get(0)+1)
TradeisON:=false
if (SLType ? close : high) >= SL
score.set(1,score.get(1)+1)
label.set_color(LAB,color.new(RED,70))
label.set_tooltip(LAB,"Stoploss Hit : "+ str.tostring(math.round_to_mintick(SL)))
TradeisON:=false
BearCon = TradeisON and ShortTrade
BullCon = TradeisON and LongTrade
barcolor(BearCon ? RED : BullCon ? _Green : color.rgb(52, 52, 54) )
plotcandle(open, high, low, close, color = BearCon ? RED : BullCon ? _Green : color.rgb(52, 52, 54),
wickcolor = color.rgb(103, 99, 99),bordercolor = BearCon ? RED : BullCon ? _Green : color.rgb(52, 52, 54))
bgcolor(BearCon ? color.rgb(136, 4, 15, 90) : BullCon ? color.rgb(8, 191, 158,90) : na )
// where is my table ?!
var tb = table.new(position.top_right, 6, 6,
bgcolor= color.new(color.gray,80))
if barstate.islast
GrossP = score.get(0) * (Risk * Target)
GrossL = score.get(1) * Risk
PNL = GrossP - GrossL
table.cell(tb, 0, 0, "Winning Trades"
, text_color = #a3a3b1)
table.cell(tb, 1, 0, str.tostring(score.get(0))
, text_color = #08c09b)
table.cell(tb, 0, 1, "Losing Trades"
, text_color = #a3a3b1)
table.cell(tb, 1, 1, str.tostring(score.get(1))
, text_color = #cd0202)
table.cell(tb, 0, 2, "Gross Profit"
, text_color = #a3a3b1)
table.cell(tb, 1, 2, str.tostring(GrossP)
, text_color = GrossP > 0 ? #1eddd4:#cd0202 )
table.cell(tb, 0, 3, "Gross Loss"
, text_color = #a3a3b1)
table.cell(tb, 1, 3, str.tostring(-GrossL)
, text_color = #cd0202 )
table.cell(tb, 0, 4, "Final PNL"
, text_color = #a3a3b1)
table.cell(tb, 1, 4, str.tostring(PNL)
, text_color = #ba7726 )
alertcondition(Long,"BUY")
alertcondition(Short,"Sell") |
Machine Learning: Anchored Gaussian Process Regression [LuxAlgo] | https://www.tradingview.com/script/a8ClWGX4-Machine-Learning-Anchored-Gaussian-Process-Regression-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 664 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Machine Learning: Anchored Gaussian Process Regression [LuxAlgo]", "LuxAlgo - Machine Learning: Anchored Gaussian Process Regression", overlay = true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
iTim = input.time (timestamp("20 Oct 2023"), 'Anchor 1' , confirm = true , inline = 'window1')
iTim_ = input.time (timestamp("20 Oct 2023"), 'Anchor 2' , confirm = true , inline = 'window2')
fitCss = input.color (#2962ff , 'Training Window Colours ' , inline = 'window3')
fitCssF = input.color (#2962ff13, '' , inline = 'window3')
forecast = input.int (20 , 'Forecasting Length ' , minval = 0 , inline = 'forecast')
fcastCss = input.color (#f23645 , '' , inline = 'forecast')
fcastCssF = input.color (#f2364513, '' , inline = 'forecast')
length = input.float (20. , 'Smooth ', minval = 1 )
sigma = input.float (0.1 , step = 0.1 , minval = 0 )
iTime = math.min(iTim, iTim_)
iTime_ = math.max(iTim, iTim_)
n = bar_index
Tdiff_bars = (iTime_ - iTime) / (timeframe.in_seconds(timeframe.period) * 1000)
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
//Radial basis function
rbf(x1, x2, l)=> math.exp(-math.pow(x1 - x2, 2) / (2.0 * math.pow(l, 2)))
//Kernel matrix
kernel_matrix(X1, X2, l)=>
km = matrix.new<float>(X1.size(), X2.size())
i = 0
for x1 in X1
j = 0
for x2 in X2
rbf = rbf(x1, x2, l)
km.set(i, j, rbf)
j += 1
i += 1
km
//-----------------------------------------------------------------------------}
//Lines
//-----------------------------------------------------------------------------{
line.new(iTime , close, iTime , close + syminfo.mintick
, color = color.new(color.silver, 50)
, xloc = xloc.bar_time
, extend = extend.both
)
line.new(iTime_, close, iTime_, close + syminfo.mintick
, color = color.new(color.yellow, 50)
, xloc = xloc.bar_time
, extend = extend.both
)
//-----------------------------------------------------------------------------}
//Kernel matrix
//-----------------------------------------------------------------------------{
var int window = 1
var matrix <int> identity = matrix.new<int>(1, 1, 0)
var matrix<float> K_source = na
if time == iTime
window := math.max(1, math.min(325 - forecast, Tdiff_bars))
identity := matrix.new<int>(window, window, 0)
xtrain = array.new<int>(0)
xtest = array.new<int>(0)
//Build identity matrix
for i = 0 to window -1
for j = 0 to window -1
identity.set(i, j, i == j ? 1 : 0)
xtrain.push(i)
for i = 0 to window + forecast -1
xtest .push(i)
//Compute kernel matrices
s = identity.mult(sigma * sigma)
Ktrain = kernel_matrix(xtrain, xtrain, length).sum(s)
//matrix.pinv() -> The function is calculated using a Moore–Penrose inverse formula based on singular-value decomposition of a matrix.
//For non-singular square matrices this function returns the result of matrix.inv.
K_inv = Ktrain.pinv()
K_star = kernel_matrix(xtrain, xtest , length)
K_source := K_star.transpose().mult(K_inv)
//-----------------------------------------------------------------------------}
//Set forecast
//-----------------------------------------------------------------------------{
var polyline poly = polyline.new( na ), points = array.new<chart.point>()
var polyline paly = polyline.new( na ), paints = array.new<chart.point>()
float mean = ta.sma(close, window )
if time == iTime_
//Remove previous polylines
poly.delete(), paly.delete()
//Dataset
ytrain = array.new<float>(0)
for i = 0 to window -1
ytrain.unshift(close[i] - mean)
//Estimate
mu = K_source.mult(ytrain)
//Set forecast
float y1 = na
k = -window +2
for element in mu
switch
k == 1 => points.push(chart.point.from_index(n+k, element + mean)),
paints.push(chart.point.from_index(n+k, element + mean))
k < 1 => points.push(chart.point.from_index(n+k, element + mean))
=> paints.push(chart.point.from_index(n+k, element + mean))
y1 := element + mean
k += 1
poly := polyline.new(points
, curved = true
, closed = false
, line_color = fitCss
, line_width = 2
, fill_color = fitCssF)
paly := polyline.new(paints
, curved = true
, closed = false
, line_color = fcastCss
, line_width = 2
, fill_color = fcastCssF)
//-----------------------------------------------------------------------------}
//Plot Moving Average
//-----------------------------------------------------------------------------{
plot(mean, 'MA', color=color.new(color.silver, 90), linewidth=5)
//-----------------------------------------------------------------------------} |
Liquidation Levels [LuxAlgo] | https://www.tradingview.com/script/VBLeqKvy-Liquidation-Levels-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,589 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator('Liquidation Levels [LuxAlgo]', 'LuxAlgo - Liquidation Levels', true, max_lines_count = 500, max_bars_back = 5000)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
rpTT = 'Liquidation Levels are estimates of potential price levels where liquidation events may occur\n' +
' - The reference price option defines the base price in calculating liquidation price levels'
refPL = input.string("open", "Reference Price", options = ["open", "close", "oc2", "hl2", "hlc3", "ohlc4", "hlcc4"], tooltip = rpTT)
vlTT = 'Liquidation data is closely tied in with trading volumes in the market and the movement in the underlying asset’s price\n' +
' - The volume threshold option is the primary factor in detecting the significant trading activities that could potentially lead to liquidating leveraged positions\n' +
' - The volatility threshold option (below) is the secondary factor that aims at detecting significant movement in the underlying asset’s price with relatively lower trading activities that could potentially also lead to liquidating high-leveraged positions'
vbHT = input.float(1.7, 'Volume Threshold', minval = 1., step = .1, tooltip = vlTT)
lqTH = input.int(10, 'Volatility Threshold', minval = 0, step = 5)
lqL1 = input.bool(true, 'Leverage', inline = 'L1')
lgL1V = input.int(25, '', minval = 1, inline = 'L1')
lqL1L = input.color(color.new(#5b9cf6, 50), '', inline = 'L1')
lqL1S = input.color(color.new(#f06292, 50), '', inline = 'L1')
lqL2 = input.bool(true, 'Leverage', inline = 'L2')
lgL2V = input.int(50, '', minval = 1, inline = 'L2')
lqL2L = input.color(color.new(#4dd0e1, 50), '', inline = 'L2')
lqL2S = input.color(color.new(#ba68c8, 50), '', inline = 'L2')
lqL3 = input.bool(true, 'Leverage', inline = 'L3')
lgL3V = input.int(100, '', minval = 1, inline = 'L3')
lqL3L = input.color(color.new(#42bda8, 50), '', inline = 'L3')
lqL3S = input.color(color.new(#9575cd, 50), '', inline = 'L3')
lqBB = input.bool(false, 'Hide Liquidation Bubbles')
lqLN = input.bool(false, 'Hide Liquidation Levels')
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field v (float) volume of the bar
// @field i (int) index of the bar
type bar
float h = high
float l = low
float v = volume
int i = bar_index
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
var aLQ = array.new_line()
nzV = nz(b.v)
//-----------------------------------------------------------------------------}
// Functions/methods
//-----------------------------------------------------------------------------{
// @function This function converts string to source
//
// @param _s [string] source custom sting
//
// @returns [float] source
f_gSRC(_s) =>
switch _s
"open" => open
"close" => close
"hl2" => hl2
"oc2" => math.avg(open, close)
"hlc3" => hlc3
"ohlc4" => ohlc4
"hlcc4" => hlcc4
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
refP = f_gSRC(refPL)
vbMA = ta.sma(nzV, 13)
nzVd2 = nzV > vbMA * (2 + vbHT)
nzVd1 = nzV > vbMA * (1 + vbHT)
nzVd0 = nzV > vbMA * (0 + vbHT)
lT = (b.l != refP and refP / (refP - b.l) <= lqTH) or (b.h != refP and refP / (b.h - refP) <= lqTH)
eC = refP * (1 + 1. / 333) < b.h or refP * (1 - 1. / 333) > b.l
l1PL = refP * (1 + 1. / lgL1V)
plotshape(not lqBB and lqL1 and nzVd2 and eC ? l1PL : na, 'Bubbles', shape.circle, location.absolute, lqL1L, editable = false, size = size.normal)
plotshape(not lqBB and lqL1 and nzVd1 and eC ? l1PL : na, 'Bubbles', shape.circle, location.absolute, lqL1L, editable = false, size = size.small)
plotshape(not lqBB and lqL1 and nzVd0 and eC ? l1PL : not lqBB and lqL1 and lT ? l1PL : na, 'Bubbles', shape.circle, location.absolute, lqL1L, editable = false, size = size.tiny)
if not lqLN and lqL1 and (lT or nzVd0) and l1PL > b.h and eC
aLQ.push(line.new(b.i, l1PL, b.i + 1, l1PL, color = lqL1L, width = nzVd2 ? 3 : nzVd1 ? 2 : 1))
l1PS = refP * (1 - 1. / lgL1V)
plotshape(not lqBB and lqL1 and nzVd0 and eC ? l1PS : not lqBB and lqL1 and lT ? l1PS : na, 'Bubbles', shape.circle, location.absolute, lqL1S, editable = false, size = size.tiny)
plotshape(not lqBB and lqL1 and nzVd1 and eC ? l1PS : na, 'Bubbles', shape.circle, location.absolute, lqL1S, editable = false, size = size.small)
plotshape(not lqBB and lqL1 and nzVd2 and eC ? l1PS : na, 'Bubbles', shape.circle, location.absolute, lqL1S, editable = false, size = size.normal)
if not lqLN and lqL1 and (lT or nzVd0) and l1PS < b.l and eC
aLQ.push(line.new(b.i, l1PS, b.i + 1, l1PS, color = lqL1S, width = nzVd2 ? 3 : nzVd1 ? 2 : 1))
l2PL = refP * (1 + 1. / lgL2V)
plotshape(not lqBB and lqL2 and nzVd2 and eC ? l2PL : na, 'Bubbles', shape.circle, location.absolute, lqL2L, editable = false, size = size.normal)
plotshape(not lqBB and lqL2 and nzVd1 and eC ? l2PL : na, 'Bubbles', shape.circle, location.absolute, lqL2L, editable = false, size = size.small)
plotshape(not lqBB and lqL2 and nzVd0 and eC ? l2PL : not lqBB and lqL2 and lT ? l2PL : na, 'Bubbles', shape.circle, location.absolute, lqL2L, editable = false, size = size.tiny)
if not lqLN and lqL2 and (lT or nzVd0) and l2PL > b.h and eC
aLQ.push(line.new(b.i, l2PL, b.i + 1, l2PL, color = lqL2L, width = nzVd2 ? 3 : nzVd1 ? 2 : 1))
l2PS = refP * (1 - 1. / lgL2V)
plotshape(not lqBB and lqL2 and nzVd0 and eC ? l2PS : not lqBB and lqL2 and lT ? l2PS : na, 'Bubbles', shape.circle, location.absolute, lqL2S, editable = false, size = size.tiny)
plotshape(not lqBB and lqL2 and nzVd1 and eC ? l2PS : na, 'Bubbles', shape.circle, location.absolute, lqL2S, editable = false, size = size.small)
plotshape(not lqBB and lqL2 and nzVd2 and eC ? l2PS : na, 'Bubbles', shape.circle, location.absolute, lqL2S, editable = false, size = size.normal)
if not lqLN and lqL2 and (lT or nzVd0) and l2PS < b.l and eC
aLQ.push(line.new(b.i, l2PS, b.i + 1, l2PS, color = lqL2S, width = nzVd2 ? 3 : nzVd1 ? 2 : 1))
l3PL = refP * (1 + 1. / lgL3V)
plotshape(not lqBB and lqL3 and nzVd2 and eC ? l3PL : na, 'Bubbles', shape.circle, location.absolute, lqL3L, editable = false, size = size.normal)
plotshape(not lqBB and lqL3 and nzVd1 and eC ? l3PL : na, 'Bubbles', shape.circle, location.absolute, lqL3L, editable = false, size = size.small)
plotshape(not lqBB and lqL3 and nzVd0 and eC ? l3PL : not lqBB and lqL3 and lT ? l3PL : na, 'Bubbles', shape.circle, location.absolute, lqL3L, editable = false, size = size.tiny)
if not lqLN and lqL3 and (lT or nzVd0) and l3PL > b.h and eC
aLQ.push(line.new(b.i, l3PL, b.i + 1, l3PL, color = lqL3L, width = nzVd2 ? 3 : nzVd1 ? 2 : 1))
l3PS = refP * (1 - 1. / lgL3V)
plotshape(not lqBB and lqL3 and nzVd0 and eC ? l3PS : not lqBB and lqL3 and lT ? l3PS : na, 'Bubbles', shape.circle, location.absolute, lqL3S, editable = false, size = size.tiny)
plotshape(not lqBB and lqL3 and nzVd1 and eC ? l3PS : na, 'Bubbles', shape.circle, location.absolute, lqL3S, editable = false, size = size.small)
plotshape(not lqBB and lqL3 and nzVd2 and eC ? l3PS : na, 'Bubbles', shape.circle, location.absolute, lqL3S, editable = false, size = size.normal)
if not lqLN and lqL3 and (lT or nzVd0) and l3PS < b.l and eC
aLQ.push(line.new(b.i, l3PS, b.i + 1, l3PS, color = lqL3S, width = nzVd2 ? 3 : nzVd1 ? 2 : 1))
if aLQ.size() > 0
qt = aLQ.size()
for ln = qt - 1 to 0
if ln < aLQ.size()
cL = aLQ.get(ln)
yL = cL.get_y1()
if b.h > yL and b.l < yL
aLQ.remove(ln)
else
cL.set_x2(b.i + 1)
if aLQ.size() > 500
aLQ.shift().delete()
//-----------------------------------------------------------------------------} |
Liquidations Meter [LuxAlgo] | https://www.tradingview.com/script/RPkiBrW7-Liquidations-Meter-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 979 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator('Liquidations Meter [LuxAlgo]', 'LuxAlgo - Liquidations Meter', true)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
clGR = 'Liquidation Price Calculator'
lmTT = 'Presents liquidations on the price chart by measuring the highest leverage value of longs and shorts that have been potentially liquidated on the last chart bar.\n\n' +
'Liquidations meter allows traders to\n -gauge the momentum of the bar,\n -identify the strength of the bulls and bears, and\n -identify probable reversal/exhaustion points\n\n' +
'Here with liquidations, we refer to the process of forcibly closing a trader\'s position in the market'
lmSH = input.bool(true, 'Liquidations Meter', group = 'Liquidations Meter', tooltip = lmTT)
refPS = input.string("open", "Base Price", options = ["open", "close", "oc2", "hl2", "ooc3", "occ3", "hlc3", "ohlc4", "hlcc4"], group = 'Liquidations Meter')
clTT = 'The liquidation price calculator is useful for leverage trading traders who want to know how much risk they can take for each trade.\n\n' +
'This tool uses a formula to calculate the liquidation price based on the entry price + leverage ratio.\n\n' +
'Other factors such as leveraged fees, position size, and other interest payments have been excluded since they are variables that don’t directly affect the level of liquidation of a leveraged position.\n\n' +
'This calculator also assumes that traders are using an isolated margin for one single position and does not take into consideration the additional margin they might have in their account.'
clSH = input.bool(true, 'Liquidation Price Calculator', group = clGR, tooltip = clTT)
epTT = 'Defines the entry price.\nIf the entry price is set to 0, then the selected \'Base Price\' value is assumed as entry price\n\n' +
'Tip: Before entering a trade, setting base price to \'close\' and entry price to remain at 0 will allow the traders to easily evaluate the risk and reward situation of any given setup'
clEP = input.float(0., 'Entry Price', group = clGR, tooltip = epTT)
lrTT = 'Leverage allows traders to borrow funds in order to enter a position larger than their own funds permit\n\n' +
'the higher the leverage ratio the higher the risk.\n\nIt is important to be aware that when the leverage ratio is increased, the liquidation price moves closer to the entry price, meaning a higher risk trader\'s position will have'
clLR = input.float(10., 'Leverage', minval = 0, group = clGR, tooltip = lrTT)
lpSH = input.bool(true, 'Show Calculated Liquidation Prices on the Chart', group = clGR)
dbTT = 'The bar statistics option enables measuring and presenting trading activity, volatility, and probable liquidations for the last chart bar'
dbSH = input.bool(true, 'Show Bar Statistics', group = 'Dashboard', tooltip = dbTT)
lcLS = input.string('Small', 'Liquidations Meter Text Size', options = ['Tiny', 'Small', 'Normal'], group = 'Others')
lcOF = input.int(3, 'Liquidations Meter Offset', minval = 0, group = 'Others')
clPS = input.string('Bottom', 'Dashboard/Calculator Placement', options=['Top', 'Middle', 'Bottom'], group = 'Others')
lcDS = input.string('Small', 'Dashboard/Calculator Text Size', options = ['Tiny', 'Small', 'Normal'], group = 'Others')
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field o (float) open price of the bar
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field i (int) index of the bar
type bar
float o = open
float h = high
float l = low
float c = close
float v = volume
int i = bar_index
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
var label lbL = na, label.delete(lbL[1])
var label lbS = na, label.delete(lbS[1])
var line lnL = na, line.delete(lnL[1])
var line lnS = na, line.delete(lnS[1])
var aLQ = array.new_box()
var aCL = array.new_box()
vST = ''
//-----------------------------------------------------------------------------}
// Functions/methods
//-----------------------------------------------------------------------------{
// @function converts simple text to formated text
//
// @param _s [string] simple string
//
// @returns enumarated text size value
f_gSZ(_s) =>
switch _s
'Tiny' => size.tiny
'Small' => size.small
=> size.normal
// @function compares the source value with the reference value
//
// @param _s [float] source
// @param _r [float] reference
// @param _m [float] multiplier
//
// @returns [string] result of the comparison
f_gST(_s, _r, _m) =>
if _s
isS = _s >= 4.669 * _r * _m
isH = _s >= 1.618 * _r * _m
isL = _s <= 0.618 * _r * _m
isS ? 'Very High' : isH ? 'High' : isL ? 'Low' : 'Average'
// @function converts simple text to source
//
// @param _s [string] simple string
//
// @returns [float] source series
f_gSRC(_s) =>
switch _s
"open" => open
"close" => close
"oc2" => math.avg(open, close)
"hl2" => hl2
"ooc3" => math.avg(open, open , close)
"occ3" => math.avg(open, close, close)
"hlc3" => hlc3
"ohlc4" => ohlc4
"hlcc4" => hlcc4
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
nzV = nz(b.v)
vDB = f_gST(nzV, ta.sma(nzV, 13), 1.1)
vST += '\n\nLast Bar Statistics:\n Trading activity : ' + vDB
aDB = f_gST(b.h - b.l, ta.atr(13), 0.9)
vST += '\n Volatility : ' + aDB
LQ = nzV / (b.o / (b.o - b.l)) + nzV / (math.avg(b.o, b.c) / (b.h - math.avg(b.o, b.c)))
lDB = f_gST(LQ, ta.sma(LQ, 89), 1.9)
vST += '\n Liquidations : ' + lDB
lSZ = f_gSZ(lcLS)
refP = f_gSRC(refPS)
if lmSH and barstate.islast
if aLQ.size() > 0
for i = 1 to aLQ.size()
box.delete(aLQ.shift())
off = lpSH ? 7 : 0
if (refP - b.l) > 0
aLQ.push(box.new(b.i + lcOF + off, refP, b.i + lcOF + off + 2, refP * (1 - 1. / 100), border_color = color(na), bgcolor = color.new(color.teal, 89), text = '100x', text_color = chart.fg_color, text_valign = text.align_bottom))
if (b.h - refP) > 0
aLQ.push(box.new(b.i + lcOF + off, refP, b.i + lcOF + off + 2, refP * (1 + 1. / 100), border_color = color(na), bgcolor = color.new(color.red, 89), text = '100x', text_color = chart.fg_color, text_valign = text.align_top))
lev = array.from(100, 50, 25, 10, 5, 3, 2, 1)
trans = array.from( 89, 76, 63, 50, 37, 24, 11, 1)
for i = 1 to 7
if (refP - b.l) > 0 and refP / (refP - b.l) < lev.get(i - 1)
aLQ.push(box.new(b.i + lcOF + off, refP * (1 - 1. / lev.get(i - 1)), b.i + lcOF + off + 2, refP * (1 - 1. / lev.get(i)), border_color = color(na),
bgcolor = color.new(color.teal, trans.get(i)), text = str.tostring(lev.get(i)) + 'x', text_color = chart.fg_color, text_valign = text.align_bottom))
if (b.h - refP) > 0 and refP / (b.h - refP) < lev.get(i - 1)
aLQ.push(box.new(b.i + lcOF + off, refP * (1 + 1. / lev.get(i - 1)), b.i + lcOF + off + 2, refP * (1 + 1. / lev.get(i)), border_color = color(na),
bgcolor = color.new(color.red, trans.get(i)), text = str.tostring(lev.get(i)) + 'x', text_color = chart.fg_color, text_valign = text.align_top))
if refP / (refP - b.l) <= 100 and (refP - b.l) > 0
lbL := label.new(b.i + lcOF + off + 1, b.l, '◄ ' + str.tostring(refP / (refP - b.l), '#.#') + 'x Longs Liquidated' ,
color = color(na), textcolor = chart.fg_color, size = lSZ, style = label.style_label_left,
tooltip = 'The highest leverage of\n probable liquidated longs : ' + str.tostring(refP / (refP - b.l), '#.##') + 'x\nEstimantion based on\n reference price : ' + str.tostring(refP, format.mintick) + vST)
lnL := line.new(b.i + lcOF + off, b.l, b.i + lcOF + off + 2, b.l, color = chart.fg_color, style = line.style_dotted)
if refP / (b.h - refP) <= 100 and (b.h - refP) > 0
lbS := label.new(b.i + lcOF + off + 1, b.h, '◄ ' + str.tostring(refP / (b.h - refP), '#.#') + 'x Shorts Liquidated',
color = color(na), textcolor = chart.fg_color, size = lSZ, style = label.style_label_left,
tooltip = 'The highest leverage of\n probable liquidated shorts : ' + str.tostring(refP / (b.h - refP), '#.##') + 'x\nEstimantion based on\n reference price : ' + str.tostring(refP, format.mintick) + vST)
lnS := line.new(b.i + lcOF + off, b.h, b.i + lcOF + off + 2, b.h, color = chart.fg_color, style = line.style_dotted)
tPOS = switch clPS
'Top' => position.top_right
'Middle' => position.middle_right
'Bottom' => position.bottom_right
tSZ = f_gSZ(lcDS)
refP := clEP == 0 ? refP : clEP
var table calc = table.new(tPOS, 3, 18, bgcolor = #1e222d, border_color = #515359, border_width = 1, frame_color = #373a46, frame_width = 1)
if barstate.islast
if dbSH
table.cell(calc, 0, 0, "BAR STATISTICS\n", text_color = color.white, text_size = tSZ, bgcolor = #2962FF)
table.merge_cells(calc, 0, 0, 2, 0)
table.cell(calc, 0, 2, "Volatility", text_color = color.white, text_size = tSZ, text_halign = text.align_left)
table.merge_cells(calc, 0, 2, 1, 2)
table.cell(calc, 2, 2, aDB, text_color = color.white, text_size = tSZ)
if nzV > 0
table.cell(calc, 0, 1, "Activity", text_color = color.white, text_size = tSZ, text_halign = text.align_left)
table.merge_cells(calc, 0, 1, 1, 1)
table.cell(calc, 2, 1, vDB, text_color = color.white, text_size = tSZ)
table.cell(calc, 0, 3, "Liquidations", text_color = color.white, text_size = tSZ, text_halign = text.align_left)
table.merge_cells(calc, 0, 3, 1, 3)
table.cell(calc, 2, 3, lDB + ' !', text_color = color.white, text_size = tSZ,
tooltip = 'The highest leverage of\n probable liquidated shorts : ' + (refP / (b.h - refP) > 100 ? '>100' : str.tostring(refP / (b.h - refP), '#.##')) +
'x\n probable liquidated longs : ' + (refP / (refP - b.l) > 100 ? '>100' : str.tostring(refP / (refP - b.l), '#.##')) +
'x\n\nEstimantion based on\n reference price : ' + str.tostring(refP, format.mintick))
if clSH
table.cell(calc, 0, 4, "CALCULATOR\n", text_color = color.white, text_size = tSZ, bgcolor = #2962FF)
table.merge_cells(calc, 0, 4, 2, 4)
table.cell(calc, 0, 5, "Entry Price ", text_color = color.white, text_size = tSZ)
table.merge_cells(calc, 0, 5, 1, 5)
table.cell(calc, 2, 5, "Leverage", text_color = color.white, text_size = tSZ)
table.cell(calc, 0, 6, str.tostring(refP, format.mintick), text_color = color.white, text_size = tSZ)
table.merge_cells(calc, 0, 6, 1, 6)
table.cell(calc, 2, 6, str.tostring(clLR), text_color = color.white, text_size = tSZ)
tip = 'Liquidation price is the distance from trader\'s entry price to the price where trader\'s leveraged position gets liquidated due to a loss.\n\n' +
'If a trader wants to enter a $1.000 trade with ' + str.tostring(clLR) + 'x leverage, then $' + str.tostring(1000/clLR, '#.##') +
' is the initial margin (the amount of money coming from the traders pocket) and the remaining $' + str.tostring(1000 - 1000/clLR, '#.##') + ' are borrowed funds\n\n' +
'When a trader\'s account falls below the required margin level, exchanges or brokerage platforms cannot allow a trader to lose borrowed funds and therefore the trader\'s positions will be forcibly closed as soon as position losses reach the initial margin.\n\n' +
'The liquidation prices presented below are approximate values of both long and short liquidation prices. It is important to note that the exchanges will taken into consideration the trader\'s open positions when calculating the liquidation price. Unrealized PNL and maintenance margin of the trader\'s open position will affect the calculation of liquidation price'
table.cell(calc, 0, 14, 'Liquidation Prices !', text_color = color.white, text_size = tSZ, tooltip = tip)
table.merge_cells(calc, 0, 14, 2, 14)
table.cell(calc, 0, 15, "█", text_color = color.teal, text_size = tSZ)
table.cell(calc, 1, 15, "Longs", text_color = color.white, text_size = tSZ, text_halign = text.align_left)
table.cell(calc, 2, 15, '≅ ' + str.tostring(refP * (1 - 1. / clLR), format.mintick) + ' (↓%' + str.tostring(100. / clLR, '#.##') + ')',
text_color = color.white, text_size = tSZ)
table.cell(calc, 0, 16, "█", text_color = color.red, text_size = tSZ)
table.cell(calc, 1, 16, "Shorts", text_color = color.white, text_size = tSZ, text_halign = text.align_left)
table.cell(calc, 2, 16, '≅ ' + str.tostring(refP * (1 + 1. / clLR), format.mintick) + ' (↑%' + str.tostring(100. / clLR, '#.##') + ')',
text_color = color.white, text_size = tSZ)
if lpSH
if aCL.size() > 0
for i = 1 to aCL.size()
box.delete(aCL.shift())
lLP = refP * (1 - 1. / clLR)
sLP = refP * (1 + 1. / clLR)
aCL.push(box.new(b.i, lLP, b.i + lcOF + 6, lLP, border_color = color.teal,
text = 'Long Liquidation Price Level\n' + (b.l < lLP ? 'trade liquidated' : '%' + str.tostring((math.abs(lLP / b.c - 1) * 100), '#.##') + ' (' + str.tostring(b.c - lLP, format.mintick) + ') to liquidation'),
text_size = size.small, text_halign = text.align_right, text_valign = text.align_top, text_color = color.teal))
aCL.push(box.new(b.i + 2, refP, b.i + lcOF + 4, refP, border_color = color.gray))
aCL.push(box.new(b.i, sLP, b.i + lcOF + 6, sLP, border_color = color.red,
text = 'Short Liquidation Price Level\n' + (b.h > sLP ? 'trade liquidated' : '%' + str.tostring((math.abs(sLP / b.c - 1) * 100), '#.##') + ' (' + str.tostring(sLP - b.c, format.mintick) + ') to liquidation'),
text_size = size.small, text_halign = text.align_right, text_valign = text.align_bottom, text_color = color.red))
//-----------------------------------------------------------------------------} |
Margin/Leverage Calculation | https://www.tradingview.com/script/Zs2YSdd8-Margin-Leverage-Calculation/ | DinGrogu | https://www.tradingview.com/u/DinGrogu/ | 1 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DinGrogu
//@version=5
library('margin')
// ############################################################
// # FUNCTIONS
// ############################################################
f_liquidation(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount, string _direction) =>
contract_qty = (_investment_capital / _price)
leveraged_balance = math.abs(contract_qty) * _price / (_leverage + 1)
maintainance_rate = _direction == 'LONG' ? (_maintenance_rate - 1) : (_maintenance_rate + 1)
total_balance = (leveraged_balance + _maintenance_amount)
total_quantity = (contract_qty * _price)
total_price = _direction == 'LONG' ? (total_balance - total_quantity) : (total_balance + total_quantity)
liquidation_price = math.round_to_mintick(total_price) / (math.abs(contract_qty) * maintainance_rate)
qty = liquidation_price * math.abs(contract_qty)
[liquidation_price, qty]
f_strategy_order_size() =>
if (strategy.closedtrades > 0)
order_size = strategy.initial_capital / strategy.closedtrades.entry_price(0)
math.round(strategy.closedtrades.size(0) / order_size, 2) * 100
else
order_size = 100
f_strategy_leverage() =>
response = int(f_strategy_order_size() / 100)
// ############################################################
// # EXPORT FUNCTIONS
// ############################################################
// function - Calculate the liquidation price.
// @param _investment_capital <float> - The source input.
// @param _price <float> - The price to calculate the liquidation level.
// @param _leverage <int> - The leverage used on the investment.
// @param _maintenance_rate <int> - The Maintenance Rate.
// @param _maintenance_amount <int> - The Maintenance Amount.
// @param _direction <string> - The direction (long or short).
export liquidation(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount, string _direction) =>
f_liquidation(_investment_capital, _price, _leverage, _maintenance_rate, _maintenance_amount, _direction)
// function - Shortcut for the long liquidation price and qty based on leverage.
export liquidation_long(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount) =>
f_liquidation(_investment_capital, _price, _leverage, _maintenance_rate, _maintenance_amount, 'LONG')
// function - Shortcut for the short liquidation price and qty based on leverage.
export liquidation_short(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount) =>
f_liquidation(_investment_capital, _price, _leverage, _maintenance_rate, _maintenance_amount, 'SHORT')
// function - Shortcut for the long liquidation price based on leverage.
export liquidation_price_long(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount) =>
[price, qty] = f_liquidation(_investment_capital, _price, _leverage, _maintenance_rate, _maintenance_amount, 'LONG')
response = price
// function - Shortcut for the short liquidation price based on leverage.
export liquidation_price_short(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount) =>
[price, qty] = f_liquidation(_investment_capital, _price, _leverage, _maintenance_rate, _maintenance_amount, 'SHORT')
response = price
// function - Shortcut for the long liquidation qty based on leverage.
export qty_long(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount) =>
[price, qty] = f_liquidation(_investment_capital, _price, _leverage, _maintenance_rate, _maintenance_amount, 'LONG')
response = qty
// function - Shortcut for the short liquidation qty based on leverage.
export qty_short(float _investment_capital, float _price, int _leverage, float _maintenance_rate, float _maintenance_amount) =>
[price, qty] = f_liquidation(_investment_capital, _price, _leverage, _maintenance_rate, _maintenance_amount, 'SHORT')
response = qty
// Function to get the order size from the properties tab.
export order_size() =>
response = f_strategy_order_size()
// Function to calculate the leverage from the order size (200% = 2x leverage)
export leverage() =>
response = f_strategy_leverage()
|
Absorbing System Support and Resistance | https://www.tradingview.com/script/rttbMbbt/ | only_fibonacci | https://www.tradingview.com/u/only_fibonacci/ | 1,004 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © only_fibonacci
//@version=5
indicator("Absorbing System", overlay = true, max_bars_back = 2000)
pivotLen = input.int(defval = 10, title = "PivotLEN", minval = 5, maxval = 10)
showBreakDown = input.bool(defval = false, title = "Show Breakdown")
sensitive = input.bool(defval = false, title = "Sensitive Breakdown")
isBox = input.bool( defval = false, title = "BOX ?", tooltip = "If box is right, line is closed")
ph = ta.pivothigh(pivotLen, pivotLen) == high[pivotLen]
pl = ta.pivotlow(pivotLen, pivotLen) == low[pivotLen]
varip indexes_r = array.new_int()
varip removed_r = array.new_int()
varip indexes_s = array.new_int()
varip removed_s = array.new_int()
// FUNC TRANSFORMATION
func(lineType)=>
wickRes = high - math.max(open,close)
wickSup = math.min(close,open) - low
body = math.abs(close - open)
isRes = wickRes > wickSup //and open > close
isSup = wickSup > wickRes
cond = lineType == "RES" ? isRes and wickRes > body : isSup and wickSup > body
resCond = lineType == "RES" ? ph and cond[pivotLen] : pl and cond[pivotLen]
res_index = ta.valuewhen(resCond, bar_index, 0) - pivotLen
brokenCond = lineType == "RES" ? ta.crossover(high, high[bar_index - res_index]) : ta.crossunder(low, low[bar_index - res_index])
indexes = lineType == "RES" ? indexes_r : indexes_s
removed = lineType == "RES" ? removed_r : removed_s
if resCond
array.push(indexes,bar_index - pivotLen)
if array.size(indexes) > 5
array.remove(indexes,0)
hORl = lineType == "RES" ? high : low
cORo = lineType == "RES" ? math.max(open,close) : math.min(open,close)
col = lineType == "RES" ? color.red : color.green
sens = sensitive ? hORl : lineType == "RES" ? math.max(close,open) : math.min(open,close)
if array.size(indexes) > 0
for i = 0 to array.size(indexes) - 1 by 1
index = array.get(indexes,i)
inCond = lineType == "RES" ? sens[1] <= hORl[bar_index - index] and sens > hORl[bar_index - index] : sens[1] >= hORl[bar_index - index] and sens < hORl[bar_index - index]
if inCond
if isBox
box.new(index, hORl[bar_index - index], bar_index, cORo[bar_index - index], bgcolor = color.new(col,80), border_color = color.new(col,80))
else
line.new(index, hORl[bar_index - index], bar_index, hORl[bar_index - index], color = col)
array.push(removed,index)
if showBreakDown
label.new(bar_index , sens[bar_index - index], text = "BREAKDOWN", color = color.new(col,80), style = lineType == "RES" ? label.style_label_up : label.style_label_down, textcolor = color.white)
if barstate.islast
for k = 0 to array.size(indexes) -1 by 1
indexk = array.get(indexes,k)
if isBox
box.new(indexk, hORl[bar_index - indexk], bar_index, cORo[bar_index - indexk], bgcolor = color.new(col,80), border_color = color.new(col,80))
else
line.new(indexk, hORl[bar_index - indexk], bar_index, hORl[bar_index - indexk], color = col)
if array.size(indexes) > 0 and array.size(removed) > 0
for x = 0 to array.size(removed) - 1 by 1
index_x = array.get(removed,x)
indexof_i = array.indexof(indexes,index_x)
if indexof_i >= 0
array.remove(indexes,indexof_i)
func("RES")
func("SUP")
|
Market Structure (Breakers) [LuxAlgo] | https://www.tradingview.com/script/cONRD5q4-Market-Structure-Breakers-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,254 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Market Structure (Breakers) [LuxAlgo]", overlay = true, max_lines_count = 500, max_labels_count = 500)
//-----------------------------------------------------------------------------}
//Settings
//-----------------------------------------------------------------------------{
length = input.int(20, 'Swings Period', minval = 2)
breaks = input.int(1, 'Maximum Breaks', minval = 1)
maxDuration = input(1000, 'Breaker Maximum Duration')
//Style
bullCss = input(#089981, 'Bullish MS', inline = 'bull', group = 'Style')
bullBreakCss = input(#f23645, 'Breaker', inline = 'bull', group = 'Style')
bearCss = input(#f23645, 'Bearish MS', inline = 'bear', group = 'Style')
bearBreakCss = input(#089981, 'Breaker', inline = 'bear', group = 'Style')
//-----------------------------------------------------------------------------}
//UDT
//-----------------------------------------------------------------------------{
type breaker
line level
int breaks = 0
//-----------------------------------------------------------------------------}
//Bullish Breaker
//-----------------------------------------------------------------------------{
var phx = 0
var phcross = false
var bullms = array.new<breaker>(0)
var os = 0
n = bar_index
ph = fixnan(ta.pivothigh(length, length))
if ph != ph[1]
phx := n-length
phcross := false
//Test for bullish market structure
if close > ph and not phcross
line.new(phx, ph, n, ph, color = bullCss)
//MS label
label.new(int(math.avg(phx, n)), ph, os == -1 ? 'MSS' : 'MSB'
, textcolor = bullCss
, color = color(na)
, size = size.small
, style = label.style_label_down)
bullms.unshift(breaker.new(line.new(n, ph, n, ph, color = bullBreakCss, style = line.style_dotted)))
phcross := true
if bullms.size() > 100
bullms.pop()
os := 1
//Iterate trough existing bullish structures and test for breaks
break_down = false
if bullms.size() > 0
for i = bullms.size()-1 to 0
get = bullms.get(i)
get.level.set_x2(n)
if close < get.level.get_y2() and open > get.level.get_y2()
get.breaks += 1
if get.breaks == breaks
bullms.remove(i)
break_down := true
else if (n - get.level.get_x1()) >= maxDuration
bullms.remove(i).level.delete()
//Support events
support = false
if bullms.size() > 0
lvl = bullms.get(0).level.get_y2()
support := low < lvl and math.min(close, open) > lvl
//-----------------------------------------------------------------------------}
//Bearish Breaker
//-----------------------------------------------------------------------------{
var plx = 0
var plcross = false
var bearms = array.new<breaker>(0)
pl = fixnan(ta.pivotlow(length, length))
if pl != pl[1]
plx := n-length
plcross := false
//Test for bearish market structure
if close < pl and not plcross
line.new(plx, pl, n, pl, color = bearCss)
//MS label
label.new(int(math.avg(plx, n)), pl, os == 1 ? 'MSS' : 'MSB'
, textcolor = bearCss
, color = color(na)
, size = size.small
, style = label.style_label_up)
bearms.unshift(breaker.new(line.new(n, pl, n, pl, color = bearBreakCss, style = line.style_dotted)))
plcross := true
if bearms.size() > 100
bearms.pop()
os := -1
//Iterate trough existing bearish structures and test for breaks
break_up = false
if bearms.size() > 0
for i = bearms.size()-1 to 0
get = bearms.get(i)
get.level.set_x2(n)
if close > get.level.get_y2() and open < get.level.get_y2()
get.breaks += 1
if get.breaks == breaks
bearms.remove(i)
break_up := true
else if (n - get.level.get_x1()) >= maxDuration
bearms.remove(i).level.delete()
//Resistance events
resistance = false
if bearms.size() > 0
lvl = bearms.get(0).level.get_y2()
resistance := high > lvl and math.max(close, open) < lvl
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plotchar(break_up, 'Bull MSB Breakout', '▲', location.belowbar, #089981)
plotchar(break_down, 'Bear MSB Breakout', '▼', location.abovebar, #f23645)
//Support events
plotcandle(high, high, low, low
, 'Support Events'
, na
, na
, bordercolor = support ? #089981 : na
, display = display.all - display.status_line)
//Resistance events
plotcandle(high, high, low, low
, 'Resistance Events'
, na
, na
, bordercolor = resistance ? #f23645 : na
, display = display.all - display.status_line)
//-----------------------------------------------------------------------------} |
Liquidity Price Depth Chart [LuxAlgo] | https://www.tradingview.com/script/93TdE1fd-Liquidity-Price-Depth-Chart-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,068 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Liquidity Price Depth Chart [LuxAlgo]", "LuxAlgo - Liquidity Price Depth Chart", overlay = true, max_labels_count = 500)
//-----------------------------------------------------------------------------}
//Settings
//-----------------------------------------------------------------------------{
//Bullish Elements
showBullMax = input(true, 'Bullish Price Highest Volume Location', group = 'Bullish Elements')
showBullPer = input(true, 'Bullish Volume %', group = 'Bullish Elements')
bullCss = input(#089981, 'Bullish Prices', inline = 'bull', group = 'Bullish Elements')
bullFillCss = input(color.new(#089981, 90), 'Area', inline = 'bull', group = 'Bullish Elements')
//Bearish Elements
showBearMax = input(true, 'Bearish Price Highest Volume Location', group = 'Bearish Elements')
showBearPer = input(true, 'Bearish Volume %', group = 'Bearish Elements')
bearCss = input(#f23645, 'Bearish Prices', inline = 'bear', group = 'Bearish Elements')
bearFillCss = input(color.new(#f23645, 90), 'Area', inline = 'bear', group = 'Bearish Elements')
//Misc
padding = input.float(5, 'Volume % Box Padding', minval = 0, maxval = 100, group = 'Misc') / 100
//-----------------------------------------------------------------------------}
//Populate maps
//-----------------------------------------------------------------------------{
var int x1 = na
var float max = na, var float max_bull_vol = na
var float min = na, var float max_bear_vol = na
var max_bull_vlvl = line.new(na,na,na,na, color = bullCss, extend = extend.both, style = line.style_dotted)
var max_bear_vlvl = line.new(na,na,na,na, color = bearCss, extend = extend.both, style = line.style_dotted)
var bull_map = map.new<float, float>()
var bear_map = map.new<float, float>()
n = bar_index
if time == chart.left_visible_bar_time
x1 := n
max := high, max_bull_vol := close > open ? volume : 0.
min := low , max_bear_vol := close < open ? volume : 0.
//Populate price/volume map
if time <= chart.right_visible_bar_time and time >= chart.left_visible_bar_time
if close > open
bull_map.put(close, volume)
max_bull_vol := math.max(volume, max_bull_vol)
if max_bull_vol == volume and showBullMax
max_bull_vlvl.set_xy1(n, close + syminfo.mintick)
max_bull_vlvl.set_xy2(n, close - syminfo.mintick)
else if close < open
bear_map.put(close, volume)
max_bear_vol := math.max(volume, max_bear_vol)
if max_bear_vol == volume and showBearMax
max_bear_vlvl.set_xy1(n, close + syminfo.mintick)
max_bear_vlvl.set_xy2(n, close - syminfo.mintick)
//Get maximum/minimum wicks in visible range
max := math.max(high, max)
min := math.min(low, min)
//-----------------------------------------------------------------------------}
//Set cumulative areas
//-----------------------------------------------------------------------------{
if time == chart.right_visible_bar_time
//Sort bull map keys
bull_sorted = bull_map.keys()
bull_sorted.sort(order.descending)
//Sort bear map keys
bear_sorted = bear_map.keys()
bear_sorted.sort(order.descending)
//Get bullish/bearish volume sums
bull_sumv = bull_map.values().sum()
bear_sumv = bear_map.values().sum()
bull_idx = 0.
bear_idx = 0.
bull_coordinates = array.new<chart.point>(0)
bear_coordinates = array.new<chart.point>(0)
bull_coordinates.push(chart.point.from_index(x1, max))
bear_coordinates.push(chart.point.from_index(n, max))
//Cumulated bullish volume
for element in bull_sorted
bull_idx += bull_map.get(element) / bull_sumv
chart_point = chart.point.from_index(x1 + int(bull_idx * (n - x1) / 2), element)
if bull_map.get(element) == max_bull_vol and showBullMax
line.new(x1, element, n, element, color = bullCss, style = line.style_dotted)
bull_coordinates.push(chart_point)
//Point label
label.new(chart_point
, color = color(na)
, style = label.style_label_center
, text = '•'
, textcolor = bullCss)
//Cumulated bearish volume
for [index, element] in bear_sorted
bear_idx += bear_map.get(element) / bear_sumv
chart_point = chart.point.from_index(n - int(bear_idx * (n - x1) / 2), element)
if bear_map.get(element) == max_bear_vol and showBearMax
line.new(x1, element, n, element, color = bearCss, style = line.style_dotted)
bear_coordinates.push(chart_point)
//Point label
label.new(chart_point
, color = color(na)
, style = label.style_label_center
, text = '•'
, textcolor = bearCss)
//Set horizontal min line for valid fill
bull_coordinates.push(chart.point.from_index(x1 + (n - x1) / 2, min))
bull_coordinates.push(chart.point.from_index(x1, min))
bear_coordinates.push(chart.point.from_index(n - (n - x1) / 2, min))
bear_coordinates.push(chart.point.from_index(n, min))
//Create polylines
polyline.new(bull_coordinates, line_color = bullCss, fill_color = bullFillCss)
polyline.new(bear_coordinates, line_color = bearCss, fill_color = bearFillCss)
//Bull % Boxes
if showBullPer
bull_vper = bull_sumv / (bull_sumv + bear_sumv)
box.new(x1, min, x1 + (n - x1) / 2, min - padding * (max - min)
, bullCss
, bgcolor = na)
box.new(x1, min, x1 + int((n - x1) / 2 * bull_vper), min - padding * (max - min)
, na
, bgcolor = bullCss
, text_color = color.white
, text = str.tostring(bull_vper * 100, format.percent)
, text_size = size.small)
//Bear % Boxes
if showBearPer
bear_vper = bear_sumv / (bull_sumv + bear_sumv)
box.new(n - (n - x1) / 2, min, n, min - padding * (max - min)
, bearCss
, bgcolor = na)
box.new(n - int((n - x1) / 2 * bear_vper), min, n, min - padding * (max - min)
, na
, bgcolor = bearCss
, text_color = color.white
, text = str.tostring(bear_vper * 100, format.percent)
, text_size = size.small)
//-----------------------------------------------------------------------------} |
2 Moving Averages | Trend Following | https://www.tradingview.com/script/Ixc6wuA0-2-Moving-Averages-Trend-Following/ | sosacur01 | https://www.tradingview.com/u/sosacur01/ | 52 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sosacur01
//@version=5
strategy(title="2 MA | Trend Following", overlay=true, pyramiding=1, commission_type=strategy.commission.percent, commission_value=0.2, initial_capital=10000)
//==========================================
//BACKTEST RANGE
useDateFilter = input.bool(true, title="Filter Date Range of Backtest",
group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 jan 2000"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
backtestEndDate = input.time(timestamp("1 Jul 2100"),
title="End Date", group="Backtest Time Period",
tooltip="This end date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
inTradeWindow = not useDateFilter or (time >= backtestStartDate and
time < backtestEndDate)
if not inTradeWindow and inTradeWindow[1]
strategy.cancel_all()
strategy.close_all(comment="Date Range Exit")
//--------------------------------------
//LONG/SHORT POSITION ON/OFF INPUT
LongPositions = input.bool(title='On/Off Long Postion', defval=true, group="Long & Short Position")
ShortPositions = input.bool(title='On/Off Short Postion', defval=true, group="Long & Short Position")
//---------------------------------------
//SLOW MA INPUTS
averageType1 = input.string(defval="SMA", group="Slow MA Inputs", title="Slow MA Type", options=["SMA", "EMA", "WMA", "HMA", "RMA", "SWMA", "ALMA", "VWMA", "VWAP"])
averageLength1 = input.int(defval=160, group="Slow MA Inputs", title="Slow MA Length", minval=50)
averageSource1 = input(close, title="Slow MA Source", group="Slow MA Inputs")
//SLOW MA TYPE
MovAvgType1(averageType1, averageSource1, averageLength1) =>
switch str.upper(averageType1)
"SMA" => ta.sma(averageSource1, averageLength1)
"EMA" => ta.ema(averageSource1, averageLength1)
"WMA" => ta.wma(averageSource1, averageLength1)
"HMA" => ta.hma(averageSource1, averageLength1)
"RMA" => ta.rma(averageSource1, averageLength1)
"SWMA" => ta.swma(averageSource1)
"ALMA" => ta.alma(averageSource1, averageLength1, 0.85, 6)
"VWMA" => ta.vwma(averageSource1, averageLength1)
"VWAP" => ta.vwap(averageSource1)
=> runtime.error("Moving average type '" + averageType1 +
"' not found!"), na
//----------------------------------
//FAST MA INPUTS
averageType2 = input.string(defval="SMA", group="Fast MA Inputs", title="Fast MA Type", options=["SMA","EMA","WMA","HMA","RMA","SWMA","ALMA","VWMA","VWAP"])
averageLength2 = input.int(defval=40, group="Fast MA Inputs", title="Fast MA Length", maxval=40)
averageSource2 = input(close, title="Fast MA Source", group="Fast MA Inputs")
//FAST MA TYPE
MovAvgType2(averageType2, averageSource2, averageLength2) =>
switch str.upper(averageType2)
"SMA" => ta.sma(averageSource2, averageLength2)
"EMA" => ta.ema(averageSource2, averageLength2)
"WMA" => ta.wma(averageSource2, averageLength2)
"HMA" => ta.hma(averageSource2, averageLength2)
"RMA" => ta.rma(averageSource2, averageLength2)
"SWMA" => ta.swma(averageSource2)
"ALMA" => ta.alma(averageSource2, averageLength2, 0.85, 6)
"VWMA" => ta.vwma(averageSource2, averageLength2)
"VWAP" => ta.vwap(averageSource2)
=> runtime.error("Moving average type '" + averageType2 +
"' not found!"), na
//---------------------------------------------------
//MA VALUES
FASTMA = MovAvgType2(averageType2, averageSource2, averageLength2)
SLOWMA = MovAvgType1(averageType1, averageSource1, averageLength1)
//BUY/SELL TRIGGERS
bullish_trend = FASTMA > SLOWMA and close > FASTMA
bearish_trend = FASTMA < SLOWMA and close < FASTMA
//MAs PLOT
plot1 = plot(SLOWMA,color=color.gray, linewidth=1, title="Slow-MA")
plot2 = plot(FASTMA,color=color.yellow, linewidth=1, title="Fast-MA")
fill(plot1, plot2, color=SLOWMA>FASTMA ? color.new(color.red, 70) : color.new(color.green, 70), title="EMA Clouds")
//-----------------------------------------------------
//PARABOLIC SAR USER INPUT
usepsarFilter = input.bool(title='Use Parabolic Sar?', defval=true, group = "Parabolic SAR Inputs")
psar_display = input.bool(title="Display Parabolic Sar?", defval=false, group="Parabolic SAR Inputs")
start = input.float(title="Start", defval=0.02, group="Parabolic SAR Inputs", step=0.001)
increment = input.float(title="Increment", defval=0.02, group="Parabolic SAR Inputs", step=0.001)
maximum = input.float(title="Maximum", defval=0.2, group="Parabolic SAR Inputs", step=0.001)
//SAR VALUES
psar = request.security(syminfo.tickerid, "D", ta.sar(start, increment, maximum))
//BULLISH & BEARISH PSAR CONDITIONS
bullish_psar = (usepsarFilter ? low > psar : bullish_trend )
bearsish_psar = (usepsarFilter ? high < psar : bearish_trend)
//SAR PLOT
psar_plot = if low > psar
color.rgb(198, 234, 199, 13)
else
color.rgb(219, 134, 134, 48)
plot(psar_display ? psar : na, color=psar_plot, title="Par SAR")
//-------------------------------------
//ENTRIES AND EXITS
long_entry = if inTradeWindow and bullish_trend and bullish_psar and LongPositions
true
long_exit = if inTradeWindow and bearish_trend
true
short_entry = if inTradeWindow and bearish_trend and bearsish_psar and ShortPositions
true
short_exit = if inTradeWindow and bullish_trend
true
//--------------------------------------
//RISK MANAGEMENT - SL, MONEY AT RISK, POSITION SIZING
atrPeriod = input.int(14, "ATR Length", group="Risk Management Inputs")
sl_atr_multiplier = input.float(title="Long Position - Stop Loss - ATR Multiplier", defval=2, group="Risk Management Inputs", step=0.5)
sl_atr_multiplier_short = input.float(title="Short Position - Stop Loss - ATR Multiplier", defval=2, group="Risk Management Inputs", step=0.5)
i_pctStop = input.float(2, title="% of Equity at Risk", step=.5, group="Risk Management Inputs")/100
//ATR VALUE
_atr = ta.atr(atrPeriod)
//CALCULATE LAST ENTRY PRICE
lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
//STOP LOSS - LONG POSITIONS
var float sl = na
//CALCULTE SL WITH ATR AT ENTRY PRICE - LONG POSITION
if (strategy.position_size[1] != strategy.position_size)
sl := lastEntryPrice - (_atr * sl_atr_multiplier)
//IN TRADE - LONG POSITIONS
inTrade = strategy.position_size > 0
//PLOT SL - LONG POSITIONS
plot(inTrade ? sl : na, color=color.blue, style=plot.style_circles, title="Long Position - Stop Loss")
//CALCULATE ORDER SIZE - LONG POSITIONS
positionSize = (strategy.equity * i_pctStop) / (_atr * sl_atr_multiplier)
//============================================================================================
//STOP LOSS - SHORT POSITIONS
var float sl_short = na
//CALCULTE SL WITH ATR AT ENTRY PRICE - SHORT POSITIONS
if (strategy.position_size[1] != strategy.position_size)
sl_short := lastEntryPrice + (_atr * sl_atr_multiplier_short)
//IN TRADE SHORT POSITIONS
inTrade_short = strategy.position_size < 0
//PLOT SL - SHORT POSITIONS
plot(inTrade_short ? sl_short : na, color=color.red, style=plot.style_circles, title="Short Position - Stop Loss")
//CALCULATE ORDER - SHORT POSITIONS
positionSize_short = (strategy.equity * i_pctStop) / (_atr * sl_atr_multiplier_short)
//===============================================
//LONG STRATEGY
strategy.entry("Long", strategy.long, comment="Long", when = long_entry, qty=positionSize)
if (strategy.position_size > 0)
strategy.close("Long", when = (long_exit), comment="Close Long")
strategy.exit("Long", stop = sl, comment="Exit Long")
//SHORT STRATEGY
strategy.entry("Short", strategy.short, comment="Short", when = short_entry, qty=positionSize_short)
if (strategy.position_size < 0)
strategy.close("Short", when = (short_exit), comment="Close Short")
strategy.exit("Short", stop = sl_short, comment="Exit Short")
//ONE DIRECTION TRADING COMMAND (BELLOW ONLY ACTIVATE TO CORRECT BUGS)
|
MA Sabres [LuxAlgo] | https://www.tradingview.com/script/viwa6CR8-MA-Sabres-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,462 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator('MA Sabres [LuxAlgo]', shorttitle='LuxAlgo - MA Sabres', max_polylines_count=100, overlay=true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
type = input.string( "TEMA" , 'MA Type' , group= 'MA'
, options = ["SMA", "EMA", "SMMA (RMA)", "HullMA", "WMA", "VWMA", "DEMA", "TEMA", "NONE"])
len = input.int ( 50 , 'Length' , group= 'MA' )
count = input.int ( 20 , 'Previous Trend Duration' , group= 'MA'
, tooltip = 'Reversal after x bars in the same direction' )
colUp = input.color (#2962ff, 'Bullish' , group='Colours')
colDn = input.color (#f23645, 'Bearish' , group='Colours')
colMa = input.color (#787b86, 'MA' , group='Colours')
//-----------------------------------------------------------------------------}
//Method MA
//-----------------------------------------------------------------------------{
method ma(string type, int length) =>
//
ema1 = ta.ema(close, length)
ema2 = ta.ema(ema1 , length)
ema3 = ta.ema(ema2 , length)
//
switch type
"SMA" => ta.sma (close, length)
"EMA" => ema1
"SMMA (RMA)" => ta.rma (close, length)
"HullMA" => ta.hma (close, length)
"WMA" => ta.wma (close, length)
"VWMA" => ta.vwma(close, length)
"DEMA" => 2 * ema1 - ema2
"TEMA" => (3 * ema1) - (3 * ema2) + ema3
=> na
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
ma = type.ma(len)
fl = ta.falling(ma , count)
rs = ta.rising (ma , count)
up = fl[1] and ma > ma[1]
dn = rs[1] and ma < ma[1]
atr = ta.atr(14)
n = bar_index
//-----------------------------------------------------------------------------}
//Execution
//-----------------------------------------------------------------------------{
if up
p = array.new<chart.point>()
p.push(chart.point.from_index(n - 1 , low [1] - atr / 15 ))
p.push(chart.point.from_index(n + (len / 2 -1) , low [1] + atr / 2.5))
p.push(chart.point.from_index(n + len , low [1] + atr * 2 ))
p.push(chart.point.from_index(n + (len / 2 -1) , low [1] + atr / 2.5))
p.push(chart.point.from_index(n - 1 , low [1] + atr / 15 ))
polyline.new(p
, curved = true
, closed = false
, line_color = colUp
, fill_color = color.new(colUp, 50))
if dn
p = array.new<chart.point>()
p.push(chart.point.from_index(n - 1 , high[1] + atr / 15 ))
p.push(chart.point.from_index(n + (len / 2 -1) , high[1] - atr / 2.5))
p.push(chart.point.from_index(n + len , high[1] - atr * 2 ))
p.push(chart.point.from_index(n + (len / 2 -1) , high[1] - atr / 2.5))
p.push(chart.point.from_index(n - 1 , high[1] - atr / 15 ))
polyline.new(p
, curved = true
, closed = false
, line_color = colDn
, fill_color = color.new(colDn, 50))
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot (ma , 'MA' , color= colMa )
plotshape(up ? low [1] : na, '', color= colUp , location=location.absolute, style=shape.circle, size=size.tiny , offset=-1)
plotshape(up ? low [1] : na, '', color=color.new(colUp, 50), location=location.absolute, style=shape.circle, size=size.small , offset=-1)
plotshape(up ? low [1] : na, '', color=color.new(colUp, 65), location=location.absolute, style=shape.circle, size=size.normal, offset=-1)
plotshape(dn ? high[1] : na, '', color= colDn , location=location.absolute, style=shape.circle, size=size.tiny , offset=-1)
plotshape(dn ? high[1] : na, '', color=color.new(colDn, 50), location=location.absolute, style=shape.circle, size=size.small , offset=-1)
plotshape(dn ? high[1] : na, '', color=color.new(colDn, 65), location=location.absolute, style=shape.circle, size=size.normal, offset=-1)
//-----------------------------------------------------------------------------} |
Bollinger Bands Strategy | https://www.tradingview.com/script/kE4i5MSC/ | gsanson66 | https://www.tradingview.com/u/gsanson66/ | 49 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gsanson66
//This strategy uses the well-known Bollinger Bands Indicator
//@version=5
strategy("BOLLINGER BANDS STRATEGY", shorttitle="BB STRATEGY", overlay=true, initial_capital=1000, default_qty_type=strategy.cash, default_qty_value=950, commission_type=strategy.commission.percent, commission_value=0.18, slippage=3)
//---------------------------------------TOOL TIPS-----------------------------------------//
t1 = "Bollinger Bands length. Corresponds to the SMA length to which we add/substract the standard deviation to create upper and lower bands."
t2 = "Corresponds to the number of standard deviations to be added/subtracted to obtain the two bands. This number can be decimal."
t3 = "The length of the SMA sending the output signals."
t4 = "The maximum percentage of the trade value we can lose. Default is 6%"
t5 = "Each gain or losse (relative to the previous reference) in an amount equal to this fixed ratio will change quantity of orders."
t6 = "The amount of money to be added to or subtracted from orders once the fixed ratio has been reached."
//----------------------------------------FUNCTIONS---------------------------------------//
//@function Displays text passed to `txt` when called.
debugLabel(txt, color) =>
label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)
//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)
//---------------------------------------USER INPUTS--------------------------------------//
//Technical parameters
bbLength = input.int(defval=120, minval=1, title="BB Length", group="Technical Parameters", tooltip=t1)
mult = input.float(defval=2, minval=0.1, title="Standard Deviation Multipler", group="Technical Parameters", tooltip=t2)
smaLength = input.int(defval=110, minval=1, title="SMA Exit Signal Length", group="Technical Parameters", tooltip=t3)
slMax = input.float(6, minval=0, title="Max Risk per trade (in %)", group="Risk Management", tooltip=t4)
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management", tooltip=t5)
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management", tooltip=t6)
//Backtesting period
startDate = input.time(title="Start Date", defval=timestamp("1 Jan 2017 00:00:00"), group="Backtesting Period")
endDate = input.time(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")
//----------------------------------VARIABLES INITIALISATION-----------------------------//
//Exit
smaExit = ta.sma(close, smaLength)
//BB Calculation
basis = ta.sma(close, bbLength)
dev = mult * ta.stdev(close, bbLength)
upperBB = basis + dev
lowerBB = basis - dev
//Money management
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95
//Backtesting period
bool inRange = na
//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//
//Checking if the date belong to the range
inRange := inBacktestPeriod(startDate, endDate)
//Checking performances of the strategy
if equity > capital_ref + fixedRatio
spread = (equity - capital_ref)/fixedRatio
nb_level = int(spread)
increasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder + increasingOrder
capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
spread = (capital_ref - equity)/fixedRatio
nb_level = int(spread)
decreasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder - decreasingOrder
capital_ref := capital_ref - nb_level*fixedRatio
//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
strategy.close_all()
debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))
//-----------------------------------EXIT SIGNAL------------------------------//
//SMA Exit Signal
if strategy.position_size > 0 and close < smaExit
strategy.close("Long")
if strategy.position_size < 0 and close > smaExit
strategy.close("Short")
//----------------------------------LONG/SHORT CONDITION---------------------------//
//Long Condition
if close > upperBB and strategy.position_size==0 and inRange
qty = cashOrder/close
strategy.entry("Long", strategy.long, qty)
strategy.exit("Exit Long", "Long", stop=close*(1-slMax/100))
//Short Condition
if close < lowerBB and strategy.position_size==0 and inRange
qty = cashOrder/close
strategy.entry("Short", strategy.short, qty)
strategy.exit("Exit Short", "Short", stop=close*(1+slMax/100))
//---------------------------------PLOTTING ELEMENT----------------------------------//
plot(smaExit, color=color.orange)
upperBBPlot = plot(upperBB, color=color.blue)
lowerBBPlot = plot(lowerBB, color=color.blue)
fill(upperBBPlot, lowerBBPlot, title = "Background", color=strategy.position_size>0 ? color.rgb(0, 255, 0, 90) : strategy.position_size<0 ? color.rgb(255, 0, 0, 90) : color.rgb(33, 150, 243, 95))
|
Pineconnector Strategy Template (Connect Any Indicator) | https://www.tradingview.com/script/GM4rFZk3-Pineconnector-Strategy-Template-Connect-Any-Indicator/ | Daveatt | https://www.tradingview.com/u/Daveatt/ | 218 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//@strategy_alert_message {{strategy.order.alert_message}}
// # ========================================================================= #
// # | SAMPLE INDICATOR |
// # ========================================================================= #
// Sample script to plug to the strategy template
////@version=5
//indicator(title='Moving Average Cross', shorttitle='Moving Average Cross', overlay=true, precision=6, max_labels_count=500, max_lines_count=500)
// type_ma1 = input.string(title='MA1 type', defval='SMA', options=['RMA', 'SMA', 'EMA'])
// length_ma1 = input(10, title='[ALL but VWAP] MA1 length')
// type_ma2 = input.string(title='MA2 type', defval='SMA', options=['RMA', 'SMA', 'EMA'])
// length_ma2 = input(100, title='[ALL but VWAP] MA2 length')
// // MA
// f_ma(smoothing, src, length) =>
// rma_1 = ta.rma(src, length)
// sma_1 = ta.sma(src, length)
// ema_1 = ta.ema(src, length)
// iff_1 = smoothing == 'EMA' ? ema_1 : src
// iff_2 = smoothing == 'SMA' ? sma_1 : iff_1
// smoothing == 'RMA' ? rma_1 : iff_2
// MA1 = f_ma(type_ma1, close, length_ma1)
// MA2 = f_ma(type_ma2, close, length_ma2)
// // buy and sell conditions
// buy = ta.crossover(MA1, MA2)
// sell = ta.crossunder(MA1, MA2)
// plot(MA1, color=color.new(color.green, 0), title='Plot MA1', linewidth=3)
// plot(MA2, color=color.new(color.red, 0), title='Plot MA2', linewidth=3)
// plotshape(buy, title='LONG SIGNAL', style=shape.circle, location=location.belowbar, color=color.new(color.green, 0), size=size.normal)
// plotshape(sell, title='SHORT SIGNAL', style=shape.circle, location=location.abovebar, color=color.new(color.red, 0), size=size.normal)
// /////////////////////////// SIGNAL FOR STRATEGY /////////////////////////
// Signal = buy ? 1 : sell ? -1 : 0
// plot(Signal, title='🔌Connector🔌', display = display.data_window)
// # ========================================================================= #
// # | SAMPLE INDICATOR |
// # ========================================================================= #
SCRIPT_NAME = "Pineconnector Strategy Template"
strategy(SCRIPT_NAME,
overlay= true,
process_orders_on_close = true,
calc_on_every_tick = true,
pyramiding = 1,
initial_capital = 100000,
default_qty_type = strategy.fixed,
default_qty_value = 1,
commission_type = strategy.commission.percent,
commission_value = 0.075,
slippage = 1
)
_ext_connector = input.source(close, title = "External Connector", group = "Connected Indicator Source", tooltip = "Select the indicator you want to connect to this strategy.\nThis indicator will be used to trigger the strategy orders.")
ext_connector = nz(_ext_connector)
// # ========================================================================= #
// # | EA |
// # ========================================================================= #
pineconnector_licence_ID = input.string(title = "Licence ID", defval = "123456789", group = "Pineconnector", tooltip = "Insert your Pineconnector Licence ID here\nYou can find it in your Pineconnector account webpage")
use_drawdown_EA_halt = input.bool(false, title = "Use Drawdown EA Halt?", group = "EA Risk Management", inline = "max drawdown", tooltip = "Halt the EA if the max drawdown value is reached")
max_drawdown_mode = input.string("%", title = "Mode", options = ["%", "USD"], group = "EA Risk Management", inline = "max drawdown")
max_drawdown_value = input.float(20, minval = 0, title = "Max Drawdown (%)", group = "EA Risk Management", inline = "max drawdown")
use_max_consecutive_days_EA_halt = input.bool(false, title = "Use Max Consecutive Days EA Halt?", group = "EA Risk Management", inline = "max consecutive days", tooltip = "Halt the EA if the max consecutive losing days value is reached")
nb_max_consecutive_days = input.int(3, minval = 0, title = "Max Consecutive Days", group = "EA Risk Management", inline = "max consecutive days")
use_max_losing_streak = input.bool(false, title = "Use Max Losing Streak?", group = "EA Risk Management", inline = "max losing streak", tooltip = "To prevent the EA from taking too many losses in a row")
maxLosingStreak = input.int(15, title="Max Losing Streak Length", minval=1, group = "EA Risk Management", inline = "max losing streak")
use_margin_call = input.bool(false, title = "Use Margin Call?", group = "EA Risk Management", inline = "margin call", tooltip = "Margin longs/shorts need to be different than 0% from the Properties tab.\nExit when we're X% away from a margin call, to prevent it")
margin_call_value = input.float(10, minval = 0, title = "Margin Call (%)", group = "EA Risk Management", inline = "margin call")
use_close_EA_total_loss = input.bool(false, title = "Use Close EA Total Loss?", group = "EA Risk Management", inline = "close EA total loss", tooltip = "Close all the trades + halt EA if the total loss is reached")
total_loss_value = input.float(-5000, maxval = 0, title = "Total Loss ($)", group = "EA Risk Management", inline = "close EA total loss")
use_intraday_losses_EA_halt = input.bool(false, title = "Use Intraday Losses EA Halt?", group = "Intraday EA Risk Management", inline = "intraday losses")
intraday_loss_value = input.string("%", title = "Mode", options = ["%", "USD"], group = "Intraday EA Risk Management", inline = "intraday losses")
nb_intraday_losses = input.int(3, minval = 0, title = "Max Intraday Losses (%)", group = "Intraday EA Risk Management", inline = "intraday losses")
use_limit_intraday_trades = input.bool(false, title = "Use Limit Intraday Trades?", group = "Intraday EA Risk Management", inline = "max intraday trades")
nb_max_intraday_trades = input.int(5, minval = 0, title = "Max Intraday Trades", group = "Intraday EA Risk Management", inline = "max intraday trades")
use_restart_intraday_EA = input.bool(false, title = "Use Restart Intraday EA?", group = "Intraday EA Risk Management", inline = "restart intraday EA", tooltip = "Restart the EA at the first bar of next day if it has been stoppped with an intraday risk management safeguard")
use_spread_filter = input.bool(false, title = "Use Spread Filter?", group = "EA Spread Filter", inline = "spread filter", tooltip = "Enter the position only if the spread is equal or less than the specified value in pips.")
spread_value = input.float(3.5, minval = 0, title = "Spread Value (pips)", group = "EA Spread Filter", inline = "spread filter")
use_acc_filter = input.bool(false, title = "Use Account Filter?", group = "EA Account Filter", inline = "account filter", tooltip = "Enter the position only if the account requirement is met.\nEA Options: Account Balance, Account Equity, Margin Percentage and Free Margin")
accfilter_value = input.float(1000, minval = 0, title = "Account Balance/Equity (USD)", group = "EA Account Filter", inline = "account filter")
// # ========================================================================= #
// # | Order Types |
// # ========================================================================= #
order_type_mode = input.string("Market", title = "Order Type", options = ["Market", "Limit", "Stop"], group = "Order Types")
order_type_price = input.float(10, title = "Price", group = "Order Types",
tooltip = "With 'Limit', below the current market price for a buy - above the current market price for a sell\nWith 'Stop', above the current market price for a buy - below the current market price for a sell\n")
// # ========================================================================= #
// # | Position Size |
// # ========================================================================= #
pos_size = input.float(3, minval = 0, maxval = 100, title = "Position Size", group = "Position Size", tooltip = "Required to specify the position size here for Pineconnector to work properly")
// # ========================================================================= #
// # | Direction |
// # ========================================================================= #
strat_direction = input.string(strategy.direction.all, title = "Direction", options = [strategy.direction.all, strategy.direction.long, strategy.direction.short], group = "Trades Direction", tooltip = "To specify in which market direction the strategy is allowed to open positions.")
//use_close_opposite = input.bool(false, title = "Close on Opposite Signal?", group = "Close on Opposite", tooltip = "Close the position if 1 or more MACDs become bearish (for longs) or bullish (for shorts)")
// # ========================================================================= #
// # | General SL/TP |
// # ========================================================================= #
sl_tp_mode = input.string("pips", title = "Mode", options = ["pips", "%"], group = "General SL/TP", tooltip = "Select the mode you want to use for the SL/TP values\nSelect the same mode in the Pineconnector EA on Metatrader")
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
use_sl = input.bool(true, title = "Use Stop Loss?", group = "Stop Loss")
sl_value = input.float(40, minval = 0, title = "Value", group = "Stop Loss", inline = "stoploss")// * 0.01
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
use_tsl = input.bool(false, title = "Use Trailing Stop Loss?", group = "Trailing Stop Loss")
tsl_input_value = input.float(10, minval = 0, title = "Value", group = "Trailing Stop Loss")
// # ========================================================================= #
// # | Take Profit |
// # ========================================================================= #
use_tp1 = input.bool(true, title = "Use Take Profit 1?", group = "Take Profit 1")
tp1_value = input.float(30, minval = 0, title = "Value", group = "Take Profit 1")
tp1_qty = input.float(50, minval = 0, title = "Quantity (%)", group = "Take Profit 1")
use_tp2 = input.bool(true, title = "Use Take Profit 2?", group = "Take Profit 2")
tp2_value = input.float(50, minval = 0, title = "Value", group = "Take Profit 2")
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
use_sl_be = input.bool(false, title = "Use Stop Loss to Breakeven Mode?", group = "Break Even")
sl_be_value = input.float(30, step = 0.1, minval = 0, title = "Value (pips)", group = "Break Even", inline = "breakeven")
sl_be_offset = input.int(1, step = 1, minval = 0, title = "Offset (pips)", group = "Break Even", tooltip = "Set the SL at BE price +/- offset value")
// # ========================================================================= #
// # | Pine Utilities |
// # ========================================================================= #
// Source: https://www.tradingview.com/pine-script-reference/v5/#var_strategy.margin_liquidation_price
changePercent(v1, v2) =>
float result = (v1 - v2) * 100 / math.abs(v2)
// Source: https://www.tradingview.com/pine-script-reference/v5/#fun_strategy.closedtrades.profit
// Calculate sum gross profit from all closed trades by adding the difference between gross profit and commission.
SumGrossProfitClosedTrades() =>
sumGrossProfit = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
sumGrossProfit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
result = nz(sumGrossProfit)
get_pip_size() =>
float _pipsize = 1.
if syminfo.type == "forex"
_pipsize := (syminfo.mintick * (str.contains(syminfo.ticker, "JPY") ? 100 : 10))
else if str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "XAG")
_pipsize := 0.1
_pipsize
// # ========================================================================= #
// # | Calculations |
// # ========================================================================= #
bull = ext_connector == 1 and barstate.isconfirmed
bear = ext_connector == -1 and barstate.isconfirmed
signal_candle = bull or bear
signal_bull = bull and strategy.position_size[1] <= 0
signal_bear = bear and strategy.position_size[1] >= 0
entryLongPrice = ta.valuewhen(signal_bull, close, 0)
entryShortPrice = ta.valuewhen(signal_bear, close, 0)
plot(strategy.position_size > 0 ? entryLongPrice : na, title = "Long Entry Price", color = color.green, linewidth = 2, style = plot.style_circles)
plot(strategy.position_size < 0 ? entryShortPrice : na, title = "Short Entry Price", color = color.red, linewidth = 2, style = plot.style_circles)
var label entry_label = na
if barstate.islast
if strategy.position_size > 0
entry_label := label.new(x = bar_index + 5, y = entryLongPrice, text = "Long Entry: " + str.tostring(entryLongPrice, format.mintick), style = label.style_label_left, color = color.green, size = size.normal)
else if strategy.position_size < 0
entry_label := label.new(x = bar_index + 5, y = entryShortPrice, text = "Short Entry: " + str.tostring(entryShortPrice, format.mintick), style = label.style_label_left, color = color.red, size = size.normal)
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
var float final_SL_Long = 0.
var float final_SL_Short = 0.
var float final_SL_Long_Pineconnector = 0.
var float final_SL_Short_Pineconnector = 0.
if use_sl
if signal_bull
final_SL_Long := (sl_tp_mode == "pips") ? entryLongPrice - (sl_value * get_pip_size()) : entryLongPrice * (1 - (sl_value * 0.01))
else if signal_bear
final_SL_Short := (sl_tp_mode == "pips") ? entryShortPrice + (sl_value * get_pip_size()) : entryShortPrice * (1 + (sl_value * 0.01))
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
var MaxReached = 0.0
if signal_candle[1]
MaxReached := strategy.position_size > 0 ? high : low
MaxReached := strategy.position_size > 0
? math.max(nz(MaxReached, high), high)
: strategy.position_size < 0 ? math.min(nz(MaxReached, low), low) : na
if use_tsl and use_sl
if strategy.position_size > 0
stopValue = MaxReached - (tsl_input_value * get_pip_size())
final_SL_Long := math.max(stopValue, final_SL_Long[1])
else if strategy.position_size < 0
stopValue = MaxReached + (tsl_input_value * get_pip_size())
final_SL_Short := math.min(stopValue, final_SL_Short[1])
// # ========================================================================= #
// # | Take Profit 1 |
// # ========================================================================= #
var float final_TP1_Long = 0.
var float final_TP1_Short = 0.
if use_tp1
if signal_bull
final_TP1_Long := (sl_tp_mode == "pips") ? entryLongPrice + (tp1_value * get_pip_size()) : entryLongPrice * (1 + (tp1_value * 0.01))
else if signal_bear
final_TP1_Short := (sl_tp_mode == "pips") ? entryShortPrice - (tp1_value * get_pip_size()) : entryShortPrice * (1 - (tp1_value * 0.01))
plot(use_tp1 and strategy.position_size > 0 ? final_TP1_Long : na, title = "TP1 Long", color = color.aqua, linewidth=2, style=plot.style_linebr)
plot(use_tp1 and strategy.position_size < 0 ? final_TP1_Short : na, title = "TP1 Short", color = color.blue, linewidth=2, style=plot.style_linebr)
var label tp1_label = na
if barstate.islast and use_tp1
if strategy.position_size > 0
tp1_label := label.new(x = bar_index + 5, y = final_TP1_Long, text = "TP1: " + str.tostring(final_TP1_Long, format.mintick), style = label.style_label_left, color = color.aqua, size = size.normal)
else if strategy.position_size < 0
tp1_label := label.new(x = bar_index + 5, y = final_TP1_Short, text = "TP1: " + str.tostring(final_TP1_Short, format.mintick), style = label.style_label_left, color = color.blue, size = size.normal)
// # ========================================================================= #
// # | Take Profit 2 |
// # ========================================================================= #
var float final_TP2_Long = 0.
var float final_TP2_Short = 0.
if use_tp2 and tp1_qty != 100
if signal_bull
final_TP2_Long := (sl_tp_mode == "pips") ? entryLongPrice + (tp2_value * get_pip_size()) : entryLongPrice * (1 + (tp2_value * 0.01))
else if signal_bear
final_TP2_Short := (sl_tp_mode == "pips") ? entryShortPrice - (tp2_value * get_pip_size()) : entryShortPrice * (1 - (tp2_value * 0.01))
plot(use_tp2 and strategy.position_size > 0 and tp1_qty != 100 ? final_TP2_Long : na, title = "TP2 Long", color = color.orange, linewidth=2, style=plot.style_linebr)
plot(use_tp2 and strategy.position_size < 0 and tp1_qty != 100 ? final_TP2_Short : na, title = "TP2 Short", color = color.white, linewidth=2, style=plot.style_linebr)
var label tp2_label = na
if barstate.islast and use_tp2
if strategy.position_size > 0 and tp1_qty != 100
tp2_label := label.new(x = bar_index + 5, y = final_TP2_Long, text = "TP2: " + str.tostring(final_TP2_Long, format.mintick), style = label.style_label_left, color = color.orange, size = size.normal)
else if strategy.position_size < 0 and tp1_qty != 100
tp2_label := label.new(x = bar_index + 5, y = final_TP2_Short, text = "TP2: " + str.tostring(final_TP2_Short, format.mintick), style = label.style_label_left, color = color.white, size = size.normal)
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
var bool SL_BE_REACHED = false
// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
sumProfit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
current_profit = tradeOpenPL()// * get_pip_size()
current_long_profit = (close - entryLongPrice) / (syminfo.mintick * 10)
current_short_profit = (entryShortPrice - close) / (syminfo.mintick * 10)
plot(current_short_profit, title = "Current Short Profit", display = display.data_window)
plot(current_long_profit, title = "Current Long Profit", display = display.data_window)
if use_sl_be
if strategy.position_size > 0
if not SL_BE_REACHED
if current_long_profit >= sl_be_value
final_SL_Long := entryLongPrice + (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
else if strategy.position_size < 0
if not SL_BE_REACHED
if current_short_profit >= sl_be_value
final_SL_Short := entryShortPrice - (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
plot(use_sl and strategy.position_size > 0 ? final_SL_Long : na, title = "SL Long", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
plot(use_sl and strategy.position_size < 0 ? final_SL_Short : na, title = "SL Short", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
var label sl_label = na
if barstate.islast and use_sl
if strategy.position_size > 0
sl_label := label.new(x = bar_index + 5, y = final_SL_Long, text = "SL: " + str.tostring(final_SL_Long, format.mintick), style = label.style_label_left, color = color.fuchsia, size = size.normal)
else if strategy.position_size < 0
sl_label := label.new(x = bar_index + 5, y = final_SL_Short, text = "SL: " + str.tostring(final_SL_Short, format.mintick), style = label.style_label_left, color = color.fuchsia, size = size.normal)
// # ========================================================================= #
// # | Pineconnector Alerts Message |
// # ========================================================================= #
string entry_long_limit_alert_message = ""
string entry_long_TP1_alert_message = ""
string entry_long_TP2_alert_message = ""
var float tp1_qty_perc = tp1_qty / 100
var string buy_command = ""
var string sell_command = ""
// Executing this only once at the beginning of the strategy
if barstate.isfirst
if order_type_mode == "Market"
buy_command := ",buy," + syminfo.ticker
sell_command := ",sell," + syminfo.ticker
else if order_type_mode == "Limit"
buy_command := ",buylimit," + syminfo.ticker + ",price=" + str.tostring(order_type_price)
sell_command := ",selllimit," + syminfo.ticker + ",price=" + str.tostring(order_type_price)
else if order_type_mode == "Stop"
buy_command := ",buystop," + syminfo.ticker + ",price=" + str.tostring(order_type_price)
sell_command := ",sellstop," + syminfo.ticker + ",price=" + str.tostring(order_type_price)
//pos_size = math.abs(strategy.position_size)
if use_tp1 and use_tp2
entry_long_TP1_alert_message := pineconnector_licence_ID + buy_command + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Long, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
entry_long_TP2_alert_message := pineconnector_licence_ID + buy_command + ",risk=" + str.tostring(pos_size - (pos_size * tp1_qty_perc)) + ",tp=" + str.tostring(final_TP2_Long, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
else if use_tp1 and (not use_tp2 or tp1_qty == 100)
entry_long_TP1_alert_message := pineconnector_licence_ID + buy_command + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Long, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
else if not use_tp1 and use_tp2
entry_long_TP2_alert_message := pineconnector_licence_ID + buy_command + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP2_Long, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
entry_long_limit_alert_message := entry_long_TP1_alert_message + "\n" + entry_long_TP2_alert_message
//entry_long_limit_alert_message = pineconnector_licence_ID + ",buystop," + syminfo.ticker + ",price=" + str.tostring(buy_price) + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP_Long) + ",sl=" + str.tostring(final_SL_Long)
//entry_short_market_alert_message = pineconnector_licence_ID + ",sell," + syminfo.ticker + ",risk=" + str.tostring(pos_size) + (use_tp1 ? ",tp=" + str.tostring(final_TP1_Short) : "")
// + (use_sl ? ",sl=" + str.tostring(final_SL_Short) : "")
//entry_short_limit_alert_message = pineconnector_licence_ID + ",sellstop," + syminfo.ticker + ",price=" + str.tostring(sell_price) + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP_Short) + ",sl=" + str.tostring(final_SL_Short)
string entry_short_limit_alert_message = ""
string entry_short_TP1_alert_message = ""
string entry_short_TP2_alert_message = ""
if use_tp1 and use_tp2
entry_short_TP1_alert_message := pineconnector_licence_ID + sell_command + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Short, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
entry_short_TP2_alert_message := pineconnector_licence_ID + sell_command + ",risk=" + str.tostring(pos_size - (pos_size * tp1_qty_perc)) + ",tp=" + str.tostring(final_TP2_Short, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
else if use_tp1 and (not use_tp2 or tp1_qty == 100)
entry_short_TP1_alert_message := pineconnector_licence_ID + sell_command + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Short, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
else if not use_tp1 and use_tp2
entry_short_TP2_alert_message := pineconnector_licence_ID + sell_command + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP2_Short, format.mintick)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short, format.mintick) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_value) + ",traildist=" + str.tostring(tsl_input_value) + ",trailstep=1" : "")
+ (use_spread_filter ? ",spread=" + str.tostring(spread_value) : "") + (use_acc_filter ? ",accfilter=" + str.tostring(accfilter_value) : "")
entry_short_limit_alert_message := entry_short_TP1_alert_message + "\n" + entry_short_TP2_alert_message
long_update_sl_alert_message = pineconnector_licence_ID + ",newsltplong," + syminfo.ticker + ",sl=" + str.tostring(final_SL_Long)
short_update_sl_alert_message = pineconnector_licence_ID + ",newsltpshort," + syminfo.ticker + ",sl=" + str.tostring(final_SL_Short)
cancel_long = pineconnector_licence_ID + ",cancellong," + syminfo.ticker// + "x"
cancel_short = pineconnector_licence_ID + ",cancellong," + syminfo.ticker// + "x"
close_long = pineconnector_licence_ID + ",closelong," + syminfo.ticker
close_short = pineconnector_licence_ID + ",closeshort," + syminfo.ticker
// Close all positions and orders, and off/halt the PineConnector EA.
halt_ea_message = pineconnector_licence_ID + ",closealleaoff," + syminfo.ticker
// Reactivates the PineConnector EA from halt.
restart_ea_message = pineconnector_licence_ID + ",eaon,eaon"
// # ========================================================================= #
// # | EA global variables |
// # ========================================================================= #
// Flag to remember to stop taking trades if we get too much Rekt :)
var bool HALT_STRATEGY = false
// # ========================================================================= #
// # | Risk Management |
// # ========================================================================= #
strategy.risk.max_drawdown(use_drawdown_EA_halt ? max_drawdown_value : 100, use_drawdown_EA_halt ? (max_drawdown_mode == "%" ? strategy.percent_of_equity : strategy.cash) : strategy.percent_of_equity, halt_ea_message)
strategy.risk.max_intraday_loss(use_intraday_losses_EA_halt and timeframe.isintraday ? nb_intraday_losses : 999999, use_intraday_losses_EA_halt and timeframe.isintraday ? (intraday_loss_value == "%" ? strategy.percent_of_equity : strategy.cash) : strategy.percent_of_equity, halt_ea_message)
strategy.risk.max_cons_loss_days(use_max_consecutive_days_EA_halt ? nb_max_consecutive_days : 999999, halt_ea_message)
strategy.risk.max_intraday_filled_orders(use_limit_intraday_trades and timeframe.isintraday ? nb_max_intraday_trades : 999999, halt_ea_message)
// Restart the EA if it's an intraday chart and it has been paused due to intraday max losses or intraday max filled orders
// test if it's a new day
newDay = dayofmonth != dayofmonth[1]
bgcolor(use_restart_intraday_EA and newDay and timeframe.isintraday ? color.aqua : na, title = "Restart EA at the first candle of the day")
if use_restart_intraday_EA and newDay and timeframe.isintraday
alert(restart_ea_message, alert.freq_once_per_bar_close)
// # ========================================================================= #
// # | Streak Management |
// # ========================================================================= #
// Source: https://www.tradingcode.net/tradingview/losing-streak/
// Check if there's a new losing trade that increased the streak
newLoss = strategy.losstrades > strategy.losstrades[1] and
strategy.wintrades == strategy.wintrades[1] and
strategy.eventrades == strategy.eventrades[1]
// Determine current losing streak length
streakLen = 0
streakLen := if newLoss
nz(streakLen[1]) + 1
else
if strategy.wintrades > strategy.wintrades[1] or
strategy.eventrades > strategy.eventrades[1]
0
else
nz(streakLen[1])
// Show current losing streak and its limit on chart
//plot(use_max_losing_streak ? streakLen : na, style=plot.style_columns, color=streakLen < maxLosingStreak ? color.maroon : color.red, title = "Max Losing Streak")
bgcolor(use_max_losing_streak and newLoss ? color.new(color.red, 80) : na, title = "New Loss Streak")
// Send the message to Pineconnector if the losing streak is too long
if streakLen > maxLosingStreak
HALT_STRATEGY := true
alert(halt_ea_message, alert.freq_once_per_bar_close)
// # ========================================================================= #
// # | Money Management |
// # ========================================================================= #
if use_margin_call
if math.abs(changePercent(close, strategy.margin_liquidation_price)) <= margin_call_value
HALT_STRATEGY := true
strategy.close_all(comment = "Closing all trades to avoid Margin Liq", alert_message = halt_ea_message)
//alert(halt_ea_message, alert.freq_once_per_bar_close)
if use_close_EA_total_loss
strategy_closeprofit = SumGrossProfitClosedTrades()
// Test if the total profit/loss of all close//open positions is below the total loss input value
if (strategy_closeprofit + strategy.openprofit) <= total_loss_value
HALT_STRATEGY := true
strategy.close_all(comment = "Closing all trades to avoid Total Loss", alert_message = halt_ea_message)
// # ========================================================================= #
// # | Trades Direction |
// # ========================================================================= #
// Didn't work
// strategy.risk.allow_entry_in(strat_direction)
// # ========================================================================= #
// # | Strategy Calls (Entries/SL/TPs) |
// # ========================================================================= #
open_all = strat_direction == strategy.direction.all
open_long = strat_direction != strategy.direction.short
open_short = strat_direction != strategy.direction.long
// Entries
if bull and strategy.position_size <= 0 and open_long and (not HALT_STRATEGY)
alert(close_short, alert.freq_once_per_bar_close)
strategy.entry("Long", strategy.long, limit = order_type_mode == "Limit" ? order_type_price : na, stop = order_type_mode == "Stop" ? order_type_price : na)
alert(entry_long_TP1_alert_message, alert.freq_once_per_bar_close)
alert(entry_long_TP2_alert_message, alert.freq_once_per_bar_close)
else if bear and strategy.position_size >= 0 and open_short and (not HALT_STRATEGY)
alert(close_long, alert.freq_once_per_bar_close)
strategy.entry("Short", strategy.short, limit = order_type_mode == "Limit" ? order_type_price : na, stop = order_type_mode == "Stop" ? order_type_price : na)
alert(entry_short_TP1_alert_message, alert.freq_once_per_bar_close)
alert(entry_short_TP2_alert_message, alert.freq_once_per_bar_close)
if strategy.position_size[1] > 0
// This handles the SL being hit even after a SL/BE and/or TSL has been triggered
if low <= final_SL_Long and use_sl
strategy.close("Long", alert_message = close_long, comment = "SL Long")
else
strategy.exit("Exit TP1 Long", "Long", limit = use_tp1 ? final_TP1_Long : na, comment_profit = "Exit TP1 Long", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Long", "Long", limit = use_tp2 ? final_TP2_Long : na, comment_profit = "Exit TP2 Long", alert_message = close_long)
else if strategy.position_size[1] < 0
// This handles the SL being hit even after a SL/BE and/or TSL has been triggered
if high >= final_SL_Short and use_sl
strategy.close("Short", alert_message = close_short, comment = "SL Short")
else
strategy.exit("Exit TP1 Short", "Short", limit = use_tp1 ? final_TP1_Short : na, comment_profit = "Exit TP1 Short", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Short", "Short", limit = use_tp2 ? final_TP2_Short : na, comment_profit = "Exit TP2 Short")
// # ========================================================================= #
// # | Logs |
// # ========================================================================= #
if bull and strategy.position_size <= 0
log.info(entry_long_limit_alert_message)
else if bear and strategy.position_size >= 0
log.info(entry_short_limit_alert_message)
// # ========================================================================= #
// # | Reset Variables |
// # ========================================================================= #
if (strategy.position_size > 0 and strategy.position_size[1] <= 0)
or (strategy.position_size < 0 and strategy.position_size[1] >= 0)
//is_TP1_REACHED := false
SL_BE_REACHED := false |
Elliott Wave Fusion - Strategy [presentTrading] | https://www.tradingview.com/script/uEQ3hQfw-Elliott-Wave-Fusion-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 41 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
strategy('Elliott Wave Fusion - Strategy [presentTrading]' ,shorttitle = 'Eillott Wave Fusion w/ BB&ST Exit', overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000, max_labels_count=300)
//Settings
// Add a button to choose the trading direction
tradingDirection = input.string("Both","Trading Direction", options=["Long", "Short", "Both"])
i_hi = input.string('high' , title= '' , group='source [high - low]', inline='hl', options=['high', 'close', 'max open/close'])
i_lo = input.string('low' , title= '' , group='source [high - low]', inline='hl', options=['low' , 'close', 'min open/close'])
s1 = input.bool (true , title= '' , group='ZigZag' , inline= '1' )
len1 = input.int ( 4 , title= ' 1 Length', group='ZigZag' , inline= '1', minval =1 )
col1 = input.color (color.red , title= '' , group='ZigZag' , inline= '1' )
// Supertrend
STLength = input.int(10, title='Supertrend Length' ,group='Exit condition')
STMultiplier = input.float(2,title='Supertrend Multiplier',group='Exit condition')
// Bollinger Bands Settings
lengthBB = input(20, title='Bollinger Bands Length',group='Exit condition')
multBB = input(2, title='Standard Deviations',group='Exit condition')
// Define the fixed percentage for the stop loss
stopLossPercentage = input.float(10, title='Stop Loss Percentage (%)', group='Stoploss: Fix percentage')
i_500 = input.float (0.500 , title=' level 1', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_618 = input.float (0.618 , title=' level 2', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_764 = input.float (0.764 , title=' level 3', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_854 = input.float (0.854 , title=' level 4', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
shZZ = input.bool (false , title= '' , group='show ZZ' , inline='zz' )
//User Defined Types
type ZZ
int [] d
int [] x
float[] y
line [] l
type Ewave
line l1
line l2
line l3
line l4
line l5
label b1
label b2
label b3
label b4
label b5
//
bool on
bool br //= na
//
int dir
//
line lA
line lB
line lC
label bA
label bB
label bC
//
bool next = false
//
label lb
box bx
type fibL
line wave1_0_500
line wave1_0_618
line wave1_0_764
line wave1_0_854
line wave1_pole_
linefill l_fill_
bool _break_ //= na
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
hi = i_hi == 'high' ? high : i_hi == 'close' ? close : math.max(open, close)
lo = i_lo == 'low' ? low : i_hi == 'close' ? close : math.min(open, close)
in_out(aZZ, d, x1, y1, x2, y2, col) =>
aZZ.d.unshift(d), aZZ.x.unshift(x2), aZZ.y.unshift(y2), aZZ.d.pop(), aZZ.x.pop(), aZZ.y.pop()
if shZZ
aZZ.l.unshift(line.new(x1, y1, x2, y2, color= col)), aZZ.l.pop().delete()
method isSame(Ewave gEW, _1x, _2x, _3x, _4x) =>
t1 = _1x == gEW.l1.get_x1()
t2 = _2x == gEW.l2.get_x1()
t3 = _3x == gEW.l3.get_x1()
t4 = _4x == gEW.l4.get_x1()
t1 and t2 and t3 and t4
method isSame2(Ewave gEW, _1x, _2x, _3x) =>
t1 = _1x == gEW.l3.get_x2()
t2 = _2x == gEW.l4.get_x2()
t3 = _3x == gEW.l5.get_x2()
t1 and t2 and t3
method dot(Ewave gEW) =>
gEW.l1.set_style(line.style_dotted)
gEW.l2.set_style(line.style_dotted)
gEW.l3.set_style(line.style_dotted)
gEW.l4.set_style(line.style_dotted)
gEW.l5.set_style(line.style_dotted)
gEW.b1.set_textcolor (color(na))
gEW.b2.set_textcolor (color(na))
gEW.b3.set_textcolor (color(na))
gEW.b4.set_textcolor (color(na))
gEW.b5.set_textcolor (color(na))
gEW.on := false
method dash(Ewave gEW) =>
gEW.lA.set_style(line.style_dashed)
gEW.lB.set_style(line.style_dashed)
gEW.lC.set_style(line.style_dashed)
gEW.bA.set_textcolor (color(na))
gEW.bB.set_textcolor (color(na))
gEW.bC.set_textcolor (color(na))
gEW.bx.set_bgcolor (color(na))
gEW.bx.set_border_color (color(na))
method sol_dot(fibL nFibL, sol_dot, col) =>
style =
sol_dot == 'dot' ?
line.style_dotted :
sol_dot == 'sol' ?
line.style_solid :
line.style_dashed
nFibL.wave1_0_500.set_style(style)
nFibL.wave1_0_618.set_style(style)
nFibL.wave1_0_764.set_style(style)
nFibL.wave1_0_854.set_style(style)
nFibL.l_fill_.set_color(col)
method set(fibL nFibL, int x1, int x2, float max_500, float max_618, float max_764, float max_854, float y2) =>
nFibL.wave1_0_500.set_xy1(x1, max_500)
nFibL.wave1_0_500.set_xy2(x2, max_500)
nFibL.wave1_0_618.set_xy1(x1, max_618)
nFibL.wave1_0_618.set_xy2(x2, max_618)
nFibL.wave1_0_764.set_xy1(x1, max_764)
nFibL.wave1_0_764.set_xy2(x2, max_764)
nFibL.wave1_0_854.set_xy1(x1, max_854)
nFibL.wave1_0_854.set_xy2(x2, max_854)
nFibL.wave1_pole_.set_xy1(x1, y2 )
nFibL.wave1_pole_.set_xy2(x1, max_854)
nFibL.l_fill_.get_line1().set_xy1(x1, max_764)
nFibL.l_fill_.get_line1().set_xy2(x2, max_764)
nFibL.l_fill_.get_line2().set_xy1(x1, max_854)
nFibL.l_fill_.get_line2().set_xy2(x2, max_854)
method setNa(fibL nFibL) =>
nFibL.wave1_0_500.set_xy1(na, na)
nFibL.wave1_0_500.set_xy2(na, na)
nFibL.wave1_0_618.set_xy1(na, na)
nFibL.wave1_0_618.set_xy2(na, na)
nFibL.wave1_0_764.set_xy1(na, na)
nFibL.wave1_0_764.set_xy2(na, na)
nFibL.wave1_0_854.set_xy1(na, na)
nFibL.wave1_0_854.set_xy2(na, na)
nFibL.wave1_pole_.set_xy1(na, na)
nFibL.wave1_pole_.set_xy2(na, na)
nFibL.l_fill_.set_color(color(na))
draw(enabled, left, col, n) =>
longEntry = false
shortEntry = false
//
max_bars_back(time, 4000)
var int dir = na, var int x1= na, var float y1 = na, var int x2 = na, var float y2 = na, var Ewave gEW = na
var int last_0x = na , var float last_0y = na , var int last_6x = na , var float last_6y = na
//
if enabled
var fibL nFibL = fibL.new(
wave1_0_500 = line.new(na, na, na, na, color= color.new(col, 50), style= line.style_solid ),
wave1_0_618 = line.new(na, na, na, na, color= color.new(col, 38), style= line.style_solid ),
wave1_0_764 = line.new(na, na, na, na, color= color.new(col, 24), style= line.style_solid ),
wave1_0_854 = line.new(na, na, na, na, color= color.new(col, 15), style= line.style_solid ),
wave1_pole_ = line.new(na, na, na, na, color= color.new(col, 50), style= line.style_dashed),
l_fill_ = linefill.new(
line.new(na, na, na, na, color= color(na))
, line.new(na, na, na, na, color= color(na))
, color= color(na))
, _break_ = na
)
//
var ZZ aZZ = ZZ.new(array.new < int > ()
, array.new < int > ()
, array.new < float > ()
, array.new < line > () )
var Ewave[] aEW = array.new < Ewave > ()
//
if barstate.isfirst
aEW.unshift(Ewave.new())
for i = 0 to 10
aZZ.d.unshift(0)
aZZ.x.unshift(0)
aZZ.y.unshift(0)
aZZ.l.unshift(shZZ ? line.new(na, na, na, na) : na)
//
sz = aZZ.d.size( )
x2 := bar_index -1
ph = ta.pivothigh(hi, left, 1)
pl = ta.pivotlow (lo, left, 1)
t = n == 2 ? '\n\n' : n == 1 ? '\n' : ''
//
// when a new Pivot High is found
if not na(ph)
gEW := aEW.get (0)
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(hi[1])
//
if dir < 1 // if previous point was a pl, add, and change direction ( 1)
in_out(aZZ, 1, x1, y1, x2, y2, col)
else
if dir == 1 and ph > y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if shZZ
aZZ.l.get(0).set_xy2(x2, y2)
//
_6x = x2, _6y = y2
_5x = aZZ.x.get(1), _5y = aZZ.y.get(1)
_4x = aZZ.x.get(2), _4y = aZZ.y.get(2)
_3x = aZZ.x.get(3), _3y = aZZ.y.get(3)
_2x = aZZ.x.get(4), _2y = aZZ.y.get(4)
_1x = aZZ.x.get(5), _1y = aZZ.y.get(5)
//
// –––––––––––––––––––––[ 12345 ]–––––––––––––––––––––
_W5 = _6y - _5y
_W3 = _4y - _3y
_W1 = _2y - _1y
min = math.min(_W1, _W3, _W5)
isWave =
_W3 != min and
_6y > _4y and
_3y > _1y and
_5y > _2y
//
same = gEW.isSame(_1x, _2x, _3x, _4x)
if isWave
if same
gEW.l5.set_xy2(_6x, _6y)
gEW.b5.set_xy (_6x, _6y)
else
tx = ''
if _2x == aEW.get(0).b5.get_x()
tx := '(5) (1)'
aEW.get(0).b5.set_text('')
else
tx := '(1)'
//
wave = Ewave.new(
l1 = line.new (_1x, _1y, _2x, _2y , color=col , style= line.style_solid ),
l2 = line.new (_2x, _2y, _3x, _3y , color=col , style= line.style_solid ),
l3 = line.new (_3x, _3y, _4x, _4y , color=col , style= line.style_solid ),
l4 = line.new (_4x, _4y, _5x, _5y , color=col , style= line.style_solid ),
l5 = line.new (_5x, _5y, _6x, _6y , color=col , style= line.style_solid ),
b1 = label.new(_2x, _2y, text= tx + t, textcolor=col, color= color(na), style=label.style_label_down),
b2 = label.new(_3x, _3y, text= t + '(2)', textcolor=col, color= color(na), style=label.style_label_up ),
b3 = label.new(_4x, _4y, text= '(3)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b4 = label.new(_5x, _5y, text= t + '(4)', textcolor=col, color= color(na), style=label.style_label_up ),
b5 = label.new(_6x, _6y, text= '(5)' + t, textcolor=col, color= color(na), style=label.style_label_down),
on = true ,
br = false ,
dir = 1
)
aEW.unshift(wave)
nFibL._break_ := false
alert('New EW Motive Bullish Pattern found' , alert.freq_once_per_bar_close)
//
if not isWave
if same and gEW.on == true
gEW.dot()
alert('Invalidated EW Motive Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ ABC ]–––––––––––––––––––––
getEW = aEW.get(0)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
diff = math.abs(last_6y - last_0y)
//
if getEW.dir == -1
getX = getEW.l5.get_x2()
getY = getEW.l5.get_y2()
isSame2 = getEW.isSame2 (_1x, _2x, _3x)
isValid =
_3x == getX and
_6y < getY + (diff * i_854) and
_4y < getY + (diff * i_854) and
_5y > getY
//
if isValid
width = _6x - _2x // –––[ width (4) - (c) ]–––
if isSame2 and getEW.bA.get_x() > _3x
getEW.lC.set_xy1(_5x, _5y), getEW.lC.set_xy2(_6x, _6y), getEW.bC.set_xy(_6x, _6y), getEW.bx.set_lefttop(_6x, _6y), getEW.bx.set_right(_6x + width)
else
getEW.lA := line.new (_3x, _3y, _4x, _4y, color=col), getEW.bA := label.new(_4x, _4y, text= '(a)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.lB := line.new (_4x, _4y, _5x, _5y, color=col), getEW.bB := label.new(_5x, _5y, text= t + '(b)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.lC := line.new (_5x, _5y, _6x, _6y, color=col), getEW.bC := label.new(_6x, _6y, text= '(c)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.bx := box.new (_6x, _6y, _6x + width, _4y, bgcolor=color.new(col, 93), border_color=color.new(col, 65))
alert('New EW Corrective Bullish Pattern found' , alert.freq_once_per_bar_close)
else
if isSame2 and getEW.bA.get_x() > _3x
getEW.dash()
alert('Invalidated EW Corrective Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ new (1) ? ]–––––––––––––––––––––
if getEW.dir == 1
if _5x == getEW.bC.get_x() and
_6y > getEW.b5.get_y() and
getEW.next == false
getEW.next := true
getEW.lb := label.new(_6x, _6y, style=label.style_circle, color=color.new(col, 65), yloc=yloc.abovebar, size=size.tiny)
alert('Possible new start of EW Motive Bullish Wave', alert.freq_once_per_bar_close)
// Check for bullish pattern (modify this condition as needed)
if isWave and getEW.dir == 1
longEntry := true
//
// when a new Pivot Low is found
if not na(pl)
gEW := aEW.get (0)
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(lo[1])
//
if dir > -1 // if previous point was a ph, add, and change direction (-1)
in_out(aZZ, -1, x1, y1, x2, y2, col)
else
if dir == -1 and pl < y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if shZZ
aZZ.l.get(0).set_xy2(x2, y2)
//
_6x = x2, _6y = y2
_5x = aZZ.x.get(1), _5y = aZZ.y.get(1)
_4x = aZZ.x.get(2), _4y = aZZ.y.get(2)
_3x = aZZ.x.get(3), _3y = aZZ.y.get(3)
_2x = aZZ.x.get(4), _2y = aZZ.y.get(4)
_1x = aZZ.x.get(5), _1y = aZZ.y.get(5)
//
// –––––––––––––––––––––[ 12345 ]–––––––––––––––––––––
_W5 = _5y - _6y
_W3 = _3y - _4y
_W1 = _1y - _2y
min = math.min(_W1, _W3, _W5)
isWave =
_W3 != min and
_4y > _6y and
_1y > _3y and
_2y > _5y
//
same = isSame(gEW, _1x, _2x, _3x, _4x)
if isWave
if same
gEW.l5.set_xy2(_6x, _6y)
gEW.b5.set_xy (_6x, _6y)
else
tx = ''
if _2x == aEW.get(0).b5.get_x()
tx := '(5) (1)'
aEW.get(0).b5.set_text('')
else
tx := '(1)'
//
wave = Ewave.new(
l1 = line.new (_1x, _1y, _2x, _2y , color=col , style= line.style_solid ),
l2 = line.new (_2x, _2y, _3x, _3y , color=col , style= line.style_solid ),
l3 = line.new (_3x, _3y, _4x, _4y , color=col , style= line.style_solid ),
l4 = line.new (_4x, _4y, _5x, _5y , color=col , style= line.style_solid ),
l5 = line.new (_5x, _5y, _6x, _6y , color=col , style= line.style_solid ),
b1 = label.new(_2x, _2y, text= t + tx, textcolor=col, color= color(na), style=label.style_label_up ),
b2 = label.new(_3x, _3y, text= '(2)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b3 = label.new(_4x, _4y, text= t + '(3)', textcolor=col, color= color(na), style=label.style_label_up ),
b4 = label.new(_5x, _5y, text= '(4)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b5 = label.new(_6x, _6y, text= t + '(5)', textcolor=col, color= color(na), style=label.style_label_up ),
on = true ,
br = false ,
dir =-1
)
aEW.unshift(wave)
nFibL._break_ := false
alert('New EW Motive Bearish Pattern found' , alert.freq_once_per_bar_close)
//
if not isWave
if same and gEW.on == true
gEW.dot()
alert('Invalidated EW Motive Bearish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ ABC ]–––––––––––––––––––––
getEW = aEW.get(0)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
diff = math.abs(last_6y - last_0y)
//
if getEW.dir == 1
getX = getEW.l5.get_x2()
getY = getEW.l5.get_y2()
isSame2 = getEW.isSame2 (_1x, _2x, _3x)
isValid =
_3x == getX and
_6y > getY - (diff * i_854) and
_4y > getY - (diff * i_854) and
_5y < getY
//
if isValid
width = _6x - _2x // –––[ width (4) - (c) ]–––
if isSame2 and getEW.bA.get_x() > _3x
getEW.lC.set_xy1(_5x, _5y), getEW.lC.set_xy2(_6x, _6y), getEW.bC.set_xy(_6x, _6y), getEW.bx.set_lefttop(_6x, _6y), getEW.bx.set_right(_6x + width)
else
getEW.lA := line.new (_3x, _3y, _4x, _4y, color=col), getEW.bA := label.new(_4x, _4y, text= t + '(a)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.lB := line.new (_4x, _4y, _5x, _5y, color=col), getEW.bB := label.new(_5x, _5y, text= '(b)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.lC := line.new (_5x, _5y, _6x, _6y, color=col), getEW.bC := label.new(_6x, _6y, text= t + '(c)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.bx := box.new (_6x, _6y, _6x + width, _4y, bgcolor=color.new(col, 93), border_color=color.new(col, 65))
alert('New EW Corrective Bearish Pattern found' , alert.freq_once_per_bar_close)
else
if isSame2 and getEW.bA.get_x() > _3x
getEW.dash()
alert('Invalidated EW Corrective Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––[ check (only once) for a possible new (1) after an impulsive AND corrective wave ]–––
if getEW.dir == -1
if _5x == getEW.bC.get_x() and
_6y < getEW.b5.get_y() and
getEW.next == false
getEW.next := true
getEW.lb := label.new(_6x, _6y, style=label.style_circle, color=color.new(col, 65), yloc=yloc.belowbar, size=size.tiny)
alert('Possible new start of EW Motive Bearish Wave', alert.freq_once_per_bar_close)
// Check for bearish pattern (modify this condition as needed)
if isWave and getEW.dir == -1
shortEntry := true
//
// –––[ check for break box ]–––
if aEW.size() > 0
gEW := aEW.get(0)
if gEW.dir == 1
if ta.crossunder(low , gEW.bx.get_bottom()) and bar_index <= gEW.bx.get_right()
label.new(bar_index, low , yloc= yloc.belowbar, style= label.style_xcross, color=color.red, size=size.tiny)
else
if ta.crossover (high, gEW.bx.get_top ()) and bar_index <= gEW.bx.get_right()
label.new(bar_index, high, yloc= yloc.abovebar, style= label.style_xcross, color=color.red, size=size.tiny)
//
if barstate.islast
// –––[ get last 2 EW's ]–––
getEW = aEW.get(0)
if aEW.size() > 1
getEW1 = aEW.get(1)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
//
diff = math.abs(last_6y - last_0y) // –––[ max/min difference ]–––
_500 = diff * i_500
_618 = diff * i_618
_764 = diff * i_764
_854 = diff * i_854
bull = getEW.dir == 1
// –––[ if EW is not valid or an ABC has developed -> remove fibonacci lines ]–––
if getEW.on == false or getEW.bC.get_x() > getEW.b5.get_x()
nFibL.setNa()
else
// –––[ get.on == true ~ valid EW ]–––
max_500 = last_6y + ((bull ? -1 : 1) * _500)
max_618 = last_6y + ((bull ? -1 : 1) * _618)
max_764 = last_6y + ((bull ? -1 : 1) * _764)
max_854 = last_6y + ((bull ? -1 : 1) * _854)
//
nFibL.set(last_6x, bar_index + 10, max_500, max_618, max_764, max_854, last_6y)
// –––[ if (2) label overlap with (C) label ]–––
if getEW.b2.get_x() == getEW1.bC.get_x()
getEW.b1.set_textcolor(color(na))
getEW.b2.set_textcolor(color(na))
strB = getEW1.bB.get_text()
strC = getEW1.bC.get_text()
strB_ = str.replace(strB, "(b)", "(b) (1)", 0)
strC_ = str.replace(strC, "(c)", "(c) (2)", 0)
getEW1.bB.set_text(strB_)
getEW1.bC.set_text(strC_)
//
// –––[ check if fib limits are broken ]–––
getP_854 = nFibL.wave1_0_854.get_y1()
for i = 0 to bar_index - nFibL.wave1_0_854.get_x1()
if getEW.dir == -1
if high[i] > getP_854
nFibL._break_ := true
break
else
if low [i] < getP_854
nFibL._break_ := true
break
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
switch nFibL._break_
true => nFibL.sol_dot('dot', color.new(color.red , 95))
false => nFibL.sol_dot('sol', color.new(color.lime, 95))
=>
nFibL.wave1_0_500.set_xy1(na, na)
nFibL.wave1_0_500.set_xy2(na, na)
nFibL.wave1_0_618.set_xy1(na, na)
nFibL.wave1_0_618.set_xy2(na, na)
nFibL.wave1_0_764.set_xy1(na, na)
nFibL.wave1_0_764.set_xy2(na, na)
nFibL.wave1_0_854.set_xy1(na, na)
nFibL.wave1_0_854.set_xy2(na, na)
nFibL.wave1_pole_.set_xy1(na, na)
nFibL.wave1_pole_.set_xy2(na, na)
nFibL.l_fill_.set_color(color(na))
if aEW.size() > 15
pop = aEW.pop()
pop.l1.delete(), pop.b1.delete()
pop.l2.delete(), pop.b2.delete()
pop.l3.delete(), pop.b3.delete()
pop.l4.delete(), pop.b4.delete()
pop.l5.delete(), pop.b5.delete()
pop.lA.delete(), pop.bA.delete()
pop.lB.delete(), pop.bB.delete()
pop.lC.delete(), pop.bC.delete()
pop.lb.delete(), pop.bx.delete()
//----------------------------------
[longEntry, shortEntry]
//Plots
draw(s1, len1, col1, 0)
// Call the draw function and get the long and short entry conditions
[longEntry1, shortEntry1] = draw(s1, len1, col1, 0)
// Calculate the stop loss levels
longStopLossLevel = close * (1 - stopLossPercentage / 100)
shortStopLossLevel = close * (1 + stopLossPercentage / 100)
// Long Entry Condition
if (shortEntry1 and (tradingDirection == "Long" or tradingDirection == "Both"))
strategy.entry("Buy", strategy.long)
strategy.exit('Exit Long', 'Buy', stop=longStopLossLevel)
// Short Entry Condition
if (longEntry1 and (tradingDirection == "Short" or tradingDirection == "Both"))
strategy.entry("Sell", strategy.short)
strategy.exit('Exit Short', 'Sell', stop=shortStopLossLevel)
// Supertrend Exit Conditions
[supertrend, direction] = ta.supertrend(STMultiplier, STLength)
var float prevDirection = na
STlongExit = false
STshortExit = false
if na(prevDirection)
prevDirection := direction
else
if direction != prevDirection
STlongExit := prevDirection < 0
STshortExit := prevDirection > 0
prevDirection := direction
// Calculate Bollinger Bands
basis = ta.wma(close, lengthBB)
dev = multBB * ta.stdev(close, lengthBB)
upperBB = basis + dev
lowerBB = basis - dev
// Plot Bollinger Bands
plot(basis, title="Middle Band", color=color.blue)
plot(upperBB, title="Upper Band", color=color.green)
plot(lowerBB, title="Lower Band", color=color.red)
BBlongExit = close > upperBB
BBshortExit = close < lowerBB
longExit = STlongExit or BBlongExit
shortExit = STshortExit or BBshortExit
// Long Exit Condition
if (longExit and (tradingDirection == "Long" or tradingDirection == "Both"))
strategy.close("Buy")
// Short Exit Condition
if (shortExit and (tradingDirection == "Short" or tradingDirection == "Both"))
strategy.close("Sell") |
TradingView.To Strategy Template (with Dyanmic Alerts) | https://www.tradingview.com/script/brMq1l1s-TradingView-To-Strategy-Template-with-Dyanmic-Alerts/ | Daveatt | https://www.tradingview.com/u/Daveatt/ | 117 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//@strategy_alert_message {{strategy.order.alert_message}}
// # ========================================================================= #
// # | SAMPLE INDICATOR |
// # ========================================================================= #
// Sample script to plug to the strategy template
////@version=5
//indicator(title='Moving Average Cross', shorttitle='Moving Average Cross', overlay=true, precision=6, max_labels_count=500, max_lines_count=500)
// type_ma1 = input.string(title='MA1 type', defval='SMA', options=['RMA', 'SMA', 'EMA'])
// length_ma1 = input(10, title='[ALL but VWAP] MA1 length')
// type_ma2 = input.string(title='MA2 type', defval='SMA', options=['RMA', 'SMA', 'EMA'])
// length_ma2 = input(100, title='[ALL but VWAP] MA2 length')
// // MA
// f_ma(smoothing, src, length) =>
// rma_1 = ta.rma(src, length)
// sma_1 = ta.sma(src, length)
// ema_1 = ta.ema(src, length)
// iff_1 = smoothing == 'EMA' ? ema_1 : src
// iff_2 = smoothing == 'SMA' ? sma_1 : iff_1
// smoothing == 'RMA' ? rma_1 : iff_2
// MA1 = f_ma(type_ma1, close, length_ma1)
// MA2 = f_ma(type_ma2, close, length_ma2)
// // buy and sell conditions
// buy = ta.crossover(MA1, MA2)
// sell = ta.crossunder(MA1, MA2)
// plot(MA1, color=color.new(color.green, 0), title='Plot MA1', linewidth=3)
// plot(MA2, color=color.new(color.red, 0), title='Plot MA2', linewidth=3)
// plotshape(buy, title='LONG SIGNAL', style=shape.circle, location=location.belowbar, color=color.new(color.green, 0), size=size.normal)
// plotshape(sell, title='SHORT SIGNAL', style=shape.circle, location=location.abovebar, color=color.new(color.red, 0), size=size.normal)
// /////////////////////////// SIGNAL FOR STRATEGY /////////////////////////
// Signal = buy ? 1 : sell ? -1 : 0
// plot(Signal, title='🔌Connector🔌', display = display.data_window)
// # ========================================================================= #
// # | SAMPLE INDICATOR |
// # ========================================================================= #
SCRIPT_NAME = "TradingViewTO Strategy Template"
strategy(SCRIPT_NAME,
overlay= true,
process_orders_on_close = true,
calc_on_every_tick = true,
pyramiding = 1,
initial_capital = 100000,
default_qty_type = strategy.fixed,
default_qty_value = 1,
commission_type = strategy.commission.percent,
commission_value = 0.075,
slippage = 1
)
_ext_connector = input.source(close, title = "External Connector", group = "Connected Indicator Source", tooltip = "Select the indicator you want to connect to this strategy.\nThis indicator will be used to trigger the strategy orders.")
ext_connector = nz(_ext_connector)
// # ========================================================================= #
// # | EA |
// # ========================================================================= #
tradingviewto_account_ID = input.string(title = "Account Name", defval = "USDM", group = "Account Name", tooltip = "Insert your TradingViewTO Account Name here")
use_drawdown_EA_halt = input.bool(false, title = "Use Drawdown EA Halt?", group = "EA Risk Management", inline = "max drawdown", tooltip = "Halt the EA if the max drawdown value is reached")
max_drawdown_mode = input.string("%", title = "Mode", options = ["%", "USD"], group = "EA Risk Management", inline = "max drawdown")
max_drawdown_value = input.float(20, minval = 0, title = "Max Drawdown (%)", group = "EA Risk Management", inline = "max drawdown")
use_max_consecutive_days_EA_halt = input.bool(false, title = "Use Max Consecutive Days EA Halt?", group = "EA Risk Management", inline = "max consecutive days", tooltip = "Halt the EA if the max consecutive losing days value is reached")
nb_max_consecutive_days = input.int(3, minval = 0, title = "Max Consecutive Days", group = "EA Risk Management", inline = "max consecutive days")
use_max_losing_streak = input.bool(false, title = "Use Max Losing Streak?", group = "EA Risk Management", inline = "max losing streak", tooltip = "To prevent the EA from taking too many losses in a row")
maxLosingStreak = input.int(15, title="Max Losing Streak Length", minval=1, group = "EA Risk Management", inline = "max losing streak")
use_margin_call = input.bool(false, title = "Use Margin Call?", group = "EA Risk Management", inline = "margin call", tooltip = "Margin longs/shorts need to be different than 0% from the Properties tab.\nExit when we're X% away from a margin call, to prevent it")
margin_call_value = input.float(10, minval = 0, title = "Margin Call (%)", group = "EA Risk Management", inline = "margin call")
use_close_EA_total_loss = input.bool(false, title = "Use Close EA Total Loss?", group = "EA Risk Management", inline = "close EA total loss", tooltip = "Close all the trades + halt EA if the total loss is reached")
total_loss_value = input.float(-5000, maxval = 0, title = "Total Loss ($)", group = "EA Risk Management", inline = "close EA total loss")
use_intraday_losses_EA_halt = input.bool(false, title = "Use Intraday Losses EA Halt?", group = "Intraday EA Risk Management", inline = "intraday losses")
intraday_loss_value = input.string("%", title = "Mode", options = ["%", "USD"], group = "Intraday EA Risk Management", inline = "intraday losses")
nb_intraday_losses = input.int(3, minval = 0, title = "Max Intraday Losses (%)", group = "Intraday EA Risk Management", inline = "intraday losses")
use_limit_intraday_trades = input.bool(false, title = "Use Limit Intraday Trades?", group = "Intraday EA Risk Management", inline = "max intraday trades")
nb_max_intraday_trades = input.int(5, minval = 0, title = "Max Intraday Trades", group = "Intraday EA Risk Management", inline = "max intraday trades")
// # ========================================================================= #
// # | Trading Mode |
// # ========================================================================= #
trading_mode = input.string("Spot", title = "Trading Mode", options = ["Spot", "Margin"], group = "Trading Mode", tooltip = "Spot for buy/sell orders\nMargin for long/short orders")
// # ========================================================================= #
// # | Order Types |
// # ========================================================================= #
order_type_mode = input.string("Market", title = "Order Type", options = ["Market", "Limit"], group = "Order Types")
order_type_price = input.float(10, title = "Price", group = "Order Types",
tooltip = "With 'Limit', below the current market price for a buy - above the current market price for a sell")
// # ========================================================================= #
// # | Position Size |
// # ========================================================================= #
pos_type = input.string("Units", title = "Position Type", options = ["Units", "Percent"], group = "Position Size", tooltip = "Select the position type you want to use for this strategy")
pos_size = input.float(3, minval = 0, maxval = 100, title = "Position Size", group = "Position Size", tooltip = "Required to specify the position size here for ProfitView to work properly")
// # ========================================================================= #
// # | Leverage |
// # ========================================================================= #
//margin_type = input.string("Isolated", title = "Margin Type", options = ["Isolated", "Crossed"], group = "Leverage", tooltip = "Select the margin type you want to use for this strategy")
use_leverage = input.bool(false, title = "Use Leverage?", group = "Leverage", tooltip = "Use this option if you want to use the Leverage for this strategy")
leverage_value = input.float(1, minval = 0, title = "Value", group = "Leverage", tooltip = "Required to specify the leverage here for ProfitView to work properly")
use_hedge_mode = input.bool(false, title = "Use Hedge Mode?", group = "Leverage", tooltip = "Use this option if you want to use the Hedge mode for this strategy")
// # ========================================================================= #
// # | Sessions |
// # ========================================================================= #
use_session = input.bool(false, title='Use Sessions ?', group='Session', tooltip = "Limit the trades between a start and end time")
Session = input.session(title='Trading Session', defval='0000-2345', group='Session')
sess_timezone = input.string('UTC-5', title='Session Timezone', group='Session')
close_trades_end_session = input.bool(false, title='Close Trades at End of Session ?', group='Session', tooltip = "Close all the trades at the end of the session")
// # ========================================================================= #
// # | Dates |
// # ========================================================================= #
// ————— Syntax coming from https://www.tradingview.com/blog/en/new-parameter-for-date-input-added-to-pine-21812/
use_date = input.bool(false, title='Use Date Filter ?', group='Date', tooltip = "Limit the trades between a start and end date")
i_startTime = input.time(defval=timestamp('01 Jan 2019 13:30 +0000'), title='Start Time', group='Date')
i_endTime = input.time(defval=timestamp('30 Dec 2021 23:30 +0000'), title='End Time', group='Date')
TradeDateIsAllowed() =>
use_date ? time >= i_startTime and time <= i_endTime : true
// # ========================================================================= #
// # | Direction |
// # ========================================================================= #
strat_direction = input.string(strategy.direction.all, title = "Direction", options = [strategy.direction.all, strategy.direction.long, strategy.direction.short], group = "Trades Direction", tooltip = "To specify in which market direction the strategy is allowed to open positions.")
//use_close_opposite = input.bool(false, title = "Close on Opposite Signal?", group = "Close on Opposite", tooltip = "Close the position if 1 or more MACDs become bearish (for longs) or bullish (for shorts)")
// # ========================================================================= #
// # | General SL/TP |
// # ========================================================================= #
sl_tp_mode = input.string("USD", title = "Mode", options = ["USD", "%"], group = "General SL/TP", tooltip = "Select the mode you want to use for the SL/TP values\nSelect the same mode in the TradingViewTO EA on Metatrader")
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
use_sl = input.bool(true, title = "Use Stop Loss?", group = "Stop Loss")
sl_value = input.float(40, minval = 0, title = "Value", group = "Stop Loss", inline = "stoploss")// * 0.01
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
use_tsl = input.bool(false, title = "Use Trailing Stop Loss?", group = "Trailing Stop Loss")
tsl_input_value = input.float(10, minval = 0, title = "Value", group = "Trailing Stop Loss")
// # ========================================================================= #
// # | Take Profit |
// # ========================================================================= #
use_tp1 = input.bool(true, title = "Use Take Profit 1?", group = "Take Profit 1")
tp1_value = input.float(30, minval = 0, title = "Value", group = "Take Profit 1")
tp1_qty = input.float(50, minval = 0, title = "Quantity (%)", group = "Take Profit 1")
use_tp2 = input.bool(true, title = "Use Take Profit 2?", group = "Take Profit 2")
tp2_value = input.float(50, minval = 0, title = "Value", group = "Take Profit 2")
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
use_sl_be = input.bool(false, title = "Use Stop Loss to Breakeven Mode?", group = "Break Even")
sl_be_value = input.float(30, step = 0.1, minval = 0, title = "Value (pips)", group = "Break Even", inline = "breakeven")
sl_be_offset = input.int(1, step = 1, minval = 0, title = "Offset (pips)", group = "Break Even", tooltip = "Set the SL at BE price +/- offset value")
// # ========================================================================= #
// # | Pine Utilities |
// # ========================================================================= #
// Source: https://www.tradingview.com/pine-script-reference/v5/#var_strategy.margin_liquidation_price
changePercent(v1, v2) =>
float result = (v1 - v2) * 100 / math.abs(v2)
// Source: https://www.tradingview.com/pine-script-reference/v5/#fun_strategy.closedtrades.profit
// Calculate sum gross profit from all closed trades by adding the difference between gross profit and commission.
SumGrossProfitClosedTrades() =>
sumGrossProfit = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
sumGrossProfit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
result = nz(sumGrossProfit)
get_pip_size() =>
float _pipsize = 1.
if syminfo.type == "forex"
_pipsize := (syminfo.mintick * (str.contains(syminfo.ticker, "JPY") ? 100 : 10))
else if str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "XAG")
_pipsize := 0.1
_pipsize
// # ========================================================================= #
// # | Calculations |
// # ========================================================================= #
bull = ext_connector == 1 and barstate.isconfirmed
bear = ext_connector == -1 and barstate.isconfirmed
signal_candle = bull or bear
signal_bull = bull and strategy.position_size[1] <= 0
signal_bear = bear and strategy.position_size[1] >= 0
entryLongPrice = ta.valuewhen(signal_bull, close, 0)
entryShortPrice = ta.valuewhen(signal_bear, close, 0)
plot(strategy.position_size > 0 ? entryLongPrice : na, title = "Long Entry Price", color = color.green, linewidth = 2, style = plot.style_circles)
plot(strategy.position_size < 0 ? entryShortPrice : na, title = "Short Entry Price", color = color.red, linewidth = 2, style = plot.style_circles)
var label entry_label = na
if barstate.islast
if strategy.position_size > 0
entry_label := label.new(x = bar_index + 5, y = entryLongPrice, text = "Long Entry: " + str.tostring(entryLongPrice, format.mintick), style = label.style_label_left, color = color.green, size = size.normal)
else if strategy.position_size < 0
entry_label := label.new(x = bar_index + 5, y = entryShortPrice, text = "Short Entry: " + str.tostring(entryShortPrice, format.mintick), style = label.style_label_left, color = color.red, size = size.normal)
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
var float final_SL_Long = 0.
var float final_SL_Short = 0.
var float final_SL_Long_Pineconnector = 0.
var float final_SL_Short_Pineconnector = 0.
if use_sl
if signal_bull
final_SL_Long := (sl_tp_mode == "USD") ? entryLongPrice - (sl_value * get_pip_size()) : entryLongPrice * (1 - (sl_value * 0.01))
else if signal_bear
final_SL_Short := (sl_tp_mode == "USD") ? entryShortPrice + (sl_value * get_pip_size()) : entryShortPrice * (1 + (sl_value * 0.01))
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
var MaxReached = 0.0
if signal_candle[1]
MaxReached := strategy.position_size > 0 ? high : low
MaxReached := strategy.position_size > 0
? math.max(nz(MaxReached, high), high)
: strategy.position_size < 0 ? math.min(nz(MaxReached, low), low) : na
if use_tsl and use_sl
if strategy.position_size > 0
stopValue = MaxReached - (tsl_input_value * get_pip_size())
final_SL_Long := math.max(stopValue, final_SL_Long[1])
else if strategy.position_size < 0
stopValue = MaxReached + (tsl_input_value * get_pip_size())
final_SL_Short := math.min(stopValue, final_SL_Short[1])
// # ========================================================================= #
// # | Take Profit 1 |
// # ========================================================================= #
var float final_TP1_Long = 0.
var float final_TP1_Short = 0.
if use_tp1
if signal_bull
final_TP1_Long := (sl_tp_mode == "USD") ? entryLongPrice + (tp1_value * get_pip_size()) : entryLongPrice * (1 + (tp1_value * 0.01))
else if signal_bear
final_TP1_Short := (sl_tp_mode == "USD") ? entryShortPrice - (tp1_value * get_pip_size()) : entryShortPrice * (1 - (tp1_value * 0.01))
plot(use_tp1 and strategy.position_size > 0 ? final_TP1_Long : na, title = "TP1 Long", color = color.aqua, linewidth=2, style=plot.style_linebr)
plot(use_tp1 and strategy.position_size < 0 ? final_TP1_Short : na, title = "TP1 Short", color = color.blue, linewidth=2, style=plot.style_linebr)
var label tp1_label = na
if barstate.islast and use_tp1
if strategy.position_size > 0
tp1_label := label.new(x = bar_index + 5, y = final_TP1_Long, text = "TP1: " + str.tostring(final_TP1_Long, format.mintick), style = label.style_label_left, color = color.aqua, size = size.normal)
else if strategy.position_size < 0
tp1_label := label.new(x = bar_index + 5, y = final_TP1_Short, text = "TP1: " + str.tostring(final_TP1_Short, format.mintick), style = label.style_label_left, color = color.blue, size = size.normal)
// # ========================================================================= #
// # | Take Profit 2 |
// # ========================================================================= #
var float final_TP2_Long = 0.
var float final_TP2_Short = 0.
if use_tp2 and tp1_qty != 100
if signal_bull
final_TP2_Long := (sl_tp_mode == "USD") ? entryLongPrice + (tp2_value * get_pip_size()) : entryLongPrice * (1 + (tp2_value * 0.01))
else if signal_bear
final_TP2_Short := (sl_tp_mode == "USD") ? entryShortPrice - (tp2_value * get_pip_size()) : entryShortPrice * (1 - (tp2_value * 0.01))
plot(use_tp2 and strategy.position_size > 0 and tp1_qty != 100 ? final_TP2_Long : na, title = "TP2 Long", color = color.orange, linewidth=2, style=plot.style_linebr)
plot(use_tp2 and strategy.position_size < 0 and tp1_qty != 100 ? final_TP2_Short : na, title = "TP2 Short", color = color.white, linewidth=2, style=plot.style_linebr)
var label tp2_label = na
if barstate.islast and use_tp2
if strategy.position_size > 0 and tp1_qty != 100
tp2_label := label.new(x = bar_index + 5, y = final_TP2_Long, text = "TP2: " + str.tostring(final_TP2_Long, format.mintick), style = label.style_label_left, color = color.orange, size = size.normal)
else if strategy.position_size < 0 and tp1_qty != 100
tp2_label := label.new(x = bar_index + 5, y = final_TP2_Short, text = "TP2: " + str.tostring(final_TP2_Short, format.mintick), style = label.style_label_left, color = color.white, size = size.normal)
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
var bool SL_BE_REACHED = false
// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
sumProfit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
current_profit = tradeOpenPL()// * get_pip_size()
current_long_profit = (close - entryLongPrice) / (syminfo.mintick * 10)
current_short_profit = (entryShortPrice - close) / (syminfo.mintick * 10)
plot(current_short_profit, title = "Current Short Profit", display = display.data_window)
plot(current_long_profit, title = "Current Long Profit", display = display.data_window)
if use_sl_be
if strategy.position_size > 0
if not SL_BE_REACHED
if current_long_profit >= sl_be_value
final_SL_Long := entryLongPrice + (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
else if strategy.position_size < 0
if not SL_BE_REACHED
if current_short_profit >= sl_be_value
final_SL_Short := entryShortPrice - (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
plot(use_sl and strategy.position_size > 0 ? final_SL_Long : na, title = "SL Long", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
plot(use_sl and strategy.position_size < 0 ? final_SL_Short : na, title = "SL Short", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
var label sl_label = na
if barstate.islast and use_sl
if strategy.position_size > 0
sl_label := label.new(x = bar_index + 5, y = final_SL_Long, text = "SL: " + str.tostring(final_SL_Long, format.mintick), style = label.style_label_left, color = color.fuchsia, size = size.normal)
else if strategy.position_size < 0
sl_label := label.new(x = bar_index + 5, y = final_SL_Short, text = "SL: " + str.tostring(final_SL_Short, format.mintick), style = label.style_label_left, color = color.fuchsia, size = size.normal)
// # ========================================================================= #
// # | Sessions |
// # ========================================================================= #
// Session calculations
// The BarInSession function returns true when
// the current bar is inside the session parameter
BarInSession(sess) =>
time(timeframe.period, sess, sess_timezone) != 0
in_session = BarInSession(Session)
okToTradeInSession = use_session ? in_session : true
new_session = in_session and not in_session[1]
bgcolor(color=use_session and BarInSession(Session)[1] ? color.new(color.green, 85) : na, title='Trading Session')
// # ========================================================================= #
// # | TradingViewTO Alerts Message |
// # ========================================================================= #
string entry_long_limit_alert_message = ""
string entry_long_TP1_alert_message = ""
string entry_long_TP2_alert_message = ""
var float tp1_qty_perc = tp1_qty / 100
var string account_command = ""
var string pyr_line_command = ""
var string bull_command = ""
var string bear_command = ""
ignore_pyr_orders = "check=pos side=[side] iffound=abort\n"
// Executing this only once at the beginning of the strategy
if barstate.isfirst
// First Line
account_command := "A=" + tradingviewto_account_ID
// Spot or Margin
if trading_mode == "Spot"
bull_command := "Buy " + syminfo.ticker
bear_command := "Sell " + syminfo.ticker
else if trading_mode == "Margin"
bull_command := "Long " + syminfo.ticker
bear_command := "Short " + syminfo.ticker
// Order Type
if order_type_mode == "Limit"
bull_command := bull_command + "p=" + str.tostring(order_type_price) + " "
bear_command := bear_command + "p=-" + str.tostring(order_type_price) + " "
// Quantity
if pos_type == "Units"
bull_command := bull_command + "Q=" + str.tostring(pos_size * tp1_qty_perc) + " "
bear_command := bear_command + "Q=" + str.tostring(pos_size * tp1_qty_perc) + " "
else if pos_type == "Percent"
bull_command := bull_command + "Q=" + str.tostring(pos_size * tp1_qty_perc) + "% "
bear_command := bear_command + "Q=" + str.tostring(pos_size * tp1_qty_perc) + "% "
// Hedge Mode
if use_hedge_mode
bull_command := bull_command + "hedge "
bear_command := bear_command + "hedge "
// Leverage
if use_leverage
bull_command := bull_command + "L=" + str.tostring(leverage_value) + " "
bear_command := bear_command + "L=" + str.tostring(leverage_value) + " "
bull_command := bull_command + "A=" + tradingviewto_account_ID
bear_command := bear_command + "A=" + tradingviewto_account_ID
if use_tp1 and use_tp2
entry_long_TP1_alert_message := bull_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Long, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP1_Long, format.mintick) : str.tostring(tp1_value) + "%")
entry_long_TP2_alert_message := bull_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Long, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP2_Long, format.mintick) : str.tostring(tp2_value) + "%")
else if use_tp1 and (not use_tp2 or tp1_qty == 100)
entry_long_TP1_alert_message := bull_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Long, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP1_Long, format.mintick) : str.tostring(tp1_value) + "%")
else if not use_tp1 and use_tp2
entry_long_TP2_alert_message := bull_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Long, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP2_Long, format.mintick) : str.tostring(tp2_value) + "%")
entry_long_limit_alert_message := entry_long_TP1_alert_message + "\n" + entry_long_TP2_alert_message
//entry_long_limit_alert_message = tradingviewto_account_ID + ",buystop," + syminfo.ticker + ",price=" + str.tostring(buy_price) + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP_Long) + ",sl=" + str.tostring(final_SL_Long)
//entry_short_market_alert_message = tradingviewto_account_ID + ",sell," + syminfo.ticker + ",risk=" + str.tostring(pos_size) + (use_tp1 ? ",tp=" + str.tostring(final_TP1_Short) : "")
// + (use_sl ? ",sl=" + str.tostring(final_SL_Short) : "")
//entry_short_limit_alert_message = tradingviewto_account_ID + ",sellstop," + syminfo.ticker + ",price=" + str.tostring(sell_price) + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP_Short) + ",sl=" + str.tostring(final_SL_Short)
string entry_short_limit_alert_message = ""
string entry_short_TP1_alert_message = ""
string entry_short_TP2_alert_message = ""
if use_tp1 and use_tp2
entry_short_TP1_alert_message := bear_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Short, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP1_Short, format.mintick) : str.tostring(tp1_value) + "%")
entry_short_TP2_alert_message := bear_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Short, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP2_Short, format.mintick) : str.tostring(tp2_value) + "%")
else if use_tp1 and (not use_tp2 or tp1_qty == 100)
entry_short_TP1_alert_message := bear_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Short, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP1_Short, format.mintick) : str.tostring(tp1_value) + "%")
else if not use_tp1 and use_tp2
entry_short_TP2_alert_message := bear_command + " sl=" + (sl_tp_mode == "USD" ? str.tostring(final_SL_Short, format.mintick) : str.tostring(sl_value) + "% ")
+ " tp=" + (sl_tp_mode == "USD" ? str.tostring(final_TP2_Short, format.mintick) : str.tostring(tp2_value) + "%")
entry_short_limit_alert_message := entry_short_TP1_alert_message + "\n" + entry_short_TP2_alert_message
cancel_long = "Cancel " + syminfo.ticker + (use_hedge_mode ? " hedge" : "") + " A=" + tradingviewto_account_ID
cancel_short = "Cancel " + syminfo.ticker + (use_hedge_mode ? " hedge" : "") + " A=" + tradingviewto_account_ID
close_long = "Close " + syminfo.ticker + " T=" + (trading_mode == "Spot" ? "buy" : "long") + (use_hedge_mode ? " hedge" : "") + " A=" + tradingviewto_account_ID
close_short = "Close " + syminfo.ticker + " T=" + (trading_mode == "Spot" ? "sell" : "short") + (use_hedge_mode ? " hedge" : "") + " A=" + tradingviewto_account_ID
// Close all positions and orders, and off/halt the PineConnector EA.
halt_ea_message = "You MUST halt your Bot manually"
// # ========================================================================= #
// # | EA global variables |
// # ========================================================================= #
// Flag to remember to stop taking trades if we get too much Rekt :)
var bool HALT_STRATEGY = false
// # ========================================================================= #
// # | Risk Management |
// # ========================================================================= #
strategy.risk.max_drawdown(use_drawdown_EA_halt ? max_drawdown_value : 100, use_drawdown_EA_halt ? (max_drawdown_mode == "%" ? strategy.percent_of_equity : strategy.cash) : strategy.percent_of_equity, halt_ea_message)
strategy.risk.max_intraday_loss(use_intraday_losses_EA_halt and timeframe.isintraday ? nb_intraday_losses : 999999, use_intraday_losses_EA_halt and timeframe.isintraday ? (intraday_loss_value == "%" ? strategy.percent_of_equity : strategy.cash) : strategy.percent_of_equity, halt_ea_message)
strategy.risk.max_cons_loss_days(use_max_consecutive_days_EA_halt ? nb_max_consecutive_days : 999999, halt_ea_message)
strategy.risk.max_intraday_filled_orders(use_limit_intraday_trades and timeframe.isintraday ? nb_max_intraday_trades : 999999, halt_ea_message)
// # ========================================================================= #
// # | Streak Management |
// # ========================================================================= #
// Source: https://www.tradingcode.net/tradingview/losing-streak/
// Check if there's a new losing trade that increased the streak
newLoss = strategy.losstrades > strategy.losstrades[1] and
strategy.wintrades == strategy.wintrades[1] and
strategy.eventrades == strategy.eventrades[1]
// Determine current losing streak length
streakLen = 0
streakLen := if newLoss
nz(streakLen[1]) + 1
else
if strategy.wintrades > strategy.wintrades[1] or
strategy.eventrades > strategy.eventrades[1]
0
else
nz(streakLen[1])
// Show current losing streak and its limit on chart
//plot(use_max_losing_streak ? streakLen : na, style=plot.style_columns, color=streakLen < maxLosingStreak ? color.maroon : color.red, title = "Max Losing Streak")
bgcolor(use_max_losing_streak and newLoss ? color.new(color.red, 80) : na, title = "New Loss Streak")
// Send the message to TradingViewTO if the losing streak is too long
if streakLen > maxLosingStreak
HALT_STRATEGY := true
alert(halt_ea_message, alert.freq_once_per_bar_close)
// # ========================================================================= #
// # | Money Management |
// # ========================================================================= #
if use_margin_call
if math.abs(changePercent(close, strategy.margin_liquidation_price)) <= margin_call_value
HALT_STRATEGY := true
strategy.close_all(comment = "Closing all trades to avoid Margin Liq", alert_message = halt_ea_message)
//alert(halt_ea_message, alert.freq_once_per_bar_close)
if use_close_EA_total_loss
strategy_closeprofit = SumGrossProfitClosedTrades()
// Test if the total profit/loss of all close//open positions is below the total loss input value
if (strategy_closeprofit + strategy.openprofit) <= total_loss_value
HALT_STRATEGY := true
strategy.close_all(comment = "Closing all trades to avoid Total Loss", alert_message = halt_ea_message)
// # ========================================================================= #
// # | Trades Direction |
// # ========================================================================= #
// Didn't work
// strategy.risk.allow_entry_in(strat_direction)
// # ========================================================================= #
// # | Strategy Calls (Entries/SL/TPs) |
// # ========================================================================= #
open_all = strat_direction == strategy.direction.all
open_long = strat_direction != strategy.direction.short
open_short = strat_direction != strategy.direction.long
okToTrade = okToTradeInSession and TradeDateIsAllowed() and (not HALT_STRATEGY)
// Entries
if bull and strategy.position_size <= 0 and open_long and okToTrade
alert(close_short, alert.freq_once_per_bar_close)
strategy.entry("Long", strategy.long, limit = order_type_mode == "Limit" ? order_type_price : na, stop = order_type_mode == "Stop" ? order_type_price : na, qty = pos_size * leverage_value)
alert(entry_long_TP1_alert_message, alert.freq_once_per_bar_close)
alert(entry_long_TP2_alert_message, alert.freq_once_per_bar_close)
else if bear and strategy.position_size >= 0 and open_short and okToTrade
alert(close_long, alert.freq_once_per_bar_close)
strategy.entry("Short", strategy.short, limit = order_type_mode == "Limit" ? order_type_price : na, stop = order_type_mode == "Stop" ? order_type_price : na, qty = pos_size * leverage_value)
alert(entry_short_TP1_alert_message, alert.freq_once_per_bar_close)
alert(entry_short_TP2_alert_message, alert.freq_once_per_bar_close)
if strategy.position_size[1] > 0
// This handles the SL being hit even after a SL/BE and/or TSL has been triggered
if low <= final_SL_Long and use_sl
strategy.close("Long", alert_message = close_long, comment = "SL Long")
else
strategy.exit("Exit TP1 Long", "Long", limit = use_tp1 ? final_TP1_Long : na, comment_profit = "Exit TP1 Long", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Long", "Long", limit = use_tp2 ? final_TP2_Long : na, comment_profit = "Exit TP2 Long", alert_message = close_long)
else if strategy.position_size[1] < 0
// This handles the SL being hit even after a SL/BE and/or TSL has been triggered
if high >= final_SL_Short and use_sl
strategy.close("Short", alert_message = close_short, comment = "SL Short")
else
strategy.exit("Exit TP1 Short", "Short", limit = use_tp1 ? final_TP1_Short : na, comment_profit = "Exit TP1 Short", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Short", "Short", limit = use_tp2 ? final_TP2_Short : na, comment_profit = "Exit TP2 Short")
// Closing all trades at the end of the session
if use_session and close_trades_end_session
strategy.close_all(alert_message = "Closing all trades at the end of the session")
// Close all the opened trades if the strategy is halted
if HALT_STRATEGY
strategy.close_all(alert_message = halt_ea_message)
// # ========================================================================= #
// # | Logs |
// # ========================================================================= #
if bull and strategy.position_size <= 0
log.info(entry_long_limit_alert_message)
else if bear and strategy.position_size >= 0
log.info(entry_short_limit_alert_message)
// # ========================================================================= #
// # | Reset Variables |
// # ========================================================================= #
if (strategy.position_size > 0 and strategy.position_size[1] <= 0)
or (strategy.position_size < 0 and strategy.position_size[1] >= 0)
//is_TP1_REACHED := false
SL_BE_REACHED := false |
Engulfing with Trend | https://www.tradingview.com/script/qVRxr42U/ | Malikdrajat | https://www.tradingview.com/u/Malikdrajat/ | 124 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Malikdrajat
//@version=4
strategy("Engulfing with Trend", overlay=true)
Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
alertcondition(buySignal, title="SuperTrend Buy", message="SuperTrend Buy!")
alertcondition(sellSignal, title="SuperTrend Sell", message="SuperTrend Sell!")
changeCond = trend != trend[1]
alertcondition(changeCond, title="SuperTrend Direction Change", message="SuperTrend has changed direction!")
// Define Downtrend and Uptrend conditions
downtrend = trend == -1
uptrend = trend == 1
// Engulfing
boringThreshold = input(25, title="Boring Candle Threshold (%)", minval=1, maxval=100, step=1)
engulfingThreshold = input(50, title="Engulfing Candle Threshold (%)", minval=1, maxval=100, step=1)
stopLevel = input(200, title="Stop Level (Pips)", minval=1)
// Boring Candle (Inside Bar) and Engulfing Candlestick Conditions
isBoringCandle = abs(open[1] - close[1]) * 100 / abs(high[1] - low[1]) <= boringThreshold
isEngulfingCandle = abs(open - close) * 100 / abs(high - low) <= engulfingThreshold
// Bullish and Bearish Engulfing Conditions
bullEngulfing = uptrend and close[1] < open[1] and close > open[1] and not isBoringCandle and not isEngulfingCandle
bearEngulfing = downtrend and close[1] > open[1] and close < open[1] and not isBoringCandle and not isEngulfingCandle
// Stop Loss, Take Profit, and Entry Price Calculation
bullStop = close + (stopLevel * syminfo.mintick)
bearStop = close - (stopLevel * syminfo.mintick)
bullSL = low
bearSL = high
bullTP = bullStop + (bullStop - low)
bearTP = bearStop - (high - bearStop)
// Entry Conditions
enterLong = bullEngulfing and uptrend
enterShort = bearEngulfing and downtrend
// Exit Conditions
exitLong = crossover(close, bullTP) or crossover(close, bullSL)
exitShort = crossover(close, bearTP) or crossover(close, bearSL)
// Check if exit conditions are met by the next candle
exitLongNextCandle = exitLong and (crossover(close[1], bullTP[1]) or crossover(close[1], bullSL[1]))
exitShortNextCandle = exitShort and (crossover(close[1], bearTP[1]) or crossover(close[1], bearSL[1]))
// Strategy Execution
strategy.entry("Buy", strategy.long, when=enterLong )
strategy.entry("Sell", strategy.short, when=enterShort )
// Exit Conditions for Long (Buy) Positions
if (bullEngulfing and not na(bullTP) and not na(bullSL))
strategy.exit("Exit Long", from_entry="Buy", stop=bullSL, limit=bullTP)
// Exit Conditions for Short (Sell) Positions
if (bearEngulfing and not na(bearTP) and not na(bearSL))
strategy.exit("Exit Short", from_entry="Sell", stop=bearSL, limit=bearTP)
// Plot Shapes and Labels
plotshape(bullEngulfing, style=shape.triangleup, location=location.abovebar, color=color.green)
plotshape(bearEngulfing, style=shape.triangledown, location=location.abovebar, color=color.red)
// Determine OP, SL, and TP
plot(bullEngulfing ? bullStop : na, title="Bullish Engulfing stop", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bearEngulfing ? bearStop : na, title="Bearish Engulfing stop", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bullEngulfing ? bullSL : na, title="Bullish Engulfing SL", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bearEngulfing ? bearSL : na, title="Bearish Engulfing SL", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bullEngulfing ? bullTP : na, title="Bullish Engulfing TP", color=color.green, linewidth=3, style=plot.style_linebr)
plot(bearEngulfing ? bearTP : na, title="Bearish Engulfing TP", color=color.green, linewidth=3, style=plot.style_linebr)
label.new(bullEngulfing ? bar_index : na, bullSL, text="SL: " + tostring(bullSL), color=color.red, textcolor=color.white, style=label.style_labelup, size=size.tiny)
label.new(bearEngulfing ? bar_index : na, bearSL, text="SL: " + tostring(bearSL), color=color.red, textcolor=color.white, style=label.style_labeldown, size=size.tiny)
label.new(bullEngulfing ? bar_index : na, bullTP, text="TP: " + tostring(bullTP), color=color.green, textcolor=color.white, style=label.style_labeldown, size=size.tiny)
label.new(bearEngulfing ? bar_index : na, bearTP, text="TP: " + tostring(bearTP), color=color.green, textcolor=color.white, style=label.style_labelup, size=size.tiny)
|
ProfitView Strategy Template | https://www.tradingview.com/script/CFOy39oC-ProfitView-Strategy-Template/ | Daveatt | https://www.tradingview.com/u/Daveatt/ | 157 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//@strategy_alert_message {{strategy.order.alert_message}}
// # ========================================================================= #
// # | SAMPLE INDICATOR |
// # ========================================================================= #
// Sample script to plug to the strategy template
////@version=5
//indicator(title='Moving Average Cross', shorttitle='Moving Average Cross', overlay=true, precision=6, max_labels_count=500, max_lines_count=500)
// type_ma1 = input.string(title='MA1 type', defval='SMA', options=['RMA', 'SMA', 'EMA'])
// length_ma1 = input(10, title='[ALL but VWAP] MA1 length')
// type_ma2 = input.string(title='MA2 type', defval='SMA', options=['RMA', 'SMA', 'EMA'])
// length_ma2 = input(100, title='[ALL but VWAP] MA2 length')
// // MA
// f_ma(smoothing, src, length) =>
// rma_1 = ta.rma(src, length)
// sma_1 = ta.sma(src, length)
// ema_1 = ta.ema(src, length)
// iff_1 = smoothing == 'EMA' ? ema_1 : src
// iff_2 = smoothing == 'SMA' ? sma_1 : iff_1
// smoothing == 'RMA' ? rma_1 : iff_2
// MA1 = f_ma(type_ma1, close, length_ma1)
// MA2 = f_ma(type_ma2, close, length_ma2)
// // buy and sell conditions
// buy = ta.crossover(MA1, MA2)
// sell = ta.crossunder(MA1, MA2)
// plot(MA1, color=color.new(color.green, 0), title='Plot MA1', linewidth=3)
// plot(MA2, color=color.new(color.red, 0), title='Plot MA2', linewidth=3)
// plotshape(buy, title='LONG SIGNAL', style=shape.circle, location=location.belowbar, color=color.new(color.green, 0), size=size.normal)
// plotshape(sell, title='SHORT SIGNAL', style=shape.circle, location=location.abovebar, color=color.new(color.red, 0), size=size.normal)
// /////////////////////////// SIGNAL FOR STRATEGY /////////////////////////
// Signal = buy ? 1 : sell ? -1 : 0
// plot(Signal, title='🔌Connector🔌', display = display.data_window)
// # ========================================================================= #
// # | SAMPLE INDICATOR |
// # ========================================================================= #
SCRIPT_NAME = "ProfitView Strategy Template"
strategy(SCRIPT_NAME,
overlay= true,
process_orders_on_close = true,
calc_on_every_tick = true,
pyramiding = 1,
initial_capital = 100000,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 1,
commission_type = strategy.commission.percent,
commission_value = 0.075,
slippage = 1
)
_ext_connector = input.source(close, title = "External Connector", group = "Connected Indicator Source", tooltip = "Select the indicator you want to connect to this strategy.\nThis indicator will be used to trigger the strategy orders.")
ext_connector = nz(_ext_connector)
// # ========================================================================= #
// # | BOT |
// # ========================================================================= #
//pineconnector_licence_ID = input.string(title = "Licence ID", defval = "123456789", group = "ProfitView", tooltip = "Insert your ProfitView Licence ID here\nYou can find it in your ProfitView account webpage")
//use_multiple_account = input.bool(false, title = "Use Multiple Account?", group = "ProfitView General Settings", tooltip = "Use this option if you want to use multiple accounts with the same strategy.\nYou can find the account ID in your ProfitView account page from the Chrome extension")
account_name = input.string(title = "Account Name", defval = "*", group = "ProfitView General Settings", tooltip = "Insert your account name here\nYou can find it in your ProfitView account page from the Chrome extension")
exchange_name = input.string("bitmex-testnet", title = "Exchange Alias", group = "ProfitView General Settings", tooltip = "Insert the ProfitView exchange ID here\nExample: 'bitmex' or 'bitmex-testnet' or 'binance-ft'")
symbol_name = input.string("xbtusd", title = "Symbol Alias", group = "ProfitView General Settings", tooltip = "Insert the ProfitView symbol ID here\nExamples: 'BTCUSDT' or 'ETHBTC' or 'XBTUSD'")
trading_mode = input.string("Spot", title = "Trading Mode", options = ["Spot", "Margin"], group = "ProfitView General Settings", tooltip = "Select the trading mode you want to use for this strategy")
delay_between_orders = input.int(2, minval = 0, title = "Delay Between Commands (seconds)", group = "ProfitView General Settings", tooltip = "Set the delay between orders in seconds.\nThis is useful to prevent the BOT from opening too many orders in a short period of time.")
nb_orders_per_direction = input.int(1, minval = 1, title = "Number of Orders per Direction", group = "ProfitView General Settings", tooltip = "Set the number of orders per direction.\nThis is useful to prevent the BOT from opening too many orders in a short period of time.")
use_drawdown_BOT_halt = input.bool(false, title = "Use Drawdown BOT Halt?", group = "BOT Risk Management", tooltip = "Halt the BOT if the max drawdown value is reached")
max_drawdown_mode = input.string("%", title = "Mode", options = ["%", "USD"], group = "BOT Risk Management", inline = "max drawdown")
max_drawdown_value = input.float(20, minval = 0, title = "Max Drawdown", group = "BOT Risk Management", inline = "max drawdown")
use_max_consecutive_days_BOT_halt = input.bool(false, title = "Use Max Consecutive Days BOT Halt?", group = "BOT Risk Management", inline = "max consecutive days", tooltip = "Halt the BOT if the max consecutive losing days value is reached")
nb_max_consecutive_days = input.int(3, minval = 0, title = "Max Consecutive Days", group = "BOT Risk Management", inline = "max consecutive days")
use_max_losing_streak = input.bool(false, title = "Use Max Losing Streak?", group = "BOT Risk Management", inline = "max losing streak", tooltip = "To prevent the BOT from taking too many losses in a row")
maxLosingStreak = input.int(15, title="Max Losing Streak Length", minval=1, group = "BOT Risk Management", inline = "max losing streak")
use_margin_call = input.bool(false, title = "Use Margin Call?", group = "BOT Risk Management", inline = "margin call", tooltip = "Margin longs/shorts need to be different than 0% from the Properties tab.\nExit when we're X% away from a margin call, to prevent it")
margin_call_value = input.float(10, minval = 0, title = "Margin Call (%)", group = "BOT Risk Management", inline = "margin call")
use_close_BOT_total_loss = input.bool(false, title = "Use Close BOT Total Loss?", group = "BOT Risk Management", inline = "close BOT total loss", tooltip = "Close all the trades + halt BOT if the total loss is reached")
total_loss_value = input.float(-5000, maxval = 0, title = "Total Loss ($)", group = "BOT Risk Management", inline = "close BOT total loss")
use_intraday_losses_BOT_halt = input.bool(false, title = "Use Intraday Losses BOT Halt?", group = "Intraday BOT Risk Management")
intraday_loss_value = input.string("%", title = "Mode", options = ["%", "USD"], group = "Intraday BOT Risk Management", inline = "intraday losses")
nb_intraday_losses = input.int(3, minval = 0, title = "Max Intraday Losses (%)", group = "Intraday BOT Risk Management", inline = "intraday losses")
use_limit_intraday_trades = input.bool(false, title = "Use Limit Intraday Trades?", group = "Intraday BOT Risk Management", inline = "max intraday trades")
nb_max_intraday_trades = input.int(5, minval = 0, title = "Max Intraday Trades", group = "Intraday BOT Risk Management", inline = "max intraday trades")
use_restart_intraday_BOT = input.bool(false, title = "Use Restart Intraday EA?", group = "Intraday BOT Risk Management", inline = "restart intraday EA", tooltip = "Restart the BOT at the first bar of next day if it has been stoppped with an intraday risk management safeguard")
//use_spread_filter = input.bool(false, title = "Use Spread Filter?", group = "BOT Spread Filter", inline = "spread filter", tooltip = "Enter the position only if the spread is equal or less than the specified value in pips.")
//spread_value = input.float(3.5, minval = 0, title = "Spread Value (pips)", group = "BOT Spread Filter", inline = "spread filter")
//use_acc_filter = input.bool(false, title = "Use Account Filter?", group = "BOT Account Filter", inline = "account filter", tooltip = "Enter the position only if the account requirement is met.\nBOT Options: Account Balance, Account Equity, Margin Percentage and Free Margin")
//accfilter_value = input.float(1000, minval = 0, title = "Account Balance/Equity (USD)", group = "BOT Account Filter", inline = "account filter")
// # ========================================================================= #
// # | Retries |
// # ========================================================================= #
use_retries = input.bool(false, title = "Use Retries?", group = "Retries", tooltip = "Retry to open the order if it fails")
nb_retries = input.int(3, minval = 0, title = "Number of Retries", group = "Retries", tooltip = "Set the number of retries")
// # ========================================================================= #
// # | Order Types |
// # ========================================================================= #
var string ORDER_TYPE_TOOLTIP = 'Limit: Place order on the books waiting to be filled for price p\n
Market: Fill order immediately for whatever prices are available (p is ignored – slippage!)\n
FOK: Fill Or Kill orders will be cancelled if they cannot be filled immediately completely\n
IOC: Immediate Or Cancel orders can be partially filled – any remaining portion is cancelled\n
Post: If any part of the order would be filled immediately (for price p) the whole order will be cancelled\n
Day (BitMEX / OANDA): "Good For Day", will be cancelled at 5pm EDT (New York)\n
Settle (Kraken): Settle position(s) at the original order price Click here for more info from Kraken!\n
Open / Close: Can be used together with c=order for specific order types – open targets limit/opening orders, close targets stops/closing orders'
order_type_mode = input.string("Market", title = "Order Type", options = ["Market", "Limit", "Stop", "FOK", "IOC", "Post", "Day", "Settle", "Open/Close"], group = "Order Types", tooltip = ORDER_TYPE_TOOLTIP)
order_type_price = input.float(10, title = "Price", group = "Order Types",
tooltip = "With 'Limit', below the current market price for a buy - above the current market price for a sell\nWith 'Stop', above the current market price for a buy - below the current market price for a sell\n")
// # ========================================================================= #
// # | Position Size |
// # ========================================================================= #
pos_type = input.string("Contracts", title = "Position Type", options = ["Contracts", "Percent", "Currency"], group = "Position Size", tooltip = "Select the position type you want to use for this strategy")
pos_size = input.float(3, minval = 0, maxval = 100, title = "Position Size", group = "Position Size", tooltip = "Required to specify the position size here for ProfitView to work properly")
// # ========================================================================= #
// # | Leverage |
// # ========================================================================= #
margin_type = input.string("Isolated", title = "Margin Type", options = ["Isolated", "Crossed"], group = "Leverage", tooltip = "Select the margin type you want to use for this strategy")
leverage_value = input.float(1, minval = 0, title = "Value", group = "Leverage", tooltip = "Required to specify the leverage here for ProfitView to work properly")
use_hedge_mode = input.bool(false, title = "Use Hedge Mode?", group = "Leverage", tooltip = "Use this option if you want to use the Hedge mode for this strategy")
// # ========================================================================= #
// # | Sessions |
// # ========================================================================= #
use_session = input.bool(false, title='Use Sessions ?', group='Session', tooltip = "Limit the trades between a start and end time")
Session = input.session(title='Trading Session', defval='0000-2345', group='Session')
sess_timezone = input.string('UTC-5', title='Session Timezone', group='Session')
// # ========================================================================= #
// # | Dates |
// # ========================================================================= #
// ————— Syntax coming from https://www.tradingview.com/blog/en/new-parameter-for-date-input-added-to-pine-21812/
use_date = input.bool(false, title='Use Date Filter ?', group='Date', tooltip = "Limit the trades between a start and end date")
i_startTime = input.time(defval=timestamp('01 Jan 2019 13:30 +0000'), title='Start Time', group='Date')
i_endTime = input.time(defval=timestamp('30 Dec 2021 23:30 +0000'), title='End Time', group='Date')
TradeDateIsAllowed() =>
use_date ? time >= i_startTime and time <= i_endTime : true
// # ========================================================================= #
// # | Direction |
// # ========================================================================= #
strat_direction = input.string(strategy.direction.all, title = "Direction", options = [strategy.direction.all, strategy.direction.long, strategy.direction.short], group = "Trades Direction", tooltip = "To specify in which market direction the strategy is allowed to open positions.")
//use_close_opposite = input.bool(false, title = "Close on Opposite Signal?", group = "Close on Opposite", tooltip = "Close the position if 1 or more MACDs become bearish (for longs) or bullish (for shorts)")
// # ========================================================================= #
// # | General SL/TP |
// # ========================================================================= #
sl_tp_mode = input.string("pips", title = "Mode", options = ["pips", "%"], group = "General SL/TP", tooltip = "Select the mode you want to use for the SL/TP values\nSelect the same mode in the ProfitView BOT on Metatrader")
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
use_sl = input.bool(true, title = "Use Stop Loss?", group = "Stop Loss")
sl_value = input.float(40, minval = 0, title = "Value", group = "Stop Loss", inline = "stoploss")// * 0.01
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
use_tsl = input.bool(false, title = "Use Trailing Stop Loss?", group = "Trailing Stop Loss")
tsl_input_value = input.float(10, minval = 0, title = "Value", group = "Trailing Stop Loss")
// # ========================================================================= #
// # | Take Profit |
// # ========================================================================= #
use_tp1 = input.bool(true, title = "Use Take Profit 1?", group = "Take Profit 1")
tp1_value = input.float(30, minval = 0, title = "Value", group = "Take Profit 1")
tp1_qty = 100//input.float(50, minval = 0, title = "Quantity (%)", group = "Take Profit 1")
//use_tp2 = input.bool(true, title = "Use Take Profit 2?", group = "Take Profit 2")
//tp2_value = input.float(50, minval = 0, title = "Value", group = "Take Profit 2")
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
use_sl_be = input.bool(false, title = "Use Stop Loss to Breakeven Mode?", group = "Break Even")
sl_be_value = input.float(30, step = 0.1, minval = 0, title = "Value (pips)", group = "Break Even", inline = "breakeven")
sl_be_offset = input.int(1, step = 1, minval = 0, title = "Offset (pips)", group = "Break Even", tooltip = "Set the SL at BE price +/- offset value")
// # ========================================================================= #
// # | Telegram/Discord |
// # ========================================================================= #
NOTIFY_TOOLTIP = "0, 1: Disable/suppress or enable/force built-in notifications for this command\n2: Force built-in notifications including balance info for this command\n3: Force built-in notifications including balance and account info for this command\n4: Force built-in notifications including balance, account and leverage info for this command\n"
disable_custom_notifications = input.bool(false, title = "Disable Custom Notifications?", group = "Custom Notifications", tooltip = "Disable the custom notifications for this strategy")
use_telegram = input.bool(false, title = "Use Telegram?", group = "Telegram", tooltip = "Send the alerts to Telegram", inline = "telegram")
//notify_telegram_int = input.int(0, minval = 0, maxval=4, title= "", group = "Telegram", inline = "telegram", tooltip = NOTIFY_TOOLTIP)
telegram_txt = input.text_area("Exchange: {exchange}, Price: {price}", title = "Telegram Notifications Text", group = "Telegram", tooltip = "Documentation: https://wiki.profitview.app/syntax/notify")
use_discord = input.bool(false, title = "Use Discord?", group = "Discord", tooltip = "Send the alerts to Discord", inline = "discord")
notify_discord_int = input.int(0, minval = 0, maxval=4, title= "", group = "Discord", inline = "discord", tooltip = NOTIFY_TOOLTIP)
discord_txt = input.text_area("Exchange: {exchange}, Price: {price}", title = "Discord Notifications Text", group = "Discord", tooltip = "Documentation: https://wiki.profitview.app/syntax/notify")
use_email = input.bool(false, title = "Use Email?", group = "Email", tooltip = "Send the alerts to Email")
//notify_email_int = input.int(1, minval = 0, maxval=4, title= "", group = "Email", tooltip = NOTIFY_TOOLTIP)
email_subject = input.string("ProfitView Alert", title = "Email Subject", group = "Email", tooltip = "Set the email subject")
//email_txt = input.text_area("Exchange: {exchange}, Price: {price}", title = "Email Notifications Text", group = "Email", tooltip = "Documentation: https://wiki.profitview.app/syntax/notify")
use_ifttt = input.bool(false, title = "Use IFTTT?", group = "IFTTT", tooltip = "Send the alerts to IFTTT", inline = "ifttt")
//notify_ifttt_int = input.int(0, minval = 0, maxval=4, title= "", group = "IFTTT", inline = "ifttt", tooltip = NOTIFY_TOOLTIP)
ifttt_txt = input.text_area("Exchange: {exchange}, Price: {price}", title = "IFTTT Notifications Text", group = "IFTTT", tooltip = "Documentation: https://wiki.profitview.app/syntax/notify")
use_twilio = input.bool(false, title = "Use Twilio?", group = "Twilio", tooltip = "Send the alerts to Twilio", inline = "twilio")
//notify_twilio_int = input.int(0, minval = 0, maxval=4, title= "", group = "Twilio", inline = "twilio", tooltip = NOTIFY_TOOLTIP)
twilio_txt = input.text_area("Exchange: {exchange}, Price: {price}", title = "Twilio Notifications Text", group = "Twilio", tooltip = "Documentation: https://wiki.profitview.app/syntax/notify")
use_log = input.bool(false, title = "Use Log?", group = "Log", tooltip = "Send the alerts to the ProfitView Logger")
log_txt = input.text_area("Exchange: {exchange}, Price: {price}", title = "Log Notifications Text", group = "Log", tooltip = "Documentation: https://wiki.profitview.app/syntax/notify")
// # ========================================================================= #
// # |Bars Colouring |
// # ========================================================================= #
clrBars = input.bool(true, title='Colour Candles to Trade Order state', group='Coloring')
// # ========================================================================= #
// # | Pine Utilities |
// # ========================================================================= #
// Source: https://www.tradingview.com/pine-script-reference/v5/#var_strategy.margin_liquidation_price
changePercent(v1, v2) =>
float result = (v1 - v2) * 100 / math.abs(v2)
// Source: https://www.tradingview.com/pine-script-reference/v5/#fun_strategy.closedtrades.profit
// Calculate sum gross profit from all closed trades by adding the difference between gross profit and commission.
SumGrossProfitClosedTrades() =>
sumGrossProfit = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
sumGrossProfit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
result = nz(sumGrossProfit)
get_pip_size() =>
float _pipsize = 1.
if syminfo.type == "forex"
_pipsize := (syminfo.mintick * (str.contains(syminfo.ticker, "JPY") ? 100 : 10))
else if str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "XAG")
_pipsize := 0.1
_pipsize
// # ========================================================================= #
// # | Calculations |
// # ========================================================================= #
bull = ext_connector == 1 and barstate.isconfirmed
bear = ext_connector == -1 and barstate.isconfirmed
signal_candle = bull or bear
signal_bull = bull and strategy.position_size[1] <= 0
signal_bear = bear and strategy.position_size[1] >= 0
entryLongPrice = ta.valuewhen(signal_bull, close, 0)
entryShortPrice = ta.valuewhen(signal_bear, close, 0)
plot(strategy.position_size > 0 ? entryLongPrice : na, title = "Long Entry Price", color = color.green, linewidth = 2, style = plot.style_circles)
plot(strategy.position_size < 0 ? entryShortPrice : na, title = "Short Entry Price", color = color.red, linewidth = 2, style = plot.style_circles)
var label entry_label = na
if barstate.islast
if strategy.position_size > 0
entry_label := label.new(x = bar_index + 5, y = entryLongPrice, text = "Long Entry: " + str.tostring(entryLongPrice, format.mintick), style = label.style_label_left, color = color.green, size = size.normal)
else if strategy.position_size < 0
entry_label := label.new(x = bar_index + 5, y = entryShortPrice, text = "Short Entry: " + str.tostring(entryShortPrice, format.mintick), style = label.style_label_left, color = color.red, size = size.normal)
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
var float final_SL_Long = 0.
var float final_SL_Short = 0.
var float final_SL_Long_Pineconnector = 0.
var float final_SL_Short_Pineconnector = 0.
if use_sl
if signal_bull
final_SL_Long := (sl_tp_mode == "pips") ? entryLongPrice - (sl_value * get_pip_size()) : entryLongPrice * (1 - (sl_value * 0.01))
else if signal_bear
final_SL_Short := (sl_tp_mode == "pips") ? entryShortPrice + (sl_value * get_pip_size()) : entryShortPrice * (1 + (sl_value * 0.01))
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
var MaxReached = 0.0
if signal_candle[1]
MaxReached := strategy.position_size > 0 ? high : low
MaxReached := strategy.position_size > 0
? math.max(nz(MaxReached, high), high)
: strategy.position_size < 0 ? math.min(nz(MaxReached, low), low) : na
if use_tsl and use_sl
if strategy.position_size > 0
stopValue = MaxReached - (tsl_input_value * get_pip_size())
final_SL_Long := math.max(stopValue, final_SL_Long[1])
else if strategy.position_size < 0
stopValue = MaxReached + (tsl_input_value * get_pip_size())
final_SL_Short := math.min(stopValue, final_SL_Short[1])
// # ========================================================================= #
// # | Take Profit 1 |
// # ========================================================================= #
var float final_TP1_Long = 0.
var float final_TP1_Short = 0.
if use_tp1
if signal_bull
final_TP1_Long := (sl_tp_mode == "pips") ? entryLongPrice + (tp1_value * get_pip_size()) : entryLongPrice * (1 + (tp1_value * 0.01))
else if signal_bear
final_TP1_Short := (sl_tp_mode == "pips") ? entryShortPrice - (tp1_value * get_pip_size()) : entryShortPrice * (1 - (tp1_value * 0.01))
plot(use_tp1 and strategy.position_size > 0 ? final_TP1_Long : na, title = "TP1 Long", color = color.aqua, linewidth=2, style=plot.style_linebr)
plot(use_tp1 and strategy.position_size < 0 ? final_TP1_Short : na, title = "TP1 Short", color = color.blue, linewidth=2, style=plot.style_linebr)
var label tp1_label = na
if barstate.islast and use_tp1
if strategy.position_size > 0
tp1_label := label.new(x = bar_index + 5, y = final_TP1_Long, text = "TP1: " + str.tostring(final_TP1_Long, format.mintick), style = label.style_label_left, color = color.aqua, size = size.normal)
else if strategy.position_size < 0
tp1_label := label.new(x = bar_index + 5, y = final_TP1_Short, text = "TP1: " + str.tostring(final_TP1_Short, format.mintick), style = label.style_label_left, color = color.blue, size = size.normal)
// # ========================================================================= #
// # | Take Profit 2 |
// # ========================================================================= #
//var float final_TP2_Long = 0.
//var float final_TP2_Short = 0.
//if use_tp2 and tp1_qty != 100
// if signal_bull
// final_TP2_Long := (sl_tp_mode == "pips") ? entryLongPrice + (tp2_value * get_pip_size()) : entryLongPrice * (1 + (tp2_value * 0.01))
// else if signal_bear
// final_TP2_Short := (sl_tp_mode == "pips") ? entryShortPrice - (tp2_value * get_pip_size()) : entryShortPrice * (1 - (tp2_value * 0.01))
//plot(use_tp2 and strategy.position_size > 0 and tp1_qty != 100 ? final_TP2_Long : na, title = "TP2 Long", color = color.orange, linewidth=2, style=plot.style_linebr)
//plot(use_tp2 and strategy.position_size < 0 and tp1_qty != 100 ? final_TP2_Short : na, title = "TP2 Short", color = color.white, linewidth=2, style=plot.style_linebr)
//var label tp2_label = na
//if barstate.islast and use_tp2
// if strategy.position_size > 0 and tp1_qty != 100
// tp2_label := label.new(x = bar_index + 5, y = final_TP2_Long, text = "TP2: " + str.tostring(final_TP2_Long, format.mintick), style = label.style_label_left, color = color.orange, size = size.normal)
// else if strategy.position_size < 0 and tp1_qty != 100
// tp2_label := label.new(x = bar_index + 5, y = final_TP2_Short, text = "TP2: " + str.tostring(final_TP2_Short, format.mintick), style = label.style_label_left, color = color.white, size = size.normal)
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
var bool SL_BE_REACHED = false
// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
sumProfit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
current_profit = tradeOpenPL()// * get_pip_size()
current_long_profit = (close - entryLongPrice) / (syminfo.mintick * 10)
current_short_profit = (entryShortPrice - close) / (syminfo.mintick * 10)
plot(current_short_profit, title = "Current Short Profit", display = display.data_window)
plot(current_long_profit, title = "Current Long Profit", display = display.data_window)
if use_sl_be
if strategy.position_size > 0
if not SL_BE_REACHED
if current_long_profit >= sl_be_value
final_SL_Long := entryLongPrice + (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
else if strategy.position_size < 0
if not SL_BE_REACHED
if current_short_profit >= sl_be_value
final_SL_Short := entryShortPrice - (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
plot(use_sl and strategy.position_size > 0 ? final_SL_Long : na, title = "SL Long", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
plot(use_sl and strategy.position_size < 0 ? final_SL_Short : na, title = "SL Short", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
var label sl_label = na
if barstate.islast and use_sl
if strategy.position_size > 0
sl_label := label.new(x = bar_index + 5, y = final_SL_Long, text = "SL: " + str.tostring(final_SL_Long, format.mintick), style = label.style_label_left, color = color.fuchsia, size = size.normal)
else if strategy.position_size < 0
sl_label := label.new(x = bar_index + 5, y = final_SL_Short, text = "SL: " + str.tostring(final_SL_Short, format.mintick), style = label.style_label_left, color = color.fuchsia, size = size.normal)
// # ========================================================================= #
// # | Sessions |
// # ========================================================================= #
// Session calculations
// The BarInSession function returns true when
// the current bar is inside the session parameter
BarInSession(sess) =>
time(timeframe.period, sess, sess_timezone) != 0
in_session = BarInSession(Session)
okToTradeInSession = use_session ? in_session : true
new_session = in_session and not in_session[1]
bgcolor(color=use_session and BarInSession(Session)[1] ? color.new(color.green, 85) : na, title='Trading Session')
// # ========================================================================= #
// # | ProfitView Alerts Message |
// # ========================================================================= #
string entry_long_limit_alert_message = ""
string entry_long_TP1_alert_message = ""
string entry_long_TP2_alert_message = ""
var float tp1_qty_perc = tp1_qty / 100
var string first_line_command = ""
var string pyr_line_command = ""
var string bull_command = ""
var string bear_command = ""
ignore_pyr_orders = "check=pos side=[side] iffound=abort\n"
// Executing this only once at the beginning of the strategy
if barstate.isfirst
// First Line
first_line_command := "a=" + account_name + " e=" + exchange_name + " s=" + symbol_name + "\n"
// Pyramiding
pyr_line_command := nb_orders_per_direction ? ignore_pyr_orders + "\n" : ""
// Spot or Margin
if trading_mode == "Spot"
bull_command := bull_command + " side=buy "
bear_command := bear_command + " side=sell "
else if trading_mode == "Margin"
bull_command := bull_command + " side=long "
bear_command := bear_command + " side=short "
// Order Type
if order_type_mode == "Market"
bull_command := bull_command + "type=market "
bear_command := bear_command + "type=market "
else if order_type_mode == "Limit"
bull_command := bull_command + "type=limit p=" + str.tostring(order_type_price) + " "
bear_command := bear_command + "type=limit p=-" + str.tostring(order_type_price) + " "
else if order_type_mode == "Stop"
bull_command := bull_command + "type=limit p=-" + str.tostring(order_type_price) + " "
bear_command := bear_command + "type=limit p=" + str.tostring(order_type_price) + " "
else if order_type_mode == "FOK"
bull_command := bull_command + "type=fok "
bear_command := bear_command + "type=fok "
else if order_type_mode == "IOC"
bull_command := bull_command + "type=ioc "
bear_command := bear_command + "type=ioc "
else if order_type_mode == "Post"
bull_command := bull_command + "type=post "
bear_command := bear_command + "type=post "
else if order_type_mode == "Day"
bull_command := bull_command + "type=day "
bear_command := bear_command + "type=day "
else if order_type_mode == "Settle"
bull_command := bull_command + "type=settle "
bear_command := bear_command + "type=settle "
else if order_type_mode == "Open/Close"
bull_command := bull_command + "type=open/close "
bear_command := bear_command + "type=open/close "
// Quantity
if pos_type == "Contracts"
bull_command := bull_command + "qty=" + str.tostring(pos_size) + " "
bear_command := bear_command + "qty=" + str.tostring(pos_size) + " "
else if pos_type == "Percent"
bull_command := bull_command + "qty=" + str.tostring(pos_size) + "% "
bear_command := bear_command + "qty=" + str.tostring(pos_size) + "% "
else if pos_type == "Currency"
bull_command := bull_command + "qty=" + str.tostring(pos_size) + " unit=currency "
bear_command := bear_command + "qty=" + str.tostring(pos_size) + " unit=currency "
// Leverage
if margin_type == "Isolated"
bull_command := bull_command + "leverage=" + str.tostring(leverage_value) + " mt=isolated "
bear_command := bear_command + "leverage=" + str.tostring(leverage_value) + " mt=isolated "
else if margin_type == "Crossed"
bull_command := bull_command + "leverage=" + str.tostring(leverage_value) + " mt=crossed "
bear_command := bear_command + "leverage=" + str.tostring(leverage_value) + " mt=crossed "
// Hedge Mode
if use_hedge_mode
bull_command := bull_command + "pm=hedge "
bear_command := bear_command + "pm=hedge "
// Retry
if use_retries
bull_command := bull_command + "error=abort retries=" + str.tostring(nb_retries) + " "
bear_command := bear_command + "error=abort retries=" + str.tostring(nb_retries) + " "
// Notifications
count_notifications = (use_telegram ? 1 : 0) + (use_discord ? 1 : 0) + (use_email ? 1 : 0) + (use_ifttt ? 1 : 0) + (use_twilio ? 1 : 0) + (use_log ? 1 : 0)
if count_notifications > 0
bull_command := bull_command + 'notify=' + (disable_custom_notifications ? "0," : "")
bear_command := bear_command + 'notify=' + (disable_custom_notifications ? "0," : "")
if count_notifications > 1
bull_command := bull_command + ','
bear_command := bear_command + ','
if count_notifications > 0
if use_telegram
bull_command := bull_command + 'telegram:"' + telegram_txt + '"'
bear_command := bear_command + 'telegram:"' + telegram_txt + '"'
if use_email
bull_command := bull_command + 'email:' + ':"' + email_subject + '"'
bear_command := bear_command + 'email:' + ':"' + email_subject + '"'
if use_discord
bull_command := bull_command + 'discord:' + str.tostring(notify_discord_int)
bear_command := bear_command + 'discord:' + str.tostring(notify_discord_int)
if use_ifttt
bull_command := bull_command + 'ifttt:"' + ifttt_txt + '"'
bear_command := bear_command + 'ifttt:"' + ifttt_txt + '"'
if use_twilio
bull_command := bull_command + 'twilio:"' + twilio_txt + '"'
bear_command := bear_command + 'twilio:"' + twilio_txt + '"'
if use_log
bull_command := bull_command + 'log:"' + log_txt + '"'
bear_command := bear_command + 'log:"' + log_txt + '"'
//pos_size = math.abs(strategy.position_size)
delay_command = "\ndelay=" + str.tostring(delay_between_orders) + "s "
entry_bull_command = first_line_command
+ pyr_line_command
+ bull_command + "sl=-" + ((sl_tp_mode == "pips") ? str.tostring(final_SL_Long, format.mintick) : str.tostring(final_SL_Long) + "%")
+ " tp=" + ((sl_tp_mode == "pips") ? str.tostring(final_TP1_Long, format.mintick) : str.tostring(final_TP1_Long) + "%")
entry_bear_command = first_line_command
+ pyr_line_command
+ bear_command + "sl=" + ((sl_tp_mode == "pips") ? str.tostring(final_SL_Short, format.mintick) : str.tostring(final_SL_Short) + "%")
+ " tp=" + ((sl_tp_mode == "pips") ? str.tostring(final_TP1_Short, format.mintick) : str.tostring(final_TP1_Short) + "%")
close_opposite_side = first_line_command + "close=[!side] type=market "
close_current_side = first_line_command + "close=[side] type=market "
close_all_pos_market = first_line_command + "close type=market"
halt_BOT_message = "exitall"
restart_BOT_message = "resumeall"
// # ========================================================================= #
// # | BOT global variables |
// # ========================================================================= #
// Flag to remember to stop taking trades if we get too much Rekt :)
var bool HALT_STRATEGY = false
// Orders part
longs_opened = strategy.position_size > 0
shorts_opened = strategy.position_size < 0
trades_opened = strategy.position_size != 0
longs_opened_in_session = use_session and longs_opened
shorts_opened_in_session = use_session and shorts_opened
// # ========================================================================= #
// # | Risk Management |
// # ========================================================================= #
strategy.risk.max_drawdown(use_drawdown_BOT_halt ? max_drawdown_value : 100, use_drawdown_BOT_halt ? (max_drawdown_mode == "%" ? strategy.percent_of_equity : strategy.cash) : strategy.percent_of_equity, halt_BOT_message)
strategy.risk.max_intraday_loss(use_intraday_losses_BOT_halt and timeframe.isintraday ? nb_intraday_losses : 999999, use_intraday_losses_BOT_halt and timeframe.isintraday ? (intraday_loss_value == "%" ? strategy.percent_of_equity : strategy.cash) : strategy.percent_of_equity, halt_BOT_message)
strategy.risk.max_cons_loss_days(use_max_consecutive_days_BOT_halt ? nb_max_consecutive_days : 999999, halt_BOT_message)
strategy.risk.max_intraday_filled_orders(use_limit_intraday_trades and timeframe.isintraday ? nb_max_intraday_trades : 999999, halt_BOT_message)
// Restart the BOT if it's an intraday chart and it has been paused due to intraday max losses or intraday max filled orders
// test if it's a new day
newDay = dayofmonth != dayofmonth[1]
bgcolor(use_restart_intraday_BOT and newDay and timeframe.isintraday ? color.aqua : na, title = "Restart BOT at the first candle of the day")
if use_restart_intraday_BOT and newDay and timeframe.isintraday
alert(restart_BOT_message, alert.freq_once_per_bar_close)
// # ========================================================================= #
// # | Streak Management |
// # ========================================================================= #
// Source: https://www.tradingcode.net/tradingview/losing-streak/
// Check if there's a new losing trade that increased the streak
newLoss = strategy.losstrades > strategy.losstrades[1] and
strategy.wintrades == strategy.wintrades[1] and
strategy.eventrades == strategy.eventrades[1]
// Determine current losing streak length
streakLen = 0
streakLen := if newLoss
nz(streakLen[1]) + 1
else
if strategy.wintrades > strategy.wintrades[1] or
strategy.eventrades > strategy.eventrades[1]
0
else
nz(streakLen[1])
// Show current losing streak and its limit on chart
//plot(use_max_losing_streak ? streakLen : na, style=plot.style_columns, color=streakLen < maxLosingStreak ? color.maroon : color.red, title = "Max Losing Streak")
bgcolor(use_max_losing_streak and newLoss ? color.new(color.red, 80) : na, title = "New Loss Streak")
// Send the message to ProfitView if the losing streak is too long
if streakLen > maxLosingStreak
HALT_STRATEGY := true
alert(halt_BOT_message, alert.freq_once_per_bar_close)
// # ========================================================================= #
// # | Money Management |
// # ========================================================================= #
if use_margin_call
if math.abs(changePercent(close, strategy.margin_liquidation_price)) <= margin_call_value
HALT_STRATEGY := true
strategy.close_all(comment = "Closing all trades to avoid Margin Liq", alert_message = halt_BOT_message)
//alert(halt_BOT_message, alert.freq_once_per_bar_close)
if use_close_BOT_total_loss
strategy_closeprofit = SumGrossProfitClosedTrades()
// Test if the total profit/loss of all close//open positions is below the total loss input value
if (strategy_closeprofit + strategy.openprofit) <= total_loss_value
HALT_STRATEGY := true
strategy.close_all(comment = "Closing all trades to avoid Total Loss", alert_message = halt_BOT_message)
// # ========================================================================= #
// # | Trades Direction |
// # ========================================================================= #
// Didn't work
// strategy.risk.allow_entry_in(strat_direction)
// # ========================================================================= #
// # | Strategy Calls (Entries/SL/TPs) |
// # ========================================================================= #
open_all = strat_direction == strategy.direction.all
open_long = strat_direction != strategy.direction.short
open_short = strat_direction != strategy.direction.long
OK_TO_TRADE = okToTradeInSession and TradeDateIsAllowed() and not HALT_STRATEGY
// Entries
if bull and strategy.position_size <= 0 and open_long and OK_TO_TRADE
alert(close_opposite_side, alert.freq_once_per_bar_close)
strategy.entry("Long", strategy.long, limit = order_type_mode == "Limit" ? order_type_price : na, stop = order_type_mode == "Stop" ? order_type_price : na)
alert(entry_bull_command, alert.freq_once_per_bar_close)
//alert(entry_long_TP2_alert_message, alert.freq_once_per_bar_close)
else if bear and strategy.position_size >= 0 and open_short and OK_TO_TRADE
alert(close_opposite_side, alert.freq_once_per_bar_close)
strategy.entry("Short", strategy.short, limit = order_type_mode == "Limit" ? order_type_price : na, stop = order_type_mode == "Stop" ? order_type_price : na)
alert(entry_bear_command, alert.freq_once_per_bar_close)
//alert(entry_short_TP2_alert_message, alert.freq_once_per_bar_close)
if strategy.position_size[1] > 0
// This handles the SL being hit even after a SL/BE and/or TSL has been triggered
if low <= final_SL_Long and use_sl
strategy.close("Long", alert_message = close_current_side, comment = "SL Long")
else
strategy.exit("Exit TP1 Long", "Long", limit = use_tp1 ? final_TP1_Long : na, comment_profit = "Exit TP Long")
//strategy.exit("Exit TP2 Long", "Long", limit = use_tp2 ? final_TP2_Long : na, comment_profit = "Exit TP2 Long", alert_message = close_long)
else if strategy.position_size[1] < 0
// This handles the SL being hit even after a SL/BE and/or TSL has been triggered
if high >= final_SL_Short and use_sl
strategy.close("Short", alert_message = close_current_side, comment = "SL Short")
else
strategy.exit("Exit TP1 Short", "Short", limit = use_tp1 ? final_TP1_Short : na, comment_profit = "Exit TP Short")
//strategy.exit("Exit TP2 Short", "Short", limit = use_tp2 ? final_TP2_Short : na, comment_profit = "Exit TP2 Short")
// # ========================================================================= #
// # | Bars Colouring |
// # ========================================================================= #
bclr = not clrBars ? na : strategy.position_size == 0 ? color.gray : longs_opened ? color.lime : shorts_opened ? color.red : color.gray
barcolor(bclr, title='Trade State Bar Colouring')
// # ========================================================================= #
// # | Logs |
// # ========================================================================= #
if bull and strategy.position_size <= 0
log.info(entry_bull_command)
else if bear and strategy.position_size >= 0
log.info(entry_bear_command)
// # ========================================================================= #
// # | Reset Variables |
// # ========================================================================= #
if (strategy.position_size > 0 and strategy.position_size[1] <= 0)
or (strategy.position_size < 0 and strategy.position_size[1] >= 0)
//is_TP1_REACHED := false
SL_BE_REACHED := false |
RMI-Super LONG | https://www.tradingview.com/script/BXcyCTrJ-RMI-Super-LONG/ | laurenreid2018 | https://www.tradingview.com/u/laurenreid2018/ | 55 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TZack88
//@version=5
strategy('RMI-Super LONG', overlay=true,max_labels_count = 500, margin_long=200)
// ** ---> Inputs ------------- {
var bool positive = false
var bool negative = false
string RSI_group = "RMI Settings"
string mom_group = "Range Vales"
string visual = "Visuals"
int Length = input(14,"RMI Length ",inline = "RMI",group = RSI_group)
int pmom = input(66," Positive above",inline = "rsi1",group =RSI_group )
int nmom = input(30,"Negative below",inline = "rsi1",group =RSI_group )
bool filleshow = input(true,"Show Range MA ",inline = "002",group =visual )
color bull = input(#00bcd4,"",inline = "002",group =visual )
color bear = input(#ff5252,"",inline = "002",group =visual )
float BarRange = high - low
up = ta.rma(math.max(ta.change(close), 0), Length)
down = ta.rma(-math.min(ta.change(close), 0), Length)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
mf = ta.mfi(hlc3, Length)
rsi_mfi = math.avg(rsi,mf)
//------------------- }
bool p_mom = rsi_mfi[1] < pmom and
rsi_mfi > pmom and
rsi_mfi > nmom and
ta.change(ta.ema(close,5)) > 0
bool n_mom = rsi_mfi < nmom and
ta.change(ta.ema(close,5)) < 0
// // ---> Momentums ------------- {
if p_mom
positive:= true
negative:= false
if n_mom
positive:= false
negative:= true
//
method _Band(int len)=>
math.min (ta.atr (len) * 0.3, close * (0.3/100)) [20] /2 * 8
Band = _Band(30)
method rangeMA(float Range,Prd)=>
weight = Range / math.sum(Range, Prd)
sum = math.sum(close * weight, Prd)
tw= math.sum(weight, Prd)
sum / tw
// Calculate the RWMA
rwma = rangeMA(BarRange,20)
// Plotting the RWMA.
colour = positive ? bull : bear
RWMA = positive ? rwma - Band : negative ? rwma + Band : na
alpha = color.new(color.black, 100)
center = plot(filleshow ? RWMA : na, "RRTH", colour, editable = true)
plot(filleshow ? RWMA : na, "RRTH", color.new(colour, 70), 2, editable = true)
plot(filleshow ? RWMA : na, "RRTH", color.new(colour, 80), 3, editable = true)
plot(filleshow ? RWMA : na, "RRTH", color.new(colour, 90), 4, editable = true)
max = RWMA + Band
min = RWMA - Band
top = plot(filleshow ? max: na, "RRTH", alpha)
bottom = plot(filleshow ? min: na, "RRTH", alpha)
fill(top, center, top_value = max, bottom_value = RWMA, bottom_color = color.new(colour, 75), top_color = alpha, editable = true)
fill(center, bottom, top_value = RWMA, bottom_value = min, bottom_color = alpha, top_color = color.new(colour, 75), editable = true)
Barcol = positive ? color.green:color.red
if negative and not negative[1]
label.new(bar_index,max+(Band/2),"",color = color.red,size=size.small)
if positive and not positive[1]
label.new(bar_index,min-(Band/2),"",color = color.green,size=size.small,style= label.style_label_up)
plotcandle(open, high, low, close,color = Barcol,wickcolor = Barcol,bordercolor = Barcol)
barcolor(color = Barcol)
// SPOT Trading Alerts
alertcondition(positive and not positive[1],"BUY")
alertcondition(negative and not negative[1],"SELL")
//Strategy//
magicline = input.int(defval=10, title='magical line MA')
//Visauls inspired by Chris Moody's Slingshot script
//EMA Definitions
smaSlow = ta.sma(close, 30)
smaFast = ta.sma(close, magicline)
//Color definition for Moving Averages
col = smaFast > smaSlow ? color.lime : smaFast < smaSlow ? color.red : color.yellow
//Moving Average Plots and Fill
p1 = plot(smaSlow, title="Slow MA", style=plot.style_line, linewidth=4, color=col)
p2 = plot(smaFast, title="Fast MA", style=plot.style_line, linewidth=2, color=col)
fill(p1, p2, color=color.silver, transp=85)
//Strategy//
float longAmount = input.float(150, "Long Amount")
if positive and smaFast > smaSlow
limitPrice = close
strategy.entry("Enter Long", strategy.long, longAmount, limit = limitPrice)
if negative and not negative[1] and smaFast < smaSlow
strategy.close_all()
|
Renko Strategy | https://www.tradingview.com/script/bl1J6Tfj/ | gsanson66 | https://www.tradingview.com/u/gsanson66/ | 92 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gsanson66
//This code must be applied to a candle graph (not a renko one)
//Interactive Broker fees are applied on this strategy and a realistic slippage is set to simulate real market conditions
//@version=5
strategy("RENKO BACKTESTING", overlay=false, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.18, slippage=3)
//------------------------------TOOL TIPS--------------------------------//
t1 = "Each gain or losse (relative to the previous reference) in an amount equal to this fixed ratio will change quantity of orders."
t2 = "The amount of money to be added to or subtracted from orders once the fixed ratio has been reached."
//------------------------------FUNCTIONS---------------------------------//
//@function Displays text passed to `txt` when called.
debugLabel(txt, color) =>
label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)
//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)
//----------------------------USER INPUTS---------------------------------//
//User inputs to choose the source and the box size
source = input.source(defval=close, title='Base price', group="Technical parameters")
box_size = input.float(title='Box size', defval=10.0, minval=0.00001, group="Technical parameters")
//User inputs to manage money :
//Every gains of fixedRatio we increase orders by increasingOrderAmount and every losses of fixedRatio we decrease the quantity to buy/sell by increasingOrderAmount
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management", tooltip=t1)
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management", tooltip=t2)
//User inputs to choose the backtesting date
startDate = input.time(title="Start Date", defval=timestamp("1 Jan 2013 00:00:00"), group="Backtesting Period")
endDate = input.time(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")
//----------------------------VARIABLES INITIALISATION-------------------------------//
//The var variables are used to store data for the next script execution (next candle)
renko_high = array.new_float(12, na)
renko_low = array.new_float(12, na)
renko_color = array.new_color(12, na)
int array_lenght = na
var float last_ref_high = close
var float last_ref_low = close - box_size
var color last_ref_color = color.lime
bool inRange = na
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95
//----------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION---------------------//
//Checking if the date belong to the range
inRange := inBacktestPeriod(startDate, endDate)
//Checking performances of the strategy to adjust order quantity
if equity > capital_ref + fixedRatio
spread = (equity - capital_ref)/fixedRatio
nb_level = int(spread)
increasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder + increasingOrder
capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
spread = (capital_ref - equity)/fixedRatio
nb_level = int(spread)
decreasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder - decreasingOrder
capital_ref := capital_ref - nb_level*fixedRatio
// Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))
strategy.close_all()
//--------------------------SCRIPT EXECUTION AND CALCULATION---------------------------//
if (source - last_ref_high)/box_size >1
spread = (source - last_ref_high)/box_size
nb_box = int(spread)
for i=1 to nb_box
if i <= 12
array.set(renko_high, i-1, last_ref_high + (i * box_size))
array.set(renko_low, i-1, last_ref_low + (i * box_size))
array.set(renko_color, i-1, color.lime)
else
array.push(renko_high, last_ref_high + (i * box_size))
array.push(renko_low, last_ref_low + (i * box_size))
array.push(renko_color, color.lime)
array_lenght := array.size(renko_high)
//We check the direction of our position
if strategy.position_size<=0 and inRange
//If we were in a short position, we pass to a long position
debugLabel("Long entry order created at " + str.tostring(array.get(renko_high, 0)), color=color.rgb(78, 188, 135))
qty = cashOrder/close
strategy.entry("Long entry", strategy.long, qty)
else if (last_ref_low - source)/box_size >1
spread = (last_ref_low - source)/box_size
nb_box = int(spread)
for i=1 to nb_box
if i <= 12
array.set(renko_high, i-1, last_ref_high - (i * box_size))
array.set(renko_low, i-1, last_ref_low - (i * box_size))
array.set(renko_color, i-1, color.red)
else
array.push(renko_high, last_ref_high - (i * box_size))
array.push(renko_low, last_ref_low - (i * box_size))
array.push(renko_color, color.red)
array_lenght := array.size(renko_high)
//We check the direction of our position
if strategy.position_size>=0 and inRange
debugLabel("Short entry order created at " + str.tostring(array.get(renko_low, 0)), color=color.rgb(252, 81, 81))
qty = cashOrder/close
strategy.entry("Short entry", strategy.short, qty)
else
array.set(renko_high, 0, last_ref_high)
array.set(renko_low, 0, last_ref_low)
array.set(renko_color, 0, last_ref_color)
array_lenght := array.size(renko_high)
for i = (array_lenght-1) to 0
if not na(array.get(renko_high, i))
last_ref_high := array.get(renko_high, i)
break
for i = (array_lenght-1) to 0
if not na(array.get(renko_low, i))
last_ref_low := array.get(renko_low, i)
break
for i = (array_lenght-1) to 0
if not na(array.get(renko_color, i))
last_ref_color := array.get(renko_color, i)
break
//--------------------------PLOTTING BOX ELEMENT----------------------------//
//We plot the first 9 candles and the last 3 candles. Tranding view limit us to plot 64 data by candles. Here we plot 5x12 = 60 data
plotcandle(array.get(renko_high, 0), array.get(renko_high, 0), array.get(renko_low, 0), array.get(renko_low, 0), color=array.get(renko_color, 0))
plotcandle(array.get(renko_high, 1), array.get(renko_high, 1), array.get(renko_low, 1), array.get(renko_low, 1), color=array.get(renko_color, 1))
plotcandle(array.get(renko_high, 2), array.get(renko_high, 2), array.get(renko_low, 2), array.get(renko_low, 2), color=array.get(renko_color, 2))
plotcandle(array.get(renko_high, 3), array.get(renko_high, 3), array.get(renko_low, 3), array.get(renko_low, 3), color=array.get(renko_color, 3))
plotcandle(array.get(renko_high, 4), array.get(renko_high, 4), array.get(renko_low, 4), array.get(renko_low, 4), color=array.get(renko_color, 4))
plotcandle(array.get(renko_high, 5), array.get(renko_high, 5), array.get(renko_low, 5), array.get(renko_low, 5), color=array.get(renko_color, 5))
plotcandle(array.get(renko_high, 6), array.get(renko_high, 6), array.get(renko_low, 6), array.get(renko_low, 6), color=array.get(renko_color, 6))
plotcandle(array.get(renko_high, 7), array.get(renko_high, 7), array.get(renko_low, 7), array.get(renko_low, 7), color=array.get(renko_color, 7))
plotcandle(array.get(renko_high, 8), array.get(renko_high, 8), array.get(renko_low, 8), array.get(renko_low, 8), color=array.get(renko_color, 8))
plotcandle(array.get(renko_high, array_lenght-3), array.get(renko_high, array_lenght-3), array.get(renko_low, array_lenght-3), array.get(renko_low, array_lenght-3), color=array.get(renko_color, array_lenght-3))
plotcandle(array.get(renko_high, array_lenght-2), array.get(renko_high, array_lenght-2), array.get(renko_low, array_lenght-2), array.get(renko_low, array_lenght-2), color=array.get(renko_color, array_lenght-2))
plotcandle(array.get(renko_high, array_lenght-1), array.get(renko_high, array_lenght-1), array.get(renko_low, array_lenght-1), array.get(renko_low, array_lenght-1), color=array.get(renko_color, array_lenght-1))
|
Stx Monthly Trades Profit | https://www.tradingview.com/script/ZOQOd3kU/ | Strambatax | https://www.tradingview.com/u/Strambatax/ | 7 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © 2023 Strambatax (Alessandro Arrabito) - Trading Bot con Ale @arrabyte
// ████████ ██ ██
// ██░██░░░ ██ ██
// ████████░ ██
// ██ ██ ██ ██
// ████████ ██ ██
//@version=5
// Monthly profit displays profits in a grid and allows you to know the gain related to the investment during each month.
// The profit could be computed in terms of gain/trade_cost or as percentage of equity update.
// The table display profit as percentage, the first cell at the top left display the global profit (not percetage) and can be compared
// with net profit reported by tradingview.
// Instruction:
// To insert the snippet in your code get the slice of code that starts below just after the line : "Insert the code below in your strategy"
// Settings:
// Profit: Monthly profit percentage or percentage of equity
// Table position
// This strategy is intended only as a container for the code and for testing the script of the profit table.
// Setting of strategy allows to select the test case for this snippet (percentage grid).
// Money management: not relevant as strategy is a test case.
// This script stand out as take in account the gain of each trade in relation to the capital invested in each trade.
// For example consider the following scenario:
// We have a start capital 10000$, and we invest 1000$ for every trade,
// Without compound interest.
// If in January we gain 50% or our trades investment, the capital become of 10500$, the percentage of equity is 10500/10000 -1 = 5% but trades have gains 50%.
// Consider another scenario. Capital of 1000$ and we invest a fixed amount of 1000$, I know is too risky but is an example, we gain 10% every month.
// After 10 months our capital is of 2000$ and our strategy is perfect as we have the same performance every month. Instead, evaluating the percentage of equity
// we have 10% the first month, 9.9% the second (1200$/1100$ - 1) and 5.26% the tenth month. So seems that strategy degrade with times but this is not true.
// For this reason, to evaluate my strategy I prefer to see the montly return of investment.
// WARNING: The strategy provided with this script is just a test case and allows to see the behavior with different "trades" management, for this reason commission are set to zero.
// At the moment only the trading scenario related to this test cases are tested, for example pyramiding is not handled.
// The test cases are:
// 1 - single entry and single exit;
// 2 - single entry and multiple exits;
// 3 - single entry and switch position;
// The gain could be calculated
strategy(title="Stx Monthly Trades Profit", shorttitle = "monthly profit", overlay=true, default_qty_type=strategy.cash, initial_capital = 5000,
default_qty_value=1000, pyramiding=0, process_orders_on_close=false, commission_type=strategy.commission.percent, commission_value=0)
string testCase = input.string("single_entry_exit", "test case", options = ["single_entry_exit", "single_entry_multiple_exit", "single_entry_switch_position"])
// case 1 single entry long and short
bool longCondition = dayofmonth == 1 and hour == 10 and minute == 0
bool shortCondition = dayofmonth == 10 and hour == 10 and minute == 0
if testCase == "single_entry_exit"
if longCondition and strategy.position_size == 0
strategy.entry("entry_long", strategy.long)
strategy.exit("exit_long", "entry_long", limit=close*(1+0.01), stop=close*(1-0.005))
if shortCondition and strategy.position_size == 0
strategy.entry("entry_short", strategy.short)
strategy.exit("exit_short", "entry_short", limit=close*(1-0.01), stop=close*(1+0.005))
else if testCase == "single_entry_multiple_exit"
if longCondition and strategy.position_size == 0
strategy.entry("entry_long", strategy.long)
strategy.exit("exit_long_1", "entry_long", limit=close*(1+0.01), stop=close*(1-0.005), qty_percent=50)
strategy.exit("exit_long_2", "entry_long", limit=close*(1+0.02), stop=close*(1-0.005), qty_percent=100)
if shortCondition and strategy.position_size == 0
strategy.entry("entry_short", strategy.short)
strategy.exit("exit_short_1", "entry_short", limit=close*(1-0.01), stop=close*(1+0.005), qty_percent=50)
strategy.exit("exit_short_2", "entry_short", limit=close*(1-0.02), stop=close*(1+0.005), qty_percent=100)
else if testCase == "single_entry_switch_position"
if longCondition
strategy.close_all()
strategy.entry("entry_long", strategy.long)
if shortCondition
strategy.close_all()
strategy.entry("entry_short", strategy.short)
// ---------------- Insert the code below in your strategy ---------------- //
// ----------------------- Stx Monthly Profit Table ----------------------- //
// © 2023 Strambatax (Alessandro Arrabito)
// ------------------------------------------------------------------------- //
string enableProfiTable = input.string("montly_profit", "profit table", options = ["disabled", "montly_profit", "montly_equity"], group = "trades profit table")
string positionProfiTable = input.string("top_right", "position", options = ["top_right", "top_center", "top_left", "bottom_right", "bottom_center", "bottom_left", "middle_center"], group = "trades profit table")
var float monthlyProfit = 0.0
var int startYear = year
var string[] monthNames = array.from("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
var monthlyPnL = matrix.new<float>(1, 12)
var table profiTable = na
var startEquity = strategy.equity
var startMonthEquity = strategy.equity
int closeTrades = ta.change(strategy.closedtrades)
var float tradeProfit = 0
var float tradeCost = .0
var float globalProfit = .0
if closeTrades > 0 and enableProfiTable == "montly_profit"
for i = 1 to closeTrades
idx = strategy.closedtrades - i
size = strategy.closedtrades.size(idx)
tradeProfit += strategy.closedtrades.profit(idx)
tradeCost += strategy.closedtrades.entry_price(idx) * strategy.closedtrades.size(idx)
// check for reversal: close and entry trade in the same bar
isPositionReversal = strategy.opentrades.entry_bar_index(strategy.opentrades -1) == bar_index
// trade is closed ?
//strategy.opentrades
if strategy.opentrades == 0 or isPositionReversal
monthlyProfit += tradeProfit / math.abs(tradeCost)
globalProfit += tradeProfit
// label.new(bar_index, high + 100*(syminfo.mintick), str.tostring(tradeProfit, "#.###") + " " + str.tostring(monthlyProfit, "#.####"))
tradeProfit := 0
tradeCost := 0
if enableProfiTable == "montly_equity"
monthlyProfit := (strategy.equity / startMonthEquity) - 1
globalProfit := strategy.equity - startEquity
// add new row for a new year
if ta.change(year) != 0 and not na(year[1])
matrix.add_row(monthlyPnL)
// Store monthly P&L in an array
if ta.change(month) != 0
startMonthEquity := strategy.equity
monthlyProfit := 0
if monthlyProfit != monthlyProfit[1]
matrix.set(monthlyPnL, matrix.rows(monthlyPnL) - 1, month - 1, monthlyProfit)
pTabHeaderBgColor = color.new(#cad5f1, 24)
pTabHeaderTextColor = color.new(#000000, 25)
pTabBgBullColor = color.new(#006d09, 26)
pTabBgBearColor = color.new(#f31201, 26)
pTabTextColor = color.new(#ffffff, 15)
pTabBdColor = color.new(#000000, 18)
// Create the P&L table
if bar_index >= 11 and barstate.islastconfirmedhistory and enableProfiTable != "disabled"
tradingYears = (year - startYear + 1)
pos = switch positionProfiTable
"top_right" => position.top_right
"top_center" => position.top_center
"top_left" => position.top_left
"bottom_right" => position.bottom_right
"bottom_center" => position.bottom_center
"bottom_left" => position.bottom_left
"middle_center" => position.middle_center
profiTable := table.new(position = pos, rows = 1 + tradingYears, columns = 13, bgcolor = pTabHeaderBgColor, border_width = 1, border_color = pTabBdColor)
// month header
int monthIndex = 0
table.cell(profiTable, row = 0, column = 0, text = "", bgcolor = pTabHeaderBgColor, text_color = pTabHeaderTextColor, text_size = size.small)
for i = 0 to 11
table.cell(profiTable, row = 0, column = i + 1, text = array.get(monthNames, i), bgcolor = pTabHeaderBgColor, text_size = size.small)
for r = 0 to tradingYears - 1
// years side header
table.cell(profiTable, row = r + 1, column = 0, text = str.tostring(startYear + r), text_color = pTabHeaderTextColor, bgcolor = pTabHeaderBgColor, text_size = size.small)
for c = 0 to 11
val = nz(matrix.get(monthlyPnL, r, c))
table.cell(profiTable, row = r + 1, column = c + 1, bgcolor = val >= 0 ? pTabBgBullColor : pTabBgBearColor, text_color = pTabTextColor, text = str.format("{0,number,#.##%}", val), text_size = size.small)
monthIndex += 1
table.cell(profiTable, row = 0, column = 0, bgcolor = globalProfit >= 0 ? pTabBgBullColor : pTabBgBearColor, text_color = pTabTextColor, text = "Profit " +str.format("{0,number,#.##}", globalProfit), text_size = size.small)
// ----------------------- @@@@@@@@@@@@@@@@@@@@@@@@ ----------------------- // |
Narrow Range Strategy | https://www.tradingview.com/script/O9onZ5WR/ | gsanson66 | https://www.tradingview.com/u/gsanson66/ | 21 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gsanson66
//This code is based on the Narrow Range strategy
//Interactive Broker fees are applied on this strategy
//@version=5
strategy("NARROW RANGE STRATEGY", shorttitle="NR STRATEGY", overlay=true, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.18, slippage=3)
//------------------------------TOOL TIPS-------------------------------------//
t1 = "Corresponds to the number of candles back to compare current volatility. Default is 4 to compare current volatility with that of 4 candles ago."
t2 = "Percentage of the reference range on which an exit order is set to limit losses. The minimum value is 0.001, while the maximum is 1. The default value is 0.35"
t3 = "Each gain or losse (relative to the previous reference) in an amount equal to this fixed ratio will change quantity of orders."
t4 = "The amount of money to be added to or subtracted from orders once the fixed ratio has been reached."
//--------------------------------FUNCTIONS------------------------------------//
//@function to print label
debugLabel(txt, color) =>
label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)
//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)
//--------------------------------USER INPUTS------------------------------------//
//Narrow Range Length
nrLength = input.int(4, minval=2, title="Narrow Range Length", group="Strategy parameters", tooltip=t1)
//Risk Management
stopLossInput = input.float(0.35, minval=0.001, maxval=1, title="Stop Loss (in percentage of reference range)", group="Strategy parameters", tooltip=t2)
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management", tooltip=t3)
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management", tooltip=t4)
//Backtesting period
startDate = input.time(title="Start Date", defval=timestamp("1 Janv 2017 00:00:00"), group="Backtesting Period")
endDate = input.time(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")
//--------------------------------VARIABLES INITIALISATION--------------------------//
bool nr = na
var bool long = na
var bool short = na
var float stopPriceLong = na
var float stopLossLong = na
var float takeProfitLong = na
var float stopPriceShort = na
var float stopLossShort = na
var float takeProfitShort = na
var float takeProfit = na
var float stopLoss = na
bool inRange = na
int closedtrades = strategy.closedtrades
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95
//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//
//Checking if the date belong to the range
inRange := inBacktestPeriod(startDate, endDate)
//Checking performances of the strategy
if equity > capital_ref + fixedRatio
spread = (equity - capital_ref)/fixedRatio
nb_level = int(spread)
increasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder + increasingOrder
capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
spread = (capital_ref - equity)/fixedRatio
nb_level = int(spread)
decreasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder - decreasingOrder
capital_ref := capital_ref - nb_level*fixedRatio
//We check if a trade has been closed to cancel all previous orders
if closedtrades > closedtrades[1]
strategy.cancel("Long")
strategy.cancel("Short")
stopPriceLong := na
stopPriceShort := na
//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))
strategy.close_all()
long := na
short := na
stopPriceLong := na
stopLossLong := na
takeProfitLong := na
stopPriceShort := na
stopLossShort := na
takeProfitShort := na
takeProfit := na
stopLoss := na
//----------------------------------FINDING NARROW RANGE DAY------------------------------------------//
// We find the Narrow Range Day
if low > low[nrLength] and high < high[nrLength]
nr := true
//------------------------------------STOP ORDERS--------------------------------------------//
// We handle plotting of stop orders and cancellation of other side order if one order is triggered
if strategy.position_size > 0 and not na(stopPriceLong) and not na(stopPriceShort)
long := true
strategy.cancel("Short")
stopPriceLong := na
stopPriceShort := na
takeProfit := takeProfitLong
stopLoss := stopLossLong
if strategy.position_size < 0 and not na(stopPriceLong) and not na(stopPriceShort)
short := true
strategy.cancel("Long")
stopPriceLong := na
stopPriceShort := na
takeProfit := takeProfitShort
stopLoss := stopLossShort
//------------------------------------STOP LOSS & TAKE PROFIT--------------------------------//
// If an order is triggered we plot TP and SL
if not na(takeProfit) and not na(stopLoss) and long
if high >= takeProfit and closedtrades == closedtrades[1] + 1
takeProfit := na
stopLoss := na
long := na
if low <= stopLoss and closedtrades == closedtrades[1] + 1
takeProfit := na
stopLoss := na
long := na
if not na(takeProfit) and not na(stopLoss) and short
if high >= stopLoss and closedtrades == closedtrades[1] + 1
takeProfit := na
stopLoss := na
short := na
if low <= takeProfit and closedtrades == closedtrades[1] + 1
takeProfit := na
stopLoss := na
short := na
//-----------------------------LONG/SHORT CONDITION-------------------------//
// Conditions to create two stop orders (one for Long and one for Short) and SL & TP calculation
if nr and inRange and strategy.position_size == 0
//LONG
stopPriceLong := high[4]
takeProfitLong := high[4] + (high[4] - low[4])
stopLossLongNr = high[4] - (high[4] - low[4])*stopLossInput
if (stopLossLongNr/stopPriceLong) - 1 < -0.10
stopLossLong := stopPriceLong*0.9
else
stopLossLong := stopLossLongNr
qtyLong = cashOrder/stopPriceLong
strategy.entry("Long", strategy.long, qtyLong, stop=stopPriceLong)
strategy.exit("Exit Long", "Long", limit=takeProfitLong ,stop=stopLossLong)
//SHORT
stopPriceShort := low[4]
takeProfitShort := low[4] - (high[4] - low[4])
stopLossShortNr = low[4] + (high[4] - low[4])*stopLossInput
if (stopLossShortNr/stopPriceShort) - 1 > 0.10
stopLossShort := stopPriceShort*1.1
else
stopLossShort := stopLossShortNr
qtyShort = cashOrder/stopPriceShort
strategy.entry("Short", strategy.short, qtyShort, stop=stopPriceShort)
strategy.exit("Exit Short", "Short", limit=takeProfitShort ,stop=stopLossShort)
//--------------------------PLOTTING ELEMENT----------------------------//
plotshape(nr, "NR", shape.arrowdown, location.abovebar, color.rgb(255, 132, 0), text= "NR4", size=size.huge)
plot(stopPriceLong, "Stop Order", color.blue, 3, plot.style_linebr)
plot(stopPriceShort, "Stop Order", color.blue, 3, plot.style_linebr)
plot(takeProfit, "Take Profit", color.green, 3, plot.style_linebr)
plot(stopLoss, "Stop Loss", color.red, 3, plot.style_linebr) |
Monthly Performance Table by Dr. Maurya | https://www.tradingview.com/script/IucWjmpl-Monthly-Performance-Table-by-Dr-Maurya/ | MAURYA_ALGO_TRADER | https://www.tradingview.com/u/MAURYA_ALGO_TRADER/ | 10 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MAURYA_ALGO_TRADER
//@version=5
strategy("Monthly Performance by Dr. Maurya", overlay=true, default_qty_value = 15, commission_type = strategy.commission.percent, commission_value = 0.1)
len = input(14)
th = input(20)
TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - nz(SmoothedTrueRange[1]) / len + TrueRange
SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - nz(SmoothedDirectionalMovementPlus[1]) / len + DirectionalMovementPlus
SmoothedDirectionalMovementMinus = 0.0
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - nz(SmoothedDirectionalMovementMinus[1]) / len + DirectionalMovementMinus
DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100
ADX = ta.sma(DX, len)
//diff_1 = math.abs(DIPlus - DIMinus)
diff_2 = math.abs(DIPlus-ADX)
diff_3 = math.abs(DIMinus - ADX)
long_diff = input(10, "Long Difference")
short_diff = input(10, "Short Difference")
buy_condition = diff_2 >=long_diff and diff_3 >=long_diff and (ADX < DIPlus and ADX > DIMinus)
sell_condition = diff_2 >=short_diff and diff_3 >=short_diff and (ADX > DIPlus and ADX < DIMinus)
if buy_condition
strategy.entry("Long Entry", strategy.long, comment = "Long")
if sell_condition
strategy.entry("Short Entry", strategy.short, comment = "Short")
// Copy below code to end of the desired strategy script
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// monthly pnl performance by Dr. Maurya @MAURYA_ALGO_TRADER //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
show_performance = input.bool(true, 'Show Monthly Monthly Performance ?', group='Monthly Performance')
dash_loc_mp = input.session("Bottom Right","Location" ,options=["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"] ,group='Monthly Performance', inline = "performance")
text_size_mp = input.session('Small',"Size" ,options=["Tiny","Small","Normal","Large"] ,group='Monthly Performance', inline = "performance")
bg_c = input.color( color.rgb(7, 226, 242, 38), "Background Color", group='Monthly Performance')
text_head_color = input.color( color.rgb(0,0,0), "Month/Year Heading Color", group='Monthly Performance')
tab_month_c = input.color( color.white, "Month PnL Data Color", group='Monthly Performance')
tab_year_c = input.color( color.rgb(0,0,0), "Year PnL Data Color", group='Monthly Performance')
border_c = input.color( color.white, "Table Border Color", group='Monthly Performance')
var table_position_mp = dash_loc_mp == 'Top Left' ? position.top_left :
dash_loc_mp == 'Bottom Left' ? position.bottom_left :
dash_loc_mp == 'Middle Right' ? position.middle_right :
dash_loc_mp == 'Bottom Center' ? position.bottom_center :
dash_loc_mp == 'Top Right' ? position.top_right : position.bottom_right
var table_text_size_mp = text_size_mp == 'Tiny' ? size.tiny :
text_size_mp == 'Small' ? size.small :
text_size_mp == 'Normal' ? size.normal : size.large
/////////////////
/////////////////////////////////////////////
// var bool new_month = na
new_month = ta.change(month) //> 0 ? true : false
newest_month = new_month and strategy.closedtrades >= 1
// profit
only_profit = strategy.netprofit
initial_balance = strategy.initial_capital
// month number
var int month_number = na
month_number := (ta.valuewhen(newest_month, month(time), 0)) //and month(time) > 1 ? (ta.valuewhen(newest_month, month(time), 0) - 1) : 12 //1 to 12
//month_year
var int month_time = na
month_time := ta.valuewhen(newest_month, time, 0) - 2419200000
var int m_counter = 0
if newest_month
m_counter += 1
// current month values
var bool new_year = na
new_year := ta.change(year)
curr_m_pnl = only_profit - nz(ta.valuewhen(newest_month, only_profit, 0), 0)
curr_m_number = newest_month ? ta.valuewhen(newest_month, month(time), 0) : month(time)
curr_y_pnl = (only_profit - nz(ta.valuewhen(new_year, only_profit, 0),0))
var float [] net_profit_array = array.new_float()
var int [] month_array = array.new_int()
var int [] month_time_array = array.new_int()
if newest_month
array.push(net_profit_array, only_profit)
array.push(month_array, month_number)
array.push(month_time_array, month_time)
var float [] y_pnl_array = array.new_float()
var int [] y_number_array = array.new_int()
var int [] y_time_array = array.new_int()
newest_year = ta.change(year) and strategy.closedtrades >= 1
get_yearly_pnl = nz(ta.valuewhen(newest_year, strategy.netprofit, 0) - nz(ta.valuewhen(newest_year, strategy.netprofit, 1), 0), 0)
get_m_year = ta.valuewhen(newest_year, year(time), 1)
get_y_time = ta.valuewhen(newest_year, time, 0)
if newest_year
array.push(y_pnl_array, get_yearly_pnl)
array.push(y_number_array, get_m_year)
array.push(y_time_array, get_y_time)
var float monthly_profit = na
var int column_month_number = na
var int row_month_time = na
var testTable = table.new(position = table_position_mp, columns = 14, rows = 40, bgcolor = bg_c, border_color = border_c, border_width = 1)
if barstate.islastconfirmedhistory and show_performance
table.cell(table_id = testTable, column = 0, row = 0, text = "YEAR", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 1, row = 0, text = "JAN", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 2, row = 0, text = "FEB", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 3, row = 0, text = "MAR", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 4, row = 0, text = "APR", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 5, row = 0, text = "MAY", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 6, row = 0, text = "JUN", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 7, row = 0, text = "JUL", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 8, row = 0, text = "AUG", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 9, row = 0, text = "SEP", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 10, row = 0, text = "OCT", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 11, row = 0, text = "NOV", text_color = text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 12, row = 0, text = "DEC", text_color =text_head_color, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 13, row = 0, text = "YEAR P/L", text_color = text_head_color, text_size=table_text_size_mp)
for i = 0 to (array.size(y_number_array) == 0 ? na : array.size(y_number_array) - 1)
row_y = year(array.get(y_time_array, i)) - year(array.get(y_time_array, 0)) + 1
table.cell(table_id = testTable, column = 13, row = row_y, text = str.tostring(array.get(y_pnl_array , i), "##.##") + '\n' + '(' + str.tostring(array.get(y_pnl_array , i)*100/initial_balance, "##.##") + ' %)', bgcolor = array.get(y_pnl_array , i) > 0 ? color.green : array.get(y_pnl_array , i) < 0 ? color.red : color.gray, text_color = tab_year_c, text_size=table_text_size_mp)
curr_row_y = array.size(month_time_array) == 0 ? 1 : (year(array.get(month_time_array, array.size(month_time_array) - 1))) - (year(array.get(month_time_array, 0))) + 1
table.cell(table_id = testTable, column = 13, row = curr_row_y, text = str.tostring(curr_y_pnl, "##.##") + '\n' + '(' + str.tostring(curr_y_pnl*100/initial_balance, "##.##") + ' %)', bgcolor = curr_y_pnl > 0 ? color.green : curr_y_pnl < 0 ? color.red : color.gray, text_color = tab_year_c, text_size=table_text_size_mp)
for i = 0 to (array.size(net_profit_array) == 0 ? na : array.size(net_profit_array) - 1)
monthly_profit := i > 0 ? ( array.get(net_profit_array, i) - array.get(net_profit_array, i - 1) ) : array.get(net_profit_array, i)
column_month_number := month(array.get(month_time_array, i))
row_month_time :=((year(array.get(month_time_array, i))) - year(array.get(month_time_array, 0)) ) + 1
table.cell(table_id = testTable, column = column_month_number, row = row_month_time, text = str.tostring(monthly_profit, "##.##") + '\n' + '(' + str.tostring(monthly_profit*100/initial_balance, "##.##") + ' %)', bgcolor = monthly_profit > 0 ? color.green : monthly_profit < 0 ? color.red : color.gray, text_color = tab_month_c, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 0, row =row_month_time, text = str.tostring(year(array.get(month_time_array, i)), "##.##"), text_color = text_head_color, text_size=table_text_size_mp)
curr_row_m = array.size(month_time_array) == 0 ? 1 : (year(array.get(month_time_array, array.size(month_time_array) - 1))) - (year(array.get(month_time_array, 0))) + 1
table.cell(table_id = testTable, column = curr_m_number, row = curr_row_m, text = str.tostring(curr_m_pnl, "##.##") + '\n' + '(' + str.tostring(curr_m_pnl*100/initial_balance, "##.##") + ' %)', bgcolor = curr_m_pnl > 0 ? color.green : curr_m_pnl < 0 ? color.red : color.gray, text_color = tab_month_c, text_size=table_text_size_mp)
table.cell(table_id = testTable, column = 0, row =curr_row_m, text = str.tostring(year(time), "##.##"), text_color = text_head_color, text_size=table_text_size_mp)
//============================================================================================================================================================================ |
RSI Box Strategy (pseudo- Grid Bot) | https://www.tradingview.com/script/I4XXBAtK-RSI-Box-Strategy-pseudo-Grid-Bot/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 92 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wbburgin
//@version=5
strategy("RSI Box Strategy (pseudo-Grid Bot)", overlay=true, initial_capital = 10000,
default_qty_type = strategy.percent_of_equity, default_qty_value = 1, pyramiding = 33, commission_value=0.10)
src = input.source(close,"Source")
rsiLength = input.int(14,"RSI Length")
oblvl = input.int(70,"Overbought Level")
oslvl = input.int(30,"Oversold Level")
useShorts = input.bool(false,"Use Shorts",inline="B")
showGrid = input.bool(false,"Show Grid",inline="B")
rsi = ta.rsi(src,rsiLength)
rsi_crossdn = ta.crossunder(rsi,oblvl)
rsi_crossup = ta.crossover(rsi,oslvl)
highest = ta.vwma(ta.highest(src,rsiLength),rsiLength)
lowest = ta.vwma(ta.lowest(src,rsiLength), rsiLength)
gridTop = ta.valuewhen(rsi_crossdn,highest,0)
gridBottom = ta.valuewhen(rsi_crossup,lowest,0)
gridMiddle = math.avg(gridTop,gridBottom)
gridMidTop = math.avg(gridMiddle,gridTop)
gridMidBottom = math.avg(gridMiddle,gridBottom)
diff1 = math.abs(src - gridTop)
diff2 = math.abs(src - gridBottom)
diff3 = math.abs(src - gridMiddle)
diff4 = math.abs(src - gridMidTop)
diff5 = math.abs(src - gridMidBottom)
minDiff = math.min(diff1, diff2, diff3, diff4, diff5)
// Determine which line is the closest
float closestLine = na
if minDiff == diff1
closestLine := gridTop
else if minDiff == diff2
closestLine := gridBottom
else if minDiff == diff3
closestLine := gridMiddle
else if minDiff == diff4
closestLine := gridMidTop
else if minDiff == diff5
closestLine := gridMidBottom
buyCrosses = ta.crossover(src,gridTop) or ta.crossover(src,gridBottom) or ta.crossover(src,gridMiddle) or ta.crossover(src,gridMidTop) or ta.crossover(src,gridMidBottom)
sellCrosses= ta.crossunder(src,gridTop) or ta.crossunder(src,gridBottom) or ta.crossunder(src,gridMiddle) or ta.crossunder(src,gridMidTop) or ta.crossunder(src,gridMidBottom)
condition_bull = buyCrosses
condition_bear = sellCrosses
var float bull_status_line = na
var float bear_status_line = na
var float bull_buy_line = na
var float bear_sell_line = na
if condition_bull
bull_status_line := closestLine
if condition_bear
bear_status_line := closestLine
if bull_status_line == gridBottom
bull_buy_line := gridMidBottom
if bull_status_line == gridMidBottom
bull_buy_line := gridMiddle
if bull_status_line == gridMiddle
bull_buy_line := gridMidTop
if bull_status_line == gridMidTop
bull_buy_line := gridTop
if bear_status_line == gridTop
bear_sell_line := gridMidTop
if bear_status_line == gridMidTop
bear_sell_line := gridMiddle
if bear_status_line == gridMiddle
bear_sell_line := gridMidBottom
if bear_status_line == gridMidBottom
bear_sell_line := gridBottom
l = ta.crossover(src,bull_buy_line)
s = ta.crossunder(src,bear_sell_line)
if l
strategy.entry("Long",strategy.long)
if s
strategy.close("Long")
if useShorts
strategy.entry("Short",strategy.short)
// Plotting
in_buy = ta.barssince(l) < ta.barssince(s)
u=plot(bull_buy_line,color=na,title="Buy Plot")
d=plot(bear_sell_line,color=na,title="Sell Plot")
plot(not showGrid?na:gridBottom,color=color.new(color.white,75),title="Grid Line -2")
plot(not showGrid?na:gridMidBottom,color=color.new(color.white,75),title="Grid Line -1")
plot(not showGrid?na:gridMiddle,color=color.new(color.white,75),title="Grid Line 0")
plot(not showGrid?na:gridMidTop,color=color.new(color.white,75),title="Grid Line 1")
plot(not showGrid?na:gridTop,color=color.new(color.white,75),title="Grid Line 2")
fill(u,d,color=in_buy ? color.new(color.lime,75) : color.new(color.red,75)) |
RSI and SMA | https://www.tradingview.com/script/RC3a12Z1/ | ExpertCryptoo1 | https://www.tradingview.com/u/ExpertCryptoo1/ | 6 | strategy | 5 | MPL-2.0 | /// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ExpertCryptoo1
//@version=5
strategy('RSI and SMA',
overlay=true,
initial_capital=1000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2022, 1, 1, 0, 0)
notInTrade = strategy.position_size <= 0
//==================================Buy Conditions============================================
//RSI
length = input(14)
rsi = ta.rsi(close, length)
//SMA
fastEMA = ta.sma(close, 100)
slowEMA = ta.sma(close, 150)
plot(fastEMA, color = color.green)
plot(slowEMA, color = color.blue)
bullish = ta.crossover(fastEMA, slowEMA) and rsi > 50
bearish = ta.crossover(slowEMA, fastEMA) and rsi < 50
strategy.entry("Long", strategy.long, when=bullish and timePeriod)
strategy.close("Exit", when=bearish)
strategy.entry("Short", strategy.short, when=bearish and timePeriod)
strategy.close("Exit", when=bullish)
|
Nifty 2 Day Breakout strategy | https://www.tradingview.com/script/CX25GKBF-Nifty-2-Day-Breakout-strategy/ | 487551 | https://www.tradingview.com/u/487551/ | 6 | strategy | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © 487551
//@version=5
strategy("Nifty 2 Day Breakout strategy", overlay=true)
// Calculate the high and low of yesterday and the day before yesterday
yesterdayHigh = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
yesterdayLow = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)
dayBeforeYesterdayHigh = request.security(syminfo.tickerid, "D", high[2], lookahead=barmerge.lookahead_on)
dayBeforeYesterdayLow = request.security(syminfo.tickerid, "D", low[2], lookahead=barmerge.lookahead_on)
// Strategy logic
buyCondition = close > yesterdayHigh and close > dayBeforeYesterdayHigh
sellCondition = close < yesterdayLow and close < dayBeforeYesterdayLow
strategy.entry("Buy", strategy.long, when = buyCondition)
strategy.close("Buy", when = sellCondition)
strategy.entry("Sell", strategy.short, when = sellCondition)
strategy.close("Sell", when = buyCondition)
// Plot the breakout levels on the chart
plot(yesterdayHigh, color=color.green, linewidth=2, title="Yesterday High")
plot(yesterdayLow, color=color.red, linewidth=2, title="Yesterday Low")
plot(dayBeforeYesterdayHigh, color=color.blue, linewidth=2, title="Day Before Yesterday High")
plot(dayBeforeYesterdayLow, color=color.orange, linewidth=2, title="Day Before Yesterday Low")
|
Death Cross Based on BTC 20W | https://www.tradingview.com/script/bQwlDo4A-Death-Cross-Based-on-BTC-20W/ | OrionAlgo | https://www.tradingview.com/u/OrionAlgo/ | 5 | strategy | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OrionAlgo
//@version=5
strategy("Death Cross Based on BTC 20W", overlay=true)
// Define the length for SMA
p = 140 //20 week
// Request the 200-day SMA of BTC
btcSMA = request.security("BINANCE:BTCUSDT", "D", ta.sma(close, p))
btcClose = request.security("BINANCE:BTCUSDT", "D", close)
ticker50 = request.security(syminfo.tickerid, "D", ta.sma(close, 50))
ticker200 = request.security(syminfo.tickerid, "D", ta.sma(close, 200))
plot(close, color= (btcClose > btcSMA and ticker50<ticker200) ? color.rgb(76, 175, 79, 50) : na, style = plot.style_area )
plot(close, color= (btcClose < btcSMA ) ? color.rgb(175, 76, 76, 50) : na, style = plot.style_area )
longCondition = (btcClose > btcSMA and ticker50<ticker200)
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = btcClose < btcSMA
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
|
Heatmap MACD Strategy - Pineconnector (Dynamic Alerts) | https://www.tradingview.com/script/GkIeBAOL-Heatmap-MACD-Strategy-Pineconnector-Dynamic-Alerts/ | Daveatt | https://www.tradingview.com/u/Daveatt/ | 55 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//@strategy_alert_message {{strategy.order.alert_message}}
SCRIPT_NAME = "Heatmap MACD Strategy - Pineconnector"
strategy(SCRIPT_NAME,
overlay= true,
process_orders_on_close = true,
calc_on_every_tick = true,
pyramiding = 1,
initial_capital = 100000,
default_qty_type = strategy.fixed,
default_qty_value = 1,
commission_type = strategy.commission.percent,
commission_value = 0.075,
slippage = 1
)
pineconnector_licence_ID = input.string(title = "Licence ID", defval = "123456789", group = "Pineconnector", tooltip = "Insert your Pineconnector Licence ID here")
pos_size = input.float(3, minval = 0, maxval = 100, title = "Position Size", group = "Position Size", tooltip = "Required to specify the position size here for Pineconnector to work properly")
res1 = input.timeframe('60', title='First Timeframe', group = "Timeframes")
res2 = input.timeframe('120', title='Second Timeframe', group = "Timeframes")
res3 = input.timeframe('240', title='Third Timeframe', group = "Timeframes")
res4 = input.timeframe('240', title='Fourth Timeframe', group = "Timeframes")
res5 = input.timeframe('480', title='Fifth Timeframe', group = "Timeframes")
macd_src = input.source(close, title="Source", group = "MACD")
fast_len = input.int(9, minval=1, title="Fast Length", group = "MACD")
slow_len = input.int(26, minval=1, title="Slow Length", group = "MACD")
sig_len = input.int(9, minval=1, title="Signal Length", group = "MACD")
// # ========================================================================= #
// # | Close on Opposite |
// # ========================================================================= #
use_close_opposite = input.bool(false, title = "Close on Opposite Signal?", group = "Close on Opposite", tooltip = "Close the position if 1 or more MACDs become bearish (for longs) or bullish (for shorts)")
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
use_sl = input.bool(true, title = "Use Stop Loss?", group = "Stop Loss")
sl_mode = "pips"//input.string("%", title = "Mode", options = ["%", "pips"], group = "Stop Loss")
sl_value = input.float(40, minval = 0, title = "Value", group = "Stop Loss", inline = "stoploss")// * 0.01
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
use_tsl = input.bool(false, title = "Use Trailing Stop Loss?", group = "Trailing Stop Loss")
tsl_input_pips = input.float(10, minval = 0, title = "Trailing Stop Loss (pips)", group = "Trailing Stop Loss")
// # ========================================================================= #
// # | Take Profit |
// # ========================================================================= #
use_tp1 = input.bool(true, title = "Use Take Profit 1?", group = "Take Profit 1")
tp1_value = input.float(30, minval = 0, title = "Value (pips)", group = "Take Profit 1")// * 0.01
tp1_qty = input.float(50, minval = 0, title = "Quantity (%)", group = "Take Profit 1")// * 0.01
use_tp2 = input.bool(true, title = "Use Take Profit 2?", group = "Take Profit 2")
tp2_value = input.float(50, minval = 0, title = "Value (pips)", group = "Take Profit 2")// * 0.01
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
use_sl_be = input.bool(false, title = "Use Stop Loss to Breakeven Mode?", group = "Break Even")
sl_be_value = input.float(30, step = 0.1, minval = 0, title = "Value (pips)", group = "Break Even", inline = "breakeven")
sl_be_offset = input.int(1, step = 1, minval = 0, title = "Offset (pips)", group = "Break Even", tooltip = "Set the SL at BE price +/- offset value")
[_, _, MTF1_hist] = request.security(syminfo.tickerid, res1, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF2_hist] = request.security(syminfo.tickerid, res2, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF3_hist] = request.security(syminfo.tickerid, res3, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF4_hist] = request.security(syminfo.tickerid, res4, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF5_hist] = request.security(syminfo.tickerid, res5, ta.macd(macd_src, fast_len, slow_len, sig_len))
bull_hist1 = MTF1_hist > 0 and MTF1_hist[1] < 0
bull_hist2 = MTF2_hist > 0 and MTF2_hist[1] < 0
bull_hist3 = MTF3_hist > 0 and MTF3_hist[1] < 0
bull_hist4 = MTF4_hist > 0 and MTF4_hist[1] < 0
bull_hist5 = MTF5_hist > 0 and MTF5_hist[1] < 0
bear_hist1 = MTF1_hist < 0 and MTF1_hist[1] > 0
bear_hist2 = MTF2_hist < 0 and MTF2_hist[1] > 0
bear_hist3 = MTF3_hist < 0 and MTF3_hist[1] > 0
bear_hist4 = MTF4_hist < 0 and MTF4_hist[1] > 0
bear_hist5 = MTF5_hist < 0 and MTF5_hist[1] > 0
plotshape(bull_hist1, title = "Bullish MACD 1", location = location.bottom, style = shape.diamond, size = size.normal, color = #33e823)
plotshape(bull_hist2, title = "Bullish MACD 2", location = location.bottom, style = shape.diamond, size = size.normal, color = #1a7512)
plotshape(bull_hist3, title = "Bullish MACD 3", location = location.bottom, style = shape.diamond, size = size.normal, color = #479c40)
plotshape(bull_hist4, title = "Bullish MACD 4", location = location.bottom, style = shape.diamond, size = size.normal, color = #81cc7a)
plotshape(bull_hist5, title = "Bullish MACD 5", location = location.bottom, style = shape.diamond, size = size.normal, color = #76d66d)
plotshape(bear_hist1, title = "Bearish MACD 1", location = location.top, style = shape.diamond, size = size.normal, color = #d66d6d)
plotshape(bear_hist2, title = "Bearish MACD 2", location = location.top, style = shape.diamond, size = size.normal, color = #de4949)
plotshape(bear_hist3, title = "Bearish MACD 3", location = location.top, style = shape.diamond, size = size.normal, color = #cc2525)
plotshape(bear_hist4, title = "Bearish MACD 4", location = location.top, style = shape.diamond, size = size.normal, color = #a11d1d)
plotshape(bear_hist5, title = "Bearish MACD 5", location = location.top, style = shape.diamond, size = size.normal, color = #ed2424)
bull_count = (MTF1_hist > 0 ? 1 : 0) + (MTF2_hist > 0 ? 1 : 0) + (MTF3_hist > 0 ? 1 : 0) + (MTF4_hist > 0 ? 1 : 0) + (MTF5_hist > 0 ? 1 : 0)
bear_count = (MTF1_hist < 0 ? 1 : 0) + (MTF2_hist < 0 ? 1 : 0) + (MTF3_hist < 0 ? 1 : 0) + (MTF4_hist < 0 ? 1 : 0) + (MTF5_hist < 0 ? 1 : 0)
bull = bull_count == 5 and bull_count[1] < 5 and barstate.isconfirmed
bear = bear_count == 5 and bear_count[1] < 5 and barstate.isconfirmed
signal_candle = bull or bear
entryLongPrice = ta.valuewhen(bull and strategy.position_size[1] <= 0, close, 0)
entryShortPrice = ta.valuewhen(bear and strategy.position_size[1] >= 0, close, 0)
plot(strategy.position_size, title = "avg_pos_size", display = display.data_window)
get_pip_size() =>
float _pipsize = 1.
if syminfo.type == "forex"
_pipsize := (syminfo.mintick * (str.contains(syminfo.ticker, "JPY") ? 100 : 10))
else if str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "XAG")
_pipsize := 0.1
_pipsize
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
var float final_SL_Long = 0.
var float final_SL_Short = 0.
if signal_candle and use_sl
final_SL_Long := entryLongPrice - (sl_value * get_pip_size())
final_SL_Short := entryShortPrice + (sl_value * get_pip_size())
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
var MaxReached = 0.0
if signal_candle[1]
MaxReached := strategy.position_size > 0 ? high : low
MaxReached := strategy.position_size > 0
? math.max(nz(MaxReached, high), high)
: strategy.position_size < 0 ? math.min(nz(MaxReached, low), low) : na
if use_tsl and use_sl
if strategy.position_size > 0
stopValue = MaxReached - (tsl_input_pips * get_pip_size())
final_SL_Long := math.max(stopValue, final_SL_Long[1])
else if strategy.position_size < 0
stopValue = MaxReached + (tsl_input_pips * get_pip_size())
final_SL_Short := math.min(stopValue, final_SL_Short[1])
// # ========================================================================= #
// # | Take Profit 1 |
// # ========================================================================= #
var float final_TP1_Long = 0.
var float final_TP1_Short = 0.
final_TP1_Long := entryLongPrice + (tp1_value * get_pip_size())
final_TP1_Short := entryShortPrice - (tp1_value * get_pip_size())
plot(use_tp1 and strategy.position_size > 0 ? final_TP1_Long : na, title = "TP1 Long", color = color.aqua, linewidth=2, style=plot.style_linebr)
plot(use_tp1 and strategy.position_size < 0 ? final_TP1_Short : na, title = "TP1 Short", color = color.blue, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// # | Take Profit 2 |
// # ========================================================================= #
var float final_TP2_Long = 0.
var float final_TP2_Short = 0.
final_TP2_Long := entryLongPrice + (tp2_value * get_pip_size())
final_TP2_Short := entryShortPrice - (tp2_value * get_pip_size())
plot(use_tp2 and strategy.position_size > 0 and tp1_qty != 100 ? final_TP2_Long : na, title = "TP2 Long", color = color.orange, linewidth=2, style=plot.style_linebr)
plot(use_tp2 and strategy.position_size < 0 and tp1_qty != 100 ? final_TP2_Short : na, title = "TP2 Short", color = color.white, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
var bool SL_BE_REACHED = false
// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
sumProfit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
//get_pip_size() =>
// syminfo.type == "forex" ? syminfo.pointvalue * 100 : 1
current_profit = tradeOpenPL()// * get_pip_size()
current_long_profit = (close - entryLongPrice) / (syminfo.mintick * 10)
current_short_profit = (entryShortPrice - close) / (syminfo.mintick * 10)
plot(current_short_profit, title = "Current Short Profit", display = display.data_window)
plot(current_long_profit, title = "Current Long Profit", display = display.data_window)
if use_sl_be
if strategy.position_size[1] > 0
if not SL_BE_REACHED
if current_long_profit >= sl_be_value
final_SL_Long := entryLongPrice + (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
else if strategy.position_size[1] < 0
if not SL_BE_REACHED
if current_short_profit >= sl_be_value
final_SL_Short := entryShortPrice - (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
plot(use_sl and strategy.position_size > 0 ? final_SL_Long : na, title = "SL Long", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
plot(use_sl and strategy.position_size < 0 ? final_SL_Short : na, title = "SL Short", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// # | Strategy Calls |
// # ========================================================================= #
string entry_long_limit_alert_message = ""
string entry_long_TP1_alert_message = ""
string entry_long_TP2_alert_message = ""
tp1_qty_perc = tp1_qty / 100
if use_tp1 and use_tp2
entry_long_TP1_alert_message := pineconnector_licence_ID + ",buy," + syminfo.ticker + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Long)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
entry_long_TP2_alert_message := pineconnector_licence_ID + ",buy," + syminfo.ticker + ",risk=" + str.tostring(pos_size - (pos_size * tp1_qty_perc)) + ",tp=" + str.tostring(final_TP2_Long)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
else if use_tp1 and not use_tp2
entry_long_TP1_alert_message := pineconnector_licence_ID + ",buy," + syminfo.ticker + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Long)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
else if not use_tp1 and use_tp2
entry_long_TP2_alert_message := pineconnector_licence_ID + ",buy," + syminfo.ticker + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP2_Long)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Long) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
entry_long_limit_alert_message := entry_long_TP1_alert_message + "\n" + entry_long_TP2_alert_message
//entry_long_limit_alert_message = pineconnector_licence_ID + ",buystop," + syminfo.ticker + ",price=" + str.tostring(buy_price) + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP_Long) + ",sl=" + str.tostring(final_SL_Long)
//entry_short_market_alert_message = pineconnector_licence_ID + ",sell," + syminfo.ticker + ",risk=" + str.tostring(pos_size) + (use_tp1 ? ",tp=" + str.tostring(final_TP1_Short) : "")
// + (use_sl ? ",sl=" + str.tostring(final_SL_Short) : "")
//entry_short_limit_alert_message = pineconnector_licence_ID + ",sellstop," + syminfo.ticker + ",price=" + str.tostring(sell_price) + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP_Short) + ",sl=" + str.tostring(final_SL_Short)
string entry_short_limit_alert_message = ""
string entry_short_TP1_alert_message = ""
string entry_short_TP2_alert_message = ""
if use_tp1 and use_tp2
entry_short_TP1_alert_message := pineconnector_licence_ID + ",sell," + syminfo.ticker + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Short)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
entry_short_TP2_alert_message := pineconnector_licence_ID + ",sell," + syminfo.ticker + ",risk=" + str.tostring(pos_size - (pos_size * tp1_qty_perc)) + ",tp=" + str.tostring(final_TP2_Short)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
else if use_tp1 and not use_tp2
entry_short_TP1_alert_message := pineconnector_licence_ID + ",sell," + syminfo.ticker + ",risk=" + str.tostring(pos_size * tp1_qty_perc) + ",tp=" + str.tostring(final_TP1_Short)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
else if not use_tp1 and use_tp2
entry_short_TP2_alert_message := pineconnector_licence_ID + ",sell," + syminfo.ticker + ",risk=" + str.tostring(pos_size) + ",tp=" + str.tostring(final_TP2_Short)
+ (use_sl ? ",sl=" + str.tostring(final_SL_Short) : "") + (use_sl_be ? ",beoffset=" + str.tostring(sl_be_offset) + ",betrigger=" + str.tostring(sl_be_value) : "")
+ (use_tsl ? ",trailtrig=" + str.tostring(tsl_input_pips) + ",traildist=" + str.tostring(tsl_input_pips) + ",trailstep=1" : "")
entry_short_limit_alert_message := entry_short_TP1_alert_message + "\n" + entry_short_TP2_alert_message
long_update_sl_alert_message = pineconnector_licence_ID + ",newsltplong," + syminfo.ticker + ",sl=" + str.tostring(final_SL_Long)
short_update_sl_alert_message = pineconnector_licence_ID + ",newsltpshort," + syminfo.ticker + ",sl=" + str.tostring(final_SL_Short)
cancel_long = pineconnector_licence_ID + ",cancellong," + syminfo.ticker// + "x"
cancel_short = pineconnector_licence_ID + ",cancellong," + syminfo.ticker// + "x"
close_long = pineconnector_licence_ID + ",closelong," + syminfo.ticker
close_short = pineconnector_licence_ID + ",closeshort," + syminfo.ticker
if bull and strategy.position_size <= 0
alert(close_short, alert.freq_once_per_bar_close)
strategy.entry("Long", strategy.long)
alert(entry_long_TP1_alert_message, alert.freq_once_per_bar_close)
alert(entry_long_TP2_alert_message, alert.freq_once_per_bar_close)
else if bear and strategy.position_size >= 0
alert(close_long, alert.freq_once_per_bar_close)
strategy.entry("Short", strategy.short)
alert(entry_short_TP1_alert_message, alert.freq_once_per_bar_close)
alert(entry_short_TP2_alert_message, alert.freq_once_per_bar_close)
if strategy.position_size[1] > 0
if low <= final_SL_Long and use_sl
strategy.close("Long", alert_message = close_long)
else
strategy.exit("Exit TP1 Long", "Long", limit = final_TP1_Long, comment_profit = "Exit TP1 Long", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Long", "Long", limit = final_TP2_Long, comment_profit = "Exit TP2 Long", alert_message = close_long)
if bull_count[1] == 5 and bull_count < 5 and barstate.isconfirmed and use_close_opposite
strategy.close("Long", comment = "1 or more MACDs became bearish", alert_message = close_long)
else if strategy.position_size[1] < 0
if high >= final_SL_Short and use_sl
//strategy.exit("Exit SL Short", "Short", stop = final_SL_Short, comment_loss = "Exit SL Short")
strategy.close("Short", alert_message = close_short)
else
strategy.exit("Exit TP1 Short", "Short", limit = final_TP1_Short, comment_profit = "Exit TP1 Short", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Short", "Short", limit = final_TP2_Short, comment_profit = "Exit TP2 Short")
if bear_count[1] == 5 and bear_count < 5 and barstate.isconfirmed and use_close_opposite
strategy.close("Short", comment = "1 or more MACDs became bullish", alert_message = close_short)
// # ========================================================================= #
// # | Logs |
// # ========================================================================= #
if bull and strategy.position_size <= 0
log.info(entry_long_limit_alert_message)
else if bear and strategy.position_size >= 0
log.info(entry_short_limit_alert_message)
// # ========================================================================= #
// # | Reset Variables |
// # ========================================================================= #
if (strategy.position_size > 0 and strategy.position_size[1] <= 0)
or (strategy.position_size < 0 and strategy.position_size[1] >= 0)
//is_TP1_REACHED := false
SL_BE_REACHED := false |
gj_lo_4H_GBPJPY | https://www.tradingview.com/script/pZdVKfrR/ | fujimoto_ka | https://www.tradingview.com/u/fujimoto_ka/ | 6 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fujimoto_ka
//@version=5
strategy("gj_lo_4H_GBPJPY", overlay=true, margin_long=100, margin_short=100,commission_type = strategy.commission.cash_per_contract,commission_value = 0.009,default_qty_value = 1000)
length = input.int(20, minval=1)
maType = input.string("EMA", "Basis MA Type", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
src = input(close, title="Source")
mult = input.float(1.9, minval=0.001, maxval=50, title="StdDev")
ma(source, length, _type) =>
switch _type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
basis = ma(src, length, maType)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
emano = ta.ema(close ,800)
emano4 = ta.ema(close ,3200)
plot( emano,color = color.red )
plot( emano4,color = color.rgb(12, 8, 8) )
ema_macd1 =ta.ema(close ,12)
ema_macd2 =ta.ema(close ,26)
ema_macd3 =ta.ema(close ,12*6)
ema_macd4 =ta.ema(close ,26*6)
ema_macd =ta.ema(close ,3)
ema_macd0 =ta.ema(close ,6)
plot( ema_macd,color = color.rgb(143, 164, 4) )
plot( ema_macd0,color = color.rgb(131, 136, 3) )
plot( ema_macd1,color = color.rgb(91, 255, 82) )
plot( ema_macd2,color = color.rgb(63, 235, 6) )
plot( ema_macd3,color = color.rgb(82, 255, 243) )
plot( ema_macd4,color = color.rgb(18, 224, 243) )
macd_short_0 = ema_macd < ema_macd0
macd_long_0 = ema_macd > ema_macd0
macd_short = ema_macd1 < ema_macd2 - 0.03
macd_long = ema_macd1 > ema_macd2
macd_short_2 = ema_macd3 < ema_macd4
macd_long_2 = ema_macd3 > ema_macd4
macd_trend_0 =ta.ema(close[1] ,3) - ema_macd < 0 ? true:false
macd_trend =ta.ema(close[1] ,12) - ema_macd1 < 0 ? true:false
macd_trend2 =ta.ema(close[1] ,12*16) - ema_macd3 < 0 ? true:false
MA_short_trend =macd_short and macd_short_2
MA_long_trend = macd_long and macd_long_2
//perfect_sort
isPerfect_sort = open[0] - close[0] >= 0.1 and high[1] < high[0] and low[1] > low[0] and close[0] < open[0] and open[1] >= close[0] and close[0]<low[1] ? true:na
//陰線ツツミ ショート
isTUTUMI_1 = open[0] - close[0] >= 0.1 and high[1] < high[0] and low[1] > low[0] and close[0] < open[0] and open[1] >= close[0] ? true:na
//上髭残しショート 一つ前陰線
isTUTUMI_7 = open[1] - close[1] >= 0 and open[0] - close[0] >= 0 and high[1] > close[0] and open[1] > low[0] and open[1] >= close[0] and close[1] >= close[0] and open[1] < high[0] ? true:na
//上髭残しショート 一つ前陽線
isTUTUMI_8 = open[1] - close[1] <= 0 and open[0] - close[0] >= 0 and high[1] > close[0] and open[1] > low[0] and open[1] >= close[0] and close[1] >= close[0] ? true:na
//陽線
isTUTUMI_2 = open[0] - close[0] <= 0 and high[1] > high[0] and low[1] > low[0] and close[0] > open[0] and close[0] > open[1] ? true:na
//陽線
isTUTUMI_3 = open[0] - close[0] <= 0 and high[1] < close[0] and open[1] > low[0] and close[1] > open[0] ? true:na
//陽線ツツミ 一つ前陰線
isTUTUMI_4 = open[1] - close[1] >= 0 and open[0] - close[0] <= 0 and high[1] < close[0] and open[1] > low[0] ? true:na
//上髭残しロング 一つ前が陰線
isTUTUMI_5 = open[1] - close[1] >= 0 and open[0] - close[0] <= 0 and high[1] > close[0] and open[1] > low[0] and open[1] <= close[0] and close[1] <= close[0] ? true:na
//した髭残し陽線ロング 一つ前陽線
isTUTUMI_6 = open[1] - close[1] <= 0 and open[0] - close[0] <= 0 and high[1] < close[0] and open[1] >= low[0] and open[1] <= close[0] and close[1] <= close[0] ? true:na
//した髭残し陽線ロング 一つ前陽線 一つ前のhighがcloseより高い
isTUTUMI_9 = open[1] - close[1] <= 0 and open[0] - close[0] <= 0 and high[1] > close[0] and open[1] >= low[0] and open[1] <= close[0] and close[1] <= close[0] ? true:na
isTUTUMI = isTUTUMI_1 or isTUTUMI_2 or isTUTUMI_3 or isTUTUMI_4 or isTUTUMI_5 or isTUTUMI_6 or isTUTUMI_7 or isTUTUMI_8 or isTUTUMI_9 ? true:false
isTUTUMI_short = (close[0] > emano) and (isTUTUMI_1 or isTUTUMI_7 or isTUTUMI_8)? true:false
isTUTUMI_long = (close[0] < emano) and (isTUTUMI_2 or isTUTUMI_3 or isTUTUMI_4 or isTUTUMI_5 or isTUTUMI_6 or isTUTUMI_9)? true:false
isTUTUMI_long_without_ema = isTUTUMI_2 or isTUTUMI_3 or isTUTUMI_4 or isTUTUMI_5 or isTUTUMI_6 or isTUTUMI_9? true:false
isTUTUMI_short_without_ema = isTUTUMI_1 or isTUTUMI_7 or isTUTUMI_8? true:false
//=====================================================================
val_min_1H = ta.lowest(low,6)
val_max_1H = ta.highest(high ,6 )
val_max_1H_within = ta.highest(high ,4 )
val_min_4H = ta.lowest(low ,18 )
val_min_5m = math.min(low[ 0 ],low[ 1 ],low[ 2 ])
val_max_5m = math.max(high[ 0 ],high[ 1 ],high[ 2 ])
val_min_1bar = low[ 0 ]
val_max_1bar = high[ 0 ]
val_min_0day = math.min(low[ 0 ],low[ 1 ],low[ 2 ],low[ 3 ],low[ 4 ],low[ 5 ])
val_max_0day = math.max(high[ 0 ],high[ 1 ],high[ 2 ],high[ 3 ],high[ 4 ],high[ 5 ])
val_min_1day = math.min(low[ 1 ],low[ 2 ],low[ 3 ],low[ 4 ],low[ 5 ],low[ 6 ])
val_max_1day = math.max(high[ 1 ],high[ 2 ],high[ 3 ],high[ 4 ],high[ 5 ],high[ 6 ])
val_min_2day = math.min(low[ 7 ],low[ 8 ],low[ 9 ],low[ 10 ],low[ 11 ],low[ 12 ])
val_max_2day = math.max(high[ 7 ],high[ 8 ],high[ 9 ],high[ 10 ],high[ 11 ],high[ 12 ])
val_min_3day = math.min(low[ 13 ],low[ 14 ],low[ 15 ],low[ 16 ],low[ 17 ],low[ 18 ])
val_max_3day = math.max(high[ 13 ],high[ 14 ],high[ 15 ],high[ 16 ],high[ 17 ],high[ 18 ])
val_min_4day = math.min(low[ 19 ],low[ 20 ],low[ 21 ],low[ 22 ],low[ 23 ],low[ 24 ])
val_max_4day = math.max(high[ 19 ],high[ 20 ],high[ 21 ],high[ 22 ],high[ 23 ],high[ 24 ])
val_min_5day = math.min(low[ 25 ],low[ 26 ],low[ 27 ],low[ 28 ],low[ 29 ],low[ 30 ])
val_max_5day = math.max(high[ 25 ],high[ 26 ],high[ 27 ],high[ 28 ],high[ 29 ],high[ 30 ])
val_min_6day = math.min(low[ 31 ],low[ 32 ],low[ 33 ],low[ 34 ],low[ 35 ],low[ 36 ])
val_max_6day = math.max(high[ 31 ],high[ 32 ],high[ 33 ],high[ 34 ],high[ 35 ],high[ 36 ])
val_min_7day = math.min(low[ 37 ],low[ 38 ],low[ 39 ],low[ 40 ],low[ 41 ],low[ 42 ])
val_max_7day = math.max(high[ 37 ],high[ 38 ],high[ 39 ],high[ 40 ],high[ 41 ],high[ 42 ])
val_min_8day = math.min(low[ 43 ],low[ 44 ],low[ 45 ],low[ 46 ],low[ 47 ],low[ 48 ])
val_max_8day = math.max(high[ 43 ],high[ 44 ],high[ 45 ],high[ 46 ],high[ 47 ],high[ 48 ])
val_min_9day = math.min(low[ 49 ],low[ 50 ],low[ 51 ],low[ 52 ],low[ 53 ],low[ 54 ])
val_max_9day = math.max(high[ 49 ],high[ 50 ],high[ 51 ],high[ 52 ],high[ 53 ],high[ 54 ])
val_min_10day = math.min(low[ 55 ],low[ 56 ],low[ 57 ],low[ 58 ],low[ 59 ],low[ 60 ])
val_max_10day = math.max(high[ 55 ],high[ 56 ],high[ 57 ],high[ 58 ],high[ 59 ],high[ 60 ])
dif_min_max_day0 =math.abs( val_max_0day - val_min_0day )
dif_min_max_day1 =math.abs( val_max_1day - val_min_1day )
dif_min_max_day2 =math.abs( val_max_2day - val_min_2day )
dif_min_max_day3 =math.abs( val_max_3day - val_min_3day )
dif_min_max_day4 =math.abs( val_max_4day - val_min_4day )
dif_min_max_day5 =math.abs( val_max_5day - val_min_5day )
dif_min_max_day6 =math.abs(val_max_6day-val_min_6day)
dif_min_max_day7 =math.abs(val_max_7day-val_min_7day)
dif_min_max_day8 =math.abs(val_max_8day-val_min_8day)
dif_min_max_day9 =math.abs(val_max_9day-val_min_9day)
dif_min_max_day10 =math.abs(val_max_10day-val_min_10day)
BigVol = 2
too_near_BigVol = (dif_min_max_day0>BigVol)
too_near_BigVol2 = (dif_min_max_day0>BigVol) or (dif_min_max_day1>BigVol)
limithaba = 1.5
DayVol_Under = (dif_min_max_day4 > limithaba)or (dif_min_max_day5 > limithaba)
// DayVol_Under = (dif_min_max_day1 > limithaba) or (dif_min_max_day2 > limithaba)or (dif_min_max_day3 > limithaba)or (dif_min_max_day4 > limithaba)or (dif_min_max_day5 > limithaba)
DayVol_Under2 = (dif_min_max_day6 > limithaba) or (dif_min_max_day7 > limithaba)or (dif_min_max_day8 > limithaba)
// DayVol_Under2 = (dif_min_max_day6 > limithaba) or (dif_min_max_day7 > limithaba)or (dif_min_max_day8 > limithaba)or (dif_min_max_day9 > limithaba)or (dif_min_max_day10 > limithaba)
Underhaba = 1.1
DayVol_within = (dif_min_max_day1 < Underhaba) or (dif_min_max_day2 < Underhaba)or (dif_min_max_day3 < Underhaba)or (dif_min_max_day4 < Underhaba)or (dif_min_max_day5 < Underhaba) or (dif_min_max_day6 < Underhaba)
DayVol_within2 = (dif_min_max_day6 < Underhaba)
// DayVol_within2 = (dif_min_max_day6 < Underhaba) or (dif_min_max_day7 < Underhaba)or (dif_min_max_day8 < Underhaba)or (dif_min_max_day9 < Underhaba)or (dif_min_max_day10 < Underhaba)
val_min_0 = math.min(low[ 1 ],low[ 2 ],low[ 3 ],low[ 4 ],low[ 5 ],low[ 6 ],low[ 7 ],low[ 8 ],low[ 9 ],low[ 10 ],low[ 11 ],low[ 12 ],low[ 13 ],low[ 14 ],low[ 15 ],low[ 16 ],low[ 17 ],low[ 18 ],low[ 19 ],low[ 20 ],low[ 21 ],low[ 22 ],low[ 23 ],low[ 24 ],low[ 25 ],low[ 26 ],low[ 27 ],low[ 28 ],low[ 29 ],low[ 30 ])
val_max_0 = math.max(high[ 1 ],high[ 2 ],high[ 3 ],high[ 4 ],high[ 5 ],high[ 6 ],high[ 7 ],high[ 8 ],high[ 9 ],high[ 10 ],high[ 11 ],high[ 12 ],high[ 13 ],high[ 14 ],high[ 15 ],high[ 16 ],high[ 17 ],high[ 18 ],high[ 19 ],high[ 20 ],high[ 21 ],high[ 22 ],high[ 23 ],high[ 24 ],high[ 25 ],high[ 26 ],high[ 27 ],high[ 28 ],high[ 29 ],high[ 30 ])
val_min_1 = math.min(low[ 31 ],low[ 32 ],low[ 33 ],low[ 34 ],low[ 35 ],low[ 36 ],low[ 37 ],low[ 38 ],low[ 39 ],low[ 40 ],low[ 41 ],low[ 42 ],low[ 43 ],low[ 44 ],low[ 45 ],low[ 46 ],low[ 47 ],low[ 48 ],low[ 49 ],low[ 50 ],low[ 51 ],low[ 52 ],low[ 53 ],low[ 54 ],low[ 55 ],low[ 56 ],low[ 57 ],low[ 58 ],low[ 59 ],low[ 60 ])
val_max_1 = math.max(high[ 31 ],high[ 32 ],high[ 33 ],high[ 34 ],high[ 35 ],high[ 36 ],high[ 37 ],high[ 38 ],high[ 39 ],high[ 40 ],high[ 41 ],high[ 42 ],high[ 43 ],high[ 44 ],high[ 45 ],high[ 46 ],high[ 47 ],high[ 48 ],high[ 49 ],high[ 50 ],high[ 51 ],high[ 52 ],high[ 53 ],high[ 54 ],high[ 55 ],high[ 56 ],high[ 57 ],high[ 58 ],high[ 59 ],high[ 60 ])
val_min_2 = math.min(low[ 61 ],low[ 62 ],low[ 63 ],low[ 64 ],low[ 65 ],low[ 66 ],low[ 67 ],low[ 68 ],low[ 69 ],low[ 70 ],low[ 71 ],low[ 72 ],low[ 73 ],low[ 74 ],low[ 75 ],low[ 76 ],low[ 77 ],low[ 78 ],low[ 79 ],low[ 80 ],low[ 81 ],low[ 82 ],low[ 83 ],low[ 84 ],low[ 85 ],low[ 86 ],low[ 87 ],low[ 88 ],low[ 89 ],low[ 90 ])
val_max_2 = math.max(high[ 61 ],high[ 62 ],high[ 63 ],high[ 64 ],high[ 65 ],high[ 66 ],high[ 67 ],high[ 68 ],high[ 69 ],high[ 70 ],high[ 71 ],high[ 72 ],high[ 73 ],high[ 74 ],high[ 75 ],high[ 76 ],high[ 77 ],high[ 78 ],high[ 79 ],high[ 80 ],high[ 81 ],high[ 82 ],high[ 83 ],high[ 84 ],high[ 85 ],high[ 86 ],high[ 87 ],high[ 88 ],high[ 89 ],high[ 90 ])
val_min_3 = math.min(low[ 91 ],low[ 92 ],low[ 93 ],low[ 94 ],low[ 95 ],low[ 96 ],low[ 97 ],low[ 98 ],low[ 99 ],low[ 100 ],low[ 101 ],low[ 102 ],low[ 103 ],low[ 104 ],low[ 105 ],low[ 106 ],low[ 107 ],low[ 108 ],low[ 109 ],low[ 110 ],low[ 111 ],low[ 112 ],low[ 113 ],low[ 114 ],low[ 115 ],low[ 116 ],low[ 117 ],low[ 118 ],low[ 119 ],low[ 120 ])
val_max_3 = math.max(high[ 91 ],high[ 92 ],high[ 93 ],high[ 94 ],high[ 95 ],high[ 96 ],high[ 97 ],high[ 98 ],high[ 99 ],high[ 100 ],high[ 101 ],high[ 102 ],high[ 103 ],high[ 104 ],high[ 105 ],high[ 106 ],high[ 107 ],high[ 108 ],high[ 109 ],high[ 110 ],high[ 111 ],high[ 112 ],high[ 113 ],high[ 114 ],high[ 115 ],high[ 116 ],high[ 117 ],high[ 118 ],high[ 119 ],high[ 120 ])
val_min_4 = math.min(low[ 121 ],low[ 122 ],low[ 123 ],low[ 124 ],low[ 125 ],low[ 126 ],low[ 127 ],low[ 128 ],low[ 129 ],low[ 130 ],low[ 131 ],low[ 132 ],low[ 133 ],low[ 134 ],low[ 135 ],low[ 136 ],low[ 137 ],low[ 138 ],low[ 139 ],low[ 140 ],low[ 141 ],low[ 142 ],low[ 143 ],low[ 144 ],low[ 145 ],low[ 146 ],low[ 147 ],low[ 148 ],low[ 149 ],low[ 150 ])
val_max_4 = math.max(high[ 121 ],high[ 122 ],high[ 123 ],high[ 124 ],high[ 125 ],high[ 126 ],high[ 127 ],high[ 128 ],high[ 129 ],high[ 130 ],high[ 131 ],high[ 132 ],high[ 133 ],high[ 134 ],high[ 135 ],high[ 136 ],high[ 137 ],high[ 138 ],high[ 139 ],high[ 140 ],high[ 141 ],high[ 142 ],high[ 143 ],high[ 144 ],high[ 145 ],high[ 146 ],high[ 147 ],high[ 148 ],high[ 149 ],high[ 150 ])
dif_min_max_3 =math.abs( val_max_3 - val_min_3 )
dif_min_max_1 =math.abs( val_max_1 - val_min_1 )
dif_min_max_0 =math.abs( val_max_0 - val_min_0 )
dif_min_max_4 =math.abs( val_max_4 - val_min_4 )
dif_min_max_2 =math.abs( val_max_2 - val_min_2 )
dif_max_min = math.abs( dif_min_max_4 + dif_min_max_0+dif_min_max_1+dif_min_max_2+dif_min_max_3)/5*1.2
week_nehaba_ave_up =(dif_min_max_0 > dif_max_min)
plotchar(week_nehaba_ave_up,location = location.top,char = '周',size = size.tiny,color =color.rgb(9, 19, 19) )
haba = 0.4
now_max_condition_1H = (val_max_1H - close[0]) < 0.2
no_near_big_down = ((val_max_1H - val_min_1H) < haba)
near_min_50 = ( close[0] - val_min_4H) > dif_min_max_0 /2.9
no_near_max_within_30 =(val_max_1H_within - close[0] ) > dif_min_max_0 /5
plotchar(near_min_50,location = location.top,char = '二',size = size.tiny,color =color.rgb(105, 248, 246) )
plotchar(no_near_max_within_30,location = location.bottom,char = '一',size = size.tiny,color =color.rgb(248, 31, 78) )
kiriage = low[1]<low[0]
kirisage = high[1]>high[0] and open[0] > close[0]
// plotchar(kirisage,location = location.top,char = '♪',size = size.tiny,color =color.rgb(8, 10, 10) )
// plotchar(kiriage,location = location.bottom,char = '♪',size = size.tiny,color =color.rgb(8, 10, 10) )
close_Without_lower = (lower > val_min_5m)
close_Without_uper = (upper < high[0])
plotchar(close_Without_lower,location = location.bottom,char = 'w',size = size.tiny,color =color.rgb(105, 248, 246))
loss_haba = close[0] - val_min_1H
tooBig_loss_haba = loss_haba > 1.2
plotchar(tooBig_loss_haba,location = location.bottom,char = 'w',size = size.normal,color =color.rgb(105, 248, 246))
barcolor(isTUTUMI and week_nehaba_ave_up ? color.rgb(255, 235, 59, 61) : na)
hr_25 = hour == 18 ? true:false
hr_0 = hour == 0 ? true:false
hr_1 = hour == 1 ? true:false
hr_2 = hour == 2 ? true:false
hr_3 = hour == 3 ? true:false
hr_14 = hour == 14 ? true:false
hr_15 = hour == 15 ? true:false
hr_16 = hour == 3 ? true:false
hr_17 = hour == 4 ? true:false
hr_18 = hour == 5 ? true:false
hr_19 = hour == 6 ? true:false
hr_8 = hour == 8 ? true:false
hr_9 = hour == 9 ? true:false
hr_10 = hour == 10 ? true:false
hr_11 = hour == 11 ? true:false
hr_12 = hour == 12 ? true:false
hr_13 = hour == 13 ? true:false
hr_20 = hour == 20 ? true:false
hr_21 = hour == 21 ? true:false
hr_24 = hour == 24 ? true:false
hr_22 = hour == 16 ? true:false
hr_23 = hour == 23 ? true:false
min_0 = minute == 0
min_15 = minute == 15
min_30 = minute == 30
min_45 = minute == 45
loss_val = val_max_1H - close[0]
profit_val = 50
bgcolor(hr_1? color.rgb(248, 163, 229, 85) : na)
longCondition = (close_Without_uper)
if (longCondition )
strategy.entry("My Entry Id_9", strategy.long,comment = "En")
|
gj_sh_1H_gbpJPY | https://www.tradingview.com/script/KVGiwH4B/ | fujimoto_ka | https://www.tradingview.com/u/fujimoto_ka/ | 4 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fujimoto_ka
//@version=5
strategy("gj_sh_1H_gbpJPY",commission_type = strategy.commission.cash_per_contract,commission_value = 0.009,default_qty_value = 1000, overlay=true, margin_long=100, margin_short=100)
length = input.int(20, minval=1)
maType = input.string("SMA", "Basis MA Type", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
src = input(close, title="Source")
mult = input.float(2, minval=0.001, maxval=50, title="StdDev")
ma(source, length, _type) =>
switch _type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
basis = ma(src, length, maType)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
emano = ta.ema(close ,800)
emano4 = ta.ema(close ,3200)
plot( emano,color = color.red )
plot( emano4,color = color.rgb(12, 8, 8) )
ema_macd1 =ta.ema(close ,12)
ema_macd2 =ta.ema(close ,26)
ema_macd3 =ta.ema(close ,12*16)
ema_macd4 =ta.ema(close ,26*16)
ema_macd =ta.ema(close ,4)
ema_macd0 =ta.ema(close ,9)
plot( ema_macd,color = color.rgb(143, 164, 4) )
plot( ema_macd0,color = color.rgb(131, 136, 3) )
plot( ema_macd1,color = color.rgb(15, 203, 5) )
plot( ema_macd2,color = color.rgb(45, 170, 3) )
plot( ema_macd3,color = color.rgb(82, 255, 243) )
plot( ema_macd4,color = color.rgb(18, 224, 243) )
macd_short = ema_macd1 < ema_macd2
macd_long = ema_macd1 > ema_macd2
macd_short_2 = ema_macd3 < ema_macd4
macd_long_2 = ema_macd3 > ema_macd4
macd_short_For_tutumi = ema_macd1 < ema_macd2 + 0.01
macd_trend =ta.ema(close[1] ,12) - ema_macd1 < 0 ? true:false
macd_trend2 =ta.ema(close[1] ,12*16) - ema_macd3 < 0 ? true:false
//陰線ツツミ ショート
isTUTUMI_1 = open[0] - close[0] >= 0.1 and high[1] < high[0] and low[1] > low[0] and close[0] < open[0] and open[1] >= close[0] ? true:na
//上髭残しショート 一つ前陰線
isTUTUMI_7 = open[1] - close[1] >= 0 and open[0] - close[0] >= 0 and high[1] > close[0] and open[1] > low[0] and open[1] >= close[0] and close[1] >= close[0] and open[1] < high[0] ? true:na
//上髭残しショート 一つ前陽線
isTUTUMI_8 = open[1] - close[1] <= 0 and open[0] - close[0] >= 0 and high[1] > close[0] and open[1] > low[0] and open[1] >= close[0] and close[1] >= close[0] ? true:na
//陽線
isTUTUMI_2 = open[0] - close[0] <= 0 and high[1] > high[0] and low[1] > low[0] and close[0] > open[0] and close[0] > open[1] ? true:na
//陽線
isTUTUMI_3 = open[0] - close[0] <= 0 and high[1] < close[0] and open[1] > low[0] and close[1] > open[0] ? true:na
//陽線ツツミ 一つ前陰線
isTUTUMI_4 = open[1] - close[1] >= 0 and open[0] - close[0] <= 0 and high[1] < close[0] and open[1] > low[0] ? true:na
//上髭残しロング 一つ前が陰線
isTUTUMI_5 = open[1] - close[1] >= 0 and open[0] - close[0] <= 0 and high[1] > close[0] and open[1] > low[0] and open[1] <= close[0] and close[1] <= close[0] ? true:na
//した髭残し陽線ロング 一つ前陽線
isTUTUMI_6 = open[1] - close[1] <= 0 and open[0] - close[0] <= 0 and high[1] < close[0] and open[1] >= low[0] and open[1] <= close[0] and close[1] <= close[0] ? true:na
//した髭残し陽線ロング 一つ前陽線 一つ前のhighがcloseより高い
isTUTUMI_9 = open[1] - close[1] <= 0 and open[0] - close[0] <= 0 and high[1] > close[0] and open[1] >= low[0] and open[1] <= close[0] and close[1] <= close[0] ? true:na
isTUTUMI = isTUTUMI_1
isTUTUMI_short = (close[0] > emano)
isTUTUMI_long = (close[0] < emano)
isTUTUMI_long_without_ema = isTUTUMI_2
isTUTUMI_short_without_ema = isTUTUMI_1
//=====================================================================
val_min_1H = ta.lowest(low,10)
val_max_1H = ta.highest(high ,12 )
val_min_4H = ta.lowest(low ,22 )
val_min_5m = math.min(low[ 0 ],low[ 1 ],low[ 2 ])
val_max_5m = math.max(high[ 0 ],high[ 1 ],high[ 2 ])
val_min_0 = math.min(low[ 1 ],low[ 2 ],low[ 3 ],low[ 4 ],low[ 5 ],low[ 6 ],low[ 7 ],low[ 8 ],low[ 9 ],low[ 10 ],low[ 11 ],low[ 12 ],low[ 13 ],low[ 14 ],low[ 15 ],low[ 16 ],low[ 17 ],low[ 18 ],low[ 19 ],low[ 20 ],low[ 21 ],low[ 22 ],low[ 23 ],low[ 24 ],low[ 25 ],low[ 26 ],low[ 27 ],low[ 28 ],low[ 29 ],low[ 30 ],low[ 31 ],low[ 32 ],low[ 33 ],low[ 34 ],low[ 35 ],low[ 36 ],low[ 37 ],low[ 38 ],low[ 39 ],low[ 40 ],low[ 41 ],low[ 42 ],low[ 43 ],low[ 44 ],low[ 45 ],low[ 46 ],low[ 47 ],low[ 48 ],low[ 49 ],low[ 50 ],low[ 51 ],low[ 52 ],low[ 53 ],low[ 54 ],low[ 55 ],low[ 56 ],low[ 57 ],low[ 58 ],low[ 59 ],low[ 60 ],low[ 61 ],low[ 62 ],low[ 63 ],low[ 64 ],low[ 65 ],low[ 66 ],low[ 67 ],low[ 68 ],low[ 69 ],low[ 70 ],low[ 71 ],low[ 72 ],low[ 73 ],low[ 74 ],low[ 75 ],low[ 76 ],low[ 77 ],low[ 78 ],low[ 79 ],low[ 80 ],low[ 81 ],low[ 82 ],low[ 83 ],low[ 84 ],low[ 85 ],low[ 86 ],low[ 87 ],low[ 88 ],low[ 89 ],low[ 90 ],low[ 91 ],low[ 92 ],low[ 93 ],low[ 94 ],low[ 95 ],low[ 96 ])
val_max_0 = math.max(high[ 1 ],high[ 2 ],high[ 3 ],high[ 4 ],high[ 5 ],high[ 6 ],high[ 7 ],high[ 8 ],high[ 9 ],high[ 10 ],high[ 11 ],high[ 12 ],high[ 13 ],high[ 14 ],high[ 15 ],high[ 16 ],high[ 17 ],high[ 18 ],high[ 19 ],high[ 20 ],high[ 21 ],high[ 22 ],high[ 23 ],high[ 24 ],high[ 25 ],high[ 26 ],high[ 27 ],high[ 28 ],high[ 29 ],high[ 30 ],high[ 31 ],high[ 32 ],high[ 33 ],high[ 34 ],high[ 35 ],high[ 36 ],high[ 37 ],high[ 38 ],high[ 39 ],high[ 40 ],high[ 41 ],high[ 42 ],high[ 43 ],high[ 44 ],high[ 45 ],high[ 46 ],high[ 47 ],high[ 48 ],high[ 49 ],high[ 50 ],high[ 51 ],high[ 52 ],high[ 53 ],high[ 54 ],high[ 55 ],high[ 56 ],high[ 57 ],high[ 58 ],high[ 59 ],high[ 60 ],high[ 61 ],high[ 62 ],high[ 63 ],high[ 64 ],high[ 65 ],high[ 66 ],high[ 67 ],high[ 68 ],high[ 69 ],high[ 70 ],high[ 71 ],high[ 72 ],high[ 73 ],high[ 74 ],high[ 75 ],high[ 76 ],high[ 77 ],high[ 78 ],high[ 79 ],high[ 80 ],high[ 81 ],high[ 82 ],high[ 83 ],high[ 84 ],high[ 85 ],high[ 86 ],high[ 87 ],high[ 88 ],high[ 89 ],high[ 90 ],high[ 91 ],high[ 92 ],high[ 93 ],high[ 94 ],high[ 95 ],high[ 96 ])
val_min_1 = math.min(low[ 97 ],low[ 98 ],low[ 99 ],low[ 100 ],low[ 101 ],low[ 102 ],low[ 103 ],low[ 104 ],low[ 105 ],low[ 106 ],low[ 107 ],low[ 108 ],low[ 109 ],low[ 110 ],low[ 111 ],low[ 112 ],low[ 113 ],low[ 114 ],low[ 115 ],low[ 116 ],low[ 117 ],low[ 118 ],low[ 119 ],low[ 120 ],low[ 121 ],low[ 122 ],low[ 123 ],low[ 124 ],low[ 125 ],low[ 126 ],low[ 127 ],low[ 128 ],low[ 129 ],low[ 130 ],low[ 131 ],low[ 132 ],low[ 133 ],low[ 134 ],low[ 135 ],low[ 136 ],low[ 137 ],low[ 138 ],low[ 139 ],low[ 140 ],low[ 141 ],low[ 142 ],low[ 143 ],low[ 144 ],low[ 145 ],low[ 146 ],low[ 147 ],low[ 148 ],low[ 149 ],low[ 150 ],low[ 151 ],low[ 152 ],low[ 153 ],low[ 154 ],low[ 155 ],low[ 156 ],low[ 157 ],low[ 158 ],low[ 159 ],low[ 160 ],low[ 161 ],low[ 162 ],low[ 163 ],low[ 164 ],low[ 165 ],low[ 166 ],low[ 167 ],low[ 168 ],low[ 169 ],low[ 170 ],low[ 171 ],low[ 172 ],low[ 173 ],low[ 174 ],low[ 175 ],low[ 176 ],low[ 177 ],low[ 178 ],low[ 179 ],low[ 180 ],low[ 181 ],low[ 182 ],low[ 183 ],low[ 184 ],low[ 185 ],low[ 186 ],low[ 187 ],low[ 188 ],low[ 189 ],low[ 190 ],low[ 191 ],low[ 192 ])
val_max_1 = math.max(high[ 97 ],high[ 98 ],high[ 99 ],high[ 100 ],high[ 101 ],high[ 102 ],high[ 103 ],high[ 104 ],high[ 105 ],high[ 106 ],high[ 107 ],high[ 108 ],high[ 109 ],high[ 110 ],high[ 111 ],high[ 112 ],high[ 113 ],high[ 114 ],high[ 115 ],high[ 116 ],high[ 117 ],high[ 118 ],high[ 119 ],high[ 120 ],high[ 121 ],high[ 122 ],high[ 123 ],high[ 124 ],high[ 125 ],high[ 126 ],high[ 127 ],high[ 128 ],high[ 129 ],high[ 130 ],high[ 131 ],high[ 132 ],high[ 133 ],high[ 134 ],high[ 135 ],high[ 136 ],high[ 137 ],high[ 138 ],high[ 139 ],high[ 140 ],high[ 141 ],high[ 142 ],high[ 143 ],high[ 144 ],high[ 145 ],high[ 146 ],high[ 147 ],high[ 148 ],high[ 149 ],high[ 150 ],high[ 151 ],high[ 152 ],high[ 153 ],high[ 154 ],high[ 155 ],high[ 156 ],high[ 157 ],high[ 158 ],high[ 159 ],high[ 160 ],high[ 161 ],high[ 162 ],high[ 163 ],high[ 164 ],high[ 165 ],high[ 166 ],high[ 167 ],high[ 168 ],high[ 169 ],high[ 170 ],high[ 171 ],high[ 172 ],high[ 173 ],high[ 174 ],high[ 175 ],high[ 176 ],high[ 177 ],high[ 178 ],high[ 179 ],high[ 180 ],high[ 181 ],high[ 182 ],high[ 183 ],high[ 184 ],high[ 185 ],high[ 186 ],high[ 187 ],high[ 188 ],high[ 189 ],high[ 190 ],high[ 191 ],high[ 192 ])
val_min_2 = math.min(low[ 193 ],low[ 194 ],low[ 195 ],low[ 196 ],low[ 197 ],low[ 198 ],low[ 199 ],low[ 200 ],low[ 201 ],low[ 202 ],low[ 203 ],low[ 204 ],low[ 205 ],low[ 206 ],low[ 207 ],low[ 208 ],low[ 209 ],low[ 210 ],low[ 211 ],low[ 212 ],low[ 213 ],low[ 214 ],low[ 215 ],low[ 216 ],low[ 217 ],low[ 218 ],low[ 219 ],low[ 220 ],low[ 221 ],low[ 222 ],low[ 223 ],low[ 224 ],low[ 225 ],low[ 226 ],low[ 227 ],low[ 228 ],low[ 229 ],low[ 230 ],low[ 231 ],low[ 232 ],low[ 233 ],low[ 234 ],low[ 235 ],low[ 236 ],low[ 237 ],low[ 238 ],low[ 239 ],low[ 240 ],low[ 241 ],low[ 242 ],low[ 243 ],low[ 244 ],low[ 245 ],low[ 246 ],low[ 247 ],low[ 248 ],low[ 249 ],low[ 250 ],low[ 251 ],low[ 252 ],low[ 253 ],low[ 254 ],low[ 255 ],low[ 256 ],low[ 257 ],low[ 258 ],low[ 259 ],low[ 260 ],low[ 261 ],low[ 262 ],low[ 263 ],low[ 264 ],low[ 265 ],low[ 266 ],low[ 267 ],low[ 268 ],low[ 269 ],low[ 270 ],low[ 271 ],low[ 272 ],low[ 273 ],low[ 274 ],low[ 275 ],low[ 276 ],low[ 277 ],low[ 278 ],low[ 279 ],low[ 280 ],low[ 281 ],low[ 282 ],low[ 283 ],low[ 284 ],low[ 285 ],low[ 286 ],low[ 287 ],low[ 288 ])
val_max_2 = math.max(high[ 193 ],high[ 194 ],high[ 195 ],high[ 196 ],high[ 197 ],high[ 198 ],high[ 199 ],high[ 200 ],high[ 201 ],high[ 202 ],high[ 203 ],high[ 204 ],high[ 205 ],high[ 206 ],high[ 207 ],high[ 208 ],high[ 209 ],high[ 210 ],high[ 211 ],high[ 212 ],high[ 213 ],high[ 214 ],high[ 215 ],high[ 216 ],high[ 217 ],high[ 218 ],high[ 219 ],high[ 220 ],high[ 221 ],high[ 222 ],high[ 223 ],high[ 224 ],high[ 225 ],high[ 226 ],high[ 227 ],high[ 228 ],high[ 229 ],high[ 230 ],high[ 231 ],high[ 232 ],high[ 233 ],high[ 234 ],high[ 235 ],high[ 236 ],high[ 237 ],high[ 238 ],high[ 239 ],high[ 240 ],high[ 241 ],high[ 242 ],high[ 243 ],high[ 244 ],high[ 245 ],high[ 246 ],high[ 247 ],high[ 248 ],high[ 249 ],high[ 250 ],high[ 251 ],high[ 252 ],high[ 253 ],high[ 254 ],high[ 255 ],high[ 256 ],high[ 257 ],high[ 258 ],high[ 259 ],high[ 260 ],high[ 261 ],high[ 262 ],high[ 263 ],high[ 264 ],high[ 265 ],high[ 266 ],high[ 267 ],high[ 268 ],high[ 269 ],high[ 270 ],high[ 271 ],high[ 272 ],high[ 273 ],high[ 274 ],high[ 275 ],high[ 276 ],high[ 277 ],high[ 278 ],high[ 279 ],high[ 280 ],high[ 281 ],high[ 282 ],high[ 283 ],high[ 284 ],high[ 285 ],high[ 286 ],high[ 287 ],high[ 288 ])
val_min_3 = math.min(low[ 289 ],low[ 290 ],low[ 291 ],low[ 292 ],low[ 293 ],low[ 294 ],low[ 295 ],low[ 296 ],low[ 297 ],low[ 298 ],low[ 299 ],low[ 300 ],low[ 301 ],low[ 302 ],low[ 303 ],low[ 304 ],low[ 305 ],low[ 306 ],low[ 307 ],low[ 308 ],low[ 309 ],low[ 310 ],low[ 311 ],low[ 312 ],low[ 313 ],low[ 314 ],low[ 315 ],low[ 316 ],low[ 317 ],low[ 318 ],low[ 319 ],low[ 320 ],low[ 321 ],low[ 322 ],low[ 323 ],low[ 324 ],low[ 325 ],low[ 326 ],low[ 327 ],low[ 328 ],low[ 329 ],low[ 330 ],low[ 331 ],low[ 332 ],low[ 333 ],low[ 334 ],low[ 335 ],low[ 336 ],low[ 337 ],low[ 338 ],low[ 339 ],low[ 340 ],low[ 341 ],low[ 342 ],low[ 343 ],low[ 344 ],low[ 345 ],low[ 346 ],low[ 347 ],low[ 348 ],low[ 349 ],low[ 350 ],low[ 351 ],low[ 352 ],low[ 353 ],low[ 354 ],low[ 355 ],low[ 356 ],low[ 357 ],low[ 358 ],low[ 359 ],low[ 360 ],low[ 361 ],low[ 362 ],low[ 363 ],low[ 364 ],low[ 365 ],low[ 366 ],low[ 367 ],low[ 368 ],low[ 369 ],low[ 370 ],low[ 371 ],low[ 372 ],low[ 373 ],low[ 374 ],low[ 375 ],low[ 376 ],low[ 377 ],low[ 378 ],low[ 379 ],low[ 380 ],low[ 381 ],low[ 382 ],low[ 383 ],low[ 384 ])
val_max_3 = math.max(high[ 289 ],high[ 290 ],high[ 291 ],high[ 292 ],high[ 293 ],high[ 294 ],high[ 295 ],high[ 296 ],high[ 297 ],high[ 298 ],high[ 299 ],high[ 300 ],high[ 301 ],high[ 302 ],high[ 303 ],high[ 304 ],high[ 305 ],high[ 306 ],high[ 307 ],high[ 308 ],high[ 309 ],high[ 310 ],high[ 311 ],high[ 312 ],high[ 313 ],high[ 314 ],high[ 315 ],high[ 316 ],high[ 317 ],high[ 318 ],high[ 319 ],high[ 320 ],high[ 321 ],high[ 322 ],high[ 323 ],high[ 324 ],high[ 325 ],high[ 326 ],high[ 327 ],high[ 328 ],high[ 329 ],high[ 330 ],high[ 331 ],high[ 332 ],high[ 333 ],high[ 334 ],high[ 335 ],high[ 336 ],high[ 337 ],high[ 338 ],high[ 339 ],high[ 340 ],high[ 341 ],high[ 342 ],high[ 343 ],high[ 344 ],high[ 345 ],high[ 346 ],high[ 347 ],high[ 348 ],high[ 349 ],high[ 350 ],high[ 351 ],high[ 352 ],high[ 353 ],high[ 354 ],high[ 355 ],high[ 356 ],high[ 357 ],high[ 358 ],high[ 359 ],high[ 360 ],high[ 361 ],high[ 362 ],high[ 363 ],high[ 364 ],high[ 365 ],high[ 366 ],high[ 367 ],high[ 368 ],high[ 369 ],high[ 370 ],high[ 371 ],high[ 372 ],high[ 373 ],high[ 374 ],high[ 375 ],high[ 376 ],high[ 377 ],high[ 378 ],high[ 379 ],high[ 380 ],high[ 381 ],high[ 382 ],high[ 383 ],high[ 384 ])
val_min_4 = math.min(low[ 385 ],low[ 386 ],low[ 387 ],low[ 388 ],low[ 389 ],low[ 390 ],low[ 391 ],low[ 392 ],low[ 393 ],low[ 394 ],low[ 395 ],low[ 396 ],low[ 397 ],low[ 398 ],low[ 399 ],low[ 400 ],low[ 401 ],low[ 402 ],low[ 403 ],low[ 404 ],low[ 405 ],low[ 406 ],low[ 407 ],low[ 408 ],low[ 409 ],low[ 410 ],low[ 411 ],low[ 412 ],low[ 413 ],low[ 414 ],low[ 415 ],low[ 416 ],low[ 417 ],low[ 418 ],low[ 419 ],low[ 420 ],low[ 421 ],low[ 422 ],low[ 423 ],low[ 424 ],low[ 425 ],low[ 426 ],low[ 427 ],low[ 428 ],low[ 429 ],low[ 430 ],low[ 431 ],low[ 432 ],low[ 433 ],low[ 434 ],low[ 435 ],low[ 436 ],low[ 437 ],low[ 438 ],low[ 439 ],low[ 440 ],low[ 441 ],low[ 442 ],low[ 443 ],low[ 444 ],low[ 445 ],low[ 446 ],low[ 447 ],low[ 448 ],low[ 449 ],low[ 450 ],low[ 451 ],low[ 452 ],low[ 453 ],low[ 454 ],low[ 455 ],low[ 456 ],low[ 457 ],low[ 458 ],low[ 459 ],low[ 460 ],low[ 461 ],low[ 462 ],low[ 463 ],low[ 464 ],low[ 465 ],low[ 466 ],low[ 467 ],low[ 468 ],low[ 469 ],low[ 470 ],low[ 471 ],low[ 472 ],low[ 473 ],low[ 474 ],low[ 475 ],low[ 476 ],low[ 477 ],low[ 478 ],low[ 479 ],low[ 480 ])
val_max_4 = math.max(high[ 385 ],high[ 386 ],high[ 387 ],high[ 388 ],high[ 389 ],high[ 390 ],high[ 391 ],high[ 392 ],high[ 393 ],high[ 394 ],high[ 395 ],high[ 396 ],high[ 397 ],high[ 398 ],high[ 399 ],high[ 400 ],high[ 401 ],high[ 402 ],high[ 403 ],high[ 404 ],high[ 405 ],high[ 406 ],high[ 407 ],high[ 408 ],high[ 409 ],high[ 410 ],high[ 411 ],high[ 412 ],high[ 413 ],high[ 414 ],high[ 415 ],high[ 416 ],high[ 417 ],high[ 418 ],high[ 419 ],high[ 420 ],high[ 421 ],high[ 422 ],high[ 423 ],high[ 424 ],high[ 425 ],high[ 426 ],high[ 427 ],high[ 428 ],high[ 429 ],high[ 430 ],high[ 431 ],high[ 432 ],high[ 433 ],high[ 434 ],high[ 435 ],high[ 436 ],high[ 437 ],high[ 438 ],high[ 439 ],high[ 440 ],high[ 441 ],high[ 442 ],high[ 443 ],high[ 444 ],high[ 445 ],high[ 446 ],high[ 447 ],high[ 448 ],high[ 449 ],high[ 450 ],high[ 451 ],high[ 452 ],high[ 453 ],high[ 454 ],high[ 455 ],high[ 456 ],high[ 457 ],high[ 458 ],high[ 459 ],high[ 460 ],high[ 461 ],high[ 462 ],high[ 463 ],high[ 464 ],high[ 465 ],high[ 466 ],high[ 467 ],high[ 468 ],high[ 469 ],high[ 470 ],high[ 471 ],high[ 472 ],high[ 473 ],high[ 474 ],high[ 475 ],high[ 476 ],high[ 477 ],high[ 478 ],high[ 479 ],high[ 480 ])
dif_min_max_3 =math.abs( val_max_3 - val_min_3 )
dif_min_max_1 =math.abs( val_max_1 - val_min_1 )
dif_min_max_0 =math.abs( val_max_0 - val_min_0 )
dif_min_max_4 =math.abs( val_max_4 - val_min_4 )
dif_min_max_2 =math.abs( val_max_2 - val_min_2 )
dif_max_min = math.abs( dif_min_max_4 + dif_min_max_0+dif_min_max_1+dif_min_max_2+dif_min_max_3)/5*1.3
week_nehaba_ave_up =(dif_min_max_0 > dif_max_min)
plotchar(week_nehaba_ave_up,location = location.top,char = '周',size = size.tiny,color =color.rgb(105, 248, 246) )
haba = 0.4
now_max_condition_1H = (val_max_1H - close[0]) < 0.2
no_near_big_down = ((val_max_1H - val_min_1H) < haba)
near_min_50 = ( close[0] - val_min_4H) > 0.3
near_max_within_30 =(val_max_1H - close[0] ) < 0.2
plotchar(near_max_within_30 ,location = location.top,char = '三',size = size.tiny,color =color.rgb(234, 43, 13) )
plotchar(near_min_50 ,location = location.bottom,char = '三',size = size.tiny,color =color.rgb(237, 35, 12) )
kiriage = low[1]<low[0]
kirisage = high[1]>high[0]
// plotchar(kirisage,location = location.top,char = '♪',size = size.tiny,color =color.rgb(8, 10, 10) )
// plotchar(kiriage,location = location.bottom,char = '♪',size = size.tiny,color =color.rgb(8, 10, 10) )
close_Without_lower = (lower > val_min_5m)
close_Without_uper = (upper < val_max_5m)
// plotchar(close_Without_lower,location = location.bottom,char = 'w',size = size.tiny,color =color.rgb(105, 248, 246))
barcolor(isTUTUMI and week_nehaba_ave_up ? color.rgb(255, 235, 59, 64) : na)
hr_25 = hour == 18 ? true:false
hr_0 = hour == 0 ? true:false
hr_1 = hour == 12 ? true:false
hr_2 = hour == 13 ? true:false
hr_3 = hour == 3 ? true:false
hr_14 = hour == 14 ? true:false
hr_15 = hour == 2 ? true:false
hr_16 = hour == 3 ? true:false
hr_17 = hour == 4 ? true:false
hr_18 = hour == 5 ? true:false
hr_19 = hour == 6 ? true:false
hr_9 = hour == 9 ? true:false
hr_10 = hour == 10 ? true:false
hr_11 = hour == 11 ? true:false
hr_12 = hour == 12 ? true:false
hr_13 = hour == 13 ? true:false
hr_20 = hour == 20 ? true:false
hr_21 = hour == 8 ? true:false
hr_24 = hour == 24 ? true:false
hr_22 = hour == 16 ? true:false
hr_23 = hour == 23 ? true:false
min_0 = minute == 0
min_15 = minute == 15
min_30 = minute == 30
min_45 = minute == 45
loss_val = val_max_1H - close[0]
profit_val = 50
bgcolor(hr_23? color.rgb(248, 163, 229, 85) : na)
longCondition = isTUTUMI_short and macd_long and near_min_50 and macd_short_2
plotchar(longCondition ,location = location.abovebar,char = 'S',size = size.tiny,color =color.rgb(249, 23, 7) )
longCondition2 = close_Without_lower and macd_long and macd_short_2
plotchar(longCondition2 ,location = location.abovebar,char = 'S',size = size.tiny,color =color.rgb(7, 31, 249) )
if (longCondition or longCondition2)
if(hr_20)
strategy.entry("My Entry Id_9", strategy.short,comment = "9EN")
|
TradersPost Example MOMO Strategy | https://www.tradingview.com/script/vqQ3BfVs-TradersPost-Example-MOMO-Strategy/ | mamalonefv | https://www.tradingview.com/u/mamalonefv/ | 3 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradersPostInc
//@version=5
strategy('TradersPost Example MOMO Strategy', overlay=true, default_qty_value=100, initial_capital=100000, default_qty_type=strategy.percent_of_equity, pyramiding=0)
startTime = input.time(defval = timestamp('01 Jan 2021 00:00 +0000'), title = 'Start Time', group = 'Date Range')
endTime = input.time(defval = timestamp('31 Dec 2023 23:59 +0000'), title = 'End Time', group = 'Date Range')
timeCondition = time >= startTime and time < endTime
timeConditionEnd = timeCondition[1] and not timeCondition
fastEmaLength = input.int(defval = 8, title = 'Fast EMA Length')
slowEmaLength = input.int(defval = 21, title = 'Slow EMA Length')
sides = input.string(defval = 'Both', title = 'Sides', options = ['Long', 'Short', 'Both', 'None'])
fastEma = ta.ema(close, fastEmaLength)
slowEma = ta.ema(close, slowEmaLength)
isUptrend = fastEma >= slowEma
isDowntrend = fastEma <= slowEma
trendChanging = ta.cross(fastEma, slowEma)
ema105 = request.security(syminfo.tickerid, '30', ta.ema(close, 105)[1], barmerge.gaps_off, barmerge.lookahead_on)
ema205 = request.security(syminfo.tickerid, '30', ta.ema(close, 20)[1], barmerge.gaps_off, barmerge.lookahead_on)
plot(ema105, linewidth=4, color=color.new(color.purple, 0), editable=true)
plot(ema205, linewidth=2, color=color.new(color.purple, 0), editable=true)
aa = plot(fastEma, linewidth=3, color=color.new(color.green, 0), editable=true)
bb = plot(slowEma, linewidth=3, color=color.new(color.red, 0), editable=true)
fill(aa, bb, color=isUptrend ? color.green : color.red, transp=90)
tradersPostBuy = trendChanging and isUptrend and timeCondition
tradersPostSell = trendChanging and isDowntrend and timeCondition
pips = syminfo.pointvalue / syminfo.mintick
percentOrPipsInput = input.string('Percent', title='Percent or Pips', options=['Percent', 'Pips'])
stopLossLongInput = input.float(defval=0, step=0.01, title='Stop Loss Long', minval=0)
stopLossShortInput = input.float(defval=0, step=0.01, title='Stop Loss Short', minval=0)
takeProfitLongInput = input.float(defval=0, step=0.01, title='Target Profit Long', minval=0)
takeProfitShortInput = input.float(defval=0, step=0.01, title='Target Profit Short', minval=0)
stopLossPriceLong = ta.valuewhen(tradersPostBuy, close, 0) * (stopLossLongInput / 100) * pips
stopLossPriceShort = ta.valuewhen(tradersPostSell, close, 0) * (stopLossShortInput / 100) * pips
takeProfitPriceLong = ta.valuewhen(tradersPostBuy, close, 0) * (takeProfitLongInput / 100) * pips
takeProfitPriceShort = ta.valuewhen(tradersPostSell, close, 0) * (takeProfitShortInput / 100) * pips
takeProfitALong = takeProfitLongInput > 0 ? takeProfitLongInput : na
takeProfitBLong = takeProfitPriceLong > 0 ? takeProfitPriceLong : na
takeProfitAShort = takeProfitShortInput > 0 ? takeProfitShortInput : na
takeProfitBShort = takeProfitPriceShort > 0 ? takeProfitPriceShort : na
stopLossALong = stopLossLongInput > 0 ? stopLossLongInput : na
stopLossBLong = stopLossPriceLong > 0 ? stopLossPriceLong : na
stopLossAShort = stopLossShortInput > 0 ? stopLossShortInput : na
stopLossBShort = stopLossPriceShort > 0 ? stopLossPriceShort : na
takeProfitLong = percentOrPipsInput == 'Pips' ? takeProfitALong : takeProfitBLong
stopLossLong = percentOrPipsInput == 'Pips' ? stopLossALong : stopLossBLong
takeProfitShort = percentOrPipsInput == 'Pips' ? takeProfitAShort : takeProfitBShort
stopLossShort = percentOrPipsInput == 'Pips' ? stopLossAShort : stopLossBShort
buyAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "buy", "price": ' + str.tostring(close) + '}'
sellAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "sell", "price": ' + str.tostring(close) + '}'
exitLongAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit", "price": ' + str.tostring(close) + '}'
exitShortAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit", "price": ' + str.tostring(close) + '}'
if (sides != "None")
if tradersPostBuy
strategy.entry('Long', strategy.long, when = sides != 'Short', alert_message = buyAlertMessage)
strategy.close('Short', when = sides == "Short" and timeCondition, alert_message = exitShortAlertMessage)
if tradersPostSell
strategy.entry('Short', strategy.short, when = sides != 'Long', alert_message = sellAlertMessage)
strategy.close('Long', when = sides == 'Long', alert_message = exitLongAlertMessage)
exitAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit"}'
strategy.exit('Exit Long', from_entry = "Long", profit = takeProfitLong, loss = stopLossLong, alert_message = exitAlertMessage)
strategy.exit('Exit Short', from_entry = "Short", profit = takeProfitShort, loss = stopLossShort, alert_message = exitAlertMessage)
strategy.close_all(when = timeConditionEnd) |
Keltner Channel Strategy with Golden Cross | https://www.tradingview.com/script/9N0JyfyH-Keltner-Channel-Strategy-with-Golden-Cross/ | OversoldPOS | https://www.tradingview.com/u/OversoldPOS/ | 36 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OversoldPOS
//@version=5
strategy("Keltner Channel Strategy by OversoldPOS", overlay=true,initial_capital = 100000,default_qty_type = strategy.percent_of_equity,default_qty_value = 10, commission_type = strategy.commission.cash_per_order, commission_value = 7)
// Parameters
length = input(21, title="MA Length")
Entrymult = input(1, title="Entry ATR")
profit_mult = input(4, title="Profit Taker")
exit_mult = input(-1, title="Exit ATR")
// Moving Average Type Input
ma_type = input.string("SMA", title="Moving Average Type", options=["SMA", "EMA", "WMA"])
// Calculate Keltner Channels for different ATR multiples
atr_value = ta.atr(length)
basis = switch ma_type
"SMA" => ta.sma(close, length)
"EMA" => ta.ema(close, length)
"WMA" => ta.wma(close, length)
//
EntryKeltLong = basis + Entrymult * ta.atr(10)
EntryKeltShort = basis - Entrymult * ta.atr(10)
upper_channel1 = basis + 1 * ta.atr(10)
lower_channel1 = basis - 1 * ta.atr(10)
upper_channel2 = basis + 2 * ta.atr(10)
lower_channel2 = basis - 2 * ta.atr(10)
upper_channel3 = basis + 3 * ta.atr(10)
lower_channel3 = basis - 3 * ta.atr(10)
upper_channel4 = basis + 4 * ta.atr(10)
lower_channel4 = basis - 4 * ta.atr(10)
// Entry condition parameters
long_entry_condition = input(true, title="Long Positions")
short_entry_condition = input(true, title="Enable Short Positions")
// Additional conditions for long and short entries
is_long_entry = ta.ema(close, 20) > ta.ema(close, 50)
is_short_entry = ta.ema(close, 20) < ta.ema(close, 50)
// Additional conditions for long and short entries
MAShort = input(50, title="Short MA for Golden Cross")
MALong = input(200, title="Long MA for Golden Cross")
is_long_entry2 = ta.ema(close, MAShort) > ta.ema(close, MALong)
is_short_entry2 = ta.ema(close, MAShort) < ta.ema(close, MALong)
// Exit condition parameters
long_exit_condition1_enabled = input(true, title="Enable Long Profit Taker")
long_exit_condition2_enabled = input(true, title="Enable Long Stop")
short_exit_condition1_enabled = input(true, title="Enable Short Profit Taker")
short_exit_condition2_enabled = input(true, title="Enable Short Stop")
// Take Profit condition parameters
take_profit_enabled = input(true, title="Enable Take Profit Condition")
Takeprofit = basis + profit_mult * atr_value
STakeprofit = basis - profit_mult * atr_value
// Long entry condition
long_condition = long_entry_condition and ta.crossover(close, EntryKeltLong) and is_long_entry2
// Short entry condition
short_condition = short_entry_condition and ta.crossunder(close, EntryKeltShort) and is_short_entry2
// Exit conditions
long_exit_condition1 = long_exit_condition1_enabled and close > Takeprofit
long_exit_condition2 = long_exit_condition2_enabled and close < basis + exit_mult * atr_value
short_exit_condition1 = short_exit_condition1_enabled and close < STakeprofit
short_exit_condition2 = short_exit_condition2_enabled and close > basis - exit_mult * atr_value
// Strategy logic
if (long_condition)
strategy.entry("Long", strategy.long)
if (short_condition)
strategy.entry("Short", strategy.short)
if (long_exit_condition1 or long_exit_condition2)
strategy.close("Long")
if (short_exit_condition1 or short_exit_condition2)
strategy.close("Short")
// Moving Averages
var float MA1 = na
var float MA2 = na
if (ma_type == "SMA")
MA1 := ta.sma(close, MAShort)
MA2 := ta.sma(close, MALong)
else if (ma_type == "EMA")
MA1 := ta.ema(close, MAShort)
MA2 := ta.ema(close, MALong)
else if (ma_type == "WMA")
MA1 := ta.wma(close, MAShort)
MA2 := ta.wma(close, MALong)
// Plotting Keltner Channels with adjusted transparency
transparentColor = color.rgb(255, 255, 255, 56)
plot(upper_channel1, color=transparentColor, title="Upper Channel 1")
plot(lower_channel1, color=transparentColor, title="Lower Channel 1")
plot(upper_channel2, color=transparentColor, title="Upper Channel 2")
plot(lower_channel2, color=transparentColor, title="Lower Channel 2")
plot(upper_channel3, color=transparentColor, title="Upper Channel 3")
plot(lower_channel3, color=transparentColor, title="Lower Channel 3")
plot(upper_channel4, color=transparentColor, title="Upper Channel 4")
plot(lower_channel4, color=transparentColor, title="Lower Channel 4")
plot(basis, color=color.white, title="Basis")
plot(MA1, color=color.rgb(4, 248, 216), linewidth=2, title="Middle MA")
plot(MA2, color=color.rgb(220, 7, 248), linewidth=2, title="Long MA")
|
IU Break of any session Strategy | https://www.tradingview.com/script/vFfsTzRy-IU-Break-of-any-session-Strategy/ | Strategy_coders | https://www.tradingview.com/u/Strategy_coders/ | 58 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © shivammandrai
//@version=5
strategy("Break of any session IU ", shorttitle="Sesion Breakout IU",overlay=true)
///// CREATING CUSTOME SESSION
custome_session = input.session("0915-1000", title='Enter your Session')
custome_session_plot = time("", custome_session)
Profit_Factor = input.float(2.0, "RTR ? ")
// CREATING IN AND OUT TIME
TimeIn = input.session(defval= "0915-1430")
TimeOut = input.session(defval= "1445-1500")
EntryTime = time(timeframe.period, TimeIn)
ExitTime = time(timeframe.period, TimeOut)
///// CHECKING SESSIONS
into_the_session = time(timeframe.period, custome_session)
next_session(R, S) =>
Time = time(R, S)
na(Time[1]) and not na(Time) or Time[1] < Time
New_session = next_session("1440", custome_session)
///// CHECKING NEW SESSIONS
next_candle(R,S) =>
Time = time(R,S)
not na(Time) and (na(Time[1]) or Time > Time[1])
new = (next_candle("1440", custome_session) ? 1 : 0)
//// STORING HIGH AND LOW
var float Low = close
var float High = close
Low := New_session? low : into_the_session ? math.min(low, Low[1]) : na
High := New_session ? high : into_the_session ? math.max(high, High[1]) : na
//// GETTING FINAL HIGH AND LOW
extend_low = ta.valuewhen((Low == low),low,0)
extend_high = ta.valuewhen((High == high),high,0)
///// CREATING CONDITIONS FOR GETTING END SESSION
start_of_session_value = ta.valuewhen((new==1),high,0)
end_session_condition = start_of_session_value !=start_of_session_value[1]?0: into_the_session?1:0
// LONG AND SHORT CONDITIONS
var bool tradeExecuted = false
long = extend_high > open and( (extend_high + 5) < close) and not tradeExecuted
short = extend_low < open and ((extend_low - 5) > close) and not tradeExecuted
if strategy.position_size == 0 and EntryTime and long //and ADX
strategy.entry("long", strategy.long, comment = "Long Trade")
alert("Long Entry has tigger", alert.freq_once_per_bar_close)
tradeExecuted := true
if strategy.position_size == 0 and EntryTime and short// and ADX
strategy.entry("short", strategy.short, comment = "Short Trade")
alert("Short Entry has tigger", alert.freq_once_per_bar_close)
tradeExecuted := true
// LONG AND SHORT STOP LOSS
longSL = low[bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1]
shortSL = high[bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1]
longTP = ((close[bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1] - longSL) * Profit_Factor ) + close[bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1]
shortTP = close[bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1] - ((shortSL - close[bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1] ) * Profit_Factor)
// EXITING TRADES
strategy.exit("long", from_entry = "long", stop = longSL, limit = longTP, comment = "Long Exit")
strategy.exit("short", "short", comment = "Short Exit", stop = shortSL, limit = shortTP)
// INTRADAY EXIT
if ExitTime
strategy.close_all(immediately = true, comment = "Closing bell")
tradeExecuted := false
///// PLOTTING FINAL VALUES
plot(strategy.position_size > 0 ? longSL: na, color = color.purple, style = plot.style_linebr)
plot( strategy.position_size < 0 ?shortSL: na, color = color.yellow, style = plot.style_linebr)
plot(strategy.position_size > 0 ? longTP: na, color = color.lime, style = plot.style_linebr)
plot( strategy.position_size < 0 ?shortTP: na, color = color.lime, style = plot.style_linebr)
plot(not na(EntryTime) ? extend_high : na, color = color.green, style = plot.style_linebr)
plot( not na(EntryTime) ? extend_low : na, color = color.green, style = plot.style_linebr) |
3kilos BTC 15m | https://www.tradingview.com/script/M9tw82HU-3kilos-BTC-15m/ | deperp | https://www.tradingview.com/u/deperp/ | 171 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © deperp
//@version=5
strategy('3kilos', shorttitle='3kilos BTC 15m', overlay=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.07, pyramiding=0)
short = input.int(30, minval=1)
srcShort = input(high, title='TEMA short')
long = input.int(50, minval=1)
srcLong = input(low, title='TEMA long 2')
long2 = input.int(140, minval=1)
srcLong2 = input(close, title='TEMA long 3')
atrLength = input.int(10, title='ATR Length', minval=1)
mult = input.float(2, title="Multiplier", minval=0.5, step=1)
takeProfitPercent = input.float(1, title="Take Profit (%)", minval=0.1) / 100
stopLossPercent = input.float(1, title="Stop Loss (%)", minval=0.1) / 100
tema(src, length) =>
ema1 = ta.ema(src, length)
ema2 = ta.ema(ema1, length)
ema3 = ta.ema(ema2, length)
3 * (ema1 - ema2) + ema3
tema1 = tema(srcShort, short)
plot(tema1, color=color.new(color.red, 0), linewidth=2)
tema2 = tema(srcLong, long)
plot(tema2, color=color.new(color.blue, 0), linewidth=2)
tema3 = tema(srcLong2, long2)
plot(tema3, color=color.new(color.green, 0), linewidth=2)
// Custom ATR calculation with EMA smoothing
atr_ema(src, length) =>
trueRange = math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
emaTrueRange = ta.ema(trueRange, length)
emaTrueRange
// Calculate ATR with EMA smoothing
atr = atr_ema(close, atrLength)
// Calculate Supertrend
var float up = na
var float dn = na
var bool uptrend = na
up := na(up[1]) ? hl2 - (mult * atr) : uptrend[1] ? math.max(hl2 - (mult * atr), up[1]) : hl2 - (mult * atr)
dn := na(dn[1]) ? hl2 + (mult * atr) : uptrend[1] ? hl2 + (mult * atr) : math.min(hl2 + (mult * atr), dn[1])
uptrend := na(uptrend[1]) ? true : close[1] > dn[1] ? true : close[1] < up[1] ? false : uptrend[1]
longC = ta.crossover(tema2, tema1) and tema2 > tema3 and uptrend and tema1
shortC = ta.crossover(tema1, tema2) and tema2 < tema3 and not uptrend and tema1
alertlong = longC and not longC[1]
alertshort = shortC and not shortC[1]
useDateFilter = input.bool(true, title="Begin Backtest at Start Date",
group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2023"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
inTradeWindow = not useDateFilter or time >= backtestStartDate
longTakeProfitLevel = close * (1 + takeProfitPercent)
longStopLossLevel = close * (1 - stopLossPercent)
shortTakeProfitLevel = close * (1 - takeProfitPercent)
shortStopLossLevel = close * (1 + stopLossPercent)
if inTradeWindow and longC
strategy.entry('Long', strategy.long, comment='Long')
strategy.exit("TP Long", "Long", limit=longTakeProfitLevel, stop=longStopLossLevel, comment="TP/SL Long")
if inTradeWindow and shortC
strategy.entry('Short', strategy.short, comment='Short')
strategy.exit("TP Short", "Short", limit=shortTakeProfitLevel, stop=shortStopLossLevel, comment="TP/SL Short")
// Alerts
alertcondition(longC, title='Long', message=' Long Signal ')
alertcondition(shortC, title='Short', message=' Short Signal ') |
Time Session Filter - MACD example | https://www.tradingview.com/script/O9GMbDXE-Time-Session-Filter-MACD-example/ | Harrocop | https://www.tradingview.com/u/Harrocop/ | 20 | strategy | 5 | MPL-2.0 | /// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Harrocop
////////////////////////////////////////////////////////////////////////////////////////
// This is and exmaple how to incorperate a sessionfilter into your strategy
// It gives traders the possibility to quickly adjust time filters to enter between specific time periodes.
// The Strategy comes with the following.
// - Basic Risk Position Sizingtool. For more info see: https://www.tradingview.com/script/HAp1ed0F-Risk-Management-and-Positionsize-MACD-example/
// - MACD Signalline based on Higher Time Frame Settings. For more info see: https://www.tradingview.com/script/rQbmGtAx-MACD-HTF-Dynamic-Smoothing/
// - Filter based on Moving Average Type on higher time frame settings. For more info see: https://www.tradingview.com/script/WSfUYnNA-HTF-Trend-Filter-Dynamic-Smoothing/
// - Dynamic smoothing calculations makes a sleek line, taking the ratio of minutes of the higher time frame to the current time frame.
// - Exit strategy is simplified using MACD crossover / crossunder.
// - no fixed stoploss.
// - option to exit trade when session ends.
// - The below strategy is for educational purposes about how to use a session filter into your strategy.
////////////////////////////////////////////////////////////////////////////////////////
//@version=5
strategy(title = "Time Session Filter - MACD example", shorttitle = "Time Session Filter", overlay=true,
pyramiding=0, initial_capital = 10000,
calc_on_order_fills=false,
slippage = 0,
commission_type=strategy.commission.percent, commission_value=0.03)
/////////////////////////////////////////////////////////////////////////////////////
////////////////// Time Session Filter //////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
TIMESESSION = "Time Session Filter"
Use_Session = input.bool(defval = true, title = 'Session ', inline = 'Session', group = TIMESESSION, tooltip = "turns on sessino filter")
Time_Session = input.session(defval = '1100-1500', title = '', inline = 'Session', group = TIMESESSION, tooltip = "time according to your tradingview timezone") + ':'
+ (input.bool(defval = true, title = 'Mon', inline = 'Days', group = TIMESESSION) ? str.tostring(dayofweek.monday) : '')
+ (input.bool(defval = true, title = 'Tue', inline = 'Days', group = TIMESESSION) ? str.tostring(dayofweek.tuesday) : '')
+ (input.bool(defval = true, title = 'Wed', inline = 'Days', group = TIMESESSION) ? str.tostring(dayofweek.wednesday) : '')
+ (input.bool(defval = true, title = 'Thu', inline = 'Days', group = TIMESESSION) ? str.tostring(dayofweek.thursday) : '')
+ (input.bool(defval = true, title = 'Fri', inline = 'Days', group = TIMESESSION) ? str.tostring(dayofweek.friday) : '')
+ (input.bool(defval = true, title = 'Sat', inline = 'Days', group = TIMESESSION) ? str.tostring(dayofweek.saturday) : '')
+ (input.bool(defval = true, title = 'Sun', inline = 'Days', group = TIMESESSION) ? str.tostring(dayofweek.sunday) : '')
closeSessionEnd = input.bool (defval = false, title = 'Close at Session End', group = TIMESESSION, tooltip = 'When session ends it closes position')
Session_Filter = Use_Session ? not (na(time(timeframe.period, Time_Session)) or na(time_close(timeframe.period, Time_Session))) : true
// Color the background when the session is active
bgcolor(Session_Filter ? color.new(color.green, 90) : color.new(color.red, 90), title="Session Background")
//////////////////////////////////////////////////////
////////// Risk Management ////////////
//////////////////////////////////////////////////////
RISKM = "Risk Management"
InitialBalance = input.float(defval = 10000, title = "Initial Balance", minval = 1, maxval = 1000000, step = 1000, tooltip = "starting capital", group = RISKM)
LeverageEquity = input.bool(defval = true, title = "qty based on equity %", tooltip = "true turns on MarginFactor based on equity, false gives fixed qty for positionsize", group = RISKM)
MarginFactor = input.float(-0.5, minval = - 0.9, maxval = 100, step = 0.1, tooltip = "Margin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument", inline = "qty", group = RISKM)
QtyNr = input.float(defval = 3.5, title = "Quantity Contracts", minval = 0, maxval = 1000000, step = 0.01, tooltip = "Margin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument", inline = "qty", group = RISKM)
EquityCurrent = InitialBalance + strategy.netprofit[1]
QtyEquity = EquityCurrent * (1 + MarginFactor) / close[1]
QtyTrade = LeverageEquity ? QtyEquity : QtyNr
//////////////////////////////////////////////////////
////////// Input MACD HTF ////////////
//////////////////////////////////////////////////////
MACD_settings = "Higher Time Frame MACD Settings"
MA_Type = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA"], title="MA type", inline = "1", group = MACD_settings)
TimeFrame_MACD = input.timeframe(title='Higher Time Frame', defval='30', inline = "1", group = MACD_settings)
fastlength = input.int(11, title="Fast MA Length", minval=1, inline = "2", group = MACD_settings)
slowlength = input.int(26, title="Slow MA Length", minval=1, inline = "2", group = MACD_settings)
signallength = input.int(9, title="Length Signal MA", minval=1, inline = "3", group = MACD_settings)
Plot_Signal = input.bool(true, title = "Plot Signal?", inline = "3", group = MACD_settings)
ma(type, src, length) =>
float result = 0
if type == 'TMA' // Triangular Moving Average
result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
result
if type == 'LSMA' // Least Squares Moving Average
result := ta.linreg(src, length, 0)
result
if type == 'SMA' // Simple Moving Average
result := ta.sma(src, length)
result
if type == 'EMA' // Exponential Moving Average
result := ta.ema(src, length)
result
if type == 'DEMA' // Double Exponential Moving Average
e = ta.ema(src, length)
result := 2 * e - ta.ema(e, length)
result
if type == 'TEMA' // Triple Exponentiale
e = ta.ema(src, length)
result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)
result
if type == 'WMA' // Weighted Moving Average
result := ta.wma(src, length)
result
if type == 'HMA' // Hull Moving Average
result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
result
result
// MACD function for calculation higher timeframe
macd_function() =>
fast_ma = ma(MA_Type, close, fastlength)
slow_ma = ma(MA_Type, close, slowlength)
macd = fast_ma - slow_ma
macd
signal_function() =>
fast_ma = ma(MA_Type, close, fastlength)
slow_ma = ma(MA_Type, close, slowlength)
macd = fast_ma - slow_ma
signal = ma(MA_Type, macd, signallength)
signal
hist_function() =>
fast_ma = ma(MA_Type, close, fastlength)
slow_ma = ma(MA_Type, close, slowlength)
macd = fast_ma - slow_ma
signal = ma(MA_Type, macd, signallength)
hist = macd - signal
hist
MACD_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, macd_function())
SIGNAL_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, signal_function())
HIST_Value_HTF = MACD_Value_HTF - SIGNAL_Value_HTF
// Get minutes for current and higher timeframes
// Function to convert a timeframe string to its equivalent in minutes
timeframeToMinutes(tf) =>
multiplier = 1
if (str.endswith(tf, "D"))
multiplier := 1440
else if (str.endswith(tf, "W"))
multiplier := 10080
else if (str.endswith(tf, "M"))
multiplier := 43200
else if (str.endswith(tf, "H"))
multiplier := int(str.tonumber(str.replace(tf, "H", "")))
else
multiplier := int(str.tonumber(str.replace(tf, "m", "")))
multiplier
// Get minutes for current and higher timeframes
currentTFMinutes = timeframeToMinutes(timeframe.period)
higherTFMinutes = timeframeToMinutes(TimeFrame_MACD)
// Calculate the smoothing factor
dynamicSmoothing = math.round(higherTFMinutes / currentTFMinutes)
MACD_Value_HTF_Smooth = ta.sma(MACD_Value_HTF, dynamicSmoothing)
SIGNAL_Value_HTF_Smooth = ta.sma(SIGNAL_Value_HTF, dynamicSmoothing)
HIST_Value_HTF_Smooth = ta.sma(HIST_Value_HTF, dynamicSmoothing)
// Determin Long and Short Conditions
LongCondition = ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth < 0
ShortCondition = ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth > 0
//////////////////////////////////////////////////////
////////// Filter Trend ////////////
//////////////////////////////////////////////////////
TREND = "Higher Time Frame Trend"
TimeFrame_Trend = input.timeframe(title='Higher Time Frame', defval='1D', inline = "Trend1", group = TREND)
length = input.int(55, title="Length MA", minval=1, tooltip = "Number of bars used to measure trend on higher timeframe chart", inline = "Trend1", group = TREND)
MA_Type_trend = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA", "McGinley"], title="MA type for HTF trend", inline = "Trend2", group = TREND)
ma_trend(type, src, length) =>
float result = 0
if type == 'TMA' // Triangular Moving Average
result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
result
if type == 'LSMA' // Least Squares Moving Average
result := ta.linreg(src, length, 0)
result
if type == 'SMA' // Simple Moving Average
result := ta.sma(src, length)
result
if type == 'EMA' // Exponential Moving Average
result := ta.ema(src, length)
result
if type == 'DEMA' // Double Exponential Moving Average
e = ta.ema(src, length)
result := 2 * e - ta.ema(e, length)
result
if type == 'TEMA' // Triple Exponentiale
e = ta.ema(src, length)
result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)
result
if type == 'WMA' // Weighted Moving Average
result := ta.wma(src, length)
result
if type == 'HMA' // Hull Moving Average
result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
result
if type == 'McGinley' // McGinley Dynamic Moving Average
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, length) : mg[1] + (src - mg[1]) / (length * math.pow(src / mg[1], 4))
result := mg
result
result
// Moving Average
MAtrend = ma_trend(MA_Type_trend, close, length)
MA_Value_HTF = request.security(syminfo.ticker, TimeFrame_Trend, MAtrend)
// Get minutes for current and higher timeframes
higherTFMinutes_trend = timeframeToMinutes(TimeFrame_Trend)
// Calculate the smoothing factor
dynamicSmoothing_trend = math.round(higherTFMinutes_trend / currentTFMinutes)
MA_Value_Smooth = ta.sma(MA_Value_HTF, dynamicSmoothing_trend)
// Trend HTF
UP = MA_Value_Smooth > MA_Value_Smooth[1] // Use "UP" Function to use as filter in combination with other indicators
DOWN = MA_Value_Smooth < MA_Value_Smooth[1] // Use "Down" Function to use as filter in combination with other indicators
/////////////////////////////////////////////////
/////////// Strategy ////////////////
/////////////////////////////////////////////////
if LongCondition and UP == true and Session_Filter
strategy.entry("Long", strategy.long, qty = QtyTrade)
strategy.close_all(when = strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))
if ShortCondition and DOWN == true and Session_Filter
strategy.entry("Short", strategy.short, qty = QtyTrade)
strategy.close_all(when = strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))
strategy.close_all(when = closeSessionEnd and not Session_Filter)
|
Hoffman Heiken Bias | https://www.tradingview.com/script/MFtxhYEZ-Hoffman-Heiken-Bias/ | mdenson | https://www.tradingview.com/u/mdenson/ | 39 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mdenson
//@version=4
strategy("Hoffman Heiken Bias", overlay=true, margin_long=100, margin_short=100)
b = sma(close,5)
c = ema(close,18)
d = ema(close,20)
e = sma(close,50)
f = sma(close,89)
g = ema(close,144)
k = ema(close,35)
r = rma(tr,35)
ku = k + r*0.5
kl = k - r*0.5
downtrend = d>c and e>c and f>c and g>c and k>c and ku>c and kl>c
uptrend = d<c and e<c and f<c and g<c and k<c and ku<c and kl<c
//========================================================================================
//Volatility Osc
//Volatility OSC
volatilitylength = input(100)
spike = close - open
volupband = stdev(spike, volatilitylength)
voldnband = stdev(spike, volatilitylength) * -1
//Hoffman IRBs
z = input(45, title="Inventory Retracement Percentage %", maxval=100)
// Candle Range
a2 = abs(high - low)
// Candle Body
b2 = abs(close - open)
// Percent to Decimal
c2 = z/100
// Range Verification
rv = b2 < c2*a2
// Price Level for Retracement
x = low + (c2 * a2)
y = high - (c2 * a2)
sl = rv == 1 and high > y and close < y and open < y
ss = rv == 1 and low < x and close > x and open > x
// Line Definition
li = sl ? y : ss ? x : (x+y)/2
//==========================================================================================
//==================================================================
//Heiken Ashi Candle Calculations
hkClose = (open + high + low + close) / 4
hkOpen = float(na)
hkOpen := na(hkOpen[1]) ? (open + close) / 2 : (nz(hkOpen[1]) + nz(hkClose[1])) / 2
hkHigh = max(high, max(hkOpen, hkClose))
hkLow = min(low, min(hkOpen, hkClose))
hkHl2 = (hkOpen + hkClose)/2
volumeHA = security(heikinashi(syminfo.tickerid), timeframe.period, volume)
//===================================================================
//volume Net Histogram calculations
topwick = iff(hkOpen<hkClose, hkHigh - hkClose, hkHigh - hkOpen)
bottomwick = iff(hkOpen<hkClose, hkOpen-hkLow, hkClose-hkLow)
body = iff(hkOpen<hkClose, hkClose-hkOpen, hkOpen-hkClose)
ohcl4 = (hkHigh+hkLow+hkOpen+hkClose)/4
fractionup = iff( hkOpen<hkClose, (topwick + bottomwick + 2*body)/(2*topwick + 2*bottomwick + 2*body), (topwick + bottomwick)/(2*topwick + 2*bottomwick + 2*body) )
fractiondown = iff( hkOpen<hkClose, (topwick + bottomwick)/(2*topwick + 2*bottomwick + 2*body), (topwick + bottomwick + 2*body)/(2*topwick + 2*bottomwick + 2*body) )
volumeup = volume * fractionup * ohcl4
volumedown = volume * fractiondown * ohcl4
netvolume = volumeup - volumedown
lengthMA =input(25, title="length")
netplot = linreg(netvolume, lengthMA, -lengthMA)
long = b>c and uptrend and netplot>0 //and close[3]<close[2] and close[2] > close [1] and close>close[1] and spike > volupband
short = b<c and downtrend and netplot<0 // and close[3]>close[2] and close[2] < close [1] and close<close[1] and spike < voldnband
plotshape(long, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), size=size.small)
plotshape(short, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), size=size.small)
|
YinYang RSI Volume Trend Strategy | https://www.tradingview.com/script/cO34DTxx-YinYang-RSI-Volume-Trend-Strategy/ | YinYangAlgorithms | https://www.tradingview.com/u/YinYangAlgorithms/ | 366 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// © YinYangAlgorithms
//@version=5
strategy("YinYang RSI Volume Trend Strategy", shorttitle="YinYang RSVT Strategy", overlay=true, initial_capital=1000000, default_qty_type=strategy.cash, default_qty_value=1000000)
// ~~~~~~~~~~~ INPUTS ~~~~~~~~~~~ //
len = input.int(80, "Trend Length:", tooltip="How far back should we span this indicator?\nThis length effects all lengths of the indicator")
purchaseSrc = input.source(close, "Purchase Source (Long and Short):", tooltip="What source needs to exit the purchase zone for a purchase to happen?")
exitSrc = input.source(close, "Exit Source (Long and Short):", tooltip="What source needs to hit a exit condition to stop the trade (Take profit, Stop Loss or hitting the other sides Purchase Zone)?")
useTakeProfit = input.bool(true, "Use Take Profit", tooltip="Should we take profit IF we cross the basis line and then cross it AGAIN?")
useStopLoss = input.bool(true, "Use Stop Loss", tooltip="Stop loss will ensure you don't lose too much if its a bad call")
stopLossMult = input.float(0.1, "Stoploss Multiplier %:", tooltip="How far from the purchase lines should the stop loss be")
resetCondition = input.string("Entry", "Reset Purchase Availability After:", options=["Entry", "Stop Loss", "None"],
tooltip="If we reset after a condition is hit, this means we can purchase again when the purchase condition is met. \n" +
"Otherwise, we will only purchase after an opposite signal has appeared.\n" +
"Entry: means when the close enters the purchase zone (buy or sell).\n" +
"Stop Loss: means when the close hits the stop loss location (even when were out of a trade)\n" +
"This allows us to get more trades and also if our stop loss initally was hit but it WAS a good time to purchase, we don't lose that chance.")
// ~~~~~~~~~~~ VARIABLES ~~~~~~~~~~~ //
var bool longStart = na
var bool longAvailable = na
var bool longTakeProfitAvailable = na
var bool longStopLoss = na
var bool shortStart = na
var bool shortAvailable = na
var bool shortTakeProfitAvailable = na
var bool shortStopLoss = na
resetAfterStopLoss = resetCondition == "Stop Loss"
resetAfterEntry = resetCondition == "Entry"
// ~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~ //
// Mid Line
midHigh = ta.vwma(ta.highest(high, len), len)
midLow = ta.vwma(ta.lowest(low, len), len)
mid = math.avg(midHigh, midLow)
midSmoothed = ta.ema(mid, len)
//Volume Filtered
avgVol = ta.vwma(volume, len)
volDiff = volume / avgVol
midVolSmoothed = ta.vwma(midSmoothed * volDiff, 3)
//RSI Filtered
midDifference = ta.sma(midHigh - midLow, len)
midRSI = ta.rsi(midVolSmoothed, len) * 0.01
midAdd = midRSI * midDifference
//Calculate Zones
purchaseZoneHigh = midSmoothed + midAdd
purchaseZoneLow = midSmoothed - midAdd
purchaseZoneBasis = math.avg(purchaseZoneHigh, purchaseZoneLow)
//Create Stop Loss Locations
stopLossHigh = purchaseZoneHigh * (1 + (stopLossMult * 0.01))
stopLossLow = purchaseZoneLow * (1 - (stopLossMult * 0.01))
// ~~~~~~~~~~~ PURCHASE CALCULATIONS ~~~~~~~~~~~ //
//Long
longEntry = ta.crossunder(purchaseSrc, purchaseZoneLow)
longStart := ta.crossover(purchaseSrc, purchaseZoneLow) and longAvailable
longAvailable := ta.crossunder(purchaseSrc, purchaseZoneHigh) or (resetAfterStopLoss and longStopLoss) or (resetAfterEntry and longEntry) ? true : longStart ? false : longAvailable[1]
longEnd = ta.crossover(exitSrc, purchaseZoneHigh)
longStopLoss := ta.crossunder(exitSrc, stopLossLow)
longTakeProfitAvailable := ta.crossover(exitSrc, purchaseZoneBasis) ? true : longEnd ? false : longTakeProfitAvailable[1]
longTakeProfit = ta.crossunder(exitSrc, purchaseZoneBasis) and longTakeProfitAvailable
//Short
shortEntry = ta.crossover(purchaseSrc, purchaseZoneHigh)
shortStart := ta.crossunder(purchaseSrc, purchaseZoneHigh) and shortAvailable
shortAvailable := ta.crossover(purchaseSrc, purchaseZoneLow) or (resetAfterStopLoss and shortStopLoss) or (resetAfterEntry and shortEntry)? true : shortStart ? false : shortAvailable[1]
shortEnd = ta.crossunder(exitSrc, purchaseZoneLow)
shortStopLoss := ta.crossover(exitSrc, stopLossHigh)
shortTakeProfitAvailable := ta.crossunder(exitSrc, purchaseZoneBasis) ? true : shortEnd ? false : shortTakeProfitAvailable[1]
shortTakeProfit = ta.crossover(exitSrc, purchaseZoneBasis) and shortTakeProfitAvailable
// ~~~~~~~~~~~ PLOTS ~~~~~~~~~~~ //
shortLine = plot(purchaseZoneHigh, color=color.green)
shortStopLossLine = plot(stopLossHigh, color=color.green) //color=color.rgb(0, 97, 3)
fill(shortLine, shortStopLossLine, color = color.new(color.green, 90))
plot(purchaseZoneBasis, color=color.white)
longLine = plot(purchaseZoneLow, color=color.red)
longStopLossLine = plot(stopLossLow, color=color.red) //color=color.rgb(105, 0, 0)
fill(longLine, longStopLossLine, color=color.new(color.red, 90))
// ~~~~~~~~~~~ STRATEGY ~~~~~~~~~~~ //
if (longStart)
strategy.entry("buy", strategy.long)
else if (longEnd or (useStopLoss and longStopLoss) or (useTakeProfit and longTakeProfit))
strategy.close("buy")
if (shortStart)
strategy.entry("sell", strategy.short)
else if (shortEnd or (useStopLoss and shortStopLoss) or (useTakeProfit and shortTakeProfit))
strategy.close("sell")
// ~~~~~~~~~~~ ALERTS ~~~~~~~~~~~ //
if longStart or (longEnd or (useStopLoss and longStopLoss) or (useTakeProfit and longTakeProfit)) or shortStart or (shortEnd or (useStopLoss and shortStopLoss) or (useTakeProfit and shortTakeProfit))
alert("{{strategy.order.action}} | {{ticker}} | {{close}}", alert.freq_once_per_bar) |
Merovinh - Mean Reversion Lowest low | https://www.tradingview.com/script/Ce2jjXVU-Merovinh-Mean-Reversion-Lowest-low/ | merovinh | https://www.tradingview.com/u/merovinh/ | 74 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © merovinh
//@version=5
strategy(title="Merovinh - Mean Reversion Lowest low",
overlay = true,
default_qty_type = strategy.percent_of_equity,
initial_capital = 10000,
default_qty_value = 10,
commission_type = strategy.commission.percent,
slippage = 1,
commission_value = 0.04)
GR_TIME = 'Time Period'
bars = input(9, title = "Minimum number of bars", tooltip = "The minimum number of bars before updating lowest low / highest high")
numberOfLows = input.string(defval='One', title='Number of broken lows', options=['One', 'Two', 'Three', 'Four'])
//Period
startTime = input.time(timestamp("27 Jul 2021 00:00 +0000"), "Start date", inline = "period", group = GR_TIME)
finalTime = input.time(timestamp("31 Dec 2030 23:59 +0000"), "Final date", inline = "period", group = GR_TIME)
var prevLow = .0
var prevHigh = .0
var prevLow2 = .0
var prevLow3 = .0
var prevLow4 = .0
truetime = time > startTime and time < finalTime
highestHigh = ta.highest(high, bars)
lowestLow = ta.lowest(low, bars)
if numberOfLows == 'One'
if truetime and prevLow > 0 and lowestLow < prevLow
strategy.entry('long', strategy.long)
if numberOfLows == 'Two'
if truetime and prevLow > 0 and lowestLow < prevLow and prevLow < prevLow2
strategy.entry('long', strategy.long)
if numberOfLows == 'Three'
if truetime and prevLow > 0 and lowestLow < prevLow and prevLow < prevLow2 and prevLow2 < prevLow3
strategy.entry('long', strategy.long)
if numberOfLows == 'Four'
if truetime and prevLow > 0 and lowestLow < prevLow and prevLow < prevLow2 and prevLow2 < prevLow3 and prevLow3 < prevLow4
strategy.entry('long', strategy.long)
if truetime and prevHigh > 0 and highestHigh > prevHigh
strategy.close('long')
if prevLow != lowestLow
prevLow4 := prevLow3
prevLow3 := prevLow2
prevLow2 := prevLow
prevLow := lowestLow
prevHigh := highestHigh
plot(lowestLow, color=color.green, linewidth=1, title="Lowest Low Line")
plot(highestHigh, color=color.green, linewidth=1, title="Highest High Line")
|
Golden Transform | https://www.tradingview.com/script/dHoF6T1G-Golden-Transform/ | DraftVenture | https://www.tradingview.com/u/DraftVenture/ | 174 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0
// © DraftVenture
//@version=5
strategy("Golden Transform Strategy", overlay=false)
// ROC - to contrast Hull TRIX, no modifications
roclength = input.int(50, title="Rate of Change Length", minval=1)
source = input(close, "ROC Source")
roc = 100 * (source - source[roclength])/source[roclength]
// Hull modified TRIX - for greater weight
length = input.int(90, title="Hull TRIX Length", minval=1)
hullma(source, length) =>
wma1 = ta.wma(source, length / 2)
wma2 = ta.wma(source, length)
hull = ta.wma(2 * wma1 - wma2, math.floor(math.sqrt(length)))
hull
hullmaValue = hullma(math.log(close), length)
trix = 10000 * ta.change(hullma(hullma(hullma(math.log(close), length), length), length))
// Hull MA - correlates Hull TRIX as an entry filter
hlength = input.int(65, title= "Hull MA Entry Length", minval=1)
src = input(close, title="Hull MA Source")
hullma2 = ta.wma(2*ta.wma(src, hlength/2)-ta.wma(src, hlength), math.floor(math.sqrt(hlength)))
// Fisher Transform - as a preemptive exit filter
len = input.int(50, minval=1, title="Fisher Reversal Length")
high_ = ta.highest(hl2, len)
low_ = ta.lowest(hl2, len)
round_(val) => val > .99 ? .999 : val < -.99 ? -.999 : val
value = 0.0
value := round_(.66 * ((hl2 - low_) / (high_ - low_) - .5) + .67 * nz(value[1]))
fish0 = 0.0
fish0 := .5 * math.log((1 + value) / (1 - value)) + .5 * nz(fish0[1])
fish2 = fish0[1]
// Smooth the Fisher with HMA to correlate with TRIX
smooth_length = input.int(5, title="Fisher Smoothing Length", minval=1)
fish1 = ta.hma(fish0, smooth_length)
// Determine long and short conditions
longCondition = ta.crossover(roc, trix) and trix < 0 and open > hullma2
shortCondition = ta.crossunder(roc, trix) and trix > 0 and open < hullma2
// Exit conditions
exitLongCondition = ta.crossunder(roc, trix) or fish1 > 1.5 and ta.crossunder(fish1, fish2)
exitShortCondition = ta.crossover(roc, trix) or fish1 < -1.5 and ta.crossover(fish1, fish2)
// Strategy entry and exit logic
if longCondition
strategy.entry("Long", strategy.long)
if exitLongCondition
strategy.close("Long")
if shortCondition
strategy.entry("Short", strategy.short)
if exitShortCondition
strategy.close("Short")
// Highlight periods for oscillater
bgcolor(longCondition ? color.new(color.yellow, 50) : na)
bgcolor(shortCondition ? color.new(color.white, 50) : na)
hline(1.5, "Overbought", color=color.yellow)
hline(0.75,"Mid High", color=color.gray)
hline(0, "Zero", color=color.yellow)
hline(-0.75, "Mid Low", color=color.gray)
hline(-1.5, "Oversold", color=color.yellow)
plot(fish1, color=color.yellow, title="Fisher Reversal")
plot(fish2, color=color.gray, title="Lag Trigger")
plotshape(series=ta.crossunder(roc, trix), style=shape.xcross, location=location.top, color=color.white, size=size.tiny)
plotshape(series=ta.crossover(roc, trix), style=shape.xcross, location=location.bottom, color=color.white, size=size.tiny)
// Strategy by KP |
Financial Ratios Fundamental Strategy | https://www.tradingview.com/script/DTIiJ6cx-Financial-Ratios-Fundamental-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 88 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//exlux99
strategy('Financial Ratios', overlay=true,initial_capital = 1000000, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.1)
//Current ratio: Current Assets / Current Liabilities
TOTAL_CURRENT_ASSETS = request.financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FQ")
TOTAL_CURRENT_LIABILITIES = request.financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FQ")
current_ratio = TOTAL_CURRENT_ASSETS/ TOTAL_CURRENT_LIABILITIES
// plot(current_ratio)
//Quick ratio (Acid-test ratio): (Current Assets – Inventories – Prepaid Expenses) / Current Liabilities
PREPAID_EXPENSES = request.financial(syminfo.tickerid, "PREPAID_EXPENSES", "FQ")
INVENTORY_FINISHED_GOODS = request.financial(syminfo.tickerid, "INVENTORY_FINISHED_GOODS", "FQ")
quick_ratio = (TOTAL_CURRENT_ASSETS - INVENTORY_FINISHED_GOODS - PREPAID_EXPENSES) / TOTAL_CURRENT_LIABILITIES
// plot(quick_ratio, color=color.white)
//Cash ratio: Cash and cash equivalents / Current Liabilities
CASH_N_EQUIVALENTS = request.financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FQ")
cash_ratio = CASH_N_EQUIVALENTS / TOTAL_CURRENT_LIABILITIES
// plot(cash_ratio, color=color.orange)
long_liquidity = current_ratio > current_ratio[1] and quick_ratio > quick_ratio[1] //and cash_ratio > cash_ratio[1]
long_exit_liquidity = current_ratio < current_ratio[1] and quick_ratio < quick_ratio[1] //or cash_ratio < cash_ratio[1]
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Leverage ratios
//Debt ratio: Total Debt / Total Assets
TOTAL_DEBT= request.financial(syminfo.tickerid, "TOTAL_DEBT", "FQ")
TOTAL_ASSETS = request.financial(syminfo.tickerid, "TOTAL_ASSETS", "FQ")
debt_ratio = TOTAL_DEBT / TOTAL_ASSETS
//plot(debt_ratio)
//Debt to equity ratio: Total Debt / Total Equity
TOTAL_EQUITY= request.financial(syminfo.tickerid, "TOTAL_EQUITY", "FQ")
debt_equity_ratio = TOTAL_DEBT / TOTAL_EQUITY
//plot(debt_equity_ratio,color=color.white)
//Interest coverage ratio: EBIT / Interest expenses
EBIT = request.financial(syminfo.tickerid, "EBIT", "FQ")
INTEREST_EXPENSE_ON_DEBT = request.financial(syminfo.tickerid, "INTEREST_EXPENSE_ON_DEBT", "FQ")
interest_ratio = EBIT / INTEREST_EXPENSE_ON_DEBT
//plot(interest_ratio, color=color.orange)
long_leverage = debt_ratio < debt_ratio[1] and debt_equity_ratio< debt_equity_ratio[1] //or interest_ratio < interest_ratio[1]
long_exit_leverage = debt_ratio > debt_ratio[1] and debt_equity_ratio > debt_equity_ratio[1] //or interest_ratio > interest_ratio[1]
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Efficiency ratios
//Asset turnover ratio: Net sales / Average total assets
SALES_OF_BUSINESS =request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FQ")
asset_turnover_ratio = SALES_OF_BUSINESS / TOTAL_ASSETS
// plot(asset_turnover_ratio)
//Inventory turnover: Cost of goods sold / Average value of inventory
// COST_OF_GOODS= request.financial(syminfo.tickerid, "COST_OF_GOODS", "FQ")
// TOTAL_INVENTORY = request.financial(syminfo.tickerid, "TOTAL_INVENTORY", "FQ")
// inventory_turnover = COST_OF_GOODS/ TOTAL_INVENTORY
INVENT_TO_REVENUE = request.financial(syminfo.tickerid, "INVENT_TO_REVENUE", "FQ")
// plot(INVENT_TO_REVENUE,color=color.white)
//Payables turnover ratio: Cost of Goods sold (or net credit purchases) / Average Accounts Payable
COST_OF_GOODS = request.financial(syminfo.tickerid, "COST_OF_GOODS", "FQ")
ACCOUNTS_PAYABLE= request.financial(syminfo.tickerid, "ACCOUNTS_PAYABLE", "FQ")
payable_turnover = COST_OF_GOODS / ACCOUNTS_PAYABLE
// plot(payable_turnover,color=color.orange)
//Receivables turnover ratio: Net credit sales / Average accounts receivable
long_Efficiency = asset_turnover_ratio > asset_turnover_ratio[1] and payable_turnover > payable_turnover[1] //and INVENT_TO_REVENUE > INVENT_TO_REVENUE[1]
long_exit_Efficiency = asset_turnover_ratio < asset_turnover_ratio[1] and payable_turnover < payable_turnover[1]// and INVENT_TO_REVENUE < INVENT_TO_REVENUE[1]
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Profitability ratios
//Gross margin: Gross profit / Net sales
GROSS_PROFIT = request.financial(syminfo.tickerid, "GROSS_PROFIT", "FQ")
SALES = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FQ")
gross_margin = GROSS_PROFIT / SALES
// plot(gross_margin)
//Operating margin: Operating income / Net sales
OPER_INCOME = request.financial(syminfo.tickerid, "OPER_INCOME", "FQ")
operating_margin = OPER_INCOME/ SALES
// plot(operating_margin, color=color.white)
//Return on assets (ROA): Net income / Total assets
NET_INCOME= request.financial(syminfo.tickerid, "NET_INCOME", "FQ")
roa = NET_INCOME/TOTAL_ASSETS
//plot(roa, color=color.orange)
//Return on equity (ROE): Net income / Total equity
roe = NET_INCOME / TOTAL_EQUITY
//plot(roe, color=color.purple)
long_profitability = (gross_margin > gross_margin[1] and operating_margin>operating_margin[1] )//and roe > roe[1] and roa > roa[1] ) // or ( roe > roe[1] and roa > roa[1] )
long_exit_profitability = (gross_margin < gross_margin[1] and operating_margin<operating_margin[1] ) //or roe < roe[1] or roa < roa[1]) // or ( roe < roe[1] and roa < roa[1])
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//5) Market Value ratios
//Earnings per share ratio (EPS): (Net Income – Preferred Dividends) / End-of-Period Common Shares Outstanding
PREFERRED_DIVIDENDS = request.financial(syminfo.tickerid, "PREFERRED_DIVIDENDS", "FQ")
TOTAL_SHARES_OUTSTANDING = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
eps_ratio = (NET_INCOME - PREFERRED_DIVIDENDS)/TOTAL_SHARES_OUTSTANDING
// plot(eps_ratio)
// //Price earnings ratio (P/E): Share price / Earnings per share
// EPS = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE", "FQ")
// closex = request.security(syminfo.tickerid, "M", close)
// PE_RATIO = closex / eps_ratio
// plot(PE_RATIO,color=color.white)
//Book value per share ratio: (Total Equity – Preferred Equity) / Total shares outstanding
COMMON_EQUITY_TOTAL = request.financial(syminfo.tickerid, "COMMON_EQUITY_TOTAL", "FQ")
preferred_equity = TOTAL_EQUITY - COMMON_EQUITY_TOTAL
TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
book_value = (TOTAL_EQUITY - preferred_equity)/TSO
// plot(book_value, color=color.white)
//Dividend yield ratio: Dividend per share / Share price
DIVIDENDS_YIELD = request.financial(syminfo.tickerid, "DIVIDENDS_YIELD", "FQ")
// plot(DIVIDENDS_YIELD,color=color.orange)
long_market = DIVIDENDS_YIELD > DIVIDENDS_YIELD[1] and eps_ratio > eps_ratio[1] and book_value > book_value[1]
long_exit_market = DIVIDENDS_YIELD < DIVIDENDS_YIELD[1] and eps_ratio < eps_ratio[1] and book_value < book_value[1]
//and (current_ratio > current_ratio[1] )
//and interest_ratio < interest_ratio[1]
//and payable_turnover > payable_turnover[1]
//and gross_margin > gross_margin[1]
//long_tot = (long_liquidity or long_leverage or long_Efficiency or long_profitability ) // or long_market
long_tot = current_ratio > current_ratio[1] or interest_ratio < interest_ratio[1] or payable_turnover > payable_turnover[1] or gross_margin > gross_margin[1]
long_tot_exit = current_ratio < current_ratio[1] or interest_ratio > interest_ratio[1] or payable_turnover < payable_turnover[1] or gross_margin > gross_margin[1]
// plot(current_ratio)
// plot(interest_ratio, color=color.white)
// plot(payable_turnover, color=color.orange)
// plot(gross_margin, color=color.purple)
// DEBT_TO_REVENUE = request.financial(syminfo.tickerid, "SPRINGATE_SCORE", "FQ")
// plot(DEBT_TO_REVENUE)
strategy.entry("long",strategy.long,when= ( long_tot or long_tot[1] ))
strategy.close("long",when= long_tot_exit )
|
AI SuperTrend - Strategy [presentTrading] | https://www.tradingview.com/script/eaTIyEty-AI-SuperTrend-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 1,145 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
strategy("AI Volume Supertrend - Strategy [presentTrading]", overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
// ~~ ToolTips {
t1="Number of nearest neighbors in KNN algorithm (k): Increase to consider more neighbors, providing a more balanced view but possibly smoothing out local patterns. Decrease for fewer neighbors to make the algorithm more responsive to recent changes. \n\nNumber of data points to consider (n): Increase for more historical data, providing a broader context but possibly diluting recent trends. Decrease for less historical data to focus more on recent behavior."
t2="Length of weighted moving average for price (KNN_PriceLen): Higher values create a smoother price line, influencing the KNN algorithm to be more stable but less sensitive to short-term price movements. Lower values enhance responsiveness in KNN predictions to recent price changes but may lead to more noise. \n\nLength of weighted moving average for SuperTrend (KNN_STLen): Higher values lead to a smoother SuperTrend line, affecting the KNN algorithm to emphasize long-term trends. Lower values make KNN predictions more sensitive to recent SuperTrend changes but may result in more volatility."
t3="Length of the SuperTrend (len): Increase for a smoother trend line, ideal for identifying long-term trends but possibly ignoring short-term fluctuations. Decrease for more responsiveness to recent changes but risk of more false signals. \n\nMultiplier for ATR in SuperTrend calculation (factor): Increase for wider bands, capturing larger price movements but possibly missing subtle changes. Decrease for narrower bands, more sensitive to small shifts but risk of more noise."
t4="Type of moving average for SuperTrend calculation (maSrc): Choose based on desired characteristics. SMA is simple and clear, EMA emphasizes recent prices, WMA gives more weight to recent data, RMA is less sensitive to recent changes, and VWMA considers volume."
t5="Color for bullish trend (upCol): Select to visually identify upward trends. \n\nColor for bearish trend (dnCol): Select to visually identify downward trends.\n\nColor for neutral trend (neCol): Select to visually identify neutral trends."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// Add Button for Trading Direction
tradeDirection = input.string("Both", "Select Trading Direction", options=["Long", "Short", "Both"])
// ~~ Input settings for K and N values
k = input.int(3, title = "Neighbors", minval=1, maxval=100,inline="AI", group="AI Settings")
n_ = input.int(10, title ="Data", minval=1, maxval=100,inline="AI", group="AI Settings", tooltip=t1)
n = math.max(k,n_)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for prediction values
KNN_PriceLen = input.int(20, title="Price Trend", minval=2, maxval=500, step=10,inline="AITrend", group="AI Trend")
KNN_STLen = input.int(100, title="Prediction Trend", minval=2, maxval=500, step=10, inline="AITrend", group="AI Trend", tooltip=t2)
aisignals = input.bool(true,title="AI Trend Signals",inline="signal", group="AI Trend")
Bullish_col = input.color(color.lime,"",inline="signal", group="AI Trend")
Bearish_col = input.color(color.red,"",inline="signal", group="AI Trend")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define SuperTrend parameters
len = input.int(10, "Length", minval=1,inline="SuperTrend", group="Super Trend Settings")
factor = input.float(3.0,step=.1,inline="SuperTrend", group="Super Trend Settings", tooltip=t3)
maSrc = input.string("WMA","Moving Average Source",["SMA","EMA","WMA","RMA","VWMA"],inline="", group="Super Trend Settings", tooltip=t4)
upCol = input.color(color.lime,"Bullish Color",inline="col", group="Super Trend Coloring")
dnCol = input.color(color.red,"Bearish Color",inline="col", group="Super Trend Coloring")
neCol = input.color(color.blue,"Neutral Color",inline="col", group="Super Trend Coloring", tooltip=t5)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Calculate the SuperTrend based on the user's choice
vwma = switch maSrc
"SMA" => ta.sma(close*volume, len) / ta.sma(volume, len)
"EMA" => ta.ema(close*volume, len) / ta.ema(volume, len)
"WMA" => ta.wma(close*volume, len) / ta.wma(volume, len)
"RMA" => ta.rma(close*volume, len) / ta.rma(volume, len)
"VWMA" => ta.vwma(close*volume, len) / ta.vwma(volume, len)
atr = ta.atr(len)
upperBand = vwma + factor * atr
lowerBand = vwma - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Collect data points and their corresponding labels
price = ta.wma(close,KNN_PriceLen)
sT = ta.wma(superTrend,KNN_STLen)
data = array.new_float(n)
labels = array.new_int(n)
for i = 0 to n - 1
data.set(i, superTrend[i])
label_i = price[i] > sT[i] ? 1 : 0
labels.set(i, label_i)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define a function to compute distance between two data points
distance(x1, x2) =>
math.abs(x1 - x2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define the weighted k-nearest neighbors (KNN) function
knn_weighted(data, labels, k, x) =>
n1 = data.size()
distances = array.new_float(n1)
indices = array.new_int(n1)
// Compute distances from the current point to all other points
for i = 0 to n1 - 1
x_i = data.get(i)
dist = distance(x, x_i)
distances.set(i, dist)
indices.set(i, i)
// Sort distances and corresponding indices in ascending order
// Bubble sort method
for i = 0 to n1 - 2
for j = 0 to n1 - i - 2
if distances.get(j) > distances.get(j + 1)
tempDist = distances.get(j)
distances.set(j, distances.get(j + 1))
distances.set(j + 1, tempDist)
tempIndex = indices.get(j)
indices.set(j, indices.get(j + 1))
indices.set(j + 1, tempIndex)
// Compute weighted sum of labels of the k nearest neighbors
weighted_sum = 0.
total_weight = 0.
for i = 0 to k - 1
index = indices.get(i)
label_i = labels.get(index)
weight_i = 1 / (distances.get(i) + 1e-6)
weighted_sum += weight_i * label_i
total_weight += weight_i
weighted_sum / total_weight
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Classify the current data point
current_superTrend = superTrend
label_ = knn_weighted(data, labels, k, current_superTrend)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot
col = label_ == 1?upCol:label_ == 0?dnCol:neCol
plot(current_superTrend, color=col, title="Volume Super Trend AI")
upTrend = plot(superTrend==lowerBand?current_superTrend:na, title="Up Volume Super Trend AI", color=col, style=plot.style_linebr)
Middle = plot((open + close) / 2, display=display.none, editable=false)
downTrend = plot(superTrend==upperBand?current_superTrend:na, title="Down Volume Super Trend AI", color=col, style=plot.style_linebr)
fill_col = color.new(col,90)
fill(Middle, upTrend, fill_col, fillgaps=false,title="Up Volume Super Trend AI")
fill(Middle, downTrend, fill_col, fillgaps=false, title="Down Volume Super Trend AI")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Ai Super Trend Signals
Start_TrendUp = col==upCol and (col[1]!=upCol or col[1]==neCol) and aisignals
Start_TrendDn = col==dnCol and (col[1]!=dnCol or col[1]==neCol) and aisignals
TrendUp = direction == -1 and direction[1] == 1 and label_ == 1 and aisignals
TrendDn = direction == 1 and direction[1] ==-1 and label_ == 0 and aisignals
plotshape(Start_TrendUp?superTrend:na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Start")
plotshape(Start_TrendDn?superTrend:na, location=location.absolute, style= shape.circle,size=size.tiny, color=Bearish_col, title="AI Bearish Trend Start")
plotshape(TrendUp?superTrend:na, location=location.absolute, style= shape.triangleup, size=size.small, color=Bullish_col, title="AI Bullish Trend Signal")
plotshape(TrendDn?superTrend:na, location=location.absolute, style= shape.triangledown,size=size.small, color=Bearish_col, title="AI Bearish Trend Signal")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// Trading Logic
longCondition = Start_TrendUp or TrendUp
shortCondition = Start_TrendDn or TrendDn
longExitCondition = false // Initialize
shortExitCondition = false // Initialize
// Trend Continuation Signals
// Note: You can refine these conditions based on your understanding of trend continuation signals.
if (direction == -1 and label_ == 1) // Bullish trend continues
longExitCondition := false
else if (direction == 1 and label_ == 0) // Bearish trend continues
shortExitCondition := false
else // Trend does not continue
longExitCondition := true
shortExitCondition := true
// Dynamic Trailing Stop Loss
longTrailingStop = superTrend - atr * factor
shortTrailingStop = superTrend + atr * factor
// Adjust Enter and Exit Conditions based on Trading Direction
if (tradeDirection == "Long" or tradeDirection == "Both")
strategy.entry("Long", strategy.long, when=longCondition)
strategy.exit("Exit Long", "Long", stop=longTrailingStop, when=longExitCondition)
if (tradeDirection == "Short" or tradeDirection == "Both")
strategy.entry("Short", strategy.short, when=shortCondition)
strategy.exit("Exit Short", "Short", stop=shortTrailingStop, when=shortExitCondition) |
Elliott Wave with Supertrend Exit - Strategy [presentTrading] | https://www.tradingview.com/script/hlOgflm1-Elliott-Wave-with-Supertrend-Exit-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 318 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
strategy('Elliott Wave with Supertrend Exit - Strategy [presentTrading]' , overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
//Settings
// Add a button to choose the trading direction
tradingDirection = input.string("Both","Trading Direction", options=["Long", "Short", "Both"])
i_hi = input.string('high' , title= '' , group='source [high - low]', inline='hl', options=['high', 'close', 'max open/close'])
i_lo = input.string('low' , title= '' , group='source [high - low]', inline='hl', options=['low' , 'close', 'min open/close'])
s1 = input.bool (true , title= '' , group='ZigZag' , inline= '1' )
len1 = input.int ( 4 , title= ' 1 Length', group='ZigZag' , inline= '1', minval =1 )
col1 = input.color (color.red , title= '' , group='ZigZag' , inline= '1' )
STMultiplier = input.float(3,title='Supertrend Multiplier',group='Exit condition: Supertrend')
STLength = input.int(10, title='Supertrend Length' ,group='Exit condition: Supertrend')
// Define the fixed percentage for the stop loss
stopLossPercentage = input.float(10, title='Stop Loss Percentage (%)', group='Stoploss: Fix percentage')
i_500 = input.float (0.500 , title=' level 1', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_618 = input.float (0.618 , title=' level 2', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_764 = input.float (0.764 , title=' level 3', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
i_854 = input.float (0.854 , title=' level 4', group='Fibonacci values' , minval =0, maxval =1, step =0.01 )
shZZ = input.bool (false , title= '' , group='show ZZ' , inline='zz' )
//User Defined Types
type ZZ
int [] d
int [] x
float[] y
line [] l
type Ewave
line l1
line l2
line l3
line l4
line l5
label b1
label b2
label b3
label b4
label b5
//
bool on
bool br //= na
//
int dir
//
line lA
line lB
line lC
label bA
label bB
label bC
//
bool next = false
//
label lb
box bx
type fibL
line wave1_0_500
line wave1_0_618
line wave1_0_764
line wave1_0_854
line wave1_pole_
linefill l_fill_
bool _break_ //= na
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
hi = i_hi == 'high' ? high : i_hi == 'close' ? close : math.max(open, close)
lo = i_lo == 'low' ? low : i_hi == 'close' ? close : math.min(open, close)
in_out(aZZ, d, x1, y1, x2, y2, col) =>
aZZ.d.unshift(d), aZZ.x.unshift(x2), aZZ.y.unshift(y2), aZZ.d.pop(), aZZ.x.pop(), aZZ.y.pop()
if shZZ
aZZ.l.unshift(line.new(x1, y1, x2, y2, color= col)), aZZ.l.pop().delete()
method isSame(Ewave gEW, _1x, _2x, _3x, _4x) =>
t1 = _1x == gEW.l1.get_x1()
t2 = _2x == gEW.l2.get_x1()
t3 = _3x == gEW.l3.get_x1()
t4 = _4x == gEW.l4.get_x1()
t1 and t2 and t3 and t4
method isSame2(Ewave gEW, _1x, _2x, _3x) =>
t1 = _1x == gEW.l3.get_x2()
t2 = _2x == gEW.l4.get_x2()
t3 = _3x == gEW.l5.get_x2()
t1 and t2 and t3
method dot(Ewave gEW) =>
gEW.l1.set_style(line.style_dotted)
gEW.l2.set_style(line.style_dotted)
gEW.l3.set_style(line.style_dotted)
gEW.l4.set_style(line.style_dotted)
gEW.l5.set_style(line.style_dotted)
gEW.b1.set_textcolor (color(na))
gEW.b2.set_textcolor (color(na))
gEW.b3.set_textcolor (color(na))
gEW.b4.set_textcolor (color(na))
gEW.b5.set_textcolor (color(na))
gEW.on := false
method dash(Ewave gEW) =>
gEW.lA.set_style(line.style_dashed)
gEW.lB.set_style(line.style_dashed)
gEW.lC.set_style(line.style_dashed)
gEW.bA.set_textcolor (color(na))
gEW.bB.set_textcolor (color(na))
gEW.bC.set_textcolor (color(na))
gEW.bx.set_bgcolor (color(na))
gEW.bx.set_border_color (color(na))
method sol_dot(fibL nFibL, sol_dot, col) =>
style =
sol_dot == 'dot' ?
line.style_dotted :
sol_dot == 'sol' ?
line.style_solid :
line.style_dashed
nFibL.wave1_0_500.set_style(style)
nFibL.wave1_0_618.set_style(style)
nFibL.wave1_0_764.set_style(style)
nFibL.wave1_0_854.set_style(style)
nFibL.l_fill_.set_color(col)
method set(fibL nFibL, int x1, int x2, float max_500, float max_618, float max_764, float max_854, float y2) =>
nFibL.wave1_0_500.set_xy1(x1, max_500)
nFibL.wave1_0_500.set_xy2(x2, max_500)
nFibL.wave1_0_618.set_xy1(x1, max_618)
nFibL.wave1_0_618.set_xy2(x2, max_618)
nFibL.wave1_0_764.set_xy1(x1, max_764)
nFibL.wave1_0_764.set_xy2(x2, max_764)
nFibL.wave1_0_854.set_xy1(x1, max_854)
nFibL.wave1_0_854.set_xy2(x2, max_854)
nFibL.wave1_pole_.set_xy1(x1, y2 )
nFibL.wave1_pole_.set_xy2(x1, max_854)
nFibL.l_fill_.get_line1().set_xy1(x1, max_764)
nFibL.l_fill_.get_line1().set_xy2(x2, max_764)
nFibL.l_fill_.get_line2().set_xy1(x1, max_854)
nFibL.l_fill_.get_line2().set_xy2(x2, max_854)
method setNa(fibL nFibL) =>
nFibL.wave1_0_500.set_xy1(na, na)
nFibL.wave1_0_500.set_xy2(na, na)
nFibL.wave1_0_618.set_xy1(na, na)
nFibL.wave1_0_618.set_xy2(na, na)
nFibL.wave1_0_764.set_xy1(na, na)
nFibL.wave1_0_764.set_xy2(na, na)
nFibL.wave1_0_854.set_xy1(na, na)
nFibL.wave1_0_854.set_xy2(na, na)
nFibL.wave1_pole_.set_xy1(na, na)
nFibL.wave1_pole_.set_xy2(na, na)
nFibL.l_fill_.set_color(color(na))
draw(enabled, left, col, n) =>
longEntry = false
shortEntry = false
//
max_bars_back(time, 4000)
var int dir = na, var int x1= na, var float y1 = na, var int x2 = na, var float y2 = na, var Ewave gEW = na
var int last_0x = na , var float last_0y = na , var int last_6x = na , var float last_6y = na
//
if enabled
var fibL nFibL = fibL.new(
wave1_0_500 = line.new(na, na, na, na, color= color.new(col, 50), style= line.style_solid ),
wave1_0_618 = line.new(na, na, na, na, color= color.new(col, 38), style= line.style_solid ),
wave1_0_764 = line.new(na, na, na, na, color= color.new(col, 24), style= line.style_solid ),
wave1_0_854 = line.new(na, na, na, na, color= color.new(col, 15), style= line.style_solid ),
wave1_pole_ = line.new(na, na, na, na, color= color.new(col, 50), style= line.style_dashed),
l_fill_ = linefill.new(
line.new(na, na, na, na, color= color(na))
, line.new(na, na, na, na, color= color(na))
, color= color(na))
, _break_ = na
)
//
var ZZ aZZ = ZZ.new(array.new < int > ()
, array.new < int > ()
, array.new < float > ()
, array.new < line > () )
var Ewave[] aEW = array.new < Ewave > ()
//
if barstate.isfirst
aEW.unshift(Ewave.new())
for i = 0 to 10
aZZ.d.unshift(0)
aZZ.x.unshift(0)
aZZ.y.unshift(0)
aZZ.l.unshift(shZZ ? line.new(na, na, na, na) : na)
//
sz = aZZ.d.size( )
x2 := bar_index -1
ph = ta.pivothigh(hi, left, 1)
pl = ta.pivotlow (lo, left, 1)
t = n == 2 ? '\n\n' : n == 1 ? '\n' : ''
//
// when a new Pivot High is found
if not na(ph)
gEW := aEW.get (0)
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(hi[1])
//
if dir < 1 // if previous point was a pl, add, and change direction ( 1)
in_out(aZZ, 1, x1, y1, x2, y2, col)
else
if dir == 1 and ph > y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if shZZ
aZZ.l.get(0).set_xy2(x2, y2)
//
_6x = x2, _6y = y2
_5x = aZZ.x.get(1), _5y = aZZ.y.get(1)
_4x = aZZ.x.get(2), _4y = aZZ.y.get(2)
_3x = aZZ.x.get(3), _3y = aZZ.y.get(3)
_2x = aZZ.x.get(4), _2y = aZZ.y.get(4)
_1x = aZZ.x.get(5), _1y = aZZ.y.get(5)
//
// –––––––––––––––––––––[ 12345 ]–––––––––––––––––––––
_W5 = _6y - _5y
_W3 = _4y - _3y
_W1 = _2y - _1y
min = math.min(_W1, _W3, _W5)
isWave =
_W3 != min and
_6y > _4y and
_3y > _1y and
_5y > _2y
//
same = gEW.isSame(_1x, _2x, _3x, _4x)
if isWave
if same
gEW.l5.set_xy2(_6x, _6y)
gEW.b5.set_xy (_6x, _6y)
else
tx = ''
if _2x == aEW.get(0).b5.get_x()
tx := '(5) (1)'
aEW.get(0).b5.set_text('')
else
tx := '(1)'
//
wave = Ewave.new(
l1 = line.new (_1x, _1y, _2x, _2y , color=col , style= line.style_solid ),
l2 = line.new (_2x, _2y, _3x, _3y , color=col , style= line.style_solid ),
l3 = line.new (_3x, _3y, _4x, _4y , color=col , style= line.style_solid ),
l4 = line.new (_4x, _4y, _5x, _5y , color=col , style= line.style_solid ),
l5 = line.new (_5x, _5y, _6x, _6y , color=col , style= line.style_solid ),
b1 = label.new(_2x, _2y, text= tx + t, textcolor=col, color= color(na), style=label.style_label_down),
b2 = label.new(_3x, _3y, text= t + '(2)', textcolor=col, color= color(na), style=label.style_label_up ),
b3 = label.new(_4x, _4y, text= '(3)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b4 = label.new(_5x, _5y, text= t + '(4)', textcolor=col, color= color(na), style=label.style_label_up ),
b5 = label.new(_6x, _6y, text= '(5)' + t, textcolor=col, color= color(na), style=label.style_label_down),
on = true ,
br = false ,
dir = 1
)
aEW.unshift(wave)
nFibL._break_ := false
alert('New EW Motive Bullish Pattern found' , alert.freq_once_per_bar_close)
//
if not isWave
if same and gEW.on == true
gEW.dot()
alert('Invalidated EW Motive Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ ABC ]–––––––––––––––––––––
getEW = aEW.get(0)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
diff = math.abs(last_6y - last_0y)
//
if getEW.dir == -1
getX = getEW.l5.get_x2()
getY = getEW.l5.get_y2()
isSame2 = getEW.isSame2 (_1x, _2x, _3x)
isValid =
_3x == getX and
_6y < getY + (diff * i_854) and
_4y < getY + (diff * i_854) and
_5y > getY
//
if isValid
width = _6x - _2x // –––[ width (4) - (c) ]–––
if isSame2 and getEW.bA.get_x() > _3x
getEW.lC.set_xy1(_5x, _5y), getEW.lC.set_xy2(_6x, _6y), getEW.bC.set_xy(_6x, _6y), getEW.bx.set_lefttop(_6x, _6y), getEW.bx.set_right(_6x + width)
else
getEW.lA := line.new (_3x, _3y, _4x, _4y, color=col), getEW.bA := label.new(_4x, _4y, text= '(a)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.lB := line.new (_4x, _4y, _5x, _5y, color=col), getEW.bB := label.new(_5x, _5y, text= t + '(b)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.lC := line.new (_5x, _5y, _6x, _6y, color=col), getEW.bC := label.new(_6x, _6y, text= '(c)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.bx := box.new (_6x, _6y, _6x + width, _4y, bgcolor=color.new(col, 93), border_color=color.new(col, 65))
alert('New EW Corrective Bullish Pattern found' , alert.freq_once_per_bar_close)
else
if isSame2 and getEW.bA.get_x() > _3x
getEW.dash()
alert('Invalidated EW Corrective Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ new (1) ? ]–––––––––––––––––––––
if getEW.dir == 1
if _5x == getEW.bC.get_x() and
_6y > getEW.b5.get_y() and
getEW.next == false
getEW.next := true
getEW.lb := label.new(_6x, _6y, style=label.style_circle, color=color.new(col, 65), yloc=yloc.abovebar, size=size.tiny)
alert('Possible new start of EW Motive Bullish Wave', alert.freq_once_per_bar_close)
// Check for bullish pattern (modify this condition as needed)
if isWave and getEW.dir == 1
longEntry := true
//
// when a new Pivot Low is found
if not na(pl)
gEW := aEW.get (0)
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(lo[1])
//
if dir > -1 // if previous point was a ph, add, and change direction (-1)
in_out(aZZ, -1, x1, y1, x2, y2, col)
else
if dir == -1 and pl < y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if shZZ
aZZ.l.get(0).set_xy2(x2, y2)
//
_6x = x2, _6y = y2
_5x = aZZ.x.get(1), _5y = aZZ.y.get(1)
_4x = aZZ.x.get(2), _4y = aZZ.y.get(2)
_3x = aZZ.x.get(3), _3y = aZZ.y.get(3)
_2x = aZZ.x.get(4), _2y = aZZ.y.get(4)
_1x = aZZ.x.get(5), _1y = aZZ.y.get(5)
//
// –––––––––––––––––––––[ 12345 ]–––––––––––––––––––––
_W5 = _5y - _6y
_W3 = _3y - _4y
_W1 = _1y - _2y
min = math.min(_W1, _W3, _W5)
isWave =
_W3 != min and
_4y > _6y and
_1y > _3y and
_2y > _5y
//
same = isSame(gEW, _1x, _2x, _3x, _4x)
if isWave
if same
gEW.l5.set_xy2(_6x, _6y)
gEW.b5.set_xy (_6x, _6y)
else
tx = ''
if _2x == aEW.get(0).b5.get_x()
tx := '(5) (1)'
aEW.get(0).b5.set_text('')
else
tx := '(1)'
//
wave = Ewave.new(
l1 = line.new (_1x, _1y, _2x, _2y , color=col , style= line.style_solid ),
l2 = line.new (_2x, _2y, _3x, _3y , color=col , style= line.style_solid ),
l3 = line.new (_3x, _3y, _4x, _4y , color=col , style= line.style_solid ),
l4 = line.new (_4x, _4y, _5x, _5y , color=col , style= line.style_solid ),
l5 = line.new (_5x, _5y, _6x, _6y , color=col , style= line.style_solid ),
b1 = label.new(_2x, _2y, text= t + tx, textcolor=col, color= color(na), style=label.style_label_up ),
b2 = label.new(_3x, _3y, text= '(2)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b3 = label.new(_4x, _4y, text= t + '(3)', textcolor=col, color= color(na), style=label.style_label_up ),
b4 = label.new(_5x, _5y, text= '(4)' + t, textcolor=col, color= color(na), style=label.style_label_down),
b5 = label.new(_6x, _6y, text= t + '(5)', textcolor=col, color= color(na), style=label.style_label_up ),
on = true ,
br = false ,
dir =-1
)
aEW.unshift(wave)
nFibL._break_ := false
alert('New EW Motive Bearish Pattern found' , alert.freq_once_per_bar_close)
//
if not isWave
if same and gEW.on == true
gEW.dot()
alert('Invalidated EW Motive Bearish Pattern', alert.freq_once_per_bar_close)
//
// –––––––––––––––––––––[ ABC ]–––––––––––––––––––––
getEW = aEW.get(0)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
diff = math.abs(last_6y - last_0y)
//
if getEW.dir == 1
getX = getEW.l5.get_x2()
getY = getEW.l5.get_y2()
isSame2 = getEW.isSame2 (_1x, _2x, _3x)
isValid =
_3x == getX and
_6y > getY - (diff * i_854) and
_4y > getY - (diff * i_854) and
_5y < getY
//
if isValid
width = _6x - _2x // –––[ width (4) - (c) ]–––
if isSame2 and getEW.bA.get_x() > _3x
getEW.lC.set_xy1(_5x, _5y), getEW.lC.set_xy2(_6x, _6y), getEW.bC.set_xy(_6x, _6y), getEW.bx.set_lefttop(_6x, _6y), getEW.bx.set_right(_6x + width)
else
getEW.lA := line.new (_3x, _3y, _4x, _4y, color=col), getEW.bA := label.new(_4x, _4y, text= t + '(a)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.lB := line.new (_4x, _4y, _5x, _5y, color=col), getEW.bB := label.new(_5x, _5y, text= '(b)' + t, textcolor=col, color= color(na), style=label.style_label_down)
getEW.lC := line.new (_5x, _5y, _6x, _6y, color=col), getEW.bC := label.new(_6x, _6y, text= t + '(c)', textcolor=col, color= color(na), style=label.style_label_up )
getEW.bx := box.new (_6x, _6y, _6x + width, _4y, bgcolor=color.new(col, 93), border_color=color.new(col, 65))
alert('New EW Corrective Bearish Pattern found' , alert.freq_once_per_bar_close)
else
if isSame2 and getEW.bA.get_x() > _3x
getEW.dash()
alert('Invalidated EW Corrective Bullish Pattern', alert.freq_once_per_bar_close)
//
// –––[ check (only once) for a possible new (1) after an impulsive AND corrective wave ]–––
if getEW.dir == -1
if _5x == getEW.bC.get_x() and
_6y < getEW.b5.get_y() and
getEW.next == false
getEW.next := true
getEW.lb := label.new(_6x, _6y, style=label.style_circle, color=color.new(col, 65), yloc=yloc.belowbar, size=size.tiny)
alert('Possible new start of EW Motive Bearish Wave', alert.freq_once_per_bar_close)
// Check for bearish pattern (modify this condition as needed)
if isWave and getEW.dir == -1
shortEntry := true
//
// –––[ check for break box ]–––
if aEW.size() > 0
gEW := aEW.get(0)
if gEW.dir == 1
if ta.crossunder(low , gEW.bx.get_bottom()) and bar_index <= gEW.bx.get_right()
label.new(bar_index, low , yloc= yloc.belowbar, style= label.style_xcross, color=color.red, size=size.tiny)
else
if ta.crossover (high, gEW.bx.get_top ()) and bar_index <= gEW.bx.get_right()
label.new(bar_index, high, yloc= yloc.abovebar, style= label.style_xcross, color=color.red, size=size.tiny)
//
if barstate.islast
// –––[ get last 2 EW's ]–––
getEW = aEW.get(0)
if aEW.size() > 1
getEW1 = aEW.get(1)
last_0x := getEW.l1.get_x1(), last_0y := getEW.l1.get_y1()
last_6x := getEW.l5.get_x2(), last_6y := getEW.l5.get_y2()
//
diff = math.abs(last_6y - last_0y) // –––[ max/min difference ]–––
_500 = diff * i_500
_618 = diff * i_618
_764 = diff * i_764
_854 = diff * i_854
bull = getEW.dir == 1
// –––[ if EW is not valid or an ABC has developed -> remove fibonacci lines ]–––
if getEW.on == false or getEW.bC.get_x() > getEW.b5.get_x()
nFibL.setNa()
else
// –––[ get.on == true ~ valid EW ]–––
max_500 = last_6y + ((bull ? -1 : 1) * _500)
max_618 = last_6y + ((bull ? -1 : 1) * _618)
max_764 = last_6y + ((bull ? -1 : 1) * _764)
max_854 = last_6y + ((bull ? -1 : 1) * _854)
//
nFibL.set(last_6x, bar_index + 10, max_500, max_618, max_764, max_854, last_6y)
// –––[ if (2) label overlap with (C) label ]–––
if getEW.b2.get_x() == getEW1.bC.get_x()
getEW.b1.set_textcolor(color(na))
getEW.b2.set_textcolor(color(na))
strB = getEW1.bB.get_text()
strC = getEW1.bC.get_text()
strB_ = str.replace(strB, "(b)", "(b) (1)", 0)
strC_ = str.replace(strC, "(c)", "(c) (2)", 0)
getEW1.bB.set_text(strB_)
getEW1.bC.set_text(strC_)
//
// –––[ check if fib limits are broken ]–––
getP_854 = nFibL.wave1_0_854.get_y1()
for i = 0 to bar_index - nFibL.wave1_0_854.get_x1()
if getEW.dir == -1
if high[i] > getP_854
nFibL._break_ := true
break
else
if low [i] < getP_854
nFibL._break_ := true
break
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
switch nFibL._break_
true => nFibL.sol_dot('dot', color.new(color.red , 95))
false => nFibL.sol_dot('sol', color.new(color.lime, 95))
=>
nFibL.wave1_0_500.set_xy1(na, na)
nFibL.wave1_0_500.set_xy2(na, na)
nFibL.wave1_0_618.set_xy1(na, na)
nFibL.wave1_0_618.set_xy2(na, na)
nFibL.wave1_0_764.set_xy1(na, na)
nFibL.wave1_0_764.set_xy2(na, na)
nFibL.wave1_0_854.set_xy1(na, na)
nFibL.wave1_0_854.set_xy2(na, na)
nFibL.wave1_pole_.set_xy1(na, na)
nFibL.wave1_pole_.set_xy2(na, na)
nFibL.l_fill_.set_color(color(na))
if aEW.size() > 15
pop = aEW.pop()
pop.l1.delete(), pop.b1.delete()
pop.l2.delete(), pop.b2.delete()
pop.l3.delete(), pop.b3.delete()
pop.l4.delete(), pop.b4.delete()
pop.l5.delete(), pop.b5.delete()
pop.lA.delete(), pop.bA.delete()
pop.lB.delete(), pop.bB.delete()
pop.lC.delete(), pop.bC.delete()
pop.lb.delete(), pop.bx.delete()
//----------------------------------
[longEntry, shortEntry]
//Plots
draw(s1, len1, col1, 0)
// Call the draw function and get the long and short entry conditions
[longEntry1, shortEntry1] = draw(s1, len1, col1, 0)
// Calculate the stop loss levels
longStopLossLevel = close * (1 - stopLossPercentage / 100)
shortStopLossLevel = close * (1 + stopLossPercentage / 100)
// Long Entry Condition
if (shortEntry1 and (tradingDirection == "Long" or tradingDirection == "Both"))
strategy.entry("Buy", strategy.long)
strategy.exit('Exit Long', 'Buy', stop=longStopLossLevel)
// Short Entry Condition
if (longEntry1 and (tradingDirection == "Short" or tradingDirection == "Both"))
strategy.entry("Sell", strategy.short)
strategy.exit('Exit Short', 'Sell', stop=shortStopLossLevel)
// Supertrend Exit Conditions
[supertrend, direction] = ta.supertrend(STMultiplier, STLength)
var float prevDirection = na
longExit = false
shortExit = false
if na(prevDirection)
prevDirection := direction
else
if direction != prevDirection
longExit := prevDirection < 0
shortExit := prevDirection > 0
prevDirection := direction
// Long Exit Condition
if (longExit and (tradingDirection == "Long" or tradingDirection == "Both"))
strategy.close("Buy")
// Short Exit Condition
if (shortExit and (tradingDirection == "Short" or tradingDirection == "Both"))
strategy.close("Sell") |
Linear On MACD | https://www.tradingview.com/script/QHGAgBT2-Linear-On-MACD/ | stocktechbot | https://www.tradingview.com/u/stocktechbot/ | 43 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © stocktechbot
//@version=5
strategy("Linear On MACD", overlay=true, margin_long=100, margin_short=100)
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
tolerance = input.string(title="Risk tolerance", defval = "LOW", options=["LOW", "HIGH"])
chng = 0
obv = ta.cum(math.sign(ta.change(close)) * volume)
if close < close[1] and (open < close)
chng := 1
else if close > close[1]
chng := 1
else
chng := -1
obvalt = ta.cum(math.sign(chng) * volume)
//src = input(title="Source", defval=close)
src = obvalt
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
//hline(0, "Zero Line", color=color.new(#787B86, 50))
//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
//plot(macd, title="MACD", color=col_macd)
//plot(signal, title="Signal", color=col_signal)
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
//Linear Regression
vol = volume
// Function to calculate linear regression
linregs(y, x, len) =>
ybar = math.sum(y, len)/len
xbar = math.sum(x, len)/len
b = math.sum((x - xbar)*(y - ybar),len)/math.sum((x - xbar)*(x - xbar),len)
a = ybar - b*xbar
[a, b]
// Historical stock price data
price = close
// Length of linear regression
len = input(defval = 21, title = 'Lookback')
// Calculate linear regression for stock price based on volume
[a, b] = linregs(price, vol, len)
// Predicted stock price based on volume
predicted_price = a + b*vol
// Check if predicted price is between open and close
is_between = open < predicted_price and predicted_price < close
// Plot predicted stock price
plot(predicted_price, color=color.rgb(218, 27, 132), linewidth=2, title="Predicted Stock Price")
plot(ta.vwma(predicted_price,len), color=color.rgb(199, 43, 64), linewidth=2, title="Predicted Stock Price")
//BUY Signal
lincrossunder = close > predicted_price
macdrise = ta.rising(macd,2)
//macdvollong = ta.crossover(macd, signal)
//macdlong = ta.crossover(macdLine, signalLine)
macdvollong = macd > signal
macdlong = macdLine > signalLine
longCondition=false
if macdlong and macdvollong and is_between and ta.rising(predicted_price,1)
longCondition := true
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
//Sell Signal
lincrossover = close < predicted_price
macdfall = ta.falling(macd,1)
macdsell = macd < signal
shortCondition = false
risklevel = predicted_price
if (tolerance == "HIGH")
risklevel := ta.vwma(predicted_price,len)
if macdfall and macdsell and (macdLine < signalLine) and (close < risklevel)
shortCondition := true
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
|
Linear Cross Trading Strategy | https://www.tradingview.com/script/owieyhFU-Linear-Cross-Trading-Strategy/ | stocktechbot | https://www.tradingview.com/u/stocktechbot/ | 76 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © stocktechbot
//@version=5
strategy("Linear Cross", overlay=true, margin_long=100, margin_short=0)
//Linear Regression
vol = volume
// Function to calculate linear regression
linregs(y, x, len) =>
ybar = math.sum(y, len)/len
xbar = math.sum(x, len)/len
b = math.sum((x - xbar)*(y - ybar),len)/math.sum((x - xbar)*(x - xbar),len)
a = ybar - b*xbar
[a, b]
// Historical stock price data
price = close
// Length of linear regression
len = input(defval = 21, title = 'Strategy Length')
linearlen=input(defval = 9, title = 'Linear Lookback')
[a, b] = linregs(price, vol, len)
// Calculate linear regression for stock price based on volume
//eps = request.earnings(syminfo.ticker, earnings.actual)
//MA For double confirmation
out = ta.sma(close, 200)
outf = ta.sma(close, 50)
outn = ta.sma(close, 90)
outt = ta.sma(close, 21)
outthree = ta.sma(close, 9)
// Predicted stock price based on volume
predicted_price = a + b*vol
// Check if predicted price is between open and close
is_between = open < predicted_price and predicted_price < close
//MACD
//[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
// Plot predicted stock price
plot(predicted_price, color=color.rgb(65, 59, 150), linewidth=2, title="Predicted Price")
plot(ta.sma(predicted_price,linearlen), color=color.rgb(199, 43, 64), linewidth=2, title="MA Predicted Price")
//offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
plot(out, color=color.blue, title="MA200")
[macdLine, signalLine, histLine] = ta.macd(predicted_price, 12, 26, 9)
//BUY Signal
longCondition=false
mafentry =ta.sma(close, 50) > ta.sma(close, 90)
//matentry = ta.sma(close, 21) > ta.sma(close, 50)
matwohun = close > ta.sma(close, 200)
twohunraise = ta.rising(out, 2)
twentyrise = ta.rising(outt, 2)
macdrise = ta.rising(macdLine,2)
macdlong = ta.crossover(predicted_price, ta.wma(predicted_price,linearlen)) and (signalLine < macdLine)
if macdlong and macdrise
longCondition := true
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
//Sell Signal
lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
daysSinceEntry = len
daysSinceEntry := int((time - strategy.opentrades.entry_time(strategy.opentrades - 1)) / (24 * 60 * 60 * 1000))
percentageChange = (close - lastEntryPrice) / lastEntryPrice * 100
//trailChange = (ta.highest(close,daysSinceEntry) - close) / close * 100
//label.new(bar_index, high, color=color.black, textcolor=color.white,text=str.tostring(int(trailChange)))
shortCondition=false
mafexit =ta.sma(close, 50) < ta.sma(close, 90)
matexit = ta.sma(close, 21) < ta.sma(close, 50)
matwohund = close < ta.sma(close, 200)
twohunfall = ta.falling(out, 3)
twentyfall = ta.falling(outt, 2)
shortmafall = ta.falling(outthree, 1)
macdfall = ta.falling(macdLine,1)
macdsell = macdLine < signalLine
if macdfall and macdsell and (macdLine < signalLine) and ta.falling(low,2)
shortCondition := true
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
|
SRP Strategy [ ZCrypto ] | https://www.tradingview.com/script/6n0tjnpK-SRP-Strategy-ZCrypto/ | TZack88 | https://www.tradingview.com/u/TZack88/ | 802 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TZack88
//@version=5
strategy("SRP Strategy [ ZCrypto ]",
overlay=true,
max_labels_count = 500,
pyramiding = 5,
default_qty_type = strategy.cash,
initial_capital = 1000,
commission_type = strategy.commission.percent,
commission_value = 0.07,
default_qty_value = 100
)
//
// inputs
color bgray = color.rgb(128, 223, 236, 81)
color WHITE = color.rgb(210, 210, 210)
color red = color.rgb(128, 49, 49, 67)
color white = color.rgb(248, 248, 248, 14)
color olive = color.olive
color blue = color.rgb(23, 43, 77)
color Yellow = color.rgb(255, 186, 75)
color BG = color.from_gradient(close,low,high ,color.rgb(16, 194, 167),color.rgb(240, 141, 71))
string s_group = " Strategy Settings"
string visual = "Visuals"
int offset = 15
var int glb_dealstart_bar_time = 0
int Length = 14
float ChangePercentage = input.float(title='SRP %',defval=1.4,group='SRP Settings',inline = "00",step=0.1)
float core = ta.vwma(hlc3, Length)
float below = input(55,title="⬇️",group='SRP Settings',inline = "00")
float above = input(100,title="⬆️",group='SRP Settings',inline = "00")
bool mintpbool = input.bool(true,"Minimal TP❓➔ ",group = s_group,inline="01")
float mintp = input.float(2.0,"",step= 0.1 , group = s_group,inline="01")/100
float minSOchange = input.float(title='Price change %', defval=2.0, step=0.1, group = s_group,inline="01")
float base = input.float(title='$ Base order', defval=100, step=1, group = s_group,inline="01")
float safety = input.float(title='DCA Multi', defval=1.5, step=1, group = s_group,inline="01",tooltip = "It Multiply the position size by this value")
int sonum = input.int(title='DCA Count', defval=4, step=1, group = s_group,inline="01",tooltip = "How Many DCA orders Do you want ?!")+1
bool DCATYPE = input.string("Volume Multiply",title ="DCA TYPE",options = ["Volume Multiply","Base Multiply"],group = s_group,inline="01") == "Volume Multiply"
bool limit_date_range = input.bool(title='Backtest Date', defval=true, group="Backtest Date")
int start_time = input.time(defval=timestamp('11 OCT 2022 00:00 +0000'), title='Start Time', group="Backtest Date")
int end_time = input.time(defval=timestamp('31 Dec 2080 00:00 +0000'), title='End Time', group="Backtest Date")
bool show_table = input(true,title= "Show Table ❓",inline = "001",group = visual)
string position = input.string("Top Right", options = ["Middle Right","Top Center","Top Right","Middle Left","Middle Center","Bottom Left","Bottom Center","Bottom Right"],title = 'Position',inline = "001",group = visual)
color textcolos = input.color(Yellow,title = "Text Color",inline = "001",group = visual)
bool showdeals = input(true,"Deal lines❓",inline = "002",group =visual )
color profitcolor = input.color(bgray,"",inline = "002",group =visual )
color socolor = input.color(red,"",inline = "002",group =visual )
color avgcolor = input.color(white,"",inline = "002",group =visual )
bool showBG = input(false,"Deal BG Color❓",inline = "003",group =visual )
color bgcolor = input.color(blue,"",inline = "003",group =visual )
bool showpnllabel = input(true,"PNL Label❓",inline = "004",group =visual )
color pnlcolor = input.color(olive,"",inline = "004",group =visual )
string table_name ='SRP Strategy [ZCrypto]'
var int socounter = 0
var int dealcount = 0
// Core calculation ---------{
in_date_range = true
if limit_date_range
in_date_range := time >= start_time and time <= end_time
else
in_date_range := true
vwma_above = core * (1 + (ChangePercentage / 100))
vwma_below = core * (1 - (ChangePercentage / 100))
//
up = ta.rma(math.max(ta.change(close), 0), 7)
down = ta.rma(-math.min(ta.change(close), 0), 7)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
mf = ta.mfi(hlc3, 7)
rsi_mfi = math.abs(rsi+mf/2)
long = low <= vwma_below and (rsi_mfi < below)
short = high >= vwma_above and (rsi_mfi > above)
table_position() =>
switch position
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
var summary_table = table.new(table_position(), 15, 33, frame_color=color.rgb(58, 58, 59, 38), frame_width=3,border_width = 2)
change_color(con)=>
con ? color.rgb(0, 149, 77) : color.rgb(152, 46, 46)
table_cell(table,_row,in1,in2)=>
table.cell(table, 0, _row,
in1,
text_color=textcolos,
bgcolor = color.rgb(58, 58, 59, 38),
text_size = size.small,
text_halign = text.align_left
)
table.cell(table, 1, _row, str.tostring(in2), text_color=WHITE,text_size = size.small,bgcolor =color.rgb(120, 123, 134, 38) )
//------------}
calcNextSOprice(pcnt) =>
if strategy.position_size > 0
strategy.position_avg_price - (math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick)) * syminfo.mintick
else if strategy.position_size < 0
strategy.position_avg_price + (math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick)) * syminfo.mintick
else
na
calcChnagefromlastdeal() =>
last_deal = strategy.opentrades.entry_price(strategy.opentrades - 1)
math.abs(((close - (last_deal) ) /close ) * 100 )
Calcprofitpercent() =>
math.abs(((close - strategy.position_avg_price ) /close ) * 100 )
// def calculate(base, SO):
// return so_size
SO = base * safety
CapitalCalculation() =>
float total = 0.0
for x= 1 to sonum - 1 by 1
so_size = SO * math.pow(safety, x-1)
total+= so_size
total + base
// plot(SO,"?111!")
// plot(CapitalCalculation(),"?!")
calculateSO(num)=>
SOv = base * math.pow(safety,num)
SOv
SOconditions()=>
(calcChnagefromlastdeal() > minSOchange ) and (close < calcNextSOprice(minSOchange))
mintpclogic()=>
(close > (strategy.position_avg_price * (1 + mintp)))
get_timestring_from_seconds(seconds) =>
if seconds >= 86400
string _string = str.tostring(math.round(seconds / 86400, 1)) + ' days'
else if seconds >= 3600
string _string = str.tostring(math.round(seconds / 3600, 1)) + ' hours'
else
string _string = str.tostring(math.round(seconds / 60, 1)) + ' mins'
get_timespan_string(start_time, end_time) =>
_seconds_diff = (end_time - start_time) / 1000
get_timestring_from_seconds(_seconds_diff)
Calcprofit()=>
(( close * strategy.position_size ) - (strategy.position_avg_price * strategy.position_size))
// var label t = na , label.delete(t) , t:= label.new(bar_index,high,str.tostring(mintpclogic()))
// plot(strategy.netprofit,"?!",display = display.data_window)
PNLlabel()=>
message = ""
message += "PNL : " +str.tostring(math.round(Calcprofit(), 2)) + ' ' + str.tostring(syminfo.currency) + '\n'
message += "Time: " +get_timespan_string(glb_dealstart_bar_time, time)+ '\n'
message += "PNL%: " + str.tostring(math.round(Calcprofitpercent(),2))+ " %"
topy = high + (high* 0.04)
label.new(bar_index + 1,
topy,
text=message,
yloc=yloc.price,
size=size.normal,
style=label.style_label_lower_left,
textcolor=color.black,
textalign = text.align_left,
color=pnlcolor
)
var float removed = na
Opentrade()=>
strategy.opentrades > 0 ? 1 : 0
PNLpercentage()=> ((close - strategy.position_avg_price ) /close ) * 100
//--------------------------------------------------------------------------
// # Strategy Inputs # |
//--------------------------------------------------------------------------
// plot(strategy.opentrades,display = display.data_window,title = "OpenSZ")
if (long) and strategy.opentrades == 0 and in_date_range
socounter := 0
dealcount+=1
dealcount
glb_dealstart_bar_time := time
strategy.entry("LONG", strategy.long,comment = "D # " + str.tostring(dealcount),qty = base/close )
alert("New LONG DEAL for {{ticker}}",freq = alert.freq_once_per_bar_close)
removed:= strategy.netprofit / close
if (long) and SOconditions() and strategy.opentrades > 0 and strategy.opentrades < sonum
socounter+=1
socounter
strategy.entry('LONG' , strategy.long,qty = DCATYPE ? (strategy.position_size*safety) : calculateSO(socounter)/close,comment = "SO # "+str.tostring(socounter))
alert("New DCA DEAL for {{ticker}}",freq = alert.freq_once_per_bar_close)
if strategy.position_size > 0 and short and (mintpbool ? mintpclogic() : true) and in_date_range
strategy.close("LONG",comment = " ")
alert("DEAL Close for {{ticker}}",freq = alert.freq_once_per_bar_close)
if showpnllabel
PNLlabel()
// hp= plot(vwma_above, color=color.new(color.red, 0))
// lp= plot(vwma_below, color=color.new(color.green, 0))
// plotshape(long and not long[1],title="Buy",style=shape.labelup,color=color.rgb(53, 141, 56),location= location.belowbar ,size=size.tiny,text= "B",textcolor = color.white)
// plotshape(short,title="Sell",style=shape.labeldown,color=color.rgb(146, 18, 13),location= location.abovebar ,size=size.tiny,text = "S",textcolor = color.white)
avg = plot(showdeals? strategy.position_avg_price : na, 'AVG Price',color= avgcolor, style=plot.style_linebr,editable = false)
sl = plot(showdeals ? calcNextSOprice(minSOchange): na, 'SO change %', color.orange, style=plot.style_linebr,editable = false)
tp = plot(showdeals ? strategy.position_avg_price * (1 + mintp): na, 'SO change %', color.rgb(3, 233, 245), style=plot.style_linebr,editable = false)
fill(tp, avg, color =profitcolor)
fill(avg, sl, color = socolor)
bgcolor(showBG and strategy.position_size > 0 ? color.new(bgcolor,90): na)
statusOpen()=>
Opentrade() == 0 ? str.tostring(Opentrade()) : str.tostring(Opentrade()) + "\n" + "------" + "\n" + str.tostring(syminfo.currency) + " :" + "$" + str.tostring(math.round(strategy.openprofit,2))+ "\n"
+ "------" + "\n" + "% " + " :" + str.tostring(math.round(PNLpercentage(),2))+ " %"
// if barstate.isconfirmed
// _row = 1
// p_row = 1
// if show_table
// text_color = show_table ? color.rgb(210, 210, 210) : color.black
// table.cell(summary_table, 0, 0, table_name,
// bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167),
// color.rgb(240, 141, 71)),
// text_size = size.small,
// text_font_family=font.family_default)
// table.cell(summary_table, 1, 0, "",
// bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167),
// color.rgb(240, 141, 71)),
// text_halign = text.align_left)
// table.merge_cells(summary_table, 0, 0, 1, 0)
// table.cell(summary_table, 0, 1, 'Deal Status', bgcolor=color.rgb(58, 58, 59, 38),text_color = textcolos,text_size = size.small,text_font_family=font.family_default,text_halign = text.align_left)
// table.cell(summary_table, 1, 1, statusOpen() , bgcolor=color.rgb(120, 123, 134, 38),text_color = WHITE,text_size = size.small,text_font_family=font.family_default)
// _row += 1
// table_cell(summary_table,_row, "Required Capital",CapitalCalculation())
// // _row += 1
// // table_cell(summary_table,_row, "Total PNL",close>open ? "True" : "False")
// _row += 1
// table_cell(summary_table,_row, "Total PNL",strategy.netprofit)
///
// |
Quantitative Trend Strategy- Uptrend long | https://www.tradingview.com/script/I4FhUvyq-Quantitative-Trend-Strategy-Uptrend-long/ | CheatCode1 | https://www.tradingview.com/u/CheatCode1/ | 143 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CheatCode1
//@version=5
strategy("Quantitative Trend Strategy- Uptrend long", 'Steady Uptrend Strategy', overlay=true, initial_capital = 1500, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.01, default_qty_type = strategy.percent_of_equity)
length = input.int(20, minval=1)
src = input(close, title="Source")
basis = ta.sma(src, length)
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
inp1 = input.int(46, 'LookbackLeft')
inp2 = input.int(32, 'LookbackRight')
l1 = ta.pivothigh(close, inp1, inp2)
S1 = ta.pivotlow(close, inp1, inp2)
// plot(l1, 'Pivothigh', color.red, 1)
// // plot(S1, 'Pivot Low', color.red)
l1V = ta.valuewhen(l1, close, 0)
S1V = ta.valuewhen(S1, close, 0)
Plotl1 = not na(l1) ? l1V : na
PlotS1 = not na(S1) ? S1V : na
plot(Plotl1, 'Resistance', color.green, 1, plot.style_stepline, true)
plot(PlotS1, 'Support', color.red, 1, plot.style_stepline, true)
Priceforlong = close > l1V ? true : na
Priceforshort = close < S1V ? true : na
plotshape(Priceforlong ? high : na, 'p', shape.arrowup, location.abovebar, color.green, size = size.small)
plotshape(Priceforshort ? low : na, 's', shape.arrowdown, location.belowbar, color.red, size = size.small)
vol = volume
volma = ta.sma(vol, 20)
Plotl1C = ta.valuewhen(na(Plotl1), l1V, 0)
PlotS1C = ta.valuewhen(na(PlotS1), S1V, 0)
//Strategy Execution
volc = volume > volma
Lc1 = Priceforlong
Sc1 = Priceforshort
sL = Plotl1 < PlotS1 ? close : na
sS = PlotS1 > Plotl1 ? close : na
if Lc1
strategy.entry('Long', strategy.long)
// if Sc1 and C2
// strategy.entry('Short', strategy.short)
if Priceforshort
strategy.cancel('Long')
if Priceforlong
strategy.cancel('Short')
// Stp1 = ta.crossover(k, d)
// Ltp1 = ta.crossunder(k, d)
// Ltp = d > 70 ? Ltp1 : na
// Stp = d < 30 ? Stp1 : na
if strategy.openprofit >= 0 and sL
strategy.close('Long')
if strategy.openprofit >= 0 and sS
strategy.close('Short')
takeP = input.float(2, title='Take Profit') / 100
stopL = input.float(1.75, title='Stop Loss') / 100
// // Pre Directionality
Stop_L = strategy.position_avg_price * (1 - stopL)
Stop_S = strategy.position_avg_price * (1 + stopL)
Take_S= strategy.position_avg_price * (1 - takeP)
Take_L = strategy.position_avg_price * (1 + takeP)
// sL = Plotl1 < PlotS1 ? close : na
// sS = PlotS1 < Plotl1 ? close : na
// //Post Excecution
if strategy.position_size > 0 and not (Lc1)
strategy.exit("Close Long", stop = Stop_L, limit = Take_L)
if strategy.position_size < 0 and not (Sc1)
strategy.exit("Close Short", stop = Stop_S, limit = Take_S) |
Good Mode RSI v2 | https://www.tradingview.com/script/X1NYTex2/ | corderomoraj | https://www.tradingview.com/u/corderomoraj/ | 150 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © corderomoraj
//@version=5
strategy("Good Mode RSI v2", overlay=true)
// Parámetros de la estrategia
rsiPeriod = input(2, "RSI Period")
sellLevel = input(96, "Sell Level")
buyLevel = input(4, "Buy Level")
takeProfitLevelSell = input(20, "Take Profit Level Sell")
takeProfitLevelBuy = input(80, "Take Profit Level Buy")
var float trailingStopPrice = na
var float trailingStopOffset = input(100, "Trailing Stop Offset (pips)")
// Capital inicial
initialCapital = 250
positionSize = initialCapital * 0.015
// Condiciones de entrada y salida
rsi = ta.rsi(close, rsiPeriod)
// Condiciones de entrada y salida para la orden de venta
sellCondition = rsi > sellLevel
closeSellCondition = rsi < takeProfitLevelSell
// Condiciones de entrada y salida para la orden de compra
buyCondition = rsi < buyLevel
closeBuyCondition = rsi > takeProfitLevelBuy
// Trailing Stop para las posiciones de venta
if strategy.position_size < 0
if low < trailingStopPrice
trailingStopPrice := low
strategy.exit("Sell", "Sell", trail_offset = trailingStopOffset * syminfo.mintick, trail_price = trailingStopPrice)
// Trailing Stop para las posiciones de compra
if strategy.position_size > 0
if high > trailingStopPrice
trailingStopPrice := high
strategy.exit("Buy", "Buy", trail_offset = trailingStopOffset * syminfo.mintick, trail_price = trailingStopPrice)
// Ejecutar orden de venta
if (sellCondition)
strategy.entry("Sell", strategy.short, qty = positionSize)
trailingStopPrice := high
// Cerrar orden de venta
if (closeSellCondition)
strategy.close("Sell")
// Ejecutar orden de compra
if (buyCondition)
strategy.entry("Buy", strategy.long, qty = positionSize)
trailingStopPrice := low
// Cerrar orden de compra
if (closeBuyCondition)
strategy.close("Buy")
|
CCI+EMA Strategy with Percentage or ATR TP/SL [Alifer] | https://www.tradingview.com/script/hHfPXUTx-CCI-EMA-Strategy-with-Percentage-or-ATR-TP-SL-Alifer/ | alifer123 | https://www.tradingview.com/u/alifer123/ | 299 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © alifer123
//@version=5
strategy("CCI+RSI+EMA Strategy with Percentage or ATR TP/SL [Alifer]", shorttitle = "CCIRSIEMA+TP/SL", overlay=false,
initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.045)
// CCI
cciLength = input(14, "CCI Length", group = "CCI")
cciOverbought = input.int(150, step = 10, title = "Overbought", group = "CCI")
cciOversold = input.int(-140, step = 10, title = "Oversold", group = "CCI")
src = hlc3
ma = ta.sma(src, cciLength)
cci = (src - ma) / (0.015 * ta.dev(src, cciLength))
// RSI
useRSI = input(false, "Use RSI", tooltip = "Only enters long when RSI is Oversold, only enters short when RSI is Overbought", group = "RSI")
rsiLength = input(14, "RSI Length", group = "RSI")
rsiOverbought = input.int(70, step = 5, title = "RSI Overbought", group = "RSI")
rsiOversold = input.int(30, step = 5, title = "RSI Oversold", group = "RSI")
var float rsi = na
if useRSI
rsi := ta.rsi(src, rsiLength)
// EMA
useEMA = input(true, "Use EMA", tooltip = "Only enters long when price is above the EMA, only enters short when price is below the EMA", group = "EMA")
emaLength = input(55, "EMA Length", group ="EMA")
var float ema = na
if useEMA
ema := ta.ema(src, emaLength)
// Take Profit and Stop Loss Method
tpSlMethod_percentage = input(true, "Percentage TP/SL", group="TP/SL Method")
tpSlMethod_atr = input(false, "ATR TP/SL", group="TP/SL Method")
// Percentage-based Take Profit and Stop Loss
tp_percentage = input.float(10.0, title="Take Profit (%)", step=0.1, group="TP/SL Method")
sl_percentage = input.float(10.0, title="Stop Loss (%)", step=0.1, group="TP/SL Method")
// ATR-based Take Profit and Stop Loss
atrLength = input(20, title="ATR Length", group="TP/SL Method")
atrMultiplier = input(4.0, title="ATR SL Multiplier", group="TP/SL Method")
riskRewardRatio = input(2.0, title="Risk Reward Ratio", group="TP/SL Method")
// Calculate TP/SL levels based on the selected method, or leave them undefined if neither method is selected
longTP = tpSlMethod_percentage ? strategy.position_avg_price * (1 + tp_percentage / 100) : na
longSL = tpSlMethod_percentage ? strategy.position_avg_price * (1 - sl_percentage / 100) : na
shortTP = tpSlMethod_percentage ? strategy.position_avg_price * (1 - tp_percentage / 100) : na
shortSL = tpSlMethod_percentage ? strategy.position_avg_price * (1 + sl_percentage / 100) : na
if tpSlMethod_atr
longSL := strategy.position_avg_price - ta.atr(atrLength) * atrMultiplier
longTP := ((strategy.position_avg_price - longSL) * riskRewardRatio) + strategy.position_avg_price
shortSL := strategy.position_avg_price + ta.atr(atrLength) * atrMultiplier
shortTP := ((strategy.position_avg_price - shortSL) * riskRewardRatio) - strategy.position_avg_price
// Enter long position when CCI crosses below oversold level and price is above EMA (if enabled) and RSI is oversold (if enabled)
longCondition = ta.crossover(cci, cciOversold) and (not useEMA or close > ema) and (not useRSI or rsi < rsiOversold)
if longCondition
strategy.entry("Buy", strategy.long)
// Enter short position when CCI crosses above overbought level and price is below EMA (if enabled) and RSI is overbought (if enabled)
shortCondition = ta.crossunder(cci, cciOverbought) and (not useEMA or close < ema) and (not useRSI or rsi > rsiOverbought)
if shortCondition
strategy.entry("Sell", strategy.short)
// Close long positions with Take Profit or Stop Loss
if strategy.position_size > 0
strategy.exit("Long Exit", "Buy", limit=longTP, stop=longSL)
// Close short positions with Take Profit or Stop Loss
if strategy.position_size < 0
strategy.exit("Short Exit", "Sell", limit=shortTP, stop=shortSL)
// Close positions when CCI crosses back above oversold level in long positions or below overbought level in short positions
if ta.crossover(cci, cciOverbought)
strategy.close("Buy")
if ta.crossunder(cci, cciOversold)
strategy.close("Sell")
// Plotting
color_c = cci > cciOverbought ? color.red : (cci < cciOversold ? color.green : color.white)
plot(cci, "CCI", color=color_c)
hline(0, "Middle Band", color=color.new(#787B86, 50))
obband = hline(cciOverbought, "OB Band", color=color.new(#78867a, 50))
osband = hline(cciOversold, "OS Band", color=color.new(#867878, 50))
fill(obband, osband, color=color.new(#787B86, 90))
plot(rsi, "RSI", color=color.new(#3c65ec, 0)) |
Crunchster's Turtle and Trend System | https://www.tradingview.com/script/7QZGe04Y-Crunchster-s-Turtle-and-Trend-System/ | Crunchster1 | https://www.tradingview.com/u/Crunchster1/ | 83 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Crunchster1
//@version=5
strategy(title="Crunchster's Turtle and Trend System", shorttitle="Turtle Trend", overlay=true, slippage=10, pyramiding=1, precision = 4, calc_on_order_fills = false, calc_on_every_tick = false, default_qty_value = 0.1, initial_capital = 1000, commission_value = 0.06, process_orders_on_close = true)
// Inputs and Parameters
src = input(close, 'Source', group='Strategy Settings')
length = input.int(title="Lookback period for fast EMA", defval=10, minval=2, group='Strategy Settings', tooltip='This sets the lookback period for the fast exponential moving average. The slow EMA is 5x the fast EMA length')
blength = input.int(title="Lookback period for Breakout", defval=20, minval=5, step=5, group='Strategy Settings')
long = input(true, 'Long', inline='08', group='Strategy toggle')
short = input(true, 'Short', inline='08', group='Strategy toggle', tooltip='Toggle long/short strategy on/off')
EMAwt = input(false, 'Trend', inline='01', group='Strategy toggle')
breakwt = input(true, 'Breakout', inline='01', group='Strategy toggle', tooltip='Toggle trend/breakout strategy on/off')
stopMultiple = input.float(2, 'Stop multiple', step=0.5, group='Risk Management Settings', tooltip='Multiple for ATR, setting hard stop loss from entry price')
trail = input.int(10, 'Trail lookback', step=5, group='Risk Management Settings', tooltip='Lookback period for the trailing stop')
lev = input.float(1, 'Max Leverage', step=0.5, group='Risk Management Settings', tooltip='Max leverage sets maximum allowable leverage of total capital (initial capital + any net profit), capping maximum volatility adjusted position size')
riskT = input.float(15, maxval=75, title='Annualised Volatility Target %', group='Risk Management Settings', tooltip='Specify annual risk target, used to determine volatility adjusted position size. Annualised daily volatility is referenced to this value and position size adjusted accordingly')
comp = input(true, 'Compounding', inline='09', group='Risk Management Settings')
Comppct = input.float(50, '%', step=5, inline='09', group='Risk Management Settings', tooltip='Toggle compounding of profit, and set % of profit to compound')
// Backtesting period
FromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, inline='04', group='Backtest range')
FromMonth = input.int(defval=1, title='From Mon', minval=1, maxval=12, inline='04', group='Backtest range')
FromYear = input.int(defval=2018, title='From Yr', minval=1900, inline='04', group='Backtest range', tooltip='Set start of backtesting period')
ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31, inline='05', group='Backtest range')
ToMonth = input.int(defval=1, title='To Mon', minval=1, maxval=12, inline='05', group='Backtest range')
ToYear = input.int(defval=9999, title='To Yr', minval=1900, inline='05', group='Backtest range', tooltip='Set end of backtesting period')
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window = time >= start and time <= finish
// Breakout strategy
lower = ta.lowest(low[1], blength)
upper = ta.highest(high[1], blength)
basis = math.avg(upper, lower)
signal = 20*(close - basis) / (upper - lower)
// Trend strategy
fEMA = ta.ema(close[1], length)
sEMA = ta.ema(close[1], length*5)
emadiff = fEMA - sEMA
nemadiff = 5*emadiff/(ta.stdev(close - close[1], 252))
//Risk Management formulae
tr = math.max(high - low, math.abs(high - close), math.abs(low - close)) //True range
stopL = ta.sma(tr, 14) //Average true range
stdev = ta.stdev(close-close[1], 14) //volatility of recent returns
maxcapital = strategy.initial_capital+strategy.netprofit //Maximum capital available to invest - initial capital net of profit
annvol = 100*math.sqrt(365)*stdev/close //converts recent volatility of returns into annualised volatility of returns - assumes daily timeframe
risk = 1.1
if comp
risk := (strategy.initial_capital+(Comppct*strategy.netprofit/100))//adjust investment capital to include compounding
else
risk := strategy.initial_capital
shares = (risk * (riskT/annvol)) / close //calculates volatility adjusted position size, dependent on user specified annualised risk target
if ((shares*close) > lev*maxcapital) //ensures position size does not exceed available capital multiplied by user specified maximum leverage
shares := lev*maxcapital/close
//To set the price at the entry point of trade
Posopen() =>
math.abs(strategy.position_size[1]) <= 0 and math.abs(strategy.position_size) > 0
var float openN = na
if Posopen()
openN := stopL
// Trailing stop
tlower = ta.lowest(low[1], trail)
tupper = ta.highest(high[1], trail)
tbasis = math.avg(tupper, tlower)
tsignal = 20*(close - tbasis) / (tupper - tlower)
// Strategy Rules
if EMAwt
if long
longCondition2 = (nemadiff >2 and nemadiff[1] <2) and window
exitlong = tsignal <= -10
if (longCondition2)
strategy.entry('Trend Long!', strategy.long, qty=shares)
if strategy.position_size > 0
strategy.exit('Stop Long', from_entry = 'Trend Long!', stop=(strategy.opentrades.entry_price(0) - (openN * stopMultiple)))
if (exitlong)
strategy.close('Trend Long!', immediately = true)
if short
shortCondition2 = (nemadiff <-1 and nemadiff[1] >-1) and window
exitshort = tsignal >= 10
if (shortCondition2)
strategy.entry('Trend Short!', strategy.short, qty=shares)
if strategy.position_size < 0
strategy.exit('Stop Short', from_entry = 'Trend Short!', stop=(strategy.opentrades.entry_price(0) + (openN * stopMultiple)))
if (exitshort)
strategy.close('Trend Short!', immediately = true)
if breakwt
if long
longCondition1 = (signal >= 10) and window
exitlong = tsignal <= -10
if (longCondition1)
strategy.entry('Break Long!', strategy.long, qty=shares)
if strategy.position_size > 0
strategy.exit('Stop Long', from_entry = 'Break Long!', stop=(strategy.opentrades.entry_price(0) - (openN * stopMultiple)))
if (exitlong)
strategy.close('Break Long!', immediately = true)
if short
shortCondition1 = (signal <= -10) and window
exitshort = tsignal >= 10
if (shortCondition1)
strategy.entry('Break Short!', strategy.short, qty=shares)
if strategy.position_size < 0
strategy.exit('Stop Short', from_entry = 'Break Short!', stop=(strategy.opentrades.entry_price(0) + (openN * stopMultiple)))
if (exitshort)
strategy.close('Break Short!', immediately = true)
// Visuals of trend and direction
plot(nemadiff, title='EMA Forecast', color=color.black, display=display.none)
plot(ta.sma(ta.median(math.sqrt(math.pow(nemadiff,2)), 700), 350), 'Forecast mean', color=color.rgb(245, 0, 0), display=display.none)
MAColor = fEMA > sEMA ? #00ff00 : #ff0000
MA1 = plot(fEMA, title='Fast EMA', color=MAColor)
MA2 = plot(sEMA, title='Slow EMA', color=MAColor)
fill(MA1, MA2, title='Band Filler', color=MAColor) |
twisted SMA strategy [4h] | https://www.tradingview.com/script/vOPO3zto-twisted-SMA-strategy-4h/ | wielkieef | https://www.tradingview.com/u/wielkieef/ | 267 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Wielkieef
//@version=5
strategy(title='twisted SMA strategy [4h] ', overlay=true, pyramiding=1, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, calc_on_order_fills=false, slippage=0, commission_type=strategy.commission.percent, commission_value=0.03)
src = close
Length1 = input.int(4, title=' 1-SMA Lenght', minval=1, group='SMA')
Length2 = input.int(9, title=' 2-SMA Lenght', minval=1, group='SMA')
Length3 = input.int(18, title=' 3-SMA Lenght', minval=1, group='SMA')
SMA1 = ta.sma(close, Length1)
SMA2 = ta.sma(close, Length2)
SMA3 = ta.sma(close, Length3)
Long_ma = SMA1 > SMA2 and SMA2 > SMA3
Short_ma = SMA1 < SMA2 and SMA2 < SMA3
LengthMainSMA = input.int(100, title=' SMA Lenght', minval=1)
SMAas = ta.sma(src, LengthMainSMA)
// Powered Kaufman Adaptive Moving Average by alexgrover (modificated by Wielkieef)
lengthas = input.int(25, title=' Lenght')
sp = input.bool(true, title=' Self Powered')
er = math.abs(ta.change(close, lengthas)) / math.sum(math.abs(ta.change(close)), lengthas)
pow = sp ? 1 / er : 2
per = math.pow(math.abs(ta.change(close, lengthas)) / math.sum(math.abs(ta.change(close)), lengthas), pow)
a = 0.
a := per * src + (1 - per) * nz(a[1], src)
mad4h = 0.
a_f = a / a[1] > .999 and a / a[1] < 1.001
///.
Bar_color = close > SMAas ? color.green : Long_ma ? color.blue : Short_ma ? color.maroon : color.gray
barcolor(color=Bar_color)
long_cond = Long_ma and SMAas < close and not a_f
long_stop = Short_ma
if long_cond
strategy.entry('BUY', strategy.long)
strategy.close_all(when=long_stop)
//by wielkieef |
Bollinger Bands Modified (Stormer) | https://www.tradingview.com/script/aksPa3e7-Bollinger-Bands-Modified-Stormer/ | AugustoErni | https://www.tradingview.com/u/AugustoErni/ | 78 | strategy | 5 | MPL-2.0 | // This close code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AugustoErni
//@version=5
strategy('Bollinger Bands Modified (Stormer)', overlay=true, process_orders_on_close=true, calc_on_every_tick=false, calc_on_order_fills=false, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=10, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.12)
bbL = input.int(20, title='BB Length/Comprimento da Banda de Bollinger', minval=1, step=1, tooltip='Calculate the length of bollinger bands./Calcula o comprimento das bandas de bollinger.')
mult = input.float(0.38, title='BB Standard Deviation/Desvio Padrão da Banda de Bollinger', minval=0.01, step=0.01, tooltip='Calculate the standard deviation of bollinger bands./Calcula o desvio padrão das bandas de bollinger.')
emaL = input.int(80, title='EMA Length/Comprimento da Média Móvel Exponencial', minval=1, step=1, tooltip='Calculate the length of EMA./Calcula o comprimento da EMA.')
highestHighL = input.int(7, title='Highest High Length/Comprimento da Alta Maior', minval=1, step=1, tooltip='Fetches the highest high candle from length input. Use to set stop loss for short position./Obtém a vela de maior alta com base na medida fornecida. Usa para definir o stop loss para uma posição curta.')
lowestLowL = input.int(7, title='Lowest Low Length/Comprimento da Baixa Menor', minval=1, step=1, tooltip='Fetches the lowest low candle from length input. Use to set stop loss for long position./Obter a vela de menor baixa com base na medida fornecida. Usa para definir o stop loss para uma posição longa.')
targetFactor = input.float(1.6, title='Target Take Profit/Objetivo de Lucro Alvo', minval=0.1, step=0.1, tooltip='Calculate the take profit factor when entry position./Calcula o fator do alvo lucro ao entrar na posição.')
emaTrend = input.bool(true, title='Check Trend EMA/Verificar Tendência da Média Móvel Exponencial', tooltip='Use EMA as trend verify for opening position./Usa a EMA como verificação de tendência para abrir posição.')
crossoverCheck = input.bool(false, title='Add Another Crossover Check/Adicionar Mais uma Verificação de Cruzamento Superior', tooltip='This option is to add one more veryfication attempt to check if price is crossover upper bollinger band./Esta opção é para adicionar uma verificação adicional para avaliar se o preço cruza a banda superior da banda de bollinger.')
crossunderCheck = input.bool(false, title='Add Another Crossunder Check/Adicionar Mais uma Verificação de Cruzamento Inferior', tooltip='This option is to add one more veryfication attempt to check if price is crossunder lower bollinger band./Esta opção é para adicionar uma verificação adicional para avaliar se o preço cruza a banda inferior da banda de bollinger.')
insideBarPatternCheck = input.bool(true, title='Show Inside Bar Pattern/Mostrar Padrão de Inside Bar', tooltip='This option is to show possible inside bar pattern./Esta opção é para mostrar um possível padrão de inside bar.')
[middle, upper, lower] = ta.bb(close, bbL, mult)
ema = ta.ema(close, emaL)
highestHigh = ta.highest(high, highestHighL)
lowestLow = ta.lowest(low, lowestLowL)
isCrossover = ta.crossover(close, upper) ? 1 : 0
isCrossunder = ta.crossunder(close, lower) ? 1 : 0
isPrevBarHighGreaterCurBarHigh = high[1] > high ? 1 : 0
isPrevBarLowLesserCurBarLow = low[1] < low ? 1 : 0
isInsideBar = isPrevBarHighGreaterCurBarHigh and isPrevBarLowLesserCurBarLow ? 1 : 0
isBarLong = ((close - open) > 0) ? 1 : 0
isBarShort = ((close - open) < 0) ? 1 : 0
isLongCross = crossoverCheck ? ((isBarLong and not isBarShort) and (open < upper and close > upper)) ? 1 : 0 : isCrossover ? 1 : 0
isShortCross = crossunderCheck ? ((isBarShort and not isBarLong) and (close < lower and open > lower)) ? 1 : 0 : isCrossunder ? 1 : 0
isCandleAboveEma = close > ema ? 1 : 0
isCandleBelowEma = close < ema ? 1 : 0
isLongCondition = emaTrend ? isLongCross and isCandleAboveEma ? 1 : 0 : isLongCross
isShortCondition = emaTrend ? isShortCross and isCandleBelowEma ? 1 : 0 : isShortCross
isPositionNone = strategy.position_size == 0 ? 1 : 0
isPositionLong = strategy.position_size > 0 ? 1 : 0
isPositionShort = strategy.position_size < 0 ? 1 : 0
var float enterLong = 0.0
var float stopLossLong = 0.0
var float targetLong = 0.0
var float enterShort = 0.0
var float stopLossShort = 0.0
var float targetShort = 0.0
var bool isLongEntry = false
var bool isShortEntry = false
if (isPositionNone)
isLongEntry := false
isShortEntry := false
enterLong := 0.0
stopLossLong := 0.0
targetLong := 0.0
enterShort := 0.0
stopLossShort := 0.0
targetShort := 0.0
if (isPositionShort or isPositionNone)
isLongEntry := false
enterLong := 0.0
stopLossLong := 0.0
targetLong := 0.0
if (isPositionLong or isPositionNone)
isShortEntry := false
enterShort := 0.0
stopLossShort := 0.0
targetShort := 0.0
if (isPositionLong and isLongEntry)
isLongEntry := true
isShortEntry := false
enterShort := 0.0
stopLossShort := 0.0
targetShort := 0.0
if (isPositionShort and isShortEntry)
isShortEntry := true
isLongEntry := false
enterLong := 0.0
stopLossLong := 0.0
targetLong := 0.0
if (isLongCondition and not isLongEntry)
isLongEntry := true
enterLong := close
stopLossLong := lowestLow
targetLong := (enterLong + (math.abs(enterLong - stopLossLong) * targetFactor))
alertMessage = '{ "side/lado": "buy", "entry/entrada": ' + str.tostring(enterLong) + ', "stop": ' + str.tostring(stopLossLong) + ', "target/alvo": ' + str.tostring(targetLong) + ' }'
alert(alertMessage)
strategy.entry('Long', strategy.long)
strategy.exit('Exit Long', 'Long', stop=stopLossLong, limit=targetLong)
if (isShortCondition and not isShortEntry)
isShortEntry := true
enterShort := close
stopLossShort := highestHigh
targetShort := (enterShort - (math.abs(enterShort - stopLossShort) * targetFactor))
alertMessage = '{ "side/lado": "sell", "entry/entrada": ' + str.tostring(enterShort) + ', "stop": ' + str.tostring(stopLossShort) + ', "target/alvo": ' + str.tostring(targetShort) + ' }'
alert(alertMessage)
strategy.entry('Short', strategy.short)
strategy.exit('Exit Short', 'Short', stop=stopLossShort, limit=targetShort)
plot(upper, title='Upper Band', color=color.blue)
plot(middle, title='Middle Band', color=color.gray)
plot(lower, title='Lower Band', color=color.blue)
plot(ema, title='EMA', color=color.white)
barcolor(insideBarPatternCheck and isInsideBar and isBarLong ? color.lime : insideBarPatternCheck and isInsideBar and isBarShort ? color.maroon : na, title='Inside Bar Color in Long Bar Long and in Short Bar Short/Cor do Inside Bar em Barra Longa Longa e em Barra Curta Curta')
tablePosition = position.bottom_right
tableColumns = 2
tableRows = 5
tableFrameWidth = 1
tableBorderColor = color.gray
tableBorderWidth = 1
tableInfoTrade = table.new(position=tablePosition, columns=tableColumns, rows=tableRows, frame_width=tableFrameWidth, border_color=tableBorderColor, border_width=tableBorderWidth)
table.cell(table_id=tableInfoTrade, column=0, row=0)
table.cell(table_id=tableInfoTrade, column=1, row=0)
table.cell(table_id=tableInfoTrade, column=0, row=1, text='Entry Side/Lado da Entrada', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=0, row=2, text=isLongEntry ? 'LONG' : isShortEntry ? 'SHORT' : 'NONE/NENHUM', text_color=color.yellow)
table.cell(table_id=tableInfoTrade, column=1, row=1, text='Entry Price/Preço da Entrada', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=1, row=2, text=isLongEntry ? str.tostring(enterLong) : isShortEntry ? str.tostring(enterShort) : 'NONE/NENHUM', text_color=color.blue)
table.cell(table_id=tableInfoTrade, column=0, row=3, text='Take Profit Price/Preço Alvo Lucro', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=0, row=4, text=isLongEntry ? str.tostring(targetLong) : isShortEntry ? str.tostring(targetShort) : 'NONE/NENHUM', text_color=color.green)
table.cell(table_id=tableInfoTrade, column=1, row=3, text='Stop Loss Price/Preço Stop Loss', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=1, row=4, text=isLongEntry ? str.tostring(stopLossLong) : isShortEntry ? str.tostring(stopLossShort) : 'NONE/NENHUM', text_color=color.red) |
Grid Strategy with MA | https://www.tradingview.com/script/ADnS28kf/ | Seungdori_ | https://www.tradingview.com/u/Seungdori_/ | 194 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Seungdori_
//@version=5
strategy("Grid Strategy with MA", overlay=true, initial_capital = 100000, default_qty_type = strategy.cash, default_qty_value = 10000, pyramiding = 10, process_orders_on_close = true, commission_type = strategy.commission.percent, commission_value = 0.04)
//Inputs//
length = input.int(defval = 100, title = 'MA Length', group = 'MA')
MA_Type = input.string("SMA", title="MA Type", options=['EMA', 'HMA', 'LSMA', 'RMA', 'SMA', 'WMA'],group = 'MA')
logic = input.string(defval='ATR', title ='Grid Logic', options = ['ATR', 'Percent'])
band_mult = input.float(2.5, step = 0.1, title = 'Band Multiplier/Percent', group = 'Parameter')
atr_len = input.int(defval=100, title = 'ATR Length', group ='parameter')
//Var//
var int order_cond = 0
var bool order_1 = false
var bool order_2 = false
var bool order_3 = false
var bool order_4 = false
var bool order_5 = false
var bool order_6 = false
var bool order_7 = false
var bool order_8 = false
var bool order_9 = false
var bool order_10 = false
var bool order_11 = false
var bool order_12 = false
var bool order_13 = false
var bool order_14 = false
var bool order_15 = false
/////////////////////
//Region : Function//
/////////////////////
getMA(source ,ma_type, length) =>
maPrice = ta.ema(source, length)
ema = ta.ema(source, length)
sma = ta.sma(source, length)
if ma_type == 'SMA'
maPrice := ta.sma(source, length)
maPrice
if ma_type == 'HMA'
maPrice := ta.hma(source, length)
maPrice
if ma_type == 'WMA'
maPrice := ta.wma(source, length)
maPrice
if ma_type == "RMA"
maPrice := ta.rma(source, length)
if ma_type == "LSMA"
maPrice := ta.linreg(source, length, 0)
maPrice
main_plot = getMA(ohlc4, MA_Type, length)
atr = ta.atr(length)
premium_zone_1 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*1), 5) : ta.ema((main_plot*(1+band_mult*0.01*1)), 5)
premium_zone_2 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*2), 5) : ta.ema((main_plot*(1+band_mult*0.01*2)), 5)
premium_zone_3 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*3), 5) : ta.ema((main_plot*(1+band_mult*0.01*3)), 5)
premium_zone_4 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*4), 5) : ta.ema((main_plot*(1+band_mult*0.01*4)), 5)
premium_zone_5 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*5), 5) : ta.ema((main_plot*(1+band_mult*0.01*5)), 5)
premium_zone_6 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*6), 5) : ta.ema((main_plot*(1+band_mult*0.01*6)), 5)
premium_zone_7 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*7), 5) : ta.ema((main_plot*(1+band_mult*0.01*7)), 5)
premium_zone_8 = logic == 'ATR' ? ta.ema(main_plot + atr*(band_mult*8), 5) : ta.ema((main_plot*(1+band_mult*0.01*8)), 5)
//premium_zone_9 = ta.rma(main_plot + atr*(band_mult*9), 5)
//premium_zone_10 = ta.rma(main_plot + atr*(band_mult*10), 5)
discount_zone_1 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*1), 5) : ta.ema((main_plot*(1-band_mult*0.01*1)), 5)
discount_zone_2 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*2), 5) : ta.ema((main_plot*(1-band_mult*0.01*2)), 5)
discount_zone_3 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*3), 5) : ta.ema((main_plot*(1-band_mult*0.01*3)), 5)
discount_zone_4 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*4), 5) : ta.ema((main_plot*(1-band_mult*0.01*4)), 5)
discount_zone_5 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*5), 5) : ta.ema((main_plot*(1-band_mult*0.01*5)), 5)
discount_zone_6 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*6), 5) : ta.ema((main_plot*(1-band_mult*0.01*6)), 5)
discount_zone_7 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*7), 5) : ta.ema((main_plot*(1-band_mult*0.01*7)), 5)
discount_zone_8 = logic == 'ATR' ? ta.ema(main_plot - atr*(band_mult*8), 5) : ta.ema((main_plot*(1-band_mult*0.01*8)), 5)
//discount_zon_9 = ta.sma(main_plot - atr*(band_mult*9), 5)
//discount_zone_10 =ta.sma( main_plot - atr*(band_mult*10), 5)
//Region End//
////////////////////
// Region : Plots//
///////////////////
dis_low1 = plot(discount_zone_1, color=color.new(color.green, 80))
dis_low2 = plot(discount_zone_2, color=color.new(color.green, 70))
dis_low3 = plot(discount_zone_3, color=color.new(color.green, 60))
dis_low4 = plot(discount_zone_4, color=color.new(color.green, 50))
dis_low5 = plot(discount_zone_5, color=color.new(color.green, 40))
dis_low6 = plot(discount_zone_6, color=color.new(color.green, 30))
dis_low7 = plot(discount_zone_7, color=color.new(color.green, 20))
dis_low8 = plot(discount_zone_8, color=color.new(color.green, 10))
//dis_low9 = plot(discount_zone_9, color=color.new(color.green, 0))
//dis_low10 = plot(discount_zone_10, color=color.new(color.green, 0))
plot(main_plot, color =color.new(color.gray, 10))
pre_up1 = plot(premium_zone_1, color=color.new(color.red, 80))
pre_up2 = plot(premium_zone_2, color=color.new(color.red, 70))
pre_up3 = plot(premium_zone_3, color=color.new(color.red, 60))
pre_up4 = plot(premium_zone_4, color=color.new(color.red, 50))
pre_up5 = plot(premium_zone_5, color=color.new(color.red, 40))
pre_up6 = plot(premium_zone_6, color=color.new(color.red, 30))
pre_up7 = plot(premium_zone_7, color=color.new(color.red, 20))
pre_up8 = plot(premium_zone_8, color=color.new(color.red, 10))
//pre_up9 = plot(premium_zone_9, color=color.new(color.red, 0))
//pre_up10 = plot(premium_zone_10, color=color.new(color.red, 0))
fill(dis_low1, dis_low2, color=color.new(color.green, 95))
fill(dis_low2, dis_low3, color=color.new(color.green, 90))
fill(dis_low3, dis_low4, color=color.new(color.green, 85))
fill(dis_low4, dis_low5, color=color.new(color.green, 80))
fill(dis_low5, dis_low6, color=color.new(color.green, 75))
fill(dis_low6, dis_low7, color=color.new(color.green, 70))
fill(dis_low7, dis_low8, color=color.new(color.green, 65))
//fill(dis_low8, dis_low9, color=color.new(color.green, 60))
//fill(dis_low9, dis_low10, color=color.new(color.green, 55))
fill(pre_up1, pre_up2, color=color.new(color.red, 95))
fill(pre_up2, pre_up3, color=color.new(color.red, 90))
fill(pre_up3, pre_up4, color=color.new(color.red, 85))
fill(pre_up4, pre_up5, color=color.new(color.red, 80))
fill(pre_up5, pre_up6, color=color.new(color.red, 75))
fill(pre_up6, pre_up7, color=color.new(color.red, 70))
fill(pre_up7, pre_up8, color=color.new(color.red, 65))
//fill(pre_up8, pre_up9, color=color.new(color.red, 60))
//fill(pre_up9, pre_up10, color=color.new(color.red, 55))
//Region End//
///////////////////////
//Region : Strategies//
///////////////////////
//Longs//
longCondition1 = ta.crossunder(low, discount_zone_7)
longCondition2 = ta.crossunder(low, discount_zone_6)
longCondition3 = ta.crossunder(low, discount_zone_5)
longCondition4 = ta.crossunder(low, discount_zone_4)
longCondition5 = ta.crossunder(low, discount_zone_3)
longCondition6 = ta.crossunder(low, discount_zone_2)
longCondition7 = ta.crossunder(low, discount_zone_1)
longCondition8 = ta.crossunder(low, main_plot)
longCondition9 = ta.crossunder(low, premium_zone_1)
longCondition10 = ta.crossunder(low, premium_zone_2)
longCondition11 = ta.crossunder(low, premium_zone_3)
longCondition12 = ta.crossunder(low, premium_zone_4)
longCondition13 = ta.crossunder(low, premium_zone_5)
longCondition14 = ta.crossunder(low, premium_zone_6)
longCondition15 = ta.crossunder(low, premium_zone_7)
if (longCondition1) and order_1 == false
strategy.entry("Long1", strategy.long)
order_1 := true
if (longCondition2) and order_2 == false
strategy.entry("Long2", strategy.long)
order_2 := true
if (longCondition3) and order_3 == false
strategy.entry("Long3", strategy.long)
order_3 := true
if (longCondition4) and order_4 == false
strategy.entry("Long4", strategy.long)
order_4 := true
if (longCondition5) and order_5 == false
strategy.entry("Long5", strategy.long)
order_5 := true
if (longCondition6) and order_6 == false
strategy.entry("Long6", strategy.long)
order_6 := true
if (longCondition7) and order_7 == false
strategy.entry("Long7", strategy.long)
order_7 := true
if (longCondition8) and order_8 == false
strategy.entry("Long8", strategy.long)
order_8 := true
if (longCondition9) and order_9 == false
strategy.entry("Long9", strategy.long)
order_9 := true
if (longCondition10) and order_10 == false
strategy.entry("Long10", strategy.long)
order_10 := true
if (longCondition11) and order_11 == false
strategy.entry("Long11", strategy.long)
order_11 := true
if (longCondition12) and order_12 == false
strategy.entry("Long12", strategy.long)
order_12 := true
if (longCondition13) and order_13 == false
strategy.entry("Long13", strategy.long)
order_13 := true
if (longCondition14) and order_14 == false
strategy.entry("Long14", strategy.long)
order_14 := true
if (longCondition15) and order_15 == false
strategy.entry("Long14", strategy.long)
order_15 := true
//Close//
shortCondition1 = ta.crossover(high, discount_zone_6)
shortCondition2 = ta.crossover(high, discount_zone_5)
shortCondition3 = ta.crossover(high, discount_zone_4)
shortCondition4 = ta.crossover(high, discount_zone_3)
shortCondition5 = ta.crossover(high, discount_zone_2)
shortCondition6 = ta.crossover(high, discount_zone_1)
shortCondition7 = ta.crossover(high, main_plot)
shortCondition8 = ta.crossover(high, premium_zone_1)
shortCondition9 = ta.crossover(high, premium_zone_2)
shortCondition10 = ta.crossover(high, premium_zone_3)
shortCondition11 = ta.crossover(high, premium_zone_4)
shortCondition12 = ta.crossover(high, premium_zone_5)
shortCondition13 = ta.crossover(high, premium_zone_6)
shortCondition14 = ta.crossover(high, premium_zone_7)
shortCondition15 = ta.crossover(high, premium_zone_8)
if (shortCondition1) and order_1 == true
strategy.close("Long1")
order_1 := false
if (shortCondition2) and order_2 == true
strategy.close("Long2")
order_2 := false
if (shortCondition3) and order_3 == true
strategy.close("Long3")
order_3 := false
if (shortCondition4) and order_4 == true
strategy.close("Long4")
order_4 := false
if (shortCondition5) and order_5 == true
strategy.close("Long5")
order_5 := false
if (shortCondition6) and order_6 == true
strategy.close("Long6")
order_6 := false
if (shortCondition7) and order_7 == true
strategy.close("Long7")
order_7 := false
if (shortCondition8) and order_8 == true
strategy.close("Long8")
order_8 := false
if (shortCondition9) and order_9 == true
strategy.close("Long9")
order_9 := false
if (shortCondition10) and order_10 == true
strategy.close("Long10")
order_10 := false
if (shortCondition11) and order_11 == true
strategy.close("Long11")
order_11 := false
if (shortCondition12) and order_12 == true
strategy.close("Long12")
order_12 := false
if (shortCondition13) and order_13 == true
strategy.close("Long13")
order_13 := false
if (shortCondition14) and order_14 == true
strategy.close("Long14")
order_14 := false
if (shortCondition15) and order_15 == true
strategy.close("Long15")
order_15 := false
|
Risk to Reward - FIXED SL Backtester | https://www.tradingview.com/script/uWMQ0vwN-Risk-to-Reward-FIXED-SL-Backtester/ | TZack88 | https://www.tradingview.com/u/TZack88/ | 536 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TZack88
//@version=5
strategy(title='RR - FIXED SL Backtester', shorttitle='ZCrypto Backtester',overlay=true,pyramiding=1, initial_capital=10000,
commission_type=strategy.commission.percent, commission_value=0.075,default_qty_value = 33, default_qty_type = strategy.percent_of_equity)
var float slVal = 0.0
float longTP = na
var float SL = na
float BreakevenTP = na
float BreakevenSL = na
var float TPlong = na
deal_start_condition = false
var float long_sl_level = na
color bgray = color.rgb(128, 223, 236, 81)
color WHITE = color.rgb(210, 210, 210)
color red = color.rgb(163, 46, 46, 29)
color white = color.rgb(248, 248, 248, 14)
color olive = color.olive
color blue = color.rgb(23, 43, 77)
color Green = color.rgb(10, 218, 103, 34)
string core = "➞ Main Core Settings 🔸"
string Breakeeven = "➞ Breakeven Settings 🔸"
string SLZ2 = "➞ TP/SL ( Risk System ) 🔸"
string RRS = "➞ Risk to Reward 🔸"
string FTPS = "➞ Fixed TP & SL 🔸"
string BES = "➞ BreakEven Settings 🔸"
float smma = ta.sma(low,14)
string SLZ2TOOL = "Select Which risk system you wanna use ?! Risk to Reward or fixed system"
string RRT = "Your Risk to Reward Ratio ? 2:1 then put 2"
string _tooltip3 = "Select external indicator plot"
string SLSelect = "Select the Stoploss Method"
float external_indicator = input.source(defval=close, title='External indicator ', group=core, tooltip=_tooltip3,inline = "00")
float deal_start_value = input.int(defval=100, title='External Value ', group=core, tooltip="Plot Value",inline = "01")
bool Risktype = input.string('Risk To Reward', title = ' 🌀 Risk Type',group=SLZ2,inline = "000",options = ['Risk To Reward', 'Fixed TP & SL'],tooltip = SLZ2TOOL) == 'Risk To Reward'
float RRTP = input.float(1.5, minval=0,step = 0.1,title="Risk To Reward Ratio",group=RRS,inline = "01",tooltip = RRT)
string stoploss = input.string("ATR SL", title=" ⬇️ Stoploss Type ", options=["ATR SL", "Pivot low", "VWAP SL"], group=RRS,inline = "02",tooltip = SLSelect)
float ATRSL = input.float(1.4," ATR Factor ",step = 0.1,group = RRS,inline = "03",tooltip = "Only used with ATR SL")
int LB = input.int(8, minval=0,title=" Pivot Lookback ",group=RRS,inline = "04",tooltip = "looks for lower low ,Only used with Pivot Low")
float VWAPSL = input.float(2.5," Vwap Multiplier ",step = 0.1,group=RRS,inline = "05",tooltip = "Gets the SMMA value ,Only used with SMMA SL")
float FixedTP = input.float(1.5, minval=0,step = 0.1,title="Fixed TP",group=FTPS,inline = "01") / 100
float FixedSL = input.float(1.5, minval=0,step = 0.1,title="Fixed SL",group=FTPS,inline = "01") / 100
bool breakon = input.bool(true,"BreakEven ?" ,group = BES, inline="06",tooltip = "Breakeven w")
float breakRR = input.float(1.0, " Risk To Reward Ratio",step = 0.1, group = BES, inline="07")
float BEper = input.float(0.1, " Percent Above Entry",step = 0.1, group = BES, inline="08",tooltip="MUST be higher than '0'. This input front loads the new breakeven stop loss so that it is actually in profit.")/100
deal_start_condition := if external_indicator == deal_start_value
true
//-----SL core calculation-----{
x2 = low - ta.rma(ta.tr(true), 14) * ATRSL
stopLong = ta.lowest(low,LB)
vwap = math.sum(ta.vwap(ta.tr(true)),14) * volume
volumz = math.sum(volume,14)
atr_vwap_volume = math.abs(vwap / volumz)
longstoploss = low - atr_vwap_volume * VWAPSL
//}
// Lets get the SL and return it
my_stop() =>
switch stoploss
"ATR SL" => x2
"Pivot low" => stopLong
"SMMA SL" => longstoploss
sl = Risktype ? my_stop() : close * (1 - FixedSL)
// lets set the SL , TP Values
if deal_start_condition and strategy.position_size == 0
slVal:= sl
else
slVal:= slVal
longDiffSL = math.abs(close - slVal)
longTP := deal_start_condition and strategy.position_size == 0 ? Risktype ? close + (RRTP * longDiffSL) : close * (1 + FixedTP) : longTP[1]
// -- Backtest Date ?! {
limit_date_range = input.bool(title='Limit Date Range', defval=true, group='Backtest date range')
start_time = input.time(defval=timestamp('01 Aug 2022 00:00 +0000'), title='Start Time', group='Backtest date range')
end_time = input.time(defval=timestamp('31 Dec 2025 00:00 +0000'), title='End Time', group='Backtest date range')
in_date_range = true
if limit_date_range
in_date_range := time >= start_time and time <= end_time
else
in_date_range := true
//-- }
longCondition = (deal_start_condition== true) and strategy.position_size == 0
//Breakeven
BreakevenTP := longCondition ? close + (breakRR * longDiffSL) : BreakevenTP[1]
BREAKPLOT = strategy.position_size > 0 ? BreakevenTP : na
BreakevenSL := strategy.position_size > 0 ? strategy.position_avg_price * (1 + BEper) :na
long_tp_hit = close >= BreakevenTP or high>= BreakevenTP
long_sl_level := longCondition ? slVal : long_tp_hit ? BreakevenSL: long_sl_level[1]
if (in_date_range and longCondition)
strategy.entry("LONG", strategy.long )
strategy.exit("Long 3","LONG",
limit=longTP,
stop=(breakon ? long_sl_level : slVal),
comment_profit = "TP HIT",
comment_loss = breakon ? "BE Close" : "Loss"
)
// PLOTS
SLplot = strategy.position_size > 0 ? slVal : na
SSL = plot(SLplot, title='LONG STOP LOSS', linewidth=2, style=plot.style_linebr, color=red)
longPlotTP = strategy.position_size > 0 ? longTP : na
TTP = plot(longPlotTP, title='LONG TAKE PROFIT', linewidth=2, style=plot.style_linebr, color=Green)
avg = plot( strategy.position_avg_price, style = plot.style_linebr,color=WHITE )
BREKEVENLINE = strategy.position_size > 0 ? long_sl_level : na
plot(breakon ? BREKEVENLINE : na, 'AVG Price',color=color.white, style=plot.style_linebr,editable = false,linewidth = 2)
fill(TTP, avg, color = color.new(Green,80))
fill(avg, SSL, color =color.new(red,80))
|
CC Trend strategy 2- Downtrend Short | https://www.tradingview.com/script/kKxnTEuC-CC-Trend-strategy-2-Downtrend-Short/ | CheatCode1 | https://www.tradingview.com/u/CheatCode1/ | 80 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CheatCode1
//@version=5
strategy("CC-Trend strategy 2", overlay=true, initial_capital = 10000, commission_type = strategy.commission.percent, commission_value = 0.01, default_qty_type = strategy.percent_of_equity, default_qty_value = 100 )
ema9 = ta.ema(close, 9)
ema21 = ta.ema(close, 21)
ema55 = ta.ema(close, 55)
ema200 = ta.ema(close, 200)
plot(ema200, '22', color.blue, 2)
FibL = input.int(100, 'Fibonacci Length', 1, 500, group = 'Automatic Fibonacci Retracement')
len1 = input.int(1, 'Show Last', 0, 1000, group = 'Automatic Fibonacci Retracement')
len2 = input.int(5, 'Offset Length', 0, 1000, group = 'Automatic Fibonacci Retracement')
highF = ta.highest(ema55 >= ema9 ? ema55:ema9, FibL)
lowF = ta.lowest(ema55 >= ema9 ? ema9:ema55, FibL)
AvgFib = highF - lowF
//Fibonacci Executions
LL2 = highF + .618 * AvgFib
LL1 = highF + .272 * AvgFib
L1 = highF
L236 = highF - 0.236 * AvgFib
L382 = highF - 0.382 * AvgFib
Mid = highF - 0.50 * AvgFib
S382 = lowF + 0.382 * AvgFib
S236 = lowF + 0.236 * AvgFib
S1 = lowF
SS1 = lowF - .272 * AvgFib
SS2 = lowF - .618 * AvgFib
//Fibonacci Plot's
high2FP = plot(LL2, 'Highe2', color.red,offset = len2, show_last = len1, trackprice = true)
high1FP = plot(LL1, 'Highe1', color.red,offset = len2, show_last = len1, trackprice = true)
highFP = plot(highF, 'High', color.red,offset = len2, show_last = len1, trackprice = true)
L236P = plot(L236, "0.764", #ED381C, offset = len2, show_last = len1, trackprice = true )
L382P = plot(L382, "0.618", color.white,offset = len2, show_last = len1, trackprice = true )
MidP = plot(Mid, "0.5", color.orange,offset = len2, show_last = len1, trackprice = true )
S382P = plot(S382, "0.382", color.yellow ,offset = len2, show_last = len1, trackprice = true)
S236P = plot(S236, "0.236", color.lime ,offset = len2, show_last = len1, trackprice = true)
lowFP = plot(lowF, 'Low', color.green,offset = len2, show_last = len1, trackprice = true)
low1FP = plot(SS1, 'Lowe1', color.green,offset = len2, show_last = len1, trackprice = true)
low2FP = plot(SS2, 'Lowe2', color.green,offset = len2, show_last = len1, trackprice = true)
plot(ema9, '22', color.yellow, 2)
plot(ema55, '55', color.aqua, 2)
plot(ema200, '200', color.maroon, 2)
shortCondition = close[1] < highF and ema21 < ema55
if (shortCondition)
strategy.entry("Short", strategy.short)
shorttp = ta.crossover(close, ema200) and strategy.openprofit >= 0
if (shorttp)
strategy.close('Short', 'Short TP', qty_percent = 100)
shortclose2 = close[1] > L236 and not (shortCondition)
if(shortclose2)
strategy.close('Short', 'Short RM', qty_percent = 100) |
Moving Average Rainbow (Stormer) | https://www.tradingview.com/script/AI6DyEXY-Moving-Average-Rainbow-Stormer/ | AugustoErni | https://www.tradingview.com/u/AugustoErni/ | 56 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AugustoErni
//@version=5
strategy('Moving Average Rainbow (Stormer)', overlay=true, process_orders_on_close=true, calc_on_every_tick=false, calc_on_order_fills=false, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=10, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.12)
maType = input.string('EMA', title='Moving Average Type/Tipo de Média Móvel', options=['EMA', 'SMA', 'RMA', 'WMA', 'HMA', 'VWMA'], tooltip='This option is to select the type of Moving Average that the Rainbow will use./Esta opção é para selecionar o tipo de Média Móvel que o Rainbow utilizará.', group='Moving Averages/Médias Móveis')
maLengthFirst = input.int(3, title='MA #1', minval=1, step=1, tooltip='First MA length./Comprimento da primeira MA.', group='Moving Averages/Médias Móveis')
maLengthSecond = input.int(5, title='MA #2', minval=1, step=1, tooltip='Second MA length./Comprimento da segunda MA.', group='Moving Averages/Médias Móveis')
maLengthThird = input.int(8, title='MA #3', minval=1, step=1, tooltip='Third MA length./Comprimento da terceira MA.', group='Moving Averages/Médias Móveis')
maLengthFourth = input.int(13, title='MA #4', minval=1, step=1, tooltip='Fourth MA length./Comprimento da quarta MA.', group='Moving Averages/Médias Móveis')
maLengthFifth = input.int(20, title='MA #5', minval=1, step=1, tooltip='Fifth MA length./Comprimento da quinta MA.', group='Moving Averages/Médias Móveis')
maLengthSixth = input.int(25, title='MA #6', minval=1, step=1, tooltip='Sixth MA length./Comprimento da sexta MA.', group='Moving Averages/Médias Móveis')
maLengthSeventh = input.int(30, title='MA #7', minval=1, step=1, tooltip='Seventh MA length./Comprimento da sétima MA.', group='Moving Averages/Médias Móveis')
maLengthEighth = input.int(35, title='MA #8', minval=1, step=1, tooltip='Eighth MA length./Comprimento da oitava MA.', group='Moving Averages/Médias Móveis')
maLengthNineth = input.int(40, title='MA #9', minval=1, step=1, tooltip='Nineth MA length./Comprimento da nona MA.', group='Moving Averages/Médias Móveis')
maLengthTenth = input.int(45, title='MA #10', minval=1, step=1, tooltip='Tenth MA length./Comprimento da décima MA.', group='Moving Averages/Médias Móveis')
maLengthEleventh = input.int(50, title='MA #11', minval=1, step=1, tooltip='Eleventh MA length./Comprimento da décima primeira MA.', group='Moving Averages/Médias Móveis')
maLengthTwelveth = input.int(55, title='MA #12', minval=1, step=1, tooltip='Twelveth MA length./Comprimento da décima segunda MA.', group='Moving Averages/Médias Móveis')
targetFactor = input.float(1.6, title='Target Take Profit/Objetivo de Lucro Alvo', minval=0.1, step=0.1, tooltip='Calculate the take profit factor when entry position./Calcula o fator do alvo lucro ao entrar na posição.', group='Risk Management/Gerenciamento de Risco')
verifyTurnoverTrend = input.bool(true, title='Verify Turnover Trend/Verificar Tendência de Rotatividade', tooltip='This option checks for a supposedly turnover trend and setup new target (for long is the highest high and for short is the lowest low identified)./Esta opção verifica uma suposta tendência de rotatividade e estabelece um novo objetivo (para long é a máxima mais alta, para short é a mínima mais baixa identificados).', group='Turnover Trend/Rotatividade Tendência')
verifyTurnoverSignal = input.bool(false, title='Verify Turnover Signal/Verificar Sinal de Rotatividade', tooltip='This option checks for a supposedly turnover signal, closing the current position and opening a new one (for long it will close and open a new for short, for short it will close and open a new for long)./Essa opção verifica um sinal de possível reversão, fechando a posição atual e abrindo uma nova (para long fechará e abrirá uma nova para short, para short fechará e abrirá uma nova para long).', group='Turnover Signal/Rotatividade Sinal')
verifyTurnoverSignalPriceExit = input.bool(false, title='Verify Price Exit Turnover Signal/Verificar Saída de Preço Sinal de Rotatividade', tooltip='This option complements "turnover signal" by veryfing the price if profitable before exiting the current position./Esta opção complementa o "sinal de rotatividade" verificando o preço do lucro antes de sair da posição atual.', group='Turnover Signal/Rotatividade Sinal')
mas(maType, maLengthFirst, maLengthSecond, maLengthThird, maLengthFourth, maLengthFifth, maLengthSixth, maLengthSeventh, maLengthEighth, maLengthNineth, maLengthTenth, maLengthEleventh, maLengthTwelveth) =>
if (maType == 'SMA')
[ta.sma(close, maLengthFirst), ta.sma(close, maLengthSecond), ta.sma(close, maLengthThird), ta.sma(close, maLengthFourth), ta.sma(close, maLengthFifth), ta.sma(close, maLengthSixth), ta.sma(close, maLengthSeventh), ta.sma(close, maLengthEighth), ta.sma(close, maLengthNineth), ta.sma(close, maLengthTenth), ta.sma(close, maLengthEleventh), ta.sma(close, maLengthTwelveth)]
else if (maType == 'RMA')
[ta.rma(close, maLengthFirst), ta.rma(close, maLengthSecond), ta.rma(close, maLengthThird), ta.rma(close, maLengthFourth), ta.rma(close, maLengthFifth), ta.rma(close, maLengthSixth), ta.rma(close, maLengthSeventh), ta.rma(close, maLengthEighth), ta.rma(close, maLengthNineth), ta.rma(close, maLengthTenth), ta.rma(close, maLengthEleventh), ta.rma(close, maLengthTwelveth)]
else if (maType == 'WMA')
[ta.wma(close, maLengthFirst), ta.wma(close, maLengthSecond), ta.wma(close, maLengthThird), ta.wma(close, maLengthFourth), ta.wma(close, maLengthFifth), ta.wma(close, maLengthSixth), ta.wma(close, maLengthSeventh), ta.wma(close, maLengthEighth), ta.wma(close, maLengthNineth), ta.wma(close, maLengthTenth), ta.wma(close, maLengthEleventh), ta.wma(close, maLengthTwelveth)]
else if (maType == 'HMA')
[ta.hma(close, maLengthFirst), ta.hma(close, maLengthSecond), ta.hma(close, maLengthThird), ta.hma(close, maLengthFourth), ta.hma(close, maLengthFifth), ta.hma(close, maLengthSixth), ta.hma(close, maLengthSeventh), ta.hma(close, maLengthEighth), ta.hma(close, maLengthNineth), ta.hma(close, maLengthTenth), ta.hma(close, maLengthEleventh), ta.hma(close, maLengthTwelveth)]
else if (maType == 'VWMA')
[ta.vwma(close, maLengthFirst), ta.vwma(close, maLengthSecond), ta.vwma(close, maLengthThird), ta.vwma(close, maLengthFourth), ta.vwma(close, maLengthFifth), ta.vwma(close, maLengthSixth), ta.vwma(close, maLengthSeventh), ta.vwma(close, maLengthEighth), ta.vwma(close, maLengthNineth), ta.vwma(close, maLengthTenth), ta.vwma(close, maLengthEleventh), ta.vwma(close, maLengthTwelveth)]
else
[ta.ema(close, maLengthFirst), ta.ema(close, maLengthSecond), ta.ema(close, maLengthThird), ta.ema(close, maLengthFourth), ta.ema(close, maLengthFifth), ta.ema(close, maLengthSixth), ta.ema(close, maLengthSeventh), ta.ema(close, maLengthEighth), ta.ema(close, maLengthNineth), ta.ema(close, maLengthTenth), ta.ema(close, maLengthEleventh), ta.ema(close, maLengthTwelveth)]
[ma1, ma2, ma3, ma4, ma5, ma6, ma7, ma8, ma9, ma10, ma11, ma12] = mas(maType, maLengthFirst, maLengthSecond, maLengthThird, maLengthFourth, maLengthFifth, maLengthSixth, maLengthSeventh, maLengthEighth, maLengthNineth, maLengthTenth, maLengthEleventh, maLengthTwelveth)
maTouchPriceTrend(ma1, ma2, ma3, ma4, ma5, ma6, ma7, ma8, ma9, ma10, ma11, ma12, trend) =>
var float touchPrice = na
if (trend == 'UPTREND')
if (low <= ma1 and low >= ma2)
touchPrice := ma2
else if (low <= ma2 and low >= ma3)
touchPrice := ma3
else if (low <= ma3 and low >= ma4)
touchPrice := ma4
else if (low <= ma4 and low >= ma5)
touchPrice := ma5
else if (low <= ma5 and low >= ma6)
touchPrice := ma6
else if (low <= ma6 and low >= ma7)
touchPrice := ma7
else if (low <= ma7 and low >= ma8)
touchPrice := ma8
else if (low <= ma8 and low >= ma9)
touchPrice := ma9
else if (low <= ma9 and low >= ma10)
touchPrice := ma10
else if (low <= ma10 and low >= ma11)
touchPrice := ma11
else if (low <= ma11 and low >= ma12)
touchPrice := ma12
else
touchPrice := na
else if (trend == 'DOWNTREND')
if (high >= ma1 and high <= ma2)
touchPrice := ma2
else if (high >= ma2 and high <= ma3)
touchPrice := ma3
else if (high >= ma3 and high <= ma4)
touchPrice := ma4
else if (high >= ma4 and high <= ma5)
touchPrice := ma5
else if (high >= ma5 and high <= ma6)
touchPrice := ma6
else if (high >= ma6 and high <= ma7)
touchPrice := ma7
else if (high >= ma7 and high <= ma8)
touchPrice := ma8
else if (high >= ma8 and high <= ma9)
touchPrice := ma9
else if (high >= ma9 and high <= ma10)
touchPrice := ma10
else if (high >= ma10 and high <= ma11)
touchPrice := ma11
else if (high >= ma11 and high <= ma12)
touchPrice := ma12
else
touchPrice := na
maMean = ((ma1 + ma2 + ma3 + ma4 + ma5 + ma6 + ma7 + ma8 + ma9 + ma10 + ma11 + ma12) / 12)
isMa1To4Above = ma1 > ma2 and ma2 > ma3 and ma3 > ma4 ? 1 : 0
isMa1To4Below = ma1 < ma2 and ma2 < ma3 and ma3 < ma4 ? 1 : 0
isMa5To8Above = ma5 > ma6 and ma6 > ma7 and ma7 > ma8 ? 1 : 0
isMa5To8Below = ma5 < ma6 and ma6 < ma7 and ma7 < ma8 ? 1 : 0
isCloseGreaterMaMean = close > maMean ? 1 : 0
isCloseLesserMaMean = close < maMean ? 1 : 0
isCurHighGreaterPrevHigh = high > high[1] ? 1 : 0
isCurLowLesserPrevLow = low < low[1] ? 1 : 0
isMaUptrend = isCloseGreaterMaMean and isMa5To8Above ? 1 : 0
isMaDowntrend = isCloseLesserMaMean and isMa5To8Below ? 1 : 0
isUptrend = isMaUptrend ? 'UPTREND' : na
isDowntrend = isMaDowntrend ? 'DOWNTREND' : na
curTouchPriceUptrend = maTouchPriceTrend(ma1, ma2, ma3, ma4, ma5, ma6, ma7, ma8, ma9, ma10, ma11, ma12, isUptrend)
prevTouchPriceUptrend = curTouchPriceUptrend[1]
curTouchPriceDowntrend = maTouchPriceTrend(ma1, ma2, ma3, ma4, ma5, ma6, ma7, ma8, ma9, ma10, ma11, ma12, isDowntrend)
prevTouchPriceDowntrend = curTouchPriceDowntrend[1]
isPrevTouchPriceUptrendTouched = prevTouchPriceUptrend > 0.0 or not na(prevTouchPriceUptrend) ? 1 : 0
isPrevTouchPriceDowntrendTouched = prevTouchPriceDowntrend > 0.0 or not na(prevTouchPriceDowntrend) ? 1 : 0
isPrevTouchedPriceUptrend = isPrevTouchPriceUptrendTouched and isMaUptrend ? 1 : 0
isPrevTouchedPriceDowntrend = isPrevTouchPriceDowntrendTouched and isMaDowntrend ? 1 : 0
isPositionFlat = strategy.position_size == 0 ? 1 : 0
var float positionEntryPrice = na
var bool positionIsEntryLong = false
var bool positionIsEntryShort = false
var float longPositionHighestHigh = na
var float shortPositionLowestLow = na
var float stopLossLong = na
var float stopLossShort = na
var float targetLong = na
var float targetShort = na
var bool isTurnoverTrendLongTrigger = na
var bool isTurnoverTrendShortTrigger = na
isPositionLongClose = na(positionEntryPrice) and not positionIsEntryLong ? 1 : 0
isPositionShortClose = na(positionEntryPrice) and not positionIsEntryShort ? 1 : 0
isLongCondition = isMaUptrend and isCurHighGreaterPrevHigh and isPrevTouchedPriceUptrend ? 1 : 0
isShortCondition = isMaDowntrend and isCurLowLesserPrevLow and isPrevTouchedPriceDowntrend ? 1 : 0
longTurnoverExit = verifyTurnoverSignal and verifyTurnoverSignalPriceExit ? (verifyTurnoverSignal and isLongCondition and positionIsEntryShort and close < positionEntryPrice) : verifyTurnoverSignal ? (verifyTurnoverSignal and isLongCondition and positionIsEntryShort) : na
shortTurnoverExit = verifyTurnoverSignal and verifyTurnoverSignalPriceExit ? (verifyTurnoverSignal and isShortCondition and positionIsEntryLong and close > positionEntryPrice) : verifyTurnoverSignal ? (verifyTurnoverSignal and isShortCondition and positionIsEntryLong) : na
if (isPositionFlat)
positionEntryPrice := na
positionIsEntryLong := false
positionIsEntryShort := false
stopLossLong := na
targetLong := na
stopLossShort := na
targetShort := na
isTurnoverTrendLongTrigger := na
isTurnoverTrendShortTrigger := na
if ((isLongCondition and isPositionLongClose) or longTurnoverExit)
positionEntryPrice := close
positionIsEntryLong := true
positionIsEntryShort := false
longPositionHighestHigh := na
shortPositionLowestLow := na
isTurnoverTrendLongTrigger := na
isTurnoverTrendShortTrigger := na
stopLossLong := prevTouchPriceUptrend
if (isCurLowLesserPrevLow)
curLowToucedPrice = na(curTouchPriceUptrend) ? low : curTouchPriceUptrend
stopLossLong := na(curTouchPriceUptrend) ? ((stopLossLong + curLowToucedPrice) / 2) : curLowToucedPrice
targetLong := (positionEntryPrice + (math.abs(positionEntryPrice - stopLossLong) * targetFactor))
if (targetLong > 0 and stopLossLong > 0)
alertMessage = '{ "side/lado": "buy", "entry/entrada": ' + str.tostring(positionEntryPrice) + ', "stop": ' + str.tostring(stopLossLong) + ', "target/alvo": ' + str.tostring(targetLong) + ' }'
alert(alertMessage)
strategy.entry('Long', strategy.long)
strategy.exit('Exit Long', 'Long', stop=stopLossLong, limit=targetLong)
if ((isShortCondition and isPositionShortClose) or shortTurnoverExit)
positionEntryPrice := close
positionIsEntryLong := false
positionIsEntryShort := true
longPositionHighestHigh := na
shortPositionLowestLow := na
isTurnoverTrendLongTrigger := na
isTurnoverTrendShortTrigger := na
stopLossShort := prevTouchPriceDowntrend
if (isCurHighGreaterPrevHigh)
curHighToucedPrice = na(curTouchPriceDowntrend) ? high : curTouchPriceDowntrend
stopLossShort := na(curTouchPriceDowntrend) ? ((stopLossShort + curHighToucedPrice) / 2) : curHighToucedPrice
targetShort := (positionEntryPrice - (math.abs(positionEntryPrice - stopLossShort) * targetFactor))
if (targetShort > 0 and stopLossShort > 0)
alertMessage = '{ "side/lado": "sell", "entry/entrada": ' + str.tostring(positionEntryPrice) + ', "stop": ' + str.tostring(stopLossShort) + ', "target/alvo": ' + str.tostring(targetShort) + ' }'
alert(alertMessage)
strategy.entry('Short', strategy.short)
strategy.exit('Exit Short', 'Short', stop=stopLossShort, limit=targetShort)
if (verifyTurnoverTrend and positionIsEntryLong)
curHighestHigh = high
if (curHighestHigh > longPositionHighestHigh or na(longPositionHighestHigh))
longPositionHighestHigh := curHighestHigh
if (isMa1To4Below and isCloseLesserMaMean and longPositionHighestHigh > positionEntryPrice)
isTurnoverTrendLongTrigger := true
alertMessage = '{ "side/lado": "buy", "stop": ' + str.tostring(stopLossLong) + ', "target/alvo": ' + str.tostring(longPositionHighestHigh) + ', "new setup/nova definição": ' + str.tostring(isTurnoverTrendLongTrigger) + ' }'
alert(alertMessage)
strategy.exit('Exit Long', 'Long', stop=stopLossLong, limit=longPositionHighestHigh)
if (verifyTurnoverTrend and positionIsEntryShort)
curLowestLow = low
if (curLowestLow < shortPositionLowestLow or na(shortPositionLowestLow))
shortPositionLowestLow := curLowestLow
if (isMa1To4Above and isCloseGreaterMaMean and shortPositionLowestLow < positionEntryPrice)
isTurnoverTrendShortTrigger := true
alertMessage = '{ "side/lado": "sell", "stop": ' + str.tostring(stopLossShort) + ', "target/alvo": ' + str.tostring(shortPositionLowestLow) + ', "new setup/nova definição": ' + str.tostring(isTurnoverTrendShortTrigger) + ' }'
alert(alertMessage)
strategy.exit('Exit Short', 'Short', stop=stopLossShort, limit=shortPositionLowestLow)
plot(ma1, title='1st Moving Average', color=color.rgb(240, 240, 240))
plot(ma2, title='2nd Moving Average', color=color.rgb(220, 220, 220))
plot(ma3, title='3rd Moving Average', color=color.rgb(200, 200, 200))
plot(ma4, title='4th Moving Average', color=color.rgb(180, 180, 180))
plot(ma5, title='5th Moving Average', color=color.rgb(160, 160, 160))
plot(ma6, title='6th Moving Average', color=color.rgb(140, 140, 140))
plot(ma7, title='7th Moving Average', color=color.rgb(120, 120, 120))
plot(ma8, title='8th Moving Average', color=color.rgb(100, 120, 120))
plot(ma9, title='9th Moving Average', color=color.rgb(80, 120, 120))
plot(ma10, title='10th Moving Average', color=color.rgb(60, 120, 120))
plot(ma11, title='11th Moving Average', color=color.rgb(40, 120, 120))
plot(ma12, title='12th Moving Average', color=color.rgb(20, 120, 120))
tablePosition = position.bottom_right
tableColumns = 2
tableRows = 7
tableFrameWidth = 1
tableBorderColor = color.gray
tableBorderWidth = 1
tableInfoTrade = table.new(position=tablePosition, columns=tableColumns, rows=tableRows, frame_width=tableFrameWidth, border_color=tableBorderColor, border_width=tableBorderWidth)
table.cell(table_id=tableInfoTrade, column=0, row=0)
table.cell(table_id=tableInfoTrade, column=1, row=0)
table.cell(table_id=tableInfoTrade, column=0, row=1, text='Entry Side/Lado da Entrada', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=0, row=2, text=positionIsEntryLong ? 'LONG' : positionIsEntryShort ? 'SHORT' : 'NONE/NENHUM', text_color=color.yellow)
table.cell(table_id=tableInfoTrade, column=1, row=1, text='Entry Price/Preço da Entrada', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=1, row=2, text=not na(positionEntryPrice) ? str.tostring(positionEntryPrice) : 'NONE/NENHUM', text_color=color.blue)
table.cell(table_id=tableInfoTrade, column=0, row=3, text='Take Profit Price/Preço Alvo Lucro', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=0, row=4, text=positionIsEntryLong ? str.tostring(targetLong) : positionIsEntryShort ? str.tostring(targetShort) : 'NONE/NENHUM', text_color=color.green)
table.cell(table_id=tableInfoTrade, column=1, row=3, text='Stop Loss Price/Preço Stop Loss', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=1, row=4, text=positionIsEntryLong ? str.tostring(stopLossLong) : positionIsEntryShort ? str.tostring(stopLossShort) : 'NONE/NENHUM', text_color=color.red)
table.cell(table_id=tableInfoTrade, column=0, row=5, text='New Target/Novo Alvo', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=0, row=6, text=verifyTurnoverTrend and positionIsEntryLong and isTurnoverTrendLongTrigger ? str.tostring(longPositionHighestHigh) : verifyTurnoverTrend and positionIsEntryShort and isTurnoverTrendShortTrigger ? str.tostring(shortPositionLowestLow) : 'NONE/NENHUM', text_color=color.green)
table.cell(table_id=tableInfoTrade, column=1, row=5, text='Possible Market Turnover/Possível Virada do Mercado', text_color=color.white)
table.cell(table_id=tableInfoTrade, column=1, row=6, text=verifyTurnoverTrend and positionIsEntryLong and isTurnoverTrendLongTrigger ? 'YES/SIM (Possible long going short/Possível long indo short)' : verifyTurnoverTrend and positionIsEntryShort and isTurnoverTrendShortTrigger ? 'YES/SIM (Possible short going long/Possível short indo long)' : 'NONE/NENHUM', text_color=color.red)
|
Volatility Capture RSI-Bollinger - Strategy [presentTrading] | https://www.tradingview.com/script/Xr2xrNAY-Volatility-Capture-RSI-Bollinger-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 131 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
// Define the strategy settings
strategy('Volatility Capture RSI-Bollinger - Strategy [presentTrading]', overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage=1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 15, initial_capital= 10000)
// Define the input parameters for the indicator
priceSource = input.source(title='Source', defval=hlc3, group='presentBollingBand') // The price source to use
lengthParam = input.int(50, 'lengthParam', minval=1, group='presentBollingBand') // The length of the moving average
multiplier = input.float(2.7183, 'Multiplier', minval=0.1, step=.1, group='presentBollingBand') // The multiplier for the ATR
useRSI = input.bool(true, 'Use RSI for signals', group='presentBollingBand') // Boolean input to decide whether to use RSI for signals
rsiPeriod = input.int(10, 'RSI Period', minval=1, group='presentBollingBand') // The period for the RSI calculation
smaPeriod = input.int(5, 'SMA Period', minval=1, group='presentBollingBand') // The period for the SMA calculation
boughtRange = input.float(55, 'Bought Range Level', minval=1, group='presentBollingBand') // The level for the bought range
soldRange = input.float(50, 'Sold Range Level', minval=1, group='presentBollingBand') // The level for the sold range
// Add a parameter for choosing Long or Short
tradeDirection = input.string("Both", "Trade Direction", options=["Long", "Short", "Both"], group='presentBollingBand') // Dropdown input for trade direction
// Calculate the bollingerBand
barIndex = bar_index // The current bar index
upperBollingerBand = ta.sma(high, lengthParam) + ta.stdev(high, lengthParam) * multiplier // Calculate the upper Bollinger Band
lowerBollingerBand = ta.sma(low, lengthParam) - ta.stdev(low, lengthParam) * multiplier // Calculate the lower Bollinger Band
var float presentBollingBand = na // Initialize the presentBollingBand variable
crossCount = 0 // Initialize the crossCount variable
// Calculate the buy and sell signals
longSignal1 = ta.crossover(priceSource, presentBollingBand) // Calculate the long signal
shortSignal1 = ta.crossunder(priceSource, presentBollingBand) // Calculate the short signal
// Calculate the RSI
rsiValue = ta.rsi(priceSource, rsiPeriod) // Calculate the RSI value
rsiSmaValue = ta.sma(rsiValue, smaPeriod) // Calculate the SMA of the RSI value
// Calculate the buy and sell signals
longSignal2 = rsiSmaValue > boughtRange // Calculate the long signal based on the RSI SMA
shortSignal2 = rsiSmaValue < soldRange // Calculate the short signal based on the RSI SMA
presentBollingBand := na(lowerBollingerBand) or na(upperBollingerBand)?0.0 : close>presentBollingBand?math.max(presentBollingBand,lowerBollingerBand) : close<presentBollingBand?math.min(presentBollingBand,upperBollingerBand) : 0.0
if (tradeDirection == "Long" or tradeDirection == "Both") and longSignal1 and (useRSI ? longSignal2 : true) // Use RSI for signals if useRSI is true
presentBollingBand := lowerBollingerBand // If the trade direction is "Long" or "Both", and the long signal is true, and either useRSI is false or the long signal based on RSI is true, then assign the lowerBollingerBand to the presentBollingBand.
strategy.entry("Long", strategy.long) // Enter a long position.
if (tradeDirection == "Short" or tradeDirection == "Both") and shortSignal1 and (useRSI ? shortSignal2 : true) // Use RSI for signals if useRSI is true
presentBollingBand := upperBollingerBand // If the trade direction is "Short" or "Both", and the short signal is true, and either useRSI is false or the short signal based on RSI is true, then assign the upperBollingerBand to the presentBollingBand.
strategy.entry("Short", strategy.short) // Enter a short position.
// Exit condition
if (strategy.position_size > 0 and ta.crossunder(close, presentBollingBand)) // If the strategy has a long position and the close price crosses under the presentBollingBand, then close the long position.
strategy.close("Long")
if (strategy.position_size < 0 and ta.crossover(close, presentBollingBand)) // If the strategy has a short position and the close price crosses over the presentBollingBand, then close the short position.
strategy.close("Short")
//~~ Plot
plot(presentBollingBand,"presentBollingBand", color=color.blue) // Plot the presentBollingBand on the chart. |
PresentTrend - Strategy [presentTrading] | https://www.tradingview.com/script/TIpnJpU8-PresentTrend-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 188 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
// Define the strategy settings
strategy('PresentTrend - Strategy [presentTrading]' , overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
// Define the input parameters
priceSource = input.source(title='Source', defval=hlc3, group='PresentTrend') // The price source to use
lengthParam = input.int(title='Length', defval=14, group='PresentTrend') // The length of the moving average
multiplier = input.float(title='Multiplier', defval=1.618, step=0.1, group='PresentTrend') // The multiplier for the ATR
indicatorChoice = input.bool(title='Whether to use RSI or MFI', defval=false, group='PresentTrend') // Whether to use RSI or MFI
// Add a parameter for choosing Long or Short
tradeDirection = input.string(title="Trade Direction", defval="Both", options=["Long", "Short", "Both"])
// Calculate the ATR and the upT and downT values
ATR = ta.sma(ta.tr, lengthParam)
upperThreshold = low - ATR * multiplier
lowerThreshold = high + ATR * multiplier
// Initialize the PresentTrend indicator
PresentTrend = 0.0
// Calculate the PresentTrend indicator
PresentTrend := (indicatorChoice ? ta.rsi(priceSource, lengthParam) >= 50 : ta.mfi(hlc3, lengthParam) >= 50) ? upperThreshold < nz(PresentTrend[1]) ? nz(PresentTrend[1]) : upperThreshold : lowerThreshold > nz(PresentTrend[1]) ? nz(PresentTrend[1]) : lowerThreshold
// Calculate the buy and sell signals
longSignal = ta.crossover(PresentTrend, PresentTrend[2])
shortSignal = ta.crossunder(PresentTrend, PresentTrend[2])
// Calculate the number of bars since the last buy and sell signals
barsSinceBuy = ta.barssince(longSignal)
barsSinceSell = ta.barssince(shortSignal)
previousBuy = ta.barssince(longSignal[1])
previousSell = ta.barssince(shortSignal[1])
// Initialize the direction variable
trendDirection = 0
// Calculate the direction of the trend
trendDirection := longSignal and previousBuy > barsSinceSell ? 1 : shortSignal and previousSell > barsSinceBuy ? -1 : trendDirection[1]
// Check the trade direction parameter before entering a trade
if (trendDirection == 1 and (tradeDirection == "Long" or tradeDirection == "Both"))
strategy.entry("Buy", strategy.long)
if (trendDirection == -1 and (tradeDirection == "Short" or tradeDirection == "Both"))
strategy.entry("Sell", strategy.short)
// Add a stop mechanism when the tradeDirection is one-sided
if (tradeDirection == "Long" and trendDirection == -1)
strategy.close("Buy")
if (tradeDirection == "Short" and trendDirection == 1)
strategy.close("Sell")
// Visualization
plot(PresentTrend, color=color.blue, title="PresentTrend")
plotshape(series=longSignal, location=location.belowbar, color=color.green, style=shape.labelup, title="Buy Signal")
plotshape(series=shortSignal, location=location.abovebar, color=color.red, style=shape.labeldown, title="Sell Signal")
|
PercentX Trend Follower [Trendoscope] | https://www.tradingview.com/script/WKgRAD0V-PercentX-Trend-Follower-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 722 | strategy | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
strategy('PercentX Trend Follower [Trendoscope]', shorttitle='pX-TF [Trendoscope]',
overlay=false, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=10,
commission_type=strategy.commission.percent, pyramiding=4, commission_value=0.01, explicit_plot_zorder=true,
margin_long=100.0, margin_short=100.0, max_bars_back=5000)
import HeWhoMustNotBeNamed/ta/1 as eta
bandType = input.string('Keltner Channel', '', ['Keltner Channel', 'Bollinger Bands'], tooltip = 'Select the band type', group='Band', inline= 'ma', display = display.none)
maType = input.string(title='', defval='hma', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma'], group='Band', inline='ma', display = display.none)
maLength = input.int(40, '', minval=5, step=10, group='Band', inline='ma', display = display.none)
useTrueRange = input.bool(true, 'Use True Range (KC)', tooltip = 'Use true range - applicable only for Keltner Channel', group='Band', display = display.none)
rangeMethod = input.string('highlow', title='', group='Range Calculation',
options=['highlow', 'sma', 'ema', 'rma', 'hma', 'wma', 'vwma', 'swma'], inline='l', display = display.none)
loopbackPeriod = input.int(80, step=10, title='', group='Range Calculation', inline="l", display = display.none)
loopbackPeriodLast = input.int(20, step=10, title='', group='Range Calculation', inline='l', display = display.none, tooltip = 'Range Calculation method, length and range length')
stickyBorders = input.bool(true, title='Sticky Borders', group='Range Calculation', inline="b", display = display.none)
outerRangeMethod = input.string('highlow', title='', group='Outer Range Calculation',
options=['highlow', 'sma', 'ema', 'rma', 'hma', 'wma', 'vwma', 'swma'], inline='l', display = display.none)
outerLoopback = input.int(80, step=10, title='', group='Outer Range Calculation', inline="l", display = display.none,
tooltip='Method and length for calculating outer range. Outer range is extreme of oversold and overbought ranges')
doubleSided = input.bool(true, 'Double Sided', group='Trade', display = display.none)
useInitialStop = input.bool(true, 'Enable Stop', group = 'Trade', inline='s', display = display.none)
atrLength = input.int(14, '', 1, step = 10, group = 'Trade', inline='s', display = display.none)
trendMultiplier = input.int(1, '', 1, 10, 1, group = 'Trade', inline='s', display = display.none)
reverseMultiplier = input.int(3, '', 1, 10, 1, group = 'Trade', inline='s', tooltip = 'Enable Stop and Configure ATR length, Trend and reverse Multiplier for the stop', display = display.none)
tradeDirection = input.string(strategy.direction.all, 'Direction', [strategy.direction.long, strategy.direction.short, strategy.direction.all], display = display.none)
strategy.risk.allow_entry_in(tradeDirection)
[bbMiddle, bbUpper, bbLower] = eta.bb(close, maType, maLength, 0.01, false)
[kcMiddle, kcUpper, kcLower] = eta.kc(close, maType, maLength, 0.01, useTrueRange, false)
middle = bandType == 'Bollinger Bands'? bbMiddle : kcMiddle
upper = bandType == 'Bollinger Bands'? bbUpper : kcUpper
lower = bandType == 'Bollinger Bands'? bbLower : kcLower
distance = close - middle
oscillator = distance/(middle-lower)
offset = 0
[overbought, oversold] = eta.oscillatorRange(oscillator, rangeMethod, loopbackPeriod, loopbackPeriodLast, stickyBorders)
oversold := oversold + offset
overbought := overbought - offset
var upOverflow = false
var downOverflow = false
highOverboughtMa = eta.ma(overbought, outerRangeMethod, outerLoopback)
highestOverbought = ta.highest(overbought, outerLoopback)
lowOversoldMa = eta.ma(oversold, outerRangeMethod, outerLoopback)
lowestOversold = ta.lowest(oversold, outerLoopback)
upperRange = outerRangeMethod == 'highlow'? highestOverbought: highOverboughtMa
lowerRange = outerRangeMethod == 'highlow'? lowestOversold : lowOversoldMa
longSignal = ta.crossover(oscillator, upperRange)
shortSignal = ta.crossunder(oscillator, lowerRange)
upOverflow := longSignal or (upOverflow and oscillator > overbought)
downOverflow := shortSignal or (downOverflow and oscillator < oversold)
transparency = 60
STATE = plot(oscillator, title='PercentX Oscillator', color=color.new(color.blue, upOverflow or downOverflow? 0 : transparency), style=plot.style_linebr)
lowerBandFill = plot(downOverflow? oversold : na, "Lower Overflow", color= color.orange, style=plot.style_linebr)
fill(STATE, lowerBandFill, color=color.orange)
lowerBand = plot(oversold, "Lower", color= color.new(color.orange, downOverflow? 0 : transparency), style=plot.style_linebr)
llowerBand = plot(lowerRange, "Extreme Lower", color= color.new(color.red, downOverflow? 0 : transparency), style=plot.style_linebr)
upperBandFill = plot(upOverflow? overbought : na, "Upper Overflow", color= color.lime, style=plot.style_linebr)
fill(STATE, upperBandFill, color=color.lime)
upperBand = plot(overbought, "Upper", color= color.new(color.lime, upOverflow? 0 : transparency), style=plot.style_linebr)
uupperBand = plot(upperRange, "Extreme Upper", color= color.new(color.green, upOverflow? 0 : transparency), style=plot.style_linebr)
atr = ta.atr(atrLength)
longtrade(multiplier, stopMultiplier)=>
strategy.entry('Long', strategy.long, oca_name='oca', oca_type=strategy.oca.none, stop = high + atr*multiplier, comment='Long - New Position')
if(useInitialStop)
strategy.exit('ExitLong', 'Long', stop = low - atr*stopMultiplier)
shorttrade(multiplier, stopMultiplier)=>
strategy.entry('Short', strategy.short, oca_name='oca', oca_type=strategy.oca.none, stop = low - atr*multiplier, comment='Short - New Position')
if(useInitialStop)
strategy.exit('ExitShort', 'Short', stop = high + atr*stopMultiplier)
if(longSignal)
longtrade(trendMultiplier, reverseMultiplier)
if(doubleSided)
shorttrade(reverseMultiplier, trendMultiplier)
if(shortSignal)
shorttrade(trendMultiplier, reverseMultiplier)
if(doubleSided)
longtrade(reverseMultiplier, trendMultiplier) |
Previous Day High Low Strategy only for Long | https://www.tradingview.com/script/mg1Qa51D-Previous-Day-High-Low-Strategy-only-for-Long/ | mangeshabhang19 | https://www.tradingview.com/u/mangeshabhang19/ | 110 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mangeshabhang19
//@version=5
strategy("Previous Day High Low Strategy only for Long", overlay=true, margin_long=100, margin_short=0, calc_on_every_tick=true, default_qty_value = 50)
[HH, LL] = request.security(syminfo.tickerid, '1D', [high, low], barmerge.gaps_off, barmerge.lookahead_off)
OpenTime = timestamp(year, month, dayofmonth , 09, 30)
CloseTime = timestamp(year, month, dayofmonth, 15, 10)
ExitTime = timestamp(year, month, dayofmonth, 15, 15)
TradeTime = time >= OpenTime and time <= CloseTime
UW = open > close ? high - open : high - close
LW = open > close ? close - low : open - low
Body = open > close ? open - close : close - open
UWP = (UW / (LW + UW)) * 100
LWP = (LW / (LW + UW)) * 100
longCondition = ta.crossover(close, HH)
longCondition := longCondition or ta.crossover(close, LL)
longCondition := longCondition //and high == close
plot(HH, color=color.red,linewidth = 1)
plot(LL, color=color.red,linewidth = 1)
//============================================= Market Strength ============================
LWadxlength = input(9, title='ADX period')
LWdilength = input(11, title='DMI Length')
dirmov(len) =>
up = ta.change(high)
down = -ta.change(low)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(up > down and up > 0 ? up : 0, len) / truerange)
minus = fixnan(100 * ta.rma(down > up and down > 0 ? down : 0, len) / truerange)
[plus, minus]
adx(LWdilength, LWadxlength) =>
[plus, minus] = dirmov(LWdilength)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), LWadxlength)
[adx, plus, minus]
[ADX, up, down] = adx(LWdilength, LWadxlength)
LWADX = (ADX - 15) * 2.5
adxcolor = up > down ? color.green : color.red
strength_up = LWADX > 11 and up > down and LWADX > ta.highest(LWADX[1],4)
longCondition := longCondition and strength_up // and close>= high-input(15,'LW Size')
plotshape(longCondition, title="Buy Signal", location=location.belowbar, color=color.green, textcolor = color.white, style=shape.labelup, text="BUY")
//========================== POSITIONS ================================
float MaxProfit = input(150.00,"Max Profit")
float T1 = MaxProfit * 0.3
float T2 = MaxProfit * 0.5
float T3 = MaxProfit * 0.8
float SL = na
float CP = na
float EP = na
if not na(EP[1])
EP := EP[1]
if not na(CP[1])
CP := CP[1]
if not na(SL[1])
SL := SL[1]
// Execute strategy on tick
if (barstate.isconfirmed)
if (strategy.position_size == 0)
EP := na
CP := na
SL := na
if (longCondition and TradeTime)
strategy.entry("Long", strategy.long)
if (strategy.position_size > 0)
if na(EP[1])
EP := strategy.position_avg_price
CP := EP
SL := math.min(input(15,"Max SL"), MaxProfit * 0.4)
if (high >= EP + T1) and CP < EP + T1
CP := EP + T1
SL := CP-EP//SL * 0.8
if (high >= EP + T2) and CP < EP + T2
CP := EP + T2
SL := CP-EP-T1//SL * 0.8
if (high >= EP + T3) and CP < EP + T3
CP := EP + MaxProfit
SL := CP-EP-T2//SL * 0.8
strategy.exit("Exit Long", "Long", limit = EP + MaxProfit, stop =CP-SL)
if (strategy.position_size > 0 and time > CloseTime)
strategy.close("Long")
//PLOT
plot(CP, title="Stop Loss", color=color.yellow, linewidth=1, style = plot.style_linebr)
plot(EP, title="Stop Loss", color=color.white, linewidth=1, style = plot.style_linebr)
plot(CP - SL, title="Stop Loss", color=color.red, linewidth=1, style = plot.style_linebr)
plot(EP + T1, title="Target 1", color=color.blue, linewidth=1, style = plot.style_linebr)
plot(EP + T2, title="Target 2", color=color.blue, linewidth=1, style = plot.style_linebr)
plot(EP + T3, title="Target 3", color=color.blue, linewidth=1, style = plot.style_linebr)
plot(EP + MaxProfit, title="Max Profit", color=color.green, linewidth=1, style = plot.style_linebr) |
Wyckoff Range Strategy | https://www.tradingview.com/script/vQSBf9rh-Wyckoff-Range-Strategy/ | deperp | https://www.tradingview.com/u/deperp/ | 302 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © deperp
//@version=5
strategy("Wyckoff Range Strategy by deperp", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent)
// Input Variables
AccumulationLength = input(32, "Accumulation")
DistributionLength = input(35, "Distribution")
SpringLength = input(10, "Spring")
UpthrustLength = input(20, "Upthrust")
stopPercentage = input(10, "Stop Percentage")
// Accumulation Phase
isAccumulation = ta.crossover(close, ta.sma(close, AccumulationLength))
// Distribution Phase
isDistribution = ta.crossunder(close, ta.sma(close, DistributionLength))
// Spring and Upthrust
isSpring = ta.crossover(low, ta.sma(low, SpringLength))
isUpthrust = ta.crossunder(high, ta.sma(high, UpthrustLength))
// Strategy Conditions
enterLong = isAccumulation and isSpring
enterShort = isDistribution and isUpthrust
// Entry and Exit Conditions
if (enterLong)
strategy.close("Short")
strategy.entry("Long", strategy.long, comment="Enter Long")
alert("Enter Long Position")
if (enterShort)
strategy.close("Long")
strategy.entry("Short", strategy.short, comment="Enter Short")
alert("Enter Short Position")
// Stop Loss
stopLossLevelLong = close * (1 - stopPercentage / 100)
stopLossLevelShort = close * (1 + stopPercentage / 100)
strategy.exit("Stop Loss Long", "Long", stop=stopLossLevelLong)
strategy.exit("Stop Loss Short", "Short", stop=stopLossLevelShort)
// Plotting Wyckoff Schematics
plotshape(isAccumulation, title="Accumulation Phase", location=location.belowbar, color=color.green, style=shape.labelup, text="Accumulation")
plotshape(isDistribution, title="Distribution Phase", location=location.abovebar, color=color.red, style=shape.labeldown, text="Distribution")
plotshape(isSpring, title="Spring", location=location.belowbar, color=color.blue, style=shape.triangleup)
plotshape(isUpthrust, title="Upthrust", location=location.abovebar, color=color.orange, style=shape.triangledown)
|
Range Breaker | https://www.tradingview.com/script/9WNF3S0S-Range-Breaker/ | deperp | https://www.tradingview.com/u/deperp/ | 125 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © deperp
//@version=5
strategy("Range Breaker", overlay=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent, commission_value=0.07, pyramiding=0)
// Backtest Time Period
useDateFilter = input.bool(true, title="Begin Backtest at Start Date",
group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2020"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
inTradeWindow = not useDateFilter or time >= backtestStartDate
swingLookback = input.int(20, title="Swing Lookback", minval=3)
stopTargetPercent = input.float(5, title="Stop Target Percentage", step=0.1)
// Calculate lockback swings
swings(len) =>
var highIndex = bar_index
var lowIndex = bar_index
var swingHigh = float(na)
var swingLow = float(na)
upper = ta.highest(len)
lower = ta.lowest(len)
if high[len] > upper
highIndex := bar_index[len]
swingHigh := high[len]
if low[len] < lower
lowIndex := bar_index[len]
swingLow := low[len]
[swingHigh, swingLow, highIndex, lowIndex]
// Strategy logic
[swingHigh, swingLow, highIndex, lowIndex] = swings(swingLookback)
longCondition = inTradeWindow and (ta.crossover(close, swingHigh))
shortCondition = inTradeWindow and (ta.crossunder(close, swingLow))
if longCondition
strategy.entry("Long", strategy.long)
if shortCondition
strategy.entry("Short", strategy.short)
longStopTarget = close * (1 + stopTargetPercent / 100)
shortStopTarget = close * (1 - stopTargetPercent / 100)
strategy.exit("Long Stop Target", "Long", limit=longStopTarget)
strategy.exit("Short Stop Target", "Short", limit=shortStopTarget)
// Plot break lines
line.new(x1=highIndex, y1=swingHigh, x2=bar_index, y2=swingHigh, color=color.rgb(255, 82, 82, 48), width=3, xloc=xloc.bar_index, extend=extend.right)
line.new(x1=lowIndex, y1=swingLow, x2=bar_index, y2=swingLow, color=color.rgb(76, 175, 79, 47), width=3, xloc=xloc.bar_index, extend=extend.right)
// Alert conditions for entry and exit
longEntryCondition = inTradeWindow and (ta.crossover(close, swingHigh))
shortEntryCondition = inTradeWindow and (ta.crossunder(close, swingLow))
longExitCondition = close >= longStopTarget
shortExitCondition = close <= shortStopTarget
alertcondition(longEntryCondition, title="Long Entry Alert", message="Enter Long Position")
alertcondition(shortEntryCondition, title="Short Entry Alert", message="Enter Short Position")
alertcondition(longExitCondition, title="Long Exit Alert", message="Exit Long Position")
alertcondition(shortExitCondition, title="Short Exit Alert", message="Exit Short Position") |
Hobbiecode - Five Day Low RSI Strategy | https://www.tradingview.com/script/PmJa1OXL/ | hobbiecode | https://www.tradingview.com/u/hobbiecode/ | 84 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hobbiecode
// If today’s close is below yesterday’s five-day low, go long at the close.
// Sell at the close when the two-day RSI closes above 50.
// There is a time stop of five days if the sell criterium is not triggered.
//@version=5
strategy("Hobbiecode - Five Day Low RSI Strategy", overlay=true)
// RSI parameters
rsi_period = 2
rsi_upper = 50
// Calculate RSI
rsi_val = ta.rsi(close, rsi_period)
// Check if today's close is below yesterday's 5 day low
conditionEntry = close < ta.lowest(low[1], 5) and strategy.position_size < 1
if (conditionEntry)
strategy.entry("Buy", strategy.long)
// Check if RSI closes above 50
if (strategy.position_size > 0 and rsi_val > rsi_upper)
strategy.close("Buy")
// If position held for more than 5 days without sell criteria, then close position
if (strategy.position_size > 0 and ta.barssince(conditionEntry) >= 5)
strategy.close("Buy")
// Plot RSI on chart
plot(rsi_val, title="RSI", color=color.red)
hline(rsi_upper, title="Overbought Level", color=color.blue)
|
Hobbiecode - SP500 IBS + Higher | https://www.tradingview.com/script/DDWqs5FT/ | hobbiecode | https://www.tradingview.com/u/hobbiecode/ | 113 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hobbiecode
// Today is Monday.
// The close must be lower than the close on Friday.
// The IBS must be below 0.5.
// If 1-3 are true, then enter at the close.
// Sell 5 trading days later (at the close).
//@version=5
strategy("Hobbiecode - SP500 IBS + Higher", overlay=true)
// Check if it's Monday
isMonday = dayofweek(time) == dayofweek.monday
// Calculate the IBS (Intraday Breadth Strength) indicator
ibs = (close - low) / (high - low)
// Calculate the close on the previous Friday
prevFridayClose = request.security(syminfo.tickerid, "W", close)
// Entry conditions
enterCondition = isMonday and close < prevFridayClose and ibs < 0.5 and strategy.position_size < 1
// Exit conditions
exitCondition = (close > high[1] or ta.barssince(enterCondition) == 4) and strategy.position_size > 0
// Entry signal
if enterCondition
strategy.entry("Buy", strategy.long)
// Exit signal
if exitCondition
strategy.close("Buy")
// Plotting the close, previous Friday's close, and entry/exit points on the chart
plot(close, title="Close", color=color.blue)
plot(prevFridayClose, title="Previous Friday Close", color=color.orange)
plotshape(enterCondition, title="Enter", location=location.belowbar, color=color.green, style=shape.labelup, text="Enter")
plotshape(exitCondition, title="Exit", location=location.abovebar, color=color.red, style=shape.labeldown, text="Exit")
|
D-Bot Alpha RSI Breakout Strategy | https://www.tradingview.com/script/0qgJw9O1/ | Genesis-Trader | https://www.tradingview.com/u/Genesis-Trader/ | 72 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © abdllhatn
//@version=5
strategy("Alpha RSI Breakout Strategy", overlay=true, initial_capital=10000, default_qty_value=100)
// Inputs
sma_length = input(200, title="SMA Length")
rsi_length = input(14, title="RSI Length")
rsi_entry = input(34, title="RSI Entry Level")
rsi_stop_loss = input(30, title="RSI Stop Loss Level")
rsi_take_profit = input(50, title="RSI Take Profit Level")
// Indicators
sma_value = ta.sma(close, sma_length)
rsi_value = ta.rsi(close, rsi_length)
var bool trailing_stop_activate = false
var float trailingStop = na
var float lastClose = na
// Conditions
longCondition = ta.crossover(rsi_value, rsi_entry) and close > sma_value
if (longCondition)
strategy.entry("Buy", strategy.long)
trailingStop := na
lastClose := na
trailing_stop_activate := false
if (strategy.position_size > 0)
if (na(lastClose) or close < lastClose)
lastClose := close
trailingStop := close
if (rsi_value >= rsi_take_profit)
trailing_stop_activate := true
if (trailing_stop_activate and not na(trailingStop) and close < trailingStop)
strategy.close("Buy")
if (rsi_value <= rsi_stop_loss)
strategy.close("Buy")
if (not trailing_stop_activate and rsi_value >= rsi_take_profit)
strategy.close("Buy")
if (trailing_stop_activate and rsi_value >= rsi_take_profit)
strategy.close("Buy")
// Plot
plot(sma_value, color=color.red, linewidth=2)
plot(rsi_value, color=color.blue, linewidth=2)
|
Subsets and Splits