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
rzigzag
https://www.tradingview.com/script/xpB2xttf-rzigzag/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
95
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/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Recursive Zigzag Using Matrix allows to create zigzags recursively on multiple levels library("rzigzag", overlay=true) import HeWhoMustNotBeNamed/_matrix/5 as ma import HeWhoMustNotBeNamed/arrays/1 as pa pivots(float[] ohlc, length) => highSource = array.max(ohlc) lowSource = array.min(ohlc) int phighbar = ta.highestbars(highSource, length) int plowbar = ta.lowestbars(lowSource, length) float phigh = ta.highest(highSource, length) float plow = ta.lowest(lowSource, length) [phigh, phighbar, plow, plowbar] iPivots(float[] h, float[] l, int i, int length) => startIndex = math.max(0, i-length+1) highSource = array.slice(h, startIndex, i+1) lowSource = array.slice(l, startIndex, i+1) highIndex = array.sort_indices(highSource, order.descending) lowIndex = array.sort_indices(lowSource, order.ascending) int pHighIndex = array.get(highIndex, 0) int pLowIndex = array.get(lowIndex, 0) float phigh = array.get(highSource, pHighIndex) float plow = array.get(lowSource, pLowIndex) [phigh, startIndex+pHighIndex, plow, startIndex+pLowIndex] addNewIPivot(zigzagmatrix, zigzagpivot, numberOfPivots)=> dir = math.sign(array.get(zigzagpivot, 1)) if(matrix.rows(zigzagmatrix) >=1) lastpivotDir = matrix.get(zigzagmatrix, 0, 1) if(math.sign(lastpivotDir) == math.sign(dir)) runtime.error('Direction mismatch') if(matrix.rows(zigzagmatrix)>=2) value = array.get(zigzagpivot, 0) llastValue = matrix.get(zigzagmatrix, 1, 0) newDir = dir * value > dir * llastValue ? dir * 2 : dir array.set(zigzagpivot, 1, newDir) ma.unshift(zigzagmatrix, zigzagpivot, numberOfPivots) addnewpivot(zigzagmatrix, zigzagpivot, numberOfPivots)=> dir = math.sign(array.get(zigzagpivot, 3)) if(matrix.rows(zigzagmatrix) >=1) lastpivotDir = matrix.get(zigzagmatrix, 0, 3) if(math.sign(lastpivotDir) == math.sign(dir)) runtime.error('Direction mismatch') if(matrix.rows(zigzagmatrix)>=2) value = array.get(zigzagpivot, 0) llastValue = matrix.get(zigzagmatrix, 1, 0) newDir = dir * value > dir * llastValue ? dir * 2 : dir array.set(zigzagpivot, 3, newDir) ma.unshift(zigzagmatrix, zigzagpivot, numberOfPivots) draw_zg_line(idx1, zigzaglines, zigzaglabels, zigzagmatrix, lineColor, lineWidth, lineStyle, showLabel, xloc) => idx2 = idx1+1 if matrix.rows(zigzagmatrix) > idx2 lastValues = matrix.row(zigzagmatrix, idx1) llastValues = matrix.row(zigzagmatrix, idx2) y1 = array.get(lastValues, 0) y2 = array.get(llastValues, 0) x1 = array.get(lastValues, xloc == xloc.bar_index? 1 : 2) x2 = array.get(llastValues, xloc == xloc.bar_index? 1 : 2) zline = line.new(x1=int(x1), y1=y1, x2=int(x2), y2=y2, xloc=xloc, color=lineColor, width=lineWidth, style=lineStyle) dir = array.get(lastValues, 3) label zlabel = na if(showLabel) [hhllText, labelColor] = switch dir 1 => ["LH", color.orange] 2 => ["HH", color.green] -1 => ["HL", color.lime] -2 => ["LL", color.red] => ["NA", color.silver] labelStyle = dir > 0? label.style_label_down : label.style_label_up zlabel := label.new(x=int(x1), y=y1, yloc=yloc.price, xloc=xloc, color=labelColor, style=labelStyle, text=hhllText, textcolor=color.black, size = size.small) pa.push(zigzaglines, zline, 500) pa.push(zigzaglabels, zlabel, 500) // @function calculates plain zigzag based on input // @param length Zigzag Length // @param ohlc Array containing ohlc values. Can also contain custom series // @param numberOfPivots Number of max pivots to be returned // @param offset Offset from current bar. Can be used for calculations based on confirmed bars // @returns [matrix<float> zigzagmatrix, bool[] flags] export zigzag(int length, float[] ohlc, simple int numberOfPivots=20, simple int offset=0) => [phigh, phighbar, plow, plowbar] = pivots(na(ohlc[offset])? ohlc : ohlc[offset], length) newBar = bar_index-offset newBarTime = time[offset] forceDoublePivot = false distanceFromLastPivot = 0.0 float pDir = 1 var matrix<float> zigzagmatrix = matrix.new<float>() if(matrix.rows(zigzagmatrix) > 0) pDir := math.sign(matrix.get(zigzagmatrix, 0, 3)) distanceFromLastPivot := newBar - matrix.get(zigzagmatrix, 0, 1) if(matrix.rows(zigzagmatrix) > 1) llastPrice = matrix.get(zigzagmatrix, 1, 0) forceDoublePivot := pDir == 1 and plowbar == 0 ? plow < llastPrice : pDir == -1 and phighbar == 0 ? phigh > llastPrice : false overflow = distanceFromLastPivot >= length newPivot = false doublePivot = false updateLastPivot = false if ((pDir == 1 and phighbar == 0) or (pDir == -1 and plowbar == 0)) and matrix.rows(zigzagmatrix)>=1 value = pDir == 1 ? phigh : plow ipivot = pDir == 1? plow : phigh pivot = matrix.get(zigzagmatrix, 0, 0) pivotbar = matrix.get(zigzagmatrix, 0, 1) pivottime = matrix.get(zigzagmatrix, 0, 2) pivotdir = matrix.get(zigzagmatrix, 0, 3) removeOld = value * pivotdir > pivot * pivotdir if(removeOld) updateLastPivot := true ma.shift(zigzagmatrix) addnewpivot(zigzagmatrix, array.from(value, newBar, newBarTime, pDir, 0), numberOfPivots) newPivot := true if (pDir == 1 and plowbar == 0) or (pDir == -1 and phighbar == 0) and (not newPivot or forceDoublePivot) value = pDir == 1 ? plow : phigh addnewpivot(zigzagmatrix, array.from(value, newBar, newBarTime, -pDir, 0), numberOfPivots) doublePivot := newPivot newPivot := true if(overflow and not newPivot) ipivot = pDir == 1? plow : phigh ipivotbar = pDir == 1? newBar+plowbar : newBar+phighbar ipivottime = time[newBar-ipivotbar+offset] addnewpivot(zigzagmatrix, array.from(ipivot, ipivotbar, ipivottime, -pDir, 0), numberOfPivots) newPivot := true [zigzagmatrix, array.from(updateLastPivot, newPivot, doublePivot)] // @function calculates plain zigzag based on input array // @param length Zigzag Length // @param h array containing high values of a series // @param l array containing low values of a series // @param numberOfPivots Number of max pivots to be returned // @returns matrix<float> zigzagmatrix export iZigzag(int length, array<float> h, array<float> l, simple int numberOfPivots=500) => matrix<float> zigzagmatrix = matrix.new<float>() for i=0 to array.size(h) >0? array.size(h)-1: na [phigh, phighbar, plow, plowbar] = iPivots(h, l, i, length) float pDir = 1 newPivot = phighbar == i or plowbar == i doublePivot = phighbar == i and plowbar == i updateLastPivot = false if(matrix.rows(zigzagmatrix) > 0) pDir := math.sign(matrix.get(zigzagmatrix, 0, 1)) if ((pDir == 1 and phighbar == i) or (pDir == -1 and plowbar == i)) and matrix.rows(zigzagmatrix)>=1 value = pDir == 1 ? phigh : plow ipivot = pDir == 1? plow : phigh pivot = matrix.get(zigzagmatrix, 0, 0) pivotdir = matrix.get(zigzagmatrix, 0, 1) removeOld = value * pivotdir > pivot * pivotdir addInverse = false if(removeOld) updateLastPivot := true ma.shift(zigzagmatrix) addNewIPivot(zigzagmatrix, array.from(value, pDir, i), numberOfPivots) if(matrix.rows(zigzagmatrix) > 1 and doublePivot) llastPivot = matrix.get(zigzagmatrix, 1, 0) if(-pDir*llastPivot >= -pDir*ipivot) addInverse := true else if (not removeOld and not doublePivot) or addInverse ipivotbar = pDir == 1? plowbar : phighbar addNewIPivot(zigzagmatrix, array.from(ipivot, -pDir, ipivotbar), numberOfPivots) doublePivot := true if (pDir == 1 and plowbar == i) or (pDir == -1 and phighbar == i) value = pDir == 1 ? plow : phigh addNewIPivot(zigzagmatrix, array.from(value, -pDir, i), numberOfPivots) zigzagmatrix // @function calculates next level zigzag based on present zigzag coordinates // @param zigzagmatrix Matrix containing zigzag pivots, bars, bar time, direction and level // @param numberOfPivots Number of max pivots to be returned // @returns matrix<float> zigzagmatrix export nextlevel(matrix<float> zigzagmatrix, simple int numberOfPivots = 20)=> mlZigzagMatrix = matrix.new<float>() if(matrix.rows(zigzagmatrix) > 0) tempRowBullish = array.new<float>() tempRowBearish = array.new<float>() for i=(matrix.rows(zigzagmatrix)-1) to 0 row = array.copy(matrix.row(zigzagmatrix, i)) dir = array.get(row, 3) newDir = math.sign(dir) value = array.get(row, 0) array.set(row, 4, array.get(row, 4)+1) if(matrix.rows(mlZigzagMatrix) > 0) lastDir = math.sign(matrix.get(mlZigzagMatrix, 0, 3)) lastPivot = matrix.get(mlZigzagMatrix, 0, 0) if(math.abs(dir) == 2) if(lastDir == newDir) if(dir*lastPivot < dir*value) ma.shift(mlZigzagMatrix) else tempRow = newDir >0 ? tempRowBearish : tempRowBullish if(array.size(tempRow) > 0) addnewpivot(mlZigzagMatrix, array.copy(tempRow), numberOfPivots) else continue else tempRowFirst = newDir >0 ? tempRowBullish : tempRowBearish tempRowSecond = newDir >0 ? tempRowBearish : tempRowBullish if(array.size(tempRowFirst) > 0 and array.size(tempRowSecond) > 0) tempVal = array.get(tempRowFirst, 0) val =array.get(row, 0) if(newDir*tempVal > newDir*val) addnewpivot(mlZigzagMatrix, array.copy(tempRowFirst), numberOfPivots) addnewpivot(mlZigzagMatrix, array.copy(tempRowSecond), numberOfPivots) addnewpivot(mlZigzagMatrix, row, numberOfPivots) array.clear(tempRowBearish) array.clear(tempRowBullish) else tempRow = newDir > 0 ? tempRowBullish : tempRowBearish if(array.size(tempRow) != 0) tempDir = array.get(tempRow, 3) tempVal = array.get(tempRow, 0) val =array.get(row, 0) if(val*dir > tempVal*dir) array.clear(tempRow) array.concat(tempRow, row) else array.concat(tempRow, row) else if(math.abs(dir) == 2) addnewpivot(mlZigzagMatrix, row, numberOfPivots) if(matrix.rows(mlZigzagMatrix) >= matrix.rows(zigzagmatrix)) ma.clear(mlZigzagMatrix) mlZigzagMatrix // @function draws zigzag based on the zigzagmatrix input // @param zigzagmatrix Matrix containing zigzag pivots, bars, bar time, direction and level // @param flags Zigzag pivot flags // @param lineColor Zigzag line color // @param lineWidth Zigzag line width // @param lineStyle Zigzag line style // @param showLabel Flag to indicate display pivot labels // @param xloc xloc preference for drawing lines/labels // @returns [array<line> zigzaglines, array<label> zigzaglabels] export draw(matrix<float> zigzagmatrix, bool[] flags, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid, bool showLabel=false, string xloc=xloc.bar_time)=> var zigzaglines = array.new<line>() var zigzaglabels = array.new<label>() if array.size(zigzaglines) > 0 and array.get(flags, 0) pa.pop(zigzaglines) pa.pop(zigzaglabels) if(array.get(flags, 1)) if array.get(flags, 2) and matrix.rows(zigzagmatrix) >=3 draw_zg_line(1, zigzaglines, zigzaglabels, zigzagmatrix, lineColor, lineWidth, lineStyle, showLabel, xloc) if matrix.rows(zigzagmatrix) >= 2 draw_zg_line(0, zigzaglines, zigzaglabels, zigzagmatrix, lineColor, lineWidth, lineStyle, showLabel, xloc) [zigzaglines, zigzaglabels] // @function calculates and draws zigzag based on zigzag length and source input // @param length Zigzag Length // @param ohlc Array containing ohlc values. Can also contain custom series // @param numberOfPivots Number of max pivots to be returned // @param offset Offset from current bar. Can be used for calculations based on confirmed bars // @param lineColor Zigzag line color // @param lineWidth Zigzag line width // @param lineStyle Zigzag line style // @param showLabel Flag to indicate display pivot labels // @param xloc xloc preference for drawing lines/labels // @returns [matrix<float> zigzagmatrix, array<line> zigzaglines, array<label> zigzaglabels, bool[] flags] export draw(int length, float[] ohlc, simple int numberOfPivots=20, simple int offset=0, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid, bool showLabel=false, string xloc=xloc.bar_time)=> [zigzagmatrix, flags] = zigzag(length, ohlc, numberOfPivots, offset) [zigzaglines, zigzaglabels] = draw(zigzagmatrix, flags, lineColor, lineWidth, lineStyle, showLabel, xloc) [zigzagmatrix, zigzaglines, zigzaglabels, flags] // @function draws fresh zigzag for all pivots in the input matrix. // @param zigzagmatrix Matrix containing zigzag pivots, bars, bar time, direction and level // @param zigzaglines array to which all newly created lines will be added // @param zigzaglabels array to which all newly created lables will be added // @param lineColor Zigzag line color // @param lineWidth Zigzag line width // @param lineStyle Zigzag line style // @param showLabel Flag to indicate display pivot labels // @param xloc xloc preference for drawing lines/labels // @returns [array<line> zigzaglines, array<label> zigzaglabels] export drawfresh(matrix<float> zigzagmatrix, array<line> zigzaglines, array<label> zigzaglabels, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid, bool showLabel = false, string xloc = xloc.bar_time)=> rows = matrix.rows(zigzagmatrix) for i=1 to rows>1? rows-1 :na lastValues = matrix.row(zigzagmatrix, i) llastValues = matrix.row(zigzagmatrix, i-1) y1 = array.get(lastValues, 0) y2 = array.get(llastValues, 0) x1 = array.get(lastValues, xloc== xloc.bar_time?2:1) x2 = array.get(llastValues, xloc == xloc.bar_time?2:1) level = array.get(lastValues, 4) zline = line.new(x1=int(x1), y1=y1, x2=int(x2), y2=y2, xloc=xloc, color=lineColor, width=lineWidth, style=lineStyle) dir = array.get(lastValues, 2) label zlabel = na if(showLabel) labelStyle = dir > 0? label.style_label_down : label.style_label_up zlabel := label.new(x=int(x1), y=y1, yloc=yloc.price, color=lineColor, style=labelStyle, text=str.tostring(level), textcolor=color.black, size = size.small, xloc=xloc) pa.push(zigzaglines, zline, 500) pa.push(zigzaglabels, zlabel, 500) [zigzaglines, zigzaglabels]
FunctionKellyCriterion
https://www.tradingview.com/script/yOwHsSyt-FunctionKellyCriterion/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
95
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 Kelly criterion methods. // the kelly criterion helps with the decision of how much one should invest in // a asset as long as you know the odds and expected return of said asset. library(title='FunctionKellyCriterion') // reference: // https://quantpedia.com/beware-of-excessive-leverage-introduction-to-kelly-and-optimal-f/?a=6080 // https://masters.donntu.org/2009/fvti/kravchenko/library/article5.htm // https://towardsdatascience.com/python-risk-management-kelly-criterion-526e8fb6d6fd // Kelly's Criterion in Portfolio Optimization: A Decoupled Problem: https://arxiv.org/abs/1710.00431 // https://catalogimages.wiley.com/images/db/pdf/9780470455951.excerpt.pdf // The Kelly criterion states that we should bet that fixed fraction of our // stake ( f ) that maximizes the growth function G( f ): // G( f ) = P ∗ ln(1 + B ∗ f ) + (1 − P) ∗ ln(1 − f ) (1.02) // where: f = the optimal fixed fraction // P = the probability of a winning bet/trade // B = the ratio of amount won on a winning bet to amount lost on // a losing bet // ln( ) = the natural logarithm function // @function simplified version of the kelly criterion formula. // @param win_p float, probability of winning. // @param rr float, reward to risk rate. // @returns // float, optimal fraction to risk. // usage: // simplified(0.55, 1.0) export simplified ( float win_p, float rr ) => //{ float _loss_p = 1.0 - win_p win_p - (_loss_p / rr) // example: // k = simplified(math.sum(close > open ? 1.0 : 0.0, 10) / (10 + 1), 2.0) plot( series = simplified(0.55, 1.0), title = 'F', color = color.aqua ) // reference: // https://quantpedia.com/beware-of-excessive-leverage-introduction-to-kelly-and-optimal-f/?a=6080 //} // @function general form of the kelly criterion formula. // @param win_p float, probability of the investment returns a positive outcome. // @param loss_p float, probability of the investment returns a negative outcome. // @param win_rr float, reward on a positive outcome. // @param loss_rr float, reward on a negative outcome. // @returns // float, optimal fraction to risk. // usage: // partial(0.6, 0.4, 0.6, 0.1) export partial ( float win_p , float loss_p , float win_rr , float loss_rr ) => //{ (win_p / loss_rr) - (loss_p / win_rr) // example: plot( series = partial(0.6, 0.4, 0.6, 0.1), title = 'Partial', color = color.purple ) // reference: // https://quantpedia.com/beware-of-excessive-leverage-introduction-to-kelly-and-optimal-f/?a=6080 //} // @function Calculate the fraction to invest from a array of returns. // @param returns array<float> trade/asset/strategy returns. // @returns // float, optimal fraction to risk. // usage: // from_returns(array.from(0.1,0.2,0.1,-0.1,-0.05,0.05)) export from_returns ( float[] returns ) => //{ int _size = array.size(returns) array<float> _wins = array.new<float>(0) array<float> _losses = array.new<float>(0) for _i = 0 to _size - 1 float _ri = array.get(returns, _i) if _ri > 0.0 array.push(_wins, _ri) else array.push(_losses, _ri) float _win_p = array.size(_wins) / _size float _rr = array.avg(_wins) / math.abs(array.avg(_losses)) simplified(_win_p, _rr) // example: plot( series = from_returns(array.from(0.25,-0.15,0.25,-0.15,0.25,-0.05,0.25,-0.15,0.25,-0.05)), title = 'from returns' ) //} // @function Final fraction, eg. if fraction is 0.2 and expected max loss is 10% // then you should size your position as 0.2/0.1=2 (leverage, 200% position size). // @param fraction float, aproximate percent fraction invested. // @param max_expected_loss float, maximum expected percent on a loss (ex 10% = 0.1). // @returns // float, final fraction to invest. // usage: // final_f(0.2, 0.5) export final_f ( float fraction , float max_expected_loss ) => //{ fraction / max_expected_loss // example: plot( series = final_f(0.2, 0.5), title = 'Ff', color = color.red ) // reference: // https://quantpedia.com/beware-of-excessive-leverage-introduction-to-kelly-and-optimal-f/?a=6080 //} // @function Holding Period Return function // @param fraction float, aproximate percent fraction invested. // @param trade float, profit or loss in a trade. // @param biggest_loss float, value of the biggest loss on record. // @returns // float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95. // usage: // hpr(fraction=0.05, trade=0.1, biggest_loss=-0.2) export hpr ( float fraction , float trade , float biggest_loss ) => //{ 1.0 + fraction * final_f(-trade, biggest_loss) // example: plot( series = hpr(0.05, 0.1, -0.2), title = 'HPR', color = color.yellow ) //} // @function Terminal Wealth Relative, returns a multiplier that can be applied // to the initial capital that leadds to the final balance. // @param returns array<float>, list of trade returns. // @param rr float , reward to risk rate. // @param eps float , minimum resolution to void zero division. // @returns // float, optimal fraction to invest. // usage: // twr(returns=array.from(0.1,-0.2,0.3), rr=0.6) export twr ( float[] returns , float rr , float eps = -1.0e-12 ) => //{ int _size = array.size(returns) // error handling: switch _size < 1 => runtime.error('FunctionKellyCriterion -> twr(): "returns" parameter array must have atleast one element!') // float _biggest_loss = math.min(eps, array.min(returns)) int _wins = 0 for _i = 0 to _size - 1 float _ti = array.get(returns, _i) if _ti > 0.0 _wins += 1 float _win_p = _wins / _size float _f = simplified(_win_p, rr) _twr = 1.0 for _i = 0 to _size - 1 _twr *= hpr(_f, array.get(returns, _i), _biggest_loss) _twr // example: r = array.from(+9.0, +18, +7, +1, +10,-5,-3,-17,-7) t = twr(r, 0.50) plot( series = t, title = 'TWR', color = color.teal ) // reference: // https://quantpedia.com/beware-of-excessive-leverage-introduction-to-kelly-and-optimal-f/?a=6080 //} //////////////////////////////////////////////////////////////////////////////// // the following functions are just accessory and are included for convenience // sake only. //////////////////////////////////////////////////////////////////////////////// // @function Geometric mean Holding Period Return, represents the average multiple made on the stake. // @param returns array<float>, list of trade returns. // @param rr float , reward to risk rate. // @param eps float , minimum resolution to void zero division. // @returns // float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95. // usage: // ghpr(returns=array.from(0.1,-0.2,0.3), rr=0.6) export ghpr ( float[] returns , float rr , float eps = -1.0e-12 ) => //{ int _size_r = array.size(returns) math.pow(twr(returns, rr, eps), 1.0 / _size_r) // example: plot( series = ghpr(r, 0.50), title = 'GHPR', color = color.yellow ) //} // @function run multiple coin flipping (binary outcome) simulations. // @param fraction float, fraction of capital to bet. // @param initial_capital float, capital at the start of simulation. // @param n_series int , number of simulation series. // @param n_periods int , number of periods in each simulation series. // @returns // matrix<float>(n_series, n_periods), matrix with simulation results per row. // usage: // run_coin_simulation(fraction=0.1) export run_coin_simulation( float fraction , float initial_capital = 100.0, int n_series = 10 , int n_periods = 100 ) => //{ // _S = matrix.new<float>(10, 100) for _i = 0 to n_series - 1 matrix.set(_S, _i, 0, initial_capital) for _t = 1 to n_periods - 1 bool _heads = math.round(math.random()) > 0 if _heads // add the win to the capital matrix.set(_S, _i, _t, (1.0 + fraction) * matrix.get(_S, _i, _t - 1) ) else // take the loss from the capital matrix.set(_S, _i, _t, (1.0 - fraction) * matrix.get(_S, _i, _t - 1) ) _S // example: // var S = run_coin_simulation(0.1) // plot(matrix.get(S, 0, bar_index%100)) // plot(array.avg(matrix.col(S, bar_index%100))) // reference: // https://towardsdatascience.com/python-risk-management-kelly-criterion-526e8fb6d6fd //} // @function run a simulation over provided returns. // @param returns array<float>, trade, asset or strategy percent returns. // @param fraction float , fraction of capital to bet. // @param initial_capital float , capital at the start of simulation. // @returns // array<float>, array with simulation results. // usage: // run_asset_simulation(returns=array.from(0.1,-0.2,0.-3,0.4), fraction=0.1) export run_asset_simulation( array<float> returns , float fraction , float initial_capital = 100.0 ) => //{ // int _size = array.size(returns) _S = array.new<float>(_size) array.set(_S, 0, initial_capital) for _t = 1 to _size - 1 float _r = math.exp(array.get(returns, _t)) // center returns around 1 instead of 0 float _eq = array.get(_S, _t - 1) if _r >= 1.0 // add the win to the capital array.set(_S, _t, math.max(0.0, (1.0 + (fraction * _r)) * _eq)) else // take the loss from the capital array.set(_S, _t, math.max(0.0, (1.0 - (fraction * _r)) * _eq)) _S // example: var rs = array.new<float>(100, 0.0) if barstate.isfirst for _i = 1 to 99 array.set(rs, _i, math.random(-0.01, 0.01) * math.random()) float optf = math.max(0.001, from_returns(rs)) var A = run_asset_simulation(rs, 0.1) var B = run_asset_simulation(rs, optf) plot(array.get(A, bar_index%100), title='Asset sim. A', color=color.blue) plot(array.get(B, bar_index%100), title='Asset sim. B', color=color.red) plotshape(series=bar_index%100==0?100:na, title='marker', style=shape.diamond, location=location.absolute, size=size.small) // reference: // https://towardsdatascience.com/python-risk-management-kelly-criterion-526e8fb6d6fd //} // @function calculate strategy() current probability of positive outcome in a trade. export strategy_win_probability() => //{ strategy.wintrades / strategy.closedtrades // reference: // https://www.tradingview.com/script/bFXf4IXh-Built-in-Kelly-ratio-for-dynamic-position-sizing/ //} // @function calculate strategy() current average won on a trade with positive outcome. export strategy_avg_won() => //{ strategy.grossprofit / strategy.wintrades // reference: // https://www.tradingview.com/script/bFXf4IXh-Built-in-Kelly-ratio-for-dynamic-position-sizing/ //} // @function calculate strategy() current average lost on a trade with negative outcome. export strategy_avg_loss() => //{ strategy.grossloss / strategy.losstrades // reference: // https://www.tradingview.com/script/bFXf4IXh-Built-in-Kelly-ratio-for-dynamic-position-sizing/ //}
LevelsManager
https://www.tradingview.com/script/e0S8cu7Z-LevelsManager/
sosso_bott
https://www.tradingview.com/u/sosso_bott/
33
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/ // © sosso_bott //@version=5 // @description TODO: Track up to 6 TakeProfits and 1 StopLoss achievement for one or many of your buy/sell conditions. library("LevelsManager") // ——————————————————————————— \\ // ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼ \\ // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ \\ // ——————————————————————————— \\ // ******************=========================== Function @manageTrade ==============================************************** \\ // -------- PARAMS ---------|----- TYPE -----|------------------------------- DESCRIPTION && DETAILS -----------------------------|----------- TIPS ------------| // @param useSignal : (series bool) | TO ACTIVATE OR DEACTIVATE Trade Management | [INPUT] | // @param b_gameOVer : (series bool) | BUY CONDITION | Pinesript logic | // @param s_gameOver : (series bool) | SELL CONDITION | Pinesript logic | // @param bName : (series string)| BUY CONDITION string ID (Make it small 3 characters max or dont listen to me lol) | Hardcode it on funtion call | // @param sName : (series string)| SELL CONDITION string ID (Make it small 3 characters max or dont listen to me lol)| Hardcode it on funtion call | // @param buyEntrySource : (series float) | ENTRY LEVEL FOR BUY CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param sellEntrySource : (series float) | ENTRY LEVEL FOR SELL CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param useTp1 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp2 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp3 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp4 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp5 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp6 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param tp1x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp2x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp3x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp4x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp5x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp6x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param slx : (series float) | PERCENTAGE FOR STOPLOSS LEVEL ACHIEVMENT | [INPUT] | // -------- RETURN ---------|----- TYPE -----|------------------------------- BEHAVIOR -----------------------------| // entry_touched : (series bool) | PLOTTED (Role: Showing if entry is hit) // entry1 : (series float) | NOT PLOTTED (Use it for alerts) // tp1 : (series float) | NOT PLOTTED (Use it for alerts) // tp2 : (series float) | NOT PLOTTED (Use it for alerts) // tp3 : (series float) | NOT PLOTTED (Use it for alerts) // tp4 : (series float) | NOT PLOTTED (Use it for alerts) // tp5 : (series float) | NOT PLOTTED (Use it for alerts) // tp6 : (series float) | NOT PLOTTED (Use it for alerts) // sl : (series float) | NOT PLOTTED (Use it for alerts) // official_buy : (series bool) | NOT PLOTTED (PLOT IT YOUR BUY CONDITION THEY WAY YOU WANT) // official_sell : (series bool) | NOT PLOTTED (PLOT IT YOUR SEEL CONDITION THEY WAY YOU WANT) // buyTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP2_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP3_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP4_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP5_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP6_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buySL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP2_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP3_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP4_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP5_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP6_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellSL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // ******************=========================== Function @manageTrade END ==============================************************** \\ // ******************=========================== Function @manageFilterredTrade ==============================************************** \\ // -------- PARAMS ---------|----- TYPE -----|------------------------------- DESCRIPTION && DETAILS -----------------------------|----------- TIPS ------------| // @param useSignal : (series bool) | TO ACTIVATE OR DEACTIVATE Trade Management | [INPUT] | // @param b_gameOVer : (series bool) | BUY CONDITION | Pinesript logic | // @param longCancel : (series bool) | CONDITION TO RESTART LOOKING FOR A BUY TRADE | Pinesript logic | // @param s_gameOver : (series bool) | SELL CONDITION | Pinesript logic | // @param shortCancel : (series bool) | CONDITION TO RESTART LOOKING FOR A SELL TRADE | Pinesript logic | // @param bName : (series string)| BUY CONDITION string ID (Make it small 3 characters max or dont listen to me lol) | Hardcode it on funtion call | // @param sName : (series string)| SELL CONDITION string ID (Make it small 3 characters max or dont listen to me lol)| Hardcode it on funtion call | // @param buyEntrySource : (series float) | ENTRY LEVEL FOR BUY CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param sellEntrySource : (series float) | ENTRY LEVEL FOR SELL CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param useTp1 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp2 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp3 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp4 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp5 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp6 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param tp1x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp2x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp3x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp4x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp5x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp6x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param slx : (series float) | PERCENTAGE FOR STOPLOSS LEVEL ACHIEVMENT | [INPUT] | // -------- RETURN ---------|----- TYPE -----|------------------------------- BEHAVIOR -----------------------------| // entry_touched : (series bool) | PLOTTED (Role: Showing if entry is hit) // entry1 : (series float) | NOT PLOTTED (Use it for alerts) // tp1 : (series float) | NOT PLOTTED (Use it for alerts) // tp2 : (series float) | NOT PLOTTED (Use it for alerts) // tp3 : (series float) | NOT PLOTTED (Use it for alerts) // tp4 : (series float) | NOT PLOTTED (Use it for alerts) // tp5 : (series float) | NOT PLOTTED (Use it for alerts) // tp6 : (series float) | NOT PLOTTED (Use it for alerts) // sl : (series float) | NOT PLOTTED (Use it for alerts) // official_buy : (series bool) | NOT PLOTTED (PLOT IT YOUR BUY CONDITION THEY WAY YOU WANT) // official_sell : (series bool) | NOT PLOTTED (PLOT IT YOUR SEEL CONDITION THEY WAY YOU WANT) // buyTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP2_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP3_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP4_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP5_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP6_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buySL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP2_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP3_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP4_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP5_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP6_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellSL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // ******************=========================== Function @manageFilterredTrade END ==============================************************** \\ // ******************=========================== Function @manageLevel ==============================************************** \\ // -------- PARAMS ---------|----- TYPE -----|------------------------------- DESCRIPTION && DETAILS -----------------------------|----------- TIPS ------------| // @param useSignal : (series bool) | TO ACTIVATE OR DEACTIVATE Trade Management | [INPUT] | // @param b_gameOVer : (series bool) | BUY CONDITION | Pinesript logic | // @param s_gameOver : (series bool) | SELL CONDITION | Pinesript logic | // @param bName : (series string)| BUY CONDITION string ID (Make it small 3 characters max or dont listen to me lol) | Hardcode it on funtion call | // @param sName : (series string)| SELL CONDITION string ID (Make it small 3 characters max or dont listen to me lol)| Hardcode it on funtion call | // @param buyEntrySource : (series float) | ENTRY LEVEL FOR BUY CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param sellEntrySource : (series float) | ENTRY LEVEL FOR SELL CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param tp1x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param slx : (series float) | PERCENTAGE FOR STOPLOSS LEVEL ACHIEVMENT | [INPUT] | // -------- RETURN ---------|----- TYPE -----|------------------------------- BEHAVIOR -----------------------------| // entry_touched : (series bool) | PLOTTED (Role: Showing if entry is hit) // entry1 : (series float) | NOT PLOTTED (Use it for alerts) // tp1 : (series float) | NOT PLOTTED (Use it for alerts) // sl : (series float) | NOT PLOTTED (Use it for alerts) // official_buy : (series bool) | NOT PLOTTED (PLOT IT YOUR BUY CONDITION THEY WAY YOU WANT) // official_sell : (series bool) | NOT PLOTTED (PLOT IT YOUR SEEL CONDITION THEY WAY YOU WANT) // buyTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buySL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellSL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // ******************=========================== Function @manageLevel END ==============================************************** \\ // ******************=========================== Function @manageFilterredLevel ==============================************************** \\ // -------- PARAMS ---------|----- TYPE -----|------------------------------- DESCRIPTION && DETAILS -----------------------------|----------- TIPS ------------| // @param useSignal : (series bool) | TO ACTIVATE OR DEACTIVATE Trade Management | [INPUT] | // @param b_gameOVer : (series bool) | BUY CONDITION | Pinesript logic | // @param longCancel : (series bool) | CONDITION TO RESTART LOOKING FOR A BUY TRADE | Pinesript logic | // @param s_gameOver : (series bool) | SELL CONDITION | Pinesript logic | // @param shortCancel : (series bool) | CONDITION TO RESTART LOOKING FOR A SELL TRADE | Pinesript logic | // @param bName : (series string)| BUY CONDITION string ID (Make it small 3 characters max or dont listen to me lol) | Hardcode it on funtion call | // @param sName : (series string)| SELL CONDITION string ID (Make it small 3 characters max or dont listen to me lol)| Hardcode it on funtion call | // @param buyEntrySource : (series float) | ENTRY LEVEL FOR BUY CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param sellEntrySource : (series float) | ENTRY LEVEL FOR SELL CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param tp1x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param slx : (series float) | PERCENTAGE FOR STOPLOSS LEVEL ACHIEVMENT | [INPUT] | // -------- RETURN ---------|----- TYPE -----|------------------------------- BEHAVIOR -----------------------------| // entry_touched : (series bool) | PLOTTED (Role: Showing if entry is hit) // entry1 : (series float) | NOT PLOTTED (Use it for alerts) // tp1 : (series float) | NOT PLOTTED (Use it for alerts) // sl : (series float) | NOT PLOTTED (Use it for alerts) // official_buy : (series bool) | NOT PLOTTED (PLOT IT YOUR BUY CONDITION THEY WAY YOU WANT) // official_sell : (series bool) | NOT PLOTTED (PLOT IT YOUR SEEL CONDITION THEY WAY YOU WANT) // buyTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buySL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellSL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // ******************=========================== Function @manageFilterredLevel END ==============================************************** \\ // ******************=========================== Function @tpLevels ==============================************************** \\ // MAIN DIFFERENCE : LEVELS WILL STAY ON THE CHART // -------- PARAMS ---------|----- TYPE -----|------------------------------- DESCRIPTION && DETAILS -----------------------------|----------- TIPS ------------| // @param useSignal : (series bool) | TO ACTIVATE OR DEACTIVATE Trade Management | [INPUT] | // @param b_gameOVer : (series bool) | BUY CONDITION | Pinesript logic | // @param s_gameOver : (series bool) | SELL CONDITION | Pinesript logic | // @param bName : (series string)| BUY CONDITION string ID (Make it small 3 characters max or dont listen to me lol) | Hardcode it on funtion call | // @param sName : (series string)| SELL CONDITION string ID (Make it small 3 characters max or dont listen to me lol)| Hardcode it on funtion call | // @param buyEntrySource : (series float) | ENTRY LEVEL FOR BUY CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param sellEntrySource : (series float) | ENTRY LEVEL FOR SELL CONDITION |[INPUT OR NOT IT'S UP TO YOU]| // @param useTp1 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp2 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp3 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp4 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp5 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param useTp6 : (series bool) | USE THE TP LEVEL OR NOT | [INPUT] | // @param tp1x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp2x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp3x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp4x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp5x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param tp6x : (series float) | PERCENTAGE FOR THIS TP LEVEL ACHIEVMENT | [INPUT] | // @param slx : (series float) | PERCENTAGE FOR STOPLOSS LEVEL ACHIEVMENT | [INPUT] | // -------- RETURN ---------|----- TYPE -----|------------------------------- BEHAVIOR -----------------------------| // entry_touched : (series bool) | PLOTTED (Role: Showing if entry is hit) // entry1 : (series float) | NOT PLOTTED (Use it for alerts) // tp1 : (series float) | NOT PLOTTED (Use it for alerts) // tp2 : (series float) | NOT PLOTTED (Use it for alerts) // tp3 : (series float) | NOT PLOTTED (Use it for alerts) // tp4 : (series float) | NOT PLOTTED (Use it for alerts) // tp5 : (series float) | NOT PLOTTED (Use it for alerts) // tp6 : (series float) | NOT PLOTTED (Use it for alerts) // sl : (series float) | NOT PLOTTED (Use it for alerts) // official_buy : (series bool) | NOT PLOTTED (PLOT IT YOUR BUY CONDITION THEY WAY YOU WANT) // official_sell : (series bool) | NOT PLOTTED (PLOT IT YOUR SEEL CONDITION THEY WAY YOU WANT) // buyTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP2_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP3_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP4_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP5_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buyTP6_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // buySL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP1_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP2_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP3_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP4_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP5_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellTP6_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // sellSL_touched : (series bool) | PLOTTED (USE IT TO ACT ON TP ACHIEVMENT) // ******************=========================== Function @tpLevels END ==============================************************** \\ // CALLING EXEMPLE \\ // HOW THE INDICATOR IN THE IMAGE CALLS @manageTrade function // import sosso_bott/TradeManager/1 as tm // [L1_S1entry_touched, L1_S1entry, L1_S1_tp1, L1_S1_tp2, L1_S1_tp3, L1_S1_tp4, L1_S1_tp5, L1_S1_tp6, L1_S1_sl, OL1, OS1, L1_buyTP1_touched, L1_buyTP2_touched, L1_buyTP3_touched, L1_buyTP4_touched, L1_buyTP5_touched, L1_buyTP6_touched, L1_buySL_Touched, S1_sellTP1_touched, S1_sellTP2_touched, S1_sellTP3_touched, S1_sellTP4_touched, S1_sellTP5_touched, S1_sellTP6_touched, S1_sellSL_touched] = tm.manageTrade(use_TrndSignals, L_1, S_1, "L_1", "S_1", buyEntrySource, sellEntrySource, useTp1, useTp2, useTp3, useTp4, useTp5, useTp6, tp1x, tp2x, tp3x, tp4x, tp5x, tp6x, slx) // [L2_S2entry_touched, L2_S2entry, L2_S2_tp1, L2_S2_tp2, L2_S2_tp3, L2_S2_tp4, L2_S2_tp5, L2_S2_tp6, L2_S2_sl, OL2, OS2, L2_buyTP1_touched, L2_buyTP2_touched, L2_buyTP3_touched, L2_buyTP4_touched, L2_buyTP5_touched, L2_buyTP6_touched, L2_buySL_Touched, S2_sellTP1_touched, S2_sellTP2_touched, S2_sellTP3_touched, S2_sellTP4_touched, S2_sellTP5_touched, S2_sellTP6_touched, S2_sellSL_touched] = tm.manageTrade(use_MidSignals, L_2, S_2, "L_2", "S_2", buyEntrySource2, sellEntrySource2, useTp1, useTp2, useTp3, useTp4, useTp5, useTp6, tp1x, tp2x, tp3x, tp4x, tp5x, tp6x, slx) // [L3_S3entry_touched, L3_S3entry, L3_S3_tp1, L3_S3_tp2, L3_S3_tp3, L3_S3_tp4, L3_S3_tp5, L3_S3_tp6, L3_S3_sl, OL3, OS3, L3_buyTP1_touched, L3_buyTP2_touched, L3_buyTP3_touched, L3_buyTP4_touched, L3_buyTP5_touched, L3_buyTP6_touched, L3_buySL_Touched, S3_sellTP1_touched, S3_sellTP2_touched, S3_sellTP3_touched, S3_sellTP4_touched, S3_sellTP5_touched, S3_sellTP6_touched, S3_sellSL_touched] = tm.manageTrade(use_scalppers, L_3, S_3, "L_3", "S_3", buyEntrySource3, sellEntrySource3, useTp1, useTp2, useTp3, useTp4, useTp5, useTp6, tp1x, tp2x, tp3x, tp4x, tp5x, tp6x, slx) // [L4_S4entry_touched, L4_S4entry, L4_S4_tp1, L4_S4_tp2, L4_S4_tp3, L4_S4_tp4, L4_S4_tp5, L4_S4_tp6, L4_S4_sl, OL4, OS4, L4_buyTP1_touched, L4_buyTP2_touched, L4_buyTP3_touched, L4_buyTP4_touched, L4_buyTP5_touched, L4_buyTP6_touched, L4_buySL_Touched, S4_sellTP1_touched, S4_sellTP2_touched, S4_sellTP3_touched, S4_sellTP4_touched, S4_sellTP5_touched, S4_sellTP6_touched, S4_sellSL_touched] = tm.manageTrade(use_scalppers2, L_4, S_4, "L_4", "S_4", buyEntrySource4, sellEntrySource4, useTp1, useTp2, useTp3, useTp4, useTp5, useTp6, tp1x, tp2x, tp3x, tp4x, tp5x, tp6x, slx) // Function @round_price is used by manageTrade function // Function @getLevel is just un example of method i use to switch between mulitple // EXAMPLE OF CALL WITH GET LEVEL : // buyEntrySource = input(defval = "RENKOMID2", title = "Buy entry source (S1_L1)", options=["CLOSE", "LOW", "HL2", "RENKOMID1", "RENKOMID2", "RENKODN", "DOWNLEVEL1", "EXTRADN", "RENKODN2", "DOWNLEVEL2", "EXTRADN2"], type = input.string, group="Signals Entry") // sellEntrySource = input(defval = "RENKOMID2", title = "Sell entry source (S1_L1)", options=["CLOSE", "HIGH", "HL2", "RENKOMID1", "RENKOMID2", "RENKOUP", "UPLEVEL1", "EXTRAUP", "RENKOUP2", "UPLEVEL2", "EXTRAUP2"], type = input.string, group="Signals Entry") // [L1_S1entry_touched, L1_S1entry, L1_S1_tp1, L1_S1_tp2, L1_S1_tp3, L1_S1_tp4, L1_S1_tp5, L1_S1_tp6, L1_S1_sl, OL1, OS1, L1_buyTP1_touched, L1_buyTP2_touched, L1_buyTP3_touched, L1_buyTP4_touched, L1_buyTP5_touched, L1_buyTP6_touched, L1_buySL_touched, S1_sellTP1_touched, S1_sellTP2_touched, S1_sellTP3_touched, S1_sellTP4_touched, S1_sellTP5_touched, S1_sellTP6_touched, S1_sellSL_touched] = manageTrade(use_TrndSignals, L_1, S_1, "L_1", "S_1", getLevel(buyEntrySource), getLevelsellEntrySource), useTp1, useTp2, useTp3, useTp4, useTp5, useTp6, tp1x, tp2x, tp3x, tp4x, tp5x, tp6x, slx) // getLevel(EntrySource) => // level = EntrySource == "LOW" ? low : EntrySource == "CLOSE" ? close : EntrySource == "HIGH" ? high : EntrySource == "HL2" ? hl2 : EntrySource == "RENKODN" ? RENKODN1 : EntrySource == "RENKOUP" ? RENKOUP1: EntrySource == "EXTRADN" ? EXTRADN1: EntrySource == "EXTRAUP" ? EXTRAUP1: EntrySource == "UPLEVEL1" ? UPLEVEL1: EntrySource == "DOWNLEVEL1" ? DOWNLEVEL1: EntrySource == "RENKODN2" ? RENKODN2: EntrySource == "RENKOUP2" ? RENKOUP2: EntrySource == "DOWNLEVEL2" ? DOWNLEVEL2: EntrySource == "UPLEVEL2" ? UPLEVEL2: EntrySource == "EXTRAUP2" ? EXTRAUP2: EntrySource == "EXTRADN2" ? EXTRADN2 : EntrySource == "RENKOMID1" ? RENKOMID: EntrySource == "RENKOMID2" ? RENKOMID2 :hl2 // level round_price(x) => xx = int(x / syminfo.mintick) xx * syminfo.mintick // @function Track TakeProfits and StopLoss achievement for one or many of your buy/sell conditions. CHECK the commented section: "Function @manageTrade" (lines: 14 - 64) for Description // @param bool useSignal. // @param bool b_gameOVer. // @param bool b_gameOVer. // @param string bName. // @param string sName. // @param float buyEntrySource. // @param float sellEntrySource. // @param bool useTp1. // @param bool useTp2. // @param bool useTp3. // @param bool useTp4. // @param bool useTp5. // @param bool useTp6. // @param float tp1x. // @param float tp2x. // @param float tp3x. // @param float tp4x. // @param float tp5x. // @param float tp6x. // @param float slx. // @returns check commented section: "Function @manageTrade" (lines: 14 - 64). export manageTrade(bool useSignal, bool b_gameOVer, bool s_gameOver , string bName, string sName, float buyEntrySource, float sellEntrySource, bool useTp1, bool useTp2, bool useTp3, bool useTp4, bool useTp5, bool useTp6, float tp1x, float tp2x, float tp3x, float tp4x, float tp5x, float tp6x, float slx) => long = b_gameOVer short = s_gameOver BentryPrice = buyEntrySource SentryPrice = sellEntrySource // Position Management Tools pos = 0.0 pos := long? 1 : short? -1 : pos[1] longCond1 = long and pos[1]!= 1 shortCond1 = short and pos[1]!=-1 buySignal = long and longCond1 sellSignal = short and shortCond1 var int trade_state = 0 var float tp1 = na var float tp2 = na var float tp3 = na var float tp4 = na var float tp5 = na var float tp6 = na var float sl = na var float entry1 = na var int et = 0 var entry_hit = false var tp1_hit = false var tp2_hit = false var tp3_hit = false var tp4_hit = false var tp5_hit = false var tp6_hit = false var sl_hit = false line l11 = na line l2 = na line l3 = na line l4 = na line l5 = na line l6 = na line l7 = na line l8 = na label lb11 = na label lb2 = na label lb3 = na label lb4 = na label lb5 = na label lb6 = na label lb7 = na label lb8 = na label lb_entryHit = na label lb_buyTP1 = na label lb_buyTP2 = na label lb_buyTP3 = na label lb_buyTP4 = na label lb_buyTP5 = na label lb_buyTP6 = na label lb_buySL = na label lb_sellTP1 = na label lb_sellTP2 = na label lb_sellTP3 = na label lb_sellTP4 = na label lb_sellTP5 = na label lb_sellTP6 = na label lb_sellSL = na dt = time - time[1] if trade_state == 1 and useSignal if sellSignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and high >= tp1 tp1_hit := true if entry_hit == true and tp2_hit == false and high >= tp2 tp2_hit := true if entry_hit == true and tp3_hit == false and high >= tp3 tp3_hit := true if entry_hit == true and tp4_hit == false and high >= tp4 tp4_hit := true if entry_hit == true and tp5_hit == false and high >= tp5 tp5_hit := true if entry_hit == true and tp6_hit == false and high >= tp6 tp6_hit := true if entry_hit == true and low <= sl trade_state := 0 sl_hit := low <= sl if trade_state == -1 and useSignal if buySignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and low <= tp1 tp1_hit := true if entry_hit == true and tp2_hit == false and low <= tp2 tp2_hit := true if entry_hit == true and tp3_hit == false and low <= tp3 tp3_hit := true if entry_hit == true and tp4_hit == false and low <= tp4 tp4_hit := true if entry_hit == true and tp5_hit == false and low <= tp5 tp5_hit := true if entry_hit == true and tp6_hit == false and low <= tp6 tp6_hit := true if entry_hit == true and high >= sl trade_state := 0 sl_hit := high >= sl if trade_state == 0 and useSignal if buySignal trade_state := 1 entry_hit := false tp1_hit := false tp2_hit := false tp3_hit := false tp4_hit := false tp5_hit := false tp6_hit := false sl_hit := false entry1 := round_price(BentryPrice) et := time tp1 := round_price(entry1 * (1 + (tp1x / 100))) tp2 := round_price(entry1 * (1 + (tp2x / 100))) tp3 := round_price(entry1 * (1 + (tp3x / 100))) tp4 := round_price(entry1 * (1 + (tp4x / 100))) tp5 := round_price(entry1 * (1 + (tp5x / 100))) tp6 := round_price(entry1 * (1 + (tp6x / 100))) sl := round_price(entry1 * (1 - (slx / 100))) if sellSignal trade_state := -1 entry_hit := false tp1_hit := false tp2_hit := false tp3_hit := false tp4_hit := false tp5_hit := false tp6_hit := false sl_hit := false entry1 := round_price(SentryPrice) et := time tp1 := round_price(entry1 * (1 - (tp1x / 100))) tp2 := round_price(entry1 * (1 - (tp2x / 100))) tp3 := round_price(entry1 * (1 - (tp3x / 100))) tp4 := round_price(entry1 * (1 - (tp4x / 100))) tp5 := round_price(entry1 * (1 - (tp5x / 100))) tp6 := round_price(entry1 * (1 - (tp6x / 100))) sl := round_price(entry1 * (1 + (slx / 100))) if trade_state[1] == -1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1, text=str.tostring(sName) +"Entry:" + str.tostring(entry1),color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl, text=str.tostring(sName) +"Stop:" + str.tostring(sl),color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb3 := label.new(useTp1 ? time + dt * 4 : na, tp1,text=str.tostring(sName) +"TP1:" + str.tostring(tp1),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text=str.tostring(sName) +"TP2:" + str.tostring(tp2),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text=str.tostring(sName) +"TP3:" + str.tostring(tp3),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text=str.tostring(sName) +"TP4:" + str.tostring(tp4),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text=str.tostring(sName) +"TP5:" + str.tostring(tp5),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text=str.tostring(sName) +"TP6:" + str.tostring(tp6),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) if trade_state[1] == 1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) //TPS l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1,text=str.tostring(bName) +"Entry:" + str.tostring(entry1),color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl,text=str.tostring(bName) +"Stop:" + str.tostring(sl),color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) //TPS lb3 := label.new(useTp1 ? time + dt * 4 : na, tp1,text=str.tostring(bName) +"TP1:" + str.tostring(tp1),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text=str.tostring(bName) +"TP2:" + str.tostring(tp2),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text=str.tostring(bName) +"TP3:" + str.tostring(tp3),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text=str.tostring(bName) +"TP4:" + str.tostring(tp4),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text=str.tostring(bName) +"TP5:" + str.tostring(tp5),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text=str.tostring(bName) +"TP6:" + str.tostring(tp6),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) line.delete(l11[1]) label.delete(lb11[1]) line.delete(l2[1]) label.delete(lb2[1]) line.delete(l3[1]) label.delete(lb3[1]) line.delete(l4[1]) label.delete(lb4[1]) line.delete(l5[1]) label.delete(lb5[1]) line.delete(l6[1]) label.delete(lb6[1]) line.delete(l7[1]) label.delete(lb7[1]) line.delete(l8[1]) label.delete(lb8[1]) //-------------------------------------------------------------------- // ENTRY && EXIT //-------------------------------------------------------------------- official_buy = trade_state == 1 and trade_state != trade_state[1] official_sell = trade_state == -1 and trade_state != trade_state[1] entry_touched = not entry_hit[1] and entry_hit buyTP1_touched = trade_state[1] == 1 and tp1_hit and tp1_hit[1]==false buyTP2_touched = useTp2 and trade_state[1] == 1 and tp2_hit and tp2_hit[1]==false buyTP3_touched = useTp3 and trade_state[1] == 1 and tp3_hit and tp3_hit[1]==false buyTP4_touched = useTp4 and trade_state[1] == 1 and tp4_hit and tp4_hit[1]==false buyTP5_touched = useTp5 and trade_state[1] == 1 and tp5_hit and tp5_hit[1]==false buyTP6_touched = useTp6 and trade_state[1] == 1 and tp6_hit and tp6_hit[1]==false buySL_touched = trade_state[1] == 1 and sl_hit and tp1_hit==false sellTP1_touched = trade_state[1] == -1 and tp1_hit and tp1_hit[1]==false sellTP2_touched = useTp2 and trade_state[1] == -1 and tp2_hit and tp2_hit[1]==false sellTP3_touched = useTp3 and trade_state[1] == -1 and tp3_hit and tp3_hit[1]==false sellTP4_touched = useTp4 and trade_state[1] == -1 and tp4_hit and tp4_hit[1]==false sellTP5_touched = useTp5 and trade_state[1] == -1 and tp5_hit and tp5_hit[1]==false sellTP6_touched = useTp6 and trade_state[1] == -1 and tp6_hit and tp6_hit[1]==false sellSL_touched = trade_state[1] == -1 and sl_hit and tp1_hit==false if trade_state == 1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(bName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if trade_state == -1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(sName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP1_touched and useSignal lb_buyTP1 := label.new(bar_index, na, text=str.tostring(bName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP2_touched and useSignal lb_buyTP2 := label.new(bar_index, na, text=str.tostring(bName) +"TP2",color=color.yellow, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP3_touched and useSignal lb_buyTP3 := label.new(bar_index, na, text=str.tostring(bName) +"TP3",color=color.orange, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP4_touched and useSignal lb_buyTP4 := label.new(bar_index, na, text=str.tostring(bName) +"TP4",color=color.gray, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP5_touched and useSignal lb_buyTP5 := label.new(bar_index, na, text=str.tostring(bName) +"TP5",color=color.lime, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP6_touched and useSignal lb_buyTP6 := label.new(bar_index, na, text=str.tostring(bName) +"TP6",color=color.black, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buySL_touched and useSignal lb_buySL := label.new(bar_index, na, text=str.tostring(bName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if sellTP1_touched and useSignal lb_sellTP1 := label.new(bar_index, na, text=str.tostring(sName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP2_touched and useSignal lb_sellTP2 := label.new(bar_index, na, text=str.tostring(sName) +"TP2",color=color.yellow, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP3_touched and useSignal lb_sellTP3 := label.new(bar_index, na, text=str.tostring(sName) +"TP3",color=color.orange, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP4_touched and useSignal lb_sellTP4 := label.new(bar_index, na, text=str.tostring(sName) +"TP4",color=color.gray, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP5_touched and useSignal lb_sellTP5 := label.new(bar_index, na, text=str.tostring(sName) +"TP5",color=color.lime, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP6_touched and useSignal lb_sellTP6 := label.new(bar_index, na, text=str.tostring(sName) +"TP6",color=color.black, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellSL_touched and useSignal lb_sellSL := label.new(bar_index, na, text=str.tostring(sName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) [entry_touched, entry1, tp1, tp2, tp3, tp4, tp5, tp6, sl, official_buy, official_sell, buyTP1_touched, buyTP2_touched, buyTP3_touched, buyTP4_touched, buyTP5_touched, buyTP6_touched, buySL_touched , sellTP1_touched, sellTP2_touched, sellTP3_touched, sellTP4_touched, sellTP5_touched, sellTP6_touched, sellSL_touched] // ======================================================================================================================================================================================================================================================================= \\ // @function Track TakeProfits and StopLoss achievement for one or many of your buy/sell conditions. CHECK the commented section: "Function @manageFilterredTrade" (lines: 66 - 118) for Description // @param bool useSignal. // @param bool b_gameOVer. // @param bool longCancel. // @param bool s_gameOVer. // @param bool shortCancel. // @param string bName. // @param string sName. // @param float buyEntrySource. // @param float sellEntrySource. // @param bool useTp1. // @param bool useTp2. // @param bool useTp3. // @param bool useTp4. // @param bool useTp5. // @param bool useTp6. // @param float tp1x. // @param float tp2x. // @param float tp3x. // @param float tp4x. // @param float tp5x. // @param float tp6x. // @param float slx. // @returns check commented section: "Function @manageFilterredTrade" (lines: 66 - 118). export manageFilteredTrade(bool useSignal, bool b_gameOVer, bool longCancel, bool s_gameOver, bool shortCancel, string bName, string sName, float buyEntrySource, float sellEntrySource, bool useTp1, bool useTp2, bool useTp3, bool useTp4, bool useTp5, bool useTp6, float tp1x, float tp2x, float tp3x, float tp4x, float tp5x, float tp6x, float slx) => // long = b_gameOVer // short = s_gameOver BentryPrice = buyEntrySource SentryPrice = sellEntrySource // // Position Management Tools // pos = 0.0 // pos := long? 1 : short? -1 : pos[1] // longCond1 = b_gameOVer //and pos[1]!= 1 // shortCond1 = s_gameOver// and pos[1]!=-1 buySignal = b_gameOVer //and longCond1 sellSignal = s_gameOver // shortCond1 var int trade_state = 0 var float tp1 = na var float tp2 = na var float tp3 = na var float tp4 = na var float tp5 = na var float tp6 = na var float sl = na var float entry1 = na var int et = 0 var entry_hit = false var tp1_hit = false var tp2_hit = false var tp3_hit = false var tp4_hit = false var tp5_hit = false var tp6_hit = false var sl_hit = false line l11 = na line l2 = na line l3 = na line l4 = na line l5 = na line l6 = na line l7 = na line l8 = na label lb11 = na label lb2 = na label lb3 = na label lb4 = na label lb5 = na label lb6 = na label lb7 = na label lb8 = na label lb_entryHit = na label lb_buyTP1 = na label lb_buyTP2 = na label lb_buyTP3 = na label lb_buyTP4 = na label lb_buyTP5 = na label lb_buyTP6 = na label lb_buySL = na label lb_sellTP1 = na label lb_sellTP2 = na label lb_sellTP3 = na label lb_sellTP4 = na label lb_sellTP5 = na label lb_sellTP6 = na label lb_sellSL = na dt = time - time[1] if trade_state != 0 if longCancel trade_state := 0 if shortCancel trade_state := 0 if trade_state == 1 and useSignal if sellSignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and high >= tp1 tp1_hit := true if entry_hit == true and tp2_hit == false and high >= tp2 tp2_hit := true if entry_hit == true and tp3_hit == false and high >= tp3 tp3_hit := true if entry_hit == true and tp4_hit == false and high >= tp4 tp4_hit := true if entry_hit == true and tp5_hit == false and high >= tp5 tp5_hit := true if entry_hit == true and tp6_hit == false and high >= tp6 tp6_hit := true if entry_hit == true and low <= sl trade_state := 0 sl_hit := low <= sl if trade_state == -1 and useSignal if buySignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and low <= tp1 tp1_hit := true if entry_hit == true and tp2_hit == false and low <= tp2 tp2_hit := true if entry_hit == true and tp3_hit == false and low <= tp3 tp3_hit := true if entry_hit == true and tp4_hit == false and low <= tp4 tp4_hit := true if entry_hit == true and tp5_hit == false and low <= tp5 tp5_hit := true if entry_hit == true and tp6_hit == false and low <= tp6 tp6_hit := true if entry_hit == true and high >= sl trade_state := 0 sl_hit := high >= sl if trade_state == 0 and useSignal if buySignal trade_state := 1 entry_hit := false tp1_hit := false tp2_hit := false tp3_hit := false tp4_hit := false tp5_hit := false tp6_hit := false sl_hit := false entry1 := round_price(BentryPrice) et := time tp1 := round_price(entry1 * (1 + (tp1x / 100))) tp2 := round_price(entry1 * (1 + (tp2x / 100))) tp3 := round_price(entry1 * (1 + (tp3x / 100))) tp4 := round_price(entry1 * (1 + (tp4x / 100))) tp5 := round_price(entry1 * (1 + (tp5x / 100))) tp6 := round_price(entry1 * (1 + (tp6x / 100))) sl := round_price(entry1 * (1 - (slx / 100))) if sellSignal trade_state := -1 entry_hit := false tp1_hit := false tp2_hit := false tp3_hit := false tp4_hit := false tp5_hit := false tp6_hit := false sl_hit := false entry1 := round_price(SentryPrice) et := time tp1 := round_price(entry1 * (1 - (tp1x / 100))) tp2 := round_price(entry1 * (1 - (tp2x / 100))) tp3 := round_price(entry1 * (1 - (tp3x / 100))) tp4 := round_price(entry1 * (1 - (tp4x / 100))) tp5 := round_price(entry1 * (1 - (tp5x / 100))) tp6 := round_price(entry1 * (1 - (tp6x / 100))) sl := round_price(entry1 * (1 + (slx / 100))) if trade_state[1] == -1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1, text=str.tostring(sName) +"Entry:" + str.tostring(entry1),color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl, text=str.tostring(sName) +"Stop:" + str.tostring(sl),color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb3 := label.new(useTp1 ? time + dt * 4 : na, tp1,text=str.tostring(sName) +"TP1:" + str.tostring(tp1),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text=str.tostring(sName) +"TP2:" + str.tostring(tp2),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text=str.tostring(sName) +"TP3:" + str.tostring(tp3),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text=str.tostring(sName) +"TP4:" + str.tostring(tp4),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text=str.tostring(sName) +"TP5:" + str.tostring(tp5),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text=str.tostring(sName) +"TP6:" + str.tostring(tp6),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) if trade_state[1] == 1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) //TPS l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1,text=str.tostring(bName) +"Entry:" + str.tostring(entry1),color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl,text=str.tostring(bName) +"Stop:" + str.tostring(sl),color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) //TPS lb3 := label.new(useTp1 ? time + dt * 4 : na, tp1,text=str.tostring(bName) +"TP1:" + str.tostring(tp1),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text=str.tostring(bName) +"TP2:" + str.tostring(tp2),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text=str.tostring(bName) +"TP3:" + str.tostring(tp3),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text=str.tostring(bName) +"TP4:" + str.tostring(tp4),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text=str.tostring(bName) +"TP5:" + str.tostring(tp5),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text=str.tostring(bName) +"TP6:" + str.tostring(tp6),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) line.delete(l11[1]) label.delete(lb11[1]) line.delete(l2[1]) label.delete(lb2[1]) line.delete(l3[1]) label.delete(lb3[1]) line.delete(l4[1]) label.delete(lb4[1]) line.delete(l5[1]) label.delete(lb5[1]) line.delete(l6[1]) label.delete(lb6[1]) line.delete(l7[1]) label.delete(lb7[1]) line.delete(l8[1]) label.delete(lb8[1]) //-------------------------------------------------------------------- // ENTRY && EXIT //-------------------------------------------------------------------- official_buy = trade_state == 1 and trade_state != trade_state[1] official_sell = trade_state == -1 and trade_state != trade_state[1] entry_touched = not entry_hit[1] and entry_hit buyTP1_touched = trade_state[1] == 1 and tp1_hit and tp1_hit[1]==false buyTP2_touched = useTp2 and trade_state[1] == 1 and tp2_hit and tp2_hit[1]==false buyTP3_touched = useTp3 and trade_state[1] == 1 and tp3_hit and tp3_hit[1]==false buyTP4_touched = useTp4 and trade_state[1] == 1 and tp4_hit and tp4_hit[1]==false buyTP5_touched = useTp5 and trade_state[1] == 1 and tp5_hit and tp5_hit[1]==false buyTP6_touched = useTp6 and trade_state[1] == 1 and tp6_hit and tp6_hit[1]==false buySL_touched = trade_state[1] == 1 and sl_hit and tp1_hit==false sellTP1_touched = trade_state[1] == -1 and tp1_hit and tp1_hit[1]==false sellTP2_touched = useTp2 and trade_state[1] == -1 and tp2_hit and tp2_hit[1]==false sellTP3_touched = useTp3 and trade_state[1] == -1 and tp3_hit and tp3_hit[1]==false sellTP4_touched = useTp4 and trade_state[1] == -1 and tp4_hit and tp4_hit[1]==false sellTP5_touched = useTp5 and trade_state[1] == -1 and tp5_hit and tp5_hit[1]==false sellTP6_touched = useTp6 and trade_state[1] == -1 and tp6_hit and tp6_hit[1]==false sellSL_touched = trade_state[1] == -1 and sl_hit and tp1_hit==false if trade_state == 1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(bName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if trade_state == -1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(sName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP1_touched and useSignal lb_buyTP1 := label.new(bar_index, na, text=str.tostring(bName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP2_touched and useSignal lb_buyTP2 := label.new(bar_index, na, text=str.tostring(bName) +"TP2",color=color.yellow, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP3_touched and useSignal lb_buyTP3 := label.new(bar_index, na, text=str.tostring(bName) +"TP3",color=color.orange, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP4_touched and useSignal lb_buyTP4 := label.new(bar_index, na, text=str.tostring(bName) +"TP4",color=color.gray, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP5_touched and useSignal lb_buyTP5 := label.new(bar_index, na, text=str.tostring(bName) +"TP5",color=color.lime, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP6_touched and useSignal lb_buyTP6 := label.new(bar_index, na, text=str.tostring(bName) +"TP6",color=color.black, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buySL_touched and useSignal lb_buySL := label.new(bar_index, na, text=str.tostring(bName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if sellTP1_touched and useSignal lb_sellTP1 := label.new(bar_index, na, text=str.tostring(sName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP2_touched and useSignal lb_sellTP2 := label.new(bar_index, na, text=str.tostring(sName) +"TP2",color=color.yellow, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP3_touched and useSignal lb_sellTP3 := label.new(bar_index, na, text=str.tostring(sName) +"TP3",color=color.orange, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP4_touched and useSignal lb_sellTP4 := label.new(bar_index, na, text=str.tostring(sName) +"TP4",color=color.gray, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP5_touched and useSignal lb_sellTP5 := label.new(bar_index, na, text=str.tostring(sName) +"TP5",color=color.lime, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP6_touched and useSignal lb_sellTP6 := label.new(bar_index, na, text=str.tostring(sName) +"TP6",color=color.black, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellSL_touched and useSignal lb_sellSL := label.new(bar_index, na, text=str.tostring(sName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) [entry_touched, entry1, tp1, tp2, tp3, tp4, tp5, tp6, sl, official_buy, official_sell, buyTP1_touched, buyTP2_touched, buyTP3_touched, buyTP4_touched, buyTP5_touched, buyTP6_touched, buySL_touched , sellTP1_touched, sellTP2_touched, sellTP3_touched, sellTP4_touched, sellTP5_touched, sellTP6_touched, sellSL_touched] // ======================================================================================================================================================================================================================================================================= \\ // @function Track 1 TakeProfit Level and StopLoss achievement for one or many of your buy/sell conditions. CHECK the commented section: "Function @manageTrade" (lines: 120 - 144) for Description // @param bool useSignal. // @param bool b_gameOVer. // @param bool s_gameOVer. // @param string bName. // @param string sName. // @param float buyEntrySource. // @param float sellEntrySource. // @param float tp1x. // @param float slx. // @returns check commented section: "Function @manageLevel" (lines: 120 - 144). export manageLevel(bool useSignal, bool b_gameOVer, bool s_gameOver , string bName, string sName, float buyEntrySource, float sellEntrySource, float tp1x, float slx) => long = b_gameOVer short = s_gameOver BentryPrice = buyEntrySource SentryPrice = sellEntrySource // Position Management Tools pos = 0.0 pos := long? 1 : short? -1 : pos[1] longCond1 = long and pos[1]!= 1 shortCond1 = short and pos[1]!=-1 buySignal = long and longCond1 sellSignal = short and shortCond1 var int trade_state = 0 var float tp1 = na var float sl = na var float entry1 = na var int et = 0 var entry_hit = false var tp1_hit = false var sl_hit = false line l11 = na line l2 = na line l3 = na line l4 = na label lb11 = na label lb2 = na label lb3 = na label lb_entryHit = na label lb_buyTP1 = na label lb_buySL = na label lb_sellTP1 = na label lb_sellSL = na dt = time - time[1] if trade_state == 1 and useSignal if sellSignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and high >= tp1 tp1_hit := true if entry_hit == true and low <= sl trade_state := 0 sl_hit := low <= sl if trade_state == -1 and useSignal if buySignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and low <= tp1 tp1_hit := true if entry_hit == true and high >= sl trade_state := 0 sl_hit := high >= sl if trade_state == 0 and useSignal if buySignal trade_state := 1 entry_hit := false tp1_hit := false sl_hit := false entry1 := round_price(BentryPrice) et := time tp1 := round_price(entry1 * (1 + (tp1x / 100))) sl := round_price(entry1 * (1 - (slx / 100))) if sellSignal trade_state := -1 entry_hit := false tp1_hit := false sl_hit := false entry1 := round_price(SentryPrice) et := time tp1 := round_price(entry1 * (1 - (tp1x / 100))) sl := round_price(entry1 * (1 + (slx / 100))) if trade_state[1] == -1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) l3 := line.new(et, tp1, time + dt * 2, tp1, color=color.green, style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1, text=str.tostring(sName) +"Entry:" + str.tostring(entry1), color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl, text=str.tostring(sName) +"Stop:" + str.tostring(sl), color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb3 := label.new(time + dt * 4, tp1, text=str.tostring(sName) +"TP1:" + str.tostring(tp1), color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) if trade_state[1] == 1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) l3 := line.new(et, tp1, time + dt * 2, tp1, color=color.green, style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1, text=str.tostring(bName) +"Entry:" + str.tostring(entry1), color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl, text=str.tostring(bName) +"Stop:" + str.tostring(sl), color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb3 := label.new(time + dt * 4, tp1, text=str.tostring(bName) +"TP1:" + str.tostring(tp1), color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) line.delete(l11[1]) label.delete(lb11[1]) line.delete(l2[1]) label.delete(lb2[1]) line.delete(l3[1]) label.delete(lb3[1]) //-------------------------------------------------------------------- // ENTRY && EXIT //-------------------------------------------------------------------- official_buy = trade_state == 1 and trade_state != trade_state[1] official_sell = trade_state == -1 and trade_state != trade_state[1] entry_touched = not entry_hit[1] and entry_hit buyTP1_touched = trade_state[1] == 1 and tp1_hit and tp1_hit[1]==false buySL_touched = trade_state[1] == 1 and sl_hit and tp1_hit==false sellTP1_touched = trade_state[1] == -1 and tp1_hit and tp1_hit[1]==false sellSL_touched = trade_state[1] == -1 and sl_hit and tp1_hit==false if trade_state == 1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(bName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if trade_state == -1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(sName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP1_touched and useSignal lb_buyTP1 := label.new(bar_index, na, text=str.tostring(bName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buySL_touched and useSignal lb_buySL := label.new(bar_index, na, text=str.tostring(bName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if sellTP1_touched and useSignal lb_sellTP1 := label.new(bar_index, na, text=str.tostring(sName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellSL_touched and useSignal lb_sellSL := label.new(bar_index, na, text=str.tostring(sName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) [entry_touched, entry1, tp1, sl, official_buy, official_sell, buyTP1_touched, buySL_touched , sellTP1_touched, sellSL_touched] // ======================================================================================================================================================================================================================================================================= \\ // @function Track 1 TakeProfit Level and StopLoss achievement for one or many of your buy/sell conditions. CHECK the commented section: "Function @manageTrade" (lines: 146 - 172) for Description // @param bool useSignal. // @param bool b_gameOVer. // @param bool longCancel. // @param bool s_gameOVer. // @param bool shortCancel. // @param string bName. // @param string sName. // @param float buyEntrySource. // @param float sellEntrySource. // @param float tp1x. // @param float slx. // @returns check commented section: "Function @manageFilterredLevel" (lines: 146 - 172) . export manageFilterredLevel(bool useSignal, bool b_gameOVer, bool longCancel, bool s_gameOver, bool shortCancel, string bName, string sName, float buyEntrySource, float sellEntrySource, float tp1x, float slx) => long = b_gameOVer short = s_gameOver BentryPrice = buyEntrySource SentryPrice = sellEntrySource // Position Management Tools pos = 0.0 pos := long? 1 : short? -1 : pos[1] longCond1 = long and pos[1]!= 1 shortCond1 = short and pos[1]!=-1 buySignal = long and longCond1 sellSignal = short and shortCond1 var int trade_state = 0 var float tp1 = na var float sl = na var float entry1 = na var int et = 0 var entry_hit = false var tp1_hit = false var sl_hit = false line l11 = na line l2 = na line l3 = na line l4 = na label lb11 = na label lb2 = na label lb3 = na label lb_entryHit = na label lb_buyTP1 = na label lb_buySL = na label lb_sellTP1 = na label lb_sellSL = na dt = time - time[1] if trade_state != 0 if longCancel trade_state := 0 if shortCancel trade_state := 0 if trade_state == 1 and useSignal if sellSignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and high >= tp1 tp1_hit := true if entry_hit == true and low <= sl trade_state := 0 sl_hit := low <= sl if trade_state == -1 and useSignal if buySignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and low <= tp1 tp1_hit := true if entry_hit == true and high >= sl trade_state := 0 sl_hit := high >= sl if trade_state == 0 and useSignal if buySignal trade_state := 1 entry_hit := false tp1_hit := false sl_hit := false entry1 := round_price(BentryPrice) et := time tp1 := round_price(entry1 * (1 + (tp1x / 100))) sl := round_price(entry1 * (1 - (slx / 100))) if sellSignal trade_state := -1 entry_hit := false tp1_hit := false sl_hit := false entry1 := round_price(SentryPrice) et := time tp1 := round_price(entry1 * (1 - (tp1x / 100))) sl := round_price(entry1 * (1 + (slx / 100))) if trade_state[1] == -1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) l3 := line.new(et, tp1, time + dt * 2, tp1, color=color.green, style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1, text=str.tostring(sName) +"Entry:" + str.tostring(entry1), color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl, text=str.tostring(sName) +"Stop:" + str.tostring(sl), color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb3 := label.new(time + dt * 4, tp1, text=str.tostring(sName) +"TP1:" + str.tostring(tp1), color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) if trade_state[1] == 1 and useSignal if barstate.islast l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) l3 := line.new(et, tp1, time + dt * 2, tp1, color=color.green, style=line.style_solid,xloc = xloc.bar_time) lb11 := label.new(time + dt * 4, entry1, text=str.tostring(bName) +"Entry:" + str.tostring(entry1), color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb2 := label.new(time + dt * 4, sl, text=str.tostring(bName) +"Stop:" + str.tostring(sl), color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) lb3 := label.new(time + dt * 4, tp1, text=str.tostring(bName) +"TP1:" + str.tostring(tp1), color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) line.delete(l11[1]) label.delete(lb11[1]) line.delete(l2[1]) label.delete(lb2[1]) line.delete(l3[1]) label.delete(lb3[1]) //-------------------------------------------------------------------- // ENTRY && EXIT //-------------------------------------------------------------------- official_buy = trade_state == 1 and trade_state != trade_state[1] official_sell = trade_state == -1 and trade_state != trade_state[1] entry_touched = not entry_hit[1] and entry_hit buyTP1_touched = trade_state[1] == 1 and tp1_hit and tp1_hit[1]==false buySL_touched = trade_state[1] == 1 and sl_hit and tp1_hit==false sellTP1_touched = trade_state[1] == -1 and tp1_hit and tp1_hit[1]==false sellSL_touched = trade_state[1] == -1 and sl_hit and tp1_hit==false if trade_state == 1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(bName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if trade_state == -1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(sName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP1_touched and useSignal lb_buyTP1 := label.new(bar_index, na, text=str.tostring(bName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buySL_touched and useSignal lb_buySL := label.new(bar_index, na, text=str.tostring(bName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if sellTP1_touched and useSignal lb_sellTP1 := label.new(bar_index, na, text=str.tostring(sName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellSL_touched and useSignal lb_sellSL := label.new(bar_index, na, text=str.tostring(sName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) [entry_touched, entry1, tp1, sl, official_buy, official_sell, buyTP1_touched, buySL_touched , sellTP1_touched, sellSL_touched] // ======================================================================================================================================================================================================================================================================= \\ // @function Track TakeProfits and StopLoss achievement for one or many of your buy/sell conditions. CHECK the commented section: "Function @tpLevels" (lines: 66 - 118) for Description // @param bool useSignal. // @param bool b_gameOVer. // @param bool s_gameOVer. // @param string bName. // @param string sName. // @param float buyEntrySource. // @param float sellEntrySource. // @param bool useTp1. // @param bool useTp2. // @param bool useTp3. // @param bool useTp4. // @param bool useTp5. // @param bool useTp6. // @param float tp1x. // @param float tp2x. // @param float tp3x. // @param float tp4x. // @param float tp5x. // @param float tp6x. // @param float slx. // @returns check commented section: "Function @tpLevels" (lines: 175 - 226). export tpLevels(bool useSignal, bool b_gameOVer,bool s_gameOver, string bName, string sName, float buyEntrySource, float sellEntrySource, bool useTp1, bool useTp2, bool useTp3, bool useTp4, bool useTp5, bool useTp6, float tp1x, float tp2x, float tp3x, float tp4x, float tp5x, float tp6x, float slx) => BentryPrice = buyEntrySource SentryPrice = sellEntrySource buySignal = b_gameOVer sellSignal = s_gameOver var int trade_state = 0 var float tp1 = na var float tp2 = na var float tp3 = na var float tp4 = na var float tp5 = na var float tp6 = na var float sl = na var float entry1 = na var int et = 0 var entry_hit = false var tp1_hit = false var tp2_hit = false var tp3_hit = false var tp4_hit = false var tp5_hit = false var tp6_hit = false var sl_hit = false line l11 = na line l2 = na line l3 = na line l4 = na line l5 = na line l6 = na line l7 = na line l8 = na label lb11 = na label lb2 = na label lb3 = na label lb4 = na label lb5 = na label lb6 = na label lb7 = na label lb8 = na label lb_entryHit = na label lb_buyTP1 = na label lb_buyTP2 = na label lb_buyTP3 = na label lb_buyTP4 = na label lb_buyTP5 = na label lb_buyTP6 = na label lb_buySL = na label lb_sellTP1 = na label lb_sellTP2 = na label lb_sellTP3 = na label lb_sellTP4 = na label lb_sellTP5 = na label lb_sellTP6 = na label lb_sellSL = na dt = time - time[1] if trade_state == 1 and useSignal if sellSignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and high >= tp1 tp1_hit := true if entry_hit == true and tp2_hit == false and high >= tp2 tp2_hit := true if entry_hit == true and tp3_hit == false and high >= tp3 tp3_hit := true if entry_hit == true and tp4_hit == false and high >= tp4 tp4_hit := true if entry_hit == true and tp5_hit == false and high >= tp5 tp5_hit := true if entry_hit == true and tp6_hit == false and high >= tp6 tp6_hit := true if entry_hit == true and low <= sl trade_state := 0 sl_hit := low <= sl if trade_state == -1 and useSignal if buySignal trade_state := 0 if entry_hit == false and ta.cross(low ,entry1) or ta.cross(high, entry1) entry_hit := true if entry_hit == true and tp1_hit == false and low <= tp1 tp1_hit := true if entry_hit == true and tp2_hit == false and low <= tp2 tp2_hit := true if entry_hit == true and tp3_hit == false and low <= tp3 tp3_hit := true if entry_hit == true and tp4_hit == false and low <= tp4 tp4_hit := true if entry_hit == true and tp5_hit == false and low <= tp5 tp5_hit := true if entry_hit == true and tp6_hit == false and low <= tp6 tp6_hit := true if entry_hit == true and high >= sl trade_state := 0 sl_hit := high >= sl if trade_state == 0 and useSignal if buySignal trade_state := 1 entry_hit := false tp1_hit := false tp2_hit := false tp3_hit := false tp4_hit := false tp5_hit := false tp6_hit := false sl_hit := false entry1 := round_price(BentryPrice) et := time tp1 := round_price(entry1 * (1 + (tp1x / 100))) tp2 := round_price(entry1 * (1 + (tp2x / 100))) tp3 := round_price(entry1 * (1 + (tp3x / 100))) tp4 := round_price(entry1 * (1 + (tp4x / 100))) tp5 := round_price(entry1 * (1 + (tp5x / 100))) tp6 := round_price(entry1 * (1 + (tp6x / 100))) sl := round_price(entry1 * (1 - (slx / 100))) if sellSignal trade_state := -1 entry_hit := false tp1_hit := false tp2_hit := false tp3_hit := false tp4_hit := false tp5_hit := false tp6_hit := false sl_hit := false entry1 := round_price(SentryPrice) et := time tp1 := round_price(entry1 * (1 - (tp1x / 100))) tp2 := round_price(entry1 * (1 - (tp2x / 100))) tp3 := round_price(entry1 * (1 - (tp3x / 100))) tp4 := round_price(entry1 * (1 - (tp4x / 100))) tp5 := round_price(entry1 * (1 - (tp5x / 100))) tp6 := round_price(entry1 * (1 - (tp6x / 100))) sl := round_price(entry1 * (1 + (slx / 100))) if trade_state == -1 and useSignal l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green, style=line.style_solid, xloc = xloc.bar_time) l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green, style=line.style_solid, xloc = xloc.bar_time) l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green, style=line.style_solid, xloc = xloc.bar_time) l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green, style=line.style_solid, xloc = xloc.bar_time) l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green, style=line.style_solid, xloc = xloc.bar_time) l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green, style=line.style_solid, xloc = xloc.bar_time) // lb11 := label.new(time + dt * 4, entry1, text=str.tostring(sName) +"Entry:" + str.tostring(entry1),color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb2 := label.new(time + dt * 4, sl, text=str.tostring(sName) +"Stop:" + str.tostring(sl),color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb3 := label.new(useTp1 ? time + dt * 4 : na, tp1,text=str.tostring(sName) +"TP1:" + str.tostring(tp1),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text=str.tostring(sName) +"TP2:" + str.tostring(tp2),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text=str.tostring(sName) +"TP3:" + str.tostring(tp3),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text=str.tostring(sName) +"TP4:" + str.tostring(tp4),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text=str.tostring(sName) +"TP5:" + str.tostring(tp5),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text=str.tostring(sName) +"TP6:" + str.tostring(tp6),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) if trade_state == 1 and useSignal l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time) l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time) //TPS l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time) // lb11 := label.new(time + dt * 4, entry1,text=str.tostring(bName) +"Entry:" + str.tostring(entry1),color=color.blue,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb2 := label.new(time + dt * 4, sl,text=str.tostring(bName) +"Stop:" + str.tostring(sl),color=color.red,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // //TPS // lb3 := label.new(useTp1 ? time + dt * 4 : na, tp1,text=str.tostring(bName) +"TP1:" + str.tostring(tp1),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text=str.tostring(bName) +"TP2:" + str.tostring(tp2),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text=str.tostring(bName) +"TP3:" + str.tostring(tp3),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text=str.tostring(bName) +"TP4:" + str.tostring(tp4),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text=str.tostring(bName) +"TP5:" + str.tostring(tp5),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) // lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text=str.tostring(bName) +"TP6:" + str.tostring(tp6),color=color.green,textcolor=color.black,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal) //-------------------------------------------------------------------- // ENTRY && EXIT //-------------------------------------------------------------------- official_buy = trade_state == 1 and trade_state != trade_state[1] official_sell = trade_state == -1 and trade_state != trade_state[1] entry_touched = not entry_hit[1] and entry_hit buyTP1_touched = trade_state[1] == 1 and tp1_hit and tp1_hit[1]==false buyTP2_touched = useTp2 and trade_state[1] == 1 and tp2_hit and tp2_hit[1]==false buyTP3_touched = useTp3 and trade_state[1] == 1 and tp3_hit and tp3_hit[1]==false buyTP4_touched = useTp4 and trade_state[1] == 1 and tp4_hit and tp4_hit[1]==false buyTP5_touched = useTp5 and trade_state[1] == 1 and tp5_hit and tp5_hit[1]==false buyTP6_touched = useTp6 and trade_state[1] == 1 and tp6_hit and tp6_hit[1]==false buySL_touched = trade_state[1] == 1 and sl_hit and tp1_hit==false sellTP1_touched = trade_state[1] == -1 and tp1_hit and tp1_hit[1]==false sellTP2_touched = useTp2 and trade_state[1] == -1 and tp2_hit and tp2_hit[1]==false sellTP3_touched = useTp3 and trade_state[1] == -1 and tp3_hit and tp3_hit[1]==false sellTP4_touched = useTp4 and trade_state[1] == -1 and tp4_hit and tp4_hit[1]==false sellTP5_touched = useTp5 and trade_state[1] == -1 and tp5_hit and tp5_hit[1]==false sellTP6_touched = useTp6 and trade_state[1] == -1 and tp6_hit and tp6_hit[1]==false sellSL_touched = trade_state[1] == -1 and sl_hit and tp1_hit==false if trade_state == 1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(bName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if trade_state == -1 and entry_touched and useSignal lb_entryHit := label.new(bar_index, na, text=str.tostring(sName) +"entry",color=color.purple, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP1_touched and useSignal lb_buyTP1 := label.new(bar_index, na, text=str.tostring(bName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP2_touched and useSignal lb_buyTP2 := label.new(bar_index, na, text=str.tostring(bName) +"TP2",color=color.yellow, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP3_touched and useSignal lb_buyTP3 := label.new(bar_index, na, text=str.tostring(bName) +"TP3",color=color.orange, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP4_touched and useSignal lb_buyTP4 := label.new(bar_index, na, text=str.tostring(bName) +"TP4",color=color.gray, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP5_touched and useSignal lb_buyTP5 := label.new(bar_index, na, text=str.tostring(bName) +"TP5",color=color.lime, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buyTP6_touched and useSignal lb_buyTP6 := label.new(bar_index, na, text=str.tostring(bName) +"TP6",color=color.black, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if buySL_touched and useSignal lb_buySL := label.new(bar_index, na, text=str.tostring(bName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.abovebar, textalign=text.align_left,size=size.normal) if sellTP1_touched and useSignal lb_sellTP1 := label.new(bar_index, na, text=str.tostring(sName) +"TP1",color=color.green, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP2_touched and useSignal lb_sellTP2 := label.new(bar_index, na, text=str.tostring(sName) +"TP2",color=color.yellow, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP3_touched and useSignal lb_sellTP3 := label.new(bar_index, na, text=str.tostring(sName) +"TP3",color=color.orange, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP4_touched and useSignal lb_sellTP4 := label.new(bar_index, na, text=str.tostring(sName) +"TP4",color=color.gray, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP5_touched and useSignal lb_sellTP5 := label.new(bar_index, na, text=str.tostring(sName) +"TP5",color=color.lime, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellTP6_touched and useSignal lb_sellTP6 := label.new(bar_index, na, text=str.tostring(sName) +"TP6",color=color.black, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) if sellSL_touched and useSignal lb_sellSL := label.new(bar_index, na, text=str.tostring(sName) + "SL",color=color.red, textcolor=color.black, style=label.style_cross,xloc = xloc.bar_index, yloc=yloc.belowbar, textalign=text.align_left,size=size.normal) [entry_touched, entry1, tp1, tp2, tp3, tp4, tp5, tp6, sl, official_buy, official_sell, buyTP1_touched, buyTP2_touched, buyTP3_touched, buyTP4_touched, buyTP5_touched, buyTP6_touched, buySL_touched , sellTP1_touched, sellTP2_touched, sellTP3_touched, sellTP4_touched, sellTP5_touched, sellTP6_touched, sellSL_touched] // ======================================================================================================================================================================================================================================================================= \\
MiteTricks
https://www.tradingview.com/script/wO553f53-MiteTricks/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
23
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/ // ©kaigouthro // @version=5 // please let e know abot any bugs, // if you can fix them, please pass them back to me. // @description Matrix Global Registry. // Get, Set, automatic growing, universal get/set, // multimatrix dictionaries, multidicitionary matrixes.. // add slice matrixes of any type, sare one commoon global key registry // pull up an item from a category, and item name ie a table of info. // same cell needs a color, a size, a string, a value, etc.. // all of which can be pulled up with trhe same group id, and key id. // just swap which matrix you pull the value from. // this has a side benefit of notrepainting and recalculating // when pulling values, changing inputs.. // makes for very fast/clean usage.. library("MiteTricks", true) var int _REG_SIZE = input.int(3, 'Registry Size', step=1, minval=2, maxval=100) // @function Registry inititalizer // @returns registry of string mttrix type export initRegistry () => varip matrix<string> _REGISTRY = matrix.new<string> (4, 4, string(na)), matrix.set(_REGISTRY,0,0,' '), _REGISTRY // @function create bool type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is bool (na) // @returns bool matrix of specified size and fill, or blank 2x2 for registry use export newbool ( int _r = 2, int _c = 2, bool fill = na ) => var matrix<bool> _ValReg = matrix.new<bool> (_r , _c, bool ( fill ) ), _ValReg // @function create box type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is box (na) // @returns box matrix of specified size and fill, or blank 2x2 for registry use export newbox ( int _r = 2, int _c = 2, box fill = na ) => var matrix<box> _ValReg = matrix.new<box> (_r , _c, box ( fill ) ), _ValReg // @function create color type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is color (na) // @returns color matrix of specified size and fill, or blank 2x2 for registry use export newcolor ( int _r = 2, int _c = 2, color fill = na ) => var matrix<color> _ValReg = matrix.new<color> (_r , _c, color ( fill ) ), _ValReg // @function create float type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is float (na) // @returns float matrix of specified size and fill, or blank 2x2 for registry use export newfloat ( int _r = 2, int _c = 2, float fill = na ) => var matrix<float> _ValReg = matrix.new<float> (_r , _c, float ( fill ) ), _ValReg // @function create int type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is int (na) // @returns int matrix of specified size and fill, or blank 2x2 for registry use export newint ( int _r = 2, int _c = 2, int fill = na ) => var matrix<int> _ValReg = matrix.new<int> (_r , _c, int ( fill ) ), _ValReg // @function create label type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is label (na) // @returns label matrix of specified size and fill, or blank 2x2 for registry use export newlabel ( int _r = 2, int _c = 2, label fill = na ) => var matrix<label> _ValReg = matrix.new<label> (_r , _c, label ( fill ) ), _ValReg // @function create line type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is line (na) // @returns line matrix of specified size and fill, or blank 2x2 for registry use export newline ( int _r = 2, int _c = 2, line fill = na ) => var matrix<line> _ValReg = matrix.new<line> (_r , _c, line ( fill ) ), _ValReg // @function create linefill type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is linefill(na) // @returns linefill matrix of specified size and fill, or blank 2x2 for registry use export newlinefill (int _r = 2, int _c = 2, linefill fill = na ) => var matrix<linefill> _ValReg = matrix.new<linefill> (_r , _c, linefill ( fill ) ), _ValReg // @function create string type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is string (na) // @returns string matrix of specified size and fill, or blank 2x2 for registry use export newstring ( int _r = 2, int _c = 2, string fill = na ) => var matrix<string> _ValReg = matrix.new<string> (_r , _c, string ( fill ) ), _ValReg // @function create table type new matrix presized 2x2 for reg // @param optional row size // @param optional column size // @param optional fill value(default is table (na) // @returns table matrix of specified size and fill, or blank 2x2 for registry use export newtable ( int _r = 2, int _c = 2, table fill = na ) => var matrix<table> _ValReg = matrix.new<table> (_r , _c, table ( fill ) ), _ValReg // @function newfrom Matrix full of item input // @param INIT_FILL item to fill (2x2) the matri and set type. a type(na) works export newfrom ( bool INIT_FILL ) => var matrix<bool> _ValReg = matrix.new<bool> (2, 2, INIT_FILL), _ValReg export newfrom ( box INIT_FILL ) => var matrix<box> _ValReg = matrix.new<box> (2, 2, INIT_FILL), _ValReg export newfrom ( color INIT_FILL ) => var matrix<color> _ValReg = matrix.new<color> (2, 2, INIT_FILL), _ValReg export newfrom ( float INIT_FILL ) => var matrix<float> _ValReg = matrix.new<float> (2, 2, INIT_FILL), _ValReg export newfrom ( int INIT_FILL ) => var matrix<int> _ValReg = matrix.new<int> (2, 2, INIT_FILL), _ValReg export newfrom ( label INIT_FILL ) => var matrix<label> _ValReg = matrix.new<label> (2, 2, INIT_FILL), _ValReg export newfrom ( line INIT_FILL ) => var matrix<line> _ValReg = matrix.new<line> (2, 2, INIT_FILL), _ValReg export newfrom ( linefill INIT_FILL ) => var matrix<linefill> _ValReg = matrix.new<linefill> (2, 2, INIT_FILL), _ValReg export newfrom ( string INIT_FILL ) => var matrix<string> _ValReg = matrix.new<string> (2, 2, INIT_FILL), _ValReg export newfrom ( table INIT_FILL ) => var matrix<table> _ValReg = matrix.new<table> (2, 2, INIT_FILL), _ValReg // Helpers for NA vals (prevents errors on reads later on) _n(bool i)=> a = array.new<bool> (1000,i), array.fill(a,bool (na)), a _n(box i)=> a = array.new<box> (1000,i), array.fill(a,box (na)), a _n(color i)=> a = array.new<color> (1000,i), array.fill(a,color (na)), a _n(float i)=> a = array.new<float> (1000,i), array.fill(a,float (na)), a _n(int i)=> a = array.new<int> (1000,i), array.fill(a,int (na)), a _n(label i)=> a = array.new<label> (1000,i), array.fill(a,label (na)), a _n(line i)=> a = array.new<line> (1000,i), array.fill(a,line (na)), a _n(linefill i)=> a = array.new<linefill> (1000,i), array.fill(a,linefill (na)), a _n(string i)=> a = array.new<string> (1000,i), array.fill(a,string (na)), a _n(table i)=> a = array.new<table> (1000,i), array.fill(a,table (na)), a import kaigouthro/columns/1 import kaigouthro/rows/1 // ========== core functions > autosizer/setter getidx( _array , _KEY ) => _idx = array.indexof ( _array , _KEY ) , _idx :=_idx >= 0 ? _idx : na _checkrow(a,b,r) => aa = _n(matrix.get(a,0,0)) ab = _n(matrix.get(b,0,0)) id = array.indexof (r,array.get(aa,0)), size = array.size(r) -2 _rws = matrix.rows(a) if id >= size columns.push(a,array.slice(aa,0,_rws)) while matrix.columns(a) > matrix.columns (b) columns.push(b,array.slice(ab,0,_rws)) _checkcol(a,b,c) => aa = _n(matrix.get(a,0,0)) ab = _n(matrix.get(b,0,0)) id = array.indexof (c,array.get(aa,0)), size = array.size(c) -2 _cols = matrix.columns(a) if id >= size rows.push(a,array.slice(aa,0,_cols)) while matrix.rows(a) > matrix.rows (b) rows.push(b,array.slice(ab,0,_cols)) getcoords(_KEYREG, _GROUP, _KEY) => _G = getidx (matrix.row (_KEYREG , 0 ) , _GROUP ) _K = getidx (matrix.col (_KEYREG , na(_G) ? 0 : _G ), _KEY ) [_K,_G] // get function : // // value matrix of current value slice // key registry (master reg, or different registries for different sub-scripts // group - can be the idnumber of the group, or the string name.. // key - can be the idnumber of the key, or the string name.. // doesn't discriminate.. // // one 'get' to rule hem all! // get from any matrix by group name and item name or index nums.. // (same group and item name map to whichever key registry and they can OVERLAP!!!)\ // @function get Grabs value and returns single item // @param _VALS Matrix Values slice // @param _KEYREG Registry values matrix (strings) // @param _GROUP name of group/category or int group key // @param _KEY name of item to fetch from value rregistry or int key id // @returns item from vals re export get ( matrix<bool> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<box> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<color> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<float> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<int> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<label> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<line> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<string> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<linefill> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<table> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _KEY ) , out = matrix.get ( _VALS , _K , _G ) export get ( matrix<bool> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<box> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<color> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<float> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<int> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<label> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<line> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<string> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<linefill> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<table> _VALS, matrix<string> _KEYREG, string _GROUP , int _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP , _GROUP ) , out = matrix.get ( _VALS , _KEY , _G ) export get ( matrix<bool> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<box> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<color> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<float> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<int> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<label> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<line> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<string> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<linefill> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) export get ( matrix<table> _VALS, matrix<string> _KEYREG, int _GROUP , string _KEY ) => _K = getidx ( matrix.col( _KEYREG, _GROUP ) , _KEY ), matrix.get ( _VALS , _K , _GROUP ) // @function get Grabs value and returns single item // @param _VALS Matrix Values slice // @param _GROUP name of group/category // @param _KEY name of item to fetch from value rregistry export get ( matrix<bool> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<box> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<color> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<float> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<int> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<label> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<line> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<linefill> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<table> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) export get ( matrix<string> _VALS, int _GROUP , int _KEY ) => matrix.get( _VALS, _GROUP , _KEY) // get group index number for matrix retrieval fronm valuematrix // @function getgid // @param _KEYREG Reg to pull group id from // @param _GROUP group index int, or string name to get the other missing type export getgid( matrix<string> _KEYREG, string _GROUP ) => getidx(matrix.row(_KEYREG,0), _GROUP) export getgid( matrix<string> _KEYREG, int _GROUP ) => matrix.get(_KEYREG,0,_GROUP) // @function getkid // @param _KEYREG Reg to pull Key id from // @param _GROUP group index int, or string name // @param _KEY index of string key id to get it's ID int export getkid( matrix<string> _KEYREG, string _GROUP , string _KEY ) => getidx(matrix.col(_KEYREG, getgid(_KEYREG, _GROUP)),_KEY) export getkid( matrix<string> _KEYREG, int _GROUP , string _KEY ) => getidx(matrix.col(_KEYREG, _GROUP),_KEY) // grab key by any string and number combination from registry // @function getkey // @param _KEYREG Reg to pull Key id from // @param _GROUP group index int, or string name for getting key string // @param _KEY index of string key id to get it's match of other type export getkey( matrix<string> _KEYREG, string _GROUP , int _KEY ) => get( _KEYREG, getgid(_KEYREG, _GROUP) , _KEY) export getkey( matrix<string> _KEYREG, int _GROUP , string _KEY ) => get( _KEYREG, _GROUP , getidx(matrix.col(_KEYREG, _GROUP),_KEY)) export getkey( matrix<string> _KEYREG, int _GROUP , int _KEY ) => get( _KEYREG, _GROUP , _KEY) setitem(_VALMATRIX, _KEYREG, _GROUP, _KEY, _value ) => row = matrix.row ( _KEYREG , 0 ) group = array.indexof ( row , array.includes ( row , _GROUP ) ? _GROUP : string (na)) matrix.set ( _KEYREG , 0 , group , _GROUP) _checkrow ( _KEYREG , _VALMATRIX , row ) col = matrix.col ( _KEYREG , group ) key = array.indexof ( col , array.includes ( col , _KEY ) ? _KEY : string (na)) matrix.set ( _KEYREG , key , group , _KEY ) _checkcol ( _KEYREG , _VALMATRIX , col ) matrix.set ( _VALMATRIX , key, group, _value ) checkmissing(_missing,_VALS,_gid,_keyid) => _missing or (not _missing and (matrix.rows(_VALS) < _keyid + 2 or matrix.columns(_VALS) < _gid + 2)) setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) => [_gid,_keyid] = getcoords(_KEYREG, _GROUP, _KEY) _missing = na(_gid) or na(_keyid) // if key/group is new, create storage, else set to known location. if checkmissing(_missing,_VALS,_gid,_keyid) setitem ( _VALS, _KEYREG, _GROUP, _KEY, _value) else matrix.set(_VALS,_gid,_keyid,_value) // set to function // @function set items to registry and chosen matrix container // @param _VALS Values matrix container // @param _KEYREG Key registry // @param _GROUP (string) Group/Category name // @param _KEY (string) Key for item // @param _value item // @returns void export set ( matrix<bool> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , bool _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ), getcoords(_KEYREG, _GROUP, _KEY) export set ( matrix<box> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , box _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<color> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , color _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<float> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , float _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<int> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , int _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<label> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , label _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<line> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , line _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<linefill>_VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , linefill _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<string> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , string _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) export set ( matrix<table> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY , table _value) => setInternal ( _VALS , _KEYREG , _GROUP , _KEY , _value ) // delete item from registry and value from loaction, // replaces with the na val used for detection of first empty slot // @function del grroup id // @param _VALS Matrix Values slice // @param _KEYREG Registry values matrix (strings) // @param _GROUP name of group/category // @param _KEY name of item to Delete frrom values and key export del ( matrix<bool> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, bool (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<box> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, box (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<color> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, color (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<float> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, float (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<int> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, int (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<label> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, label (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<line> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, line (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<linefill> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, linefill(na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<table> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, table (na)), matrix.set(_KEYREG, _K, _G, string(na)) export del ( matrix<string> _VALS, matrix<string> _KEYREG, string _GROUP , string _KEY ) => [_K, _G] = getcoords( _KEYREG , _GROUP, _KEY ), matrix.set(_VALS, _K, _G, string (na)), matrix.set(_KEYREG, _K, _G, string(na)) // ========================================================= detach_internal(_val, _GROUP,_KEY,_VALUE) => var _KEYREG = initRegistry() set (_val , _KEYREG, _GROUP,_KEY,_VALUE) [_KEYREG, _val] // start a new registry and a single matrix along with it, autotypified and given first value. // @function detached make detached registry/val matrix // @param _GROUP Name of first group // @param _KEY Name of first item // @param _VALUE Item of any type, sets the output type too. // @returns [new key registry, initial values matrix, id of initial group, id of first key] export detached(string _GROUP, string _KEY, bool _VALUE ) => _vals = newbool () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, box _VALUE ) => _vals = newbox () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, color _VALUE ) => _vals = newcolor () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, float _VALUE ) => _vals = newfloat () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, int _VALUE ) => _vals = newint () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, label _VALUE ) => _vals = newlabel () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, line _VALUE ) => _vals = newline () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, linefill _VALUE ) => _vals = newlinefill() , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, string _VALUE ) => _vals = newstring () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] export detached(string _GROUP, string _KEY, table _VALUE ) => _vals = newtable () , [_r,_v] = detach_internal( _vals, _GROUP, _KEY, _VALUE) , [_g,_k] =getcoords(_r, _GROUP, _KEY), [_r,_v,_g,_k] // // ============================================================================ // // ====================== DEMO =========================== // // a few uses, there is ar more that can be done // // ie: a sepearate4 key registry for each ticker and multiportfolio management // // it's a low level tool, so there's raelly a mountain of options // // the setting/getting by name is mainly for passing globals into functions // // however within a local block, best to use the GID/KEYID for direct get/set // // init a registry for global // varip _KEYREG = initRegistry () // // init matrixes to hold different types of data // var _boolvals = newbool ( ) // var _floatvals = newfloat ( ) // var _mtx_lines = newline ( ) // var _mtx_boxes = newbox ( ) // var _mtx_fills = newlinefill ( ) // if barstate.islastconfirmedhistory // for i = 1 to 5 // _linetesta = line.new(last_bar_index - 5*i , close[5* i] , last_bar_index , close) // _linetestb = line.new(last_bar_index - math.floor(5*i*i-i), close[5* i+1] , last_bar_index , close) // _linefill = linefill.new(_linetesta, _linetestb, color.new(color.aqua,90)) // set(_mtx_lines , _KEYREG, 'Line A', str.tostring(i) +' line A', _linetesta ) // set(_mtx_lines , _KEYREG, 'Line B', str.tostring(i) +' line B', _linetestb ) // set(_mtx_fills , _KEYREG, 'Fills ', str.tostring(i) +' Fill ', _linefill ) // set ( _boolvals, _KEYREG, 'boxes', 'boolbox' , true ) // set ( _mtx_boxes , _KEYREG, 'boxes', 'boolbox' , box.new(time[10], math.max(high,high[10]), time, math.min(low,low[100]), text_color = color.white, bgcolor = color.new(color.black,90), // text = 'Mite Tricks', xloc=xloc.bar_time, border_style=line.style_dashed)) // // // =============================================================== // // // OTHER DEMO... // mtf(x) => request.security(syminfo.tickerid, '15', x) // /// example 2... cqan be expanded on vastly // // .. or as far as pine script will take you. // _ohlcreg = initRegistry() // //some mtx slices // _regfloats = newfloat() // _hist1_floats = newfloat() // _colorreg = newcolor() // var _MTFSTR = 'MTF' // var _REGSTR = 'Regular' // var _openSTR = 'open' // var _highSTR = 'high' // var _lowSTR = 'low' // var _closeSTR = 'close' // set(_regfloats , _ohlcreg, _REGSTR , _openSTR , open ) // set(_regfloats , _ohlcreg, _REGSTR , _highSTR , high ) // set(_regfloats , _ohlcreg, _REGSTR , _lowSTR , low ) // set(_regfloats , _ohlcreg, _REGSTR , _closeSTR , close ) // set(_regfloats , _ohlcreg, _MTFSTR , _openSTR , mtf(open )) // set(_regfloats , _ohlcreg, _MTFSTR , _highSTR , mtf(high )) // set(_regfloats , _ohlcreg, _MTFSTR , _lowSTR , mtf(low )) // set(_regfloats , _ohlcreg, _MTFSTR , _closeSTR , mtf(close )) // set(_hist1_floats, _ohlcreg, _REGSTR , _openSTR , open [1]) // set(_hist1_floats, _ohlcreg, _REGSTR , _highSTR , high [1]) // set(_hist1_floats, _ohlcreg, _REGSTR , _lowSTR , low [1]) // set(_hist1_floats, _ohlcreg, _REGSTR , _closeSTR , close [1]) // set(_hist1_floats, _ohlcreg, _MTFSTR , _openSTR , mtf(open [1] )) // set(_hist1_floats, _ohlcreg, _MTFSTR , _highSTR , mtf(high [1] )) // set(_hist1_floats, _ohlcreg, _MTFSTR , _lowSTR , mtf(low [1] )) // set(_hist1_floats, _ohlcreg, _MTFSTR , _closeSTR , mtf(close[1] )) // // add colors for these specific ones.. if a value is attempted to retrieve // // but the spot on the value matrix is empty, it will siimple pull a typecast na. // // so these colors show when specidfied.. will have to make a global or a '*' for any' // // you can have multiple overlapping key regiustries, say each with a differnt tite for the groups andcategories.. // // write into one key registry and pull up by other names and titles to another key registry. // set(_colorreg , _ohlcreg, _REGSTR, _openSTR , color.red ) // set(_colorreg , _ohlcreg, _REGSTR, _highSTR , color.green ) // set(_colorreg , _ohlcreg, _REGSTR, _lowSTR , color.blue ) // set(_colorreg , _ohlcreg, _REGSTR, _closeSTR , color.orange) // set(_colorreg , _ohlcreg, _MTFSTR, _openSTR , color.fuchsia ) // set(_colorreg , _ohlcreg, _MTFSTR, _highSTR , color.lime ) // set(_colorreg , _ohlcreg, _MTFSTR, _lowSTR , color.aqua ) // set(_colorreg , _ohlcreg, _MTFSTR, _closeSTR , color.yellow) // // plot those 4.. // plot(get(_regfloats,_ohlcreg, _REGSTR, _openSTR ), 'Normal open ' , get(_colorreg , _ohlcreg, _REGSTR, _openSTR)) // plot(get(_regfloats,_ohlcreg, _REGSTR, _highSTR ), 'Normal high ' , get(_colorreg , _ohlcreg, _REGSTR, _highSTR)) // plot(get(_regfloats,_ohlcreg, _REGSTR, _lowSTR ), 'Normal low ' , get(_colorreg , _ohlcreg, _REGSTR, _lowSTR )) // plot(get(_regfloats,_ohlcreg, _REGSTR, _closeSTR), 'Normal close ' , get(_colorreg , _ohlcreg, _REGSTR, _closeSTR)) // // or select one amongst them all for switchng around.. // // the retrieval now can select along any axis... // // which matrix to use // valmatrix = switch input.int(0,'Pick Matrix slice, reg/hist') // 0 => _regfloats // 1 => _hist1_floats // /// which group to pull from // _barchoice = input.string(_REGSTR, 'MTF or REg', options = [_REGSTR,_MTFSTR]) // /// which value from that group-. // valuechoice = switch input.int(1,'Val O/H/L/C',1,4) // 1 => _openSTR // 2 => _highSTR // 3 => _lowSTR // 4 => _closeSTR // plot(get(valmatrix , _ohlcreg, _barchoice , valuechoice), ' chosenval', get(_colorreg , _ohlcreg, _barchoice , valuechoice),2) // import kaigouthro/matrixautotable/9 as mtb // mtb.matrixtable(_KEYREG , tableYpos = 'bottom', tableXpos = 'right' ) // mtb.matrixtable(_regfloats ,_ohlcreg, _colorreg, tableYpos = 'bottom', tableXpos = 'center')
HelperFunctions
https://www.tradingview.com/script/lt61p5GI-HelperFunctions/
cryptofnq
https://www.tradingview.com/u/cryptofnq/
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/ // © cryptofnq //@version=5 // @description apply one of Pine Script's built-in smoothing or oscillator functions to a series library("HelperFunctions", false) // @function Apply a built-in smoothing function to a series. // @param method string One of['ema', 'sma', 'wma', 'vwma', 'rma', 'hma', 'none'] // @param length int The number of bars to use for the smoothing function // @param source series The series to smooth // @returns A smoothed series based on the input source export apply_smoothing(simple string method='ema', float source=hl2, simple int length=2) => smoothed = switch method 'ema' => ta.ema(source, length) 'sma' => ta.sma(source, length) 'wma' => ta.wma(source, length) 'vwma' => ta.vwma(source, length) 'rma' => ta.rma(source, length) 'hma' => ta.hma(source, length) // @function Create a basic oscillator that requres no input. // @param method string One of ['wvad', 'iii'] // @returns A series which oscillates around zero export create_basic_oscillator(simple string method='wvad') => oscillator = switch method // Williams Variable Accumulation/Distribution 'wvad' => ta.wvad // Intraday Intensity Index // adjusted to be between -1 and +1 'iii' => ta.iii * 1000 // @function Create a simple oscillator from a series. // @param method string One of ['wpr'] // @param length int The number of bars to use in oscillator calculation // @returns A series which oscillates around zero export create_simple_oscillator(simple string method='wpr', simple int length=5) => oscillator = switch method // Williams %R returns values between 0 and -100 // centre the oscillator by adding 50 'wpr' => ta.wpr(length) + 50 // @function Create a single length oscillator from a series. // @param method string One of ['change', 'cmo', 'rank', 'roc', 'rsi'] // @param source series The series on which to base the oscillator // @param length int The number of bars to use in oscillator calculation // @returns A series which oscillates around zero export create_single_oscillator(simple string method='rsi', float source=close, simple int length=5) => oscillator = switch method // Relative Strength Index // centre oscillator on zero 'rsi' =>ta.rsi(source, length) - 50 // Rate Of Change 'roc' => ta.roc(source, length) // Percent of previous bars less than current // centre oscillator on zero 'rank' => ta.percentrank(source, length) - 50 // Chande Momentum Oscillator 'cmo' => ta.cmo(source, length) // Change over the length 'change' => ta.change(source, length) // @function Create a dual length oscillator from a series. // @param method string One of ['tsi'] // @param src series The series on which to base the oscillator // @param fastLength int The number of bars to use in fast oscillator calculation // @param slowLength int The number of bars to use in slow oscillator calculation // @returns A series which oscillates around zero export create_dual_oscillator(simple string method='tsi', float source=hl2, simple int fastLength=5, simple int slowLength=10) => oscillator = switch method // True Strength Index 'tsi' => ta.tsi(source, fastLength, slowLength) var srcTip = 'Select the series to be the base of the oscillator' src = input.source(close,'Source', tooltip = srcTip, group = 'Global') functionTypeTip = 'Select either oscillator or smoothing and define a method below' functionType = input.string('smoothing', 'Function Type', ['smoothing', 'oscillator'], group = 'Global') smoothingMethod = input.string('ema', 'Method', ['ema', 'sma', 'wma', 'vwma', 'rma', 'hma'], inline='smoothing', group = 'Smoothing') smoothingLengthTip = 'How many bars to use in the smoothing calculations' smoothingLength = input.int(5, 'Length', minval=2, inline='smoothing', group = 'Smoothing', tooltip = smoothingLengthTip) oscillatorMethodTip = 'Select the type of oscillator to create, each type requires different inputs: "wvad" & "iii" require no inputs. "wpr" requires a length. "change", "cmo", "obv", "rank", "roc" & "rsi" require a length and a source. "tsi" requires two lengths and a source.' oscillatorMethod = input.string('rsi', 'Method', ['wvad', 'iii', 'wpr', 'change', 'cmo', 'rank', 'roc', 'rsi', 'tsi'], tooltip=oscillatorMethodTip, group = 'Oscillator') oscillatorLengthTip = 'Select the number of bars to use in the oscillator calculation' oscillatorLength = input.int(5, 'Length', minval=1, tooltip=oscillatorLengthTip, group = 'Simple & Single Oscillator') oscillatorFastLength = input.int(5, 'Fast Length', minval=1, tooltip=oscillatorLengthTip, inline='dual', group = 'Dual Length Oscillator') oscillatorSlowLength = input.int(10, 'Slow Length', minval=1, tooltip=oscillatorLengthTip, inline='dual', group = 'Dual Length Oscillator') plotSeries = switch functionType 'smoothing' => apply_smoothing(smoothingMethod, src, smoothingLength) 'oscillator' => if oscillatorMethod == 'wvad' or oscillatorMethod == 'iii' or oscillatorMethod == 'obv' create_basic_oscillator(oscillatorMethod) else if oscillatorMethod == 'wpr' create_simple_oscillator(oscillatorMethod, oscillatorLength) else if oscillatorMethod == 'change' or oscillatorMethod == 'cmo' or oscillatorMethod == 'rank' or oscillatorMethod == 'roc' or oscillatorMethod == 'rsi' create_single_oscillator(oscillatorMethod, src, oscillatorLength) else if oscillatorMethod == 'tsi' create_dual_oscillator(oscillatorMethod, src, oscillatorFastLength, oscillatorSlowLength) else create_single_oscillator(oscillatorMethod, src, oscillatorLength) plot(plotSeries, color=color.blue, title='Helper Function Plot')
X48_LibaryStrategyStatus
https://www.tradingview.com/script/Vg4LmYYm-X48-LibaryStrategyStatus/
X4815162342
https://www.tradingview.com/u/X4815162342/
46
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/ // © X4815162342 //@version=5 // Thanks For Code by Cayoshi this code back up for my strategy, make sure when use libary direct the code in my libary //เรียกใช้ library //import X4815162342/X48_LibaryStrategyStatus/1 as fuLi //แสดงผล Backtest //show_Net = input.bool(true,'Show Net', inline = 'Lnet') //position_ = input.string('bottom_center','Position', options = ['top_right','middle_right','bottom_right','top_center','middle_center','bottom_center','middle_left','bottom_left'] , inline = 'Lnet') //size_i = input.string('auto','size', options = ['auto','tiny','small','normal'] , inline = 'Lnet') //color_Net = input.color(color.blue,"" , inline = 'Lnet') //fuLi.NetProfit_Show(show_Net , position_ , size_i, color_Net ) library("X48_LibaryStrategyStatus") export Win_Loss_Show() => //== var entryP = 0. //== var exitP = 0. //== //== if(ta.change(strategy.position_size) and strategy.position_size == 0) //== //== entryP := nz(strategy.closedtrades.entry_price(strategy.closedtrades-1)) //== exitP := nz(strategy.closedtrades.exit_price(strategy.closedtrades-1)) //== buy_entryP = entryP //== sell_exitP = exitP //== var buy_SELL = 2 //== buy_SELL := strategy.position_size > 0 ? 0 : strategy.position_size < 0 ? 1 : 2 win = nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy_entryP < sell_exitP loss = nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy_entryP > sell_exitP equal = nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy_entryP == sell_exitP [win,loss,equal] export NetProfit_Show(bool show_Net ,string position_ ,string size_i,color color_Net ) => percenProfit = (strategy.netprofit / strategy.initial_capital ) *100 colprofit = percenProfit < 0 ? color.red : color.white profitFac = strategy.grossprofit / strategy.grossloss percenwin = (strategy.wintrades / strategy.closedtrades) * 100 Netprofit = str.tostring(strategy.netprofit,'#,###.##') +'\n'+str.tostring(percenProfit,'#,###.##')+' % ' win = str.tostring(percenwin,'#.##')+' % ' profitFactor = str.tostring(profitFac,'#.###') close_Trade = str.tostring(strategy.closedtrades,'#,###') + '\n' + 'W: '+str.tostring(strategy.wintrades)+' | L: '+ str.tostring(strategy.losstrades) max_drawdown =str.tostring( strategy.max_drawdown,'#,###.##') tra = 80 position_CH = position_ == 'bottom_right' ? position.bottom_right : position_ == 'bottom_left' ? position.bottom_left : position_ == 'bottom_center' ? position.bottom_center : position_ == 'middle_right' ? position.middle_right : position_ == 'middle_left' ? position.middle_left : position_ == 'middle_center' ? position.middle_center : position_ == 'top_right' ? position.top_right : position_ == 'top_center' ? position.top_center : position.bottom_right size_ = size_i == 'auto' ? size.auto : size_i == 'tiny' ? size.tiny : size_i == 'small' ? size.small : size_i == 'small' ? size.normal : size.auto if show_Net table table_Net = table.new(position_CH , 5,50 ,border_color = color.black, border_width = 1 ) table.cell(table_Net, 0,1, 'Netprofit',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) ) table.cell(table_Net, 1,1, 'CloseTrade',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) ) table.cell(table_Net, 2,1, 'Win',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) ) table.cell(table_Net, 3,1, 'Factor',text_size =size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) ) table.cell(table_Net, 4,1, 'Drawdown',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) ) table.cell(table_Net, 0, 2, Netprofit,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(colprofit,0)) table.cell(table_Net, 1, 2, close_Trade,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(color.white,0)) table.cell(table_Net, 2, 2, win ,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(color.white,0) ) table.cell(table_Net, 3, 2, profitFactor,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(colprofit,0)) table.cell(table_Net, 4, 2, max_drawdown,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(color.red,0)) export Count_Bar_Back_Test(bool Back_Test ,int Back_Test_bar_start,int Back_Test_step_start,int Back_Test_bar_end, int Back_Test_step_end ,bool i_dateFilter,int i_fromYear,int i_fromMonth,int i_fromDay,int i_toYear,int i_toMonth,int i_toDay ) => count_backtest_bar_start = Back_Test ? ( Back_Test_bar_start * Back_Test_step_start) : 0 count_backtest_bar_end = Back_Test ? last_bar_index - ( Back_Test_bar_end* Back_Test_step_end) : last_bar_index BarBackTEST = bar_index >= count_backtest_bar_start and bar_index <= count_backtest_bar_end maxbar = last_bar_index / Back_Test_step_start fromDate = timestamp(i_fromYear, i_fromMonth, i_fromDay, 00, 00) toDate = time < timestamp(i_toYear, i_toMonth, i_toDay, 23, 59) ? time : timestamp(i_toYear, i_toMonth, i_toDay, 23, 59) date_start_entry = i_dateFilter ? fromDate < time ? time : fromDate : time var begin = date_start_entry days = (toDate - begin) / (24 * 60 * 60 * 1000) mess1 = str.tostring(days, "#.0 days /") + str.tostring(days/30, "#.0 month /") + str.tostring( strategy.closedtrades / days, "#.0 ") + 'ครั้งต่อวัน' mess2 = Back_Test ? count_backtest_bar_start > last_bar_index ? ('start ' + str.tostring( count_backtest_bar_start,'#,###.##') +'....Over Bar' +' MAX:'+ str.tostring(maxbar,'#,###') ) : ('start ' + str.tostring( count_backtest_bar_start,'#,###.##') +' MAX:'+ str.tostring(maxbar,'#,###') ) : 'start 0 Bar MAX:'+ str.tostring(maxbar,'#,###') mess3 = ( Back_Test ? ('end ' + str.tostring(last_bar_index ,'#,###.##') +' - ' + str.tostring( Back_Test_bar_end* Back_Test_step_end) + ' = ' + str.tostring(count_backtest_bar_end ,'#,###.##') ) : 'end ' +str.tostring(count_backtest_bar_end ,'#,###.##') ) + ' Bar' table table_countbar = table.new(position.bottom_right, 1,50 ,border_color = color.orange) table.cell(table_countbar,0, 0, mess1, bgcolor =color.new(color.blue,80),text_color =color.new(color.white,0) ) table.cell(table_countbar, 0, 1, mess2, bgcolor = color.new(color.red,80),text_color = count_backtest_bar_start > last_bar_index ? color.new(color.red,0) : color.new(color.white,15) ) table.cell(table_countbar, 0, 2, mess3, bgcolor = color.new(color.red,80),text_color =color.new(color.white,0) ) x = BarBackTEST and (not i_dateFilter or (time >= fromDate and time <= toDate)) export percen(float pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na) export curProfitInPts() => if strategy.position_size > 0 (high - strategy.position_avg_price) / syminfo.mintick else if strategy.position_size < 0 (strategy.position_avg_price - low) / syminfo.mintick else 0 export calcStopLossPrice(float OffsetPts) => var float price = 0. if strategy.position_size > 0 //ราคาเปิด - price := strategy.position_avg_price - OffsetPts * syminfo.mintick else if strategy.position_size < 0 price := strategy.position_avg_price + OffsetPts * syminfo.mintick else price := na export calcProfitTrgtPrice(float OffsetPts) => calcStopLossPrice(-OffsetPts) export getCurrentStage(float tp1 ,float tp2) => var stage = 0 if strategy.position_size == 0 stage := 0 if stage == 0 and strategy.position_size != 0 stage := 1 else if stage == 1 and curProfitInPts() >= tp1// 5 stage := 2 else if stage == 2 and curProfitInPts() >= tp2//10 stage := 3 stage export calcTrailingAmountLevel(float points) => var float level = na level := calcProfitTrgtPrice(points) if not na(level) if strategy.position_size > 0 if not na(level[1]) level := math.max(level[1], level) if not na(level) level := math.max(high, level) else if strategy.position_size < 0 if not na(level[1]) level := math.min(level[1], level) if not na(level) level := math.min(low, level) export calcTrailingOffsetLevel(float points, float offset) => float result = na amountLevel = calcTrailingAmountLevel(points) if strategy.position_size > 0 trailActiveDiff = amountLevel - calcProfitTrgtPrice(points) if trailActiveDiff > 0 result := trailActiveDiff + calcProfitTrgtPrice(offset) else if strategy.position_size < 0 trailActiveDiff = calcProfitTrgtPrice(points) - amountLevel if trailActiveDiff > 0 result := calcProfitTrgtPrice(offset) - trailActiveDiff result export trailing_3step(float tp1_,float tp2_,float tp3_,bool activateTrailingOnThirdStep,float sl_ ) => var float tp1 = 0. tp1 := percen(tp1_) var float tp2 = 0. tp2 := percen(tp2_) var float tp3 = 0. tp3 := percen(tp3_) var float sl = 0. sl := percen(sl_) float stopLevel = na float trailOffsetLevel = na float c1 = calcTrailingAmountLevel(tp3) float c2 = calcProfitTrgtPrice(tp3) float profitLevel = activateTrailingOnThirdStep ? c1 : c2 curStage = getCurrentStage(tp1,tp2) if curStage == 1 stopLevel := calcStopLossPrice(sl) strategy.exit("x", loss = sl, profit = tp3, comment = "sl or tp3") else if curStage == 2 stopLevel := calcStopLossPrice(0) strategy.exit("x", stop = stopLevel, profit = tp3, comment = "breakeven or tp3") else if curStage == 3 stopLevel := calcStopLossPrice(-tp1) if activateTrailingOnThirdStep strategy.exit("x", stop = stopLevel, trail_points = tp3, trail_offset = tp3-tp2, comment = "stop tp1 or trailing tp3 with offset tp2") else strategy.exit("x", stop = stopLevel, profit = tp3, comment = "tp1 or tp3") else strategy.cancel("x")
FunctionLAPACKdtrsm
https://www.tradingview.com/script/lbXBXINm-FunctionLAPACKdtrsm/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
20
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 subroutine in the LAPACK:linear algebra package, used to solve one of the following matrix equations: // // op( A )*X = alpha*B, or X*op( A ) = alpha*B, // // where alpha is a scalar, X and B are m by n matrices, A is a unit, or // non-unit, upper or lower triangular matrix and op( A ) is one of // // op( A ) = A or op( A ) = A**T. // // The matrix X is overwritten on B. // // reference: // https://netlib.org/lapack/explore-html/de/da7/dtrsm_8f_source.html#l00180 library(title='FunctionLAPACKdtrsm') // { helper functions: // https://netlib.org/lapack/explore-html/d0/dbf/_b_l_a_s_2_s_r_c_2lsame_8f_source.html#l00052 // test if letter in 'a' equals 'b' regardless of case. lsame (string a, string b) => str.lower(a) == str.lower(b) // // https://netlib.org/lapack/explore-html/d1/dc0/_b_l_a_s_2_s_r_c_2xerbla_8f_source.html#l00059 xerbla (string srname, int info) => runtime.error(str.format(' ** On entry to {0} parameter number {1} had an illegal value', srname, info)) // end: helper functions } // { brief: DTRSM // // =========== DOCUMENTATION =========== // // Online html documentation available at // http://www.netlib.org/lapack/explore-html/ // // Definition: // =========== // // SUBROUTINE DTRSM(SIDE,UPLO,TRANSA,DIAG,M,N,ALPHA,A,LDA,B,LDB) // // .. Scalar Arguments .. // DOUBLE PRECISION ALPHA // INTEGER LDA,LDB,M,N // CHARACTER DIAG,SIDE,TRANSA,UPLO // .. // .. Array Arguments .. // DOUBLE PRECISION A(LDA,*),B(LDB,*) // .. // // // \par Purpose: // ============= // // \verbatim // // DTRSM solves one of the matrix equations // // op( A )*X = alpha*B, or X*op( A ) = alpha*B, // // where alpha is a scalar, X and B are m by n matrices, A is a unit, or // non-unit, upper or lower triangular matrix and op( A ) is one of // // op( A ) = A or op( A ) = A**T. // // The matrix X is overwritten on B. // \endverbatim // // Arguments: // ========== // // \param[in] SIDE // \verbatim // SIDE is CHARACTER*1 // On entry, SIDE specifies whether op( A ) appears on the left // or right of X as follows: // // SIDE = 'L' or 'l' op( A )*X = alpha*B. // // SIDE = 'R' or 'r' X*op( A ) = alpha*B. // \endverbatim // // \param[in] UPLO // \verbatim // UPLO is CHARACTER*1 // On entry, UPLO specifies whether the matrix A is an upper or // lower triangular matrix as follows: // // UPLO = 'U' or 'u' A is an upper triangular matrix. // // UPLO = 'L' or 'l' A is a lower triangular matrix. // \endverbatim // // \param[in] TRANSA // \verbatim // TRANSA is CHARACTER*1 // On entry, TRANSA specifies the form of op( A ) to be used in // the matrix multiplication as follows: // // TRANSA = 'N' or 'n' op( A ) = A. // // TRANSA = 'T' or 't' op( A ) = A**T. // // TRANSA = 'C' or 'c' op( A ) = A**T. // \endverbatim // // \param[in] DIAG // \verbatim // DIAG is CHARACTER*1 // On entry, DIAG specifies whether or not A is unit triangular // as follows: // // DIAG = 'U' or 'u' A is assumed to be unit triangular. // // DIAG = 'N' or 'n' A is not assumed to be unit // triangular. // \endverbatim // // \param[in] M // \verbatim // M is INTEGER // On entry, M specifies the number of rows of B. M must be at // least zero. // \endverbatim // // \param[in] N // \verbatim // N is INTEGER // On entry, N specifies the number of columns of B. N must be // at least zero. // \endverbatim // // \param[in] ALPHA // \verbatim // ALPHA is DOUBLE PRECISION. // On entry, ALPHA specifies the scalar alpha. When alpha is // zero then A is not referenced and B need not be set before // entry. // \endverbatim // // \param[in] A // \verbatim // A is DOUBLE PRECISION array, dimension ( LDA, k ), // where k is m when SIDE = 'L' or 'l' // and k is n when SIDE = 'R' or 'r'. // Before entry with UPLO = 'U' or 'u', the leading k by k // upper triangular part of the array A must contain the upper // triangular matrix and the strictly lower triangular part of // A is not referenced. // Before entry with UPLO = 'L' or 'l', the leading k by k // lower triangular part of the array A must contain the lower // triangular matrix and the strictly upper triangular part of // A is not referenced. // Note that when DIAG = 'U' or 'u', the diagonal elements of // A are not referenced either, but are assumed to be unity. // \endverbatim // // \param[in] LDA // \verbatim // LDA is INTEGER // On entry, LDA specifies the first dimension of A as declared // in the calling (sub) program. When SIDE = 'L' or 'l' then // LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' // then LDA must be at least max( 1, n ). // \endverbatim // // \param[in,out] B // \verbatim // B is DOUBLE PRECISION array, dimension ( LDB, N ) // Before entry, the leading m by n part of the array B must // contain the right-hand side matrix B, and on exit is // overwritten by the solution matrix X. // \endverbatim // // \param[in] LDB // \verbatim // LDB is INTEGER // On entry, LDB specifies the first dimension of B as declared // in the calling (sub) program. LDB must be at least // max( 1, m ). // \endverbatim // // Authors: // ======== // // \author Univ. of Tennessee // \author Univ. of California Berkeley // \author Univ. of Colorado Denver // \author NAG Ltd. // // \ingroup double_blas_level3 // // \par Further Details: // ===================== // // \verbatim // // Level 3 Blas routine. // // // -- Written on 8-February-1989. // Jack Dongarra, Argonne National Laboratory. // Iain Duff, AERE Harwell. // Jeremy Du Croz, Numerical Algorithms Group Ltd. // Sven Hammarling, Numerical Algorithms Group Ltd. // \endverbatim // // ===================================================================== // } // @function solves one of the matrix equations // op( A )*X = alpha*B, or X*op( A ) = alpha*B, // where alpha is a scalar, X and B are m by n matrices, A is a unit, or // non-unit, upper or lower triangular matrix and op( A ) is one of // op( A ) = A or op( A ) = A**T. // The matrix X is overwritten on B. // // @param side string , On entry, SIDE specifies whether op( A ) appears on the left or right of X as follows: // SIDE = 'L' or 'l' op( A )*X = alpha*B. // SIDE = 'R' or 'r' X*op( A ) = alpha*B. // @param uplo string , specifies whether the matrix A is an upper or lower triangular matrix as follows: // UPLO = 'U' or 'u' A is an upper triangular matrix. // UPLO = 'L' or 'l' A is a lower triangular matrix. // @param transa string , specifies the form of op( A ) to be used in the matrix multiplication as follows: // TRANSA = 'N' or 'n' op( A ) = A. // TRANSA = 'T' or 't' op( A ) = A**T. // TRANSA = 'C' or 'c' op( A ) = A**T. // @param diag string , specifies whether or not A is unit triangular as follows: // DIAG = 'U' or 'u' A is assumed to be unit triangular. // DIAG = 'N' or 'n' A is not assumed to be unit triangular. // @param m int , the number of rows of B. M must be at least zero. // @param n int , the number of columns of B. N must be at least zero. // @param alpha float , specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. // @param a matrix<float>, Triangular matrix. // @param lda int , specifies the first dimension of A. // @param b matrix<float>, right-hand side matrix B, and on exit is overwritten by the solution matrix X. // @param ldb int , specifies the first dimension of B. // @returns void, modifies matrix b. // usage: // dtrsm ('L', 'U', 'N', 'N', 5, 3, 1.0, a, 7, b, 6) export dtrsm ( string side, string uplo, string transa, string diag, int m, int n, float alpha, matrix<float> a, int lda, matrix<float> b, int ldb ) => // { int _m = m, int _m1 = _m - 1 int _n = n, int _n1 = _n - 1 // Test the input parameters. bool _lside = lsame(side, 'L') int _nrowa = _lside ? _m : _n bool _nounit = lsame(diag, 'N') bool _upper = lsame(uplo, 'U') // int _info = 0 switch (not _lside) and (not lsame(side,'R')) => _info := 1 (not _upper) and (not lsame(uplo,'L')) => _info := 2 (not lsame(transa,'N')) and (not lsame(transa,'T')) and (not lsame(transa,'C')) => _info := 3 (not lsame(diag,'U')) and (not lsame(diag,'N')) => _info := 4 _m < 0 => _info := 5 _n < 0 => _info := 6 lda < math.max(1, _nrowa) => _info := 9 ldb < math.max(1, _m) => _info := 11 if _info != 0 xerbla('DTRSM ', _info)// ### log and break, TODO: can build in messages directly.. switch // Quick return if possible. _m == 0 or _n == 0 => 0 // RETURN alpha == 0.0 => for _j = 0 to _n1 for _i = 0 to _m1 matrix.set(b, _i, _j, 0.0) 0 // RETURN => // Start the operations. if _lside if lsame(transa, 'N') // Form B := alpha*inv( A )*B. if _upper for _j = 0 to _n1 if alpha != 1.0 for _i = 0 to _m1 matrix.set(b, _i, _j, alpha * matrix.get(b, _i, _j)) for _k = _m1 to 0 float _Bkj = matrix.get(b, _k, _j) if _Bkj != 0.0 if _nounit matrix.set(b, _k, _j, _Bkj / matrix.get(a, _k, _k)) if _k > 0 // ### protection against index out of bounds. for _i = 0 to _k - 1 // ### potencial out of bounds. //DO 40 i = 1,k - 1 matrix.set(b, _i, _j, matrix.get(b, _i, _j) - matrix.get(b, _k, _j) * matrix.get(a, _i, _k)) else for _j = 0 to _n1 if alpha != 1.0 for _i = 0 to _m1 matrix.set(b, _i, _j, alpha * matrix.get(b, _i, _j)) for _k = 0 to _m1 if matrix.get(b, _k, _j) != 0.0 if _nounit matrix.set(b, _k, _j, matrix.get(b, _k, _j) / matrix.get(a, _k, _k)) if _k > 0 // ### protection against index out of bounds. for _i = _k + 1 to _m1 // ### potencial out of bounds. //DO 80 i = k + 1,m matrix.set(b, _i, _j, matrix.get(b, _i, _j) - matrix.get(b, _k, _j) * matrix.get(a, _i, _k)) else // Form B := alpha*inv( A**T )*B. if _upper for _j = 0 to _n1 for _i = 0 to _m1 float _temp = alpha * matrix.get(b, _i, _j) if _i > 0 // ### protection against index out of bounds. for _k = 0 to _i - 1 // ### potential out of bounds. //DO 110 k = 1,i - 1 _temp -= matrix.get(a, _k, _i) * matrix.get(b, _k, _j) if _nounit _temp /= matrix.get(a, _i, _i) matrix.set(b, _i, _j, _temp) else for _j = 0 to _n1 for _i = _m1 to 0 float _temp = alpha * matrix.get(b, _i, _j) if _i < _m1 // ### protection against index out of bounds. for _k = _i + 1 to _m1 // ### potential out of bounds. //DO 140 k = i + 1,m _temp -= matrix.get(a, _k, _i) * matrix.get(b, _k, _j) if _nounit _temp /= matrix.get(a, _i, _i) matrix.set(b, _i, _j, _temp) else if lsame(transa, 'N') // Form B := alpha*B*inv( A ). if _upper for _j = 0 to _n1 if alpha != 1.0 for _i = 0 to _m1 matrix.set(b, _i, _j, alpha * matrix.get(b, _i, _j)) if _j > 0 // ### protection against index out of bounds. for _k = 0 to _j - 1 // ### potential out of bounds. //DO 190 k = 1,j - 1 if matrix.get(a, _k, _j) != 0.0 for _i = 0 to _m1 matrix.set(b, _i, _j, matrix.get(b, _i, _j) - matrix.get(a, _k, _j) * matrix.get(b, _i, _k)) if _nounit float _temp = 1.0 / matrix.get(a, _j, _j) for _i = 0 to _m1 matrix.set(b, _i, _j, _temp * matrix.get(b, _i, _j)) else for _j = _n1 to 0 if alpha != 1.0 for _i = 0 to _m1 matrix.set(b, _i, _j, alpha * matrix.get(b, _i, _j)) if _j < _n1 // ### protection against index out of bounds. for _k = _j + 1 to _n1 // ### potential out of bounds. //DO 240 k = j + 1,n if matrix.get(a, _k, _j) != 0.0 for _i = 0 to _m1 matrix.set(b, _i, _j, matrix.get(b, _i, _j) - matrix.get(a, _k, _j) * matrix.get(b, _i, _k)) if _nounit float _temp = 1.0 / matrix.get(a, _j, _j) for _i = 0 to _m1 matrix.set(b, _i, _j, _temp * matrix.get(b, _i, _j)) else // Form B := alpha*B*inv( A**T ). if _upper for _k = _n1 to 0 if _nounit float _temp = 1.0 / matrix.get(a, _k, _k) for _i = 0 to _m1 matrix.set(b, _i, _k, _temp * matrix.get(b, _i, _k)) if _k > 0 // ### protection against index out of bounds. for _j = 0 to _k - 1 // ### potential out of bounds. //DO 290 j = 1,k - 1 if matrix.get(a, _j, _k) != 0.0 float _temp = matrix.get(a, _j, _k) for _i = 0 to _m1 matrix.set(b, _i, _j, matrix.get(b, _i, _j) - _temp * matrix.get(b, _i, _k)) if alpha != 1.0 for _i = 0 to _m1 matrix.set(b, _i, _k, alpha * matrix.get(b, _i, _k)) else for _k = 0 to _n1 if _nounit float _temp = 1.0 / matrix.get(a, _k, _k) for _i = 0 to _m1 matrix.set(b, _i, _k, _temp * matrix.get(b, _i, _k)) if _k < _n1 // ### protection against index out of bounds. for _j = _k + 1 to _n1 // ### potential out of bounds. //DO 340 j = k + 1,n if matrix.get(a, _j, _k) != 0.0 float _temp = matrix.get(a, _j, _k) for _i = 0 to _m1 matrix.set(b, _i, _j, matrix.get(b, _i, _j) - _temp * matrix.get(b, _i, _k)) if alpha != 1.0 for _i = 0 to _m1 matrix.set(b, _i, _k, alpha * matrix.get(b, _i, _k)) 0 // RETURN // End of DTRSM // { example: // tested only on this example.. // string side = input.string(defval = 'L', options = ['L', 'l', 'R', 'r']) // string uplo = input.string(defval = 'U', options = ['U', 'u', 'L', 'l']) // string transa = input.string(defval = 'N', options = ['N', 'n', 'T', 't', 'C', 'c']) // string diag = input.string(defval = 'N', options = ['U', 'u', 'N', 'n']) // int m = input.int(5) // int n = input.int(3) // float alpha = input.float(1.0) // int k = switch side // 'L' => m // 'R' => n // lda = switch side // 'L' => m // 'R' => n // ldb = m a = matrix.new<float>(0, 5)//(lda, k, 1.0) matrix.add_row(a, 0, array.from(3.0, -1.0, 2.0, 2.0, 1.0)) matrix.add_row(a, 1, array.from(float(na), -2.0, 4.0, -1.0, 3.0)) matrix.add_row(a, 2, array.from(float(na), float(na), -3.0, 0.0, 2.0)) matrix.add_row(a, 3, array.from(float(na), float(na), float(na), 4.0, -2.0)) matrix.add_row(a, 4, array.from(float(na), float(na), float(na), float(na), 1.0)) // matrix.add_row(a, 5), matrix.add_row(a, 6) b = matrix.new<float>(0, 3)//(ldb, n, 1.0) matrix.add_row(b, 0, array.from(6.0, 10.0, -2.0)) matrix.add_row(b, 1, array.from(-16.0, -1.0, 6.0)) matrix.add_row(b, 2, array.from(-2.0, 1.0, -4.0)) matrix.add_row(b, 3, array.from(14.0, 0.0, -14.0)) matrix.add_row(b, 4, array.from(-1.0, 2.0, 1.0)) // matrix.add_row(b, 5) import RicardoSantos/DebugConsole/10 as console [__T, __C] = console.init() console.queue_one(__C, 'A:\n' + str.tostring(a)) console.queue_one(__C, 'B:\n' + str.tostring(b)) //dtrsm (side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) // https://www.ibm.com/docs/en/essl/6.1?topic=mos-strsm-dtrsm-ctrsm-ztrsm-solution-triangular-systems-equations-multiple-right-hand-sides // example 1: dtrsm ('L', 'U', 'N', 'N', 5, 3, 1.0, a, 7, b, 6) console.queue_one(__C, 'solution X:\n' + str.tostring(b)) console.update(__T, __C) //} //}
Binance_Min_Limit_Order_amount_library
https://www.tradingview.com/script/XqERkvMh/
potatoshop
https://www.tradingview.com/u/potatoshop/
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/ // © potatoshop //@version=5 // @description The value is truncated to the same decimal point as the minimum contract size for the current symbol in Binance. library("Binance_Min_Limit_Order_amount_library") // @function The value is ceil_truncated to the same decimal point as the minimum unit // @param number // @param min unit // @returns The ceil_truncated value export ceil_truncate(float number, float min_unit = 1.0) => getDecimals = math.abs(math.log(min_unit) / math.log(10)) factor = math.pow(10, getDecimals) math.ceil(number * factor) / factor // @function The value is truncated to the same decimal point as the minimum unit // @param number // @param min unit // @returns The truncated value export truncate(float number, float min_unit = 1.0) => getDecimals = math.abs(math.log(min_unit) / math.log(10)) factor = math.pow(10, getDecimals) int(number * factor) / factor //////////////////////////////////////////////////////////////////////////////// // @function TODO: it give us the Minimum Qty for the trading in Binance // @param n_v TODO: min_notional_value. 5 dollar is the minimum notional amount in Binance at the moment. // @param m_fee TODO: maker_fee % // @param t_fee TODO: taker_fee % // @param cost TODO: your investing money // @param price TODO: Target price you want to trade in Limit_Order, if you want Market_Order, NaN // @returns TODO: for the coin of binance on your chart, [min_unit,min_qty,posible_qty,fee_price] export m_qty(float n_v=5,float m_fee=0.02,float t_fee=0.04,float cost=100,float price=na) => min_notional_value = n_v // Binance have chaged their Minimum notion value from 10 USD to 5 USD. maker_fee = m_fee // % taker_fee = t_fee // % isprice = price ? price : close var min_unit_str="" var m = matrix.new<string>(158,2) matrix.set(m, 0, 0,"0.001"),matrix.set(m, 0, 1,"BCH") matrix.set(m, 1, 0,"0.001"),matrix.set(m, 1, 1,"BTC") matrix.set(m, 2, 0,"0.001"),matrix.set(m, 2, 1,"BTCDOM") matrix.set(m, 3, 0,"0.001"),matrix.set(m, 3, 1,"COMP") matrix.set(m, 4, 0,"0.001"),matrix.set(m, 4, 1,"DASH") matrix.set(m, 5, 0,"0.001"),matrix.set(m, 5, 1,"DEFI") matrix.set(m, 6, 0,"0.001"),matrix.set(m, 6, 1,"ETH") matrix.set(m, 7, 0,"0.001"),matrix.set(m, 7, 1,"LTC") matrix.set(m, 8, 0,"0.001"),matrix.set(m, 8, 1,"MKR") matrix.set(m, 9, 0,"0.001"),matrix.set(m, 9, 1,"XMR") matrix.set(m, 10, 0,"0.001"),matrix.set(m, 10,1,"YFI") matrix.set(m, 11, 0,"0.001"),matrix.set(m, 11,1,"ZEC") matrix.set(m, 12, 0,"0.01"),matrix.set(m, 12, 1,"ATOM") matrix.set(m, 13, 0,"0.01"),matrix.set(m, 13, 1,"BNB") matrix.set(m, 14, 0,"0.01"),matrix.set(m, 14, 1,"ETC") matrix.set(m, 15, 0,"0.01"),matrix.set(m, 15, 1,"LINK") matrix.set(m, 16, 0,"0.01"),matrix.set(m, 16, 1,"LTC") matrix.set(m, 17, 0,"0.01"),matrix.set(m, 17, 1,"NEO") matrix.set(m, 18, 0,"0.1"),matrix.set(m, 18, 1,"AAVE") matrix.set(m, 19, 0,"0.1"),matrix.set(m, 19, 1,"ALGO") matrix.set(m, 20, 0,"0.1"),matrix.set(m, 20, 1,"ALICE") matrix.set(m, 21, 0,"0.1"),matrix.set(m, 21, 1,"ANT") matrix.set(m, 22, 0,"0.1"),matrix.set(m, 22, 1,"APE") matrix.set(m, 23, 0,"0.1"),matrix.set(m, 23, 1,"API3") matrix.set(m, 24, 0,"0.1"),matrix.set(m, 24, 1,"AR") matrix.set(m, 25, 0,"0.1"),matrix.set(m, 25, 1,"AUCTION") matrix.set(m, 26, 0,"0.1"),matrix.set(m, 26, 1,"AVAX") matrix.set(m, 27, 0,"0.1"),matrix.set(m, 27, 1,"BAL") matrix.set(m, 28, 0,"0.1"),matrix.set(m, 28, 1,"BAND") matrix.set(m, 29, 0,"0.1"),matrix.set(m, 29, 1,"BAT") matrix.set(m, 30, 0,"0.1"),matrix.set(m, 30, 1,"BNX") matrix.set(m, 31, 0,"0.1"),matrix.set(m, 31, 1,"CELO") matrix.set(m, 32, 0,"0.1"),matrix.set(m, 32, 1,"CRV") matrix.set(m, 33, 0,"0.1"),matrix.set(m, 33, 1,"CVX") matrix.set(m, 34, 0,"0.1"),matrix.set(m, 34, 1,"DAR") matrix.set(m, 35, 0,"0.1"),matrix.set(m, 35, 1,"DOT") matrix.set(m, 36, 0,"0.1"),matrix.set(m, 36, 1,"DYDX") matrix.set(m, 37, 0,"0.1"),matrix.set(m, 37, 1,"EGLD") matrix.set(m, 38, 0,"0.1"),matrix.set(m, 38, 1,"ENS") matrix.set(m, 39, 0,"0.1"),matrix.set(m, 39, 1,"EOS") matrix.set(m, 40, 0,"0.1"),matrix.set(m, 40, 1,"ETC") matrix.set(m, 41, 0,"0.1"),matrix.set(m, 41, 1,"FIL") matrix.set(m, 42, 0,"0.1"),matrix.set(m, 42, 1,"FLOW") matrix.set(m, 43, 0,"0.1"),matrix.set(m, 43, 1,"FTT") matrix.set(m, 44, 0,"0.1"),matrix.set(m, 44, 1,"GMT") matrix.set(m, 45, 0,"0.1"),matrix.set(m, 45, 1,"GTC") matrix.set(m, 46, 0,"0.1"),matrix.set(m, 46, 1,"ICP") matrix.set(m, 47, 0,"0.1"),matrix.set(m, 47, 1,"IOTA") matrix.set(m, 48, 0,"0.1"),matrix.set(m, 48, 1,"KAVA") matrix.set(m, 49, 0,"0.1"),matrix.set(m, 49, 1,"KLAY") matrix.set(m, 50, 0,"0.1"),matrix.set(m, 50, 1,"KSM") matrix.set(m, 51, 0,"0.1"),matrix.set(m, 51, 1,"LDO") matrix.set(m, 52, 0,"0.1"),matrix.set(m, 52, 1,"LINK") matrix.set(m, 53, 0,"0.1"),matrix.set(m, 53, 1,"LIT") matrix.set(m, 54, 0,"0.1"),matrix.set(m, 54, 1,"LPT") matrix.set(m, 55, 0,"0.1"),matrix.set(m, 55, 1,"NEAR") matrix.set(m, 56, 0,"0.1"),matrix.set(m, 56, 1,"OMG") matrix.set(m, 57, 0,"0.1"),matrix.set(m, 57, 1,"ONT") matrix.set(m, 58, 0,"0.1"),matrix.set(m, 58, 1,"OP") matrix.set(m, 59, 0,"0.1"),matrix.set(m, 59, 1,"QTUM") matrix.set(m, 60, 0,"0.1"),matrix.set(m, 60, 1,"RAY") matrix.set(m, 61, 0,"0.1"),matrix.set(m, 61, 1,"RLC") matrix.set(m, 62, 0,"0.1"),matrix.set(m, 62, 1,"SAND") matrix.set(m, 63, 0,"0.1"),matrix.set(m, 63, 1,"SNX") matrix.set(m, 64, 0,"0.1"),matrix.set(m, 64, 1,"SXP") matrix.set(m, 65, 0,"0.1"),matrix.set(m, 65, 1,"THETA") matrix.set(m, 66, 0,"0.1"),matrix.set(m, 66, 1,"TRB") matrix.set(m, 67, 0,"0.1"),matrix.set(m, 67, 1,"UNFI") matrix.set(m, 68, 0,"0.1"),matrix.set(m, 68, 1,"UNI") matrix.set(m, 69, 0,"0.1"),matrix.set(m, 69, 1,"WAVES") matrix.set(m, 70, 0,"0.1"),matrix.set(m, 70, 1,"XRP") matrix.set(m, 71, 0,"0.1"),matrix.set(m, 71, 1,"XTZ") matrix.set(m, 72, 0,"0.1"),matrix.set(m, 72, 1,"ZEN") matrix.set(m, 73, 0,"0.1"),matrix.set(m, 73, 1,"ZRX") matrix.set(m, 74, 0,"1"),matrix.set(m, 74,1,"000LUNC") matrix.set(m, 75, 0,"1"),matrix.set(m, 75,1,"000SHIB") matrix.set(m, 76, 0,"1"),matrix.set(m, 76,1,"000XEC") matrix.set(m, 77, 0,"1"),matrix.set(m, 77,1,"INCH") matrix.set(m, 78, 0,"1"),matrix.set(m, 78,1,"DA") matrix.set(m, 79, 0,"1"),matrix.set(m, 79,1,"LPHA") matrix.set(m, 80, 0,"1"),matrix.set(m, 80,1,"NC") matrix.set(m, 81, 0,"1"),matrix.set(m, 81,1,"NKR") matrix.set(m, 82, 0,"1"),matrix.set(m, 82,1,"PE") matrix.set(m, 83, 0,"1"),matrix.set(m, 83,1,"RPA") matrix.set(m, 84, 0,"1"),matrix.set(m, 84,1,"TA") matrix.set(m, 85, 0,"1"),matrix.set(m, 85,1,"UDIO") matrix.set(m, 86, 0,"1"),matrix.set(m, 86,1,"VAX") matrix.set(m, 87, 0,"1"),matrix.set(m, 87,1,"XS") matrix.set(m, 88, 0,"1"),matrix.set(m, 88,1,"AKE") matrix.set(m, 89, 0,"1"),matrix.set(m, 89,1,"EL") matrix.set(m, 90, 0,"1"),matrix.set(m, 90,1,"LZ") matrix.set(m, 91, 0,"1"),matrix.set(m, 91,1,"TS") matrix.set(m, 92, 0,"1"),matrix.set(m, 92,1,"98") matrix.set(m, 93, 0,"1"),matrix.set(m, 93,1,"ELR") matrix.set(m, 94, 0,"1"),matrix.set(m, 94,1,"HR") matrix.set(m, 95, 0,"1"),matrix.set(m, 95,1,"HZ") matrix.set(m, 96, 0,"1"),matrix.set(m, 96,1,"OTI") matrix.set(m, 97, 0,"1"),matrix.set(m, 97,1,"TK") matrix.set(m, 98, 0,"1"),matrix.set(m, 98,1,"TSI") matrix.set(m, 99, 0,"1"),matrix.set(m, 99,1,"VC") matrix.set(m, 100, 0,"1"),matrix.set(m, 100,1,"DENT") matrix.set(m, 101, 0,"1"),matrix.set(m, 101,1,"DGB") matrix.set(m, 102, 0,"1"),matrix.set(m, 102,1,"DODO") matrix.set(m, 103, 0,"1"),matrix.set(m, 103,1,"DOGE") matrix.set(m, 104, 0,"1"),matrix.set(m, 104,1,"DUSK") matrix.set(m, 105, 0,"1"),matrix.set(m, 105,1,"ENJ") matrix.set(m, 106, 0,"1"),matrix.set(m, 106,1,"FLM") matrix.set(m, 107, 0,"1"),matrix.set(m, 107,1,"FTM") matrix.set(m, 108, 0,"1"),matrix.set(m, 108,1,"GAL") matrix.set(m, 109, 0,"1"),matrix.set(m, 109,1,"GALA") matrix.set(m, 110, 0,"1"),matrix.set(m, 110,1,"GMT") matrix.set(m, 111, 0,"1"),matrix.set(m, 111,1,"GRT") matrix.set(m, 112, 0,"1"),matrix.set(m, 112,1,"HBAR") matrix.set(m, 113, 0,"1"),matrix.set(m, 113,1,"HNT") matrix.set(m, 114, 0,"1"),matrix.set(m, 114,1,"HOT") matrix.set(m, 115, 0,"1"),matrix.set(m, 115,1,"ICX") matrix.set(m, 116, 0,"1"),matrix.set(m, 116,1,"IMX") matrix.set(m, 117, 0,"1"),matrix.set(m, 117,1,"IOST") matrix.set(m, 118, 0,"1"),matrix.set(m, 118,1,"IOTX") matrix.set(m, 119, 0,"1"),matrix.set(m, 119,1,"JASMY") matrix.set(m, 120, 0,"1"),matrix.set(m, 120,1,"KNC") matrix.set(m, 121, 0,"1"),matrix.set(m, 121,1,"LEVER") matrix.set(m, 122, 0,"1"),matrix.set(m, 122,1,"LINA") matrix.set(m, 123, 0,"1"),matrix.set(m, 123,1,"LRC") matrix.set(m, 124, 0,"1"),matrix.set(m, 124,1,"LUNA2") matrix.set(m, 125, 0,"1"),matrix.set(m, 125,1,"MANA") matrix.set(m, 126, 0,"1"),matrix.set(m, 126,1,"MASK") matrix.set(m, 127, 0,"1"),matrix.set(m, 127,1,"MATIC") matrix.set(m, 128, 0,"1"),matrix.set(m, 128,1,"MTL") matrix.set(m, 129, 0,"1"),matrix.set(m, 129,1,"NEAR") matrix.set(m, 130, 0,"1"),matrix.set(m, 130,1,"NKN") matrix.set(m, 131, 0,"1"),matrix.set(m, 131,1,"OCEAN") matrix.set(m, 132, 0,"1"),matrix.set(m, 132,1,"OGN") matrix.set(m, 133, 0,"1"),matrix.set(m, 133,1,"ONE") matrix.set(m, 134, 0,"1"),matrix.set(m, 134,1,"PEOPLE") matrix.set(m, 135, 0,"1"),matrix.set(m, 135,1,"REEF") matrix.set(m, 136, 0,"1"),matrix.set(m, 136,1,"REN") matrix.set(m, 137, 0,"1"),matrix.set(m, 137,1,"ROSE") matrix.set(m, 138, 0,"1"),matrix.set(m, 138,1,"RSR") matrix.set(m, 139, 0,"1"),matrix.set(m, 139,1,"RUNE") matrix.set(m, 140, 0,"1"),matrix.set(m, 140,1,"RVN") matrix.set(m, 141, 0,"1"),matrix.set(m, 141,1,"SAND") matrix.set(m, 142, 0,"1"),matrix.set(m, 142,1,"SFP") matrix.set(m, 143, 0,"1"),matrix.set(m, 143,1,"SKL") matrix.set(m, 144, 0,"1"),matrix.set(m, 144,1,"SOL") matrix.set(m, 145, 0,"1"),matrix.set(m, 145,1,"SRM") matrix.set(m, 146, 0,"1"),matrix.set(m, 146,1,"STMX") matrix.set(m, 147, 0,"1"),matrix.set(m, 147,1,"STORJ") matrix.set(m, 148, 0,"1"),matrix.set(m, 148,1,"SUSHI") matrix.set(m, 149, 0,"1"),matrix.set(m, 149,1,"TLM") matrix.set(m, 150, 0,"1"),matrix.set(m, 150,1,"TOMO") matrix.set(m, 151, 0,"1"),matrix.set(m, 151,1,"TRX") matrix.set(m, 152, 0,"1"),matrix.set(m, 152,1,"UNI") matrix.set(m, 153, 0,"1"),matrix.set(m, 153,1,"VET") matrix.set(m, 154, 0,"1"),matrix.set(m, 154,1,"WOO") matrix.set(m, 155, 0,"1"),matrix.set(m, 155,1,"XEM") matrix.set(m, 156, 0,"1"),matrix.set(m, 156,1,"XLM") matrix.set(m, 157, 0,"1"),matrix.set(m, 157,1,"ZIL") //TODO : [min_unit,min_qty,posible_qty,fee_price] var bool is_right = false for i=0 to 157 if syminfo.basecurrency == matrix.get(m,i,1) and syminfo.prefix == "BINANCE" min_unit_str := matrix.get(m,i,0) is_right := true if is_right == false runtime.error("hey~~!! it,s not Binance, check the exchange" ) min_unit = str.tonumber(min_unit_str) // The minimum Limit Order amount for the contract. fee = price ? maker_fee : taker_fee min_qty = ceil_truncate(min_notional_value*(1+fee/100)/isprice,min_unit) // base coin min_cost = (min_qty*isprice)*(1+fee/100) posible_qty = truncate(cost/isprice,min_unit) >= min_qty? truncate(cost/isprice,min_unit) : 0 // Amount fee_price = (posible_qty*isprice)*fee if truncate(cost/isprice,min_unit) < min_qty runtime.error("Not enough Money" ) [min_unit,min_qty,posible_qty,fee_price] [min_u,min_q,p_q,f_p] = m_qty() plot(min_u,"min_unit",color.blue) plot(min_q,"min_qty",color.yellow) plot(p_q,"posible_qty",color.white) plot(f_p,"fee_price",color.white) how_many_unit = p_q/min_u how_much_cost = p_q*close how_much_costwithfee = (p_q*close)*(1+f_p/100) plot(how_many_unit,"how_many_min_unit",color.lime) plot(how_much_cost,"just Q x C",color.gray) plot(how_much_costwithfee,"real invest cost with fee",color.white)
Color Library: Rainbow Index & Simplest Return Color
https://www.tradingview.com/script/jj1Bl0U6-Color-Library-Rainbow-Index-Simplest-Return-Color/
Pip-Whisperer
https://www.tradingview.com/u/Pip-Whisperer/
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/ // © Pip-Whisperer //Shoutout to @Pine-Coders for going through all the rainbow colors and making this easy // If you guys make some crazy larger color library comment below so i can see it, i love the RGB beauty haha :) //@version=5 // @description TODO: add library description here library("Colors") // @function TODO: color.this(Brown) // @param x TODO: String Color Name // @returns TODO: Color export this(simple string Color) => switch Color "brown" => color.new(#442211, 0) "wood" => color.new(#774433, 0) "tan" => color.new(#AA8855, 0) "gold" => color.new(#C0C000, 0) "olive" => color.new(#808000, 0) "green" => color.new(#008000, 0) "teal" => color.new(#008080, 0) "navy" => color.new(#000088, 0) "maroon" => color.new(#800000, 0) "coral" => color.new(#FF8080, 0) "lavender" => color.new(#8080FF, 0) "indigo" => color.new(#440088, 0) "darkpurple" => color.new(#660066, 0) "purple" => color.new(#990099, 0) "fuchsia" => color.new(#FF00FF, 0) "violet" => color.new(#AA00FF, 0) "hanpurple" => color.new(#5500FF, 0) "blue " => color.new(#0000FF, 0) "cichlid" => color.new(#0044FF, 0) "azure" => color.new(#0080FF, 0) "skyblue" => color.new(#00BBFF, 0) "aqua " => color.new(#00FFFF, 0) "mint" => color.new(#00FF80, 0) "lime" => color.new(#00FF00, 0) "chartreuse" => color.new(#80FF00, 0) "yellow" => color.new(#FFFF00, 0) "amber" => color.new(#FFC000, 0) "orange" => color.new(#FF8000, 0) "redorange" => color.new(#FF4400, 0) "red" => color.new(#FF0000, 0) "hotpink" => color.new(#FF0099, 0) "fuchsia" => color.new(#FF00FF, 0) "pink" => color.new(#FF99FF, 0) "white" => color.new(#FFFFFF, 0) "silver" => color.new(#C0C0C0, 0) "gray" => color.new(#808080, 0) "darkgray" => color.new(#404040, 0) "nero" => color.new(#202020, 0) "eclipse" => color.new(#101010, 0) "black" => color.new(#000000, 0) "Brown" => color.new(#442211, 0) "Wood" => color.new(#774433, 0) "Tan" => color.new(#AA8855, 0) "Gold" => color.new(#C0C000, 0) "Olive" => color.new(#808000, 0) "Green" => color.new(#008000, 0) "Teal" => color.new(#008080, 0) "Navy" => color.new(#000088, 0) "Maroon" => color.new(#800000, 0) "Coral" => color.new(#FF8080, 0) "Lavender" => color.new(#8080FF, 0) "Indigo" => color.new(#440088, 0) "Darkpurple" => color.new(#660066, 0) "Purple" => color.new(#990099, 0) "Fuchsia" => color.new(#FF00FF, 0) "Violet" => color.new(#AA00FF, 0) "Hanpurple" => color.new(#5500FF, 0) "Blue " => color.new(#0000FF, 0) "Cichlid" => color.new(#0044FF, 0) "Azure" => color.new(#0080FF, 0) "Skyblue" => color.new(#00BBFF, 0) "Aqua " => color.new(#00FFFF, 0) "Mint" => color.new(#00FF80, 0) "Lime" => color.new(#00FF00, 0) "Chartreuse" => color.new(#80FF00, 0) "Yellow" => color.new(#FFFF00, 0) "Amber" => color.new(#FFC000, 0) "Orange" => color.new(#FF8000, 0) "Redorange" => color.new(#FF4400, 0) "Red" => color.new(#FF0000, 0) "Hotpink" => color.new(#FF0099, 0) "Fuchsia" => color.new(#FF00FF, 0) "Pink" => color.new(#FF99FF, 0) "White" => color.new(#FFFFFF, 0) "Silver" => color.new(#C0C0C0, 0) "Gray" => color.new(#808080, 0) "Darkgray" => color.new(#404040, 0) "Nero" => color.new(#202020, 0) "Eclipse" => color.new(#101010, 0) "Black" => color.new(#000000, 0) // @function TODO: Return Rainbow Index // @param x TODO: Number is index of Rainbow :) // @returns TODO: Color export rainbow(simple int Number) => switch Number 1 => color.new(#442211, 0) 2 => color.new(#774433, 0) 3 => color.new(#AA8855, 0) 4 => color.new(#C0C000, 0) 5 => color.new(#808000, 0) 6 => color.new(#008000, 0) 7 => color.new(#008080, 0) 8 => color.new(#000088, 0) 9 => color.new(#800000, 0) 10 => color.new(#FF8080, 0) 11 => color.new(#8080FF, 0) 12 => color.new(#440088, 0) 13 => color.new(#660066, 0) 14 => color.new(#990099, 0) 15 => color.new(#FF00FF, 0) 16 => color.new(#AA00FF, 0) 17 => color.new(#5500FF, 0) 18 => color.new(#0000FF, 0) 19 => color.new(#0044FF, 0) 20 => color.new(#0080FF, 0) 21 => color.new(#00BBFF, 0) 22 => color.new(#00FFFF, 0) 23 => color.new(#00FF80, 0) 24 => color.new(#00FF00, 0) 25 => color.new(#80FF00, 0) 26 => color.new(#FFFF00, 0) 27 => color.new(#FFC000, 0) 28 => color.new(#FF8000, 0) 29 => color.new(#FF4400, 0) 30 => color.new(#FF0000, 0) 31 => color.new(#FF0099, 0) 32 => color.new(#FF00FF, 0) 33 => color.new(#FF99FF, 0) 34 => color.new(#FFFFFF, 0) 35 => color.new(#C0C0C0, 0) 36 => color.new(#808080, 0) 37 => color.new(#404040, 0) 38 => color.new(#202020, 0) 39 => color.new(#101010, 0) 40 => color.new(#000000, 0)
myAlerts
https://www.tradingview.com/script/qkM3fLOZ-myAlerts/
incryptowetrust100k
https://www.tradingview.com/u/incryptowetrust100k/
2
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/ // © incryptowetrust100k //@version=5 // @description My Alerts Functions - To use with autoview library("myAlerts") //==================================================-----------EXTERNAL-----------==================================================// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // - 1 - INTERNAL { // - 1.0 - Header { // @function - Set token on Messages // @param typeMsg - Used to define type of writing // @param i_token - User token // @returns - Returns the header message f_header(bool typeMsg, string i_token) => typeMsg ? i_token+"," : "{ \n \"token\": \""+i_token+"\", \n \"commands\": \" " // } // - } End 1.0 - Header // - } End INTERNAL // - 2 - EXTERNAL { // - 2.1 - Order { // @function - Write the entry order message // @param _price - The order price // @param _qty - The order quantity // @param _position - The order side // @param _account - The user account // @param _exchange - The user exchange // @param _i - Used for multi-accounts, this represents the index of accounts // @param i_qtyTypeOrder - String used to set Thether or Bitcoin Type Orders // @param typeMsg - True = Autoview; False = Metatrader // @param syminfoticker - Ticker // @returns - Returns the open order message export f_order(float _price,float _qty, int _position, string _account, string _exchange, int _i, string i_qtyTypeOrder, int i_delayOrders, bool typeMsg, string msg_syminfoticker) => _msg = "" _xQty = _qty _currency = i_qtyTypeOrder == "TETHER" ? " u=currency" : "" if i_qtyTypeOrder == "FIAT" _xQty := math.round(math.round(_qty*close) / 100) * 100 else if i_qtyTypeOrder == "TETHER" _xQty := _qty * close / 100 _op = _position == 1 ? "long" : "short" _txtDelay = _i == 0 ? " delay=" + str.tostring(i_delayOrders) + " " : " " if not typeMsg _msg := " a="+_account+" e="+_exchange+" s="+msg_syminfoticker + _txtDelay + " b="+_op+" q="+str.tostring(_xQty)+ _currency + " fp="+str.tostring(_price)+" | " else _op := _op == "long" ? "buylimit" : "selllimit" _msg := _op+","+msg_syminfoticker+",risk="+str.tostring(math.round(_xQty/100000,2))+",price="+str.format("{0,number,#.#####}",_price)+"" _msg // - } End 2.1 - Order // - 2.2 - Stop { // @function - Write the stop order message // @param _stop_price - The order stop price // @param _slLimit_price - The order stop limit price // @param _account - The user account // @param _exchange - The user exchange // @param _i - Used for multi-accounts, this represents the index of accounts // @param i_delayOrders - Time in seconds to delay command on autoview // @param typeMsg - True = Autoview; False = Metatrader // @param syminfoticker - Ticker // @returns - Returns the open order message export f_stop(float _stop_price, float _slLimit_price, string _account, string _exchange, int _i, int i_delayOrders, bool typeMsg, string msg_syminfoticker) => _msg = "" _txtDelay = _i == 0 ? " delay=" + str.tostring(i_delayOrders) + " " : " " if not typeMsg _msg := " a="+_account+" e="+_exchange+" s="+msg_syminfoticker + _txtDelay + " q=100% c=position fsl="+str.tostring(_stop_price)+" fp="+str.tostring(_slLimit_price)+" ro=1 | " else _msg := ",sl="+str.tostring(_stop_price)+"" _msg // - } End 2.2 - Order // - 2.3 - Take { // @function - Write the stop order message // @param _take_price - The order stop price // @param _account - The user account // @param _exchange - The user exchange // @param _i - Used for multi-accounts, this represents the index of accounts // @param i_delayOrders - Time in seconds to delay command on autoview // @param typeMsg - True = Autoview; False = Metatrader // @param syminfoticker - Ticker // @returns - Returns the open order message export f_take(float _take_price, string _account, string _exchange, int _i, int i_delayOrders, bool typeMsg, string msg_syminfoticker) => _msg = "" _txtDelay = _i == 0 ? " delay=" + str.tostring(i_delayOrders) + " " : " " if not typeMsg _msg := " a="+_account+" e="+_exchange+" s="+msg_syminfoticker + _txtDelay + " q=100% c=position fp="+str.tostring(_take_price)+" ro=1 | " else _msg := ",tp="+str.tostring(_take_price)+"" _msg // - } End 2.3 - Take // - 2.4 - Update { // @function - Write the update order message // @param _account - The user account // @param _exchange - The user exchange // @param _i - Used for multi-accounts, this represents the index of accounts // @param i_delayOrders - Time in seconds to delay command on autoview // @param typeMsg - True = Autoview; False = Metatrader // @param syminfoticker - Ticker // @returns - Returns the open order message export f_update(string _account, string _exchange, int _i, int i_delayOrders, bool typeMsg, string msg_syminfoticker) => _msg = "" _txtDelay = _i == 0 ? " delay=" + str.tostring(i_delayOrders + 1) + " " : " " if not typeMsg _msg := " a="+_account+" e="+_exchange+" s="+msg_syminfoticker + _txtDelay +" c=order | " else _msg := "" _msg // - } End 2.4 - Update // - 2.5 - Exit { // @function - Write the exit order message // @param _account - The user account // @param _exchange - The user exchange // @param _i - Used for multi-accounts, this represents the index of accounts // @param i_delayOrders - Time in seconds to delay command on autoview // @param typeMsg - True = Autoview; False = Metatrader // @param syminfoticker - Ticker // @returns - Returns the open order message export f_exit(string _account, string _exchange, int _i, int i_delayOrders, bool typeMsg, string msg_syminfoticker)=> _msg = "" _txtDelay = _i == 0 ? " delay=" + str.tostring(i_delayOrders) + " " : " " if not typeMsg _msg := " a="+_account+" e="+_exchange+" s="+msg_syminfoticker + _txtDelay + " c=position t=market ro=1 | " else _msg := "" _msg // - } End 2.5 - Exit // - 2.6 - Hedge { // @function - Write the exit order message // @param _account - The user account // @param _exchange - The user exchange // @param _i - Used for multi-accounts, this represents the index of accounts // @param i_delayOrders - Time in seconds to delay command on autoview // @param typeMsg - True = Autoview; False = Metatrader // @param syminfoticker - Ticker // @returns - Returns the open order message export f_hedge(string _account, string _exchange, int _i, int i_delayOrders, bool typeMsg, string msg_syminfoticker)=> _msg = "" _txtDelay = _i == 0 ? " delay=" + str.tostring(i_delayOrders) + " " : " " if not typeMsg _msg := _msg + " a="+_account+" e="+_exchange+" s="+msg_syminfoticker + _txtDelay + " b=short q=100% t=limit | " else _msg := "" _msg // - } End 2.6 - Hedge // - } End EXTERNAL
FunctionLAPACKdsyrk
https://www.tradingview.com/script/bNEt3znT-FunctionLAPACKdsyrk/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
26
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 subroutine part of LAPACK: Linear Algebra Package, // performs one of the symmetric rank k operations // . // C := alpha*A*A**T + beta*C, or C := alpha*A**T*A + beta*C, // . // where alpha and beta are scalars, C is an n by n symmetric matrix // and A is an n by k matrix in the first case and a k by n matrix // in the second case. // . // reference: // https://netlib.org/lapack/explore-html/dc/d05/dsyrk_8f_source.html#l00168 library(title = 'FunctionLAPACKdsyrk') // { helper functions: // https://netlib.org/lapack/explore-html/d0/dbf/_b_l_a_s_2_s_r_c_2lsame_8f_source.html#l00052 // test if letter in 'a' equals 'b' regardless of case. lsame (string a, string b) => str.lower(a) == str.lower(b) // // https://netlib.org/lapack/explore-html/d1/dc0/_b_l_a_s_2_s_r_c_2xerbla_8f_source.html#l00059 xerbla (string srname, int info) => runtime.error(str.format(' ** On entry to {0} parameter number {1} had an illegal value', srname, info)) // end: helper functions } // { brief DSYRK // // =========== DOCUMENTATION =========== // // Online html documentation available at // http://www.netlib.org/lapack/explore-html/ // // Definition: // =========== // // SUBROUTINE DSYRK(UPLO,TRANS,N,K,ALPHA,A,LDA,BETA,C,LDC) // // .. Scalar Arguments .. // DOUBLE PRECISION ALPHA,BETA // INTEGER K,LDA,LDC,N // CHARACTER TRANS,UPLO // .. // .. Array Arguments .. // DOUBLE PRECISION A(LDA,*),C(LDC,*) // .. // // // \par Purpose: // ============= // > // \verbatim // > // DSYRK performs one of the symmetric rank k operations // > // C := alpha*A*A**T + beta*C, // > // or // > // C := alpha*A**T*A + beta*C, // > // where alpha and beta are scalars, C is an n by n symmetric matrix // and A is an n by k matrix in the first case and a k by n matrix // in the second case. // \endverbatim // // Arguments: // ========== // // \param[in] UPLO // \verbatim // UPLO is CHARACTER*1 // On entry, UPLO specifies whether the upper or lower // triangular part of the array C is to be referenced as // follows: // > // UPLO = 'U' or 'u' Only the upper triangular part of C // is to be referenced. // > // UPLO = 'L' or 'l' Only the lower triangular part of C // is to be referenced. // \endverbatim // > // \param[in] TRANS // \verbatim // TRANS is CHARACTER*1 // On entry, TRANS specifies the operation to be performed as // follows: // > // TRANS = 'N' or 'n' C := alpha*A*A**T + beta*C. // > // TRANS = 'T' or 't' C := alpha*A**T*A + beta*C. // > // TRANS = 'C' or 'c' C := alpha*A**T*A + beta*C. // \endverbatim // > // \param[in] N // \verbatim // N is INTEGER // On entry, N specifies the order of the matrix C. N must be // at least zero. // \endverbatim // > // \param[in] K // \verbatim // K is INTEGER // On entry with TRANS = 'N' or 'n', K specifies the number // of columns of the matrix A, and on entry with // TRANS = 'T' or 't' or 'C' or 'c', K specifies the number // of rows of the matrix A. K must be at least zero. // \endverbatim // > // \param[in] ALPHA // \verbatim // ALPHA is DOUBLE PRECISION. // On entry, ALPHA specifies the scalar alpha. // \endverbatim // > // \param[in] A // \verbatim // A is DOUBLE PRECISION array, dimension ( LDA, ka ), where ka is // k when TRANS = 'N' or 'n', and is n otherwise. // Before entry with TRANS = 'N' or 'n', the leading n by k // part of the array A must contain the matrix A, otherwise // the leading k by n part of the array A must contain the // matrix A. // \endverbatim // > // \param[in] LDA // \verbatim // LDA is INTEGER // On entry, LDA specifies the first dimension of A as declared // in the calling (sub) program. When TRANS = 'N' or 'n' // then LDA must be at least math.max( 1, n ), otherwise LDA must // be at least math.max( 1, k ). // \endverbatim // > // \param[in] BETA // \verbatim // BETA is DOUBLE PRECISION. // On entry, BETA specifies the scalar beta. // \endverbatim // > // \param[in,out] C // \verbatim // C is DOUBLE PRECISION array, dimension ( LDC, N ) // Before entry with UPLO = 'U' or 'u', the leading n by n // upper triangular part of the array C must contain the upper // triangular part of the symmetric matrix and the strictly // lower triangular part of C is not referenced. On exit, the // upper triangular part of the array C is overwritten by the // upper triangular part of the updated matrix. // Before entry with UPLO = 'L' or 'l', the leading n by n // lower triangular part of the array C must contain the lower // triangular part of the symmetric matrix and the strictly // upper triangular part of C is not referenced. On exit, the // lower triangular part of the array C is overwritten by the // lower triangular part of the updated matrix. // \endverbatim // > // \param[in] LDC // \verbatim // LDC is INTEGER // On entry, LDC specifies the first dimension of C as declared // in the calling (sub) program. LDC must be at least // math.max( 1, n ). // \endverbatim // // Authors: // ======== // // \author Univ. of Tennessee // \author Univ. of California Berkeley // \author Univ. of Colorado Denver // \author NAG Ltd. // // \ingroup double_blas_level3 // // \par Further Details: // ===================== // > // \verbatim // > // Level 3 Blas routine. // > // -- Written on 8-February-1989. // Jack Dongarra, Argonne National Laboratory. // Iain Duff, AERE Harwell. // Jeremy Du Croz, Numerical Algorithms Group Ltd. // Sven Hammarling, Numerical Algorithms Group Ltd. // \endverbatim // > // ===================================================================== // end brief } // @function performs one of the symmetric rank k operations // . // C := alpha*A*A**T + beta*C, or C := alpha*A**T*A + beta*C, // . // where alpha and beta are scalars, C is an n by n symmetric matrix // and A is an n by k matrix in the first case and a k by n matrix // in the second case. // . // @param uplo string specifies whether the upper or lower triangular part of // the array C is to be referenced as follows: // UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. // UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. //. // @param trans string specifies the operation to be performed as follows: // TRANS = 'N' or 'n' C := alpha*A*A**T + beta*C. // TRANS = 'T' or 't' C := alpha*A**T*A + beta*C. // TRANS = 'C' or 'c' C := alpha*A**T*A + beta*C. // . // @param n int specifies the order of the matrix C. N must be at least zero. // @param k int On entry with: // TRANS = 'N' or 'n', K specifies the number of columns of the matrix A. // TRANS = 'T' or 't' or 'C' or 'c', K specifies the number of rows of the matrix A. // K must be at least zero. // . // @param alpha float scalar. // @param a matrix<float> matrix A. // @param lda int specifies the first dimension of A. // @param beta float scalar. // @param c matrix<float> matrix C, is overwritten by the lower triangular part of the updated matrix. // @param ldc int specifies the first dimension of C // @returns void, C is overwritten by the lower triangular part of the updated matrix. export dsyrk ( string uplo , string trans, int n , int k, float alpha, matrix<float> a , int lda, float beta , matrix<float> c , int ldc ) => // { int _n = n, int _n1 = _n - 1 int _k = math.max(1, k) // Test the input parameters. int _nrowa = lsame(trans,'N') ? n : _k bool _upper = lsame(uplo,'U') // int _info = 0 switch (not _upper) and (not lsame(uplo, 'L')) => _info := 1 (not lsame(trans,'N')) and (not lsame(trans,'T')) and (not lsame(trans,'C'))=> _info := 2 _n < 0 => _info := 3 k < 0 => _info := 4 lda < math.max(1, _nrowa) => _info := 7 ldc < math.max(1, _n) => _info := 10 if (_info != 0) xerbla('DSYRK ', _info) // ### log and break, TODO: can build in messages directly.. switch // Quick return if possible. (_n == 0 or ((alpha == 0.0 or k == 0) and beta == 1.0)) => 0 // RETURN alpha == 0.0 => if _upper if beta == 0.0 0 for _j = 0 to _n1 for _i = 0 to _j matrix.set(c, _i, _j, 0.0) else for _j = 0 to _n1 for _i = 0 to _j matrix.set(c, _i, _j, beta * matrix.get(c, _i, _j)) else if beta == 0.0 for _j = 0 to _n1 for _i = _j to _n1 matrix.set(c, _i, _j, 0.0) else for _j = 0 to _n1 for _i = _j to _n1 matrix.set(c, _i, _j, beta * matrix.get(c, _i, _j)) 0 // RETURN => // Start the operations. if lsame(trans, 'N') // Form C := alpha*A*A**T + beta*C. if _upper for _j = 0 to _n1 if beta == 0.0 for _i = 0 to _j matrix.set(c, _i, _j, 0.0) else if beta != 1.0 for _i = 0 to _j matrix.set(c, _i, _j, beta * matrix.get(c, _i, _j)) for _l = 0 to _k-1 // ### modified logic on _k if matrix.get(a, _j, _l) != 0.0 float _temp = alpha * matrix.get(a, _j, _l) for _i = 0 to _j matrix.set(c, _i, _j, matrix.get(c, _i, _j) + _temp * matrix.get(a, _i, _l)) else for _j = 0 to _n1 if beta == 0.0 for _i = _j to _n1 matrix.set(c, _i, _j, 0.0) else if beta != 1.0 for _i = _j to _n1 matrix.set(c, _i, _j, beta * matrix.get(c, _i, _j)) for _l = 0 to _k-1 // ### modified logic on _k if matrix.get(a, _j, _l) != 0.0 float _temp = alpha * matrix.get(a, _j, _l) for _i = _j to _n1 matrix.set(c, _i, _j, matrix.get(c, _i, _j) + _temp * matrix.get(a, _i, _l)) else // Form C := alpha*A**T*A + beta*C. if _upper for _j = 0 to _n1 for _i = 0 to _j float _temp = 0.0 for _l = 0 to _k-1 // ### modified logic on _k _temp += matrix.get(a, _l, _i) * matrix.get(a, _l, _j) if beta == 0.0 matrix.set(c, _i, _j, alpha * _temp) else matrix.set(c, _i, _j, alpha * _temp + beta * matrix.get(c, _i, _j)) else for _j = 0 to _n1 for _i = _j to _n1 float _temp = 0.0 for _l = 0 to _k-1 // ### modified logic on _k _temp += matrix.get(a, _l, _i) * matrix.get(a, _l, _j) if beta == 0.0 matrix.set(c, _i, _j, alpha * _temp) else matrix.set(c, _i, _j, alpha * _temp + beta * matrix.get(c, _i, _j)) 0 // RETURN // End of DSYRK // { example: // reference: // https://www.ibm.com/docs/en/essl/6.1?topic=mos-ssyrk-dsyrk-csyrk-zsyrk-cherk-zherk-rank-update-real-complex-symmetric-complex-hermitian-matrix A = matrix.new<float>(8, 0) matrix.add_col(A, 0, array.from(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) matrix.add_col(A, 1, array.from(8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0)) C = matrix.new<float>(0, 8) matrix.add_row(C, 0, array.from( 0.0, 1.0, 3.0, 6.0, 10.0, 15.0, 21.0, 28.0)) matrix.add_row(C, 1, array.from(float(na), 2.0, 4.0, 7.0, 11.0, 16.0, 22.0, 29.0)) matrix.add_row(C, 2, array.from(float(na), float(na), 5.0, 8.0, 12.0, 17.0, 23.0, 30.0)) matrix.add_row(C, 3, array.from(float(na), float(na), float(na), 9.0, 13.0, 18.0, 24.0, 31.0)) matrix.add_row(C, 4, array.from(float(na), float(na), float(na), float(na), 14.0, 19.0, 25.0, 32.0)) matrix.add_row(C, 5, array.from(float(na), float(na), float(na), float(na), float(na), 20.0, 26.0, 33.0)) matrix.add_row(C, 6, array.from(float(na), float(na), float(na), float(na), float(na), float(na), 27.0, 34.0)) matrix.add_row(C, 7, array.from(float(na), float(na), float(na), float(na), float(na), float(na), float(na), 35.0)) import RicardoSantos/DebugConsole/10 as console [__T, __C] = console.init() console.queue_one(__C, 'A:\n' + str.tostring(A)) console.queue_one(__C, 'C:\n' + str.tostring(C)) dsyrk('U', 'N', 8, 2, 1.0, A, 9, 1.0, C, 10) console.queue_one(__C, 'solution X:\n' + str.tostring(C)) console.update(__T, __C) // } // }
BoxLine_Lib
https://www.tradingview.com/script/Qhv09owj-BoxLine-Lib/
FFriZz
https://www.tradingview.com/u/FFriZz/
34
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/ // © FFriZz //@version=5 library("BoxLine_Lib") // @description : personal Library for line and box built in functions // @function get [x1: y1,x2,y2] in a tuple // @param line line // @returns tuple of [x1,y1,x2,y2] export LineXY(line line) => x1 = line.get_x1(line) x2 = line.get_x2(line) y1 = line.get_y1(line) y2 = line.get_y2(line) [x1,y1,x2,y2] // @function Create line with only the y1 value(when line == na) // when line != na set x1,y1,x2,y2 individually just 1 or all // - use just the line value to set the x2 to current bar or time will set to time // will auto pick xloc.bar_index or xloc.bar_time if not used by checking if // if x1 or x2 is > a number bar index couldnt be i.e. 1000000 // @param line x1 y1 x2 y2 xloc extend color style width // @returns : Line export Line(int x1 = na,float y1 = na,int x2 = na,float y2 = na, string extend = extend.none,color color = #000000, string style = line.style_solid,int width = 1,line line = na, bool delete = true) => var line Line = na bt = time_close - time x = na(x1) ? time : x1 y = na(y1) ? close : y1 xx = na(x2) ? x > 100000 ? last_bar_time + (50*bt) : last_bar_index + 50 : x2 yy = na(y2) ? y : y2 xloc = x > 100000 ? xloc.bar_time : xloc.bar_index if not na(line) if na(x1) x := line.get_x1(line) if na(y1) y := line.get_y1(line) if na(x2) xx := line.get_x2(line) if xx == last_bar_index[1] xx += 1 if xx == last_bar_time[1] xx += bt if na(y2) yy := y if delete line.delete(line) Line := line.new( x1 = x, y1 = y, x2 = xx, y2 = yy, xloc = xloc, extend = extend, color = color, style = style, width = width) Line // @function get [left,top,right,bottom] in a tuple // @param box box // @returns tuple of [left,top,right,bottom] export BoxXY(box box) => left = box.get_left(box) top = box.get_top(box) right = box.get_right(box) bottom = box.get_bottom(box) [left,top,right,bottom] // @function // Create box with only the top,bottom value(when box == na) // when box != na set left,top,right,bottom individually just 1 or all // - use just the box value to set the right to current bar or time, will set to time // if right is above a number that a bar_index wouldnt be above i.e. 1000000 // @param box left top right // bottom border_color border_width border_style extend xloc bgcolor text text_size text_color text_halign text_valign text_wrap // @returns Box export Box(int left = na,float top = na,int right = na,float bottom = na, color border_color = #00000073, int border_width = 1, string border_style = line.style_solid, string extend = extend.none, color bgcolor = #0000003f, string txt = '',string text_size = size.normal, color text_color = #000000, string text_halign = text.align_center,string text_valign = text.align_center,string text_wrap = text.wrap_auto, box box = na, bool delete = true) => var box Box = na bt = time_close - time Top = top Bottom = bottom Left = na(left) ? time : left Right = na(right) ? Left > 100000 ? last_bar_time + (50*bt) : last_bar_index + 50 : right xloc = Left > 100000 ? xloc.bar_time : xloc.bar_index if not na(box) if na(left) Left := box.get_left(box) if na(bottom) Bottom := box.get_bottom(box) if na(top) Top := box.get_top(box) if na(right) Right := box.get_right(box) if delete box.delete(box) Box := box.new( left = Left, top = top, right = Right, bottom = bottom, border_color = border_color, border_width = border_width, border_style = border_style, extend = extend, xloc = xloc, bgcolor = bgcolor, text = txt, text_size = text_size, text_color = text_color, text_halign = text_halign, text_valign = text_valign, text_wrap = text_wrap) Box // @function get [x,y,txt] in a tuple // @param label label // @returns tuple of [x,y,txt] export LabelXY(label label) => txt = label.get_text(label) x = label.get_x(label) y = label.get_y(label) [x,y,txt] // @function Create label with only the y1 value(when label == na) // when label != na set x1,y1,x2,y2 individually just 1 or all // - use just the label value to set the x2 to current bar or time will set to time // will auto pick xloc.bar_index or xloc.bar_time if not used by checking if // if x1 or x2 is > a number bar index couldnt be i.e. 1000000 // @param label txt x y xloc.yloc color style textcolor size textalign tooltip text_font // @returns Label export Label(int x = na,float y = na,string yloc = yloc.price,string txt = '',color color = #000000, string style = label.style_label_down ,color textcolor = #9acd32,string size = size.normal, string textalign = text.align_center,string tooltip = na,string text_font_family = font.family_default, label label = na, bool delete = true) => var label Label = na _x = na(x) ? time : x _y = na(y) ? close < open ? low : high : y _style = na(y) ? close < open ? label.style_label_down : label.style_label_up : style _text = txt _xloc = _x > 100000 ? xloc.bar_time : xloc.bar_index if not na(label) if na(x) _x := label.get_x(label) if na(y) _y := label.get_y(label) if na(txt) _text := label.get_text(label) if delete label.delete(label) Label := label.new( x = _x, y = _y, text = _text, xloc = _xloc, yloc = yloc, color = color, style = style, textcolor = textcolor, size = size, textalign = textalign, tooltip = tooltip, text_font_family = text_font_family) Label //Usage var label label = na var line line = na var box box = na box := Box(box = box,left = last_bar_index,txt = str.tostring(timenow),bottom = low,top = high) line := Line(line = line,x1 = bar_index - 50,y1 = close, delete = true) if barstate.islast label := Label(label = label,y = high,textalign = text.align_left,txt = str.tostring(bar_index) + ' | ' + str.format_time(timenow,'hh:mm:ssa','UTC-5')) [x,y,txt] = LabelXY(label) [left,top,right,bottom] = BoxXY(box) [x1,y1,x2,y2] = LineXY(line) label.set_text(label,label.get_text(label) + str.format('\nLabel | [x:{0}] [y:{1}] [txt:{2}] \nBox | [left:{3}] [top:{4}] [right:{5}] [bottom:{6}]\nLine | [x1:{7}] [y1:{8}] [x2:{9}] [y2:{10}]',x,y,txt,left,top,right,bottom,x1,y1,x2,y2))
CalulateWinLoss
https://www.tradingview.com/script/MhVLPufb-CalulateWinLoss/
Nut_Satit
https://www.tradingview.com/u/Nut_Satit/
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/ // © Nut_Satit //@version=5 // @description TODO: add library description here library("CalulateWinLoss", overlay=true) // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export colorwhitered(float value2color) => export_color = value2color < 0 ? color.red : color.white export_color export colorredwhite(float value2color) => export_color = value2color > 0 ? color.red : color.white export_color export calwinloss() => //TODO : add function body and return value here //Define for calulate win loss var count_loss = 0 var count_win = 0 var tmp_loss = 0 var tmp_win = 0 var max_loss = 0 var max_win = 0 var current_stat= 0 var win_stat = 0 var loss_stat = 0 win = ta.rising(strategy.wintrades, 1) loss = ta.rising(strategy.losstrades,1) win_long = win and strategy.position_size[1] > 0 win_short = win and strategy.position_size[1] < 0 loss_long = loss and strategy.position_size[1] > 0 loss_short = loss and strategy.position_size[1] < 0 // set Current Status to win loss for Calulate if (win) win_stat := win_stat+1 loss_stat := 0 count_win := count_win+1 current_stat := 1 if (loss) loss_stat := loss_stat+1 win_stat := 0 count_loss:= count_loss+1 current_stat := -1 if (current_stat[1]!=win) and (current_stat[1]!=loss) current_stat := 0 // Calulate max win status if (current_stat[1]==0 and current_stat==-1) tmp_win := 0 else if (current_stat[1]==0 and current_stat==1) tmp_win := tmp_win+1 if (tmp_win>max_win) max_win := tmp_win // Calulate max loss status if (current_stat[1]==0 and current_stat==1) tmp_loss := 0 else if (current_stat[1]==0 and current_stat==-1) tmp_loss := tmp_loss+1 if (tmp_loss>max_loss) max_loss := tmp_loss // Calulate value to Table me_close_trades = "Total:" + str.format("{0,number,#.#}", count_win+count_loss) + "\nWin:" + str.format("{0,number,#.#}", count_win) + " | Loss:" + str.format("{0,number,#.#}", count_loss) tv_close_trades = "Total:" + str.format("{0,number,#.#}", strategy.closedtrades) + "\nWin:" + str.format("{0,number,#.#}", strategy.wintrades) + " | Loss:" + str.format("{0,number,#.#}", strategy.losstrades) // Show table winlossDisplay var table winlossDisplay = table.new(position.bottom_left, 10, 4, bgcolor=color.new(color.white,70), frame_width=5, frame_color=color.black, border_color=color.black, border_width=1) table.cell(winlossDisplay, 0, 0, "", text_size=size.small, bgcolor = color.silver, text_color= color.new(color.white,0)) table.cell(winlossDisplay, 1, 0, "CloseTrades", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 2, 0, "Won", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 3, 0, "Lost", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 4, 0, "W/L Ratio", text_size=size.small,bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 5, 0, "WinRate%", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 6, 0, "Net Profit", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 7, 0, "Profit Factor", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 8, 0, "Max Drawdown", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 0, 1, "Me", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 1, 1, me_close_trades, text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 2, 1, str.format("{0,number,#.#}", max_win), text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 3, 1, str.format("{0,number,#.#}", max_loss), text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 4, 1, str.format("{0,number,#.##}", count_win/count_loss), text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 5, 1, str.format("{0,number,#.##}", 100*count_win/(count_win+count_loss)), text_size=size.small, text_color = color.new(colorwhitered(100*count_win/(count_win+count_loss)),0)) table.cell(winlossDisplay, 6, 1, str.format("{0,number,#.##}", 0), text_size=size.small,text_color = color.new(color.white,0)) table.cell(winlossDisplay, 7, 1, str.format("{0,number,#.##}", 0), text_size=size.small,text_color = color.new(color.white,0)) table.cell(winlossDisplay, 8, 1, str.format("{0,number,#.##}", 0), text_size=size.small,text_color = color.new(color.white,0)) table.cell(winlossDisplay, 0, 2, "TV", text_size=size.small, bgcolor = color.silver, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 1, 2, tv_close_trades, text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 2, 2, str.format("{0,number,#.#}", 0), text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 3, 2, str.format("{0,number,#.#}", 0), text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 4, 2, str.format("{0,number,#.##}", strategy.wintrades/strategy.losstrades), text_size=size.small, text_color = color.new(color.white,0)) table.cell(winlossDisplay, 5, 2, str.format("{0,number,#.##}", 100*strategy.wintrades/strategy.closedtrades), text_size=size.small,text_color = color.new(color.white,0)) table.cell(winlossDisplay, 6, 2, str.format("{0,number,#.##}", strategy.netprofit), text_size=size.small,text_color = color.new(colorwhitered(strategy.netprofit),0)) table.cell(winlossDisplay, 7, 2, str.format("{0,number,#.##}", strategy.grossprofit / strategy.grossloss), text_size=size.small,text_color = color.new(colorredwhite(strategy.grossprofit / strategy.grossloss),0)) table.cell(winlossDisplay, 8, 2, str.format("{0,number,#.##}", strategy.max_drawdown), text_size=size.small,text_color = color.new(colorredwhite(strategy.max_drawdown),0)) //return value [win_long,win_short,loss_long,loss_short] //[win_long,win_short,loss_long,loss_short] = calwinloss() // Your insert undercode to Show plot Win Loss icon // import Nut_Satit/CalulateWinLoss/version as calwinloss // [win_long,win_short,loss_long,loss_short] = calwinloss.calwinloss() // plotshape(win_long, title="Win Long", color=color.lime, location=location.belowbar,style=shape.triangleup,size=size.small, text="") // plotshape(win_short, title="Win Short", color=color.lime, location=location.abovebar,style=shape.triangledown,size=size.small,text="") // plotshape(loss_long, title="Loss Long", color=color.orange,location=location.belowbar,style=shape.triangleup,size=size.small, text="") // plotshape(loss_short,title="Loss Short",color=color.orange,location=location.abovebar,style=shape.triangledown,size=size.small,text="") export rangdate(int startDate, int finishDate) => //TODO : add function body and return value here // Backtesting day range // Your insert undercode [$time_cond]to Buy Sell Condition // ($time_cond and [Condition]) time_cond = time >= startDate and time <= finishDate
L_Index_4khansolo
https://www.tradingview.com/script/QwKVL6Qz-L-Index-4khansolo/
fourkhansolo
https://www.tradingview.com/u/fourkhansolo/
5
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/ // © fourkhansolo //@version=5 // library("L_Index_4khansolo") // ****************************************** All Imports ************************************************************************************ import fourkhansolo/MMRI_4khansolo/2 as mmri import fourkhansolo/L_Beta/4 as beta // ****************************************** Country Auto Select ****************************************** export countrySelect()=> // Source: // What economic data is available in pine? Accessed On Jul 1, 2022. https://www.tradingview.com/chart/s7pJ0Zi5/?solution=43000665359 // this will select the country automatically // Countries au = "AU" // Australia ca = "CA" // Canada eu = "EU" // European Union us = "US" // USA ind = "IN" // India ja = "JP" // Japan ch = "CH" // Switzerland ru = "RU" // Russia gb = "GB" // United Kingdom tr = "TR" // Turkey // Country Abbreviation. NIH. https://www.ncbi.nlm.nih.gov/books/NBK7249/ // doubleChecking with the ticker location locationDynamic = if syminfo.currency == currency.USD us else if syminfo.currency == currency.CAD ca else if syminfo.currency == currency.EUR eu else if syminfo.currency == currency.JPY ja else if syminfo.currency == currency.AUD au else if syminfo.currency == currency.CHF ch else if syminfo.currency == currency.RUB ru else if syminfo.currency == currency.GBP gb else if syminfo.currency == currency.TRY tr else if syminfo.ticker == "NIFTY" ind else us country=locationDynamic // ****************************************** Indicator Color ************************************************************************************ export positron(series float number)=> // This will basically change color based on positivity :) if number >= 0 color.new(color.green,1) else color.new(color.red,1) // ****************************************** Index: Invoke New Index ****************************************** // Available Current_Currency // US USD // CA CAD // JP JPY export indexName()=> // This one will need to import L_BearishMarketIndicator for countrySelect() // Appropiate Index (i.e., ETF) // Note this will only invoke the largest and NOT ALL of the index(es) // Future Implementation: RUPEE (when support comes), Other Currencies as well // Source: Accessed as of June 15, 2022. https://www.tradingview.com/pine-script-reference/v5/#var_syminfo{dot}currency indexName = if syminfo.currency == currency.USD //systeminfo.prefix "SPX" else if syminfo.currency == currency.CAD //syminfo.prefix == "TSX" or syminfo.prefix == "TSXV" or syminfo.prefix == "NEO" or syminfo.prefix == "CSE" "TSX" else if syminfo.currency == currency.JPY "NI225" else if syminfo.currency == currency.EUR "EU500" else "SPX" indexName // indexRSI = ticker.new(syminfo.prefix, index, session.regular, adjustment.splits) // DEBUGGING // lot(indexProperValue) // frequency="D" // ****************************************** Index: Relative Strength Index [RSI]****************************************** // RSI Days // Seven 7 // Fourteen 14 // Twenty One 21 // Fifty 50 // Hundred 100 // Two Hundred 200 export indexRSI(float indexProperValue)=> // This will use the index (from the above function) sevenRSI=ta.rsi(indexProperValue,7) fourteenRSI=ta.rsi(indexProperValue,14) twentyOneRSI=ta.rsi(indexProperValue,21) fiftyRSI=ta.rsi(indexProperValue,50) hundredRSI=ta.rsi(indexProperValue,100) twoHundredRSI=ta.rsi(indexProperValue,200) [sevenRSI,fourteenRSI,twentyOneRSI,fiftyRSI,hundredRSI,twoHundredRSI] // Source: accessed as of June 14, 2022. https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}rsi // Plotting the Index RSI // fourteenRSI ***************************************** export maRSI(float sevenRSI,float fourteenRSI,float twentyOneRSI,float fiftyRSI,float hundredRSI,float twoHundredRSI)=> sevenRSIma=ta.sma(sevenRSI,7) fourteenRSIma=ta.sma(fourteenRSI,14) twentyOneRSIma=ta.sma(twentyOneRSI,21) fiftyRSIma=ta.sma(fiftyRSI,50) hundredRSIma=ta.sma(hundredRSI,100) twoHundredRSIma=ta.sma(twoHundredRSI,200) [sevenRSIma,fourteenRSIma,twentyOneRSIma,fiftyRSIma,hundredRSIma,twoHundredRSIma] // ****************************************** RSI Plotting ****************************************** export colorRSIfull (float rsi, float rsiMA)=> rsiColor=if rsi >= 70 // Overbought Territory if rsiMA < rsi // RSI < 70 and RSI < RSIma // Strong Signal color.new(color.green,80) else if rsiMA > rsi color.new(color.red,45) else color.new(color.purple,45) else if rsi < 30 // Oversold Territory if rsiMA < rsi color.new(color.green,45) else if rsiMA >= rsi // Weak Signal color.new(color.red,80) // This will give out a darken red color else color.new(color.orange,45) else // Inclusive RSI between 70 and 30 if rsiMA > rsi // Weak Signal color.new(color.red,45) else // Strong Signal color.new(color.green,45) export rsiColor(float rsiInput)=> // this will change the color of the RSI in ranges colours = if rsiInput <= 30 color.new(color.red,1) else if rsiInput >31 and rsiInput <50 color.new(color.yellow,1) else if rsiInput >=50 and rsiInput <70 color.new(color.orange,1) else color.new(color.red,1) // Changing colors based on the less or more for the moving averages export rsiFillColor (float rsi,float maRSI, float opacity)=> rsiFillColor=if rsi > maRSI color.new(color.green,opacity) else color.new(color.red,opacity) export rsiCompartments(float rsi, series color colour)=> seventy = if rsi > 70 colour else color.new(color.red,80) fiftyPlus = if (rsi > 50) and (rsi < 70) colour fiftyLess = if rsi > 30 and rsi <50 colour thirty = if rsi < 30 colour else color.new(color.red,80) [seventy,fiftyPlus,fiftyLess,thirty] // ************************************************************ Location based Currency Index ************************************************************ export fiatIndexer()=> // ************************************************************ Establishing some variables ************************************************************ // Canada, USA, UK, Japan, EU can = "CXY" // Canada; Bank of Canada (BOC) usa = "DXY" // US; US FED (Fed) uk = "BXY" // Great Britain; Bank of England (BOE) jap = "JXY" // Japan; Bank of Japan (BOJ) eu = "EXY" // Europe; European Central Bank (ECB) fiatIndex = if syminfo.currency == currency.USD //if syminfo.ticker == "NASDAQ" or syminfo.ticker == "NYSE" or syminfo.ticker == "OTC" usa else if syminfo.currency == currency.CAD//if syminfo.ticker == "TSX" or syminfo.ticker == "TSXV" or syminfo.ticker == "NEO" or syminfo.ticker == "CSE" can else if syminfo.currency == currency.JPY//if syminfo.ticker == "SSE" or syminfo.ticker == "NSE" or syminfo.ticker == "FSE" or syminfo.ticker == "NSE" or syminfo.ticker == "TSE" or syminfo.ticker == "TFX" or syminfo.ticker == "TOCOM" or syminfo.ticker == "OSE" jap else if syminfo.currency == currency.GBP//if syminfo.ticker == "SSE" or syminfo.ticker == "NSE" or syminfo.ticker == "FSE" or syminfo.ticker == "NSE" or syminfo.ticker == "TSE" or syminfo.ticker == "TFX" or syminfo.ticker == "TOCOM" or syminfo.ticker == "OSE" uk else if syminfo.currency == currency.EUR//if syminfo.ticker == "SSE" or syminfo.ticker == "NSE" or syminfo.ticker == "FSE" or syminfo.ticker == "NSE" or syminfo.ticker == "TSE" or syminfo.ticker == "TFX" or syminfo.ticker == "TOCOM" or syminfo.ticker == "OSE" eu else usa // ****************************************** Index: Moving Average Convergence Divergence [MACD] ****************************************** export colorMACD(float macdLine, float signalLine)=> properSignal=if macdLine<=signalLine color.new(color.red,20) else color.new(color.green,20) export indexMACD(series float indexProperValue)=> //you will need the two variables below outside of the funcition //indexValue=indexName() //indexProperValue=request.security(indexValue, "D", close) [macdLineIndex, signalLineIndex, histLineIndex] = ta.macd(indexProperValue, 12, 26, 9) export colour(float col,float col2)=> exportColor=if col > col2 color.new(color.green,30) else color.new(color.red,30) // The following function will take a correct period export returns_calculation_length (string returns_calculation_intervals,int returns_calculation_week,int returns_calculation_day)=> // Needed //returns_calculation_week = input.int(252, title="How may weekdays?", options=[250,251,252,253,254,255,256,257,258,259,260]) //returns_calculation_day = input.int(365, title="How many days?", options=[365,366]) // length = returns_calculation_length(intervals,returns_calculation_week,returns_calculation_day) result = if returns_calculation_intervals == "D" returns_calculation_day else if returns_calculation_intervals == "W" returns_calculation_week else 12 export select_index(simple string returns_calculation_index) => // This needs >> // returns_calculation_index = input.session("Auto", "Pick Index", options=["Auto","NDX","IXIC", "SPX", "TSX","W4500"]) // also this >> // price_index = request.security(name_of_the_index, intervals, close) // D as default result = if returns_calculation_index =="Auto" indexName() else returns_calculation_index export select_security_or_index(simple string ticker_or_index, simple string returns_calculation_index)=> name_of_the_index=if ticker_or_index == "Index!" select_index(returns_calculation_index) //indexName() // Retrieving the name of the index else syminfo.tickerid export returns (series float current_price, series float previous_price, float length)=> // returns implies mean values delta =0.0 for i = 0 to length -1 // this loop basically calculates for changes tallied up /sumed up delta:=delta+((current_price-previous_price)/previous_price) mean = (delta/length)*100 export multiplier(simple int returns_calculation_how_long,int length)=>//string intervals, result =returns_calculation_how_long*length export stochastic_color(series float fast, series float slow)=> result = if fast >=80 or slow >=80 if fast > slow color.new(color.green,95) else color.new(color.red,95) else if fast > slow color.new(color.green,90) else color.new(color.red,90) export ma_color(series float ma50, series float ma200)=> ma50Close=ta.crossover(ma50,close) ma200Close=ta.crossover(ma200,close) ma50And200Close=(ma50 >=close) and (ma200 >= close) ma50Less200=ma200>ma50 maColor = if close <= ma50 and ma50Close color.new(color.white,80) else if close <=ma200 and ma200Close color.new(color.orange,70) else if ma50And200Close //and not bearishMarketDefinition if ma50Less200 color.new(color.red,40) else if ma50>ma200 color.new(color.red,60)// :P else na else na // ****************************************** Actual Work is below! ****************************************** intervals = input.session("D", "Day | Week | Month", options=["D", "W", "M"]) //returns_calculation_intervals = input.session("D", "Returns Calculation: Day | Week | Month", options=["D", "W", "M"]) ticker_or_index = input.session("Index!", "ticker or index? ", options=["Stock!","Index!"]) // //returns_calculation_intervals = input.session("D", "Returns Calculation: Day | Week | Month", options=["D", "W", "M"]) returns_calculation_day = input.int(252, title="How may days?", options=[250,251,252,253,254,255,256,257,258,259,260,365,366])// this implies days returns_calculation_week = 52//returns_calculation_day/7 //returns_calculation_week = input.int(52, title="How many weeks?", options=[52,53]) returns_calculation_how_long = input.int(1, title="For how long?", options=[1,2,3,4,5,6,7,8,9,10,15]) returns_calculation_index = input.session("Auto", "Pick Index", options=["Auto","NDQ","NDX","DJI","IXIC", "SPX", "TSX","W4500"]) length = returns_calculation_length(intervals,returns_calculation_week,returns_calculation_day)//,returns_calculation_how_long)// returns_calculation_how_long aka multiplier true_length=multiplier(returns_calculation_how_long,length)// if 2Y selected, 2x... = 2(something) //plot(true_length) name_of_the_index=select_security_or_index(ticker_or_index,returns_calculation_index) index_price_currently = request.security(name_of_the_index, intervals, close) // D as default index_price_previously = request.security(name_of_the_index, intervals, close[1]) // D as default // MMRI dxy = request.security("DXY", intervals, close) // 1 Day tnx = request.security("TNX", intervals, close) // 1 Day [mmri,mmri_color]=mmri.mmri(dxy,tnx) // Stochastics periodK = 14//input.int(14, title="%K Length", minval=1) smoothK = 1//input.int(1, title="%K Smoothing", minval=1) periodD = 3//input.int(3, title="%D Smoothing", minval=1) k = ta.sma(ta.stoch(close, high, low, periodK), smoothK) d = ta.sma(k, periodD) stochastic_color=stochastic_color(k,d) //plot(k) //plot(d,color=color.purple) // MACD [macdLineIndex, signalLineIndex, histLineIndex] = indexMACD(index_price_currently)// alt indexProperValue colorMACD=colorMACD(macdLineIndex,signalLineIndex) //RSI with RSIma [sevenRSI,fourteenRSI,twentyOneRSI,fiftyRSI,hundredRSI,twoHundredRSI]=indexRSI(index_price_currently) [sevenRSIma,fourteenRSIma,twentyOneRSIma,fiftyRSIma,hundredRSIma,twoHundredRSIma]=maRSI(sevenRSI,fourteenRSI,twentyOneRSI,fiftyRSI,hundredRSI,twoHundredRSI) colorRSI=colorRSIfull(fourteenRSI,fourteenRSIma) [seventyRSI,fiftyPlusRSI,fiftyLessRSI,thirtyRSI]=rsiCompartments(fourteenRSI,colorRSI) fourteen_rsi_plot=plot(fourteenRSI, color=color.green, title="14 Day RSI") fourteen_rsi_plot_ma=plot(fourteenRSIma, color=color.red,title="14 Day RSI MA") fill(fourteen_rsi_plot,fourteen_rsi_plot_ma,color=colorRSI) // ****************************************** Plotting Framework Color ************************************************************************************ //zero to hundred zero_plot=hline(0, title="0",color=color.new(color.white,70)) five_plot=hline(5, title="5",color=color.new(color.yellow,70)) twenty_plot=hline(20, title="20",display=display.none) thirty_plot=hline(30, title="30",color=color.new(color.orange,40)) fifty_plot=hline(50, title="50",color=color.new(color.white,70)) seventy_plot=hline(70, title="70",color=color.new(color.orange,40)) eighty_plot=hline(80, title="80",display=display.none) ninety_plot=hline(90, title="90",color=color.new(color.red,70)) ninety_five_plot=hline(95, title="95",color=color.new(color.red,70)) // Plotting the Indicators fill(ninety_plot,ninety_five_plot, color=mmri_color) // MMRI fill(five_plot,zero_plot, color=colorMACD) // MACD fill(thirty_plot,seventy_plot,color=color.new(color.blue,99)) // Polishing the RSI fill(ninety_plot,five_plot, color=stochastic_color) // stochastic_color
cnd
https://www.tradingview.com/script/2nEOvkTZ-cnd/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 // @description a standalone cumulative normal distrubtion routine that does not require any external libraries. // This includes 3 differnt CND calculations: Hart (1968), Abromowitz and Stegun (1974) Polynomial Approximation, and // Newton-Cotes using Boole's rule. // comments: // The cumulative normal distribution function integral has no closed-form solution, so a numerical approximation must be used. // Recent research has shown that a high precision approximation can be of great importance in options valuation (West, 2005b). // For this reason, we recommend the use of the Hart algorithm, which offers double precision. I have also included third- and // fifth-degree polynomial approximations that are well known from the options literature. The polynomial approximations are known to // suffer from inaccuracies far out in the tails and can in some special situations result in completely wrong options prices. // reference: // The Complete Guide to Option Pricing Formulas, 2nd ed. (Espen Gaarder Haug) library("cnd") // @function Returns the Cumulative Normal Distribution (CND) using the Hart (1968) method. // @param x float, // @returns float. export CND1(float x)=> float Exponential = 0 float SumA = 0 float SumB = 0 float CND = 0 float y = math.abs(x) if y > 37 CND := 0 else Exponential := math.exp(-math.pow(y, 2) / 2) if y < 7.07106781186547 SumA := 0.0352624965998911 * y + 0.700383064443688 SumA := SumA * y + 6.37396220353165 SumA := SumA * y + 33.912866078383 SumA := SumA * y + 112.079291497871 SumA := SumA * y + 221.213596169931 SumA := SumA * y + 220.206867912376 SumB := 0.0883883476483184 * y + 1.75566716318264 SumB := SumB * y + 16.064177579207 SumB := SumB * y + 86.7807322029461 SumB := SumB * y + 296.564248779674 SumB := SumB * y + 637.333633378831 SumB := SumB * y + 793.826512519948 SumB := SumB * y + 440.413735824752 CND := Exponential * SumA / SumB else SumA := y + 0.65 SumA := y + 4 / SumA SumA := y + 3 / SumA SumA := y + 2 / SumA SumA := y + 1 / SumA CND := Exponential / (SumA * 2.506628274631) CND := x > 0 ? 1 - CND : CND CND // @function Returns the Cumulative Normal Distribution (CND) using the Abromowitz and Stegun (1974) Polynomial Approximation. // @param x float, // @returns float. export CND2(float x)=> float CND2 = 0 if x == 0 CND2 := 0.5 else float L = 0 float k = 0 var float a1 = 0.31938153 var float a2 = -0.356563782 var float a3 = 1.781477937 var float a4 = -1.821255978 var float a5 = 1.330274429 L := math.abs(x) k := 1 / (1 + 0.2316419 * L) CND2 := 1 - 1 / math.sqrt(2 * math.pi) * math.exp(-math.pow(L, 2) / 2) * (a1 * k + a2 * math.pow(k, 2) + a3 * math.pow(k, 3) + a4 * math.pow(k, 4) + a5 * math.pow(k, 5)) if x < 0 CND2 := 1 - CND2 CND2 // internal normal distribution function ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out // internal Newton-Cotes method, Boole’s rule Boole(float StartPoint, float EndPoint, int n)=> float[] X = array.new<float>(n + 1 , 0) float[] Y = array.new<float>(n + 1 , 0) float delta_x = (EndPoint - StartPoint) / n for i = 0 to n array.set(X, i, StartPoint + i * delta_x) array.set(Y, i, ND(array.get(X, i))) float sum = 0 for t = 0 to (n - 1) / 4 int ind = 4 * t sum += (1 / 45.0) * (14 * array.get(Y, ind) + 64 * array.get(Y, ind + 1) + 24 * array.get(Y, ind + 2) + 64 * array.get(Y, ind + 3) + 14 * array.get(Y, ind + 4)) * delta_x sum // @function Returns the Cumulative Normal Distribution (CND) using Newton-Cotes method, Boole’s rule // @param x float, // @returns float. export CND3(float x)=> float out = Boole(-10.0, x, 240) out // error function erf(float xin)=> float[] cof = array.new<float>(28, 0) array.set(cof, 0, -1.3026537197817094) array.set(cof, 1, 6.4196979235649026e-1) array.set(cof, 2, 1.9476473204185836e-2) array.set(cof, 3, -9.561514786808631e-3) array.set(cof, 4, -9.46595344482036e-4) array.set(cof, 5, 3.66839497852761e-4) array.set(cof, 6, 4.2523324806907e-5) array.set(cof, 7, -2.0278578112534e-5) array.set(cof, 8, -1.624290004647e-6) array.set(cof, 9, 1.303655835580e-6) array.set(cof, 10, 1.5626441722e-8) array.set(cof, 11, -8.5238095915e-8) array.set(cof, 12, 6.529054439e-9) array.set(cof, 13, 5.059343495e-9) array.set(cof, 14, -9.91364156e-10) array.set(cof, 15, -2.27365122e-10) array.set(cof, 16, 9.6467911e-11) array.set(cof, 17, 2.394038e-12) array.set(cof, 18, -6.886027e-12) array.set(cof, 19, 8.94487e-13) array.set(cof, 20, 3.13092e-13) array.set(cof, 21, -1.12708e-13) array.set(cof, 22, 3.81e-16) array.set(cof, 23, 7.106e-15) array.set(cof, 24, -1.523e-15) array.set(cof, 25, -9.4e-17) array.set(cof, 26, 1.21e-16) array.set(cof, 27, -2.8e-17) bool isneg = false float d = 0 float dd = 0 float x = xin if xin < 0 x := -xin isneg := true float t = 2 / (2 + x) float ty = 4 * t - 2 for j = array.size(cof) - 1 to 1 float tmp = d d := ty * d - dd + array.get(cof, j) dd := tmp float res = t * math.exp(-x * x + 0.5 * (array.get(cof, 0) + ty * d) - dd) out = isneg ? res - 1 : 1 - res out // Complementary Error Function erfc(float x)=> out = 1 - erf(x) out // @function Returns the standard normal cumulative distribution function. The distribution has a mean of 0 (zero) and a standard deviation of one. Use this function in place of a table of standard normal curve areas. // @param Z float, The value for which you want the distribution. // @returns float, standard normal cumulative distribution function export CND4(float a)=> float NPY_SQRT1_2 = 0.707106781186547524400844362104849039 float x = 0 float y = 0 float z = 0 if na(a) runtime.error("ndtr") x := a * NPY_SQRT1_2 z := math.abs(x) if z < NPY_SQRT1_2 y := 0.5 + 0.5 * erf(x) else y := 0.5 * erfc(z) if x > 0 y := 1.0 - y y // example usage: inx = input.float(0.5) out1 = CND1(inx) out2 = CND2(inx) out3 = CND3(inx) out4 = CND4(inx) plot(out1, "out1") plot(out2, "out2") plot(out3, "out3") plot(out4, "out4")
chi2Inv
https://www.tradingview.com/script/GoCcwJ35-chi2Inv/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 // @description Returns the inverse of the right-tailed or left-tailed probability of the chi-squared distribution. // reference: // https://github.com/zetos/inv-chisquare-cdf library("chi2Inv") // import gamma log functions import RicardoSantos/MathSpecialFunctionsGamma/1 as gl //inverse regularized low gamma function invRegLowGamma(p, a)=> float a1 = a - 1 float EPS = 1e-8 float gln = gl.GammaLn(a) float inverseRegLowGamma = 0 float err = 0 float t = 0 float u = 0 float pp = 0 float lna1 = 0 float afac = 0 float out = 0 if a > 1 lna1 := math.log(a1) afac := math.exp(a1 * (lna1 - 1) - gln) pp := (p < 0.5) ? p : 1 - p t := math.sqrt(-2 * math.log(pp)) inverseRegLowGamma := (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t if (p < 0.5) inverseRegLowGamma := -inverseRegLowGamma inverseRegLowGamma := math.max(1e-3, a * math.pow(1 - 1 / (9 * a) - inverseRegLowGamma / (3 * math.sqrt(a)), 3)) else t := 1 - a * (0.253 + a * 0.12) if p < t inverseRegLowGamma := math.pow(p / t, 1 / a) else inverseRegLowGamma := 1 - math.log(1 - (p - t) / (1 - t)) for j = 0 to 12 - 1 if inverseRegLowGamma <= 0 out := 0 err := gl.GammaLowerRegularized(a, inverseRegLowGamma) - p if a > 1 t := afac * math.exp(-(inverseRegLowGamma - a1) + a1 * (math.log(inverseRegLowGamma) - lna1)) else t := math.exp(-inverseRegLowGamma + a1 * math.log(inverseRegLowGamma) - gln) u := err / t t := u / (1 - 0.5 * math.min(1, u * ((a - 1) / inverseRegLowGamma - 1))) inverseRegLowGamma -= t if inverseRegLowGamma <= 0 inverseRegLowGamma := 0.5 * (inverseRegLowGamma + t) if math.abs(t) < EPS * inverseRegLowGamma break out := inverseRegLowGamma // @function Returns the inverse of the right-tailed or left-tailed probability of the chi-squared distribution. // @param pin float, probability // @param deg float, degress of freedom. // @param tail string, tail, either "r" for right or "l" for left // @returns float. export chi2Inv(float pin, float deg, string tail)=> float p = tail == "l" ? pin : 1 - pin out = 2 * invRegLowGamma(p, 0.5 * deg) out //example usage right = chi2Inv(.93, 2, "r") left = chi2Inv(.93, 2, "l") plot(right, "right") plot(left, "left")
cbnd
https://www.tradingview.com/script/J6n6adzN-cbnd/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 // @description a standalone Cumulative Bivariate Normal Distribution (CBND) functions that do not require any external libraries. // This includes 3 differnt CBND calculations: Drezner(1978), Drezner and Wesolowsky (1990), and Genz (2004) // comments: // The standardized cumulative normal distribution function returns the probability that one random // variable is less than a and that a second random variable is less than b when the correlation // between the two variables is p. Since no closed-form solution exists for the bivariate cumulative // normal distribution, we present three approximations. The first one is the well-known // Drezner (1978) algorithm. The second one is the more efficient Drezner and Wesolowsky (1990) // algorithm. The third is the Genz (2004) algorithm, which is the most accurate one and therefore // our recommended algorithm. West (2005b) and Agca and Chance (2003) discuss the speed and // accuracy of bivariate normal distribution approximations for use in option pricing in // ore detail. // reference: // The Complete Guide to Option Pricing Formulas, 2nd ed. (Espen Gaarder Haug) library("cbnd") //import Cumulative Normal Distribution import loxx/cnd/1 // @function Returns the Cumulative Bivariate Normal Distribution (CBND) using Drezner 1978 Algorithm // @param A float, // @param b float, // @param rho float, // @returns float. export CBND1(float A, float b, float rho)=> float g = 0 float P = 0 float sum = 0 float CBND2 = 0 array<float> x = array.new<float>(5, 0) array.set(x, 0, 0.018854042) array.set(x, 1, 0.038088059) array.set(x, 2, 0.0452707394) array.set(x, 3, 0.038088059) array.set(x, 4, 0.018854042) array<float> y = array.new<float>(5, 0) array.set(y, 0, 0.04691008) array.set(y, 1, 0.23076534) array.set(y, 2, 0.5) array.set(y, 3, 0.76923466) array.set(y, 4, 0.95308992) sum := 0 for i = 0 to 4 P := array.get(y, i) * rho g := 1 - P * P sum += array.get(x, i) * math.exp((2 * A * b * P - A * A - b * b) / g / 2) / math.sqrt(g) CBND2 := rho * sum + cnd.CND1(A) * cnd.CND1(b) CBND2 // @function Returns the Cumulative Bivariate Normal Distribution (CBND) using Drezner and Wesolowsky (1990) function // @param A float, // @param b float, // @param rho float, // @returns float. export CBND2(float A, float b, float rho)=> // modified/corrected from the second function in Drez & Wes paper pg. 105 // 0/0 case resolved by l'H rule float h1 = 0 float h2 = 0 float LH = 0 float h12 = 0 float h3 = 0 float h5 = 0 float h6 = 0 float h7 = 0 float h8 = 0 float r1 = 0 float r2 = 0 float r3 = 0 float rr = 0 float AA = 0 float ab = 0 float CBND4 = 0 array<float> x = array.new<float>(5, 0) array.set(x, 0, 0.04691008) array.set(x, 1, 0.23076534) array.set(x, 2, 0.5) array.set(x, 3, 0.76923466) array.set(x, 4, 0.95308992) array<float> W = array.new<float>(5, 0) array.set(W, 0, 0.018854042) array.set(W, 1, 0.038088059) array.set(W, 2, 0.0452707394) array.set(W, 3, 0.038088059) array.set(W, 4, 0.018854042) h1 := A h2 := b h12 := (h1 * h1 + h2 * h2) / 2 if math.abs(rho) >= 0.7 r2 := 1 - rho * rho r3 := math.sqrt(r2) if rho < 0 h2 := -h2 h3 := h1 * h2 h7 := math.exp(-h3 / 2) if math.abs(rho) < 1 h6 := math.abs(h1 - h2) h5 := h6 * h6 / 2 h6 := h6 / r3 AA := 0.5 - h3 / 8 ab := 3 - 2 * AA * h5 LH := 0.13298076 * h6 * ab * (1 - cnd.CND1(h6)) - math.exp(-h5 / r2) * (ab + AA * r2) * 0.053051647 for i = 0 to 4 r1 := r3 * array.get(x, i) rr := r1 * r1 r2 := math.sqrt(1 - rr) if h7 == 0 h8 := 0 else h8 := math.exp(-h3 / (1 + r2)) / r2 / h7 LH := LH - array.get(W, i) * math.exp(-h5 / rr) * (h8 - 1 - AA * rr) CBND4 := LH * r3 * h7 + cnd.CND1(math.min(h1, h2)) if rho < 0 CBND4 := cnd.CND1(h1) - CBND4 else h3 := h1 * h2 if rho != 0 for i = 0 to 4 r1 := rho * array.get(x, i) r2 := 1 - r1 * r1 LH := LH + array.get(W, i) * math.exp((r1 * h3 - h12) / r2) / math.sqrt(r2) CBND4 := cnd.CND1(h1) * cnd.CND1(h2) + rho * LH CBND4 // @function Returns the Cumulative Bivariate Normal Distribution (CBND) using Genz (2004) algorithm (this is the preferred method) // @param x float, // @param y float, // @param rho float, // @returns float. export CBND3(float x, float y, float rho)=> // A function for computing bivariate normal probabilities. // Alan Genz // Department of Mathematics // Washington State University // Pullman, WA 99164-3113 // Email : [email protected] // This function is based on the method described by // Drezner, Z and G.O. Wesolowsky, (1990), // On the computation of the bivariate normal integral, // Journal of Statist. Comput. Simul. 35, pp. 101-107, // with major modifications for double precision, and for |R| close to 1. // This code was originally transelated into VBA by Graeme West int LG = 0 int NG = 0 float h = 0 float k = 0 float hk = 0 float hs = 0 float BVN = 0 float Ass = 0 float asr = 0 float sn = 0 float A = 0 float b = 0 float bs = 0 float c = 0 float d = 0 float xs = 0 float rs = 0 float CBND = 0 matrix<float> XX = matrix.new<float>(11, 4, 0) matrix<float> W = matrix.new<float>(11, 4, 0) matrix.set(W, 1, 1, 0.17132449237917) matrix.set(XX, 1, 1, -0.932469514203152) matrix.set(W, 2, 1, 0.360761573048138) matrix.set(XX, 2, 1, -0.661209386466265) matrix.set(W, 3, 1, 0.46791393457269) matrix.set(XX, 3, 1, -0.238619186083197) matrix.set(W, 1, 2, 0.0471753363865118) matrix.set(XX, 1, 2, -0.981560634246719) matrix.set(W, 2, 2, 0.106939325995318) matrix.set(XX, 2, 2, -0.904117256370475) matrix.set(W, 3, 2, 0.160078328543346) matrix.set(XX, 3, 2, -0.769902674194305) matrix.set(W, 4, 2, 0.203167426723066) matrix.set(XX, 4, 2, -0.587317954286617) matrix.set(W, 5, 2, 0.233492536538355) matrix.set(XX, 5, 2, -0.36783149899818) matrix.set(W, 6, 2, 0.249147045813403) matrix.set(XX, 6, 2, -0.125233408511469) matrix.set(W, 1, 3, 0.0176140071391521) matrix.set(XX, 1, 3, -0.993128599185095) matrix.set(W, 2, 3, 0.0406014298003869) matrix.set(XX, 2, 3, -0.963971927277914) matrix.set(W, 3, 3, 0.0626720483341091) matrix.set(XX, 3, 3, -0.912234428251326) matrix.set(W, 4, 3, 0.0832767415767048) matrix.set(XX, 4, 3, -0.839116971822219) matrix.set(W, 5, 3, 0.10193011981724) matrix.set(XX, 5, 3, -0.746331906460151) matrix.set(W, 6, 3, 0.118194531961518) matrix.set(XX, 6, 3, -0.636053680726515) matrix.set(W, 7, 3, 0.131688638449177) matrix.set(XX, 7, 3, -0.510867001950827) matrix.set(W, 8, 3, 0.142096109318382) matrix.set(XX, 8, 3, -0.37370608871542) matrix.set(W, 9, 3, 0.149172986472604) matrix.set(XX, 9, 3, -0.227785851141645) matrix.set(W, 10, 3, 0.152753387130726) matrix.set(XX, 10, 3, -0.0765265211334973) if math.abs(rho) < 0.3 NG := 1 LG := 3 else if math.abs(rho) < 0.75 NG := 2 LG := 6 else NG := 3 LG := 10 h := -x k := -y hk := h * k BVN := 0 if math.abs(rho) < 0.925 if math.abs(rho) > 0 hs := (h * h + k * k) / 2 asr := math.asin(rho) for i = 1 to LG for ISs = -1 to 1 by 2 sn := math.sin(asr * (ISs * matrix.get(XX, i, NG) + 1) / 2) BVN := BVN + matrix.get(W, i, NG) * math.exp((sn * hk - hs) / (1 - sn * sn)) BVN := BVN * asr / (4 * math.pi) BVN := BVN + cnd.CND1(-h) * cnd.CND1(-k) else if rho < 0 k := -k hk := -hk if math.abs(rho) < 1 Ass := (1 - rho) * (1 + rho) A := math.sqrt(Ass) bs := math.pow(h - k, 2) c := (4 - hk) / 8 d := (12 - hk) / 16 asr := -(bs / Ass + hk) / 2 if asr > -100 BVN := A * math.exp(asr) * (1 - c * (bs - Ass) * (1 - d * bs / 5) / 3 + c * d * Ass * Ass / 5) if -hk < 100 b := math.sqrt(bs) BVN := BVN - math.exp(-hk / 2) * math.sqrt(2 * math.pi) * cnd.CND1(-b / A) * b * (1 - c * bs * (1 - d * bs / 5) / 3) A := A / 2 for i = 1 to LG for ISs = -1 to 1 by 2 xs := math.pow(A * (ISs * matrix.get(XX, i, NG) + 1), 2) rs := math.sqrt(1 - xs) asr := -(bs / xs + hk) / 2 if asr > -100 BVN := BVN + A * matrix.get(W, i, NG) * math.exp(asr) * (math.exp(-hk * (1 - rs) / (2 * (1 + rs))) / rs - (1 + c * xs * (1 + d * xs))) BVN := -BVN / (2 * math.pi) if rho > 0 BVN := BVN + cnd.CND1(-math.max(h, k)) else BVN := -BVN if k > h BVN := BVN + cnd.CND1(k) - cnd.CND1(h) CBND := BVN CBND x = input.float(0.5) y = input.float(0.5) rho = input.float(0.95) out1 = CBND1(x, y, rho) out2 = CBND2(x, y, rho) out3 = CBND3(x, y, rho) plot(out1, "Drezner 1978 ") plot(out2, "Drezner-Weso-90a") plot(out3, "Genze")
TradingWolfLibary
https://www.tradingview.com/script/SYDhROCh-TradingWolfLibary/
TradingWolf
https://www.tradingview.com/u/TradingWolf/
11
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/ // © TradingWolf //@version=5 library("TradingWolfLibary") // @function Gets a Moving Average based on type // @param int length The MA period // @param string maType The type of MA // @returns A moving average with the given parameters export getMA(string maType, simple int length) => switch maType "EMA" => ta.ema(close, length) "SMA" => ta.sma(close, length) "HMA" => ta.hma(close, length) "WMA" => ta.wma(close, length) "VWMA" => ta.vwma(close, length) "VWAP" => ta.vwap => e1 = ta.ema(close, length) e2 = ta.ema(e1, length) 2 * e1 - e2 // @function Calculates and returns Minimum stop loss // @param float entry price (Close if calculating on the entry candle) // @param simple int Calculate how many bars back to look at swings // @param float Minimum Stop Loss allowed (Should be x 0.01) if input // @param string Direciton of trade either "Long" or "Short" // @returns Stop Loss Value export minStop(float _entry, simple int _swingDistance, float _minStop, string _direction) => if _direction == "Long" swingLow = ta.lowest(low, _swingDistance) distance = ((_entry - swingLow)/swingLow) stop = _minStop > distance ? _entry*(1-_minStop) : swingLow else if _direction == "Short" swingHigh = ta.highest(high,_swingDistance) distance = ((swingHigh-_entry)/_entry) stop = _minStop > distance ? _entry*(1+_minStop) : swingHigh // @function Calculates and returns Minimum/Maximum stop loss // @param float entry price (Close if calculating on the entry candle) // @param simple int Calculate how many bars back to look at swings // @param float Minimum Stop Loss allowed (Should be x 0.01) if input // @param float Maximum Stop Loss allowed (Should be x 0.01) if input // @param string Direciton of trade either "Long" or "Short" // @returns Stop Loss Value export minmaxStop(float _entry, float _swing, float _minStop, float _maxStop, string _direction) => if _direction == "Long" distance = ((_entry - _swing)/_swing) stop = _minStop > distance ? _entry*(1-_minStop) : _maxStop < distance ? _entry*(1-_maxStop) : _swing else if _direction == "Short" distance = ((_swing-_entry)/_entry) stop = _minStop > distance ? _entry*(1+_minStop) : _maxStop < distance ? _entry*(1+_maxStop) : _swing // @function Calculates the take profit value // @param float entry price (Close if calculating on the entry candle) // @param float stop would be the variable calculated just before your TP, you can use the minmaxStop // @param float ratio is a reward multiplier // @param string direction is the direction of the trade // @returns Take proit value export tpCalc(float _entry, float _stop, float _ratio, string _direction) => if _direction == "Long" take = ((_entry - _stop)*_ratio) + _entry else if _direction == "Short" take = _entry - ((_stop - _entry)*_ratio) // @function Calculates the Stop Loss using ATR // @param float entry price (Close if calculating on the entry candle) // @param float ATR Risk // @param string direction is the direction of the trade // @returns Take proit value export atrStop(float _entry, float _risk, string _direction)=> atr = ta.rma(ta.tr(true), 14) if _direction == "Long" stop = _entry - (atr*_risk) else if _direction == "Short" stop = _entry + (atr*_risk) // @function Calculates the Take profitusing ATR // @param float entry price (Close if calculating on the entry candle) // @param float ATR Reward // @param string direction is the direction of the trade // @returns Take proit value export atrTake(float _entry, float _reward, string _direction)=> atr = ta.rma(ta.tr(true), 14) if _direction == "Long" take = _entry + (atr*_reward) else if _direction == "Short" take = _entry - (atr*_reward)
Time_Filter
https://www.tradingview.com/script/MNJr4b6o-Time-Filter/
agprado
https://www.tradingview.com/u/agprado/
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/ // © agprado //@version=5 // @description Time filters for trading strategies. library(title="Time_Filter", overlay = true) // @function f_isInWeekDay - Filter by week day or by time delimited session. // @param _timeZone - Time zone to use when filter allowed trading by days of the week. // @param _byWeekDay - Filter allowed trading time by days of the week. // @param _byMon - Is Monday a trading day? // @param _byTue - Is Tuesday a trading day? // @param _byWed - Is Wednesday a trading day? // @param _byThu - Is Thursday a trading day? // @param _byFri - Is Friday a trading day? // @param _bySat - Is Saturday a trading day? // @param _bySun - Is Sunday a trading day? // @returns series of bool whether or not the time is inside the current day. export f_isInWeekDay( string _timeZone, simple bool _byWeekDay, simple bool _byMon, simple bool _byTue, simple bool _byWed, simple bool _byThu, simple bool _byFri, simple bool _bySat, simple bool _bySun) => _today = dayofweek(time, _timeZone) _isWeekDay = not _byWeekDay ? true : _byMon and _today == dayofweek.monday ? true : _byTue and _today == dayofweek.tuesday ? true : _byWed and _today == dayofweek.wednesday ? true : _byThu and _today == dayofweek.thursday ? true : _byFri and _today == dayofweek.friday ? true : _bySat and _today == dayofweek.saturday ? true : _bySun and _today == dayofweek.sunday ? true : false // @function f_isInSession - Is the current time with in the allowed trading session time. // @param _timeZone - Time zone to use when filter allowed trading by days of the week. // @param _bySession_1 - Filter allowed trading time with in hours defined in _timeSession_1 // @param _timeSession_1 - Hours with in trading is allowed. // @param _bySession_2 - Filter allowed trading time with in hours defined in _timeSession_2 // @param _timeSession_2 - Hours with in trading is allowed. // @returns series of bool whether or not the time is inside selected session. export f_isInSession(simple string _timeZone, simple bool _bySession_1, simple string _timeSession_1, simple bool _bySession_2, simple string _timeSession_2) => _inSession = not _bySession_1 ? true : _bySession_1 and time(timeframe.period, _timeSession_1, _timeZone) ? true : _bySession_2 and time(timeframe.period, _timeSession_2, _timeZone) ? true : false // @function f_isTradingAllowed - Is the current time with in the allowed. // @param _timeZone - Time zone to use when filter allowed trading by days of the week. // @param _byWeekDay - Filter allowed trading time by days of the week. // @param _byMon - Is Monday a trading day? // @param _byTue - Is Tuesday a trading day? // @param _byWed - Is Wednesday a trading day? // @param _byThu - Is Thursday a trading day? // @param _byFri - Is Friday a trading day? // @param _bySat - Is Saturday a trading day? // @param _bySun - Is Sunday a trading day? // @param _bySession_1 - Filter allowed trading time with in hours defined in _timeSession_1 // @param _timeSession_1 - Hours with in trading is allowed. // @param _bySession_2 - Filter allowed trading time with in hours defined in _timeSession_2 // @param _timeSession_2 - Hours with in trading is allowed. // @returns series of bool whether or not trading is allowed at the current time. export f_isTradingAllowed(simple string _timeZone, simple bool _byWeekDay, simple bool _byMon, simple bool _byTue, simple bool _byWed, simple bool _byThu, simple bool _byFri, simple bool _bySat, simple bool _bySun, simple bool _bySession_1, simple string _timeSession_1, simple bool _bySession_2, simple string _timeSession_2) => _inWeekDay = f_isInWeekDay(_timeZone, _byWeekDay, _byMon, _byTue, _byWed, _byThu, _byFri, _bySat, _bySun) _inSession = f_isInSession(_timeZone, _bySession_1, _timeSession_1, _bySession_2, _timeSession_2) _tradingTime = _inWeekDay and _inSession // ========================================================================================================== // EXAMPLE // ========================================================================================================== // === INPUT === filterTime_timeZone = input.string("GMT+0", "Time Zone", group = "⏱️ Time Filter" , tooltip = "GMT and UTC is the same thing \nMatch this setting to bottom right time", options = [ "GMT-10", "GMT-9", "GMT-8", "GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT+0", "GMT+1", "GMT+2", "GMT+3", "GMT+4", "GMT+5", "GMT+6", "GMT+7", "GMT+8", "GMT+9", "GMT+10", "GMT+10:30","GMT+11", "GMT+12", "GMT+13", "GMT+13:45"]) // Weekdays Filter filterTime_byWeekDay = input.bool(true, "Use Weekdays Filter?", group = "⏱️ Time Filter" , tooltip = "Disable to allow all weekdays, Enable to choose certain days") filterTime_Mon = input.bool(true, "Mon  ", inline = "Days", group = "⏱️ Time Filter" ) filterTime_Tue = input.bool(true, "Tue  ", inline = "Days", group = "⏱️ Time Filter" ) filterTime_Wed = input.bool(true, "Wed  ", inline = "Days", group = "⏱️ Time Filter" ) filterTime_Thu = input.bool(true, "Thu  ", inline = "Days", group = "⏱️ Time Filter" ) filterTime_Fri = input.bool(true, "Fri  ", inline = "Days", group = "⏱️ Time Filter" ) filterTime_Sat = input.bool(false, "Sat  ", inline = "Days", group = "⏱️ Time Filter" ) filterTime_Sun = input.bool(false, "Sun", inline = "Days", group = "⏱️ Time Filter" ) // Hour Filter by session filterTime_bySession_1 = input.bool(false, "Use Hourly Filter?", group = "⏱️ Time Filter" ) filterTime_timeSession_1 = input.session("0900-1730", "Hour Session", group = "⏱️ Time Filter" ) filterTime_bySession_2 = input.bool(false, "Use 2ND Hourly Filter?", group = "⏱️ Time Filter" ) filterTime_timeSession_2 = input.session("1930-2100", "Hour Session 2", group = "⏱️ Time Filter" ) // === LOGIC === bool isInTime = f_isTradingAllowed(filterTime_timeZone, filterTime_byWeekDay, filterTime_Mon, filterTime_Tue, filterTime_Wed, filterTime_Thu, filterTime_Fri, filterTime_Sat, filterTime_Sun, filterTime_bySession_1, filterTime_timeSession_1, filterTime_bySession_2, filterTime_timeSession_2) // === PLOT === bgcolor(isInTime ? na : color.new(color.gray, 90), title = "⏱️ Time Filter" )
intersect
https://www.tradingview.com/script/n6xE1ljs-intersect/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
19
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/ // © kaigouthro //@version=5 // @description Find Line Intersecction X/Y library("intersect") // @function line intersection coordinates // @returns [x,y] with x as int if bool is used _isect(l1,l2)=> x1 = line.get_x1(l1), y1 =line.get_y1(l1), x2 = line.get_x2(l1), y2 =line.get_y2(l1) x3 = line.get_x1(l2), y3 =line.get_y1(l2), x4 = line.get_x2(l2), y4 =line.get_y2(l2) x = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) y = ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) ylow = math.min( math.max ( y1, y2 ) , math.max ( y3, y4 ) ) yhigh = math.max( math.min ( y1, y2 ) , math.min ( y3, y4 ) ) xlow = math.min( math.max ( x1, x2 ) , math.max ( x3, x4 ) ) xhigh = math.max( math.min ( x1, x2 ) , math.min ( x3, x4 ) ) if (x > xlow or x < xhigh) or (y> ylow or y < yhigh) x := float(na) y := float(na) [x,y] // @function line intersection coordinates // @returns [x,y] with x as int if bool is used _isect(l1,l2,round) => [x,y] = _isect(l1,l2) int x1 = round ? math.round(x) : int(x) [int(x1),float(y)] // @function line intersection coordinates // @param l1 (line) first line // @param l2 (line) second line // @param _round True to makee an INT for plotting // if not used, will not round ( overload loophole) // @returns [x,y] with x as int if bool is used export get(line l1, line l2, bool _round) => _isect(l1,l2,_round) // @function line intersection coordinates // @returns [x,y] with x as int if bool is used export get(line l1, line l2 ) => _isect(l1,l2,true) // ////////////////////////////////////////////////////////////////// // /// demo // import kaigouthro/hsvColor/6 as h // // helpers // li ( ) => last_bar_index // bi ( ) => bar_index // lh (i) => li() - i // h (i) => bi() - i // var l1 = line(na) // var l2 = line(na) // var n1 = line(na) // var n2 = line(na) // if barstate.isconfirmed and bar_index % 10 == 0 // _c = color.new(h.hsv(bar_index% 60*6,1,.8,1),0) // l1 := line.new(h(int(math.random(0,100))) , math.random(0, 100) , h(int(math.random(0,100))), math.random(0,100), color = _c, style = line.style_arrow_left) // l2 := line.new(h(int(math.random(0,100))) , math.random(0, 100) , h(int(math.random(0,100))), math.random(0,100), color = _c, style = line.style_arrow_left) // // find getion and draw new line to indicate rounded for plot // [x,y] = get(l1,l2,true) // label.new(x,y,'Cross', style=label.style_cross, textcolor = color.white, color = color.red) // // truncate the right/second half of line to getion // n1 := line.copy(l1) // n2 := line.copy(l2) // line.set_x2(l1,x) // line.set_x2(l2,x) // line.set_y2(l1,y) // line.set_y2(l2,y) // if na(x) // line.delete(l1) // line.delete(l2) // line.delete(n1) // line.delete(n2) // line.set_color(n1,#a0a0a0a0) // line.set_color(n2,#a0a0a0a0) // line.set_style(n1,line.style_dotted) // line.set_style(n2,line.style_dotted)
String to Number
https://www.tradingview.com/script/Dk2Si12u-String-to-Number/
Fuwn
https://www.tradingview.com/u/Fuwn/
2
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/ // © MichelT //@version=5 library('StringToNumber') // some enumerations DECIMAL_POINT = 0.1 MINUS = -1 error() => // a function to throw an error label.new(0, close[-1]) // // Here goes all the magic. // // To detect that the last value is a specific digit (or a minus or a decimal point), // we should add any symbol which is definitely not in the string to the end of the string. // I use semicolon (';') for this purpose. // Then we'are trying to replace the group of the digit and semicolon with empty string. // Then we're comparing the new string to the string before replacing. // If the string changed - it means that the last value was the being checked digit. // // NOTE: we cannot try to replace just a digit with an empty string for this purpose, // because replace_all will remove all the digits in the string and we won't be able to understand // what the digit's position was. // cutLastDigit(str) => s = str + ';' r = str.replace_all(s, '1;', '') if r != s [r, 1.] else r = str.replace_all(s, '2;', '') if r != s [r, 2.] else r = str.replace_all(s, '3;', '') if r != s [r, 3.] else r = str.replace_all(s, '4;', '') if r != s [r, 4.] else r = str.replace_all(s, '5;', '') if r != s [r, 5.] else r = str.replace_all(s, '6;', '') if r != s [r, 6.] else r = str.replace_all(s, '7;', '') if r != s [r, 7.] else r = str.replace_all(s, '8;', '') if r != s [r, 8.] else r = str.replace_all(s, '9;', '') if r != s [r, 9.] else r = str.replace_all(s, '0;', '') if r != s [r, 0.] else r = str.replace_all(s, '.;', '') if r != s [r, DECIMAL_POINT] else r = str.replace_all(s, '-;', '') if r != s [r, MINUS] else error() [str, -1] export strToNum(string str) => fractional = 0. // fractional part of the number integer = 0. // integer part of the number s_new = str position = 0.0 // handled position of the number. sign = 1 // sign of the number. 1.0 is PLUS and -1.0 is MINUS. for i = 0 to 1000 by 1 [s, digit] = cutLastDigit(s_new) // here we'll cut the digits by one from the string till the string is empty. if digit == DECIMAL_POINT // DECIMAL_POINT is found. That means the number has decimal part. order = math.pow(10, i) // convert the decimal part by shifting the accumulated value to (10^i) positions to right fractional := integer / order integer := 0. position := 0 position else if digit == MINUS // MINUS sing is found. sign := MINUS break // I expect that there's nothing after the MINUS ('-') sign. 0. // just a little workaround to help the 'if' to detect returning type. else integer += digit * math.pow(10, position) // it's just a regular digit. position += 1 position if s == '' break s_new := s // If we are here, then there are more digits in the string. Let's handle the next one! s_new sign * (integer + fractional) // We've exited from the loop. Build the returning value.
Wick Percentage Indicator
https://www.tradingview.com/script/KD8rzxfn-Wick-Percentage-Indicator/
allmightycrypto
https://www.tradingview.com/u/allmightycrypto/
12
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/ // © allmightycrypto //@version=5 indicator("Wick Percentage Indicator", shorttitle="Wick %", overlay=false) // Calculate the greater wick size wick_upper = high - close wick_lower = low - open if (open - close > 0) // down candle wick_upper := high - open wick_lower := low - close // greater_wick = math.max(wick_high, wick_low) // Calculate the wick percentage as a percent of the opening price // wick_percentage = (greater_wick / open) * 100 lower_wick_percentage = (wick_lower / open) * 100 upper_wick_percentage = (wick_upper / open) * 100 // Plot the wick percentage on the chart // plot(wick_percentage, title="Upper Wick %", color=color.blue, linewidth=2) plot(upper_wick_percentage, title="Upper Wick %", color=color.blue, linewidth=2) plot(lower_wick_percentage, title="Lower Wick %", color=color.red, linewidth=2)
Silph Scope
https://www.tradingview.com/script/JjJBIvsp-Silph-Scope/
Vanitati
https://www.tradingview.com/u/Vanitati/
48
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/ // © vanitati //@version=5 indicator('Silph Scope') hline(30, 'Upper Line', color=color.rgb(255, 255, 255), linestyle=hline.style_dashed, linewidth=1) hline(-30, 'Lower Line', color=color.rgb(255, 255, 255), linestyle=hline.style_dashed, linewidth=1) src = input(close, title='RSI Source') RSI_Period = input(10, title='RSI Length') SF = input(5, title='RSI Smoothing') QQE = input(4.238, title='Fast QQE Factor') ThreshHold = input(10, title='Thresh-hold') sQQEx = input(false, title='Show Smooth RSI, QQE Signal crosses') sQQEz = input(false, title='Show Smooth RSI Zero crosses') sQQEc = input(false, title='Show Smooth RSI Thresh Hold Channel Exits') ma_type = input.string(title='MA Type', defval='EMA', options=['ALMA', 'EMA', 'DEMA', 'TEMA', 'WMA', 'VWMA', 'SMA', 'SMMA', 'HMA', 'LSMA', 'PEMA']) lsma_offset = input.int(defval=0, title='* Least Squares (LSMA) Only - Offset Value', minval=0) alma_offset = input.float(defval=0.85, title='* Arnaud Legoux (ALMA) Only - Offset Value', minval=0, step=0.01) alma_sigma = input.int(defval=6, title='* Arnaud Legoux (ALMA) Only - Sigma Value', minval=0) ma(type, src, len) => float result = 0 if type == 'SMA' // Simple result := ta.sma(src, len) result if type == 'EMA' // Exponential result := ta.ema(src, len) result if type == 'DEMA' // Double Exponential e = ta.ema(src, len) result := 2 * e - ta.ema(e, len) result if type == 'TEMA' // Triple Exponential e = ta.ema(src, len) result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) result if type == 'WMA' // Weighted result := ta.wma(src, len) result if type == 'VWMA' // Volume Weighted result := ta.vwma(src, len) result if type == 'SMMA' // Smoothed w = ta.wma(src, len) smma_val = ta.sma(src, len) result := na(w[1]) ? smma_val : (w[1] * (len - 1) + src) / len result if type == 'HMA' // Hull result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result if type == 'LSMA' // Least Squares result := ta.linreg(src, len, lsma_offset) result if type == 'ALMA' // Arnaud Legoux result := ta.alma(src, len, alma_offset, alma_sigma) result if type == 'PEMA' // Copyright (c) 2010-present, Bruno Pio // Copyright (c) 2019-present, Alex Orekhov (everget) // Pentuple Exponential Moving Average script may be freely distributed under the MIT license. ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) ema3 = ta.ema(ema2, len) ema4 = ta.ema(ema3, len) ema5 = ta.ema(ema4, len) ema6 = ta.ema(ema5, len) ema7 = ta.ema(ema6, len) ema8 = ta.ema(ema7, len) pema = 8 * ema1 - 28 * ema2 + 56 * ema3 - 70 * ema4 + 56 * ema5 - 28 * ema6 + 8 * ema7 - ema8 result := pema result result // Wilders_Period = RSI_Period * 2 - 1 Rsi = ta.rsi(src, RSI_Period) RsiMa = ma(ma_type, Rsi, SF) AtrRsi = math.abs(RsiMa[1] - RsiMa) MaAtrRsi = ma(ma_type, AtrRsi, Wilders_Period) dar = ma(ma_type, MaAtrRsi, Wilders_Period) * QQE longband = 0.0 shortband = 0.0 trend = 0 DeltaFastAtrRsi = dar RSIndex = RsiMa newshortband = RSIndex + DeltaFastAtrRsi newlongband = RSIndex - DeltaFastAtrRsi longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongband shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband cross_1 = ta.cross(longband[1], RSIndex) trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1) FastAtrRsiTL = trend == 1 ? longband : shortband // Find all the QQE Crosses QQExlong = 0 QQExlong := nz(QQExlong[1]) QQExshort = 0 QQExshort := nz(QQExshort[1]) QQExlong := sQQEx and FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0 QQExshort := sQQEx and FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0 // Zero cross QQEzlong = 0 QQEzlong := nz(QQEzlong[1]) QQEzshort = 0 QQEzshort := nz(QQEzshort[1]) QQEzlong := sQQEz and RSIndex >= 50 ? QQEzlong + 1 : 0 QQEzshort := sQQEz and RSIndex < 50 ? QQEzshort + 1 : 0 // Thresh Hold channel Crosses give the BUY/SELL alerts. QQEclong = 0 QQEclong := nz(QQEclong[1]) QQEcshort = 0 QQEcshort := nz(QQEcshort[1]) QQEclong := sQQEc and RSIndex > 50 + ThreshHold ? QQEclong + 1 : 0 QQEcshort := sQQEc and RSIndex < 50 - ThreshHold ? QQEcshort + 1 : 0 // QQE exit from Thresh Hold Channel plotshape(sQQEc and QQEclong == 1 ? RsiMa - 50 : na, title='QQE XC Over Channel', style=shape.diamond, location=location.absolute, color=color.rgb(128, 128, 0, 100), size=size.small, offset=0, editable=false) plotshape(sQQEc and QQEcshort == 1 ? RsiMa - 50 : na, title='QQE XC Under Channel', style=shape.diamond, location=location.absolute, color=color.rgb(255, 82, 82, 100), size=size.small, offset=0, editable=false) // QQE crosses plotshape(sQQEx and QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na, title='QQE XQ Cross Over', style=shape.circle, location=location.absolute, color=color.rgb(0, 230, 119, 100), size=size.small, offset=-1, editable=false) plotshape(sQQEx and QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na, title='QQE XQ Cross Under', style=shape.circle, location=location.absolute, color=color.rgb(33, 149, 243, 100), size=size.small, offset=-1, editable=false) // Signal crosses zero line plotshape(sQQEz and QQEzlong == 1 ? RsiMa - 50 : na, title='QQE XZ Zero Cross Over', style=shape.square, location=location.absolute, color=color.rgb(0, 187, 212, 100), size=size.small, offset=0, editable=false) plotshape(sQQEz and QQEzshort == 1 ? RsiMa - 50 : na, title='QQE XZ Zero Cross Under', style=shape.square, location=location.absolute, color=color.rgb(223, 64, 251, 100), size=size.small, offset=0, editable=false) hcolor = RsiMa - 50 > ThreshHold ? color.rgb(65, 135, 175, 1) : RsiMa - 50 < 0 - ThreshHold ? color.rgb(226, 82, 255) : color.rgb(105, 94, 94, 1) plot(FastAtrRsiTL - 50, color=color.rgb(33, 149, 243, 100), linewidth=2, editable=false) p1 = plot(RsiMa - 50, color=color.rgb(255, 153, 0, 100), linewidth=2, editable=false) plot(RsiMa - 50, color=hcolor, style=plot.style_columns)
PCA-Risk Indicator
https://www.tradingview.com/script/Fo1R6YBx/
Julien-PH
https://www.tradingview.com/u/Julien-PH/
56
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/ // © Julien-PH //@version=5 indicator(title="PCA Risk Indicator", shorttitle="PCA-RI", overlay=false) //---- Settings source = input.source(defval=close , title='Source' , group='General setting') mtf = input.timeframe(defval='' , title='Timeframe' , group='General setting') //---- Display display_input = input.bool(false, title="Display raw input indicators ?" , group="Display") offsetDisplay = input.int(defval=-100, title="Offset raw input indicators", group="Display") display_output = input.bool(true, title="Display output indicators ?" , group="Display") ncPCA = input.string('Centered Reduced', title='How to display all PCA indicators ?', options=['Centered Reduced','Original'], group='Display') //---- Method MaxMinNz(value,max=100,min=0,def=50) => nz(math.max(math.min(value,max),min),def) isPL(src=close,left=3,right=0) => ta.pivotlow(src,left,right) isPH(src=close,left=3,right=0) => ta.pivothigh(src,left,right) wtMethod(l1, l2, ampl=0.5, offset=50) => esa = ta.ema(hlc3, l1) ci = (hlc3 - esa) / (0.015 * ta.ema(math.abs(hlc3 - esa), l1)) wt1 = MaxMinNz(ta.ema(ci, l2)*ampl + offset) wt2 = nz(ta.sma(wt1,3),50) [wt1,wt2] distanceSMA(l,ampl,offset) => sma = ta.sma(source, l) MaxMinNz( ((source - sma) / sma)* ampl + offset ) williamsRangeMethod(length) => (source - ta.lowest(length)) / (ta.highest(length) - ta.lowest(length)) * 100 momentumMethod(length,ampl=100, offset=50) => MaxMinNz((source/source[length]-1)*ampl+offset) stochasticRsiMethod(rsi,rsiLength,smoothK,smoothD,offset=50) => k = ta.sma(ta.stoch(rsi, rsi, rsi, rsiLength), smoothK) d = ta.sma(k, smoothD) kdDelta = MaxMinNz((k - d) + offset) [k,d,kdDelta] rviMethod(lengthStDev,lengthEma) => stddev = ta.stdev(source,lengthStDev) upper = ta.ema(ta.change(source) <= 0 ? 0 : stddev, lengthEma) lower = ta.ema(ta.change(source) > 0 ? 0 : stddev, lengthEma) rvi = upper / (upper + lower) * 100 double_smoothEMA(src, long, short) => ta.ema(ta.ema(src, long), short) tsiMethod(long, short, ampl=60, offset=50) => dsTSI = double_smoothEMA(ta.change(source), long, short) dsAbsTSI= double_smoothEMA(math.abs(ta.change(source)), long, short) tsi = MaxMinNz(ampl*(dsTSI/dsAbsTSI)+offset) bbMethod(length,mult) => [middle, upper, lower] = ta.bb(source,length,mult) MaxMinNz( ((source - lower) / (upper - lower)) * 100 ) stcMethod(length, fastLength, slowLength) => m = ta.ema(source, fastLength) - ta.ema(source, slowLength) Kstc = nz(fixnan(ta.stoch(m, m, m, length))) Dstc = ta.ema(Kstc, 3) KDstc = nz(fixnan(ta.stoch(Dstc, Dstc, Dstc, 3))) stc = ta.ema(KDstc, 3) stc := math.max(math.min(stc, 100), 0) aroonMethod(lengthUp,lengthDown) => up = (100 * (ta.highestbars(high, lengthUp+1) + lengthUp) /lengthUp ) down = (-100 * (ta.lowestbars(low , lengthDown+1) + lengthDown)/lengthDown) + 100 //Down adjusted to match the 0 with the bottom and 100 with the top [up,down] haCountMethod(length) => [haclose,haopen] = request.security(ticker.heikinashi(syminfo.tickerid), mtf, [close,open]) hac = 50.0 hac := if barstate.isfirst 50 else if haclose > haopen hac[1] / length + (100 * ((length - 1)/length)) else if haclose < haopen hac[1] / length else hac[1] cmfMethod(length,ampl=150,offset=50) => mfv = math.sum(((high == low) ? 0 : ((close - low) - (high - close)) / (high - low)) * volume, length) / math.sum(volume, length) MaxMinNz(mfv * ampl + offset) TDSMethod(length=4,maxTD=13) => TDSUp = 0 TDSUp := source > source[length] ? nz(TDSUp[1] ) + 1 : 0 TDSDown = 0 TDSDown := source < source[length] ? nz(TDSDown[1]) - 1 : 0 [MaxMinNz((((TDSUp + TDSDown) / maxTD) + 1) * 50),TDSUp,TDSDown] isInBullDivergence(indicator,price=close,length=100,confirm=true,confLength=1) => isDiv = 0 confirmOffset = confirm ? confLength : 0 LL = indicator[0+confirmOffset] if (isPL(indicator,right=confirmOffset) and indicator < 50) for i = 1+confirmOffset to length+confirmOffset if (LL > indicator[i] and indicator[i] < indicator[i+1]) LL := indicator[i] if (price[i] > price[confirmOffset] and ta.lowestbars(price,i) < 3) isDiv := i isDiv isInBearDivergence(indicator,price=close,length=100,confirm=true,confLength=1) => isDiv = 0 confirmOffset = confirm ? confLength : 0 HH = indicator[0+confirmOffset] if (isPH(indicator,right=confirmOffset) and indicator > 50) for i = 1+confirmOffset to length+confirmOffset if (HH < indicator[i] and indicator[i] > indicator[i+1]) HH := indicator[i] if (price[i] < price[confirmOffset] and ta.highestbars(price,i) < 3) isDiv := i isDiv findDivergences(indicator,price=close,length=100,confirm=true,confLength=1) => bullDiv = isInBullDivergence(indicator,price,length,confirm,confLength) bearDiv = isInBearDivergence(indicator,price,length,confirm,confLength) [bullDiv,bearDiv] oscillatorsDivergence(bullDiv=0,bearDiv=0,slope=2.0) => bullOsc = 100.0 bullOsc := if barstate.isfirst 100.0 else bullDiv > 0 ? 0 : math.min(bullOsc[1] * (bearDiv>0 ? 2 : 1) + slope, 100) bearOsc = 0.0 bearOsc := if barstate.isfirst 0.0 else bearDiv > 0 ? 100 : math.max(bearOsc[1] / (bullDiv>0 ? 2 : 1) - slope, 0 ) [bullOsc,bearOsc] divergenceIndicator(bullOsc,bearOsc) => (bullOsc+bearOsc)/2 chooseSrcDiv(option,wt,hac,rsi,stochRsi,rvi,tsi,mom,tds,mfi,cmf) => if option == 'WaveTrend' wt else if option == 'HA Count' hac else if option == 'RSI' rsi else if option == 'Stoch RSI' stochRsi else if option == 'RVI' rvi else if option == 'TSI' tsi else if option == 'Momentum' mom else if option == 'TD Sequential' tds else if option == 'MFI' mfi else if option == 'CMF' cmf //######## INPUT //---- WaveTrend display_wt = input.bool(true , title="Display WaveTrend indicator ?" , group="WaveTrend Settings", tooltip="WaveTrend Oscillator develop by LazyBear") display_wtDelta = input.bool(true , title="Display WaveTrend delta ?" , group="WaveTrend Settings", tooltip="Represents the difference between the WaveTrend and its SMA") weigthWT = input.float(1 , minval=0, step=0.1, title="Weigth WaveTrend" , group="WaveTrend Settings", tooltip="Weight on the Risk indicator") length1WT = input.int(9 , minval=1, title="Channel Length" , group="WaveTrend Settings") length2WT = input.int(12 , minval=1, title="Average Length" , group="WaveTrend Settings") amplWT = input.float(0.5 , title="WaveTrend Amplitude" , group="WaveTrend Settings") offsetWT = input.int(50 , title="WaveTrend Offset" , group="WaveTrend Settings") [wt1,wt2] = request.security(syminfo.tickerid, mtf, wtMethod(length1WT,length2WT,amplWT,offsetWT)) wtDelta = MaxMinNz((wt1 - wt2)*(amplWT*8) + offsetWT) // Plot colorWT1 = input.color(color.rgb(144,202,249,30) , title="WaveTrend color" , group="WaveTrend Settings") colorWT2 = input.color(color.rgb(13, 71, 161,30) , title="WaveTrend MA color" , group="WaveTrend Settings") colorDelta = input.color(color.new(color.yellow,60), title="WaveTrend delta color" , group="WaveTrend Settings") display_WTdivs = input.bool(true , title="Display WaveTrend signals ?" , group="WaveTrend Settings") colorWTBullDiv = input.color(color.new(color.green ,30), title="WaveTrend Bull reversal color" , group="WaveTrend Settings") colorWTBearDiv = input.color(color.new(color.red ,30), title="WaveTrend Bear reversal color" , group="WaveTrend Settings") plot(display_input and display_wt ? wt1+offsetDisplay : na , title="WaveTrend" , color=colorWT1, linewidth = 1, histbase=50+offsetDisplay, style=plot.style_area) plot(display_input and display_wt ? wt2+offsetDisplay : na , title="WaveTrendMA", color=colorWT2, linewidth = 1, histbase=50+offsetDisplay, style=plot.style_area) plot(display_input and display_wtDelta ? wtDelta+offsetDisplay : na, title="WaveTrend Delta" , color=colorDelta, linewidth = 1, histbase=50+offsetDisplay, style=plot.style_area) plotchar(display_input and display_WTdivs and ta.cross(wt1,wt2) ? wt1[0]+offsetDisplay : na, title = 'WaveTrend Bull reversal signal', char='•', color = ta.crossover(wt1,wt2) ? colorWTBullDiv : colorWTBearDiv, location = location.absolute, size = size.tiny) //---- Heikin Ashi Count display_hac = input.bool(true ,title="Display Heikin Ashi Count indicator ?" , group="Heikin Ashi Count Settings") weigthHAC = input.float(1, minval=0, step=0.1, title="Weigth HAC" , group="Heikin Ashi Count Settings", tooltip="Weight on the Risk indicator") lengthHAC = input.float(defval=1.15, minval=1, step=0.01, title="Counting Length" , group="Heikin Ashi Count Settings") hac = request.security(syminfo.tickerid, mtf, haCountMethod(lengthHAC)) // Plot colorHAC = input.color(color.rgb(255,92,21,50), title="Heinkin Ashi Count color" , group="Heikin Ashi Count Settings") plot(display_input and display_hac ? hac+offsetDisplay : na, title="HAC", color=colorHAC, linewidth=1, histbase=(offsetDisplay+50), style=plot.style_area) //---- Aroon display_aroonUp = input.bool(true ,title="Display AroonUp indicator ?" , group="Aroon Settings") weigthAroonUp = input.float(1, minval=0, step=0.1, title="Weigth AroonUp" , group="Aroon Settings", tooltip="Weight on the Risk indicator") lengthAroonUp = input.int(14, minval=1, title="AroonUp Length" , group="Aroon Settings") display_aroonDown = input.bool(true ,title="Display AroonDown indicator ?" , group="Aroon Settings", tooltip="Down adjusted to match the 0|100 with the bottom|top") weigthAroonDown = input.float(1, minval=0, step=0.1,title="Weigth AroonDown", group="Aroon Settings", tooltip="Weight on the Risk indicator") lengthAroonDown = input.int(14, minval=1, title="AroonDown Length" , group="Aroon Settings") [aroonUp,aroonDown] = request.security(syminfo.tickerid, mtf, aroonMethod(lengthAroonUp,lengthAroonDown)) // Plot colorAroonUp = input.color(color.new(color.orange,50), title="AroonUp color" , group="Aroon Settings") colorAroonDown = input.color(color.new(color.blue, 50), title="AroonDown color" , group="Aroon Settings") plot(display_input and display_aroonUp ? aroonUp +offsetDisplay : na, title="AroonUp" , color=colorAroonUp , linewidth=1, histbase=50+offsetDisplay, style=plot.style_line) plot(display_input and display_aroonDown ? aroonDown+offsetDisplay : na, title="AroonDown" , color=colorAroonDown , linewidth=1, histbase=50+offsetDisplay, style=plot.style_line) //---- Schaff Trend Cycle display_stc = input.bool(true,title="Display Schaff Trend Cycle indicator ?" , group="Schaff Trend Cycle Settings") weigthSTC = input.float(1, minval=0, step=0.1, title="Weigth STC" , group="Schaff Trend Cycle Settings", tooltip="Weight on the Risk indicator") lengthSTC = input.int(10, minval=1, title="Schaff Trend Cycle Length" , group="Schaff Trend Cycle Settings") fastLengthSTC = input.int(23, minval=1, title="Schaff Trend Cycle fast Length" , group="Schaff Trend Cycle Settings") slowLengthSTC = input.int(50, minval=1, title="Schaff Trend Cycle slow Length" , group="Schaff Trend Cycle Settings") stc = request.security(syminfo.tickerid, mtf, stcMethod(lengthSTC,fastLengthSTC,slowLengthSTC)) // Plot colorSTC = input.color(color.rgb(128,0,128,0), title="Schaff Trend Cycle color" , group="Schaff Trend Cycle Settings") plot(display_input and display_stc ? stc+offsetDisplay : na, title="STC", color=colorSTC, linewidth=2, histbase=50+offsetDisplay) //---- RSI display_rsi = input.bool(true , title="Display RSI indicator ?" , group="Relative Strength Index Settings") weigthRSI = input.float(1, minval=0, step=0.1, title="Weigth RSI" , group="Relative Strength Index Settings", tooltip="Weight on the Risk indicator") lengthRSI = input.int(14, minval=1, title="RSI Length" , group="Relative Strength Index Settings") rsi = request.security(syminfo.tickerid, mtf, ta.rsi(source,lengthRSI)) // Plot colorRSI = input.color(color.rgb(255,127,0,20), title="RSI color", group="Relative Strength Index Settings") plot(display_input and display_rsi ? rsi+offsetDisplay : na, title="RSI", color=colorRSI, linewidth=2, histbase=50+offsetDisplay) //---- Stochastic RSI display_stoch = input.bool(true , title="Display Stochastic indicators ?" , group="Stochastic RSI Settings") weigthStoch = input.float(1, minval=0, step=0.1, title="Weigth Stochastic RSI" , group="Stochastic RSI Settings", tooltip="Weight on the Risk indicator") display_kdDelta = input.bool(true , title="Display delta between K and D ?" , group="Stochastic RSI Settings", tooltip="Represents the difference between the stochastic and its SMA") smoothK = input.int(4, minval=1, title="K Length" , group="Stochastic RSI Settings") smoothD = input.int(4, minval=1, title="D Length" , group="Stochastic RSI Settings") [k,d,kdDelta] = request.security(syminfo.tickerid, mtf, stochasticRsiMethod(rsi,lengthRSI,smoothK,smoothD)) // Plot colorStochK = input.color(color.rgb(214,253,22 ,70), title="Stochastic K color" , group="Stochastic RSI Settings") colorStochD = input.color(color.rgb(255,162,18 ,70), title="Stochastic D color" , group="Stochastic RSI Settings") colorFillKD = k >= d ? colorStochK : colorStochD stochKplot = plot(display_input and display_stoch ? k+offsetDisplay : na, title="K", color=colorStochK, linewidth=1, histbase=50+offsetDisplay) stochDplot = plot(display_input and display_stoch ? d+offsetDisplay : na, title="D", color=colorStochD, linewidth=1, histbase=50+offsetDisplay) //fill(stochKplot, stochDplot, title='KD Fill', color= display_stoch ? colorFillKD : color.new(color.black,100)) plot(display_input and display_kdDelta ? kdDelta+offsetDisplay : na, title="KDDelta" , color=colorFillKD, linewidth=1, histbase=50+offsetDisplay, style=plot.style_area) //---- Relative Volatility Index display_rvi = input.bool(true , title="Display RVI indicator ?" , group="Relative Volatility Index Settings") weigthRVI = input.float(1, minval=0, step=0.1, title="Weigth RVI" , group="Relative Volatility Index Settings", tooltip="Weight on the Risk indicator") lengthStDevRVI = input.int(10, minval=1, title="RVI Length price deviation", group="Relative Volatility Index Settings") lengthEMARVI = input.int(14, minval=1, title="RVI Length EMA" , group="Relative Volatility Index Settings") rvi = request.security(syminfo.tickerid, mtf, rviMethod(lengthStDevRVI,lengthEMARVI)) // Plot colorRVI = input.color(color.rgb(126,87 ,194,0), title="RVI color" , group="Relative Volatility Index Settings") plot(display_input and display_rvi ? rvi+offsetDisplay : na, title="RVI", color=colorRVI, linewidth=1, histbase=50+offsetDisplay) //---- True Strength Indicator display_tsi = input.bool(true , title="Display TSI indicator ?" , group="True Strength Indicator Settings") weigthTSI = input.float(1,minval=0, step=0.1, title="Weigth TSI" , group="True Strength Indicator Settings", tooltip="Weight on the Risk indicator") longTSI = input.int(25, minval=1, title="TSI Long Length" , group="True Strength Indicator Settings") shortTSI = input.int(13, minval=1, title="TSI Short Length" , group="True Strength Indicator Settings") amplLTSI = input.float(80 , title="TSI Amplitude" , group="True Strength Indicator Settings") offsetTSI = input.int(50 , title="TSI Offset" , group="True Strength Indicator Settings") tsi = request.security(syminfo.tickerid, mtf, tsiMethod(longTSI,shortTSI,amplLTSI,offsetTSI)) // Plot colorTSI = input.color(color.rgb(87 ,147,255,0), title="TSI color" , group="True Strength Indicator Settings") plot(display_input and display_tsi ? tsi+offsetDisplay : na, title="TSI", color=colorTSI, linewidth=1, histbase=50+offsetDisplay) //---- Bollinger Bands display_bb = input.bool(true , title="Display BB ratio indicator ?" , group="Bollinger Bands Settings") weigthBB = input.float( 1 , minval=0 , step=0.1, title="Weigth Bollinger Bands" , group="Bollinger Bands Settings", tooltip="Weight on the Risk indicator") lengthBB = input.int( 20 , minval=1 , step=1 , title="Bollinger Period Length" , group="Bollinger Bands Settings") multBB = input.float( 3.0, minval=0.1, step=0.1, title="Bollinger Bands Standard Deviation", group="Bollinger Bands Settings") ratioBB = request.security(syminfo.tickerid, mtf, bbMethod(lengthBB,multBB)) // Plot colorBB = input.color(color.rgb(62,195,137,10) , title="BB ratio color" , group="Bollinger Bands Settings") plot(display_input and display_bb ? ratioBB+offsetDisplay : na, title="BB", color=colorBB, linewidth=1, histbase=50+offsetDisplay, style=plot.style_stepline) //---- Williams Percent Range display_wr = input.bool(true , title="Display Williams Percent Range indicator ?" , group="Williams %R Settings", tooltip="Similar to a range in the Donchian channel") weigthWR = input.float(1, minval=0, step=0.1, title="Weigth Williams %R" , group="Williams %R Settings", tooltip="Weight on the Risk indicator") lengthWR = input.int(21 , minval=1, title="Williams %R Length" , group="Williams %R Settings", tooltip="Length of the measured range, usually 14 or 21") wr = request.security(syminfo.tickerid, mtf, williamsRangeMethod(lengthWR)) // Plot colorWR = input.color(color.rgb(38 ,166,154,10) , title="Williams %R color" , group="Williams %R Settings") plot(display_input and display_wr ? wr+offsetDisplay : na, title="W%R", color=colorWR, linewidth=1, histbase=50+offsetDisplay, style=plot.style_stepline) //---- Momentum % display_mom = input.bool(true , title="Display Momentum indicator ?" , group="Momentum % Settings") weigthMom = input.float(1, minval=0, step=0.1, title="Weigth Momentum" , group="Momentum % Settings", tooltip="Weight on the Risk indicator") lengthMom = input.int(10, minval=1, title="Mom Length" , group="Momentum % Settings") amplMom = input.float(100 , title="Momentum Amplitude" , group="Momentum % Settings", tooltip="must be defined to fit the market volatility") mom = request.security(syminfo.tickerid, mtf, momentumMethod(lengthMom,amplMom)) // Plot colorMom = input.color(color.rgb(210,180,0 ,50), title="Mom color" , group="Momentum % Settings") plot(display_input and display_mom ? mom+offsetDisplay : na, title="Mom", color=colorMom, linewidth=1, histbase=50+offsetDisplay, style=plot.style_columns) //---- TD Sequential display_TDS = input.bool(true , title="Display TD Sequential indicator ?" , group="TD Sequential Settings", tooltip="The TD Sequential indicator is based on trend momentum, basically it counts the number of bars that confirm the trend") display_TDS_Labels = input.bool(false, title="Display TD Sequential labels ?" , group="TD Sequential Settings", tooltip="Real value of TD Sequential") weigthTDS = input.float(1 , minval=0, step=0.1, title="Weigth TD Sequential" , group="TD Sequential Settings", tooltip="Weight on the Risk indicator") lengthTDS = input.int(4 , minval=1, title="TD Sequential Length" , group="TD Sequential Settings", tooltip="Length between the source bars compared") maxCountTDS = input.int(13 , minval=1, title="TD Sequential maximum count" , group="TD Sequential Settings", tooltip="Maximum bar count, usually 9 or 13") [TDSRange,TDSUp,TDSDown]= request.security(syminfo.tickerid, mtf, TDSMethod(lengthTDS,maxCountTDS)) // Plot colorTDS = input.color(color.rgb(200,142,41 ,50), title="TD Sequential color", group="TD Sequential Settings") plot(display_input and display_TDS ? TDSRange+offsetDisplay : na, title="TDS", color=colorTDS, linewidth=1, histbase=50+offsetDisplay, style=plot.style_columns) if display_input and display_TDS_Labels and TDSRange > 50 label.new(x=bar_index, y=TDSRange+offsetDisplay, color=color.rgb(0,0,0,100), text=str.tostring(TDSUp) , textcolor=color.white, style=label.style_label_center, size=size.tiny) else if display_input and display_TDS_Labels and TDSRange < 50 label.new(x=bar_index, y=TDSRange+offsetDisplay, color=color.rgb(0,0,0,100), text=str.tostring(-TDSDown), textcolor=color.white, style=label.style_label_center, size=size.tiny) //---- Money Flow Index display_mfi = input.bool(true , title="Display Money Flow Index indicator ?", group="Money Flow Index Settings") weigthMFI = input.float(1, minval=0, step=0.1, title="Weigth MFI" , group="Money Flow Index Settings", tooltip="Weight on the Risk indicator") lengthMFI = input.int(14, minval=1, maxval=2000 , title="MFI Length" , group="Money Flow Index Settings") mfi = request.security(syminfo.tickerid, mtf, nz(ta.mfi(hlc3, lengthMFI),50)) // Plot colorMFI = input.color(color.new(color.green,0) , title="MFI color" , group="Money Flow Index Settings") plot(display_input and display_mfi ? mfi+offsetDisplay : na, title="MFI", color=colorMFI, linewidth=1, histbase=50+offsetDisplay) //---- Chaikin Money Flow display_cmf = input.bool(true , title="Display Chaikin Money Flow indicator ?" , group="Chaikin Money Flow Settings") weigthCMF = input.float(1 , minval=0, step=0.1, title="Weigth CMF" , group="Chaikin Money Flow Settings", tooltip="Weight on the Risk indicator") lengthCMF = input.int(21 , minval=1, maxval=1000, title="Chaikin Money Flow Length" , group="Chaikin Money Flow Settings") amplCMF = input.float(150 , title="Chaikin Money Flow Amplitude" , group="Chaikin Money Flow Settings") offsetCMF = input.int(50 , title="Chaikin Money Flow Offset" , group="Chaikin Money Flow Settings") cmf = request.security(syminfo.tickerid, mtf, cmfMethod(lengthCMF,amplCMF,offsetCMF)) // Plot colorCMF = input.color(color.new(color.lime,0), title="Chaikin Money Flow color" , group="Chaikin Money Flow Settings") plot(display_input and display_cmf ? cmf+offsetDisplay : na, title="CMF", color=colorCMF, linewidth=1, histbase=50+offsetDisplay) //---- Distance short moving average display_DistanceShortSMA= input.bool(false,title="Display distance from short moving average ?" , group="Distance short MA Settings") weigthSSMA = input.float(1, minval=0, step=0.1, title="Weigth short moving average", group="Distance short MA Settings", tooltip="Weight on the Risk indicator") lengthSSMA = input.int( 7 , title="Short MA Length", minval=1 , group="Distance short MA Settings") amplSSMA = input.float(300, title="Short MA Amplitude" , group="Distance short MA Settings") offsetSSMA = input.int( 50 , title="Short MA Offset" , group="Distance short MA Settings") distance_close_shortsma = request.security(syminfo.tickerid, mtf, distanceSMA(lengthSSMA,amplSSMA,offsetSSMA)) // Plot colorDistanceShortSMA = input.color(color.new(color.aqua,20), title="Distance short MA color" , group="Distance short MA Settings") plot(display_input and display_DistanceShortSMA ? distance_close_shortsma+offsetDisplay : na, title='Distance from short MA', color=colorDistanceShortSMA, linewidth=1, histbase=50+offsetDisplay) //---- Distance long moving average display_DistanceLongSMA = input.bool(false,title="Display distance from long moving average ?" , group="Distance long MA Settings") weigthLSMA = input.float(1, minval=0, step=0.1, title="Weigth long moving average" , group="Distance long MA Settings", tooltip="Weight on the Risk indicator") lengthLSMA = input.int( 50 , title="Long MA Length", minval=1 , group="Distance long MA Settings") amplLSMA = input.float(100, title="Long MA Amplitude" , group="Distance long MA Settings") offsetLSMA = input.int( 50 , title="Long MA Offset" , group="Distance long MA Settings") distance_close_longsma = request.security(syminfo.tickerid, mtf, distanceSMA(lengthLSMA,amplLSMA,offsetLSMA)) // Plot colorDistanceLongSMA = input.color(color.new(color.aqua,20), title="Distance long MA color" , group="Distance long MA Settings") plot(display_input and display_DistanceLongSMA ? distance_close_longsma+offsetDisplay : na, title='Distance from long MA', color=colorDistanceLongSMA , linewidth=1, histbase=50+offsetDisplay) //---- Oscillator Divergence display_OscDiv = input.bool(true , title="Display oscillator divergence indicator ?" , group="Oscillator Divergence Settings") weigthOscDiv = input.float(1, minval=0, step=0.1 , title="Weigth oscillator divergence" , group="Oscillator Divergence Settings", tooltip="Weight on the Risk indicator") confirmedDiv = input.bool(true , title="Wait confirmation for signal ?" , group="Oscillator Divergence Settings", tooltip="Authorize repainting (on the signals, not on the oscillator)") confLengthDiv = input.int(1, minval=1 , title="Number of bars for divergence confirmation" , group="Oscillator Divergence Settings") srcDivOption = input.string(defval='HA Count' , title='Indicator to look for divergence' , group='Oscillator Divergence Settings', options=['WaveTrend','HA Count','RSI','Stoch RSI','RVI','TSI','Momentum','TD Sequential','MFI','CMF']) slopeDiv = input.float(defval=4.0 , minval=0.1, step=0.1 , title="Slope for oscillator divergence" , group="Oscillator Divergence Settings") lengthDiv = input.float(defval=100 , minval=3 , step=1 , title="Number of bars to look for divergences" , group="Oscillator Divergence Settings") srcDiv = chooseSrcDiv(srcDivOption,wt1,hac,rsi,k,rvi,tsi,mom,TDSRange,mfi,cmf) [bullDiv,bearDiv] = request.security(syminfo.tickerid, mtf, findDivergences(srcDiv,close,lengthDiv,confirmedDiv,confLengthDiv)) [bullOsc,bearOsc] = oscillatorsDivergence(bullDiv,bearDiv,slopeDiv) oscDiv = divergenceIndicator(bullOsc,bearOsc) // Plot confirmationDivOffset = confirmedDiv ? confLengthDiv : 0 locDivOption = input.string(defval='Absolute' , title='Location of the divergence signals', options=['Absolute','Value'], group='Oscillator Divergence Settings') display_divs = input.bool(true , title="Display divergence signals ?" , group="Oscillator Divergence Settings") display_divline = input.bool(true , title="Display divergence lines ?" , group="Oscillator Divergence Settings") colorBullDiv = input.color(color.new(color.green ,30), title="Bull Divergence color" , group="Oscillator Divergence Settings") colorBearDiv = input.color(color.new(color.red ,30), title="Bear Divergence color" , group="Oscillator Divergence Settings") colorOscDiv = input.color(color.new(color.silver,25), title="Oscillator divergence color" , group="Oscillator Divergence Settings") plotchar(display_input and display_divs and bullDiv ? (locDivOption == 'Value' ? srcDiv[confirmationDivOffset] : 0 )+offsetDisplay : na, title = 'Bull Divergence signal', char='•', color = colorBullDiv, location = location.absolute, size = size.small, offset = -confirmationDivOffset) plotchar(display_input and display_divs and bearDiv ? (locDivOption == 'Value' ? srcDiv[confirmationDivOffset] : 100)+offsetDisplay : na, title = 'Bear Divergence signal', char='•', color = colorBearDiv, location = location.absolute, size = size.small, offset = -confirmationDivOffset) plot(display_input and display_OscDiv ? oscDiv+offsetDisplay : na, title="OscDiv", color=colorOscDiv, linewidth=1, histbase=50+offsetDisplay, style=plot.style_line) if display_input and display_divline and bullDiv>0 line.new(x1=bar_index-bullDiv, y1=math.round(srcDiv[bullDiv])+offsetDisplay, x2=bar_index-confirmationDivOffset, y2=math.round(srcDiv[confirmationDivOffset])+offsetDisplay, color=colorBullDiv, width = 1) if display_input and display_divline and bearDiv>0 line.new(x1=bar_index-bearDiv, y1=math.round(srcDiv[bearDiv])+offsetDisplay, x2=bar_index-confirmationDivOffset, y2=math.round(srcDiv[confirmationDivOffset])+offsetDisplay, color=colorBearDiv, width = 1) //######## OUTPUT centeredReducedDisplay(choice,src,ampl,offset) => if choice=='Original' src else src * ampl + offset // Variable avgIndicators() => sumIndicators = (display_wt ? wt1*weigthWT : 0) + (display_DistanceShortSMA ? distance_close_shortsma*weigthSSMA : 0) + (display_DistanceLongSMA ? distance_close_longsma*weigthLSMA : 0) + (display_wr ? wr*weigthWR : 0) + (display_mom ? mom*weigthMom : 0) + (display_rsi ? rsi*weigthRSI : 0) + (display_stoch ? ((k+d)/2)*weigthStoch : 0) + (display_rvi ? rvi*weigthRVI : 0) + (display_tsi ? tsi*weigthTSI : 0) + (display_hac ? hac*weigthHAC : 0) + (display_bb ? ratioBB*weigthBB : 0) + (display_stc ? stc*weigthSTC : 0) + (display_aroonUp ? aroonUp*weigthAroonUp : 0) + (display_aroonDown ? aroonDown*weigthAroonDown : 0) + (display_mfi ? mfi*weigthMFI : 0) + (display_cmf ? cmf*weigthCMF : 0) + (display_TDS ? TDSRange*weigthTDS : 0) + (display_OscDiv ? oscDiv*weigthOscDiv : 0) nbIndicators = (display_wt ? weigthWT : 0) + (display_DistanceShortSMA ? weigthSSMA : 0) + (display_DistanceLongSMA ? weigthLSMA : 0) + (display_wr ? weigthWR : 0) + (display_mom ? weigthMom : 0) + (display_rsi ? weigthRSI : 0) + (display_stoch ? weigthStoch : 0) + (display_rvi ? weigthRVI : 0) + (display_tsi ? weigthTSI : 0) + (display_hac ? weigthHAC : 0) + (display_bb ? weigthBB : 0) + (display_stc ? weigthSTC : 0) + (display_aroonUp ? weigthAroonUp : 0) + (display_aroonDown ? weigthAroonDown : 0) + (display_mfi ? weigthMFI : 0) + (display_cmf ? weigthCMF : 0) + (display_TDS ? weigthTDS : 0) + (display_OscDiv ? weigthOscDiv : 0) sumIndicators / nbIndicators pc1Indicator() => sumIndicators = (display_wt ? wt1*weigthWT*0.28057677 : 0) + (display_wt ? wt2*weigthWT*0.26604956 : 0) + (display_wt ? wtDelta*weigthWT*0.09335345 : 0) + (display_hac ? hac*weigthHAC*0.27042294 : 0) + (display_aroonUp ? aroonUp*weigthAroonUp*0.2242386 : 0) + (display_aroonDown ? aroonDown*weigthAroonDown*0.21645523 : 0) + (display_stc ? stc*weigthSTC*0.22345921 : 0) + (display_rsi ? rsi*weigthRSI*0.27158859 : 0) + (display_stoch ? k*weigthStoch*0.21072071 : 0) + (display_stoch ? d*weigthStoch*0.20982997 : 0) + (display_stoch ? kdDelta*weigthStoch*0.0288154 : 0) + (display_rvi ? rvi*weigthRVI*0.21184407 : 0) + (display_tsi ? tsi*weigthTSI*0.22443242 : 0) + (display_bb ? ratioBB*weigthBB*0.27157343 : 0) + (display_wr ? wr*weigthWR*0.26881983 : 0) + (display_mom ? mom*weigthMom*0.15357979 : 0) + (display_TDS ? TDSRange*weigthTDS*0.21931816 : 0) + (display_mfi ? mfi*weigthMFI*0.16602267 : 0) + (display_cmf ? cmf*weigthCMF*0.17098777 : 0) + (display_OscDiv ? oscDiv*weigthOscDiv*0.06303232 : 0) nbIndicators = (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_hac ? weigthHAC : 0) + (display_aroonUp ? weigthAroonUp : 0) + (display_aroonDown ? weigthAroonDown : 0) + (display_stc ? weigthSTC : 0) + (display_rsi ? weigthRSI : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_rvi ? weigthRVI : 0) + (display_tsi ? weigthTSI : 0) + (display_bb ? weigthBB : 0) + (display_wr ? weigthWR : 0) + (display_mom ? weigthMom : 0) + (display_TDS ? weigthTDS : 0) + (display_mfi ? weigthMFI : 0) + (display_cmf ? weigthCMF : 0) + (display_OscDiv ? weigthOscDiv : 0) centeredReducedDisplay(ncPCA,(sumIndicators/nbIndicators),5.7,-8) pc2Indicator() => sumIndicators = (display_wt ? wt1*weigthWT*-0.11182425 : 0) + (display_wt ? wt2*weigthWT*-0.20781823 : 0) + (display_wt ? wtDelta*weigthWT*0.4838739 : 0) + (display_hac ? hac*weigthHAC*-0.001317 : 0) + (display_aroonUp ? aroonUp*weigthAroonUp*-0.1147146 : 0) + (display_aroonDown ? aroonDown*weigthAroonDown*-0.08458132 : 0) + (display_stc ? stc*weigthSTC*0.17033607 : 0) + (display_rsi ? rsi*weigthRSI*-0.06229966 : 0) + (display_stoch ? k*weigthStoch*0.30367343 : 0) + (display_stoch ? d*weigthStoch*0.11936626 : 0) + (display_stoch ? kdDelta*weigthStoch*0.46254792 : 0) + (display_rvi ? rvi*weigthRVI*0.1004253 : 0) + (display_tsi ? tsi*weigthTSI*-0.3034206 : 0) + (display_bb ? ratioBB*weigthBB*0.10333061 : 0) + (display_wr ? wr*weigthWR*0.02885504 : 0) + (display_mom ? mom*weigthMom*0.00359513 : 0) + (display_TDS ? TDSRange*weigthTDS*0.21002577 : 0) + (display_mfi ? mfi*weigthMFI*-0.05906281 : 0) + (display_cmf ? cmf*weigthCMF*-0.18905868 : 0) + (display_OscDiv ? oscDiv*weigthOscDiv*-0.37262208 : 0) nbIndicators = (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_hac ? weigthHAC : 0) + (display_aroonUp ? weigthAroonUp : 0) + (display_aroonDown ? weigthAroonDown : 0) + (display_stc ? weigthSTC : 0) + (display_rsi ? weigthRSI : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_rvi ? weigthRVI : 0) + (display_tsi ? weigthTSI : 0) + (display_bb ? weigthBB : 0) + (display_wr ? weigthWR : 0) + (display_mom ? weigthMom : 0) + (display_TDS ? weigthTDS : 0) + (display_mfi ? weigthMFI : 0) + (display_cmf ? weigthCMF : 0) + (display_OscDiv ? weigthOscDiv : 0) centeredReducedDisplay(ncPCA,(sumIndicators/nbIndicators),10,40) pc3Indicator() => sumIndicators = (display_wt ? wt1*weigthWT*0.00237309 : 0) + (display_wt ? wt2*weigthWT*0.05854934 : 0) + (display_wt ? wtDelta*weigthWT*-0.28723163 : 0) + (display_hac ? hac*weigthHAC*-0.01040362 : 0) + (display_aroonUp ? aroonUp*weigthAroonUp*0.12899243 : 0) + (display_aroonDown ? aroonDown*weigthAroonDown*0.17181989 : 0) + (display_stc ? stc*weigthSTC*0.26369398 : 0) + (display_rsi ? rsi*weigthRSI*-0.20109388 : 0) + (display_stoch ? k*weigthStoch*0.29001052 : 0) + (display_stoch ? d*weigthStoch*0.48443807 : 0) + (display_stoch ? kdDelta*weigthStoch*-0.41041703 : 0) + (display_rvi ? rvi*weigthRVI*-0.20322031 : 0) + (display_tsi ? tsi*weigthTSI*-0.19336318 : 0) + (display_bb ? ratioBB*weigthBB*-0.10276601 : 0) + (display_wr ? wr*weigthWR*-0.10545847 : 0) + (display_mom ? mom*weigthMom*-0.00559493 : 0) + (display_TDS ? TDSRange*weigthTDS*-0.07692795 : 0) + (display_mfi ? mfi*weigthMFI*0.0611499 : 0) + (display_cmf ? cmf*weigthCMF*-0.25686345 : 0) + (display_OscDiv ? oscDiv*weigthOscDiv*-0.30690315 : 0) nbIndicators = (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_hac ? weigthHAC : 0) + (display_aroonUp ? weigthAroonUp : 0) + (display_aroonDown ? weigthAroonDown : 0) + (display_stc ? weigthSTC : 0) + (display_rsi ? weigthRSI : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_rvi ? weigthRVI : 0) + (display_tsi ? weigthTSI : 0) + (display_bb ? weigthBB : 0) + (display_wr ? weigthWR : 0) + (display_mom ? weigthMom : 0) + (display_TDS ? weigthTDS : 0) + (display_mfi ? weigthMFI : 0) + (display_cmf ? weigthCMF : 0) + (display_OscDiv ? weigthOscDiv : 0) centeredReducedDisplay(ncPCA,(sumIndicators/nbIndicators),11,70) pc4Indicator() => sumIndicators = (display_wt ? wt1*weigthWT*-0.04892113 : 0) + (display_wt ? wt2*weigthWT*-0.03916461 : 0) + (display_wt ? wtDelta*weigthWT*-0.05407767 : 0) + (display_hac ? hac*weigthHAC*-0.02241438 : 0) + (display_aroonUp ? aroonUp*weigthAroonUp*-0.12627281 : 0) + (display_aroonDown ? aroonDown*weigthAroonDown*-0.06693908 : 0) + (display_stc ? stc*weigthSTC*-0.1231245 : 0) + (display_rsi ? rsi*weigthRSI*0.04708137 : 0) + (display_stoch ? k*weigthStoch*-0.11330626 : 0) + (display_stoch ? d*weigthStoch*-0.08116231 : 0) + (display_stoch ? kdDelta*weigthStoch*-0.0883354 : 0) + (display_rvi ? rvi*weigthRVI*0.11037185 : 0) + (display_tsi ? tsi*weigthTSI*0.05410202 : 0) + (display_bb ? ratioBB*weigthBB*-0.0521927 : 0) + (display_wr ? wr*weigthWR*-0.13628793 : 0) + (display_mom ? mom*weigthMom*0.83241525 : 0) + (display_TDS ? TDSRange*weigthTDS*0.03529496 : 0) + (display_mfi ? mfi*weigthMFI*0.28100209 : 0) + (display_cmf ? cmf*weigthCMF*0.02892046 : 0) + (display_OscDiv ? oscDiv*weigthOscDiv*-0.33888006 : 0) nbIndicators = (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_wt ? weigthWT : 0) + (display_hac ? weigthHAC : 0) + (display_aroonUp ? weigthAroonUp : 0) + (display_aroonDown ? weigthAroonDown : 0) + (display_stc ? weigthSTC : 0) + (display_rsi ? weigthRSI : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_stoch ? weigthStoch : 0) + (display_rvi ? weigthRVI : 0) + (display_tsi ? weigthTSI : 0) + (display_bb ? weigthBB : 0) + (display_wr ? weigthWR : 0) + (display_mom ? weigthMom : 0) + (display_TDS ? weigthTDS : 0) + (display_mfi ? weigthMFI : 0) + (display_cmf ? weigthCMF : 0) + (display_OscDiv ? weigthOscDiv : 0) centeredReducedDisplay(ncPCA,(sumIndicators/nbIndicators),22,45) // explained_variance_ratio_ : 0.55540809 0.13021972 0.07303142 0.03760925 // explained_variance_ : 11.6639671 2.73470717 1.53371209 0.7898212 methodRiskIndicator(method) => if method == 'Average' avgIndicators() else if method == 'PC1' pc1Indicator() else if method == 'PC2' pc2Indicator() else if method == 'PC3' pc3Indicator() else if method == 'PC4' pc4Indicator() else avgIndicators() //---- Risk Indicator avgIndicator = avgIndicators() pc1Indicator = pc1Indicator() pc2Indicator = pc2Indicator() pc3Indicator = pc3Indicator() pc4Indicator = pc4Indicator() display_AvgRisk = input.bool(false,title="Display Average Indicator ?" , group="Risk Settings", tooltip="It is a synthetic output indicator that simply averages all the input indicators you have selected") colorAvgRisk = input.color(color.new(color.white ,30), title="Average risk color", group="Risk Settings") display_PC1 = input.bool(false,title="Display PC1 Indicator ?" , group="Risk Settings", tooltip="This indicator is calculated according to the PC1 from the PCA statistical method that analyzes each indicator input") colorPC1 = input.color(color.new(color.red ,30), title="PC1 color" , group="Risk Settings") display_PC2 = input.bool(false,title="Display PC2 Indicator ?" , group="Risk Settings", tooltip="This indicator is calculated according to the PC2 from the PCA statistical method that analyzes each indicator input") colorPC2 = input.color(color.new(color.blue ,30), title="PC2 color" , group="Risk Settings") display_PC3 = input.bool(false,title="Display PC3 Indicator ?" , group="Risk Settings", tooltip="This indicator is calculated according to the PC3 from the PCA statistical method that analyzes each indicator input") colorPC3 = input.color(color.new(color.green ,30), title="PC3 color" , group="Risk Settings") display_PC4 = input.bool(false,title="Display PC4 Indicator ?" , group="Risk Settings", tooltip="This indicator is calculated according to the PC4 from the PCA statistical method that analyzes each indicator input") colorPC4 = input.color(color.new(color.yellow,30), title="PC4 color" , group="Risk Settings") display_Risk = input.bool(true, title="Display Risk Indicator ?" , group="Risk Settings", tooltip="This indicator can be the output indicator you choose and display this one with variable color") methodRI = input.string('PC1', title='Which method to use to define Risk Indicator ?', options=['Average','PC1','PC2','PC3','PC4'], group='Risk Settings') barcolor_Risk = input.bool(true, title="Display barcolor with Risk indicator ?" , group="Risk Settings") colorOption = input.string(defval='Gradient', title='Method for displaying risk colors' , options=['Gradient','Absolute','Uniform'] , group='Risk Settings') riskRatio = methodRiskIndicator(methodRI) levelRiskSafe = input.int(10, minval=0, maxval=100, title="Level risk safe" , group="Risk Settings") colorRiskSafe = input.color(color.rgb(0,0,255,0) , title="Risk safe color" , group="Risk Settings") levelRiskOk = input.int(40, minval=0, maxval=100, title="Level risk ok" , group="Risk Settings") colorRiskOk = input.color(color.rgb(0,255,0,0) , title="Risk ok color" , group="Risk Settings") levelRiskWarn = input.int(60, minval=0, maxval=100, title="Level risk warn" , group="Risk Settings") colorRiskWarn = input.color(color.rgb(255,255,0,0), title="Risk warning color" , group="Risk Settings") levelRiskDanger = input.int(90, minval=0, maxval=100, title="Level risk danger" , group="Risk Settings") colorRiskDanger = input.color(color.rgb(255,0,0,0) , title="Risk danger color" , group="Risk Settings") colorRisk = if colorOption == 'Gradient' riskRatio > levelRiskOk ? riskRatio > levelRiskWarn ? color.from_gradient(riskRatio, levelRiskWarn, levelRiskDanger, colorRiskWarn, colorRiskDanger) : color.from_gradient(riskRatio, levelRiskOk, levelRiskWarn, colorRiskOk, colorRiskWarn) : color.from_gradient(riskRatio, levelRiskSafe, levelRiskOk, colorRiskSafe, colorRiskOk) else if colorOption == 'Absolute' riskRatio > levelRiskOk ? riskRatio > levelRiskWarn ? riskRatio > levelRiskDanger ? colorRiskDanger : colorRiskWarn : colorRiskOk : colorRiskSafe else colorRiskOk // Plot band1 = hline(display_input ? offsetDisplay : 0 , color=color.gray, linestyle=hline.style_solid) band0 = hline(0 , color=color.gray, linestyle=hline.style_solid) bandMinus1 = hline(display_output ? 100 : 0 , color=color.gray, linestyle=hline.style_solid) plot(display_output and display_PC4 ? pc4Indicator : na, title="PC4 Indicator" , color=colorPC4 , linewidth = 2, histbase=50, style=plot.style_line) plot(display_output and display_PC3 ? pc3Indicator : na, title="PC3 Indicator" , color=colorPC3 , linewidth = 2, histbase=50, style=plot.style_line) plot(display_output and display_PC2 ? pc2Indicator : na, title="PC2 Indicator" , color=colorPC2 , linewidth = 2, histbase=50, style=plot.style_line) plot(display_output and display_PC1 ? pc1Indicator : na, title="PC1 Indicator" , color=colorPC1 , linewidth = 2, histbase=50, style=plot.style_line) plot(display_output and display_AvgRisk ? avgIndicator : na, title="Average Indicator" , color=colorAvgRisk, linewidth = 2, histbase=50, style=plot.style_line) plot(display_output and display_Risk ? riskRatio : na, title="Risk Ratio" , color=colorRisk , linewidth = 2, histbase=50, style=plot.style_line) barcolor(color = barcolor_Risk ? colorRisk : na) // Alert lowRiskAlert = input.int(10, minval=0, maxval=100, title="Low risk level for the alert" , group="Alerts") highRiskAlert = input.int(90, minval=0, maxval=100, title="High risk level for the alert" , group="Alerts") if (riskRatio < lowRiskAlert and riskRatio < riskRatio[2]) or (riskRatio > highRiskAlert and riskRatio > riskRatio[2]) alert("{\n\"tickerId\" : \"" + syminfo.tickerid + "\",\n\"timestamp\" : " + str.tostring(timenow) + ",\n\"risk-ratio\": " + str.tostring(riskRatio) + "\n}", alert.freq_once_per_bar_close)
Candle Gaps
https://www.tradingview.com/script/KaDyEvwI-Candle-Gaps/
ivanroyloewen
https://www.tradingview.com/u/ivanroyloewen/
18
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/ // © ivanroyloewen //@version=5 indicator("Candle Gaps", overlay = true, max_boxes_count = 50) //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Input // the colour that the gaps will be colour_Of_Gaps = input(title = "Gap Colour", defval = color.black) // start drawing the left of the gaps box at the previous candles wick or from the current candle draw_Gap_From_Wick = input(title = "Start Gaps From Wicks", defval = false) //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Handle Down Gaps // create an array for all the down gaps var down_Gaps = array.new<box>(0) // draw the down gaps Draw_Down_Gaps() => // check if there is an down gap on the present candle... if close < low[1] // there is... draw an down box box down_box = box.new(bar_index[draw_Gap_From_Wick ? 1 : 0], low[1], bar_index, close, border_color = na, bgcolor = colour_Of_Gaps, extend = extend.right) // add it to the down_Gaps array array.push(down_Gaps, down_box) // fill in down gaps as price crosses over them Fill_In_Down_Gaps() => // loop through all the down gaps for [index, value] in down_Gaps // check if the loop gap ( value ) is the present candle, if it is keep looping ( prevents the present candle gap from being filled always)... if value.get_left() != bar_index[draw_Gap_From_Wick ? 1 : 0] // it is not... check if the high of the current candle is higher than the bottom of the loop gap ( value )... if high > value.get_bottom() // it is... check if the present candle high is above the loop gap ( value ) top... if high < value.get_top() // it is... set the bottom of the loop gap ( value ) to the high of the present candle, partially filling in the gap value.set_bottom(high) else // it is not... the current candle high is higher than the loop gap ( value ) top, the gap is entirely filled, delete it value.delete() //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Handle Up Gaps // create an array for all the up gaps var up_Gaps = array.new<box>(0) // draw the up gaps Draw_Up_Gaps() => // check if there is an up gap on the present candle... if close > high[1] // there is... draw an up box box up_Gap = box.new(bar_index[draw_Gap_From_Wick ? 1 : 0], close, bar_index, high[1], border_color = na, bgcolor = colour_Of_Gaps, extend = extend.right) // add it to the up_Gaps array array.push(up_Gaps, up_Gap) // fill in up gaps as price crosses over them Fill_In_Up_Gaps() => // loop through all the up gaps for [index, value] in up_Gaps // check if the loop gap ( value ) is the present candle, if it is keep looping ( prevents the present candle gap from being filled always)... if value.get_left() != bar_index[draw_Gap_From_Wick ? 1 : 0] // it is not... check if the low of the current candle is lower than the top of the loop gap ( value )... if low < value.get_top() // it is... check if the present candle low is above the loop gap ( value ) bottom... if low > value.get_bottom() // it is... set the top of the loop gap ( value ) to the low of the present candle, partially filling in the gap value.set_top(low) else // it is not... the current candle low is lower than the loop gap ( value ) bottom, the gap is entirely filled, delete it value.delete() //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Execution // execute all gap drawing functions Draw_Down_Gaps() Draw_Up_Gaps() // execute all gap filling functions Fill_In_Down_Gaps() Fill_In_Up_Gaps() //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Recession Indicator (Unemployment Rate)
https://www.tradingview.com/script/Apvuuszy-Recession-Indicator-Unemployment-Rate/
VanHe1sing
https://www.tradingview.com/u/VanHe1sing/
33
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/ // © VanHe1sing //@version=5 indicator("Recession Indicator (Unemployment Rate)") // Unemployment Rate source src = request.security("UNRATE", "", close) // Yearly Rate of change YoY = (src-src[12])/src[12] //Checking of timeframe timeframe = timeframe.ismonthly // Colored background between the annual ROC above zero and its peak var ath = 0.0 if YoY > ath ath := YoY bgcolor(timeframe ? (YoY > 0 and YoY < ath and YoY > ta.sma(YoY,5) ? color.rgb(120, 123, 134, 31): na) : na) //Plot's plot(timeframe ? YoY : na, color = color.white), plot(timeframe ? 0 : na, color = color.gray) // Checker of timeframe tbl= table.new(position.middle_center,1,1),table.cell(tbl, 0, 0, timeframe ? "" : "USE MONTHLY TIMEFRAME", text_color = color.red, text_size = size.huge)
9-20 sma multi timeframe indicator
https://www.tradingview.com/script/jvg3Qf5W-9-20-sma-multi-timeframe-indicator/
Elimak07
https://www.tradingview.com/u/Elimak07/
23
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/ // © Elimak07 // @version=5 indicator("9-20 multi timeframes indicator") // Get user input res1 = input.timeframe(title="Timeframe #1", defval="") res2 = input.timeframe(title="Timeframe #2", defval="3") res3 = input.timeframe(title="Timeframe #3", defval="5") // set style strong_green = input(#26A69A, "Above Grow", group="Sma", inline="Above") weak_green = input(#8bc8c3, "Fall", group="Sma", inline="Above") weak_red = input(#eab3b9, "Below Grow", group="Sma", inline="Below") strong_red = input(#FF5252, "Fall", group="Sma", inline="Below") // Define custom security function f_sync(_res, _exp) => request.security(syminfo.tickerid, _res, _exp) // Function to find the closest previous value of the serie // because of using differentr time frame, this could be several index back f_findFirstPreviousValue(serie) => found = serie for i = 0 to 20 if serie[i] != serie found := serie[i] break found // Function to get if the sma crossed in the timeframe selected f_crossed(res, sma9, sma20) => syncSma9 = f_sync(res,sma9) syncSma20 = f_sync(res,sma20) crossUp = ta.crossover(syncSma9, syncSma20) crossDown = ta.crossunder(syncSma9, syncSma20) crossUp or crossDown // get the trend in the timeframe selected f_uptrend(res, sma9, sma20) => syncSma9 = f_sync(res, sma9) syncSma20 = f_sync(res, sma20) syncSma9 > syncSma20 // Function to find the status of the trade: started, not started f_tradeStarted(res, sma9, sma20, tradeStarted) => bool result = tradeStarted syncClose = f_sync(res, close) syncOpen = f_sync(res, open) syncSma9 = f_sync(res, sma9) syncSma20 = f_sync(res, sma20) isGreen = syncClose > syncOpen isRed = syncClose < syncOpen crossed = f_sync(res, ta.crossover(syncSma9, syncSma20)) or f_sync(res, ta.crossunder(syncSma9, syncSma20)) uptrend = f_uptrend(res, sma9, sma20) if crossed result := false else isGreenCandleAbove9 = isGreen and syncClose > syncSma9 isRedCandleBelow9 = isRed and syncClose < syncSma9 if uptrend and not tradeStarted if isGreenCandleAbove9 result := true if uptrend and tradeStarted if isRedCandleBelow9 result := false if not uptrend and not tradeStarted if isRedCandleBelow9 result := true if not uptrend and tradeStarted if isGreenCandleAbove9 result := false log.info("> started "+ str.tostring(result)) result // when the trade is favorable, it will be green in the uptrend // and red in the downtrend - when falling in uptrend and growing // in downtrend, we wignal the weakness with a lighter color f_colorFill(res, sma9, sma20) => sma9Sync = f_sync(res1, sma9) previousValue = f_findFirstPreviousValue(sma9Sync) growing = sma9Sync >= previousValue falling = sma9Sync < previousValue colorUp = growing ? strong_green : weak_green colorDown = falling ? strong_red : weak_red uptrend = f_uptrend(res, sma9, sma20) uptrend ? colorUp : colorDown // Get SMA values sma9 = ta.sma(close, 9) sma20 = ta.sma(close, 20) bool trade1Started = na trade1Started := f_tradeStarted(res1, sma9, sma20, trade1Started[1]) showCross1 = f_crossed(res1, sma9, sma20) colorFill1 = f_colorFill(res1, sma9, sma20) color1 = trade1Started? colorFill1 : color.rgb(198, 202, 219) bool trade2Started = na trade2Started := f_tradeStarted(res2, sma9, sma20, trade2Started[1]) showCross2 = f_crossed(res2, sma9, sma20) colorFill2 = f_colorFill(res2, sma9, sma20) color2 = trade2Started? colorFill2 : color.rgb(198, 202, 219) bool trade3Started = na trade3Started := f_tradeStarted(res3, sma9, sma20, trade3Started[1]) showCross3 = f_crossed(res3, sma9, sma20) colorFill3 = f_colorFill(res3, sma9, sma20) color3 = trade3Started? colorFill3 : color.rgb(198, 202, 219) plotshape(showCross1? 2.5:na, title = "crossed #1", text = '', style = shape.xcross, location = location.absolute, color= color.rgb(0, 0, 0), textcolor = color.white, size = size.tiny) plotshape(showCross2? 1.5:na, title = "crossed #2", text = '', style = shape.xcross, location = location.absolute, color= color.rgb(0, 0, 0), textcolor = color.white, size = size.tiny) plotshape(showCross3? 0.5:na, title = "crossed #3", text = '', style = shape.xcross, location = location.absolute, color= color.rgb(0, 0, 0), textcolor = color.white, size = size.tiny) // Change background color #3 r1 = hline(0, color=color.black) r2 = hline(1, color=color.black) fill(r1, r2, color3) // Change background color #2 r3 = hline(1, color=color.black) r4 = hline(2, color=color.black) fill(r3, r4, color2) // Change background color #1 r5 = hline(2, color=color.black) r6 = hline(3, color=color.black) fill(r5, r6, color1) // Alert conditions bool enter1 = na if trade1Started != trade1Started[1] and trade1Started enter1 := true bool exit1 = na if trade1Started != trade1Started[1] and not trade1Started exit1 := true alertcondition(enter1, 'Start trading timeframe #1', 'Start trading timeframe #1 - look at the chart for direction - {{interval}} {{ticker}}') alertcondition(exit1, 'Exit trading timeframe #1', 'Exit trading timeframe #1 - {{interval}} {{ticker}}') bool enter2 = na if trade1Started != trade1Started[1] and trade1Started enter2 := true bool exit2 = na if trade2Started != trade2Started[2] and not trade2Started exit2 := true alertcondition(enter2, 'Start trading timeframe #2', 'Start trading timeframe #2 - look at the chart for direction - {{interval}} {{ticker}}') alertcondition(exit2, 'Exit trading timeframe #2', 'Exit trading timeframe #2 - {{interval}} {{ticker}}') bool enter3 = na if trade3Started != trade3Started[1] and trade3Started enter3 := true bool exit3 = na if trade3Started != trade3Started[2] and not trade3Started exit3 := true alertcondition(enter3, 'Start trading timeframe #3', 'Start trading timeframe #3 - look at the chart for direction - {{interval}} {{ticker}}') alertcondition(exit3, 'Exit trading timeframe #3', 'Exit trading timeframe #3 - {{interval}} {{ticker}}')
Asiri Colored Candle
https://www.tradingview.com/script/jybNovHM/
asiri8
https://www.tradingview.com/u/asiri8/
19
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/ // © asiri8 //@version=5 indicator("Asiri Colored Candle", overlay=true, max_labels_count=500, max_lines_count = 1) len_changed = (timeframe.period == 'W' ? 14 : timeframe.period == 'D' ? 14 : timeframe.period == '240' ? 14 : timeframe.period == '60' ? 14 : timeframe.period == '30' ? 14 : timeframe.period == '15' ? 14 : timeframe.period == '10' ? 14 : timeframe.period == '5' ? 14 : 14) //Volume Moving Average SMA_Volume = ta.sma(volume, 20) // MFI MFIlength = input.int(title="Length", defval=14, minval=1, maxval=2000) src = hlc3 mf = ta.mfi(src, MFIlength) // White Candle, current volume greater than previous volume, and also greater than volume moving average SMA_Volume = ta.sma(volume, 20) //Elasticity_Green_Candle = ((close>open) and (close>close[1]) and (volume>volume[1]) and ((((volume-volume[1])/volume[1])/((close-close[1])/close[1]))>0)) // شمعة المرونة Elasticity_Green_Candle_with_Volume = ( (volume>volume[1]) and (close>open) and (close>close[1]) and (volume > SMA_Volume) ) plotcandle(Elasticity_Green_Candle_with_Volume ? open: na, Elasticity_Green_Candle_with_Volume ? high : na, Elasticity_Green_Candle_with_Volume ? low : na, Elasticity_Green_Candle_with_Volume ? close : na, title="Elasticity_Green_Candle_with_Volume", color=color.white, wickcolor=color.white, bordercolor=color.white) // Green Candle, current volume greater than previous volume, and smaller than volume moving average Elasticity_Green_Candle_No_Volume = ((volume>volume[1]) and (close>open) and (close>close[1]) and (volume < SMA_Volume)) plotcandle(Elasticity_Green_Candle_No_Volume ? open: na, Elasticity_Green_Candle_No_Volume ? high : na, Elasticity_Green_Candle_No_Volume ? low : na, Elasticity_Green_Candle_No_Volume ? close : na, title="Elasticity_Green_Candle_No_Volume", color=color.lime, wickcolor=color.lime, bordercolor=color.lime) // Use this for condition data = ( (volume>volume[1]) and (close>open) and (close>close[1]) and (volume > 1.5*(SMA_Volume)) ) //data = ( ( (close>open) and (volume > 1.5*(SMA_Volume)) ) ) //data = ( ((close>open) or (close==open)) and (volume > 1.5*(SMA_Volume)) ) //data1 = ( ((close==open) or (close>open)) and ((close == close[1]) or (close<close[1])) and (volume > 1.5*(SMA_Volume)) ) data1 =(close==open and (volume > 1.5*(SMA_Volume))) data2 = (close==open and (volume > 1.5*(SMA_Volume))) data3 = (close>open and (close<close[1]and ((volume>volume[1]) or (volume<volume[1]) or (volume==volume[1]))) and (volume > 1.5*(SMA_Volume))) data4 = (close>open and (close>close[1]and ((volume<volume[1]) or (volume==volume[1]))) and (volume > 1.5*(SMA_Volume))) data5 = (close>open and (close==close[1]and ((volume>volume[1]) or (volume<volume[1]) or (volume==volume[1]))) and (volume > 1.5*(SMA_Volume))) //data = ( (volume>volume[1]) and (close>open) and (close>close[1]) and (volume > (SMA_Volume + (1.5*(SMA_Volume)))) ) //data = ( (volume>volume[1]) and (close>open) and (close>close[1]) and (volume > 1.5*(SMA_Volume)) ) //data1 = ( ((close>open) and (volume <volume[1]) and (volume > 1.5*(SMA_Volume))) ) //data2 = ( ((close==open) and ((close == close[1]) or (close>close[1]))) and (volume > 1.5*(SMA_Volume)) ) //data3 = ( ((close==open) and (close == close[1]) and (volume > 1.5*(SMA_Volume))) or ((close==open) and (close > close[1]) and (volume > 1.5*(SMA_Volume))) ) //data4 = ( ((close==open) and (volume > 1.5*(SMA_Volume))) ) //plotchar(data, location = location.abovebar, color = color.white) //plotchar(data, location = location.abovebar, color = color.white, text="X") //plotchar(data, char='❄', location = location.abovebar, color = color.white) label volumelabel1 = na // This condition to put the volume Multipliers if (data) highvolume = volume /(SMA_Volume) volumelabel1 := label.new(bar_index, high, text=str.tostring(highvolume,'#'), size = size.small, textcolor = color.white ,color = color.white, yloc=yloc.abovebar, style=label.style_none) //volumelabel1 := label.new(bar_index, high, text=str.tostring(highvolume,'#.#'), size = size.small, textcolor = color.white ,color = color.white, yloc=yloc.abovebar, style=label.style_none) // This condition to put the volume Multipliers if (data2 or data3 or data4 or data5) highvolume = volume /(SMA_Volume) volumelabel1 := label.new(bar_index, high, text=str.tostring(highvolume,'#'), size = size.small, textcolor = color.yellow ,color = color.white, yloc=yloc.abovebar, style=label.style_none) //volumelabel1 := label.new(bar_index, high, text=str.tostring(highvolume,'#.#'), size = size.small, textcolor = color.yellow ,color = color.white, yloc=yloc.abovebar, style=label.style_none) //if (data4) //highvolume = volume /(SMA_Volume) //volumelabel1 := label.new(bar_index, high, text=str.tostring(highvolume,'#'), size = size.small, textcolor = color.yellow ,color = color.white, yloc=yloc.abovebar, style=label.style_none) // Rate_of_Candle_Change = (((close - close[1])/close[1]) * 100) Elasticity_Green_Candle_with_change = input.bool(false) Elasticity_Green_Candle_with_change_1 = input.bool(false) Elasticity_Green_Candle_1 = input.bool(false) // Bullish candle, its change 3% and higher, and the volume greater than previous, no matter for volume moving average, // this candleو Often they appear in high Time Frame // Purchaseing_Candle = ( (close>open) and (volume<volume[1]) and (Rate_of_Candle_Change >= 3) ) Minutes_Purchaseing_Candle = input.bool(false) // Bearish candle, its change 3%, and this candleو Often they appear in high Time Frame Selling_Candle = ((Rate_of_Candle_Change < -3) and (close<open)) Minutes_Selling_Candle = input.bool(false) if(timeframe.isminutes) Minutes_Purchaseing_Candle := ( (close>open) and (volume<volume[1]) and (Rate_of_Candle_Change >= 1.3) ) Minutes_Selling_Candle := ((Rate_of_Candle_Change < -1.3) and (close<open)) barcolor(Elasticity_Green_Candle_with_Volume? color.white :Elasticity_Green_Candle_No_Volume? color.lime :Purchaseing_Candle? color.rgb(92, 90, 248): Minutes_Purchaseing_Candle? color.rgb(92, 90, 248):Selling_Candle? color.yellow: Minutes_Selling_Candle? color.yellow : na) // Set the color of the candles barcolor(Elasticity_Green_Candle_with_Volume? color.white :Elasticity_Green_Candle_No_Volume? color.lime: Purchaseing_Candle? color.rgb(92, 90, 248): Selling_Candle? color.yellow: na) //Purchaseing_Candle? color.rgb(92, 90, 248) plotcandle(Purchaseing_Candle ? open: na, Purchaseing_Candle ? high : na, Purchaseing_Candle ? low : na, Purchaseing_Candle ? close : na, title="Purchaseing_Candle", color=color.rgb(92, 90, 248), wickcolor=color.rgb(92, 90, 248), bordercolor=color.rgb(92, 90, 248)) plotcandle(Minutes_Purchaseing_Candle ? open: na, Minutes_Purchaseing_Candle ? high : na, Minutes_Purchaseing_Candle ? low : na, Minutes_Purchaseing_Candle ? close : na, title="Minutes_Purchaseing_Candle", color=color.rgb(92, 90, 248), wickcolor=color.rgb(92, 90, 248), bordercolor=color.rgb(92, 90, 248)) LowestValueAndBar(source, lenght) => MFIValue = mf MFIIndex = bar_index //Loop e.g. 100 times and see if the other previous values are smaller. Then update the "minValue" and "minIndex" for i = 1 to lenght if source[i] < MFIValue MFIValue := source[i] MFIIndex := bar_index[i] [MFIValue, MFIIndex] [value, index] = LowestValueAndBar(mf, 14) //label.new(index, value, text="Hello, world!", style=label.style_circle, size = size.tiny) // To put the lowest MFI vlaue under the candle label label1 = na //lowestrsi = 0.0 lowestrsi = ta.lowest(mf, 14) //bar = ta.barssince(ta.lowest(mf, 14)) //lo = ta.barssince(ta.lowest(mf, 14)) Buy_M = input.bool(false) if timeframe.isminutes if (mf < 30) Buy_M := (mf < 30) //label1 = label.new(bar_index , low - 0.05, text="B", size = size.normal, textcolor = color.black ,color = color.rgb(255, 255, 255), style=label.style_label_up) label1 := label.new(index, value, text=str.tostring(value,'#'), size = size.small, textcolor = color.white ,color = color.white, yloc=yloc.belowbar, style=label.style_none) //label1 := label.new(bar_index , low - 0.3, text=str.tostring(rsi,'#'), size = size.normal, textcolor = color.white ,color = color.rgb(255, 255, 255), style=label.style_none) //label1 := label.new(bar_index, na, text=str.tostring(rsi,'#'), size = size.small, textcolor = color.black ,color = color.white, yloc=yloc.belowbar, style=label.style_label_up) label.delete(label1[1]) //label.new(bar_index, low - 0.1, "Buy", textcolor=color.rgb(255, 251, 2), style=label.style_none, size=size.small) //plotchar(Buy_M, char='B', location = location.belowbar, color = color.white, size = size.tiny) Buy_D = input.bool(false) if timeframe.isdaily if (mf < 30) Buy_D := (mf < 30) //label1 := label.new(bar_index , na, text=str.tostring(rsi,'#'), size = size.small, textcolor = color.black ,color = color.white, yloc=yloc.belowbar,style=label.style_label_up) label1 := label.new(index, value, text=str.tostring(value,'#'), size = size.small, textcolor = color.white ,color = color.white, yloc=yloc.belowbar, style=label.style_none) //label1 := label.new(bar_index , low - 1, text=str.tostring(rsi,'#'), size = size.normal, textcolor = color.white ,color = color.rgb(255, 255, 255), style=label.style_none) label.delete(label1[1]) Buy_Mo = input.bool(false) if timeframe.isweekly if (mf < 30) Buy_Mo := (mf < 30) label1 := label.new(index, value, text=str.tostring(value,'#'), size = size.small, textcolor = color.white ,color = color.white, yloc=yloc.belowbar, style=label.style_none) label.delete(label1[1]) // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Machine Learning: MFI Heat Map [YinYangAlgorithms]
https://www.tradingview.com/script/h3bdHkHg-Machine-Learning-MFI-Heat-Map-YinYangAlgorithms/
YinYangAlgorithms
https://www.tradingview.com/u/YinYangAlgorithms/
45
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: MFI Heat Map [YinYangAlgorithms]") // ~~~~~~~~~~~~~~ INPUTS ~~~~~~~~~~~~~~ // // -- MFI showSignals = input.bool(false, "Show MFI and SMA Crossing Signals", group="MFI", tooltip="MFI and SMA Crossing is one of the leading Bullish and Bearish Signals in this Indicator. You can also add alerts for these signals.") plotAmount = input.int(28, "Plot Amount", minval=2, maxval=28, group="MFI", tooltip="How many plots are used in this Heat Map. (2 - 28).") source = input.source(ohlc4, "Source", group="MFI", tooltip="The Source to use in all MFI calculations.") smoothInitialMFI = input.int(1, "Smooth Initial MFI Length", minval=1, group="MFI", tooltip="How much to smooth the Fast and Slow MFI calculation by. 1 = No smoothing.") smaLength = input.int(16, "MFI SMA Length", group="MFI", tooltip="What length we smooth the MFI Average over to get our MFI SMA.") // -- Machine Learning useKInSource = input.bool(false, "Average MFI data by adding a lookback to the Source", group="Machine Learning Settings", tooltip="While populating our Heat Map with the MFI's, should use use the Source each MFI Length increase or should we also lookback a Source each MFI Length Increase.") distanceType = input.string("Max", "KNN Distance Requirement", options=["Max", "Min", "Both"], group="Machine Learning Settings", tooltip="To be a valid KNN, it needs to abide by a Distance calculation. Generally only Max is used, but you can change it if it suits your trading style better.") mlLength = input.int(5, "Machine Learning Length", minval=1, group="Machine Learning Settings", tooltip="How much ML data should we store? The longer the length generally the smoother the result; which may not be as accurate for something like a Heat Map, so keeping this relatively low may lead to more accurate results.") knnLength = input.int(2, "KNN Length", minval=1, group="Machine Learning Settings", tooltip="How many KNN are used in the slice to calculate max/min distance allowed.") fastLength = input.int(2, "Fast Length", minval=1, group="Machine Learning Settings", tooltip="Fast MFI length used in KNN to calculate distances by comparing its distance with the Slow MFI Length.") slowLength = input.int(5, "Slow Length", minval=2, group="Machine Learning Settings", tooltip="Slow MFI length used in KNN to calculate distances by comparing its distance with the Fast MFI Length.") kSmoothing = input.int(1, "Smoothing Length", minval=1, group="Machine Learning Settings", tooltip="When populating our Heat Map, at what length do we start our MFI calculations with (A Higher value with result in a slower and more smoothed MFI / Heat Map).") // -- Colors changeBarColor = input.bool(true, "Change Bar Color", group="Heat Map Colors", tooltip="Change bar colors to MFI Avg Color") trans = input.float(30., "Heat Map Transparency", tooltip="If there isn't any transparency it can be a little hard on the eyes. The Greater the Line Width, generally the more transparency you'll want for your eyes.", group="Heat Map Colors") lineWidth = input.int(2, "Line Width", minval=1, tooltip="Set how wide the Heat Map lines are", group="Heat Map Colors") //high color_high_1_input = input.color(#de1414, "MFI 90-100 Color", group="Heat Map Colors") color_high_2_input = input.color(#f35208, "MFI 80-89 Color", group="Heat Map Colors") color_high_3_input = input.color(#f3970e, "MFI 70-79 Color", group="Heat Map Colors") color_high_4_input = input.color(#f2f608, "MFI 60-69 Color", group="Heat Map Colors") color_high_5_input = input.color(#35f60a, "MFI 50-59 Color", group="Heat Map Colors") //low color_low_1_input = input.color(#001b73, "MFI 40-49 Color", group="Heat Map Colors") color_low_2_input = input.color(#003afa, "MFI 30-39 Color", group="Heat Map Colors") color_low_3_input = input.color(#0372fa, "MFI 20-29 Color", group="Heat Map Colors") color_low_4_input = input.color(#00a7e4, "MFI 10-19 Color", group="Heat Map Colors") color_low_5_input = input.color(#00f2ff, "MFI 0-9 Color", group="Heat Map Colors") // ~~~~~~~~~~~~~~ VARIABLES ~~~~~~~~~~~~~~ // //Used in KNN Function minDist = distanceType == "Both" or distanceType == "Min" maxDist = distanceType == "Both" or distanceType == "Max" //high color_high_1 = color.new(color_high_1_input, trans) color_high_2 = color.new(color_high_2_input, trans) color_high_3 = color.new(color_high_3_input, trans) color_high_4 = color.new(color_high_4_input, trans) color_high_5 = color.new(color_high_5_input, trans) //low color_low_1 = color.new(color_low_1_input, trans) color_low_2 = color.new(color_low_2_input, trans) color_low_3 = color.new(color_low_3_input, trans) color_low_4 = color.new(color_low_4_input, trans) color_low_5 = color.new(color_low_5_input, trans) // ~~~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~~~ // //Get the color of MFI level for the Heat Map getColor(_mfi) => mfiColor = color.red if _mfi >= 90 mfiColor := color_high_1 else if _mfi >= 80 and _mfi < 90 mfiColor := color_high_2 else if _mfi >= 70 and _mfi < 80 mfiColor := color_high_3 else if _mfi >= 60 and _mfi < 70 mfiColor := color_high_4 else if _mfi >= 50 and _mfi < 60 mfiColor := color_high_5 else if _mfi >= 40 and _mfi < 50 mfiColor := color_low_1 else if _mfi >= 30 and _mfi < 40 mfiColor := color_low_2 else if _mfi >= 20 and _mfi < 30 mfiColor := color_low_3 else if _mfi >= 10 and _mfi < 20 mfiColor := color_low_4 else mfiColor := color_low_5 mfiColor //Simple k-Nearest Neighbor function used to filter ML Data //Average all data from ML Length (Setting) that is between Min/Max KNN Distance (Setting) getKNN(_dataFast, _dataSlow) => //Calculate the distance between slow and fast moving MIF distances = array.new_float(0) for i = 0 to _dataSlow.size() - 1 distance = _dataFast.get(i) - _dataSlow.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) //return the average of valid distances validDistances.avg() // ~~~~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~~~~ // //Get the fast and slow (potentially smoothed) MFIs float mfi_fast = ta.ema(ta.mfi(source, fastLength), smoothInitialMFI) float mfi_slow = ta.ema(ta.mfi(source, slowLength), smoothInitialMFI) //Create a storage array to save the MFI data to be used in KNN Function mfis_fast = array.new_float(mlLength) mfis_slow = array.new_float(mlLength) //Populate MFI data with previous fast and slow MFIs for i = 0 to mlLength - 1 mfis_fast.set(i, mfi_fast[i]) mfis_slow.set(i, mfi_slow[i]) //Calculate the MFI's ML Average using KNN float mfiKNN = getKNN(mfis_fast, mfis_slow) //Create a storage array to save the MFI KNN ML Data mfisKNN_data = array.new_float(plotAmount) //Populate ML data with the average between MFI at loop index, and MFI from KNN data at loop index for k = 0 to plotAmount - 1 mfisKNN_data.set(k, math.avg(mfiKNN[k], ta.mfi(useKInSource ? source[k] : source, k + kSmoothing))) //Calculate MFI Average scaled to fit on Heat Map mfiAvg = ta.vwma((mfisKNN_data.avg() / 100) * plotAmount, 2) //Calculate MFI SMA which can be used to visuallize cross' ma = ta.sma(mfiAvg, smaLength) //Calculate Crossing Signals bullCross = ta.crossover(mfiAvg, ma) bearCross = ta.crossunder(mfiAvg, ma) //calculate bar color barColor = getColor(mfisKNN_data.avg()) // ~~~~~~~~~~~~~~ PLOTS ~~~~~~~~~~~~~~ // //Heat Map plot(0, color=getColor(mfisKNN_data.get(0)), title="MFI Plot 1", linewidth = lineWidth) plot(plotAmount > 1 ? 1 : na, color=getColor(mfisKNN_data.get(1)), title="MFI Plot 2", linewidth = lineWidth) plot(plotAmount > 2 ? 2 : na, color=getColor(mfisKNN_data.get(2)), title="MFI Plot 3", linewidth = lineWidth) plot(plotAmount > 3 ? 3 : na, color=getColor(mfisKNN_data.get(3)), title="MFI Plot 4", linewidth = lineWidth) plot(plotAmount > 4 ? 4 : na, color=getColor(mfisKNN_data.get(4)), title="MFI Plot 5", linewidth = lineWidth) plot(plotAmount > 5 ? 5 : na, color=getColor(mfisKNN_data.get(5)), title="MFI Plot 6", linewidth = lineWidth) plot(plotAmount > 6 ? 6 : na, color=getColor(mfisKNN_data.get(6)), title="MFI Plot 7", linewidth = lineWidth) plot(plotAmount > 7 ? 7 : na, color=getColor(mfisKNN_data.get(7)), title="MFI Plot 8", linewidth = lineWidth) plot(plotAmount > 8 ? 8 : na, color=getColor(mfisKNN_data.get(8)), title="MFI Plot 9", linewidth = lineWidth) plot(plotAmount > 9 ? 9 : na, color=getColor(mfisKNN_data.get(9)), title="MFI Plot 10", linewidth = lineWidth) plot(plotAmount > 10 ? 10 : na, color=getColor(mfisKNN_data.get(10)), title="MFI Plot 11", linewidth = lineWidth) plot(plotAmount > 11 ? 11 : na, color=getColor(mfisKNN_data.get(11)), title="MFI Plot 12", linewidth = lineWidth) plot(plotAmount > 12 ? 12 : na, color=getColor(mfisKNN_data.get(12)), title="MFI Plot 13", linewidth = lineWidth) plot(plotAmount > 13 ? 13 : na, color=getColor(mfisKNN_data.get(13)), title="MFI Plot 14", linewidth = lineWidth) plot(plotAmount > 14 ? 14 : na, color=getColor(mfisKNN_data.get(14)), title="MFI Plot 15", linewidth = lineWidth) plot(plotAmount > 15 ? 15 : na, color=getColor(mfisKNN_data.get(15)), title="MFI Plot 16", linewidth = lineWidth) plot(plotAmount > 16 ? 16 : na, color=getColor(mfisKNN_data.get(16)), title="MFI Plot 17", linewidth = lineWidth) plot(plotAmount > 17 ? 17 : na, color=getColor(mfisKNN_data.get(17)), title="MFI Plot 18", linewidth = lineWidth) plot(plotAmount > 18 ? 18 : na, color=getColor(mfisKNN_data.get(18)), title="MFI Plot 19", linewidth = lineWidth) plot(plotAmount > 19 ? 19 : na, color=getColor(mfisKNN_data.get(19)), title="MFI Plot 20", linewidth = lineWidth) plot(plotAmount > 20 ? 20 : na, color=getColor(mfisKNN_data.get(20)), title="MFI Plot 21", linewidth = lineWidth) plot(plotAmount > 21 ? 21 : na, color=getColor(mfisKNN_data.get(21)), title="MFI Plot 22", linewidth = lineWidth) plot(plotAmount > 22 ? 22 : na, color=getColor(mfisKNN_data.get(22)), title="MFI Plot 23", linewidth = lineWidth) plot(plotAmount > 23 ? 23 : na, color=getColor(mfisKNN_data.get(23)), title="MFI Plot 24", linewidth = lineWidth) plot(plotAmount > 24 ? 24 : na, color=getColor(mfisKNN_data.get(24)), title="MFI Plot 25", linewidth = lineWidth) plot(plotAmount > 25 ? 25 : na, color=getColor(mfisKNN_data.get(25)), title="MFI Plot 26", linewidth = lineWidth) plot(plotAmount > 26 ? 26 : na, color=getColor(mfisKNN_data.get(26)), title="MFI Plot 27", linewidth = lineWidth) plot(plotAmount > 27 ? 27 : na, color=getColor(mfisKNN_data.get(27)), title="MFI Plot 28", linewidth = lineWidth) //AVG and SMA Lines plot(mfiAvg, color=color.white, title="MFI Average", linewidth=lineWidth) plot(ma, color=color.orange, title="MFI Smoothed", linewidth=lineWidth) //OB / Neutral / OS Zones hline((70. / 100.) * plotAmount, "Upper Band", color=color.new(color.white, 30)) hline(plotAmount / 2., "Middle Band", color=color.new(color.white, 30)) hline((30. / 100.) * plotAmount, "Lower Band", color=color.new(color.white, 30)) //Bull and Bear Signals plot(showSignals and bullCross ? mfiAvg : na, color=color.green, linewidth=3, style=plot.style_circles, title="MFI Bull Cross") plot(showSignals and bearCross ? mfiAvg : na, color=color.red, linewidth=3, style=plot.style_circles, title="MFI Bear Cross") //Change bar color barcolor(changeBarColor ? barColor : na) // ~~~~~~~~~~~~~~ ALERTS ~~~~~~~~~~~~~~ // alertcondition(bullCross, title="MFI Bull Cross", message="MFI Bull Cross") alertcondition(bearCross, title="MFI Bear Cross", message="MFI Bear Cross") // ~~~~~~~~~~~~~~ END ~~~~~~~~~~~~~~ //
TTP Pair Slope/Hedge
https://www.tradingview.com/script/4kIbHu2o-TTP-Pair-Slope-Hedge/
TheTradingParrot
https://www.tradingview.com/u/TheTradingParrot/
20
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/ // © TheTradingParrot //@version=5 indicator("TTP Pair Slope/Hedge") xx = input.symbol("BINANCE:BTCUSDT.P", "X", group = "pair") yy = input.symbol("BINANCE:BTCUSDT.P", "Y", group = "pair") x = request.security(xx,timeframe.period,close) y = request.security(yy,timeframe.period,close) candlefrom = input.int(1000, "from", group = "candle limits") candleto = input.int(0, "to", group = "candle limits") length = candlefrom - candleto // mean( (x-mean(x))^2 ) // —————————————————— // mean( (x-mean(x)) * (y-mean(y)) ) meanx = ta.sma(x[candleto], length) meany = ta.sma(y[candleto], length) diffx = x[candleto] - meanx diffy = y[candleto] - meany top = ta.sma(math.pow(diffx, 2), length) bottom = ta.sma(diffx * diffy, length) result = top / bottom plot(result, "slope", color = color.white)
NRAA_CRUDE Trading Indicator
https://www.tradingview.com/script/qE35O3dz-NRAA-CRUDE-Trading-Indicator/
neerajupadhyaya
https://www.tradingview.com/u/neerajupadhyaya/
4
study
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/ // © neerajupadhyaya //@version=5 indicator(title='NRAA_CRUDE', shorttitle=' NRAA_Crude ', overlay=true) t1 = time(timeframe.period,"1800-1815") bgcolor(t1?color.rgb(49, 27, 146, 86):na) inputema1 = input.int(5,"ema1") inputema2 = input.int(10,"ema2") ema1 = ta.ema(close,inputema1) ema2 = ta.ema(close,inputema2) plot1 = plot(ema1,color=color.rgb(214, 99, 22),linewidth=1) plot2 = plot(ema2,color=color.rgb(37, 6, 100),linewidth=1) UTCTimeInput = input('1800-1815', title="Get Open Value at Time?") OpenValueTime = time("1", UTCTimeInput) var OpenPA = 0.0 if OpenValueTime if not OpenValueTime[1] OpenPA := high plot(not OpenValueTime ? OpenPA : na, title="Open at time", color=color.rgb(10, 121, 20), linewidth=2, style=plot.style_linebr) UTCTimeInput1 = input('1815-1800', title="Get close Value at Time?") OpenValueTime1 = time("1", UTCTimeInput) var OpenPA1 = 0.0 if OpenValueTime1 if not OpenValueTime1[1] OpenPA1 := low plot(not OpenValueTime1 ? OpenPA1 : na, title="close at time", color=color.rgb(158, 7, 7, 10), linewidth=2, style=plot.style_linebr)
Ichimoku - Kepler
https://www.tradingview.com/script/hF0saZIb/
Kepler00008
https://www.tradingview.com/u/Kepler00008/
6
study
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/ // © pune3tghai //@version=4 study(title="一目云 - 艾克Kepler",overlay=true, resolution="") conversionPeriods = input(9, minval=1, title="Conversion Line Periods"), basePeriods = input(26, minval=1, title="Base Line Periods") laggingSpan2Periods = input(52, minval=1, title="Lagging Span 2 Periods"), displacement = input(26, minval=1, title="Displacement") donchian(len) => avg(lowest(len), highest(len)) conversionLine = donchian(conversionPeriods) baseLine = donchian(basePeriods) spanA = avg(conversionLine, baseLine) spanB = donchian(laggingSpan2Periods) plot(conversionLine, color=#0496ff, title="Conversion Line") plot(baseLine, color=#000000, title="Base Line") p1 = plot(spanA, offset = displacement - 1, color=color.green, title="Span A") p2 = plot(spanB, offset = displacement - 1, color=color.red, title="Span B") fill(p1, p2, color = spanA > spanB ? color.green : color.red) plot(spanA[25], color=color.orange) plot(spanB[25], color=color.yellow) priceincloud = (close>spanA[25] and close<spanB[25]) or (close<spanA[25] and close>spanB[25]) //TRADING RULES //Conversion Line and Baseline crossover with Laggin Span Filter ConvBaseBuy = crossover(conversionLine, baseLine) ConvBaseSell = crossunder(conversionLine, baseLine) //Laggin Span Filter // cblagBuy = ConvBaseBuy==true and (close > high[25]) // cblagSell = ConvBaseSell == true and (close < low[25]) //test plot for cb filter // plotshape(series=cblagBuy, text = "LS Buy", title="Lagging Span Buy", location=location.belowbar, style=shape.triangleup, color=color.lime, size=size.small) // plotshape(series=cblagSell, text="LS Sell", title="Laggin Span Sell", location=location.abovebar, style=shape.triangledown, color=color.red, size=size.small) //Conversion Line and Baseline crossover with Kumo Cloud Filter //Kumo Cloud Rule idealbuy = (close>high[25]) and conversionLine>baseLine and (close>spanA[25] and close>spanB[25]) and (low>spanA[25] and low>spanB[25]) idealsell = (close<low[25]) and conversionLine<baseLine and (close<spanB[25] and close<spanB[25]) and (high<spanA[25] and high<spanB[25]) buymem = false sellmem = false buymem := idealbuy?true:idealsell?false:buymem[1] sellmem := idealsell?true:idealbuy?false:sellmem[1] longCond = idealbuy and not(buymem[1]) shortCond = idealsell and not(sellmem[1]) plotshape(series=longCond, text = "1 买", title="1 买", location=location.belowbar, style=shape.triangleup, color=color.lime, size=size.small) plotshape(series=shortCond, text="1 卖", title="1 卖", location=location.abovebar, style=shape.triangledown, color=color.red, size=size.small) //Cloud Rule buycloud = crossover(spanA, spanB) and (low>spanA[25] and low>spanB[25]) sellcloud = crossunder(spanA, spanB) and (high<spanA[25] and high<spanB[25]) plotshape(series=buycloud, text = "2 买", title="2 买", location=location.belowbar, style=shape.triangleup, color=color.lime, size=size.small) plotshape(series=sellcloud, text="2 卖", title="2 卖", location=location.abovebar, style=shape.triangledown, color=color.red, size=size.small) alertcondition(longCond, title="1 买", message="买 it like a snail") alertcondition(shortCond, title="1 卖", message="卖 it like a snail") alertcondition(buycloud, title="2 买", message="I'm Goku") alertcondition(sellcloud, title="2 卖", message="Bulma took a ride and is now Falling")
RSI + Fibonacci HH LL Support Resistance
https://www.tradingview.com/script/GrrLdAPF/
hayashipallu
https://www.tradingview.com/u/hayashipallu/
35
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/ // © hayashipallu //@version=5 indicator("RSI + Fibonacci HH LL Support Resistance ",shorttitle = "RSI+FIB HH,LL,SR", overlay = true) //Fibonacci Number is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 620, 987, 1597, ... //FIbonacci Ratio is 0.236, 0.382, 0.5, 0.618, 1, 1.618, 2.618, 4.236, ... src1 = high src2 = low length = input(55) ama1 = 0. ama2 = 0. hh = math.max(math.sign(ta.change(ta.highest(length))), 0) ll = math.max(math.sign(ta.change(ta.lowest(length)) * -1), 0) tc = math.pow(ta.sma(hh or ll ? 1 : 0, length), 2) ama1 := nz(ama1[1] + tc * (high - ama1[1]), high) ama2 := nz(ama2[1] + tc * (low - ama2[1]), low) //Midline mah = ama1 mal = ama2 m = (mah + mal)/2 //Half Mean Range dist = (mah - mal)/2 //Levels h6 = m + dist * 11.089 h5 = m + dist * 6.857 h4 = m + dist * 4.235 h3 = m + dist * 2.618 h2 = m + dist * 1.618 h1 = m + dist * 0.618 l1 = m - dist * 0.618 l2 = m - dist * 1.618 l3 = m - dist * 2.618 l4 = m - dist * 4.235 l5 = m - dist * 6.857 l6 = m - dist * 11.089 plot(m, linewidth = 3, color = m > m[5] ? color.lime : color.red) ph6 = plot(h6, color = color.new(color.lime,40)) ph5 = plot(h5, color = color.new(color.lime,50)) ph4 = plot(h4, color = color.new(color.lime,60)) ph3 = plot(h3, color = color.new(color.lime,70)) ph2 = plot(h2, color = color.new(color.lime,80)) ph1 = plot(h1, color = color.new(color.lime,90)) pl6 = plot(l6, color = color.new(color.red,90)) pl5 = plot(l5, color = color.new(color.red,80)) pl4 = plot(l4, color = color.new(color.red,70)) pl3 = plot(l3, color = color.new(color.red,60)) pl2 = plot(l2, color = color.new(color.red,50)) pl1 = plot(l1, color = color.new(color.red,40)) fill(ph6, ph5, color = color.new(color.lime, 87), editable = true) fill(pl6, pl5, color = color.new(color.red, 87), editable = true) fill(ph5, ph4, color = color.new(color.lime, 90), editable = true) fill(pl5, pl4, color = color.new(color.red, 90), editable = true) fill(ph4, ph3, color = color.new(color.lime, 93), editable = true) fill(pl4, pl3, color = color.new(color.red, 93), editable = true) fill(ph3, ph2, color = color.new(color.lime, 96), editable = true) fill(pl3, pl2, color = color.new(color.red, 96), editable = true) fill(ph2, ph1, color = color.new(color.lime, 99), editable = true) fill(pl2, pl1, color = color.new(color.red, 99), editable = true) lookback_bars = input(defval = 144) lookback_bars2 = input(defval = 144) ema_len1 = input(defval = 2) ema_len2 = input(defval = 2) slide = input(defval = 13) highest_ema = ta.ema(ta.highest(high, lookback_bars), ema_len1) highest_ema2 = ta.ema(ta.highest(high, lookback_bars2), ema_len2)[slide] lowest_ema = ta.ema(ta.lowest(low, lookback_bars), ema_len1) lowest_ema2 = ta.ema(ta.lowest(low, lookback_bars2), ema_len2)[slide] len = input(defval = 5) ema = ta.ema(close, len) rsi_len = input(defval = 13) rsi = ta.rsi(ema, rsi_len) ob = input(70) os = input(40) p1 = plot(highest_ema,title = "Highest High", color =color.new(color.red, 80), linewidth = 2) p2 = plot(highest_ema2,title = "Delay Highest High", color =color.new(color.red, 80), linewidth = 2) p3 = plot(lowest_ema, title = "Lowest Low", color =color.new(color.lime , 80), linewidth = 2) p4 = plot(lowest_ema2, title = "Delay Lowest Low", color =color.new(color.lime, 80), linewidth = 2) hh_color = highest_ema[1] < highest_ema2 ? color.red:color.red ll_color = lowest_ema[1] > lowest_ema2 ? color.lime : color.lime fill(p1, p2, color = color.new(hh_color, 80), editable = true) fill(p3, p4, color = color.new(ll_color, 80), editable = true) cc = rsi > ob and close > h3 ? color.new(color.red,60) : rsi > ob and close > h4 ? color.new(color.red,40) : rsi > ob and close > h5 ? color.new(color.red,20) : rsi > ob and close > h6 ? color.new(color.red,0) : rsi < os and close < h3 ? color.new(color.lime,60) : rsi < os and close < l4 ? color.new(color.lime,40) : rsi < os and close < l5 ? color.new(color.lime,20) : rsi < os and close < l6 ? color.new(color.lime,0) : color.gray barcolor(color = cc, title = "RSI Bar Over Bought/Sold Color") crsi = rsi > ob and close < h6 ? color.red : rsi < os and close < h6 ? color.lime : color.new(color.gray,90) plotshape(rsi, color = crsi, style = shape.square, size = size.tiny, location = location.bottom)
SMA Crossover System
https://www.tradingview.com/script/YnKIFd5Y-SMA-Crossover-System/
Michael71825
https://www.tradingview.com/u/Michael71825/
4
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/ // © Michael71825 //@version=5 indicator("SMA Crossover System", shorttitle="SMA Crossover System", overlay=true) smaShortPeriod = input(13, title="Short SMA Period") smaMiddlePeriod = input(48, title="Middle SMA Period") smaLongPeriod = input(200, title="Long SMA Period") smaShort = ta.sma(close, smaShortPeriod) smaMiddle = ta.sma(close, smaMiddlePeriod) smaLong = ta.sma(close, smaLongPeriod) plot(smaShort, color=color.green, linewidth=1) plot(smaMiddle, color=color.blue, linewidth=1) plot(smaLong, color=color.red, linewidth=1) buyCondition = ta.crossover(smaShort, smaMiddle) and smaShort > smaLong and smaMiddle > smaLong sellCondition = ta.crossunder(smaShort, smaMiddle) and smaShort < smaLong and smaMiddle < smaLong if (buyCondition) label.new(bar_index, low, text="Buy", color=color.green, style=label.style_label_up, yloc=yloc.belowbar) if (sellCondition) label.new(bar_index, high, text="Sell", color=color.red, style=label.style_label_down, yloc=yloc.abovebar)
Support and Resistance: Triangles [YinYangAlgorithms]
https://www.tradingview.com/script/RkeTwjoq-Support-and-Resistance-Triangles-YinYangAlgorithms/
YinYangAlgorithms
https://www.tradingview.com/u/YinYangAlgorithms/
75
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("Support and Resistance: Triangles [YinYangAlgorithms]", overlay=true) // ~~~~~~~~ INPUTS ~~~~~~~~ // showTriangles = input.bool(true, "Show Triangles", tooltip="Should we plot triangles on the screen?") createZonesFor = input.string("Both", "Triangle Zones", options=["Upwards", "Downwards", "Both", "Neither"], tooltip="What types of triangles should we create our zones for?") dev = input.float(0.0001, "Max Deviation Allowed", tooltip="Maximum Deviation up or down from the last bars High/Low for potential to create a Triangle") lookBack = input.int(50, "Lookback Distance", tooltip="How far back we look to see for potential of a High/Low within Deviation range") minDistance = input.int(10, "Min Distance", tooltip="This is so triangles are spaced properly and not from 2 bars beside each other. Min distance allocated between 2 points to create a Triangle") eachBarPercentIncrease = input.float(0.005, "Bar Percent Increase", tooltip="How much % multiplier do we apply for each bar spacing of the triangle. 0.005 creates a close to Equilateral Triangle, but other values like 0.004 and 0.006 seem to work well too.") // ~~~~~~~~ VARIABLES ~~~~~~~~ // createUpwardsTriangle = createZonesFor == "Both" or createZonesFor == "Upwards" createDownwardsTriangle = createZonesFor == "Both" or createZonesFor == "Downwards" float lt = 0. float lb = 0. float ht = 0. float hb = 0. // ~~~~~~~~ FUNCTIONS ~~~~~~~~ // //Create the triangles and send back its Support and Resistance locations createTriangle(_up, _src, _color) => //Calculate the maximum upwards and downwards deviation allowed based on source srcDown = _src[1] - (_src[1] * dev) srcUp = _src[1] + (_src[1] * dev) //see if any of the same source between minDistance and lookBack are within the deviation allowment triangleDev = 0. triangleIndex = 0 for i = minDistance to lookBack cur = _src[i] if cur >= srcDown and cur <= srcUp triangleDev := cur triangleIndex := i break //calculate the support and resistance locations based on this triangle triangleTop = -1. triangleBot = -1. //did we find a valid triangle? if triangleDev != 0 //the middle of the triangle (bar index location) midDist = triangleIndex / 2 //how much of a % change is there (we generally want to create an Equilateral Triangle) percentIncrease = triangleIndex * eachBarPercentIncrease //modify the mid point based on if its an upward or downward triangle midPoint = _up ? triangleDev * (1 + percentIncrease) : triangleDev * (1 - percentIncrease) //create the triangle if showTriangles and ((_up and createUpwardsTriangle) or (not _up and createDownwardsTriangle)) line.new(bar_index - triangleIndex, triangleDev, bar_index[1], _src[1], color=_color, width=1) line.new(bar_index - triangleIndex, triangleDev, bar_index - midDist, midPoint, color=_color, width=1) line.new(bar_index - midDist, midPoint, bar_index[1], _src[1], color=_color, width=1) //save the support and resistance locations triangleTop := midPoint triangleBot := triangleDev //return the support and resistance locations (if there were any) [triangleTop, triangleBot] // ~~~~~~~~ CALCULATIONS ~~~~~~~~ // [lowTop, lowBot] = createTriangle(true, low, color.green) [highTop, highBot] = createTriangle(false, high, color.red) lt := lowTop != -1 ? lowTop : lt[1] lb := lowBot != -1 ? lowBot : lb[1] ht := highTop != -1 ? highTop : ht[1] hb := highBot != -1 ? highBot : hb[1] // ~~~~~~~~ PLOTS ~~~~~~~~ // plot(createUpwardsTriangle ? lt : na, color=color.red, style=plot.style_circles) plot(createUpwardsTriangle ? lb : na, color=color.orange, style=plot.style_circles) plot(createDownwardsTriangle ? ht : na, color=color.green, style=plot.style_circles) plot(createDownwardsTriangle ? hb : na, color=color.blue, style=plot.style_circles) // ~~~~~~~~ END ~~~~~~~~ //
Three Candle Rolling Pivot Range
https://www.tradingview.com/script/XHukXhvD-Three-Candle-Rolling-Pivot-Range/
Sabarijegan
https://www.tradingview.com/u/Sabarijegan/
9
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/ // © Sabarijegan //@version=5 indicator("Three Candle Rolling Pivot Range", overlay=true) // Calculate rolling pivot range for the last three candles c = input(3, title="Number of Previous Candles") rolling_pivot = (high[c] + low[c] + close[c]) / 3 second_number = (high[c] + low[c]) / 2 pivot_differential = rolling_pivot - second_number range_high = rolling_pivot + pivot_differential range_low = rolling_pivot - pivot_differential // Plot pivot range plot(range_high, color=color.green, linewidth=2, title="Rolling Pivot Range High") plot(rolling_pivot, color=color.blue, linewidth=2, title="Rolling Pivot") plot(range_low, color=color.red, linewidth=2, title="Rolling Pivot Range Low") // Entry conditions long_entry = close > range_high and close[1] > range_high[1] short_entry = close < range_low and close[1] < range_low[1] // Plot entry signals plotshape(series=long_entry, color=color.green, style=shape.triangleup, location=location.belowbar, size=size.small, title="Long Entry") plotshape(series=short_entry, color=color.red, style=shape.triangledown, location=location.abovebar, size=size.small, title="Short Entry")
exponential movil average with points
https://www.tradingview.com/script/bHFub6XR/
Volta_Trade
https://www.tradingview.com/u/Volta_Trade/
3
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/ // © Adan1560 //@version=5 indicator('exponential movil average with points ', overlay=true) // Definir inputs para las EMAs ema1_length = input(title='EMA1 Periodos', defval=20) ema2_length = input(title='EMA2 Periodos', defval=50) // Definir medias móviles exponenciales ema1 = ta.ema(close, ema1_length) ema2 = ta.ema(close, ema2_length) // Dibujar medias móviles plot(ema1, color=color.new(color.orange, 0), title='EMA1') plot(ema2, color=color.new(color.blue, 0), title='EMA2') // Comprobar si la EMA1 es mayor que la EMA2 signal = ema1 > ema2 // Comprobar si la EMA1 ha disminuido en el último periodo ema1_decreasing = ema1 < ema1[1] // Dibujar señales plotshape(signal and not ema1_decreasing, color=color.new(color.green, 0), location=location.belowbar, style=shape.triangleup, title='Señal de Compra') plotshape(not signal and ema1_decreasing, color=color.new(color.red, 0), location=location.abovebar, style=shape.triangledown, title='Señal de Venta')
W. Wilder ATR VI
https://www.tradingview.com/script/9u1aWkAH-W-Wilder-ATR-VI/
JakeTheDane
https://www.tradingview.com/u/JakeTheDane/
4
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/ // © JakeTheDane //@version=5 indicator(title="W. Wilder ATR VI", shorttitle="ATR VI", overlay=false) // Initialize ATR atrLength = input(7, "ATR Length") var float atr = na var float trSum = na // Initialize VI var float vi = na // True Range Calculation var float trueRange = na diff1 = high - low diff2 = close[1] - high diff3 = close[1] - low if (diff1 >= diff2 and diff1 >= diff3) trueRange := diff1 else if (diff2 >= diff1 and diff2 >= diff3) trueRange := diff2 else trueRange := diff3 // ATR Calculation if (bar_index < atrLength) trSum := na(trSum) ? trueRange : trSum + trueRange atr := trSum / atrLength else atr := ((atr * (atrLength - 1)) + trueRange) / atrLength // VI Calculation vi := na(vi) ? atr : (13 * vi + trueRange) / 14 // Plot the ATR and VI plot(atr, title="ATR", color=color.blue) plot(vi, title="VI", color=color.red)
Highlight Day of Week
https://www.tradingview.com/script/frXRX3Ql-Highlight-Day-of-Week/
SyedMehdi
https://www.tradingview.com/u/SyedMehdi/
7
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/ // A simple indicator that highlights certain days of the week by changing the background color of the chart to a specified color. // Each day can be highlighted its own respective color. // © SyedMehdi //@version=5 indicator('Highlight Day of Week', overlay=true) highlightMon = input.bool(true, 'Monday', inline='Monday') colorMon = input.color(color.new(color.yellow, 50), '', inline='Monday') highlightTues = input.bool(true, 'Tuesday', inline='Tuesday') colorTues = input.color(color.new(color.yellow, 60), '', inline='Tuesday') highlightWed = input.bool(true, 'Wednesday', inline='Wednesday') colorWed = input.color(color.new(color.yellow, 70), '', inline='Wednesday') highlightThurs = input.bool(true, 'Thursday', inline='Thursday') colorThurs = input.color(color.new(color.yellow, 80), '', inline='Thursday') highlightFri = input.bool(true, 'Friday', inline='Friday') colorFri = input.color(color.new(color.yellow, 90), '', inline='Friday') var bool timeIsWM = timeframe.isweekly or timeframe.ismonthly bgColor = if not timeIsWM dayofweek == dayofweek.monday and highlightMon ? colorMon : dayofweek == dayofweek.tuesday and highlightTues ? colorTues : dayofweek == dayofweek.wednesday and highlightWed ? colorWed : dayofweek == dayofweek.thursday and highlightThurs ? colorThurs : dayofweek == dayofweek.friday and highlightFri ? colorFri : na else na bgcolor(color=bgColor)
Gap SMA
https://www.tradingview.com/script/gsl0TToT-Gap-SMA/
str0zzapreti
https://www.tradingview.com/u/str0zzapreti/
3
study
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/ // © jdavenport416 //@version=5 indicator("Gap SMA", overlay=true) n = input(5, title="Number of gaps to consider") multiplier = input.float(1.5, title="Multiplier for Gap", step=0.1) var float avg_gap_up = na var float avg_gap_down = na gap_ups = open > close[1] ? (open - close[1]) * multiplier : na gap_downs = open < close[1] ? (close[1] - open) * multiplier : na avg_gap_up := ta.sma(na(gap_ups) ? avg_gap_up[1] : gap_ups, n) avg_gap_down := ta.sma(na(gap_downs) ? avg_gap_down[1] : gap_downs, n) if bar_index > n avg_gap_up := avg_gap_up avg_gap_down := avg_gap_down close_plus_gap_up_avg = close + avg_gap_up close_minus_gap_down_avg = close - avg_gap_down plot(close_plus_gap_up_avg, color=color.green, title="Close + Avg Gap Up") plot(close_minus_gap_down_avg, color=color.red, title="Close - Avg Gap Down") // Alert conditions alertcondition(close > close_plus_gap_up_avg, "Close Crosses Above Avg Gap Up", "Close crosses above the 'Close + Avg Gap Up' line") alertcondition(close < close_minus_gap_down_avg, "Close Crosses Below Avg Gap Down", "Close crosses below the 'Close - Avg Gap Down' line")
BOLLINGER Bands with MA_EMA/SMA_日本語
https://www.tradingview.com/script/NINjtU09/
FukuiFinance
https://www.tradingview.com/u/FukuiFinance/
3
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/ // © FukuiFinance //@version=5 indicator("BOLLINGER Bands with MA_EMA/SMA", overlay = true) //MAの種類 MethodMA = input.string(defval = "SMA", title = "MAの種類", options = ["EMA", "SMA"]) //EMA5 length_MA5 = input(title='短期MAの期間', defval=5) MA5 = MethodMA == "EMA"? ta.ema(close, length_MA5): ta.sma(close, length_MA5) PlotEMA5 = plot(MA5, title = "MA5", color = color.rgb(198, 68, 68), linewidth = 2) //EMA20 length_MA20 = input(title='中期MAの期間', defval=20) MA20 = MethodMA == "EMA"? ta.ema(close, length_MA20): ta.sma(close, length_MA20) PlotEMA20 = plot(MA20, title = "MA20", color = color.rgb(59, 122, 54), linewidth = 2) //EMA200 length_MA200 = input(title='長期MAの期間', defval=200) MA200 = MethodMA == "EMA"? ta.ema(close, length_MA200): ta.sma(close, length_MA200) PlotEMA200 = plot(MA200, title = "MA200", color = color.rgb(95, 31, 130), linewidth = 2) //BOLLINGER Bands lengthBB = input(20, title='BBの算出する期間') EMABB = MethodMA == "EMA"? ta.ema(close, lengthBB): ta.sma(close, lengthBB) dev = ta.stdev(close, lengthBB) line1 = plot(EMABB + dev, color=color.rgb(60, 60, 60, 100), linewidth=1) line2 = plot(EMABB + dev * 2, color=color.rgb(60, 60, 60, 100), linewidth=1) line3 = plot(EMABB - dev, color=color.rgb(60, 60, 60, 100), linewidth=1) line4 = plot(EMABB - dev * 2, color=color.rgb(60, 60, 60, 100), linewidth=1) //帯の背景色変更 fill(line1, line2, color=color.rgb(76, 149, 47, 70), title = "BBの背景_上") fill(line3, line4, color=color.rgb(76, 149, 47, 70), title = "BBの背景_下")
WP_MM
https://www.tradingview.com/script/w7p1pjBs/
Wpkenpachi
https://www.tradingview.com/u/Wpkenpachi/
3
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/ // © Wpkenpachi //@version=5 indicator("WP_MM", overlay = true) // INPUTS src = input.source(close, title="Source") tf = input.timeframe(title="Timeframe", defval = "2") ema50_out = ta.ema(close, 50) ema20_out = ta.ema(close, 20) ema9_out = ta.ema(close, 9) ema50 = request.security(syminfo.tickerid, tf, ema50_out, gaps=barmerge.gaps_on) ema20 = request.security(syminfo.tickerid, tf, ema20_out, gaps=barmerge.gaps_on) ema9 = request.security(syminfo.tickerid, tf, ema9_out, gaps=barmerge.gaps_on) show_strengh_bar = input.bool(defval = true, title = "Show Strengh Bar") // Verify candle type BULLISH | BEARISH is_bulish_candle() => open < close ? true : false // Strengh Candle verify if // A candle with body <= 400 ticks has <= 25 points in shadow size ( up shadow if bullish, down shadow if bearish ), or if > 400 if it has <= 50 points in shadow size // Or a candle with 100% of body size <= 400 having max of 5% in shadow size (the same rule for shadows above), or if > 400 if it having max of 10% in shadow is_strenght_candle() => _body = math.abs(close - open) _is_bullish = is_bulish_candle() _up_shadow = high // just a series default value _down_shadow = low // just serties default value if _is_bullish _up_shadow := high - close _down_shadow := open - low else _up_shadow := high - open _down_shadow := close - low _literal_min_shadow_size = (_body <= 400) ? 25 : 50 _literal_min_shadow_percent = (_body <= 400) ? 5 : 10 _up_shadow_percent = math.abs((_up_shadow * 100) / _body) _down_shadow_percent = math.abs((_down_shadow * 100) / _body) var is_strenght = false if _is_bullish is_strenght := _up_shadow_percent <= _literal_min_shadow_percent or _up_shadow <= _literal_min_shadow_size ? true : false else is_strenght := _down_shadow_percent <= _literal_min_shadow_percent or _down_shadow <= _literal_min_shadow_size ? true : false is_strenght // Check the up micro trend // it means: if EMA9 is above EMA20 and the space between them is up to 30 ticks is_up_micro_trend() => (ema9 > ema20) and (ema9 - ema20) >= 30 // Check the down micro trend // it means: if EMA9 is below EMA20 and the space between them is up to 30 ticks is_down_micro_trend() => (ema9 < ema20) and (ema20 - ema9) >= 30 // Check if the EMAS are directional it means the diffrence betwen current price ema and last price ema is up to 15 ticks (diff_to_be_directional) ema_is_directional() => lower_ema = ema9 higher_ema = ema20 diff_to_be_directional = 15 if is_up_micro_trend() (lower_ema > lower_ema[1]) and math.abs(lower_ema - lower_ema[1]) >= diff_to_be_directional and (higher_ema > higher_ema[1]) and math.abs(higher_ema - higher_ema[1]) >= diff_to_be_directional else if is_down_micro_trend() (lower_ema[1] > lower_ema) and math.abs(lower_ema[1] - lower_ema) >= diff_to_be_directional and (higher_ema[1] > higher_ema) and math.abs(higher_ema[1] - higher_ema) >= diff_to_be_directional // Check if it is a trigger candle // it means: // in a up trend the candle need to touch EMA20 with his low and close above EMA9 // in a down trend the candle need to touch EMA20 with his high and close below EMA9 // is_trigger_candle() => // if is_up_micro_trend() // true ? (low <= ema20) and (close > ema9) : false // else if is_down_micro_trend() // true ? (high >= ema20) and (close < ema9) : false // Color the candle if its a trigger candle in the apropriated context barcolor(show_strengh_bar and is_strenght_candle() and is_up_micro_trend() and ema_is_directional() and is_bulish_candle() ? color.lime : na) barcolor(show_strengh_bar and is_strenght_candle() and is_down_micro_trend() and ema_is_directional() and not is_bulish_candle() ? color.maroon : na) // Painting the trend range plot_50 = plot(ema50, title = "EMA50", color = color.red) plot_20 = plot(ema20, title = "EMA20", color = color.yellow) plot_9 = plot(ema9, title = "EMA9", color = color.green) fill_color = is_up_micro_trend() and ema_is_directional() ? color.new(color.green, 10) : (is_down_micro_trend() ? color.new(color.maroon, 10) : na) fill(plot_20, plot_9, color = fill_color, title = "MicroTrend", fillgaps = true)
DCA Simulator
https://www.tradingview.com/script/Fzc9nqmn/
Julien-PH
https://www.tradingview.com/u/Julien-PH/
2
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/ // © Julien-PH //@version=5 indicator("DCA Simulator", shorttitle="DCA", overlay=true) // Input showMeanPrice = input(true, "Show average price ?", tooltip = "Show the average price from this date to now") sourceMeanPrice = input(close, "Source average price") colorMeanPrice = input(color.blue, "Color average price") showDCA = input(true, "Show average DCA price ?", tooltip = "Show the average DCA price from this date to now") sourceDCA = input(open, "DCA time") colorDCA = input(color.orange, "Color DCA") maxNbBars = input(4000, "Maximum number of bars for the duration of the DCA/average") previousBar = math.min(bar_index,maxNbBars) // PRICE AVERAGE // List of mean price sort buy starting date var ListMeanPrice = array.new<float>(0) // Previous price if bar_index > maxNbBars array.shift(ListMeanPrice) if ListMeanPrice.size() > 0 for i = 0 to (previousBar - 1) newValue = ((ListMeanPrice.get(i) * (previousBar + 1 - i)) + sourceMeanPrice) / (previousBar + 2 - i) array.set(ListMeanPrice, i, newValue) // Current Price array.push(ListMeanPrice, sourceMeanPrice) // DCA // List of DCA sort buy starting date var ListBagDCA = array.new<float>(0) var ListMeanDCA = array.new<float>(0) // Previous DCA if bar_index > maxNbBars array.shift(ListBagDCA) array.shift(ListMeanDCA) if ListBagDCA.size() > 0 for i = 0 to (previousBar - 1) newBag = ListBagDCA.get(i) + (sourceDCA[previousBar-i] / sourceDCA) array.set(ListBagDCA, i, newBag) // Update average price per bag newMeanPrice = (sourceDCA[previousBar - i] * (previousBar - i + 1)) / ListBagDCA.get(i) array.set(ListMeanDCA, i, newMeanPrice) // Current DCA array.push(ListBagDCA , 1) array.push(ListMeanDCA, sourceDCA) // Plot if barstate.islast var pMeanPrice = array.new<chart.point>() var pMeanDCA = array.new<chart.point>() for i = 0 to previousBar //No -1 becase of the push on series pMeanPrice.push(chart.point.from_index(bar_index-previousBar+i,ListMeanPrice.get(i) )) pMeanDCA.push( chart.point.from_index(bar_index-previousBar+i,ListMeanDCA.get(i) )) polyline.new(showMeanPrice ? pMeanPrice : na, curved = false, closed = false, line_color = colorMeanPrice ) polyline.new(showDCA ? pMeanDCA : na, curved = false, closed = false, line_color = colorDCA )
Cumulative NHNL (markets, sectors, lookbacks)
https://www.tradingview.com/script/OUz6Gw44-Cumulative-NHNL-markets-sectors-lookbacks/
StevenM85
https://www.tradingview.com/u/StevenM85/
2
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/ // © StevenM85 //@version=5 indicator("Cumulative NHNL") //@version=5 var gref = 'Cum NHNL' sector_full = input.string(defval='NDXcomp', title='', options=['NYSE','SPX', 'NDXcomp', 'NDX100','IWM','DJI','DJT','SP Growth','SP Value', 'XLK', 'XLF', 'XLV', 'XLE', 'XLB', 'XLC', 'XLY', 'XLP', 'XLRE', 'XLI', 'XLU'], inline='1', group=gref) timeframe_full = input.string(defval='1-month', title='NHNL', options=['5-day', '1-month', '3-month','6-month','12-month','YTD'], inline='1', group=gref) NHNLfirst=sector_full=='NDX100'?'N':sector_full=='DJI'?'N':sector_full=='DJT'?'N':sector_full=='SP Growth'?'N':sector_full=='SP Value'?'N':'M' NHNLsecond=timeframe_full=='5-day'?'5':timeframe_full=='1-month'?'1':timeframe_full=='3-month'?'3':timeframe_full=='6-month'?'6':timeframe_full=='12-month'?'A':'Y' NHNLfourth=sector_full=='NYSE'?'N':sector_full=='SPX'?'P':sector_full == 'NDXcomp'?'Q':sector_full=='NDX100'?'C':sector_full=='IWM'?'C':sector_full=='DJI'?'D':sector_full=='DJT'?'F':sector_full=='SP Growth'?'Z':sector_full=='SP Value'?'Y':sector_full=='XLK'?'K':sector_full=='XLF'?'F':sector_full=='XLV'?'S':sector_full=='XLE'?'T':sector_full=='XLB'?'B':sector_full=='XLC'?'W':sector_full=='XLY'?'Y':sector_full=='XLP'?'M':sector_full=='XLRE'?'R':sector_full=='XLI'?'I':'U' //ticker = input.string(title='Exchange', defval='NDX', options=['NDX', 'NYSE']) smaSshow=input(title='', defval=true, inline='1') smaS=input(title='', defval=9, inline='1') smaStype=input.string(title='', defval='EMA', options=['SMA','EMA'], inline='1') smaScolor=input.color(color.green, inline='1', title='') smaSwidth=input.int(defval=2, inline='1', title='') smaLshow=input(title='', defval=true, inline='2') smaL=input(title='', defval=50, inline='2') smaLtype=input.string(title='', defval='SMA', options=['SMA','EMA'], inline='2') smaLcolor=input.color(color.orange, inline='2',title='') smaLwidth=input.int(defval=2, inline='2',title='') highs=request.security(NHNLfirst+NHNLsecond+'H'+NHNLfourth, 'D', close) lows=request.security(NHNLfirst+NHNLsecond+'L'+NHNLfourth, 'D', close) //highs=request.security(ticker=='NDX'? "HIGQ":"HIGN", 'D', close) //lows=request.security(ticker=='NDX'? "LOWQ":"LOWN", 'D', close) diff=highs-lows cumdiff = ta.cum(diff) ma10=smaStype=='SMA'?ta.sma(cumdiff, smaS):ta.ema(cumdiff, smaS) ma50=smaLtype=='SMA'?ta.sma(cumdiff, smaL):ta.ema(cumdiff, smaL) plot(cumdiff, color=color.black) plot(ma10, color=color.new(smaScolor, transp=smaSshow==true?0:100), linewidth = smaSwidth) plot(ma50, color=color.new(smaLcolor, transp=smaLshow==true?0:100),linewidth = smaLwidth) // --- PLOT THE TABLE --- var table newHighLowTable = table.new(position.middle_left, 2, 1, border_width=1, border_color=color.rgb(209, 212, 219, 0)) i_plotTable = true //Function f_fillCell(_table, _column, _row, _value) => _c_color = color.rgb(54, 58, 69, 0) _transp = 0 _cellText = str.tostring(_value, '0') table.cell(_table, _column, _row, _cellText, bgcolor=color.rgb(209, 212, 219, 0), text_color=color.rgb(54, 58, 69, 0), text_size=size.normal) // Diplay if i_plotTable table.cell(newHighLowTable, 0, 0, text=timeframe_full + ' ' + sector_full, bgcolor=color.rgb(209, 212, 219, 0), text_color=color.rgb(54, 58, 69, 0), text_size=size.normal) table.cell(newHighLowTable, 1, 0, text='', bgcolor=color.white, text_color=color.rgb(54, 58, 69, 0), text_size=size.normal)
FIREFLY INTERVAL RELEASE
https://www.tradingview.com/script/JjpMiuzE/
fireflies_
https://www.tradingview.com/u/fireflies_/
3
study
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/ // © fireflies_ // @version=5 indicator("FIREFLY INTERVAL RELEASE", overlay=true) import TradingView/ta/5 // --------------------------------------------------- // MA // --------------------------------------------------- src = close ma1_inp = input.int(25, "ma1") ma2_inp = input.int(99, "ma2") ma1 = ta.sma(src, ma1_inp) ma2 = ta.sma(src, ma2_inp) plot(ma1, "ma1", color = color.rgb(242, 12, 177), linewidth = 1) plot(ma2, "ma2", color = color.rgb(24, 165, 246)) // --------------------------------------------------- // MACD macd_fast_inp = input.int(12, "MACD FAST") macd_slow_inp = input.int(26, "MACD SLOW") macd_signal_inp = input.int(title="MACD SIGNAL", minval = 1, maxval = 50, defval = 9) macd_source = input.string(title = "MACD SOURCE", defval = "EMA", options = ["SMA", "EMA"]) macd_signal_source = input.string(title = "MACD SIGNAL SOURCE", defval = "EMA", options = ["SMA", "EMA"]) // HISTOGRAM macd_fast = macd_source == "SMA" ? ta.sma(src, macd_fast_inp) : ta.ema(src, macd_fast_inp) macd_slow = macd_source == "SMA" ? ta.sma(src, macd_slow_inp) : ta.ema(src, macd_slow_inp) macd_signal = macd_signal_source == "SMA" ? ta.sma((macd_fast - macd_slow), macd_signal_inp) : ta.ema((macd_fast - macd_slow), macd_signal_inp) hist = macd_fast - macd_slow - macd_signal // ATR atr_inp = input.int(14, title="ATR LENGTH") atr_value = ta.atr(atr_inp) // BULL var line bull_key_high = na var line bull_key_low = na var label bull_point = na var bull_arr_line = array.new_line() // BEAR var line bear_key_high = na var line bear_key_low = na var label bear_point = na var bear_arr_line = array.new_line() // BULL STOP var float bull_stop = na var label bull_stop_key = na var bool stop_isTrue = false // BUY CONDITION var float bull_point_high = na var bool buy_isTrue = false var label buy_key = na if hist < 0 if hist[1] < hist if hist[2] > hist[1] label.delete(bull_point) line.delete(bull_key_high) line.delete(bull_key_low) bull_point := label.new(bar_index, low, text = "HIGH: " + str.tostring(high) + "\nLOW: " + str.tostring(low), style = label.style_label_up, color = color.rgb(39, 176, 85), yloc = yloc.belowbar, textcolor = color.white, size = size.normal) bull_key_high := line.new(bar_index[1], high, bar_index, high, width=1, color=color.rgb(76, 175, 79, 100), extend = extend.right, style = line.style_dashed) bull_key_low := line.new(bar_index[1], low, bar_index, low, width=1, color=color.rgb(76, 175, 79, 100), extend = extend.right, style = line.style_dashed) linefill.new(bull_key_high, bull_key_low, color = color.rgb(76, 175, 79, 80)) array.push(bull_arr_line, line.new(bar_index[1], high, bar_index, high, width=1, color=color.green, extend = extend.both)) bull_point_high := high buy_isTrue := true else if hist[1] > hist if hist[2] < hist[1] line.delete(bear_key_low) line.delete(bear_key_high) label.delete(bear_point) bear_point := label.new(bar_index, high, text = "HIGH: " + str.tostring(high) + "\nLOW: " + str.tostring(low), style = label.style_label_down, color = color.rgb(176, 39, 39), yloc = yloc.abovebar, textcolor = color.white, size = size.normal) bear_key_low := line.new(bar_index[1], low, bar_index, low, width=1, color=color.rgb(255, 82, 82, 100), extend = extend.right, style = line.style_dashed) bear_key_high := line.new(bar_index[1], high, bar_index, high, width=1, color=color.rgb(255, 82, 82, 100), extend = extend.right, style = line.style_dashed) linefill.new(bear_key_low, bear_key_high, color = color.rgb(255, 82, 82, 80)) array.push(bear_arr_line, line.new(bar_index[1], low, bar_index, low, width=1, color=color.red, extend = extend.both)) // RESISTANCE LINE bull_line_inp = input.int(1, "BOTTOM LINE") if array.size(bull_arr_line) > bull_line_inp bullal = array.shift(bull_arr_line) line.delete(bullal) bear_line_inp = input.int(1, "UPPER LINE") if array.size(bear_arr_line) > bear_line_inp bearal = array.shift(bear_arr_line) line.delete(bearal) // BUY SIGNAL // --------------------------------------------------- if buy_isTrue and close > bull_point_high bull_stop := math.round(low - atr_value, 4) label.delete(buy_key) buy_key := label.new(bar_index, high, text = "BUY\n STOP VALUE:" + str.tostring(bull_stop), style = label.style_label_lower_right, color = color.rgb(0, 179, 249, 10), textcolor = color.white) label.delete(bull_stop_key) buy_isTrue := false stop_isTrue := true if stop_isTrue and low < bull_stop bull_stop_key := label.new(bar_index, low, text = "STOP", style = label.style_label_lower_left, color = color.rgb(251, 164, 3, 20), textcolor = color.rgb(248, 246, 243)) stop_isTrue := false
TrendAlert
https://www.tradingview.com/script/ltIrEwln-TrendAlert/
qwertytehseen
https://www.tradingview.com/u/qwertytehseen/
2
study
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/ // © qwertytehseen //@version=5 // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © TradeWithTehseen_ //@version=5 indicator('TrendAlert', overlay=false) // Trend and direction determination Step 1 en Step 2 method conform ZoneRecovery from 4x-dat.com Joseph Nemeth // https://www.youtube.com/watch?v=YxDAYtlQjBM // step 1 LongTerm timefram/resolution (LT) determine general direction //• color last Heikenahsi bar gives is the general direction // step 2 MidTerm timeframe/resolution determine trend //• color last Heikenahsi bar must match Direction step 1 and //• slope of 20EMA in direction step 1 and //• price relation to EMA20: above = up, below=down // Step 1 AND step 2 => TrendAlert (-1 for Short, 1 for Long, 0 for No trend) //Heiken Ashi Candles data = ticker.heikinashi(syminfo.tickerid) resLT = input.timeframe(title='Res LT', defval='D') resMT = input.timeframe(title='Res MT', defval='240') LTo = request.security(data, resLT, open) LTc = request.security(data, resLT, close) MTo = request.security(data, resMT, open) MTc = request.security(data, resMT, close) LTlong = LTc > LTo LTshort = LTc < LTo MTema20 = ta.ema(MTc, 20) MTema20delta = ta.change(MTema20) MTlong = MTc > MTo and MTc > MTema20 and MTema20delta > 0 MTshort = MTc < MTo and MTc < MTema20 and MTema20delta < 0 Long = MTlong and LTlong Short = MTshort and LTshort plot(Long ? 1 : Short ? -1 : 0, title='TrendAlert', color=Long ? color.lime : Short ? color.red : color.gray, style=plot.style_columns)
Cumulative ADD
https://www.tradingview.com/script/6s4oOYfA-Cumulative-ADD/
StevenM85
https://www.tradingview.com/u/StevenM85/
2
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/ // © StevenM85 //@version=5 indicator("Cum ADD") ticker = input.string(title='Exchange', defval='NDXcomp', options=['NDXcomp', 'NYSE']) pltsma=input(defval=true, title='Show', inline='0') sma=input(title='Length', defval=9, inline='0') smatype=input.string(title='Type', defval='EMA', options=['SMA','EMA'], inline='0') pltlongsma=input(defval=true, title='Show', inline='1') smalong=input(title='Length', defval=50, inline='1') smalongtype=input.string(title='Type', defval='SMA', options=['SMA','EMA'], inline='1') add_diff=request.security(ticker=='NDXcomp'? "ADDQ":"ADD", 'D', close) cumdiff = ta.cum(add_diff) ma10=smatype=="SMA"?ta.sma(cumdiff, sma):ta.ema(cumdiff, sma) ma50=smalongtype=="SMA"?ta.sma(cumdiff, smalong):ta.ema(cumdiff, smalong) plot(cumdiff, color=color.black) plot(ma10, color=color.new(color.blue, transp=pltsma==true?0:100)) plot(ma50, color=color.new(color.orange, transp=pltlongsma==true?0:100)) // --- PLOT THE TABLE --- var table newHighLowTable = table.new(position.middle_left, 2, 1, border_width=1, border_color=color.rgb(209, 212, 219, 0)) i_plotTable = true //Function f_fillCell(_table, _column, _row, _value) => _c_color = color.rgb(54, 58, 69, 0) _transp = 0 _cellText = str.tostring(_value, '0') table.cell(_table, _column, _row, _cellText, bgcolor=color.rgb(209, 212, 219, 0), text_color=color.rgb(54, 58, 69, 0), text_size=size.normal) // Diplay if i_plotTable table.cell(newHighLowTable, 0, 0, text=ticker, bgcolor=color.rgb(209, 212, 219, 0), text_color=color.rgb(54, 58, 69, 0), text_size=size.normal) table.cell(newHighLowTable, 1, 0, text=' ', bgcolor=color.white, text_color=color.rgb(54, 58, 69, 0), text_size=size.normal)
ZWAP (ZigZag Anchored VWAP) [Kioseff Trading]
https://www.tradingview.com/script/NiL9i0qV-ZWAP-ZigZag-Anchored-VWAP-Kioseff-Trading/
KioseffTrading
https://www.tradingview.com/u/KioseffTrading/
131
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("ZWAP [Kioseff Trading]", overlay = true, max_polylines_count = 100, max_lines_count = 500, max_labels_count = 500) import TradingView/ZigZag/6 as ZigZagLib import kaigouthro/hsvColor/15 as kai import HeWhoMustNotBeNamed/arraymethods/1 use = input.bool (defval = false, title = "Use Visible Range") curvy = input.bool (defval = true, title = "Curvy Zig Zag") show = not use ? input.int (defval = 25, minval = 1, title = "Pivots To Show", maxval = 100) + 1 : 100 start = input.time (timestamp("20 Jul 2000 00:00 +0300"), "Start Time") colType = input.bool (defval = true, title = "Color As Support / Resistance") sCol = input.color (defval = #14D990, title = "VWAP Support Color", inline = "Col"), rCol = input.color (defval = #F24968, title = "VWAP Resistance Color", inline = "Col") transp = input.int (defval = 0, maxval = 100, title = "Color Transparency") curc = input.color (defval = #6929F2, title = "Curve ZZ Color") lineS = input.string(defval = "Solid", options = ["Solid", "Dotted", "Dashed"], title = "Line Style") styl = switch lineS "Solid" => line.style_solid "Dotted" => line.style_dotted "Dashed" => line.style_dashed 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(65, "Pivot legs", 2, group = "Zig Zag Settings"), input(#00000000, "Line color", group = "Zig Zag Settings"), input(true, "Extend to last bar", group = "Zig Zag Settings"), 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) ) zigZag.update(), change = ta.change(line.all.size()) var kv = matrix.new<float>(2, 0) var pivots = array.new <float>() var timeArr = array.new_int(), var curves = matrix.new<float>(2, 0) cond = switch use true => time <= chart.right_visible_bar_time and time >= chart.left_visible_bar_time => time >= start if cond if change and line.all.size() > 1 if line.all.get(line.all.size() - 2).get_x2() >= (use ? chart.left_visible_bar_time : start) pivots.push( line.all.get(line.all.size() - 2).get_x2()) kv.add_col(0, array.from( hlc3, volume )) timeArr.unshift(time) if barstate.islast pivots.push( line.all.last().get_x2()) if last_bar_index - bar_index <= 15000 if change and line.all.size() > 1 curves.add_col(curves.columns(), array.from( line.all.get(line.all.size() - 2).get_x2(), line.all.get(line.all.size() - 2).get_y2() )) if barstate.islast curves.add_col(curves.columns(), array.from( line.all.last().get_x2(), line.all.last().get_y2() )) curves.add_col(curves.columns(), array.from( last_bar_time, ohlc4 )) if barstate.islast if polyline.all.size() > 0 for i = 0 to polyline.all.size() - 1 polyline.all.shift().delete() if pivots.size() > show for i = 0 to pivots.size() - show pivots.shift() if pivots.size() > 0 for i = 0 to pivots.size() - 1 sumHLC3 = 0.0, sumVol = 0.0 points = array.new<chart.point>() for x = timeArr.indexof(int(pivots.get(i))) to 0 sumHLC3 += kv.get(0, x) * kv.get(1, x) sumVol += kv.get(1, x) points.push(chart.point.from_time(timeArr.get(x), sumHLC3 / sumVol)) col = switch sumHLC3 / sumVol >= close true => color.new(rCol, transp) => color.new(sCol, transp) polyline.new(points, curved = false, xloc = xloc.bar_time, line_color = col, line_width = 1, line_style = styl) points = array.new<chart.point>() for i = 0 to curves.columns() - 1 points.push(chart.point.from_time(int(curves.get(0, i)), curves.get(1, i))) polyline.new(points, curved = curvy , xloc = xloc.bar_time, line_color = curc)
Liquidity Spike Pool
https://www.tradingview.com/script/f63DTnLS-Liquidity-Spike-Pool/
AleSaira
https://www.tradingview.com/u/AleSaira/
124
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/ // © AleSaira //==============================/////////////==========================} // _____ .__ _________ .__ // / _ \ | | ____ / _____/____ |__|___________ /// /_\ \| | _/ __ \ \_____ \\__ \ | \_ __ \__ \ /// | \ |_\ ___/ / \/ __ \| || | \// __ \_ //\____|__ /____/\___ >_______ (____ /__||__| (____ / // \/ \/ \/ \/ \/ //==============================/////////////==========================} //@version=5 indicator("Liquidity Spike Pool", overlay=true) //==============================/////////////==========================} Pwick = input.int (55, minval=1, maxval=99, title="% The Wick Of Candle") look_back = input.int (6, minval=1, maxval=100, title="Look Back Period") rangelb = input.int (5, minval=1, maxval=99, title=" Percent of Range") colorlineup = input.color (color.blue, "Liquidity up") colorlineup1 = input.color (color.rgb(169, 9, 9), "Liquidity up big candle") colorlinedown = input.color (color.rgb(6, 6, 6), "Liquidity down") colorlinedown1 = input.color (color.rgb(255, 255, 255), "Liquidity down big candle") // Define the percentage for big candles bigCandleThreshold = input.int (70, minval=1, maxval=99, title="Big Candle Threshold Percentage") bigCandleThreshold1 = input.int (80, minval=1, maxval=99, title="Big Candle Threshold Percentage") bars01 = true //==============================/////////////==========================} // PBar Percentages tot01O = Pwick * 0.01 tot01OO = 1 - tot01O range1 = high - low //==============================/////////////==========================} // PinBars pBarUp() => open > high - (range1 * tot01OO) and close > high - (range1 * tot01OO) pBarDn() => open < high - (range1 * tot01O) and close < high - (range1 * tot01O) //==============================/////////////==========================} // Calculate the moving average of the range of previous candles avgRange = ta.sma(range1, look_back) //==============================/////////////==========================} // Create a condition to identify big candles isBigCandle = range1 > (avgRange * bigCandleThreshold / 100) isBigCandle1 = range1 > (avgRange * bigCandleThreshold1 / 100) //==============================/////////////==========================} // Find the price of the top wick of pBarUp only for big candles var float pBarUpWickTopPrice = na if (pBarUp() and isBigCandle) line.new(x1=bar_index, y1=low, x2=bar_index + 20, y2=low, color=colorlinedown, width=1) if (pBarUp() and isBigCandle1) line.new(x1=bar_index, y1=low, x2=bar_index + 20, y2=low, color=colorlinedown1, width=2) //==============================/////////////==========================} // Find the price of the bottom wick of pBarDn only for big candles var float pBarDnWickBottomPrice = na if (pBarDn() and isBigCandle) line.new(x1=bar_index, y1=high, x2=bar_index + 20, y2=high, color=colorlineup, width=1) if (pBarDn() and isBigCandle1) line.new(x1=bar_index, y1=high, x2=bar_index + 20, y2=high, color=colorlineup1, width=2) //==============================/////////////==========================} //==============================/////////////==========================}
Volatility Adjusted Composite RSI with SMA and EMA Signals
https://www.tradingview.com/script/HNPswA6x-Volatility-Adjusted-Composite-RSI-with-SMA-and-EMA-Signals/
Jagandeep
https://www.tradingview.com/u/Jagandeep/
39
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/ // © Jagandeep //@version=5 indicator("VAC - RSI with SMA and EMA Signals", overlay=false) // User inputs priceWeight = input.float(65, title="Price RSI Weightage (%)", minval=0, maxval=100) timeWeight = 100 - priceWeight RSI_T_RSI_Period = input.int(14, title="Unified Period for RSI & T-RSI", minval=1) smaPeriod = input.int(13, title="C-RSI SMA Period", minval=1) emaPeriod = input.int(33, title="C-RSI EMA Period", minval=1) bull_sup = input.int(35, title="C-RSI Bull Trend Support", minval=0, maxval=100) bear_res = input.int(65, title="C-RSI Bear Trend Resistance", minval=0, maxval=100) useStdDev = input.bool(true, title="Use Volatility Adjusted C-RSI (VAC-RSI)?") stdDevPeriod = input.int(14, title="Standard Deviation Period", minval=1) alpha = input.float(5, title="Volatility Scaling Factor (α)", minval=0.1) // RSI Calculation Delta = close - close[1] Gain = Delta > 0 ? Delta : 0 Loss = Delta < 0 ? -Delta : 0 AvgGain = ta.sma(Gain, RSI_T_RSI_Period) AvgLoss = ta.sma(Loss, RSI_T_RSI_Period) RS = AvgGain / AvgLoss TraditionalRSI = 100 - (100 / (1 + RS)) // Time-based RSI (T-RSI) using unified period TimeScore = math.sum(close > close[1] ? 1 : close < close[1] ? -1 : 0, RSI_T_RSI_Period) TRSI = (TimeScore + RSI_T_RSI_Period) * (100 / (2 * RSI_T_RSI_Period)) // Combine Traditional RSI and T-RSI C_RSI = (TraditionalRSI * priceWeight/100) + (TRSI * timeWeight/100) // Volatility Adjustment using Z-Score meanClose = ta.sma(close, stdDevPeriod) stdDevValue = ta.stdev(close, stdDevPeriod) zScore = (close - meanClose) / stdDevValue VAC_RSI = useStdDev ? C_RSI + alpha * zScore : C_RSI // SMA & EMA for VAC-RSI smaVAC_RSI = ta.sma(VAC_RSI, smaPeriod) emaVAC_RSI = ta.ema(VAC_RSI, emaPeriod) // Plotting prsi = plot(VAC_RSI, title='VAC-RSI', color=color.new(color.purple, 0), style=plot.style_line, linewidth=2) overbought = hline(80, title="Overbought", color=color.new(color.purple, 20), linestyle=hline.style_dashed, linewidth=1) oversold = hline(20, title="Oversold", color=color.new(color.purple, 20), linestyle=hline.style_dashed, linewidth=1) fill(overbought, oversold, color=color.new(color.purple, 80), title="VAC-RSI Fill") psma = plot(smaVAC_RSI, title='SMA', color=color.new(color.gray, 35), style=plot.style_line, linewidth=2) pema = plot(emaVAC_RSI, title="EMA", color=color.new(color.gray, 35), style=plot.style_line, linewidth=2) fillColor = emaVAC_RSI < smaVAC_RSI ? color.new(color.green, 65) : color.new(color.red, 65) fill(psma, pema, color=fillColor, title="EMA vs SMA Fill") fill(psma, prsi, color=color.new(color.gray, 80), title="VAC-RSI vs SMA Fill") hline(bull_sup, title="Bull Market VAC-RSI Support", color=color.new(color.green, 35), linestyle=hline.style_solid, linewidth=3) hline(bear_res, title="Bear Market VAC-RSI Resistance", color=color.new(color.red, 65), linestyle=hline.style_solid, linewidth=3)
Backtester Utility
https://www.tradingview.com/script/VWqQX7xK-Backtester-Utility/
Am_ContentCreator_
https://www.tradingview.com/u/Am_ContentCreator_/
3
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/ // © Am_ContentCreator_ //@version=5 //!!!!!!!!!!!!!!!Requires Editing for fulfilling your Requirements!!!!!!!!!!!!!!!// //!!!!!!!!!!!!!!!Requires Editing for fulfilling your Requirements!!!!!!!!!!!!!!!// //!!!!!!!!!!!!!!!Requires Editing for fulfilling your Requirements!!!!!!!!!!!!!!!// //!!!!!!!!!!!!!!!Hide you chart for using the indicator!!!!!!!!!!!!!!// //!!!!!!!!!!!!!!!Hide you chart for using the indicator!!!!!!!!!!!!!!// //!!!!!!!!!!!!!!!Hide you chart for using the indicator!!!!!!!!!!!!!!// //NAME=//Backtester Utility// //USAGE=//This program is useful for manual backtesting of your trading strategies. // //It is highly recommended to edit the program according to your requirements// //SPECIALITY=//Backetesting Feature requires the user to buy Paid Plans but instead we can use this Indicator //PROPERTIES=//This Indicator Hides the Price action and also the indicator plot after acertained time// //NOTE=//This program is not created for the intention of Direct usage, This is purely Educational Content. This is not any Investment Advise// indicator(title="Backtester Utility",shorttitle="BU",overlay=true) //Here I am using simple EMA crossver strategy// //INPUT//(Change or add Inputs according to your strategy) src = open len1 = input.int(40,title ="Short Length") len3 = input.int(65,title ="long Length") //CALCULATION//(Change or add Calculation according to your strategy) // Input variables for the date and time/////Do not change this///// hideAfterYear = input(2023, 'Hide After Year') hideAfterMonth = input(12, 'Hide After Month') hideAfterDay = input(5, 'Hide After Day') hideAfterHour = input(0, 'Hide After Hour') hideAfterMinute = input.int(0, 'Hide After Minute',step=5) // Convert user inputs to timestamp/////Do not change this///// hideFromTime = timestamp(hideAfterYear, hideAfterMonth, hideAfterDay, hideAfterHour, hideAfterMinute) //ema// //👇Change name ////////////////////👇also change this calculation according to your requirement// ema1 = time >= hideFromTime ? na : ta.ema(src,len1) ema3 = time >= hideFromTime ? na : ta.ema(src, len3) //Do not change any other syntax in above , it will result in error// crossBL13_ema = ta.crossover(ema1,ema3) crossBR13_ema = ta.crossunder(ema1,ema3) //PLOT//(Change or add plots according to your strategy) plotshape(ema1 ? crossBL13_ema : na , color=color.aqua, location=location.bottom , size=size.huge , style = shape.arrowup) plotshape(ema3 ? crossBR13_ema : na , color=color.yellow, location=location.top , size=size.huge , style = shape.arrowdown) // Convert user inputs to timestamp hideAfterDate = timestamp(hideAfterYear, hideAfterMonth, hideAfterDay, hideAfterHour, hideAfterMinute) // Determine if the current bar's timestamp is after the specified date and time isAfterHideDate = time > hideAfterDate // Plot the candles only if the bar's timestamp is before the specified date and time plotcandle(isAfterHideDate ? na : close, open, high, low, color=color.black)
Yield Spread Histogram
https://www.tradingview.com/script/WWjRKqoQ-Yield-Spread-Histogram/
AJMourot
https://www.tradingview.com/u/AJMourot/
3
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/ // © AJMourot //@version=5 indicator("Yield Spread Candles", shorttitle="Yield Spread", overlay=true) // Fetch data for "US10Y-US02Y" yieldSpread = request.security("US10Y-US02Y", "D", close) // Calculate color based on yield spread value candleColor = yieldSpread > 0 ? color.new(color.green, 0) : color.new(color.red, 0) // Plot colored candles plot(open, color=candleColor, style=plot.style_histogram, linewidth=0) plot(close, color=candleColor, style=plot.style_histogram, linewidth=1) // Plot yield spread histogram filling entire space plot(yieldSpread, color=candleColor, style=plot.style_histogram, linewidth=0) // Plot white line across zero plot(0, color=color.new(color.white, 0), linewidth=2, title="Zero Line")
HistDistDevsv2
https://www.tradingview.com/script/8SWdNLJf-HistDistDevsv2/
eexpeeriments
https://www.tradingview.com/u/eexpeeriments/
6
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/ // © ChrisakaChris //@version=5 indicator(title="HistDistDevsv2", overlay=true, max_lines_count = 500) //Inputs------------------------------------------------------------ ShowLines = input.bool(true, "Show Lines") LabelBool = input.bool(true, title="Show Labels") DevLineStyle = input.string("Dashed", title="Line Style", options=["Solid", "Dotted", "Dashed"]) PosDevs = input.color(color.rgb(48, 105, 30, 70), title="Positive Devs Color") NegDevs = input.color(color.rgb(141, 46, 46, 70), title="Negative Devs Color") OpenDev = input.color(color.rgb(180, 162, 57, 70), title="Open Line Color") LabelColor = input.color(color.rgb(0, 0, 0, 70), title="Labels Color") ShowHist = input.bool(false, title="Show Historical Sessions") ShowOpen = input.bool(true, title="Show Open") ShowP5 = input.bool(true, title="Show .5") Show1 = input.bool(true, title="Show 1") Show1P5 = input.bool(true, title="Show 1.5") Show2 = input.bool(false, title="Show 2") Show2P5 = input.bool(false, title="Show 2.5") Show3 = input.bool(false, title="Show 3") //Global Variables------------------------------------------------------------ var xPer = 0.0 var xBar = 0 var xOpen = 0.0 var xDay = 0 var NQper = 0.0 var ESper = 0.0 var YMper = 0.0 var RTYper = 0.0 var CLper = 0.0 var GCper = 0.0 string TFval = "" bool badTimeframe = false bool badTicker = false //Timeframe Switch------------------------------------------------------------ if timeframe.period == "D" or timeframe.isintraday TFval := "D" NQper := 0.0119 ESper := 0.0098 YMper := 0.0095 RTYper := 0.0135 CLper := 0.0234 GCper := 0.0080 else if timeframe.period == "W" TFval := "W" NQper := 0.0265 ESper := 0.0229 YMper := 0.0228 RTYper := 0.0305 CLper := 0.0525 GCper := 0.0202 else if timeframe.period == "M" TFval := "M" NQper := 0.0510 ESper := 0.0427 YMper := 0.0421 RTYper := 0.0570 CLper := 0.1183 GCper := 0.0459 else badTimeframe := true //Asset Selection Switch------------------------------------------------------------ if str.contains(syminfo.ticker, "NQ") xPer := NQper else if str.contains(syminfo.ticker, "ES") xPer := ESper else if str.contains(syminfo.ticker, "YM") xPer := YMper else if str.contains(syminfo.ticker, "RTY") xPer := RTYper else if str.contains(syminfo.ticker, "CL") xPer := CLper else if str.contains(syminfo.ticker, "GC") xPer := GCper else badTicker := true //Post Calculation Variables------------------------------------------------------------ [lineStart, lineEnd] = request.security(syminfo.tickerid, TFval, [time, time_close]) xOpen := request.security(syminfo.tickerid, TFval, open) var lineStyle = line.style_dashed if DevLineStyle == "Solid" lineStyle := line.style_solid else if DevLineStyle == "Dotted" lineStyle := line.style_dotted //Draw Once------------------------------------------------------------ if not ShowHist and (not badTimeframe and not badTicker) and ShowLines if Show3 var p3 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(p3, lineStart, xOpen + ((xOpen*xPer)*3)) line.set_xy2(p3, lineEnd, xOpen + ((xOpen*xPer)*3)) line.set_color(p3, color = PosDevs) if Show2P5 var p25 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(p25, lineStart, xOpen + ((xOpen*xPer)*2.5)) line.set_xy2(p25, lineEnd, xOpen + ((xOpen*xPer)*2.5)) line.set_color(p25, color = PosDevs) if Show2 var p2 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(p2, lineStart, xOpen + ((xOpen*xPer)*2)) line.set_xy2(p2, lineEnd, xOpen + ((xOpen*xPer)*2)) line.set_color(p2, color = PosDevs) if Show1P5 var p15 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(p15, lineStart, xOpen + ((xOpen*xPer)*1.5)) line.set_xy2(p15, lineEnd, xOpen + ((xOpen*xPer)*1.5)) line.set_color(p15, color = PosDevs) if Show1 var p1 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(p1, lineStart, xOpen + ((xOpen*xPer)*1)) line.set_xy2(p1, lineEnd, xOpen + ((xOpen*xPer)*1)) line.set_color(p1, color = PosDevs) if ShowP5 var p5 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(p5, lineStart, xOpen + ((xOpen*xPer)*0.5)) line.set_xy2(p5, lineEnd, xOpen + ((xOpen*xPer)*0.5)) line.set_color(p5, color = PosDevs) if ShowOpen var oo = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(oo, lineStart, xOpen) line.set_xy2(oo, lineEnd, xOpen) line.set_color(oo, color = OpenDev) if ShowP5 var n5 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(n5, lineStart, xOpen - ((xOpen*xPer)*0.5)) line.set_xy2(n5, lineEnd, xOpen - ((xOpen*xPer)*0.5)) line.set_color(n5, color = NegDevs) if Show1 var n1 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(n1, lineStart, xOpen - ((xOpen*xPer)*1)) line.set_xy2(n1, lineEnd, xOpen - ((xOpen*xPer)*1)) line.set_color(n1, color = NegDevs) if Show1P5 var n15 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(n15, lineStart, xOpen - ((xOpen*xPer)*1.5)) line.set_xy2(n15, lineEnd, xOpen - ((xOpen*xPer)*1.5)) line.set_color(n15, color = NegDevs) if Show2 var n2 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(n2, lineStart, xOpen - ((xOpen*xPer)*2)) line.set_xy2(n2, lineEnd, xOpen - ((xOpen*xPer)*2)) line.set_color(n2, color = NegDevs) if Show2P5 var n25 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(n25, lineStart, xOpen - ((xOpen*xPer)*2.5)) line.set_xy2(n25, lineEnd, xOpen - ((xOpen*xPer)*2.5)) line.set_color(n25, color = NegDevs) if Show3 var n3 = line.new(na, na, na, na, xloc = xloc.bar_time, style = lineStyle, width = 1) line.set_xy1(n3, lineStart, xOpen - ((xOpen*xPer)*3)) line.set_xy2(n3, lineEnd, xOpen - ((xOpen*xPer)*3)) line.set_color(n3, color = NegDevs) //Draw Current and Historical------------------------------------------------------------ if ShowHist and (xOpen != xOpen[1]) and (not badTimeframe and not badTicker) and ShowLines var line p3 = na var line p25 = na var line p2 = na var line p15 = na var line p1 = na var line p5 = na var line oo = na var line n5 = na var line n1 = na var line n15 = na var line n2 = na var line n25 = na var line n3 = na p3 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(p3, lineStart, xOpen + ((xOpen*xPer)*3)) line.set_xy2(p3, lineEnd, xOpen + ((xOpen*xPer)*3)) line.set_color(p3, color = PosDevs) p25 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(p25, lineStart, xOpen + ((xOpen*xPer)*2.5)) line.set_xy2(p25, lineEnd, xOpen + ((xOpen*xPer)*2.5)) line.set_color(p25, color = PosDevs) p2 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(p2, lineStart, xOpen + ((xOpen*xPer)*2)) line.set_xy2(p2, lineEnd, xOpen + ((xOpen*xPer)*2)) line.set_color(p2, color = PosDevs) p15 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(p15, lineStart, xOpen + ((xOpen*xPer)*1.5)) line.set_xy2(p15, lineEnd, xOpen + ((xOpen*xPer)*1.5)) line.set_color(p15, color = PosDevs) p1 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(p1, lineStart, xOpen + ((xOpen*xPer)*1)) line.set_xy2(p1, lineEnd, xOpen + ((xOpen*xPer)*1)) line.set_color(p1, color = PosDevs) p5 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(p5, lineStart, xOpen + ((xOpen*xPer)*0.5)) line.set_xy2(p5, lineEnd, xOpen + ((xOpen*xPer)*0.5)) line.set_color(p5, color = PosDevs) oo := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(oo, lineStart, xOpen) line.set_xy2(oo, lineEnd, xOpen) line.set_color(oo, color = OpenDev) n5 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(n5, lineStart, xOpen - ((xOpen*xPer)*0.5)) line.set_xy2(n5, lineEnd, xOpen - ((xOpen*xPer)*0.5)) line.set_color(n5, color = NegDevs) n1 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(n1, lineStart, xOpen - ((xOpen*xPer)*1)) line.set_xy2(n1, lineEnd, xOpen - ((xOpen*xPer)*1)) line.set_color(n1, color = NegDevs) n15 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(n15, lineStart, xOpen - ((xOpen*xPer)*1.5)) line.set_xy2(n15, lineEnd, xOpen - ((xOpen*xPer)*1.5)) line.set_color(n15, color = NegDevs) n2 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(n2, lineStart, xOpen - ((xOpen*xPer)*2)) line.set_xy2(n2, lineEnd, xOpen - ((xOpen*xPer)*2)) line.set_color(n2, color = NegDevs) n25 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(n25, lineStart, xOpen - ((xOpen*xPer)*2.5)) line.set_xy2(n25, lineEnd, xOpen - ((xOpen*xPer)*2.5)) line.set_color(n25, color = NegDevs) n3 := line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_dashed, width = 1) line.set_xy1(n3, lineStart, xOpen - ((xOpen*xPer)*3)) line.set_xy2(n3, lineEnd, xOpen - ((xOpen*xPer)*3)) line.set_color(n3, color = NegDevs) //Draw Labels------------------------------------------------------------ if LabelBool and (not badTimeframe and not badTicker) if Show3 var devp3 = label.new(na, na, "3", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devp3, lineEnd, xOpen + ((xOpen*xPer)*3)) label.set_size(devp3, size.small) label.set_textcolor(devp3, textcolor = LabelColor) if Show2P5 var devp25 = label.new(na, na, "2.5", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devp25, lineEnd, xOpen + ((xOpen*xPer)*2.5)) label.set_size(devp25, size.small) label.set_textcolor(devp25, textcolor = LabelColor) if Show2 var devp2 = label.new(na, na, "2", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devp2, lineEnd, xOpen + ((xOpen*xPer)*2)) label.set_size(devp2, size.small) label.set_textcolor(devp2, textcolor = LabelColor) if Show1P5 var devp15 = label.new(na, na, "1.5", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devp15, lineEnd, xOpen + ((xOpen*xPer)*1.5)) label.set_size(devp15, size.small) label.set_textcolor(devp15, textcolor = LabelColor) if Show1 var devp1 = label.new(na, na, "1", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devp1, lineEnd, xOpen + ((xOpen*xPer)*1)) label.set_size(devp1, size.small) label.set_textcolor(devp1, textcolor = LabelColor) if ShowP5 var devp05 = label.new(na, na, ".5", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devp05, lineEnd, xOpen + ((xOpen*xPer)*0.5)) label.set_size(devp05, size.small) label.set_textcolor(devp05, textcolor = LabelColor) if ShowOpen var devO = label.new(na, na, "O", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devO, lineEnd, xOpen) label.set_size(devO, size.small) label.set_textcolor(devO, textcolor = LabelColor) if ShowP5 var devn05 = label.new(na, na, ".5", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devn05, lineEnd, xOpen - ((xOpen*xPer)*0.5)) label.set_size(devn05, size.small) label.set_textcolor(devn05, textcolor = LabelColor) if Show1 var devn1 = label.new(na, na, "1", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devn1, lineEnd, xOpen - ((xOpen*xPer)*1)) label.set_size(devn1, size.small) label.set_textcolor(devn1, textcolor = LabelColor) if Show1P5 var devn15 = label.new(na, na, "1.5", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devn15, lineEnd, xOpen - ((xOpen*xPer)*1.5)) label.set_size(devn15, size.small) label.set_textcolor(devn15, textcolor = LabelColor) if Show2 var devn2 = label.new(na, na, "2", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devn2, lineEnd, xOpen - ((xOpen*xPer)*2)) label.set_size(devn2, size.small) label.set_textcolor(devn2, textcolor = LabelColor) if Show2P5 var devn25 = label.new(na, na, "2.5", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devn25, lineEnd, xOpen - ((xOpen*xPer)*2.5)) label.set_size(devn25, size.small) label.set_textcolor(devn25, textcolor = LabelColor) if Show3 var devn3 = label.new(na, na, "3", xloc = xloc.bar_time, color = LabelColor, style = label.style_none) label.set_xy(devn3, lineEnd, xOpen - ((xOpen*xPer)*3)) label.set_size(devn3, size.small) label.set_textcolor(devn3, textcolor = LabelColor)
Moving averages & clouds
https://www.tradingview.com/script/lUhJUbuC-Moving-averages-clouds/
mickes
https://www.tradingview.com/u/mickes/
9
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/ // © mickes //@version=5 indicator("Moving averages & clouds", overlay = true) import TradingView/ta/5 _timeFrame = input.timeframe("", "Time frame", group = "General") _ma1Length = input.int(21, "Length", group = "Moving average 1") _ma1Type = input.string("EMA", "Type", ["SMA", "EMA", "HMA", "WMA", "VWMA", "DEMA"], group = "Moving average 1") _ma1Alert = input.string("None", "Type", ["None", "Price cross", "Price cross up", "Price cross down"], group = "Moving average 1") _ma2Length = input.int(50, "Length", group = "Moving average 2") _ma2Type = input.string("SMA", "Type", ["SMA", "EMA", "HMA", "WMA", "VWMA", "DEMA"], group = "Moving average 2") _ma2Alert = input.string("None", "Type", ["None", "Cross", "Cross up", "Cross down"], group = "Moving average 2") _ma3Length = input.int(200, "Length", group = "Moving average 3") _ma3Type = input.string("SMA", "Type", ["SMA", "EMA", "HMA", "WMA", "VWMA", "DEMA"], group = "Moving average 3") _ma3Alert = input.string("None", "Type", ["None", "Cross", "Cross up", "Cross down"], group = "Moving average 3") _alertFrequency = input.string(alert.freq_all, "Frequecy", [alert.freq_all, alert.freq_once_per_bar, alert.freq_once_per_bar_close], group = "Alert") type movingAverage float Price getMovingAverage(movingAverageType, length) => ma = movingAverage.new() switch movingAverageType "SMA" => ma.Price := ta.sma(close, length) "EMA" => ma.Price := ta.ema(close, length) "HMA" => ma.Price := ta.hma(close, length) "WMA" => ma.Price := ta.wma(close, length) "VWMA" => ma.Price := ta.vwma(close, length) "DEMA" => ma.Price := ta.dema2(close, length) ma alertUser(movingAveragePrice, alertType, message) => lowCrossUp = ta.crossover(low, movingAveragePrice) highCrossDown = ta.crossunder(high, movingAveragePrice) var highCrossedDown = false var lowCrossedUp = false if highCrossDown highCrossedDown := true if lowCrossUp lowCrossedUp := true switch alertType "Price cross" => if (lowCrossUp and highCrossedDown) or (highCrossDown and lowCrossedUp) alert(str.format("Price crossed {0}", message), _alertFrequency) highCrossedDown := false lowCrossedUp := false label.new(bar_index, high, str.format("Price crossed {0}", message)) "Price cross up" => if lowCrossUp and highCrossedDown alert(str.format("Price crossed {0} up", message), _alertFrequency) highCrossedDown := false label.new(bar_index, high, str.format("Price crossed {0} up", message)) "Price cross down" => if highCrossDown and lowCrossedUp alert(str.format("Price crossed {0} down", message), _alertFrequency) lowCrossedUp := false label.new(bar_index, high, str.format("Price crossed {0} down", message)) ma1 = request.security(syminfo.tickerid, _timeFrame, getMovingAverage(_ma1Type, _ma1Length), lookahead = barmerge.lookahead_on) ma2 = request.security(syminfo.tickerid, _timeFrame, getMovingAverage(_ma2Type, _ma2Length), lookahead = barmerge.lookahead_on) ma3 = request.security(syminfo.tickerid, _timeFrame, getMovingAverage(_ma3Type, _ma3Length), lookahead = barmerge.lookahead_on) ma1Plot = plot(ma1.Price, "MA 1", color = color.blue) ma2Plot = plot(ma2.Price, "MA 2", color = color.orange) ma3Plot = plot(ma3.Price, "MA 3", color = color.red) fill(ma1Plot, ma2Plot, title = "Cloud 1 <-> 2", color = color.new(na, 100)) fill(ma1Plot, ma3Plot, title = "Cloud 1 <-> 3", color = color.new(na, 100)) fill(ma2Plot, ma3Plot, title = "Cloud 2 <-> 3", color = color.new(color.red, 85)) alertUser(ma1.Price, _ma1Alert, str.format("Moving average 1 ({0} {1} {2}) on {3} chart", _ma1Length, _ma1Type, _timeFrame, timeframe.period)) alertUser(ma2.Price, _ma2Alert, str.format("Moving average 2 ({0} {1} {2}) on {3} chart", _ma1Length, _ma1Type, _timeFrame, timeframe.period)) alertUser(ma3.Price, _ma3Alert, str.format("Moving average 3 ({0} {1} {2}) on {3} chart", _ma1Length, _ma1Type, _timeFrame, timeframe.period))
Blockchain Fundamental
https://www.tradingview.com/script/afvXr9C3-Blockchain-Fundamental/
gotbeatz26107
https://www.tradingview.com/u/gotbeatz26107/
81
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/ // © gotbeatz26107 //@version=5 indicator("Blockchain fundamental", shorttitle = "BF V0.1", overlay = false, precision = 2) // Libraries import gotbeatz26107/ma_/2 as ma // Indicator settings htfInterval = input.timeframe("D", title = 'Timeframe', options = ['D', '3D', 'W', '2W', 'M'], group = 'Indicator settings', inline = '1') average_type = input.string ("JMA", options = ['SMA', 'EMA', 'ALMA', 'DEMA', 'HMA' , 'JMA', 'KAMA', 'SMMA', 'TMA', 'TSF' , 'VAR', 'VMA', 'VAMA', 'VWMA', 'WMA' ,'WWMA', 'ZLEMA'], inline = '1', title = "Moving Average Type", group = 'Indicator settings') osc_ma_length = input.int(90, title = "MA length", group = "Indicator settings") Sharpness = input.float(25.0, "Sharpness", group = "Kalman Filter", inline = "kf") K = input.float(1.0, "Filter Period", group = "Kalman Filter", inline = "kf") use_kalman = input.bool(true, title = "Use kalman filter for signals?", group = "Kalman Filter") incl_balance = input.bool(true, group = "Metrics", title = "Mean value an address holds") incl_drawdown = input.bool(true, group = "Metrics", title = "ATH drawdown") incl_sopr = input.bool(true, group = "Metrics", title = "Spent Optput Profit ratio") incl_mvrv = input.bool(true, group = "Metrics", title = "Market Cap to Realised Cap ratio") incl_pnl_perc = input.bool(true, group = "Metrics", title = "Profit/Loss delta") incl_mcap = input.bool(true, group = "Metrics", title = "MCAP/real MCAP ratio") incl_mcap_ratio = input.bool(true, group = "Metrics", title = "MCAP/ Stablecoin MCAP ratio") incl_tx_large = input.bool(true, group = "Metrics", title = "Transfers > $100.000") incl_hashrate = input.bool(true, group = "Metrics", title = "Hashrate time delta") incl_miner_rev = input.bool(true, group = "Metrics", title = "Miner revenue/number of tx's") incl_miner_fees = input.bool(true, group = "Metrics", title = "Miner fees time delta") // Kalman filter kalman_filter(src, Sharpness, K) => velocity = 0.0 kfilt = 0.0 Distance = src - nz(kfilt[1], src) Error = nz(kfilt[1], src) + Distance * math.sqrt(Sharpness*K/ 100) velocity := nz(velocity[1], 0) + Distance*K / 100 kfilt := Error + velocity kfilt // // Function to calculate bollinger bands deviation bbr(float src, int length) => basis = ma.selector(src, length, average_type) dev = 1 * ta.stdev(src, length) upper = basis + dev lower = basis - dev bbr = (src - lower)/(upper - lower) //Output bbr // // Profiler function profiler(float src, float percentile, int lookback) => poc_val = ta.percentile_linear_interpolation(src, lookback, 50) lower_boundary_val = ta.percentile_linear_interpolation(src, lookback, 100 - percentile) upper_boundary_val = ta.percentile_linear_interpolation(src, lookback, percentile) [poc_val, lower_boundary_val, upper_boundary_val] // // Convert Timeframe getTimeframeMinutes(timeframe) => // Input minutes = 0 // Conversion if timeframe == '5' minutes := 5 if timeframe == '10' minutes := 10 if timeframe == '15' minutes := 15 if timeframe == '30' minutes := 30 if timeframe == '60' minutes := 60 if timeframe == '120' minutes := 120 if timeframe == '240' minutes := 240 if timeframe == '720' minutes := 720 if timeframe == 'D' minutes := 1440 if timeframe == '3D' minutes := 4320 if timeframe == 'W' minutes := 10080 if timeframe == '2W' minutes := 20160 if timeframe == 'M' minutes := 43200 // Output minutes // calculateTimeframeRatio(htf) => getTimeframeMinutes(htf) / getTimeframeMinutes(timeframe.period) tf_ratio = calculateTimeframeRatio(htfInterval) // percentile = input(99, title = "Value Area Percentile", inline = 'l2', group = "Indicator settings") lookback = input(365, title = "Lookback period", inline = 'l2', group = "Indicator settings") * tf_ratio bound_up = input(90.0, title = "Upper bound", inline = "b1", group = "Bounds") bound_dn = input(-90.0, title = "Lower bound", inline = "b1", group = "Bounds") //--------------------------------------------------------------------------------------------------------------------// //----------------------------------------------------Calculation-----------------------------------------------------// //--------------------------------------------------------------------------------------------------------------------// // USD value of all coins based on a close price of the day they last moved mcap_real = request.security("COINMETRICS:" + syminfo.basecurrency + "_MARKETCAPREAL", htfInterval, close, ignore_invalid_symbol = true) // Market Cap mcap = request.security("GLASSNODE:" + syminfo.basecurrency + "_MARKETCAP", htfInterval, close, ignore_invalid_symbol = true) mcap() => mcap_ratio = mcap / mcap_real mcap_ratio_90 = ma.selector(mcap_ratio, 90 * tf_ratio, average_type) mcap_ratio_365 = ma.selector(mcap_ratio, 365 * tf_ratio, average_type) mcap_score = 0 if mcap_ratio >= mcap_ratio_365 mcap_score += 25 if mcap_ratio_90 >= mcap_ratio_365 mcap_score += 25 if mcap_ratio >= 2 mcap_score += 25 if mcap_ratio >= 3 mcap_score += 25 if mcap_ratio <= mcap_ratio_365 mcap_score -= 25 if mcap_ratio_90 <= mcap_ratio_365 mcap_score -= 25 if mcap_ratio <= 2 mcap_score -= 25 if mcap_ratio <= 1 mcap_score -= 25 // Output mcap_score // // Spent Output Profit Ratio (SOPR) sopr = request.security("GLASSNODE:" + syminfo.basecurrency + "_SOPR", htfInterval, close, ignore_invalid_symbol = true) sopr() => // Calculation length = 30 * tf_ratio sopr_ma = ma.selector(sopr, length, average_type) // Logic soprScore = 0 if sopr_ma < 1 soprScore -= 25 if sopr_ma < 0.995 soprScore -= 25 if sopr_ma < 0.990 soprScore -= 25 if sopr_ma < 0.985 soprScore -= 25 if sopr_ma > 1 soprScore += 25 if sopr_ma > 1.005 soprScore += 25 if sopr_ma > 1.010 soprScore += 25 if sopr_ma > 1.015 soprScore += 25 // Output soprScore // // Percentage of addresses that are profiting at current price profit_perc = request.security("INTOTHEBLOCK:" + syminfo.basecurrency + "_INOUTMONEYINPERCENTAGE", htfInterval, close, ignore_invalid_symbol = true) // Percentage of break even addresses out of all addresses holding this asset even_perc = request.security("INTOTHEBLOCK:" + syminfo.basecurrency + "_BREAKEVENADDRESSESPERCENTAGE", htfInterval, close, ignore_invalid_symbol = true) // Percentage of addresses that are losing at current price loss_perc = request.security("INTOTHEBLOCK:" + syminfo.basecurrency + "_INOUTMONEYOUTPERCENTAGE", htfInterval, close, ignore_invalid_symbol = true) pnl_perc() => net_pnl_perc = (profit_perc + even_perc) - (loss_perc + even_perc) pnl_perc_score = 0 if net_pnl_perc <= 0.5 pnl_perc_score -= 20 if net_pnl_perc <= 0.4 pnl_perc_score -= 20 if net_pnl_perc <= 0.3 pnl_perc_score -= 20 if net_pnl_perc <= 0.2 pnl_perc_score -= 20 if net_pnl_perc <= 0.1 pnl_perc_score -= 20 if net_pnl_perc >= 0.5 pnl_perc_score += 20 if net_pnl_perc >= 0.6 pnl_perc_score += 20 if net_pnl_perc >= 0.7 pnl_perc_score += 20 if net_pnl_perc >= 0.8 pnl_perc_score += 20 if net_pnl_perc >= 0.9 pnl_perc_score += 20 // Output pnl_perc_score // // Price Drawdown from ATH ath_drawdown = request.security("GLASSNODE:" + syminfo.basecurrency + "_ATHDRAWDOWN", htfInterval, close, ignore_invalid_symbol = true) drawdown_score() => [poc_val, _, _] = profiler(ath_drawdown, percentile, lookback) ath_drawdown_score = 0 if ath_drawdown >= poc_val ath_drawdown_score += 25 if ath_drawdown >= -0.05 ath_drawdown_score += 25 if ath_drawdown >= (-0.05 - poc_val) / 2 ath_drawdown_score += 25 if ath_drawdown >= (-0.05 - poc_val) / 3 ath_drawdown_score += 25 if ath_drawdown <= poc_val ath_drawdown_score -= 25 if ath_drawdown <= -0.7 ath_drawdown_score -= 25 if ath_drawdown <= (-0.7 + poc_val) / 2 ath_drawdown_score -= 25 if ath_drawdown <= (-0.7 + poc_val) / 3 ath_drawdown_score -= 25 // Output ath_drawdown_score // // Market Cap to Realised cap ratio (MVRV) mvrv = request.security("INTOTHEBLOCK:" + syminfo.basecurrency + "_MVRV", htfInterval, close, ignore_invalid_symbol = true) mvrv() => mvrv_score = 0 mvrv_30 = ma.selector(mvrv, 30 * tf_ratio, average_type) mvrv_1y = ma.selector(mvrv, 365 * tf_ratio, average_type) if mvrv < 2 mvrv_score -= 25 if mvrv < 1 mvrv_score -= 25 if mvrv_30 < 1 mvrv_score -= 25 if mvrv < mvrv_1y mvrv_score -= 25 if mvrv > 3 mvrv_score += 25 if mvrv > 2 mvrv_score += 25 if mvrv_30 > 2 mvrv_score += 25 if mvrv > mvrv_1y mvrv_score += 25 // output mvrv_score // // Mean Value an address holds avg_balance = request.security("INTOTHEBLOCK:" + syminfo.basecurrency + "_AVGTXUSD", htfInterval, close, ignore_invalid_symbol = true) avg_balance() => avg_balance_30 = ma.selector(math.log(avg_balance), 30 * tf_ratio, average_type) avg_balance_90 = ma.selector(math.log(avg_balance), 90 * tf_ratio, average_type) // Extract values from the profiler [poc_val, lower_boundary_val, upper_boundary_val] = profiler(avg_balance_30, percentile, lookback) avg_balance_score = 0 if avg_balance_30 >= poc_val avg_balance_score += 25 if avg_balance_30 >= upper_boundary_val avg_balance_score += 25 if avg_balance_30 >= avg_balance_90 avg_balance_score += 25 if avg_balance_90 >= poc_val avg_balance_score += 25 if avg_balance_30 <= poc_val avg_balance_score -= 25 if avg_balance_30 <= lower_boundary_val avg_balance_score -= 25 if avg_balance_30 <= avg_balance_90 avg_balance_score -= 25 if avg_balance_90 <= poc_val avg_balance_score -= 25 // Output avg_balance_score // // Sum of all transfers > $100.000 in a day in USD tx_large_usd = request.security("COINMETRICS:" + syminfo.basecurrency + "_LARGETXVOLUMEUSD", htfInterval, close, ignore_invalid_symbol = true) tx_large() => tx_large_30 = ma.selector(math.log(tx_large_usd), 30 * tf_ratio, average_type) tx_large_90 = ma.selector(math.log(tx_large_usd), 90 * tf_ratio, average_type) [poc_val, lower_boundary_val, upper_boundary_val] = profiler(tx_large_30, percentile, lookback) tx_large_score = 0 if tx_large_30 >= tx_large_90 tx_large_score += 25 if tx_large_30 >= poc_val tx_large_score += 25 if tx_large_30 >= upper_boundary_val tx_large_score += 25 if tx_large_90 >= poc_val tx_large_score += 25 if tx_large_30 <= tx_large_90 tx_large_score -= 25 if tx_large_30 <= poc_val tx_large_score -= 25 if tx_large_30 <= lower_boundary_val tx_large_score -= 25 if tx_large_90 <= poc_val tx_large_score -= 25 // Output tx_large_score // // Mean Hash Rate hashRate = request.security("GLASSNODE:" + syminfo.basecurrency + "_HASHRATE", htfInterval, close, ignore_invalid_symbol = true) hashrate() => hashRate_30 = math.log(ma.selector(hashRate, 30 * tf_ratio, average_type)) hashRate_60 = math.log(ma.selector(hashRate, 60 * tf_ratio, average_type)) hashrate_delta = hashRate_30 - hashRate_60 hashrate_1y = ma.selector(hashrate_delta, 365 * tf_ratio, average_type) hashrate_90 = ma.selector(hashrate_delta, 90 * tf_ratio, average_type) hash_score = 0 if hashrate_delta >= 0 hash_score += 25 if hashrate_delta >= hashrate_90 hash_score += 25 if hashrate_delta >= hashrate_1y hash_score += 25 if hashrate_90 >= hashrate_1y hash_score += 25 if hashrate_delta <= hashrate_90 hash_score -= 25 if hashrate_delta <= hashrate_1y hash_score -= 25 if hashrate_delta <= 0 hash_score -= 25 if hashrate_90 <= hashrate_1y hash_score -= 25 // Output hash_score // // A chart showing miners revenue divided by the number of transactions. miner_revenue_txdivided = request.quandl("BCHAIN/CPTRA") miner_rev_divided() => mrtd = math.log10(miner_revenue_txdivided) mrtd_30 = ma.selector(mrtd, 30 * tf_ratio, average_type) mrtd_90 = ma.selector(mrtd, 90 * tf_ratio, average_type) mrtd_365 = ma.selector(mrtd, 365 * tf_ratio, average_type) mrtd_dev = bbr(mrtd, 365 * tf_ratio) mrtd_score = 0 if mrtd >= mrtd_30 mrtd_score += 20 if mrtd_30 >= mrtd_90 mrtd_score += 20 if mrtd_90 >= mrtd_365 mrtd_score += 20 if mrtd_dev >= 0.5 mrtd_score += 20 if mrtd_dev >= 1 mrtd_score += 20 if mrtd <= mrtd_30 mrtd_score -= 20 if mrtd_30 <= mrtd_90 mrtd_score -= 20 if mrtd_90 <= mrtd_365 mrtd_score -= 20 if mrtd_dev <= 0.5 mrtd_score -= 20 if mrtd_dev <= 0 mrtd_score -= 20 // Output mrtd_score // // The total value of all transaction fees paid to miners in USD (not including the coinbase value of block rewards). miner_fees_usd = request.quandl("BCHAIN/TRFUS") miner_fees_usd() => fees_usd = math.log10(miner_fees_usd) fees_30 = ma.selector(fees_usd, 30 * tf_ratio, average_type) fees_90 = ma.selector(fees_usd, 90 * tf_ratio, average_type) fees_365 = ma.selector(fees_usd, 365 * tf_ratio, average_type) fees_dev = bbr(fees_usd, 365 * tf_ratio) fees_score = 0 if fees_usd >= fees_30 fees_score += 20 if fees_30 >= fees_90 fees_score += 20 if fees_90 >= fees_365 fees_score += 20 if fees_dev >= 0.5 fees_score += 20 if fees_dev >= 1 fees_score += 20 if fees_usd <= fees_30 fees_score -= 20 if fees_30 <= fees_90 fees_score -= 20 if fees_90 <= fees_365 fees_score -= 20 if fees_dev <= 0.5 fees_score -= 20 if fees_dev <= 0 fees_score -= 20 // Output fees_score // usdt_mcap = request.security("CRYPTOCAP:USDT", htfInterval, close) usdc_mcap = request.security("CRYPTOCAP:USDC", htfInterval, close) dai_mcap = request.security("CRYPTOCAP:DAI", htfInterval, close) mcap_ratio() => stablecoin_mcap = usdt_mcap + usdc_mcap + dai_mcap mcap_ratio = mcap / stablecoin_mcap mcap_ratio_30 = ma.selector(mcap_ratio, 30 * tf_ratio, average_type) mcap_ratio_90 = ma.selector(mcap_ratio, 90 * tf_ratio, average_type) mcap_ratio_365 = ma.selector(mcap_ratio, 365 * tf_ratio, average_type) mcap_score = 0.0 if mcap_ratio >= mcap_ratio_30 mcap_score += 33.4 if mcap_ratio_30 >= mcap_ratio_90 mcap_score += 33.3 if mcap_ratio_90 >= mcap_ratio_365 mcap_score += 33.3 if mcap_ratio <= mcap_ratio_30 mcap_score -= 33.4 if mcap_ratio_30 <= mcap_ratio_90 mcap_score -= 33.3 if mcap_ratio_90 <= mcap_ratio_365 mcap_score -= 33.3 // Output mcap_score // balance = 0 balance := incl_balance ? avg_balance() : 0 drawdown = 0 drawdown := incl_drawdown ? drawdown_score() : 0 sopr_ = 0 sopr_ := incl_sopr ? sopr() : 0 mvrv_ = 0 mvrv_ := incl_mvrv ? mvrv() : 0 pnl = 0 pnl := incl_pnl_perc ? pnl_perc() : 0 mcap_ = 0 mcap_ := incl_mcap ? mcap() : 0 mcap_ratio_ = 0.0 mcap_ratio_ := incl_mcap_ratio ? mcap_ratio() : 0 tx_large_ = 0 tx_large_ := incl_tx_large ? tx_large() : 0 hrate = 0 hrate := incl_hashrate ? hashrate() : 0 miner_rev_ = 0 miner_rev_ := incl_miner_rev ? miner_rev_divided() : 0 miner_fee_usd = 0 miner_fee_usd := incl_miner_fees ? miner_fees_usd() : 0 counter() => count = 0 if mcap() != 0 and incl_mcap count += 1 if sopr() != 0 and incl_sopr count += 1 if pnl_perc() != 0 and incl_pnl_perc count += 1 if drawdown_score() != 0 and incl_drawdown count += 1 if mvrv() != 0 and incl_mvrv count += 1 if avg_balance() != 0 and incl_balance count += 1 if tx_large() != 0 and incl_tx_large count += 1 if hashrate() != 0 and incl_hashrate count += 1 if miner_rev_divided() != 0 and incl_miner_rev count += 1 if miner_fees_usd() != 0 and incl_miner_fees count += 1 if mcap_ratio() != 0 and incl_mcap_ratio count += 1 // Output count // count = counter() fundamental = (balance + drawdown + sopr_ + mvrv_ + pnl + mcap_ + mcap_ratio_ + tx_large_ + hrate + miner_rev_ + miner_fee_usd ) / count fundamental_ma = ma.selector(fundamental, osc_ma_length * tf_ratio, average_type) fundamental_kalman = kalman_filter(fundamental, Sharpness, K) signal = use_kalman ? fundamental_kalman : fundamental //--------------------------------------------------------------------------------------------------------------------// //-----------------------------------------------------Plotting-------------------------------------------------------// //--------------------------------------------------------------------------------------------------------------------// plot(fundamental, color = color.white, title = "Signal oscillator") plot(fundamental_ma, color = color.yellow, title = "Signal Oscillator MA") plot(fundamental_kalman, color = color.orange, title = "Signal Oscillator Kalman") plot(count, color = color.rgb(120, 123, 134, 50), title = "Signal counter") hline(0, title = "Zero line") hline(bound_up, title = "Bound up") hline(bound_dn, title = "Bound down") bgcolor(signal >= bound_up ? color.red : na, title = "Buy signal color") bgcolor(signal <= bound_dn ? color.teal : na, title = "Sell signal color")
[dharmatech] U.S. Treasury Yield Curve
https://www.tradingview.com/script/zLbGeh27-dharmatech-U-S-Treasury-Yield-Curve/
dharmatech
https://www.tradingview.com/u/dharmatech/
32
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/ // © dharmatech // 2023-10-01 : Hardcoded timeframe of securities to 1D. Without this, RRP doesn't load at lower timeframes. // Also, without this, at lower timeframes, the yield curve difference is sometimes hardly noticeable. //@version=5 indicator("US Treasury Yield Curve", overlay = false, precision = 4) width = input.int(defval = 15, title = "Spacing between labels in bars") prev = input.int(defval = 1, title = "Previous") prev_1 = input.int(defval = 30, title = "Previous 1") prev_2 = input.int(defval = 60, title = "Previous 2") prev_3 = input.int(defval = 90, title = "Previous 3") prev_4 = input.int(defval = 180, title = "Previous 4") prev_5 = input.int(defval = 360, title = "Previous 5") prev_1_on = input.bool(defval = false) prev_2_on = input.bool(defval = false) prev_3_on = input.bool(defval = false) prev_4_on = input.bool(defval = false) prev_5_on = input.bool(defval = false) symbols = 13 rrp = request.security("RRPONTSYAWARD", timeframe = '1D', expression = close) us1m = request.security("US01MY", timeframe = '1D', expression = close) us2m = request.security("US02MY", timeframe = '1D', expression = close) us3m = request.security("US03MY", timeframe = '1D', expression = close) us4m = request.security("US04MY", timeframe = '1D', expression = close) us6m = request.security("US06MY", timeframe = '1D', expression = close) us1y = request.security("US01Y", timeframe = '1D', expression = close) us2y = request.security("US02Y", timeframe = '1D', expression = close) us3y = request.security("US03Y", timeframe = '1D', expression = close) us5y = request.security("US05Y", timeframe = '1D', expression = close) us7y = request.security("US07Y", timeframe = '1D', expression = close) us10y = request.security("US10Y", timeframe = '1D', expression = close) us20y = request.security("US20Y", timeframe = '1D', expression = close) us30y = request.security("US30Y", timeframe = '1D', expression = close) pos(idx) => bar_index - (symbols - idx) * width draw_label(idx, src, txt) => var label la = na label.delete(la) la := label.new(x = pos(idx), y = src - 0.1, text = txt, color = color.black, style = label.style_label_up, textcolor = color.white) draw_line(idx1, src1, idx2, src2) => var line li = na line.delete(li) li := line.new(x1 = pos(idx1), y1 = src1, x2 = pos(idx2), y2 = src2, color=color.red, width=3) draw_line_prev(idx1, src1, idx2, src2) => var line li2 = na line.delete(li2) li2 := line.new(x1 = pos(idx1), y1 = src1[prev], x2 = pos(idx2), y2 = src2[prev], color=color.yellow, width=1) draw_line_prev_alt(idx1, src1, idx2, src2, color) => var line li3 = na line.delete(li3) li3 := line.new(x1 = pos(idx1), y1 = src1[prev], x2 = pos(idx2), y2 = src2[prev], color=color, width=1) draw_label( -1, rrp, "RRP% \n (" + str.tostring(math.round(rrp, 3)) + ")") draw_label( 0, us1m, "1M \n (" + str.tostring(math.round(us1m, 3)) + ")") draw_label( 1, us2m, "2M \n (" + str.tostring(math.round(us2m, 3)) + ")") draw_label( 2, us3m, "3M \n (" + str.tostring(math.round(us3m, 3)) + ")") draw_label( 3, us4m, "4M \n (" + str.tostring(math.round(us4m, 3)) + ")") draw_label( 4, us6m, "6M \n (" + str.tostring(math.round(us6m, 3)) + ")") draw_label( 5, us1y, "1Y \n (" + str.tostring(math.round(us1y, 3)) + ")") draw_label( 6, us2y, "2Y \n (" + str.tostring(math.round(us2y, 3)) + ")") draw_label( 7, us3y, "3Y \n (" + str.tostring(math.round(us3y, 3)) + ")") draw_label( 8, us5y, "5Y \n (" + str.tostring(math.round(us5y, 3)) + ")") draw_label( 9, us7y, "7Y \n (" + str.tostring(math.round(us7y, 3)) + ")") draw_label( 10, us10y, "10Y \n (" + str.tostring(math.round(us10y, 3)) + ")") draw_label( 11, us20y, "20Y \n (" + str.tostring(math.round(us20y, 3)) + ")") draw_label( 12, us30y, "30Y \n (" + str.tostring(math.round(us30y, 3)) + ")") draw_line(-1, rrp, 0, us1m) draw_line( 0, us1m, 1, us2m) draw_line( 1, us2m, 2, us3m) draw_line( 2, us3m, 3, us4m) draw_line( 3, us4m, 4, us6m) draw_line( 4, us6m, 5, us1y) draw_line( 5, us1y, 6, us2y) draw_line( 6, us2y, 7, us3y) draw_line( 7, us3y, 8, us5y) draw_line( 8, us5y, 9, us7y) draw_line( 9, us7y, 10, us10y) draw_line(10, us10y, 11, us20y) draw_line(11, us20y, 12, us30y) draw_line_prev(-1, rrp, 0, us1m) draw_line_prev( 0, us1m, 1, us2m) draw_line_prev( 1, us2m, 2, us3m) draw_line_prev( 2, us3m, 3, us4m) draw_line_prev( 3, us4m, 4, us6m) draw_line_prev( 4, us6m, 5, us1y) draw_line_prev( 5, us1y, 6, us2y) draw_line_prev( 6, us2y, 7, us3y) draw_line_prev( 7, us3y, 8, us5y) draw_line_prev( 8, us5y, 9, us7y) draw_line_prev( 9, us7y, 10, us10y) draw_line_prev(10, us10y, 11, us20y) draw_line_prev(11, us20y, 12, us30y) draw_curve(int n, color color) => draw_line_prev_alt(-1, rrp[n], 0, us1m[n], color) draw_line_prev_alt( 0, us1m[n], 1, us2m[n], color) draw_line_prev_alt( 1, us2m[n], 2, us3m[n], color) draw_line_prev_alt( 2, us3m[n], 3, us4m[n], color) draw_line_prev_alt( 3, us4m[n], 4, us6m[n], color) draw_line_prev_alt( 4, us6m[n], 5, us1y[n], color) draw_line_prev_alt( 5, us1y[n], 6, us2y[n], color) draw_line_prev_alt( 6, us2y[n], 7, us3y[n], color) draw_line_prev_alt( 7, us3y[n], 8, us5y[n], color) draw_line_prev_alt( 8, us5y[n], 9, us7y[n], color) draw_line_prev_alt( 9, us7y[n], 10, us10y[n], color) draw_line_prev_alt(10, us10y[n], 11, us20y[n], color) draw_line_prev_alt(11, us20y[n], 12, us30y[n], color) if prev_1_on draw_curve(prev_1, color.green) if prev_2_on draw_curve(prev_2, color.blue) if prev_3_on draw_curve(prev_3, color.orange) if prev_4_on draw_curve(prev_4, color.white) if prev_5_on draw_curve(prev_5, color.teal) us10y3m = (us10y - us3m) * 100 us10y2y = (us10y - us2y) * 100 p = "Important spreads:\n\n" p := p + "10Y/03M: " + str.tostring(us10y3m) + " bps\n" p := p + "10Y/02Y: " + str.tostring(us10y2y) + " bps\n" // draw_label(12, us30y, p)
Candle Pivot and Stop Loss
https://www.tradingview.com/script/U9mjGpvi-Candle-Pivot-and-Stop-Loss/
Sabarijegan
https://www.tradingview.com/u/Sabarijegan/
4
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/ // © Sabarijegan //@version=5 indicator("Candle Pivot and Stop Loss", overlay=true) // Calculate Current candle Pivot point currentCandlePivot = (high[1] + low[1] + close[1]) / 3 // Calculate Current candle True Range prevHighLowDiff = high[1] - low[1] prevHighCloseDiff = high[1] - close[1] prevLowCloseDiff = low[1] - close[1] currentCandleTrueRange = math.max(prevHighLowDiff, math.max(prevHighCloseDiff, prevLowCloseDiff)) // Calculate Current candle Down Side stop-loss downsideStopLoss = currentCandlePivot + currentCandleTrueRange // Calculate Current candle Up Side stop-loss upsideStopLoss = currentCandlePivot - currentCandleTrueRange // Plotting the Current candle Pivot point and Stop Loss levels plot(currentCandlePivot, color=color.blue, title="Current Candle Pivot") plot(downsideStopLoss, color=color.red, title="Downside Stop Loss") plot(upsideStopLoss, color=color.green, title="Upside Stop Loss")
syminfo table
https://www.tradingview.com/script/Stcga0LM-syminfo-table/
weak_hand
https://www.tradingview.com/u/weak_hand/
4
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/ // © weak_hand //@version=5 indicator("syminfo table", "syminfo", true) string table_xpos = input.string("center", "X-Position", ["center", "left", "right"], display = display.none) string table_ypos = input.string("middle", "Y-Position" , ["bottom", "middle", "top"], display = display.none) string table_size = input.string("auto", "Text Size", ["auto", "tiny", "small", "normal", "large", "huge"], display = display.none) color color_bg = input.color(defval = color.yellow, title = "Background") color color_text = input.color(defval = color.black, title = "Text") var table_syminfo = table.new(table_ypos + "_" + table_xpos, 2, 1, color_bg) string nl = "\n" string left = na string right = na if syminfo.type == "stock" left := "syminfo.country: " + nl + "syminfo.currency: " + nl + "syminfo.description: " + nl + "syminfo.employees: " + nl + "syminfo.industry: " + nl + "syminfo.minmove: " + nl + "syminfo.mintick: " + nl + "syminfo.pointvalue: " + nl + "syminfo.prefix: " + nl + "syminfo.pricescale: " + nl + "syminfo.recommendations_buy: " + nl + "syminfo.recommendations_buy_strong: " + nl + "syminfo.recommendations_date: " + nl + "syminfo.recommendations_hold: " + nl + "syminfo.recommendations_sell: " + nl + "syminfo.recommendations_sell_strong: " + nl + "syminfo.recommendations_total: " + nl + "syminfo.root: " + nl + "syminfo.sector: " + nl + "syminfo.session: " + nl + "syminfo.shareholders: " + nl + "syminfo.shares_outstanding_float: " + nl + "syminfo.shares_outstanding_total: " + nl + "syminfo.target_price_average: " + nl + "syminfo.target_price_date: " + nl + "syminfo.target_price_estimates: " + nl + "syminfo.target_price_high: " + nl + "syminfo.target_price_low: " + nl + "syminfo.target_price_median: " + nl + "syminfo.ticker: " + nl + "syminfo.tickerid: " + nl + "syminfo.timezone: " + nl + "syminfo.type: " + nl + "syminfo.volumetype: " right := syminfo.country + nl + syminfo.currency + nl + syminfo.description + nl + str.tostring(syminfo.employees, format.volume) + nl + syminfo.industry + nl + str.tostring(syminfo.minmove) + nl + str.tostring(syminfo.mintick) + nl + str.tostring(syminfo.pointvalue) + nl + syminfo.prefix + nl + str.tostring(syminfo.pricescale) + nl + str.tostring(syminfo.recommendations_buy) + nl + str.tostring(syminfo.recommendations_buy_strong) + nl + str.format_time(syminfo.recommendations_date, "yyyy-MM-dd", syminfo.timezone) + nl + str.tostring(syminfo.recommendations_hold) + nl + str.tostring(syminfo.recommendations_sell) + nl + str.tostring(syminfo.recommendations_sell_strong) + nl + str.tostring(syminfo.recommendations_total) + nl + syminfo.root + nl + syminfo.sector + nl + syminfo.session + nl + str.tostring(syminfo.shareholders, format.volume) + nl + str.tostring(syminfo.shares_outstanding_float, format.volume) + nl + str.tostring(syminfo.shares_outstanding_total, format.volume) + nl + str.tostring(syminfo.target_price_average, format.mintick) + nl + str.format_time(syminfo.target_price_date, "yyyy-MM-dd", syminfo.timezone) + nl + str.tostring(syminfo.target_price_estimates, format.mintick) + nl + str.tostring(syminfo.target_price_high, format.mintick) + nl + str.tostring(syminfo.target_price_low, format.mintick) + nl + str.tostring(syminfo.target_price_median, format.mintick) + nl + syminfo.ticker + nl + syminfo.tickerid + nl + syminfo.timezone + nl + syminfo.type + nl + syminfo.volumetype else if syminfo.type == "fund" left := "syminfo.country: " + nl + "syminfo.currency: " + nl + "syminfo.description: " + nl + "syminfo.industry: " + nl + "syminfo.minmove: " + nl + "syminfo.mintick: " + nl + "syminfo.pointvalue: " + nl + "syminfo.prefix: " + nl + "syminfo.pricescale: " + nl + "syminfo.root: " + nl + "syminfo.sector: " + nl + "syminfo.session: " + nl + "syminfo.ticker: " + nl + "syminfo.tickerid: " + nl + "syminfo.timezone: " + nl + "syminfo.type: " + nl + "syminfo.volumetype: " right := syminfo.country + nl + syminfo.currency + nl + syminfo.description + nl + syminfo.industry + nl + str.tostring(syminfo.minmove) + nl + str.tostring(syminfo.mintick) + nl + str.tostring(syminfo.pointvalue) + nl + syminfo.prefix + nl + str.tostring(syminfo.pricescale) + nl + syminfo.root + nl + syminfo.sector + nl + syminfo.session + nl + syminfo.ticker + nl + syminfo.tickerid + nl + syminfo.timezone + nl + syminfo.type + nl + syminfo.volumetype else if syminfo.type == "fund" or syminfo.type == "futures" left := "syminfo.country: " + nl + "syminfo.currency: " + nl + "syminfo.description: " + nl + "syminfo.minmove: " + nl + "syminfo.mintick: " + nl + "syminfo.pointvalue: " + nl + "syminfo.prefix: " + nl + "syminfo.pricescale: " + nl + "syminfo.root: " + nl + "syminfo.session: " + nl + "syminfo.ticker: " + nl + "syminfo.tickerid: " + nl + "syminfo.timezone: " + nl + "syminfo.type: " + nl + "syminfo.volumetype: " right := syminfo.country + nl + syminfo.currency + nl + syminfo.description + nl + str.tostring(syminfo.minmove) + nl + str.tostring(syminfo.mintick) + nl + str.tostring(syminfo.pointvalue) + nl + syminfo.prefix + nl + str.tostring(syminfo.pricescale) + nl + syminfo.root + nl + syminfo.session + nl + syminfo.ticker + nl + syminfo.tickerid + nl + syminfo.timezone + nl + syminfo.type + nl + syminfo.volumetype else if syminfo.type == "forex" or syminfo.type == "crypto" or syminfo.type == "index" left := "syminfo.basecurrency: " + nl + "syminfo.currency: " + nl + "syminfo.description: " + nl + "syminfo.minmove: " + nl + "syminfo.mintick: " + nl + "syminfo.pointvalue: " + nl + "syminfo.prefix: " + nl + "syminfo.pricescale: " + nl + "syminfo.root: " + nl + "syminfo.session: " + nl + "syminfo.ticker: " + nl + "syminfo.tickerid: " + nl + "syminfo.timezone: " + nl + "syminfo.type: " + nl + "syminfo.volumetype: " right := syminfo.basecurrency + nl + syminfo.currency + nl + syminfo.description + nl + str.tostring(syminfo.minmove) + nl + str.tostring(syminfo.mintick) + nl + str.tostring(syminfo.pointvalue) + nl + syminfo.prefix + nl + str.tostring(syminfo.pricescale) + nl + syminfo.root + nl + syminfo.session + nl + syminfo.ticker + nl + syminfo.tickerid + nl + syminfo.timezone + nl + syminfo.type + nl + syminfo.volumetype else if syminfo.type == "bond" or syminfo.type == "economic" left := "syminfo.country: " + nl + "syminfo.description: " + nl + "syminfo.minmove: " + nl + "syminfo.mintick: " + nl + "syminfo.pointvalue: " + nl + "syminfo.prefix: " + nl + "syminfo.pricescale: " + nl + "syminfo.root: " + nl + "syminfo.session: " + nl + "syminfo.ticker: " + nl + "syminfo.tickerid: " + nl + "syminfo.timezone: " + nl + "syminfo.type: " + nl + "syminfo.volumetype: " right := syminfo.country + nl + syminfo.description + nl + str.tostring(syminfo.minmove) + nl + str.tostring(syminfo.mintick) + nl + str.tostring(syminfo.pointvalue) + nl + syminfo.prefix + nl + str.tostring(syminfo.pricescale) + nl + syminfo.root + nl + syminfo.session + nl + syminfo.ticker + nl + syminfo.tickerid + nl + syminfo.timezone + nl + syminfo.type + nl + syminfo.volumetype else left := "syminfo.basecurrency: " + nl + "syminfo.country: " + nl + "syminfo.currency: " + nl + "syminfo.description: " + nl + "syminfo.employees: " + nl + "syminfo.industry: " + nl + "syminfo.minmove: " + nl + "syminfo.mintick: " + nl + "syminfo.pointvalue: " + nl + "syminfo.prefix: " + nl + "syminfo.pricescale: " + nl + "syminfo.recommendations_buy: " + nl + "syminfo.recommendations_buy_strong: " + nl + "syminfo.recommendations_date: " + nl + "syminfo.recommendations_hold: " + nl + "syminfo.recommendations_sell: " + nl + "syminfo.recommendations_sell_strong: " + nl + "syminfo.recommendations_total: " + nl + "syminfo.root: " + nl + "syminfo.sector: " + nl + "syminfo.session: " + nl + "syminfo.shareholders: " + nl + "syminfo.shares_outstanding_float: " + nl + "syminfo.shares_outstanding_total: " + nl + "syminfo.target_price_average: " + nl + "syminfo.target_price_date: " + nl + "syminfo.target_price_estimates: " + nl + "syminfo.target_price_high: " + nl + "syminfo.target_price_low: " + nl + "syminfo.target_price_median: " + nl + "syminfo.ticker: " + nl + "syminfo.tickerid: " + nl + "syminfo.timezone: " + nl + "syminfo.type: " + nl + "syminfo.volumetype: " right := syminfo.basecurrency + nl + syminfo.country + nl + syminfo.currency + nl + syminfo.description + nl + str.tostring(syminfo.employees, format.volume) + nl + syminfo.industry + nl + str.tostring(syminfo.minmove) + nl + str.tostring(syminfo.mintick) + nl + str.tostring(syminfo.pointvalue) + nl + syminfo.prefix + nl + str.tostring(syminfo.pricescale) + nl + str.tostring(syminfo.recommendations_buy) + nl + str.tostring(syminfo.recommendations_buy_strong) + nl + str.format_time(syminfo.recommendations_date, "yyyy-MM-dd", syminfo.timezone) + nl + str.tostring(syminfo.recommendations_hold) + nl + str.tostring(syminfo.recommendations_sell) + nl + str.tostring(syminfo.recommendations_sell_strong) + nl + str.tostring(syminfo.recommendations_total) + nl + syminfo.root + nl + syminfo.sector + nl + syminfo.session + nl + str.tostring(syminfo.shareholders, format.volume) + nl + str.tostring(syminfo.shares_outstanding_float, format.volume) + nl + str.tostring(syminfo.shares_outstanding_total, format.volume) + nl + str.tostring(syminfo.target_price_average, format.mintick) + nl + str.format_time(syminfo.target_price_date, "yyyy-MM-dd", syminfo.timezone) + nl + str.tostring(syminfo.target_price_estimates, format.mintick) + nl + str.tostring(syminfo.target_price_high, format.mintick) + nl + str.tostring(syminfo.target_price_low, format.mintick) + nl + str.tostring(syminfo.target_price_median, format.mintick) + nl + syminfo.ticker + nl + syminfo.tickerid + nl + syminfo.timezone + nl + syminfo.type + nl + syminfo.volumetype if barstate.isfirst table_syminfo.cell(0, 0, left , text_color = color_text, text_halign = text.align_right, text_size = table_size) table_syminfo.cell(1, 0, "---", text_color = color_text, text_halign = text.align_left , text_size = table_size) else if barstate.islastconfirmedhistory table_syminfo.cell_set_text(1, 0, right)
BTC - Hotness Index
https://www.tradingview.com/script/meDpESGA/
dakixr
https://www.tradingview.com/u/dakixr/
13
study
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/ // © dakixr //@version=4 study("BTC - Hotness Index") // Pi Cycle Top Indicator ///////////////////////////////////////// D_111SMA = security(syminfo.tickerid, "1D",sma(close,111)) D_350SMA = security(syminfo.tickerid, "1D",sma(close,350)*2) pi_indicator = (D_111SMA / D_350SMA) pi_plot = pi_indicator[1] < 1 and pi_indicator[0] >= 1? 1 : 0 pi_plot_buy = pi_indicator[1] > 0.35 and pi_indicator[0] <= 0.35? 1 : 0 // Horizontal Lines ///////////////////////////////////////// hline(1, "Sell Zone", color=color.rgb(255, 255, 255, 75)) hline(0.35, "Buy Zone", color=color.rgb(255, 255, 255, 75)) // Ploting ///////////////////////////////////////// plot(pi_plot, color = pi_plot == 1? color.rgb(255, 59, 59) : #476b6b, style = plot.style_histogram) plot(pi_plot_buy, color = pi_plot_buy == 1? color.rgb(82, 255, 59) : #476b6b, style = plot.style_histogram) plot(pi_indicator)
God Candles
https://www.tradingview.com/script/J1UtMw5c-God-Candles/
Vanitati
https://www.tradingview.com/u/Vanitati/
58
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/ // © Vanitati //@version=5 indicator('God Candles', overlay=true) // ----------- Inputs ------------ // God Candle Settings lookbackPeriod = input.int(30, title="Dilution", tooltip ='Higher value will show fewer god candles, but should be stronger. Lower value will show more god candles, but they will be less strong',group ='god candle settings') lineLength = input.int(6, "Line Length", minval=1, maxval=100, group ='god candle settings') godCandleLineColor1 = input(color.rgb(20, 190, 202), "Bullish God candle line", group='god candle settings') godCandleLineColor2 = input(color.rgb(171, 49, 196), "Bearish God candle line", group='god candle settings') showDiamonds = input.bool(true, "Show Diamonds", group ='god candle settings') // Session Time Filter useSessionFilter = input.bool(defval=false, title="Use Session Time Filter", group="Session Time Filter") sessionStartHour = input.int(defval=15, title="Session Start Hour", minval=0, maxval=23, group="Session Time Filter") sessionEndHour = input.int(defval=19, title="Session End Hour", minval=0, maxval=23, group="Session Time Filter") // ----------- God Candle Conditions ------------ //basic engulfing maths bodyBarPrevious = math.abs(close[1] - open[1]) bodyBarCurrent = math.abs(close - open) bullishEngulfing = (low <= low[1]) and (close >= high[1]) bearishEngulfing = (high >= high[1]) and (close <= low[1]) //god candle volume calculations sumVolume = math.sum(volume, 10) av = sumVolume / 10 valueVolume = volume * (high - low) hivalueVolume = ta.highest(valueVolume, 10) va = volume >= av * 2 or valueVolume >= hivalueVolume ? 1 : (volume >= av * 1.5 ? 2 : 0) isBull = close > open //god candle colour settings CUColor = color.lime CDColor = color.red //engulfing calculations lowestLow = ta.lowest(low[1], lookbackPeriod) highestHigh = ta.highest(high[1], lookbackPeriod) bullishEngulfingClimax = bullishEngulfing and (va == 1) and isBull and (low < lowestLow) bearishEngulfingClimax = bearishEngulfing and (va == 1) and not isBull and (high > highestHigh) bullishEngulfingDiamond = bullishEngulfing and bodyBarCurrent >= bodyBarPrevious * 2 and low[1] < open and low < open and low[1] < close and low < close bearishEngulfingDiamond = bearishEngulfing and bodyBarCurrent >= bodyBarPrevious * 2 and high[1] > open and high > open and high[1] > close and high > close // Determine if the current bar's time is within the session newDay = sessionEndHour < sessionStartHour isInSession = useSessionFilter ? (newDay ? ((hour(time) >= sessionStartHour) or (hour(time) < sessionEndHour)) : ((hour(time) >= sessionStartHour) and (hour(time) < sessionEndHour))) : true // ----------- Plotting ------------ //candles barcolor(isInSession and bullishEngulfingClimax ? CUColor : isInSession and bearishEngulfingClimax ? CDColor : na) //Session filter background colour bgcolor(useSessionFilter and isInSession ? color.new(color.gray, 90) : na, title="Session Background") //god candle plotting if isInSession and bullishEngulfingClimax line.new(x1 = bar_index, y1 = low + (open - low) / 2, x2 = bar_index + lineLength, y2 = low + (open - low) / 2, color = godCandleLineColor1, width = 1) if isInSession and bearishEngulfingClimax line.new(x1 = bar_index, y1 = high - (high - open) / 2, x2 = bar_index + lineLength, y2 = high - (high - open) / 2, color = godCandleLineColor2, width = 1) //Dots plotting plotshape(series=isInSession and bullishEngulfing and bullishEngulfingDiamond and not bullishEngulfingClimax, title='Pressure up', location=location.belowbar, color=showDiamonds ? color.rgb(29, 155, 177) : na, style=shape.diamond) plotshape(series=isInSession and bearishEngulfing and bearishEngulfingDiamond and not bearishEngulfingClimax, title='Pressure down', location=location.abovebar, color=showDiamonds ? color.rgb(171, 46, 196) : na, style=shape.diamond) // Alert conditions alertcondition(bullishEngulfingClimax or bearishEngulfingClimax, title='God Candle', message='God candle')
Volume-Price Diff
https://www.tradingview.com/script/GF0sMTcF-volume-price-diff/
siq_trader
https://www.tradingview.com/u/siq_trader/
16
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/ // © siq_trader //@version=5 indicator("Volume-Price Diff", overlay = true) var bool initialized = false varip int volumeChanges = 0 varip int priceChanges = 0 varip lastPrice = close varip diffPercentage = 0 var color startLabelBgColor = #ffffff var color startLabelTextColor = #8d8c8c var color currentInfoLabelBgColor = #ece2e2 var color currentInfoLabelTextColor = #2c455a if barstate.isnew volumeChanges := 0 priceChanges := 0 diffPercentage := 0 lastPrice := close if barstate.isrealtime if not initialized label.new(bar_index - 1, low, yloc = yloc.belowbar, color = startLabelBgColor, textcolor = startLabelTextColor, text = "start", style = label.style_arrowup) initialized := true volumeChanges += 1 if close != lastPrice priceChanges += 1 diffPercentage := ((volumeChanges - priceChanges) / volumeChanges) * 100 if barstate.isconfirmed label.new(bar_index, high, color = color.new(color.white, 90), tooltip = "Volume changes: " + str.tostring(volumeChanges) + "\n" + "Price changes: " + str.tostring(priceChanges) + "\n" + "Diff: " + str.tostring(diffPercentage, format.percent), size = size.tiny) else label.new(bar_index, high, yloc = yloc.abovebar, color = currentInfoLabelBgColor, textcolor = currentInfoLabelTextColor, text = "Volume changes: " + str.tostring(volumeChanges) + "\n" + "Price changes: " + str.tostring(priceChanges) + "\n" + "Diff: " + str.tostring(diffPercentage, format.percent)) plot(volumeChanges, color = color.new(color.white, 100), display = display.status_line) plot(priceChanges, color = color.new(color.white, 100), display = display.status_line) plot(diffPercentage, color = color.new(color.white, 100), display = display.status_line)
BETA Benchmark - Tables!
https://www.tradingview.com/script/bDseVY2c-BETA-Benchmark-Tables/
Mishari_Alr
https://www.tradingview.com/u/Mishari_Alr/
1
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/ // © Mishari_Algos //@version=5 indicator(title='BETA Benchmark - Tables!', overlay=false, precision = 2) smooth = input.int(1, title="Smooth") period1 = input.int(30, title="First Period") period2 = input.int(60, title="Second Period") period3 = input.int(90, title="Third Period") period4 = input.int(120, title="Fourth Period") usePeriod5 = input.bool(false, title="Use Fifth Period?") period5 = usePeriod5 ? input.int(180, title="Fifth Period") : na return_percent(src) => ta.change(src) * 100 / src[1] instrument = ta.ema(close, smooth) benchmark = request.security(input.symbol('CRYPTOCAP:TOTAL', title="Benchmark"), timeframe.period, ta.ema(close, smooth)) inst_return = return_percent(instrument) bench_return = return_percent(benchmark) // Function to calculate beta for given length calculate_beta(_length) => avg_inst_return = ta.sma(inst_return, _length) avg_bench_return = ta.sma(bench_return, _length) sum = 0.0 varianceSum = 0.0 for idx = 0 to _length - 1 inst_variance = inst_return[idx] - avg_inst_return bench_variance = bench_return[idx] - avg_bench_return sum := sum + inst_variance * bench_variance varianceSum := varianceSum + bench_variance * bench_variance covariance = sum / (_length - 1) _beta = covariance / (varianceSum / (_length - 1)) _beta beta1 = calculate_beta(period1) beta2 = calculate_beta(period2) beta3 = calculate_beta(period3) beta4 = calculate_beta(period4) beta5 = usePeriod5 ? calculate_beta(period5) : na // Calculate average beta average_beta = usePeriod5 ? (beta1 + beta2 + beta3 + beta4 + beta5) / 5 : (beta1 + beta2 + beta3 + beta4) / 4 // Plot the average beta plot(average_beta, color=color.blue, title="Average Beta") // Display betas in a table var table betas = table.new(position.top_right, usePeriod5 ? 6 : 5, 2) table.cell(betas, 0, 0, "Period", bgcolor=color.gray, text_color=color.white) table.cell(betas, 0, 1, "Beta Value", bgcolor=color.gray, text_color=color.white) table.cell(betas, 1, 0, str.tostring(period1) + " Days", bgcolor=color.silver, text_color=color.black) table.cell(betas, 1, 1, str.tostring(math.round(beta1,2)), bgcolor=color.silver, text_color=color.black) table.cell(betas, 2, 0, str.tostring(period2) + " Days", bgcolor=color.silver, text_color=color.black) table.cell(betas, 2, 1, str.tostring(math.round(beta2,2)), bgcolor=color.silver, text_color=color.black) table.cell(betas, 3, 0, str.tostring(period3) + " Days", bgcolor=color.silver, text_color=color.black) table.cell(betas, 3, 1, str.tostring(math.round(beta3,2)), bgcolor=color.silver, text_color=color.black) table.cell(betas, 4, 0, str.tostring(period4) + " Days", bgcolor=color.silver, text_color=color.black) table.cell(betas, 4, 1, str.tostring(math.round(beta4,2)), bgcolor=color.silver, text_color=color.black) if usePeriod5 table.cell(betas, 5, 0, str.tostring(period5) + " Days", bgcolor=color.silver, text_color=color.black) table.cell(betas, 5, 1, str.tostring(math.round(beta5,2)), bgcolor=color.silver, text_color=color.black)
Gap SMA
https://www.tradingview.com/script/1Ao7kuCA-Gap-SMA/
str0zzapreti
https://www.tradingview.com/u/str0zzapreti/
1
study
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/ // © jdavenport416 //@version=5 indicator("Gap SMA", overlay=true) n = input(5, title="Number of gaps to consider") multiplier = input.float(1.5, title="Multiplier for Gap", step=0.1) var float avg_gap_up = na var float avg_gap_down = na gap_ups = open > close[1] ? (open - close[1]) * multiplier : na gap_downs = open < close[1] ? (close[1] - open) * multiplier : na avg_gap_up := ta.sma(na(gap_ups) ? avg_gap_up[1] : gap_ups, n) avg_gap_down := ta.sma(na(gap_downs) ? avg_gap_down[1] : gap_downs, n) if bar_index > n avg_gap_up := avg_gap_up avg_gap_down := avg_gap_down close_plus_gap_up_avg = close + avg_gap_up close_minus_gap_down_avg = close - avg_gap_down plot(close_plus_gap_up_avg, color=color.green, title="Close + Avg Gap Up") plot(close_minus_gap_down_avg, color=color.red, title="Close - Avg Gap Down") // Alert conditions alertcondition(close > close_plus_gap_up_avg, "Close Crosses Above Avg Gap Up", "Close crosses above the 'Close + Avg Gap Up' line") alertcondition(close < close_minus_gap_down_avg, "Close Crosses Below Avg Gap Down", "Close crosses below the 'Close - Avg Gap Down' line")
[KVA]Body Percentage Counter
https://www.tradingview.com/script/y6jGP6Ut-KVA-Body-Percentage-Counter/
Kamvia
https://www.tradingview.com/u/Kamvia/
1
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/ // © Kamvia //@version=5 indicator("[KVA]Body Percentage Counter ") isGreen(c,o) => c > o isRed(c,o) => c < o //enter values here float[] greenPercents = array.from(0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.1,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,0.19,0.2,0.3, 0.4,0.5,0.6,0.7,0.8,0.9,1,1.3,1.5,2,3,4,5,6,7,8,9,10,15,20) // helper functions percent_change(new, old) => 100 * (new - old) / old calc_price_diff(entry_amt, price_change_percent) => entry_amt + (price_change_percent * entry_amt) formatPercent(n) => str.format("{0,number,percent}", n) formatNumber(n) => str.format("{0,number}", n) formatCurrency(n) => str.format("{0,number,currency}", n) // table functions buildBodyRows(pb, greenPercents, greenCountByThreshold , num_entries,r) => for i = 0 to num_entries-1 curr_amt = array.get(greenCountByThreshold , i) table.cell(table_id = pb, column = i, row = r, text = str.tostring(curr_amt), text_color = color.black, text_halign=text.align_left) buildTotalRow(pb, greenCountByThreshold , redCountByThreshold , greenPercents) => num_entriesp = array.size(greenPercents) for i = 0 to num_entriesp-1 curr_amtp = array.get(greenPercents, i) total = array.get(greenCountByThreshold , i) + array.get(redCountByThreshold , i) table.cell(table_id = pb, column = i, row = 3, text = str.tostring(total), text_color = color.black) buildHeaderRow(pb,greenPercents) => num_entriesp = array.size(greenPercents) for i = 0 to num_entriesp-1 curr_amtp = array.get(greenPercents, i) table.cell(table_id = pb, column = i, row = 0, text = str.tostring(curr_amtp), text_color = color.black) buildTable(num_entries, greenPercents, greenCountByThreshold ,redCountByThreshold ) => num_columns = array.size(greenPercents) var pb = table.new(position = position.top_right, columns = num_columns, rows = num_entries+2) buildHeaderRow(pb,greenPercents) buildBodyRows(pb, greenPercents, greenCountByThreshold , num_entries,1) buildBodyRows(pb, greenPercents, redCountByThreshold , num_entries,2) buildTotalRow(pb, greenCountByThreshold , redCountByThreshold , greenPercents) /////////////////////////////////////////////////////////////////////////////// // main num_entries = array.size(greenPercents) // get current amounts greenCountByThreshold = array.new_float(num_entries,0) redCountByThreshold = array.new_float(num_entries,0) // create table if barstate.islast for barindex=0 to 5000 price_change_percent = math.abs(percent_change(close[barindex], open[barindex])) if isGreen(close[barindex],open[barindex]) for i = 0 to num_entries-1 lv = array.get(greenCountByThreshold , i) if i==0 if price_change_percent < array.get(greenPercents, i) array.set(greenCountByThreshold , i, lv+1) else if (price_change_percent >=array.get(greenPercents, i-1)) and (price_change_percent < array.get(greenPercents, i)) array.set(greenCountByThreshold , i, lv+1) if isRed(close[barindex],open[barindex]) for i = 0 to num_entries-1 lv = array.get(redCountByThreshold , i) if i==0 if price_change_percent < array.get(greenPercents, i) array.set(redCountByThreshold , i, lv+1) else if (price_change_percent >=array.get(greenPercents, i-1)) and (price_change_percent < array.get(greenPercents, i)) //lv1 = array.get(greenCountByThreshold , i) array.set(redCountByThreshold , i, lv+1) buildTable(num_entries, greenPercents, greenCountByThreshold ,redCountByThreshold ) printDebug(txt) => var table t = table.new(position.bottom_right, 1, 1),table.cell(t, 0, 0, str.tostring(txt), bgcolor = color.yellow)
50 EMA - Multi 1D 4H 1H
https://www.tradingview.com/script/YO1Y3Jmd-50-EMA-Multi-1D-4H-1H/
rrchico
https://www.tradingview.com/u/rrchico/
2
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/ // © rrchico //@version=5 indicator("50 EMA - Multi 1D 4H 1H", overlay=true, timeframe="60") //inputs plot1DVisibility = input.bool(true, "50D Visible") plot1Dcolor = input.color(color.yellow, title="5DD EMA") plot4HVisibility = input.bool(true, "50 4H Visible") plot4Hcolor = input.color(color.lime, title="50 4H EMA") plot1HVisibility = input.bool(true, "50 1H Visible") plot1Hcolor = input.color(color.fuchsia, title="50 1H EMA") source = close emaLength = 50 ema50D = ta.ema(source, 24 * emaLength) ema504H = ta.ema(source, 4 * emaLength) ema50 = ta.ema(source, emaLength) out50dLength = request.security(syminfo.tickerid, "60", ema50D) out504hLength = request.security(syminfo.tickerid, "60", ema504H) out501hLength = request.security(syminfo.tickerid, "60", ema50) out50dDisplay = display.all out504hDisplay = display.all out501hDisplay = display.all if plot1DVisibility == false out50dDisplay := display.none if plot4HVisibility == false out504hDisplay := display.none if plot1HVisibility == false out501hDisplay := display.none ema50dPlot = plot(out50dLength, color=plot1Dcolor, title="50D EMA", display = out50dDisplay) ema504hPlot = plot(out504hLength, color=plot4Hcolor, title="50 4H EMA", display = out504hDisplay) ema501hPlot = plot(out501hLength, color=plot1Hcolor, title="50 1H EMA", display = out501hDisplay)
Extended Engulfing Candle
https://www.tradingview.com/script/NI5jqX5h/
MentalGap
https://www.tradingview.com/u/MentalGap/
28
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/ // © MentalGap //@version=5 indicator("Consecutive Engulfing Candle", overlay=true) var int consecutiveDown = 0 var int consecutiveUp = 0 var float HH = na //HighestHigh of consecutive down candle var float LL = na var bool uDisplayed = false //trace BullishEngulfing label plot status var bool dDisplayed = false var bool isBullishEngulfing = false var bool isBearishEngulfing = false barup = close > close[1] bardown = close < close[1] if (bardown) consecutiveDown := consecutiveDown + 1 if (na(HH) or barup[1]) HH := high if (barup) consecutiveUp := consecutiveUp + 1 if (na(LL) or bardown[1]) LL := low // Check for Bullish Engulfing pattern if barup and close > HH and not uDisplayed uDisplayed := true dDisplayed := false isBullishEngulfing := true consecutiveDown := 0 HH := na else isBullishEngulfing := false //Bearish Engulfing if bardown and close < LL and not dDisplayed dDisplayed := true uDisplayed := false isBearishEngulfing := true consecutiveUp := 0 LL := na else isBearishEngulfing := false plotshape(series=isBullishEngulfing, title="Bullish Engulfing", location=location.belowbar, color=color.new(color.green, 100), textcolor= input.color(color.green, "BullsihEngulfing"),style=shape.labelup, text="U") plotshape(series=isBearishEngulfing, title="Bearish Engulfing", location=location.abovebar, color=color.new(color.red, 100), textcolor= input.color(color.red, "BearishEngulfing"), style=shape.labeldown, text="D")
SOLANA Performance & Volatility Analysis BB%
https://www.tradingview.com/script/MO4w0UuK-SOLANA-Performance-Volatility-Analysis-BB/
Volatility_Vibes
https://www.tradingview.com/u/Volatility_Vibes/
15
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/ // © Volatility_Vibes //@version=5 indicator(title='SOLANA Performance & Volatility Analysis BB%', shorttitle='SOL P&V Analysis BB%', format=format.price, precision=2) // Inputs ChartLine = input(title='SOLANA PRICE (SOLUSD)', defval=true) SOLINVERSE = input(title='SOLANA INVERRSE (SOLUSDT.3S)', defval=true) SOLVOL = input(title='SOLANA VOLATILITY (SOLUSDSHORTS)', defval=true) BITCOIN24HVOLATILITY = input(title='BITCOIN 24 HOUR HISTORICAL VOLATILITY(BVOL24H)', defval=false) // Define variables res = timeframe.period source = close SOLANAINVERSESymbol = input('SOLUSDT.3S') xInverse = request.security(SOLANAINVERSESymbol, res, source) SOLANAVOLSymbol = input('SOLUSDSHORTS') yVolatility = request.security(SOLANAVOLSymbol, res, source) BVOL24Symbol = input('BVOL24H') zBTC24HVolatility = request.security(BVOL24Symbol, res, source) // BB length = input.int(20, minval=1) //src = close mult = input.float(2.0, minval=0.001, maxval=50) // SOLANA PRICE basisSOLANAPRICE = ta.sma(close, length) devSOLANAPRICE = mult * ta.stdev(close, length) upperSOLANAPRICE = basisSOLANAPRICE + devSOLANAPRICE lowerSOLANAPRICE = basisSOLANAPRICE - devSOLANAPRICE normalizedPrice = (close - lowerSOLANAPRICE) / (upperSOLANAPRICE - lowerSOLANAPRICE) plot(ChartLine ? normalizedPrice : na, color=color.new(color.blue, 0), style=plot.style_stepline, title='Price') // SOLANA INVERSE basisSOLANAINVERSE = ta.sma(xInverse, length) devSOLANAINVERSE = mult * ta.stdev(xInverse, length) upperSOLANAINVERSE = basisSOLANAINVERSE + devSOLANAINVERSE lowerSOLANAINVERSE = basisSOLANAINVERSE - devSOLANAINVERSE normalizedInverse = (xInverse - lowerSOLANAINVERSE) / (upperSOLANAINVERSE - lowerSOLANAINVERSE) plot(SOLINVERSE ? normalizedInverse : na, color=color.new(color.red, 0), style=plot.style_stepline, title='SOLANA INVERSE') // SOLANA VOLATILITY basisSOLANAVOL = ta.sma(yVolatility, length) devSOLANAVOL = mult * ta.stdev(yVolatility, length) upperSOLANAVOL = basisSOLANAVOL + devSOLANAVOL lowerSOLANAVOL = basisSOLANAVOL - devSOLANAVOL normalizedVolatility = (yVolatility - lowerSOLANAVOL) / (upperSOLANAVOL - lowerSOLANAVOL) plot(SOLVOL ? normalizedVolatility : na, color=color.new(color.green, 0), style=plot.style_stepline, title='SOLANA VOLATILITY') // BITCOIN 24HR VOLATILITY basisBTC24HVOL = ta.sma(zBTC24HVolatility, length) devBTC24HVOL = mult * ta.stdev(zBTC24HVolatility, length) upperBTC24HVOL = basisBTC24HVOL + devBTC24HVOL lowerBTC24HVOL = basisBTC24HVOL - devBTC24HVOL normalizedBTC24HVolatility = (zBTC24HVolatility - lowerBTC24HVOL) / (upperBTC24HVOL - lowerBTC24HVOL) plot(BITCOIN24HVOLATILITY ? normalizedBTC24HVolatility : na, color=color.new(#ffffff, 0), style=plot.style_stepline, title='BITCOIN 24HR VOLATILITY') // Plot bands band1 = hline(0.80, color=color.red, linestyle=hline.style_dashed) band2 = hline(0.60, color=color.gray, linestyle=hline.style_dashed) band3 = hline(0.40, color=color.gray, linestyle=hline.style_dashed) band4 = hline(0.20, color=color.red, linestyle=hline.style_dashed) fill(band2, band3, color=color.new(color.teal, 90))
每根单位K线时间
https://www.tradingview.com/script/1tSqJT0F/
qqqq95
https://www.tradingview.com/u/qqqq95/
3
study
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/ // © qqqq95 //@version=5 indicator("每根单位K线时间",overlay = true) second_tostr(s) => h = (s - s%(3600*1000))/(3600*1000) h_t = (s - s%(3600*1000)) min = ((s-h_t) - (s-h_t)%(60*1000))/(60*1000) str = str.tostring(h)+"h"+str.tostring(min)+'min' str label.new(time[1],close,xloc = xloc.bar_time,text = second_tostr(time -time[1])) plot(close)
Breakout mode patterns [yohtza]
https://www.tradingview.com/script/3Fro4IUz-Breakout-mode-patterns-yohtza/
yohtza
https://www.tradingview.com/u/yohtza/
16
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/ // © yohtza //@version=5 indicator("Breakout mode patterns [yohtza]", overlay = true) textColor = input.color(color.gray,"Text Color") oo_condition = high[1] >= high[2] and low[1] <= low[2] and high[2] >= high[3] and low[2] <= low[3] ii_condition = high[1] <= high[2] and low[1] >= low[2] and high[2] <= high[3] and low[2] >= low[3] ioi_condition = high[1] <= high[2] and low[1] >= low[2] and high[2] >= high[3] and low[2] <= low[3] if oo_condition label.new(bar_index -1, na, yloc = yloc.abovebar, text='oo', size= size.large, textcolor = color.gray, color = color.new(color.red, 100)) if ii_condition label.new(bar_index -1, na, yloc = yloc.abovebar, text='ii', size= size.large, textcolor = color.gray, color = color.new(color.red, 100)) if ioi_condition label.new(bar_index -2, na, yloc = yloc.abovebar, text='ioi', size= size.large, textcolor = color.gray, color = color.new(color.red, 100))
IU SIP CALCULATOR
https://www.tradingview.com/script/rlrRGVnI-IU-SIP-CALCULATOR/
Strategy_coders
https://www.tradingview.com/u/Strategy_coders/
7
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/ // © shivammandrai //@version=5 indicator("IU SIP", overlay = true ) ///////// WARNING if timeframe.period != "M" runtime.error("Please Go To monthly(M) timeframe ") ///// SIP GREEN SIGNAL go_SIP = true //// USER INPUTS Amount = input.int(5000, "Enter the SIP Amount") start_month = input.int(1, "Starting Month ?", minval = 1, maxval = 12) start_year = input.int(2022, "Startimg Year ?", minval = 1900, maxval = 2100) ending_month = input.int(12, "Ending Month ?", minval = 1, maxval = 12) ending_year = input.int(2022, "Ending Year ?", minval = 1900, maxval = 2100) ///// COLOR VARIABLES table_color = input.color(color.gray, 'Table Color') text_color = input.color(color.white, "Text Color") frame_color = input.color(color.green, "Frame Color ") tranc = input.int(30, "Enter the transparency", minval = 0, maxval = 100) var monthly_close = array.new<float>() var monthly_open = array.new<float>() var time_line = array.new<string>() var string text1 = na var string text2 = na monthly_Close = request.security(syminfo.tickerid, "M", close) monthly_Open = request.security(syminfo.tickerid, "M", open) var stocks = array.new<float>() if go_SIP == true and timeframe.period == "M" array.push(monthly_close, monthly_Close) array.push(monthly_open, monthly_Open ) text1 := str.tostring(month) + str.tostring(year) array.push(time_line, text1) array.push(stocks, (Amount / monthly_Open)) //// MATCHING INDEX VALUE WITH INPUTS string m1 = str.tostring(start_month) + str.tostring(start_year) string m2 = str.tostring(ending_month) + str.tostring(ending_year) /////// CREATING VARIABLES WITH na int getting_index_start = na int getting_index_end = na float [] slicing_array1 = na float open_value = na float average = na float amount_invt = na float number_of_stocks = na float profit_value = na float portfolio_value = na float profit_value_pec = na float returns = na float end_close = na float monthly_returns = na float yearly_returns = na ///// SEEING IF THE ARRAY CONTAIN THE RIGHT VALUE OR NOT float first_open = na float last_open = na float [] slicing_stocks = na float stocks_no = na if year >= ending_year and month >= ending_month and barstate.isconfirmed //// GETTIMG THE INDEXOF VALUE getting_index_start := array.indexof(time_line, m1) getting_index_end := array.indexof(time_line, m2) ////// GETTING THE VALUES THROUGH SLICING ARRAYS slicing_array1 := array.slice(monthly_open, (getting_index_start), (getting_index_end +1)) slicing_stocks := array.slice(stocks, getting_index_start, (getting_index_end + 1)) end_close := array.get(monthly_close, getting_index_end) average := array.avg(slicing_array1) returns := end_close - average //// CALCULATING INVESTMENT VALUE amount_invt := (array.size(slicing_array1)) * Amount /// CAL PORTFOLIO VALUE stocks_no := array.sum(slicing_stocks) profit_value := stocks_no * returns portfolio_value := amount_invt + profit_value profit_value_pec := profit_value / (amount_invt * 0.01) first_open := array.get(slicing_array1,0) last_open := array.last(slicing_array1) monthly_returns := profit_value_pec / (array.size(slicing_array1)) yearly_returns := profit_value_pec / (array.size(slicing_array1) / 12) ///MAKING THE TABLE var table mytable = table.new(position = position.top_right,columns = 8, rows = 8, bgcolor = color.new(table_color, tranc), border_width = 3, frame_color = color.new(table_color, tranc), frame_width = 5 ) ///// CREARING TEXTS text_1 = "Avrage Buy Price " + "\n " + str.tostring(math.round(average, 2)) text_2 = "Number of Stocks " + "\n " + str.tostring(math.floor(stocks_no)) text3 = "Profit Value" + "\n " + str.tostring(math.round(profit_value, 2)) text4 = "Profit Value in % " + "\n " + str.tostring(math.round(profit_value_pec, 2)) + "%" text5 = "Amount Invested " + "\n " + str.tostring(amount_invt) text6 = "Portfolio value" + "\n " + str.tostring(math.round(portfolio_value, 2)) text7 = "yearly_returns " + "\n " + str.tostring(math.round(yearly_returns, 2)) + "%" text8 = "monthly_returns " + "\n " + str.tostring(math.round(monthly_returns, 2)) + "%" text9 = profit_value > 0 ? "Performace is : 😊 " : "Performace is : 😓 " table.cell(mytable, 1,1,text = "SIP OF " + str.tostring(syminfo.tickerid), text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 1,2,text = "", text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 1,3,text = "", text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 2,1,text = text_1, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 2,2,text = text_2, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 2,3,text = text3, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 3,1,text = text4, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 3,2,text = text5, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 3,3,text = text6, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 1,4,text = text7, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 2,4,text = text8, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.cell(mytable, 3,4,text = text9, text_color = text_color, bgcolor = profit_value > 0 ? color.new(frame_color, tranc) : color.new(color.red, tranc)) table.merge_cells(mytable, start_column = 1, start_row = 1, end_column = 1, end_row = 3)
Worm *Public*
https://www.tradingview.com/script/g1ODrArg-Worm-Public/
aidenhawkins2004
https://www.tradingview.com/u/aidenhawkins2004/
25
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/ // ©aidenhawkins2004 //@version=5 indicator("Worm (Clean)" , overlay = true) //__ Inputs //Titles SettingTitle1 = "Indicator Settings" , SettingTitle2 = "Backtest Settings" , SettingTitle3 = "Color Settings" IntegerTitle1 = "Alpha" , IntegerTitle2 = "Gap between indicator and current price" , IntegerTitle3 = "Gap between price and Indicator" Color1 = "Buy Color" , Color2 = "Sell Color" , Color3 = "Wait Color" Color1Tooltip = "Default Green" , Color2Tooltip = "Default Red" , Color3Tooltip = "Default Yellow" AlertTitle1 = "Red Worm" , AlertTitle2 = "Green Worm" , AlertTitle3 = "Yellow Zig Zag" Location1 = "Momentum Indicator display above price?" , LocationTooltip1 = "On higher timeframes, this will revert to tracking the price." Location2 = "Momentum Indicator displays below price?" , LocationTooltip2 = "On higher timeframes, this will revert to tracking the price. Is the default option." Location3 = "Momentum Indicator displays at price?" , LocationTooltip3 = "Other options revert to this by default on higher timeframes." IndicatorTitle1 = "Trailing Momentum" , IndicatorTitle2 = "Wiggly Worm" //Toggleable Inputs Above_price = input.bool (defval = false , title = Location1 , group = SettingTitle1 , tooltip = LocationTooltip1 , confirm = true) Below_price = input.bool (defval = true , title = Location2 , group = SettingTitle1 , tooltip = LocationTooltip2 , confirm = true) At_price = input.bool (defval = false , title = Location3 , group = SettingTitle1 , tooltip = LocationTooltip3 , confirm = true) Buy_Color = input.color (defval = color.green , title = Color1 , group = SettingTitle3 , display = display.all , confirm = true) Sell_Color = input.color (defval = color.red , title = Color2 , group = SettingTitle3 , display = display.all , confirm = true) Wait_Color = input.color (defval = color.yellow , title = Color3 , group = SettingTitle3 , display = display.all , confirm = true) AlphaLine = input.float (defval = 0.10 , title = IntegerTitle1 , minval = 0 , maxval = 100 , step = 0.1 , group = SettingTitle1 , confirm = true) Gap = input.float (defval = 1.05 , title = IntegerTitle3 , minval = 1 , maxval = 100 , step = 0.1 , group = SettingTitle1 , confirm = true) //Bool Inputs & Source HighlightCrossovers = true , ApplyNorm = true , ColorChange = true Tru = true , Src = close , SourceLine = hl2 //Indicator Values Length = 20 , LengthKC = 20 , MulIntegerTitle1 = 2.0 , MultKC = 1.5 L0Line = 0.0 , L0 = 0.0 , L1Line = 0.0 , L1 = 0.0 L2Line = 0.0 , L2 = 0.0 , L3Line = 0.0 , L3 = 0.0 CU = 0.0 , CD = 0.0 , Half_Price = 0.0 //*************************\\ //__ Momentum Calculations HC = math.max(high , nz(close[1])) , OC = (open + nz(close[1])) / 2 LC = math.min(low , nz(close[1])) , Gamma = 1 - AlphaLine L0 := (1 - Gamma) * SourceLine + Gamma * nz(L0[1]) , L1 := -Gamma * L0 + nz(L0[1]) + Gamma * nz(L1[1]) L2 := -Gamma * L1 + nz(L1[1]) + Gamma * nz(L2[1]) , L3 := -Gamma * L2 + nz(L2[1]) + Gamma * nz(L3[1]) lrsi = (L0 + 2 * L1 + 2 * L2 + L3) / 6 CU := (L0 >= L1 ? L0 - L1 : 0 ) + (L1 >= L2 ? L1 - L2 : 0 ) + (L2 >= L3 ? L2 - L3 : 0 ) CD := (L0 >= L1 ? 0 : L1 - L0) + (L1 >= L2 ? 0 : L2 - L1) + (L2 >= L3 ? 0 : L3 - L2) lrsi := CU + CD != 0 ? ApplyNorm ? 100 * CU / (CU + CD) : CU / (CU + CD) : 0 mult = ApplyNorm ? 100 : 1 ob = 0.75 * mult middle = 0.5 * mult os = 0.25 * mult //*************************\\ //__ Calculate BB Source = close , Basis = ta.sma (Source, Length) , Dev = MultKC * ta.stdev(Source, Length) UpperBB = Basis + Dev , LowerBB = Basis - Dev //*************************\\ //__ Calculate KC Range_1 = Tru ? ta.tr : high - low , Ma = ta.sma (Source , LengthKC) , Rangema = ta.sma (Range_1 , LengthKC) UpperKC = Ma + Rangema * MultKC , LowerKC = Ma - Rangema * MultKC SqzOn = LowerBB > LowerKC and UpperBB < UpperKC SqzOff = LowerBB < LowerKC and UpperBB > UpperKC NoSqz = SqzOn == false and SqzOff == false Val = ta.linreg (Source - math.avg(math.avg(ta.highest(high, LengthKC), ta.lowest(low, LengthKC)), ta.sma(close, LengthKC)), LengthKC, 0) Buy = Val > 0 and ta.barssince(ta.crossover(lrsi, os)) < ta.barssince(ta.crossunder(lrsi, ob)) Iff_1 = Val > nz(Val[1]) ? Buy_Color : Wait_Color Iff_2 = Val < nz(Val[1]) ? Sell_Color : Wait_Color Bcolor = Val > 0 ? Iff_1 : Iff_2 Scolor = NoSqz ? color.blue : Buy ? Buy_Color : Sell_Color L0Line := (1-Gamma) * SourceLine + Gamma * nz(L0Line[1]) L1Line := -Gamma * L0Line + nz(L0Line[1]) + Gamma * nz(L1Line[1]) L2Line := -Gamma * L1Line + nz(L1Line[1]) + Gamma * nz(L2Line[1]) L3Line := -Gamma * L2Line + nz(L2Line[1]) + Gamma * nz(L3Line[1]) LagF = (L0Line + 2 * L1Line + 2 * L2Line + L3Line) / 6 //*************************\\ //__ Control colour Color = ColorChange ? (LagF > LagF[1] ? Buy_Color : Sell_Color) : Wait_Color Ycol = 10 if close > close[1] Ycol := Ycol + 1 if close < close[1] Ycol := Ycol - 1 //*************************\\ //__ Red -->> Green var line LowestRedLine = na , var line HighestGreenLine = na var float LowestRedPrice = na , var float HighestGreenPrice = na if Color == Sell_Color LowestRedPrice := math.min(LowestRedPrice , low) line.set_xy1 (LowestRedLine , bar_index[1] , LowestRedPrice ) line.set_xy2 (LowestRedLine , bar_index , LowestRedPrice ) if Color == Buy_Color HighestGreenPrice := math.max(HighestGreenPrice , high) line.set_xy1 (HighestGreenLine , bar_index[1] , HighestGreenPrice) line.set_xy2 (HighestGreenLine , bar_index , HighestGreenPrice) //_Location for Wave Line (above / below price) if Above_price == true Half_Price := close * Gap if Below_price == true Half_Price := close / Gap if At_price == true Half_Price := 0.0 //__ Plot Wave Line plot(Val + Half_Price, title=IndicatorTitle1, color=Bcolor, style=plot.style_stepline, linewidth=4, display = display.all) //__ Plot Worm plot(LagF, title=IndicatorTitle2, linewidth=1, color=color.from_gradient(close, low, high, color.new(Color, Ycol), color.new(Color, Ycol)), style=plot.style_stepline, display = display.all) alertcondition (Color == Sell_Color , title = AlertTitle1, message = AlertTitle1) alertcondition (Color == Buy_Color , title = AlertTitle2, message = AlertTitle2) alertcondition (Bcolor == Wait_Color , title = AlertTitle3, message = AlertTitle3) //*************************\\..........// EXPERIMENT SECTION \\..........//*************************\\ //*************************\\
pips bar
https://www.tradingview.com/script/NSqb6ZI0-pips-bar/
Swingbird
https://www.tradingview.com/u/Swingbird/
4
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/ // © Swingbird //@version=5 indicator("pips bar", overlay = true) pips = input.int(20, 'pips') col_bar = input.color(color.orange, 'color') wid_bar = input.int(4, 'bar width', [1,2,3,4]) xbars = input.int(10, 'gaps between the last bar') bar_pos = input.string('top', 'position', ['top','middle','bottom']) // pips and bar length tkr = syminfo.ticker pip = str.pos(tkr, 'J')==3 ? 0.01: 0.0001 bar_len = pip * pips // virtical position lbt = chart.left_visible_bar_time rbt = chart.right_visible_bar_time var float hp = na var float lp = na if time == lbt hp := high lp := low if time > lbt and time <= rbt hp := hp < high ? high: hp lp := lp > low ? low : lp var float y1 = na var float y2 = na if bar_pos == 'top' y1 := hp - bar_len y2 := hp else if bar_pos == 'middle' y1 := (hp+lp)/2 - bar_len/2 y2 := (hp+lp)/2 + bar_len/2 else y1 := lp y2 := lp + bar_len // horizontal position dt = time - nz(time[1]) regular_dt = math.min(dt, nz(dt[1], dt)) var arr_dt = array.new_int() if dt > nz(dt[1]) arr_dt.push(dt) var int wk_interval = 0 if arr_dt.size()>2 wk_interval := arr_dt.get(2) weekend_time = request.security(syminfo.tickerid, 'W', time_close) int weekend_adjust = 0 if session.islastbar and time_close == weekend_time weekend_adjust := wk_interval pb_time = time + regular_dt*xbars + weekend_adjust // pips bar and label var pipsbar = line.new(0,0,0,0,xloc.bar_time, color = col_bar, width = wid_bar) var la = label.new(0,0, str.tostring(pips) + ' pips' + '\n', xloc.bar_time, textcolor = col_bar, style = label.style_none) // var tbl = table.new(position.top_right, 2, 2) if barstate.islast pipsbar.set_xy1(pb_time, y1) pipsbar.set_xy2(pb_time, y2) la.set_xy(pb_time, y2) // tbl.cell(0,0, tkr) // tbl.cell(0,1, str.tostring(pip))
Predictive Trend and Structure (Expo)
https://www.tradingview.com/script/LeeciZlD-Predictive-Trend-and-Structure-Expo/
Zeiierman
https://www.tradingview.com/u/Zeiierman/
354
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("Predictive Trend and Structure (Expo)", overlay = true) // ~~ Tooltip { t1 = "Determines the number of periods used for the standard deviation calculation. Increasing the value makes the indicator less sensitive to price changes, possibly identifying longer-term trends, while decreasing the value makes the indicator more sensitive, possibly identifying shorter-term trends." t2 = "Scales the computed standard deviation. Increasing this value may result in larger deviations being needed to confirm trends, potentially filtering out minor price fluctuations and focusing on significant trend changes, while decreasing this value may allow smaller deviations to confirm trends, possibly detecting more frequent changes." t3 = "Enables or disables the predictive structure setting. Enabling it may emphasize the prediction of market structures, such as potential levels of structure breaks/trend continuation breaks." t4 = "Activates or deactivates BTC Scalping Mode. When activated, the indicator’s parameters adjust to optimize for shorter time frames and quicker trades, potentially beneficial for scalping strategies in BTC markets." t5 = "Adjusts the scaling divisor when in BTC Scalping Mode. Modifying this value impacts the volatility and trend sensitivity during scalping. A higher value might result in less sensitivity to price fluctuations, focusing on more substantial trend changes, while a lower value might increase sensitivity, detecting minor trend changes." //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Inputs { period = input.int(20, title="Period for Std Dev", minval = 1, maxval=200, inline="", group="", tooltip=t1) stdDevScaler = input.int(5, title="Standard Deviation Scaler", minval = 1, maxval=200, inline="", group="", tooltip=t2) structure = input.bool(false, title="Predictive Structure", inline = "s", group = "", tooltip=t3) s_col = input.color(color.rgb(70, 40, 204), title="", inline = "s", group = "") isScalpingModeEnabled = false //input.bool(false, title="BTC Scalping Mode", inline="scalp", group="BTC Scalping", tooltip=t4) scalpingDivisor = isScalpingModeEnabled==true ? input.int(1, title="", minval = 0, maxval=200, inline="scalp", group="BTC Scalping", tooltip=t5) : 1 bullish_col = structure?s_col :input.color(color.lime, title="Bullish Trend Color", inline = "Trend", group = "Color") bearish_col = structure?s_col :input.color(color.red, title="Bearish Trend Color", inline = "Trend", group = "Color") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Initialize Variables { var float trend = 0 var int trendDirection = 0 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Function to determine the trend direction { trendDirectionFunction(dir) => dir - dir[1] > 0 ? 1 : (dir - dir[1] < 0 ? -1 : 0) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Function to check if the trend direction has changed { trendDirectionChanged(trendDirection) => trendDirection != trendDirection[1] //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Function to calculate standard deviation { stddev_function(src_, p) => if bar_index < p - 1 0.0 else sum = 0.0 for i = 0 to p - 1 sum := sum + src_[i] mean = sum / p sum_diff_sq = 0.0 for i = 0 to p - 1 sum_diff_sq := sum_diff_sq + math.pow(src_[i] - mean, 2) stdev = isScalpingModeEnabled ? math.sqrt(sum_diff_sq / close * p * scalpingDivisor) : math.sqrt(sum_diff_sq / p * scalpingDivisor) stdev scaledStdDev = stdDevScaler * stddev_function(trend, period) priceDifference = close - trend > 0 ? close - trend : trend - close rateOfChangeFactor = float(100) div = structure? float(int(1) / int(100)): 1 / rateOfChangeFactor reciprocal_factors = (1 / stdDevScaler) * div trend := priceDifference > scaledStdDev ? math.avg(close, trend): trendDirection * (trendDirectionChanged(trendDirection) ? scaledStdDev : reciprocal_factors * scaledStdDev) + trend trendDirection := trendDirectionFunction(trend) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Plot { color = trendDirection == 1 ? bullish_col : bearish_col plot(trend, title="Trend", color=trendDirectionChanged(trendDirection) ? na : color) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
Correlational cycles
https://www.tradingview.com/script/eXMMZfRk-Correlational-cycles/
Kowalski_Trader
https://www.tradingview.com/u/Kowalski_Trader/
26
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/ // © Kowalski_Trader //@version=5 indicator("Correlation Coefficient", shorttitle = "CC", format = format.price, precision = 2) symbolInput = input.symbol("FNGU", "Symbol", confirm = true) second_symbolInput = input.symbol("QQQ", "Symbol", confirm = true) sourceInput = input.source(close, "Source") multiplierInput = input.int(-1,"Multiplier") second_symbolMultiplier = input.int(-1,"Second Symbol Multiplier") lengthInput = input.int(11, "Length") adjustedSeries = ticker.modify(symbolInput) second_adjustedSeries = ticker.modify(second_symbolInput) requestedData = request.security(adjustedSeries, timeframe.period, (sourceInput*multiplierInput)) second_requestedData = request.security(second_adjustedSeries, timeframe.period, (sourceInput*second_symbolMultiplier)) correlation = ta.correlation(sourceInput, requestedData, lengthInput) second_correlation = ta.correlation(sourceInput, second_requestedData, lengthInput) plot(second_correlation, "Correlation Second Symbol", color = color.red) plot(correlation, "Correlation", color = color.blue) hline(1) hline(0, color = color.new(color.gray, 50)) hline(-1)
[dharmatech] KBDR Mean Reversion
https://www.tradingview.com/script/tsN1a2uK-dharmatech-KBDR-Mean-Reversion/
dharmatech
https://www.tradingview.com/u/dharmatech/
76
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/ // © dharmatech //@version=5 indicator(title = "KBDR Mean Reversion", shorttitle = "KBDR Mean Reversion", overlay = true) // 2023-09-21 Updating permissions // ---------------------------------------------------------------------- // bollinger bands // ---------------------------------------------------------------------- length = input.int(20, minval=1) src = input(close, title="Source") mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev") basis = ta.sma(src, length) dev = mult * ta.stdev(src, length) bbands_upper = basis + dev bbands_lower = basis - dev // ---------------------------------------------------------------------- // keltner channels // ---------------------------------------------------------------------- exp = input(true, "Use Exponential MA") BandsStyle = input.string("Average True Range", options = ["Average True Range", "True Range", "Range"], title="Bands Style") atrlength = input(10, "ATR Length") esma(source, length)=> s = ta.sma(source, length) e = ta.ema(source, length) exp ? e : s ma = esma(src, length) rangema = BandsStyle == "True Range" ? ta.tr(true) : BandsStyle == "Average True Range" ? ta.atr(atrlength) : ta.rma(high - low, length) kc_upper = ma + rangema * mult kc_lower = ma - rangema * mult // ---------------------------------------------------------------------- input_bbands_lower = input.float(defval = 0.98) input_bbands_upper = input.float(defval = 1.02) near_bbands_lower = low * input_bbands_lower < bbands_lower // is (low - 1%) < bbands_lower near_bbands_upper = high * input_bbands_upper > bbands_upper // ---------------------------------------------------------------------- // DI+ and DI- // ---------------------------------------------------------------------- len = input(14) th = input(20) // TrueRange = max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1]))) 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 // ---------------------------------------------------------------------- // DI+ increasing // DI- decreasing // ---------------------------------------------------------------------- // bullish di_plus_increasing = DIPlus > DIPlus[1] di_minus_decreasing = DIMinus < DIMinus[1] di_bullish = di_plus_increasing and di_minus_decreasing // bearish di_plus_decreasing = DIPlus < DIPlus[1] di_minus_increasing = DIMinus > DIMinus[1] di_bearish = di_plus_decreasing and di_minus_increasing bbands_outside_keltner = bbands_lower < kc_lower and bbands_upper > kc_upper // ---------------------------------------------------------------------- // RSI // ---------------------------------------------------------------------- rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings") rsiSourceInput = input.source(close, "Source", group="RSI Settings") up = ta.rma( math.max(ta.change(rsiSourceInput), 0), rsiLengthInput) down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) // ---------------------------------------------------------------------- rsi_increasing = rsi > rsi[1] rsi_decreasing = rsi < rsi[1] // rsi_near_bottom = rsi < 40 // rsi_near_top = rsi > 60 input_rsi_near_bottom = input.float(defval = 40) input_rsi_near_top = input.float(defval = 60) rsi_near_bottom = rsi < input_rsi_near_bottom or rsi[1] < input_rsi_near_bottom rsi_near_top = rsi > input_rsi_near_top or rsi[1] > input_rsi_near_top // rsi_bullish = rsi_near_bottom and rsi_increasing // rsi_bearish = rsi_near_top and rsi_decreasing rsi_big_increase = (rsi - rsi[1]) / rsi[1] > 0.19 // RSI increased 19% rsi_big_decrease = (rsi - rsi[1]) / rsi[1] < -0.19 // RSI decreased 19% rsi_bullish = (rsi_near_bottom and rsi_increasing) or rsi_big_increase rsi_bearish = (rsi_near_top and rsi_decreasing) or rsi_big_decrease // ---------------------------------------------------------------------- bool bull_signal = bbands_outside_keltner and near_bbands_lower and di_bullish and rsi_bullish bool bear_signal = bbands_outside_keltner and near_bbands_upper and di_bearish and rsi_bearish // ---------------------------------------------------------------------- bool bear_signal_di_bearish = bbands_outside_keltner and di_bearish and not bear_signal bool bull_signal_di_bullish = bbands_outside_keltner and di_bullish and not bull_signal // ---------------------------------------------------------------------- input_partial_1 = input.bool(defval = false, title = "Partial 1") input_partial_2 = input.bool(defval = false, title = "Partial 2") input_partial_3 = input.bool(defval = false, title = "Partial 3") input_partial_4 = input.bool(defval = false, title = "Partial 4") //plotchar(input_partial and not bbands_outside_keltner and not di_bearish and not rsi_bearish and not near_bbands_upper, "Short", "", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "") plotchar(input_partial_1 and not bbands_outside_keltner and not di_bearish and not rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "B") plotchar(input_partial_1 and not bbands_outside_keltner and not di_bearish and rsi_bearish and not near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "R") plotchar(input_partial_2 and not bbands_outside_keltner and not di_bearish and rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "B\nR") plotchar(input_partial_1 and not bbands_outside_keltner and di_bearish and not rsi_bearish and not near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "D") plotchar(input_partial_2 and not bbands_outside_keltner and di_bearish and not rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "B\nD") plotchar(input_partial_2 and not bbands_outside_keltner and di_bearish and rsi_bearish and not near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "D\nR") plotchar(input_partial_3 and not bbands_outside_keltner and di_bearish and rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "B\nD\nR") plotchar(input_partial_1 and bbands_outside_keltner and not di_bearish and not rsi_bearish and not near_bbands_upper, "Short", "", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\n") plotchar(input_partial_2 and bbands_outside_keltner and not di_bearish and not rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nB") plotchar(input_partial_2 and bbands_outside_keltner and not di_bearish and rsi_bearish and not near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nR") plotchar(input_partial_3 and bbands_outside_keltner and not di_bearish and rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nB\nR") plotchar(input_partial_2 and bbands_outside_keltner and di_bearish and not rsi_bearish and not near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nD") plotchar(input_partial_3 and bbands_outside_keltner and di_bearish and not rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nB\nD") plotchar(input_partial_3 and bbands_outside_keltner and di_bearish and rsi_bearish and not near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nD\nR") plotchar(input_partial_4 and bbands_outside_keltner and di_bearish and rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.red, size = size.tiny, display = display.pane, text = "K\nB\nD\nR") plotchar( bbands_outside_keltner and di_bearish and rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.yellow, size = size.tiny, display = display.pane) // plotchar( bbands_outside_keltner and di_bearish and rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.red, size = size.tiny, text = "K\nB\nD\nR") // plotchar(not bbands_outside_keltner and di_bearish and rsi_bearish and near_bbands_upper, "Short", "▼", location.abovebar, color = color.red, size = size.tiny, text = "B\nD\nR") // ---------------------------------------------------------------------- // plotchar(input_partial and not bbands_outside_keltner and not di_bullish and not rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "") plotchar(input_partial_1 and not bbands_outside_keltner and not di_bullish and not rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "B") plotchar(input_partial_1 and not bbands_outside_keltner and not di_bullish and rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "R") plotchar(input_partial_2 and not bbands_outside_keltner and not di_bullish and rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "B\nR") plotchar(input_partial_1 and not bbands_outside_keltner and di_bullish and not rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "D") plotchar(input_partial_2 and not bbands_outside_keltner and di_bullish and not rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "B\nD") plotchar(input_partial_2 and not bbands_outside_keltner and di_bullish and rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "D\nR") plotchar(input_partial_3 and not bbands_outside_keltner and di_bullish and rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "B\nD\nR") plotchar(input_partial_1 and bbands_outside_keltner and not di_bullish and not rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\n") plotchar(input_partial_2 and bbands_outside_keltner and not di_bullish and not rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nB") plotchar(input_partial_2 and bbands_outside_keltner and not di_bullish and rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nR") plotchar(input_partial_3 and bbands_outside_keltner and not di_bullish and rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nB\nR") plotchar(input_partial_2 and bbands_outside_keltner and di_bullish and not rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nD") plotchar(input_partial_3 and bbands_outside_keltner and di_bullish and not rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nB\nD") plotchar(input_partial_3 and bbands_outside_keltner and di_bullish and rsi_bullish and not near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane, text = "K\nD\nR") plotchar(input_partial_4 and bbands_outside_keltner and di_bullish and rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.green, size = size.tiny, display = display.pane, text = "K\nB\nD\nR") plotchar( bbands_outside_keltner and di_bullish and rsi_bullish and near_bbands_lower, "Long", "▲", location.belowbar, color = color.yellow, size = size.tiny, display = display.pane)
Barbwire [yohtza]
https://www.tradingview.com/script/lb9nUFFK-Barbwire-yohtza/
yohtza
https://www.tradingview.com/u/yohtza/
16
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/ // © yohtza //@version=5 indicator("Barbwire [yohtza]", overlay = true) borderColor = input.color(color.new(color.gray, 80), "Barbwire border color") bgColor = input.color(color.new(color.gray, 80), "Barbwire background color") bool isDoji = math.abs(open-close) / (high - low) < 0.5 sixtysix_pbar = high[1] - ((high[1] - low[1]) * 0.66) thirtythree_pbar = high[1] - ((high[1] - low[1]) * 0.33) thirtythree = high - ((high - low) * 0.33) sixtysix = high - ((high - low) * 0.66) fifty_pbar = high[1] - ((high[1] - low[1]) * 0.5) fifty = high - ((high - low) * 0.5) bool bl = high > high[1] and low > low[1] bool br = high < high[1] and low < low[1] bool o = high >= high[1] and low <= low[1] bool i = (high <= high[1] and low > low[1]) or (high < high[1] and low >= low[1]) bool bullBar = open[1] <= close[1] // bool deepPb = bl ? low < sixtysix_pbar and high[1] > thirtythree : br ? high > thirtythree_pbar and low[1] < sixtysix : i ? high > thirtythree_pbar and low < sixtysix_pbar : o ? low[1] < sixtysix and high[1] > thirtythree : false bool deepPb = bl ? low < fifty_pbar and high[1] > fifty : br ? high > fifty_pbar and low[1] < fifty : i ? high > fifty_pbar and low < fifty_pbar : o ? low[1] < fifty and high[1] > fifty : false bool overlap = deepPb and deepPb[1] //and deepPb[2] bool atLeastOneDojiInLastThreeBars = isDoji or isDoji[1] or isDoji[2] bool barbwire = atLeastOneDojiInLastThreeBars and overlap top = ta.highest(3) bot = ta.lowest(3) var int start = na var float trtop = na var float trbot = na var box ttrbox = na if barbwire[1] == false and barbwire start := bar_index -2 right = bar_index trtop := top trbot := bot ttrbox := box.new(start,trtop,right,trbot, border_color = borderColor, bgcolor = bgColor, border_width = 3) if barbwire[1] and barbwire right = bar_index trtop := trtop > top ? trtop : top trbot := trbot < bot ? trbot : bot box.set_bottom(ttrbox, trbot) box.set_top(ttrbox, trtop) box.set_right(ttrbox,right)
Double RSI 00 1.0
https://www.tradingview.com/script/e1gYMWGt/
egghen
https://www.tradingview.com/u/egghen/
9
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/ // © egghen //@version=5 indicator('Double RSI 00 1.0') // Inputs length_1 = input(7, title='RSI1 Length') length_2 = input(12, title='RSI2 Length') overbought_1 = input(75, title='Overbought Signal') oversold_1 = input(25, title='Oversold Signal ') overbought_2 = input(85, title='High Overbought Signal') oversold_2 = input(15, title='High Oversold Signal') // RSI Calculation rsi_1 = ta.rsi(hl2, length_1) rsi_2 = ta.rsi(hl2, length_2) // Plot Setting plot(rsi_1, color=color.new(#1fed14, 0), linewidth=2, title='RSI1') plot(rsi_2, color=color.new(#cfd648, 37), title='RSI2') h0 = hline(0, 'Lower Band', color=#787B86) h1 = hline(50, 'Middle Band', color=#f2f3f5cb) h2 = hline(100, 'Upper Band', color=#787B86) h3 = hline(oversold_1, 'Oversold', color=#26f806a1) h4 = hline(overbought_1, 'Overbought', color=#f50e06a1) h5 = hline(oversold_2, 'High Oversold', color=#787B86) h6 = hline(overbought_2, 'High Overbought', color=#787B86) // Define Alerts overbought = ta.crossunder(rsi_1, overbought_1) oversold = ta.crossover(rsi_1, oversold_1) high_overbought = ta.crossunder(rsi_1, overbought_2) high_oversold = ta.crossover(rsi_1, oversold_2) long_alert = ta.crossover(rsi_1, rsi_2) short_alert = ta.crossunder(rsi_1, rsi_2) // Send an alert if long_alert alert('DoubleRSI OO 1.0 - Long Signal.') if short_alert alert('DoubleRSI OO 1.0 - Short Signal.') if overbought alert('DoubleRSI OO 1.0 - Overbought Signal.') if oversold alert('DoubleRSI OO 1.0 - Oversold Signal.') if high_overbought alert('DoubleRSI OO 1.0 - High Overbought Signal.') if high_oversold alert('DoubleRSI OO 1.0 - High Oversold Signal.') // // end code
Get start of previous day on any timeframe
https://www.tradingview.com/script/Xa4qbgR7-Get-start-of-previous-day-on-any-timeframe/
haribotagada
https://www.tradingview.com/u/haribotagada/
4
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/ // © haribotagada //@version=5 indicator("Get start of previous day on any timeframe", overlay = true) getPreviousDay(int referenceTime = last_bar_time) => dayOfWeekNow = dayofweek(referenceTime) dayOfMonthNow = dayofmonth(referenceTime) monthNow = month(referenceTime) yearNow = year(referenceTime) dayOffset = int(na) if syminfo.type == "forex" or syminfo.type == "futures" or syminfo.type == "crypto" or syminfo.type == "spot" dayOffset := 1 else // Calculate offset for assets which don't trade 24x7 so we exclude week-ends dayOffset := switch dayOfWeekNow 1 => 2 // Sunday 2 => 3 // Monday 3 => 1 // Tuesday 4 => 1 // Wednesday 5 => 1 // Thursday 6 => 1 // Friday 7 => 1 // Saturday referenceDay = timestamp(year=yearNow, month = monthNow, day = dayOfMonthNow, hour=0, minute = 0, second = 0) previousDay = referenceDay - ( (24 * 60 * 60 * 1000) * dayOffset) previousDay yesterday = getPreviousDay() if time >= yesterday and time[1] < yesterday label.new(x=bar_index, y=high, style = label.style_label_down, text = 'Yesterday!')
WW DMI with Wilders smooting
https://www.tradingview.com/script/8tQqhj7K-WW-DMI-with-Wilders-smooting/
JakeTheDane
https://www.tradingview.com/u/JakeTheDane/
2
study
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/ // © JakeTheDane //@version=4 study(title="WW DMI with Wilders smooting", shorttitle="WW DMI", overlay=false) // User Inputs len = input(14, minval=1, title="DI Length") lensig = input(14, title="ADX Smoothing", minval=1, maxval=50) // True Range Calculation var float trueRange = na diff1 = high - low diff2 = abs(high - close[1]) diff3 = abs(low - close[1]) trueRange := na(trueRange) ? diff1 : trueRange - (trueRange / len) + iff(na(diff1), 0.0, diff1) // Directional Movement Calculation var float plusDM = na var float minusDM = na upMove = high - high[1] downMove = low[1] - low plusDM := na(plusDM) ? 0.0 : plusDM - (plusDM / len) + (upMove > downMove and upMove > 0.0 ? upMove : 0.0) minusDM := na(minusDM) ? 0.0 : minusDM - (minusDM / len) + (downMove > upMove and downMove > 0.0 ? downMove : 0.0) // Calculating +DI and -DI plusDI = 100 * (plusDM / trueRange) minusDI = 100 * (minusDM / trueRange) // Calculating DX dx = abs(plusDI - minusDI) / (plusDI + minusDI) * 100 // Calculating ADX var float adx = na adx := na(adx) ? dx : (adx * (lensig - 1) + dx) / lensig // Plotting the indicators with updated colors plot(adx, color= color.blue) plot(plusDI, color= color.green) plot(minusDI, color= color.red) // Adding horizontal lines at essential value points hline(20, "", color= color.gray, linestyle=hline.style_dotted) hline(50, "", color= color.gray, linestyle=hline.style_dotted)
Fibonacci HH LL TRAMA Band
https://www.tradingview.com/script/Y6iGumYx/
hayashipallu
https://www.tradingview.com/u/hayashipallu/
36
study
5
CC-BY-NC-SA-4.0
// This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ //hayashipallu //@version=5 indicator('Fibonacci HH LL Trend Regularity Adaptive Moving Average Band Ribbon',shorttitle = "FIB HHLL TRAMA" ,overlay=true) length = input(55) src1 = high src2 = low ama1 = 0. ama2 = 0. hh = math.max(math.sign(ta.change(ta.highest(length))), 0) ll = math.max(math.sign(ta.change(ta.lowest(length)) * -1), 0) tc = math.pow(ta.sma(hh or ll ? 1 : 0, length), 2) ama1 := nz(ama1[1] + tc * (src1 - ama1[1]), src1) ama2 := nz(ama2[1] + tc * (src2 - ama2[1]), src2) //Midline mah = ama1//alma1 mal = ama2 m = (mah + mal)/2 //Half Mean Range dist = (mah - mal)/2 //Levels h6 = m + dist * 11.089 h5 = m + dist * 6.857 h4 = m + dist * 4.235 h3 = m + dist * 2.618 h2 = m + dist * 1.618 h1 = m + dist * 0.618 l1 = m - dist * 0.618 l2 = m - dist * 1.618 l3 = m - dist * 2.618 l4 = m - dist * 4.235 l5 = m - dist * 6.857 l6 = m - dist * 11.089 plot(m, linewidth = 3, color = m > m[5] ? color.lime : color.red) ph6 = plot(h6, color = color.lime) ph5 = plot(h5, color = color.lime) ph4 = plot(h4, color = color.lime) ph3 = plot(h3, color = color.lime) ph2 = plot(h2, color = color.lime) ph1 = plot(h1, color = color.lime) pl6 = plot(l6, color = color.red) pl5 = plot(l5, color = color.red) pl4 = plot(l4, color = color.red) pl3 = plot(l3, color = color.red) pl2 = plot(l2, color = color.red) pl1 = plot(l1, color = color.red) fill(ph6, ph5, color = color.new(color.lime, 70), editable = true) fill(pl6, pl5, color = color.new(color.red, 70), editable = true) fill(ph5, ph4, color = color.new(color.lime, 90), editable = true) fill(pl5, pl4, color = color.new(color.red, 90), editable = true) fill(ph4, ph3, color = color.new(color.lime, 93), editable = true) fill(pl4, pl3, color = color.new(color.red, 93), editable = true) fill(ph3, ph2, color = color.new(color.lime, 96), editable = true) fill(pl3, pl2, color = color.new(color.red, 96), editable = true) fill(ph2, ph1, color = color.new(color.lime, 99), editable = true) fill(pl2, pl1, color = color.new(color.red, 99), editable = true)
Trendy Bars Counter
https://www.tradingview.com/script/tZCGIPfk-Trendy-Bars-Counter/
agbay
https://www.tradingview.com/u/agbay/
6
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/ // Trendy Bars Counter indicates the number of bars in trend. // Meaning of the color of the numbers plotted on graph is: // Green: If trend is up // Red: If trend is down // // Minimum Number Of Trendy Bars: if trendy bars count is greater than this value trendy bars count will be plotted // // Meaning of plotted chars: // Numbers: sequential number of bars in trend // ^: Sequential number of bars in trend are bigger than 10 and trend is positive // v: Sequential number of bars in trend are bigger than 10 and trend is negative // © agbay //@version=5 indicator(title="Trendy Bars Counter", shorttitle="Tdy Bar", overlay = true) max_bars = input.int(defval = 20, minval = 1, title = "Maximum Historical Bar Count") min_trend = input.int(defval = 0, minval = 0, title = "Minimum Number Of Trendy Bars") max1_bars = max_bars-1 strend = 0 //---------------------------------------------------------------------------------------------- // Calculate trend //---------------------------------------------------------------------------------------------- if not na(open[max1_bars]) trend = 0 counter = 0 var prev_o = open[max1_bars] var prev_c = close[max1_bars] var prev_h = high[max1_bars] var prev_l =low[max1_bars] var prev_min = prev_o < prev_c ? prev_o : prev_c var prev_max = prev_o > prev_c ? prev_o : prev_c for bi=max1_bars to 0 if bi<0 continue o = open[bi] h = high[bi] l = low[bi] c = close[bi] min = o < c ? o : c max = o > c ? o : c if o==c and prev_o==prev_c trend := 0 counter := 0 else if prev_min < c and c < prev_h and o!=c trend := 0 counter := 0 else if prev_c < c and o!=c if trend > 0 trend := trend + 1 counter := counter + 1 else trend := 1 prev_c := c counter := 0 else if prev_c > c and o!=c if trend > 0 trend := -1 prev_c := c counter := 0 else trend := trend - 1 counter := counter + 1 prev_o := o prev_c := c prev_l := o prev_h := c prev_min := min prev_max := max strend := counter>=min_trend ? trend : 0 plotchar(strend==1, title="", char="1", color=color.green, location=location.abovebar) plotchar(strend==2, title="", char="2", color=color.green, location=location.abovebar) plotchar(strend==3, title="", char="3", color=color.green, location=location.abovebar) plotchar(strend==4, title="", char="4", color=color.green, location=location.abovebar) plotchar(strend==5, title="", char="5", color=color.green, location=location.abovebar) plotchar(strend==6, title="", char="6", color=color.green, location=location.abovebar) plotchar(strend==7, title="", char="7", color=color.green, location=location.abovebar) plotchar(strend==8, title="", char="8", color=color.green, location=location.abovebar) plotchar(strend==9, title="", char="9", color=color.green, location=location.abovebar) plotchar(strend>=10, title="", char="^", color=color.green, location=location.abovebar) plotchar(strend==-1, title="", char="1", color=color.red, location=location.belowbar) plotchar(strend==-2, title="", char="2", color=color.red, location=location.belowbar) plotchar(strend==-3, title="", char="3", color=color.red, location=location.belowbar) plotchar(strend==-4, title="", char="4", color=color.red, location=location.belowbar) plotchar(strend==-5, title="", char="5", color=color.red, location=location.belowbar) plotchar(strend==-6, title="", char="6", color=color.red, location=location.belowbar) plotchar(strend==-7, title="", char="7", color=color.red, location=location.belowbar) plotchar(strend==-8, title="", char="8", color=color.red, location=location.belowbar) plotchar(strend==-9, title="", char="9", color=color.red, location=location.belowbar) plotchar(strend<=-10, title="", char="v", color=color.red, location=location.belowbar)
Intraday Intensity Index [SyntaxGeek]
https://www.tradingview.com/script/K00MMBW4-Intraday-Intensity-Index-SyntaxGeek/
syntaxgeek
https://www.tradingview.com/u/syntaxgeek/
22
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/ // © syntaxgeek // _____ _____ _____ _____ _____ _____ _____ _____ _____ // /\ \ |\ \ /\ \ /\ \ /\ \ ______ /\ \ /\ \ /\ \ /\ \ // /::\ \ |:\____\ /::\____\ /::\ \ /::\ \ |::| | /::\ \ /::\ \ /::\ \ /::\____\ // /::::\ \ |::| | /::::| | \:::\ \ /::::\ \ |::| | /::::\ \ /::::\ \ /::::\ \ /:::/ / // /::::::\ \ |::| | /:::::| | \:::\ \ /::::::\ \ |::| | /::::::\ \ /::::::\ \ /::::::\ \ /:::/ / // /:::/\:::\ \ |::| | /::::::| | \:::\ \ /:::/\:::\ \ |::| | /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/ / // /:::/__\:::\ \ |::| | /:::/|::| | \:::\ \ /:::/__\:::\ \ |::| | /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/____/ // \:::\ \:::\ \ |::| | /:::/ |::| | /::::\ \ /::::\ \:::\ \ |::| | /:::/ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /::::\ \ // ___\:::\ \:::\ \ |::|___|______ /:::/ |::| | _____ /::::::\ \ /::::::\ \:::\ \ |::| | /:::/ / \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /::::::\____\________ // /\ \:::\ \:::\ \ /::::::::\ \ /:::/ |::| |/\ \ /:::/\:::\ \ /:::/\:::\ \:::\ \ ______|::|___|___ ____ /:::/ / \:::\ ___\ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ \ /:::/\:::::::::::\ \ // /::\ \:::\ \:::\____\/::::::::::\____/:: / |::| /::\____\/:::/ \:::\____/:::/ \:::\ \:::\____|:::::::::::::::::| /:::/____/ ___\:::| /:::/__\:::\ \:::\____/:::/__\:::\ \:::\____/:::/ |:::::::::::\____\ // \:::\ \:::\ \::/ /:::/~~~~/~~ \::/ /|::| /:::/ /:::/ \::/ \::/ \:::\ /:::/ |:::::::::::::::::|____\:::\ \ /\ /:::|____\:::\ \:::\ \::/ \:::\ \:::\ \::/ \::/ |::|~~~|~~~~~ // \:::\ \:::\ \/____/:::/ / \/____/ |::| /:::/ /:::/ / \/____/ \/____/ \:::\/:::/ / ~~~~~~|::|~~~|~~~ \:::\ /::\ \::/ / \:::\ \:::\ \/____/ \:::\ \:::\ \/____/ \/____|::| | // \:::\ \:::\ \ /:::/ / |::|/:::/ /:::/ / \::::::/ / |::| | \:::\ \:::\ \/____/ \:::\ \:::\ \ \:::\ \:::\ \ |::| | // \:::\ \:::\____\/:::/ / |::::::/ /:::/ / \::::/ / |::| | \:::\ \:::\____\ \:::\ \:::\____\ \:::\ \:::\____\ |::| | // \:::\ /:::/ /\::/ / |:::::/ /\::/ / /:::/ / |::| | \:::\ /:::/ / \:::\ \::/ / \:::\ \::/ / |::| | // \:::\/:::/ / \/____/ |::::/ / \/____/ /:::/ / |::| | \:::\/:::/ / \:::\ \/____/ \:::\ \/____/ |::| | // \::::::/ / /:::/ / /:::/ / |::| | \::::::/ / \:::\ \ \:::\ \ |::| | // \::::/ / /:::/ / /:::/ / |::| | \::::/ / \:::\____\ \:::\____\ \::| | // \::/ / \::/ / \::/ / |::|___| \::/____/ \::/ / \::/ / \:| | // \/____/ \/____/ \/____/ ~~ \/____/ \/____/ \|___| //@version=5 indicator("Intraday Intensity Index [SyntaxGeek]", "III") // { consts c_mode_histo = 'Histogram' c_mode_hilo = 'High/Low' // } consts // { inputs i_mode = input.string(c_mode_histo, '', options=[c_mode_histo, c_mode_hilo], group='Mode', inline='mode') i_trendPeriod = input.int(20, '', group='Mode', tooltip=c_mode_hilo + ' Trend Period', inline='mode') i_intradayMode = input.bool(true, 'Intraday mode clears after RTH session restarts') i_colorUp = input.color(color.green, 'Up', group='Colors') i_colorDown = input.color(color.red, 'Down', group='Colors') // } inputs // { vars var v_finalVolumeIntensity = 0.0 if i_intradayMode and session.isfirstbar_regular v_finalVolumeIntensity := 0.0 v_finalVolumeIntensity += (ta.iii * 1000000) // sue me I like the numbers better this way :D v_colorVolumeIntensity = v_finalVolumeIntensity > 0 ? v_finalVolumeIntensity < v_finalVolumeIntensity[1] ? color.new(i_colorUp, 50) : i_colorUp : v_finalVolumeIntensity > v_finalVolumeIntensity[1] ? color.new(i_colorDown, 50) : i_colorDown // } vars // { plots plot(ta.sma(v_finalVolumeIntensity, i_trendPeriod), 'Trend', color=color.white, display=i_mode == c_mode_hilo ? display.all : display.none) plot(v_finalVolumeIntensity, 'Intensity', color=v_colorVolumeIntensity, linewidth=3, style=i_mode == c_mode_histo ? plot.style_columns : plot.style_line) plot(ta.highest(v_finalVolumeIntensity, i_trendPeriod), 'High', color=i_colorUp, display=i_mode == c_mode_hilo ? display.all : display.none) plot(ta.lowest(v_finalVolumeIntensity, i_trendPeriod), 'Low', color=i_colorDown, display=i_mode == c_mode_hilo ? display.all : display.none) hline(0, 'Neutral', color=color.white, linestyle=hline.style_dashed) // } plots
Stocks Seasonality Gauge
https://www.tradingview.com/script/9MRGNYIN-Stocks-Seasonality-Gauge/
jawauntb
https://www.tradingview.com/u/jawauntb/
8
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/ // © jawauntb //@version=5 indicator("Stocks Seasonality Gauge", overlay=true, shorttitle="SSG") // Input Parameters lookbackYears = input.int(5, title="Lookback Years") emaLength = input.int(9, title="EMA Length for Current Month's Performance") // Calculate monthly performance for a specific year getReturn(yearOffset, monthOffset) => startPrice = request.security(syminfo.tickerid, "M", close[12*yearOffset+monthOffset]) endPrice = request.security(syminfo.tickerid, "M", close[12*yearOffset+monthOffset+1]) (endPrice - startPrice) / startPrice // Get average performance of the current month over the last 5 years currentMonthAvg = 0.0 for i = 0 to lookbackYears - 1 currentMonthAvg := currentMonthAvg + getReturn(i, month[0] - 1) currentMonthAvg := currentMonthAvg / lookbackYears // Get average performance of all months for the current year currentYearAvg = 0.0 for i = 0 to month[0] - 1 currentYearAvg := currentYearAvg + getReturn(0, i) currentYearAvg := currentYearAvg / month[0] // New code starts here // Calculate price change percentage over a given period getPriceChangePercentage(period) => change = (close - close[period]) / close[period] change // Get the percentage change over 21 days and 7 days threeWeekChange = getPriceChangePercentage(21) oneWeekChange = getPriceChangePercentage(7) // Create an EMA of these two values currentMonthEMA = ta.ema(threeWeekChange, emaLength) + ta.ema(oneWeekChange, emaLength) currentMonthEMA := currentMonthEMA / 2 // Averaging the two EMAs // New code ends here hline(0, "0% Change", color=color.rgb(237, 255, 170), linewidth = 1,linestyle=hline.style_dashed) // Plotting the lines plot(currentMonthAvg, color=color.rgb(33, 240, 243), linewidth=2, title="Avg Performance This Month Over Last 5 Years") plot(currentYearAvg, color=color.rgb(79, 226, 101), linewidth=3, title="Avg Monthly Performance Year to Date") plot(currentMonthEMA, color=color.rgb(255, 178, 55), linewidth=4, title="EMA of Current Months Performance")
Sebastine Gap Detector
https://www.tradingview.com/script/kiYGbfse-Sebastine-Gap-Detector/
sebastinecc
https://www.tradingview.com/u/sebastinecc/
28
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/ // © sebastinecc //@version=5 indicator("Sebastine Gap Detector", overlay=true) var float openingPrice = na var bool gapFilledUp = na var bool gapFilledDown = na var bool gapFilled = false var float previousDayClose = na is_new_day = ta.change(dayofweek(time)) != 0 if is_new_day openingPrice := open gapFilledUp := false gapFilledDown := false gapFilled := false previousDayClose := close[1] gapUp = openingPrice > close[1] gapDown = openingPrice < close[1] plot(previousDayClose,"PrCl",color=color.yellow,style=plot.style_circles) plot(openingPrice,"OpPr",color=color.yellow,style=plot.style_circles)
3GBH - ICT NY Session
https://www.tradingview.com/script/te3vgDMd-3GBH-ICT-NY-Session/
Clancy3gbh
https://www.tradingview.com/u/Clancy3gbh/
5
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/ // © Clancy3gbh //@version=5 indicator("NY Session", overlay = true) // New York Morning Session showNY = input.bool(true, 'Show →', group = 'NY Session', inline = '0', tooltip = 'Morning Session.') timeframe = input.session('0630-1000', ' ', group = 'NY Session', inline ='0') nyColor = input.color(color.new(color.green, 85), "", group = 'NY Session', inline = '0') sessionNY = time(timeframe.period, timeframe, 'UTC-6') bgcolor(showNY and sessionNY ? nyColor : na) // New York Lunch Session showNYlunch = input.bool(true, 'Show →', group = 'NY Session', inline = '1', tooltip = 'Lunch/No trade session.') lunchtimeframe = input.session('1000-1100', '', group = 'NY Session', inline = '1') lunchColor = input.color(color.new(color.red, 85), '', group = 'NY Session', inline = '1') lunchNY = time(timeframe.period, lunchtimeframe, 'UTC-6') bgcolor(showNYlunch and lunchNY ? lunchColor : na) // New York Afternoon Session showNYpm = input.bool(true, 'Show →', group = 'NY Session', inline = '2', tooltip = 'Afternoon Session.') pmtimeframe = input.session('1100-1430', '', group = 'NY Session', inline = '2') pmColor = input.color(color.new(color.green, 85), '', group = 'NY Session', inline = '2') pmNY = time(timeframe.period, pmtimeframe, 'UTC-6') bgcolor(showNYpm and pmNY ? pmColor : na)
TREND LINES B/O By Vintage Trader_ The Analytical skills
https://www.tradingview.com/script/wAGtdPmi-TREND-LINES-B-O-By-Vintage-Trader-The-Analytical-skills/
merchantmariner007
https://www.tradingview.com/u/merchantmariner007/
10
study
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/ // © Vintage Trader_ The Analytical Skills // //@version=4 study("TREND LINES B/O By Vintage Trader_ The Analytical skills", overlay=true) lb = input(30, title="Left Bars", minval=1) rb = input(30, title="Right Bars", minval=1) showpivot = input(true, title="Show Pivot Points") chdashed = input(true, title="Show Old Line as Dashed") ucolor = input(defval = #f81212db, title = "Uptrend line color") dcolor = input(defval = color.rgb(12, 1, 1), title = "Downtrend line color") mb = lb + rb + 1 float top = na float bot = na top := iff(not na(high[mb]), iff(highestbars(high, mb) == -rb, high[rb], na), na) // Pivot High bot := iff(not na(low[mb]), iff(lowestbars(low, mb) == -rb, low[rb], na), na) // Pivot Low plotshape(top and showpivot, text="HIGH V.T", style=shape.labeldown, color=color.new(color.white, 100), textcolor=color.rgb(12, 1, 1), location=location.abovebar, offset = -rb) plotshape(bot and showpivot, text="LOW V.T", style=shape.labelup, color=color.new(color.white, 100), textcolor=color.rgb(235, 79, 89), location=location.belowbar, offset = -rb) ltop = valuewhen(top, top, 1) bst = 0 bst := top ? 1 : nz(bst[1]) + 1 float t_angle = 0.0 t_angle := t_angle[1] if not na(ltop) and not na(top) line tline = na if ltop > top tline := line.new(bar_index - bst[1] - rb, high[bst[1] + rb], bar_index - rb, high[rb], color = dcolor, extend = extend.right) t_angle := (high[bst[1] + rb] - high[rb]) / bst[1] if t_angle < t_angle[1] and t_angle[1] != 0 line.set_extend(tline[1], extend = extend.none) if t_angle > t_angle[1] and t_angle[1] != 0 line.set_extend(tline, extend = extend.none) if ltop <= top t_angle := 0.0 if chdashed line.set_style(tline[1], style = line.style_dashed) lbot = valuewhen(bot, bot, 1) bsb = 0 bsb := bot ? 1 : nz(bsb[1]) + 1 float b_angle = 0.0 b_angle := b_angle[1] if not na(lbot) and not na(bot) line bline = na if lbot < bot bline := line.new(bar_index - bsb[1] - rb, low[bsb[1] + rb], bar_index - rb, low[rb], color = ucolor, extend = extend.right) b_angle := (low[bsb[1] + rb] - low[rb]) / bsb[1] if b_angle > b_angle[1] and b_angle[1] != 0 line.set_extend(bline[1], extend = extend.none) if b_angle < b_angle[1] and b_angle[1] != 0 line.set_extend(bline, extend = extend.none) if lbot >= bot b_angle := 0.0 if chdashed line.set_style(bline[1], style = line.style_dashed)
RSI + FIB HH LL StopLoss Finder/Contrarian Trades
https://www.tradingview.com/script/MYMna6kI/
hayashipallu
https://www.tradingview.com/u/hayashipallu/
44
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/ // © hayashipallu //@version=5 indicator("RSI + Fibonacci Higher Highs, Lower Lows StopLoss Finder / Contrarian Trade",shorttitle = "RSI,FHH,LL SLF/CT", overlay = true) //Fibonacci Number is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, ... //FIbonacci Ratio is 0.236, 0.382, 0.5, 0.618, 1, 1.618, 2.618, 4.236, ... lookback_bars = input(defval = 144) lookback_bars2 = input(defval = 144) ema_len1 = input(defval = 2) ema_len2 = input(defval = 2) slide = input(defval = 13) highest_ema = ta.ema(ta.highest(high, lookback_bars), ema_len1) highest_ema2 = ta.ema(ta.highest(high, lookback_bars2), ema_len2)[slide] lowest_ema = ta.ema(ta.lowest(low, lookback_bars), ema_len1) lowest_ema2 = ta.ema(ta.lowest(low, lookback_bars2), ema_len2)[slide] len = input(defval = 5) ema = ta.ema(close, len) rsi_len = input(defval = 13) rsi = ta.rsi(ema, rsi_len) ob = input(70) os = input(40) p1 = plot(highest_ema,color = color.new(#FC0400, 0), linewidth = 2) p2 = plot(highest_ema2,color = color.new(#0022FC, 0), linewidth = 2) p3 = plot(lowest_ema,color =color.new(#FC0400, 0), linewidth = 2) p4 = plot(lowest_ema2,color =color.new(#0022FC, 0), linewidth = 2) hh_color = highest_ema[1] < highest_ema2 ? #80000B :#00E60F ll_color = lowest_ema[1] > lowest_ema2 ? #00E60F : #80000B fill(p1, p2, color = color.new(hh_color, 33), editable = true) fill(p3, p4, color = color.new(ll_color, 33), editable = true) cc = rsi > ob ? color.red : rsi < os ? color.lime : color.silver barcolor(color = cc)
IU Probability Calculator
https://www.tradingview.com/script/TvXciTns-IU-Probability-Calculator/
Strategy_coders
https://www.tradingview.com/u/Strategy_coders/
23
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/ // © shivammandrai //@version=5 indicator("IU Probability Calculator", overlay=false) ///////////////////////////////////////// USER INPUTS //////////////////////////////////////// //// BULLISH AND BEARISH FILTER fliter = input.string("Bullish", "Enter the directions ", options = ["Bullish", "Bearish"]) lenght = input.int(14, title = " ATR / Std lenght", minval = 1, tooltip = "Enter the ATR period ") a = input.float(defval=27000,title="price level", tooltip = "Write the level from where you want to calculate the probabilty") calculation_method = input.string("ATR", title="Calculation Method", options=["ATR", "Standard Deviation"]) ////////////////////////////////////////// CALCULATIONS/////////////////////////////////////////////// b = close c = ta.atr(lenght) std_deviation = ta.stdev(close, length = lenght) z = 0.0 //// CHECKING THE VALUE IN NORMAL DISTRIBUTION TABLE float value = 0.00000 if fliter == "Bullish" if calculation_method == "ATR" z := (a - b)/ c else z := (a - b)/ std_deviation if z <= 0.01 value := 0.5040 else if z <= 0.02 value := 0.5080 else if z <= 0.03 value := 0.5120 else if z <= 0.04 value := 0.5160 else if z <= 0.05 value := 0.5199 else if z <= 0.06 value := 0.5239 else if z <= 0.07 value := 0.5279 else if z <= 0.08 value := 0.5319 else if z <= 0.09 value := 0.5359 else if z <= 0.10 value := 0.5398 else if z <= 0.11 value := 0.5438 else if z <= 0.12 value := 0.5478 else if z <= 0.13 value := 0.5517 else if z <= 0.14 value := 0.5557 else if z <= 0.15 value := 0.5596 else if z <= 0.16 value := 0.5636 else if z <= 0.17 value := 0.5675 else if z <= 0.18 value := 0.5714 else if z <= 0.19 value := 0.5753 else if z <= 0.20 value := 0.5793 else if z <= 0.21 value := 0.5832 else if z <= 0.22 value := 0.5871 else if z <= 0.23 value := 0.5910 else if z <= 0.24 value := 0.5948 else if z <= 0.25 value := 0.5987 else if z <= 0.26 value := 0.6026 else if z <= 0.27 value := 0.6064 else if z <= 0.28 value := 0.6103 else if z <= 0.29 value := 0.6141 else if z <= 0.30 value := 0.6179 else if z <= 0.31 value := 0.6217 else if z <= 0.32 value := 0.6255 else if z <= 0.33 value := 0.6293 else if z <= 0.34 value := 0.6331 else if z <= 0.35 value := 0.6368 else if z <= 0.36 value := 0.6406 else if z <= 0.37 value := 0.6443 else if z <= 0.38 value := 0.6480 else if z <= 0.39 value := 0.6517 else if z <= 0.40 value := 0.6554 else if z <= 0.41 value := 0.6591 else if z <= 0.42 value := 0.6628 else if z <= 0.43 value := 0.6664 else if z <= 0.44 value := 0.6700 else if z <= 0.45 value := 0.6736 else if z <= 0.46 value := 0.6772 else if z <= 0.47 value := 0.6808 else if z <= 0.48 value := 0.6844 else if z <= 0.49 value := 0.6879 else if z <= 0.50 value := 0.6915 else if z <= 0.51 value := 0.6968 else if z <= 0.52 value := 0.7020 else if z <= 0.53 value := 0.7071 else if z <= 0.54 value := 0.7123 else if z <= 0.55 value := 0.7174 else if z <= 0.56 value := 0.7224 else if z <= 0.57 value := 0.7274 else if z <= 0.58 value := 0.7324 else if z <= 0.59 value := 0.7374 else if z <= 0.60 value := 0.7424 else if z <= 0.61 value := 0.7472 else if z <= 0.62 value := 0.7521 else if z <= 0.63 value := 0.7569 else if z <= 0.64 value := 0.7617 else if z <= 0.65 value := 0.7664 else if z <= 0.66 value := 0.7712 else if z <= 0.67 value := 0.7759 else if z <= 0.68 value := 0.7806 else if z <= 0.69 value := 0.7852 else if z <= 0.70 value := 0.7897 else if z <= 0.71 value := 0.7942 else if z <= 0.72 value := 0.7986 else if z <= 0.73 value := 0.8029 else if z <= 0.74 value := 0.8072 else if z <= 0.75 value := 0.8115 else if z <= 0.76 value := 0.8156 else if z <= 0.77 value := 0.8198 else if z <= 0.78 value := 0.8238 else if z <= 0.79 value := 0.8279 else if z <= 0.80 value := 0.8319 else if z <= 0.81 value := 0.8357 else if z <= 0.82 value := 0.8396 else if z <= 0.83 value := 0.8434 else if z <= 0.84 value := 0.8471 else if z <= 0.85 value := 0.8508 else if z <= 0.86 value := 0.8544 else if z <= 0.87 value := 0.8580 else if z <= 0.88 value := 0.8615 else if z <= 0.8900 value := 0.8649 else if z <= 0.9000 value := 0.8683 else if z <= 0.9100 value := 0.8717 else if z <= 0.9200 value := 0.8749 else if z <= 0.9300 value := 0.8781 else if z <= 0.9400 value := 0.8812 else if z <= 0.9500 value := 0.8842 else if z <= 0.9600 value := 0.8872 else if z <= 0.9700 value := 0.8901 else if z <= 0.9800 value := 0.8929 else if z <= 0.9900 value := 0.8957 else if z <= 1.0000 value := 0.8983 else if z <= 1.0100 value := 0.9008 else if z <= 1.0200 value := 0.9025 else if z <= 1.0300 value := 0.9040 else if z <= 1.0400 value := 0.9055 else if z <= 1.0500 value := 0.9069 else if z <= 1.0600 value := 0.9082 else if z <= 1.0700 value := 0.9094 else if z <= 1.0800 value := 0.9106 else if z <= 1.0900 value := 0.9117 else if z <= 1.1000 value := 0.9129 else if z <= 1.1100 value := 0.9139 else if z <= 1.1200 value := 0.9149 else if z <= 1.1300 value := 0.9159 else if z <= 1.1400 value := 0.9168 else if z <= 1.1500 value := 0.9177 else if z <= 1.1600 value := 0.9186 else if z <= 1.1700 value := 0.9194 else if z <= 1.1800 value := 0.9202 else if z <= 1.1900 value := 0.9210 else if z <= 1.2000 value := 0.9217 else if z <= 1.2100 value := 0.9224 else if z <= 1.2200 value := 0.9230 else if z <= 1.2300 value := 0.9236 else if z <= 1.2400 value := 0.9243 else if z <= 1.2500 value := 0.9249 else if z <= 1.2600 value := 0.9254 else if z <= 1.2700 value := 0.9260 else if z <= 1.2800 value := 0.9265 else if z <= 1.2900 value := 0.9270 else if z <= 1.3000 value := 0.9274 else if z <= 1.3100 value := 0.9279 else if z <= 1.3200 value := 0.9283 else if z <= 1.3300 value := 0.9287 else if z <= 1.3400 value := 0.9291 else if z <= 1.3500 value := 0.9295 else if z <= 1.3600 value := 0.9299 else if z <= 1.3700 value := 0.9302 else if z <= 1.3800 value := 0.9306 else if z <= 1.3900 value := 0.9309 else if z <= 1.4000 value := 0.9312 else if z <= 1.4100 value := 0.9315 else if z <= 1.4200 value := 0.9319 else if z <= 1.4300 value := 0.9322 else if z <= 1.4400 value := 0.9325 else if z <= 1.4500 value := 0.9327 else if z <= 1.4600 value := 0.9330 else if z <= 1.4700 value := 0.9332 else if z <= 1.4800 value := 0.9335 else if z <= 1.4900 value := 0.9338 else if z <= 1.5000 value := 0.9340 else if z <= 1.5100 value := 0.9342 else if z <= 1.5200 value := 0.9345 else if z <= 1.5300 value := 0.9348 else if z <= 1.5400 value := 0.9351 else if z <= 1.5500 value := 0.9354 else if z <= 1.5600 value := 0.9357 else if z <= 1.5700 value := 0.9359 else if z <= 1.5800 value := 0.9362 else if z <= 1.5900 value := 0.9365 else if z <= 1.6000 value := 0.9367 else if z <= 1.6100 value := 0.9370 else if z <= 1.6200 value := 0.9372 else if z <= 1.6300 value := 0.9374 else if z <= 1.6400 value := 0.9377 else if z <= 1.6500 value := 0.9379 else if z <= 1.6600 value := 0.9381 else if z <= 1.6700 value := 0.9384 else if z <= 1.6800 value := 0.938 else if z <= 1.6900 value := 0.9388 else if z <= 1.7000 value := 0.9390 else if z <= 1.7100 value := 0.9392 else if z <= 1.7200 value := 0.9394 else if z <= 1.7300 value := 0.9396 else if z <= 1.7400 value := 0.9398 else if z <= 1.7500 value := 0.9400 else if z <= 1.7600 value := 0.9402 else if z <= 1.7700 value := 0.9404 else if z <= 1.7800 value := 0.9406 else if z <= 1.7900 value := 0.9408 else if z <= 1.8000 value := 0.9410 else if z <= 1.8100 value := 0.9411 else if z <= 1.8200 value := 0.9413 else if z <= 1.8300 value := 0.9415 else if z <= 1.8400 value := 0.9416 else if z <= 1.8500 value := 0.9418 else if z <= 1.8600 value := 0.9420 else if z <= 1.8700 value := 0.9421 else if z <= 1.8800 value := 0.9423 else if z <= 1.8900 value := 0.9424 /////////////////////////////////////// FOR BEARISH CALCULATIONS ///////////////////////////////// if fliter == "Bearish" if calculation_method == "ATR" z := (b - a)/ c else z := (b - a)/ std_deviation if z <= 0.01 value := 0.5040 else if z <= 0.02 value := 0.5080 else if z <= 0.03 value := 0.5120 else if z <= 0.04 value := 0.5160 else if z <= 0.05 value := 0.5199 else if z <= 0.06 value := 0.5239 else if z <= 0.07 value := 0.5279 else if z <= 0.08 value := 0.5319 else if z <= 0.09 value := 0.5359 else if z <= 0.10 value := 0.5398 else if z <= 0.11 value := 0.5438 else if z <= 0.12 value := 0.5478 else if z <= 0.13 value := 0.5517 else if z <= 0.14 value := 0.5557 else if z <= 0.15 value := 0.5596 else if z <= 0.16 value := 0.5636 else if z <= 0.17 value := 0.5675 else if z <= 0.18 value := 0.5714 else if z <= 0.19 value := 0.5753 else if z <= 0.20 value := 0.5793 else if z <= 0.21 value := 0.5832 else if z <= 0.22 value := 0.5871 else if z <= 0.23 value := 0.5910 else if z <= 0.24 value := 0.5948 else if z <= 0.25 value := 0.5987 else if z <= 0.26 value := 0.6026 else if z <= 0.27 value := 0.6064 else if z <= 0.28 value := 0.6103 else if z <= 0.29 value := 0.6141 else if z <= 0.30 value := 0.6179 else if z <= 0.31 value := 0.6217 else if z <= 0.32 value := 0.6255 else if z <= 0.33 value := 0.6293 else if z <= 0.34 value := 0.6331 else if z <= 0.35 value := 0.6368 else if z <= 0.36 value := 0.6406 else if z <= 0.37 value := 0.6443 else if z <= 0.38 value := 0.6480 else if z <= 0.39 value := 0.6517 else if z <= 0.40 value := 0.6554 else if z <= 0.41 value := 0.6591 else if z <= 0.42 value := 0.6628 else if z <= 0.43 value := 0.6664 else if z <= 0.44 value := 0.6700 else if z <= 0.45 value := 0.6736 else if z <= 0.46 value := 0.6772 else if z <= 0.47 value := 0.6808 else if z <= 0.48 value := 0.6844 else if z <= 0.49 value := 0.6879 else if z <= 0.50 value := 0.6915 else if z <= 0.51 value := 0.6968 else if z <= 0.52 value := 0.7020 else if z <= 0.53 value := 0.7071 else if z <= 0.54 value := 0.7123 else if z <= 0.55 value := 0.7174 else if z <= 0.56 value := 0.7224 else if z <= 0.57 value := 0.7274 else if z <= 0.58 value := 0.7324 else if z <= 0.59 value := 0.7374 else if z <= 0.60 value := 0.7424 else if z <= 0.61 value := 0.7472 else if z <= 0.62 value := 0.7521 else if z <= 0.63 value := 0.7569 else if z <= 0.64 value := 0.7617 else if z <= 0.65 value := 0.7664 else if z <= 0.66 value := 0.7712 else if z <= 0.67 value := 0.7759 else if z <= 0.68 value := 0.7806 else if z <= 0.69 value := 0.7852 else if z <= 0.70 value := 0.7897 else if z <= 0.71 value := 0.7942 else if z <= 0.72 value := 0.7986 else if z <= 0.73 value := 0.8029 else if z <= 0.74 value := 0.8072 else if z <= 0.75 value := 0.8115 else if z <= 0.76 value := 0.8156 else if z <= 0.77 value := 0.8198 else if z <= 0.78 value := 0.8238 else if z <= 0.79 value := 0.8279 else if z <= 0.80 value := 0.8319 else if z <= 0.81 value := 0.8357 else if z <= 0.82 value := 0.8396 else if z <= 0.83 value := 0.8434 else if z <= 0.84 value := 0.8471 else if z <= 0.85 value := 0.8508 else if z <= 0.86 value := 0.8544 else if z <= 0.87 value := 0.8580 else if z <= 0.88 value := 0.8615 else if z <= 0.8900 value := 0.8649 else if z <= 0.9000 value := 0.8683 else if z <= 0.9100 value := 0.8717 else if z <= 0.9200 value := 0.8749 else if z <= 0.9300 value := 0.8781 else if z <= 0.9400 value := 0.8812 else if z <= 0.9500 value := 0.8842 else if z <= 0.9600 value := 0.8872 else if z <= 0.9700 value := 0.8901 else if z <= 0.9800 value := 0.8929 else if z <= 0.9900 value := 0.8957 else if z <= 1.0000 value := 0.8983 else if z <= 1.0100 value := 0.9008 else if z <= 1.0200 value := 0.9025 else if z <= 1.0300 value := 0.9040 else if z <= 1.0400 value := 0.9055 else if z <= 1.0500 value := 0.9069 else if z <= 1.0600 value := 0.9082 else if z <= 1.0700 value := 0.9094 else if z <= 1.0800 value := 0.9106 else if z <= 1.0900 value := 0.9117 else if z <= 1.1000 value := 0.9129 else if z <= 1.1100 value := 0.9139 else if z <= 1.1200 value := 0.9149 else if z <= 1.1300 value := 0.9159 else if z <= 1.1400 value := 0.9168 else if z <= 1.1500 value := 0.9177 else if z <= 1.1600 value := 0.9186 else if z <= 1.1700 value := 0.9194 else if z <= 1.1800 value := 0.9202 else if z <= 1.1900 value := 0.9210 else if z <= 1.2000 value := 0.9217 else if z <= 1.2100 value := 0.9224 else if z <= 1.2200 value := 0.9230 else if z <= 1.2300 value := 0.9236 else if z <= 1.2400 value := 0.9243 else if z <= 1.2500 value := 0.9249 else if z <= 1.2600 value := 0.9254 else if z <= 1.2700 value := 0.9260 else if z <= 1.2800 value := 0.9265 else if z <= 1.2900 value := 0.9270 else if z <= 1.3000 value := 0.9274 else if z <= 1.3100 value := 0.9279 else if z <= 1.3200 value := 0.9283 else if z <= 1.3300 value := 0.9287 else if z <= 1.3400 value := 0.9291 else if z <= 1.3500 value := 0.9295 else if z <= 1.3600 value := 0.9299 else if z <= 1.3700 value := 0.9302 else if z <= 1.3800 value := 0.9306 else if z <= 1.3900 value := 0.9309 else if z <= 1.4000 value := 0.9312 else if z <= 1.4100 value := 0.9315 else if z <= 1.4200 value := 0.9319 else if z <= 1.4300 value := 0.9322 else if z <= 1.4400 value := 0.9325 else if z <= 1.4500 value := 0.9327 else if z <= 1.4600 value := 0.9330 else if z <= 1.4700 value := 0.9332 else if z <= 1.4800 value := 0.9335 else if z <= 1.4900 value := 0.9338 else if z <= 1.5000 value := 0.9340 else if z <= 1.5100 value := 0.9342 else if z <= 1.5200 value := 0.9345 else if z <= 1.5300 value := 0.9348 else if z <= 1.5400 value := 0.9351 else if z <= 1.5500 value := 0.9354 else if z <= 1.5600 value := 0.9357 else if z <= 1.5700 value := 0.9359 else if z <= 1.5800 value := 0.9362 else if z <= 1.5900 value := 0.9365 else if z <= 1.6000 value := 0.9367 else if z <= 1.6100 value := 0.9370 else if z <= 1.6200 value := 0.9372 else if z <= 1.6300 value := 0.9374 else if z <= 1.6400 value := 0.9377 else if z <= 1.6500 value := 0.9379 else if z <= 1.6600 value := 0.9381 else if z <= 1.6700 value := 0.9384 else if z <= 1.6800 value := 0.938 else if z <= 1.6900 value := 0.9388 else if z <= 1.7000 value := 0.9390 else if z <= 1.7100 value := 0.9392 else if z <= 1.7200 value := 0.9394 else if z <= 1.7300 value := 0.9396 else if z <= 1.7400 value := 0.9398 else if z <= 1.7500 value := 0.9400 else if z <= 1.7600 value := 0.9402 else if z <= 1.7700 value := 0.9404 else if z <= 1.7800 value := 0.9406 else if z <= 1.7900 value := 0.9408 else if z <= 1.8000 value := 0.9410 else if z <= 1.8100 value := 0.9411 else if z <= 1.8200 value := 0.9413 else if z <= 1.8300 value := 0.9415 else if z <= 1.8400 value := 0.9416 else if z <= 1.8500 value := 0.9418 else if z <= 1.8600 value := 0.9420 else if z <= 1.8700 value := 0.9421 else if z <= 1.8800 value := 0.9423 else if z <= 1.8900 value := 0.9424 //// PLOTING THE VALUES correct_value = value * 100 plot( (100 - correct_value) == 49.60 ? 0 : (100 - correct_value) , title="Probability of not happing ", color=color.green, linewidth=2, style = plot.style_stepline_diamond) plot( (correct_value) == 50.40 ? 0 : correct_value , title="Probability of happing ", color=color.red, linewidth=2, style = plot.style_stepline_diamond) //////////// CREATIING LABLE var label lable = na if barstate.islast lable := label.new( chart.point.from_index( bar_index[10], 50) , text = "Green menas Probability of happing" + "\n" + "Red means Probability of not happing ", color = color.green, style = label.style_label_lower_left) label.delete(lable[1])
Trend Flow Profile [AlgoAlpha]
https://www.tradingview.com/script/r4HlfwPz-Trend-Flow-Profile-AlgoAlpha/
AlgoAlpha
https://www.tradingview.com/u/AlgoAlpha/
4
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/ // © AlgoAlpha X © Sushiboi77 //@version=5 indicator(title='Trend Flow Profile [AlgoAlpha]', shorttitle='📈 TFP [AlgoAlpha]', overlay=false) // Input parameters orderFlowPeriod = input.int(12, minval=1, title='Trend Flow Period') emashow = input.bool(true, "Show EMA band?") emalen = input(8, "EMA Length") green = input.color(#00ffbb, "Up Color") //#00ffbb red = input.color(#ff1100, "Down Color") //#ff1100 //Trend Flow orderFlow = math.sum(close > close[1] ? volume : (close < close[1] ? -volume : 0), orderFlowPeriod) orderFlow := orderFlow /1000 //Rate of Change lenr = input(14, "ROC Length") roc = ta.roc(close, lenr) //Calculation trendflow = (roc + orderFlow) / 2 ematrend = ta.ema(trendflow, emalen) //Colors gcol1 = color.new(green, 20) gcol2 = color.new(green, 50) rcol1 = color.new(red, 20) rcol2 = color.new(red, 50) col = (trendflow > 0 ? (trendflow > trendflow[1] ? gcol1 : gcol2) : (trendflow < trendflow[1] ? rcol1 : rcol2)) // Plotting plot(trendflow, title='Combined Indicator', color= col, linewidth=2, style=plot.style_columns) plot(orderFlow, style = plot.style_columns, color=orderFlow > 0 ? color.new(green, 80) : color.new(red, 80)) plot(emashow ? ematrend: na, color = color.white)
Limited Growth Stock-to-Flow (LGS2F) [AlgoAlpha]
https://www.tradingview.com/script/GxV0eOCA-Limited-Growth-Stock-to-Flow-LGS2F-AlgoAlpha/
AlgoAlpha
https://www.tradingview.com/u/AlgoAlpha/
1
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/ // © AlgoAlpha X © Sushiboi77 //@version=5 indicator("∂ Limited Growth Stock-to-Flow [AlgoAlpha]", shorttitle = "∂ LG-S2F [AlgoAlpha]", overlay = true) green = input.color(#00ffbb, "Up Color") //#00ffbb red = input.color(#ff1100, "Down Color") //#ff1100 //Getting info for BTC supply and block height s = request.security("BTC_SUPPLY", "D", close) h = request.security("BTC_BLOCKS", "D", close) //Getting the +/- values for the error bands based on uncertainty values derived via error propagation of the standard errors from the model parameters. ae1 = 0.17/2 ae2 = 0.17 ae3 = 0.17*(3.0/2) be1 = 0.02/2 be2 = 0.02 be3 = 0.02*(3.0/2) ce1 = (22.7*1000000000000)/2 ce2 = 22.7*1000000000000 ce3 = (22.7*1000000000000)*(3.0/2) ////getting variations of coefficients a, b and c for the error bands using values above. a = 24.160 a1a = a+ae1 a1b = a+ae2 a1c = a+ae3 a2a = a-ae1 a2b = a-ae2 a2c = a-ae3 b = 0.377 b1a = b+be1 b1b = b+be2 b1c = b+be3 b2a = b-be1 b2b = b-be2 b2c = b-be3 c = 81.000*1000000000000 c1a = c+ce1 c1b = c+ce2 c1c = c+ce3 c2a = c-ce1 c2b = c-ce2 c2c = c-ce3 //The price formula is long, therefore I split the formula into multiple parts. // Getting the values for the parts of the price model formula as well as the error bands. w = a*math.pow((3.64568*1000000), b) w1a = a1a*math.pow((3.64568*1000000), b1a) w1b = a1b*math.pow((3.64568*1000000), b1b) w1c = a1c*math.pow((3.64568*1000000), b1c) w2a = a2a*math.pow((3.64568*1000000), b2a) w2b = a2b*math.pow((3.64568*1000000), b2b) w2c = a2c*math.pow((3.64568*1000000), b2c) e = -0.0000047619*b*h e1a = -0.0000047619*b1a*h e1b = -0.0000047619*b1b*h e1c = -0.0000047619*b1c*h e2a = -0.0000047619*b2a*h e2b = -0.0000047619*b2b*h e2c = -0.0000047619*b2c*h r = -math.pow(2, e) r1a = -math.pow(2, e1a) r1b = -math.pow(2, e1b) r1c = -math.pow(2, e1c) r2a = -math.pow(2, e2a) r2b = -math.pow(2, e2b) r2c = -math.pow(2, e2c) t = math.pow(s, -b) t1a = math.pow(s, -b1a) t1b = math.pow(s, -b1b) t1c = math.pow(s, -b1c) t2a = math.pow(s, -b2a) t2b = math.pow(s, -b2b) t2c = math.pow(s, -b2c) //Putting back the formula together, where p is the price and the rest are error bands. p = (1/s)*(c*math.exp(w*r*t)) p1a = (1/s)*(c1a*math.exp(w1a*r1a*t1a)) p1b = (1/s)*(c1b*math.exp(w1b*r1b*t1b)) p1c = (1/s)*(c1c*math.exp(w1c*r1c*t1c)) p2a = (1/s)*(c2a*math.exp(w2a*r2a*t2a)) p2b = (1/s)*(c2b*math.exp(w2b*r2b*t2b)) p2c = (1/s)*(c2c*math.exp(w2c*r2c*t2c)) // labelling the plots so I can use the fill() function. mm = plot(p, color = color.gray) ul = plot(p1a, color = color.new(red, 50)) um = plot(p1b, color = color.new(red, 70)) uu = plot(p1c, color = color.new(red, 90)) lu = plot(p2a, color = color.new(green, 50)) lm = plot(p2b, color = color.new(green, 70)) ll = plot(p2c, color = color.new(green, 90)) // filling the spaces inbetween the errorbands and the price to mark out overbought and oversold conditions. fill(mm, ul, color = color.new(red, 50)) fill(ul, um, color = color.new(red, 70)) fill(um, uu, color = color.new(red, 90)) fill(ll, lm, color = color.new(green, 90)) fill(lm, lu, color = color.new(green, 70)) fill(lu, mm, color = color.new(green, 50))
3X Hưng
https://www.tradingview.com/script/S0Jfa9ag/
Rockbuith
https://www.tradingview.com/u/Rockbuith/
4
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 3.0 at https://mozilla.org/MPL/2.0/ // © thiennarts //@version=5 indicator('3X', '3X', true,timeframe="30", timeframe_gaps=true, precision=4, max_labels_count=500) //------------------------------------------------------------------------------ bool1 = input(true, title='Line S1') atr1len = input.int(10, minval=1, title='ATR period 1') multiplier1 = input.float(3, minval=0.1, title='ATR multiplier 1') bool2 = input(true, title='Line S2') atr2len = input.int(20, minval=1, title='ATR period 2') multiplier2 = input.float(5, minval=0.1, title='ATR multiplier 2') bool3 = input(true, title='Line S3') atr3len = input.int(30, minval=1, title='ATR period 3') multiplier3 = input.float(9, minval=0.1, title='ATR multiplier 3') //------------------------------------------------------------------------------ atr1 = ta.atr(atr1len) atr2 = ta.atr(atr2len) atr3 = ta.atr(atr3len) sma = plot(ta.sma(close, 50), color=color.new(color.white, 0), title='0', display=display.none) // 1 ------------------------------------------------------------------------------ up_one = hl2 - atr1 * multiplier1 up1_one = up_one[1] up_one := close[1] > up1_one ? math.max(up_one, up1_one) : up_one down_one = hl2 + atr1 * multiplier1 down1_one = down_one[1] down_one := close[1] < down1_one ? math.min(down_one, down1_one) : down_one trendup_one = ta.crossover(close, down1_one) trenddown_one = ta.crossunder(close, up1_one) var trend_one = 0 if trendup_one trend_one := 1 trend_one if trenddown_one trend_one := -1 trend_one buysignal1 = trend_one == 1 and trend_one[1] == -1 sellsignal1 = trend_one == -1 and trend_one[1] == 1 greenline1 = plot(trend_one == 1 and bool1 ? up_one : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='S1') redline1 = plot(trend_one == -1 and bool1 ? down_one : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='S1') //fill(greenline1, sma, color=color.new(color.green, 90)) //fill(redline1, sma, color=color.new(color.red, 90)) //plotshape(buysignal1 and bool1 ? up_one : na, style=shape.arrowup, location=location.absolute, size=size.tiny, color=color.new(color.green, 0)) //plotshape(sellsignal1 and bool1 ? down_one : na, style=shape.arrowdown, location=location.absolute, size=size.tiny, color=color.new(color.red, 0)) //plotshape(buysignal1 and bool1 ? up_one : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.lime, 0), textcolor=color.new(color.black, 0)) //plotshape(sellsignal1 and bool1 ? down_one : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0)) // 2 ------------------------------------------------------------------------------ up_two = hl2 - atr2 * multiplier2 up1_two = up_two[1] up_two := close[1] > up1_two ? math.max(up_two, up1_two) : up_two down_two = hl2 + atr2 * multiplier2 down1_two = down_two[1] down_two := close[1] < down1_two ? math.min(down_two, down1_two) : down_two trendup_two = ta.crossover(close, down1_two) trenddown_two = ta.crossunder(close, up1_two) var trend_two = 0 if trendup_two trend_two := 1 trend_two if trenddown_two trend_two := -1 trend_two buysignal2 = trend_two == 1 and trend_two[1] == -1 sellsignal2 = trend_two == -1 and trend_two[1] == 1 greenline2 = plot(trend_two == 1 and bool2 ? up_two : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=3, title='S2') redline2 = plot(trend_two == -1 and bool2 ? down_two : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=3, title='S2') fill(greenline2, sma, color=color.new(color.green, 90)) fill(redline2, sma, color=color.new(color.red, 90)) plotshape(buysignal2 and bool2 ? up_two : na, style=shape.arrowup, location=location.absolute, size=size.tiny, color=color.new(color.green, 0)) plotshape(sellsignal2 and bool2 ? down_two : na, style=shape.arrowdown, location=location.absolute, size=size.tiny, color=color.new(color.red, 0)) // 3 ------------------------------------------------------------------------------ up_Three = hl2 - atr3 * multiplier3 up1_Three = up_Three[1] up_Three := close[1] > up1_Three ? math.max(up_Three, up1_Three) : up_Three down_Three = hl2 + atr3 * multiplier3 down1_Three = down_Three[1] down_Three := close[1] < down1_Three ? math.min(down_Three, down1_Three) : down_Three trendup_Three = ta.crossover(close, down1_Three) trenddown_Three = ta.crossunder(close, up1_Three) var trend_Three = 0 if trendup_Three trend_Three := 1 trend_Three if trenddown_Three trend_Three := -1 trend_Three buysignal3 = trend_Three == 1 and trend_Three[1] == -1 sellsignal3 = trend_Three == -1 and trend_Three[1] == 1 greenline3 = plot(trend_Three == 1 and bool3 ? up_Three : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=3, title='S3') redline3 = plot(trend_Three == -1 and bool3 ? down_Three : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=3, title='S3') fill(greenline3, sma, color=color.new(color.green, 90)) fill(redline3, sma, color=color.new(color.red, 90)) plotshape(buysignal3 and bool3 ? up_Three : na, style=shape.arrowup, location=location.absolute, size=size.tiny, color=color.new(color.green, 0)) plotshape(sellsignal3 and bool3 ? down_Three : na, style=shape.arrowdown, location=location.absolute, size=size.tiny, color=color.new(color.red, 0)) alertcondition(buysignal1 or buysignal2 or buysignal3, title='Buy S 123', message='Long Q=0.01') alertcondition(sellsignal1 or sellsignal2 or sellsignal3, title='Sell S 123', message='Short Q=0.01 ')
RSI MFI MultiTimeframe Oversold/Overbought
https://www.tradingview.com/script/wpMvWjAp/
Seungdori_
https://www.tradingview.com/u/Seungdori_/
2
study
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/ // © Seungdori_ //@version=5 indicator("RSI MFI MultiTimeframe Oversold/Overbought", shorttitle = 'RSI/MFI MTF', overlay =false) //Region : Inputs// main_osc = input.string(defval = 'RSI', title = '[ RSI / MFI / Sto RSI ] ', options = ['RSI', 'MFI', 'Sto RSI'], group = 'OSC') overbought = input.int(defval = 70, group = 'OSC') oversold = input.int(defval = 30, group = 'OSC') mtf1= input.timeframe('15' , title = 'TimeFrame 1st', group = 'TimeFrame') mtf2= input.timeframe('60' , title = 'TimeFrame 2nd', group = 'TimeFrame') mtf3= input.timeframe('240', title = 'TimeFrame 3rd', group = 'TimeFrame') mtf4= input.timeframe('D' , title = 'TimeFrame 4th', group = 'TimeFrame') mtf5= input.timeframe('W' , title = 'TimeFrame 5th', group = 'TimeFrame') grad = input.bool(defval = true, title = 'GRADIENT COLOR', group = 'COLOR') up_color = input.color(defval = color.rgb(9, 156, 142), title = 'UP', group = 'COLOR') down_color = input.color(defval = color.rgb(247, 30, 30), title = 'DOWN', group = 'COLOR') //Region : Oscilators// rsi = ta.rsi(close, 14) mfi = ta.mfi(hlc3, 14) smoothK = 3 smoothD = 3 lengthStoch = 14 k = ta.sma(ta.stoch(rsi, rsi, rsi, lengthStoch), smoothK) d = ta.sma(k, smoothD) var float osc = close var int osc_state = 0 if main_osc == 'MFI' osc := mfi if main_osc == 'RSI' osc := rsi if main_osc == 'Sto RSI' osc := d if osc > overbought osc_state := 1 if osc < oversold osc_state := -1 //Region : MTF// OSC_MTF_STATE_1 = request.security(syminfo.tickerid, mtf1, osc_state) OSC_MTF_STATE_2 = request.security(syminfo.tickerid, mtf2, osc_state) OSC_MTF_STATE_3 = request.security(syminfo.tickerid, mtf3, osc_state) OSC_MTF_STATE_4 = request.security(syminfo.tickerid, mtf4, osc_state) OSC_MTF_STATE_5 = request.security(syminfo.tickerid, mtf5, osc_state) OSC_MTF_1 = request.security(syminfo.tickerid, mtf1, osc, barmerge.gaps_off) OSC_MTF_2 = request.security(syminfo.tickerid, mtf2, osc, barmerge.gaps_off) OSC_MTF_3 = request.security(syminfo.tickerid, mtf3, osc, barmerge.gaps_off) OSC_MTF_4 = request.security(syminfo.tickerid, mtf4, osc, barmerge.gaps_off) OSC_MTF_5 = request.security(syminfo.tickerid, mtf5, osc, barmerge.gaps_off) //Region : Colors// color plot1_up_color = grad ? color.from_gradient(OSC_MTF_1, 60, overbought + 15, color.new(color.gray, 80),up_color) : color.green color plot2_up_color = grad ? color.from_gradient(OSC_MTF_2, 60, overbought + 15, color.new(color.gray, 80),up_color) : color.green color plot3_up_color = grad ? color.from_gradient(OSC_MTF_3, 60, overbought + 15, color.new(color.gray, 80),up_color) : color.green color plot4_up_color = grad ? color.from_gradient(OSC_MTF_4, 60, overbought + 15, color.new(color.gray, 80),up_color) : color.green color plot5_up_color = grad ? color.from_gradient(OSC_MTF_5, 60, overbought + 15, color.new(color.gray, 80),up_color) : color.green color plot1_down_color = grad ? color.from_gradient(OSC_MTF_1, oversold - 15, 60, down_color,color.new(color.gray, 80)) : color.red color plot2_down_color = grad ? color.from_gradient(OSC_MTF_2, oversold - 15, 60, down_color,color.new(color.gray, 80)) : color.red color plot3_down_color = grad ? color.from_gradient(OSC_MTF_3, oversold - 15, 60, down_color,color.new(color.gray, 80)) : color.red color plot4_down_color = grad ? color.from_gradient(OSC_MTF_4, oversold - 15, 60, down_color,color.new(color.gray, 80)) : color.red color plot5_down_color = grad ? color.from_gradient(OSC_MTF_5, oversold - 15, 60, down_color,color.new(color.gray, 80)) : color.red //Region : Plots// plot(1, style = plot.style_line, color= grad ? (OSC_MTF_1 >= 50 ? plot1_up_color : plot1_down_color) : OSC_MTF_STATE_1 == 1 ? color.new(up_color,15) : OSC_MTF_STATE_1 == -1 ? color.new(down_color,15) : na, linewidth =10) plot(2, style = plot.style_line, color= grad ? (OSC_MTF_2 >= 50 ? plot2_up_color : plot2_down_color) : OSC_MTF_STATE_2 == 1 ? color.new(up_color,15) : OSC_MTF_STATE_2 == -1 ? color.new(down_color,15) : na, linewidth =10) plot(3, style = plot.style_line, color= grad ? (OSC_MTF_3 >= 50 ? plot3_up_color : plot3_down_color) : OSC_MTF_STATE_3 == 1 ? color.new(up_color,15) : OSC_MTF_STATE_3 == -1 ? color.new(down_color,15) : na, linewidth =10) plot(4, style = plot.style_line, color= grad ? (OSC_MTF_4 >= 50 ? plot4_up_color : plot4_down_color) : OSC_MTF_STATE_4 == 1 ? color.new(up_color,15) : OSC_MTF_STATE_4 == -1 ? color.new(down_color,15) : na, linewidth =10) plot(5, style = plot.style_line, color= grad ? (OSC_MTF_5 >= 50 ? plot5_up_color : plot5_down_color) : OSC_MTF_STATE_5 == 1 ? color.new(up_color,15) : OSC_MTF_STATE_5 == -1 ? color.new(down_color,15) : na, linewidth =10) //Region : Labels// formatTimeframe(_tf) => tfStr = "" if _tf == "D" tfStr := "1D" else if _tf == "W" tfStr := "1W" else tfNum = str.tonumber(_tf) if tfNum < 60 tfStr := _tf + "m" else if tfNum == 60 tfStr := "1H" else hours = tfNum / 60 tfStr := str.tostring(hours) + "H" tfStr var label osc_label_1 = label.new(x = bar_index+3, y = 1, text = "", color = color.new(color.black, 100), textcolor=color.white, style = label.style_label_left) var label osc_label_2 = label.new(x = bar_index+3, y = 2, text = "", color = color.new(color.black, 100), textcolor=color.white, style = label.style_label_left) var label osc_label_3 = label.new(x = bar_index+3, y = 3, text = "", color = color.new(color.black, 100), textcolor=color.white, style = label.style_label_left) var label osc_label_4 = label.new(x = bar_index+3, y = 4, text = "", color = color.new(color.black, 100), textcolor=color.white, style = label.style_label_left) var label osc_label_5 = label.new(x = bar_index+3, y = 5, text = "", color = color.new(color.black, 100), textcolor=color.white, style = label.style_label_left) _label(_label, _timeframe, plot, _value) => label.set_x(_label, bar_index+5) label.set_y(_label, plot) label.set_text(_label, formatTimeframe(_timeframe) + ": " + str.tostring(math.round(_value,2))) _label(osc_label_1, mtf1, 1,OSC_MTF_1) _label(osc_label_2, mtf2, 2,OSC_MTF_2) _label(osc_label_3, mtf3, 3,OSC_MTF_3) _label(osc_label_4, mtf4, 4,OSC_MTF_4) _label(osc_label_5, mtf5, 5,OSC_MTF_5)
IU Average move
https://www.tradingview.com/script/jJIPBmVZ-IU-Average-move/
Strategy_coders
https://www.tradingview.com/u/Strategy_coders/
9
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/ // © shivammandrai //@version=5 indicator("IU Average move ",overlay=true) ///// CREATING CUSTOME SESSION custome_session = input.session("0915-1000", title='Enter your Session') ///// 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 ////// CREARING ARRAYS TO STORE VALUES var range_array = array.new<float>() var range_pec_array = array.new<float>() //// GETTING THE FIRST BAR OUTBOF THE SESSION starting_point = time[1] <= into_the_session and time > into_the_session //// CREATING RANGE VARIABLE var float range_ = na var float range_pec = na ///// CALCULATING RANGE AND STORING ITS VALUE if end_session_condition == 0 range_ := extend_high - extend_low array.push(range_array,range_) range_pec := (extend_high - extend_low) / (((extend_low + extend_high ) / 2)/100) array.push(range_pec_array, range_pec) //// GETTING THE AVRAGE OF THAT ARRAY avg = math.round(array.avg(range_array), precision = 2) avg_pec = math.round(array.avg(range_pec_array), precision = 3) ///// CREATING TABLE bgcolor = input.color(color.blue, "BG Color") bgcolor_tr = input.int(50, "Enter the color Transparancy") text_color = input.color(color.green, "Enter The text color ") var table array_table = table.new(position.top_right, 3,3 , bgcolor = color.new(bgcolor, bgcolor_tr)) text1 = "The Average Move " + "\n " + str.tostring(avg) text2 = "The % Average Move " + "\n " + str.tostring(avg_pec) //// SETTING TABLE VALUES table.cell(array_table, 1,1,text = text1, text_color = text_color) table.cell(array_table, 1,2,text = text2, text_color = text_color)
RSRW
https://www.tradingview.com/script/yD63DdWn/
MaskinAlv
https://www.tradingview.com/u/MaskinAlv/
8
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/ // © WorkPiece 12.28.21 OMXS30 //@version=5 indicator(title="Real Relative Strength", shorttitle="RSRW") comparedWithSecurity = input.symbol(title="Compare With", defval="SPY") length = input(title="Length", defval=12) //##########Rolling Price Change########## comparedClose = request.security(symbol=comparedWithSecurity, timeframe="", expression=close) comparedRollingMove = comparedClose - comparedClose[length] symbolRollingMove = close - close[length] //##########Rolling ATR Change########## symbolRollingATR = ta.atr(length)[1] comparedRollingATR = request.security (symbol=comparedWithSecurity, timeframe="", expression= ta.atr(length)[1]) //##########Calculations########## powerIndex = comparedRollingMove / comparedRollingATR RRS = (symbolRollingMove - powerIndex * symbolRollingATR) / symbolRollingATR //##########Plot########## RealRelativeStrength = plot(RRS, "RealRelativeStrength", color=color.blue, linewidth=2) Baseline = plot(0, "Baseline", color=color.red) //##########Extra Stuff########## //fill(RealRelativeStrength, Baseline, color = RRS >= 0 ? color.green : color.red, title="fill") correlated = ta.correlation(close, comparedClose, length) Correlation = plot(0, title="Correlation", color = correlated > .75 ? #00ff00 : correlated > .50 ? #00C000 : correlated > .25 ? #008000 : correlated > 0.0 ? #004000 :correlated > -.25 ? #400000 :correlated > -.50 ? #800000 :correlated > -.75 ? #C00000 :#FF0000, linewidth=3, style=plot.style_line)
Pocket Pivot, Darvas Box, EMA
https://www.tradingview.com/script/B9Jhbn4t-Pocket-Pivot-Darvas-Box-EMA/
Krishna216
https://www.tradingview.com/u/Krishna216/
1
study
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/ // © Krishna216 //@version=5 indicator("Pocket Pivot, Darvas Box, EMA", shorttitle="PPDBEMA", overlay=true) // EMA emaLength = input(20,title = "EMA Length") emaValue = ta.ema(close, emaLength) // Pocket Pivot Condition ppCondition = close > emaValue and close > close[1] and close[1] > ta.ema(close[1],emaLength) // Darvas Box Condition boxCondition = low > low[1] and high < high[1] // Plotting conditions plotshape(ppCondition, title="Pocket Pivot", color=color.green, style=shape.triangleup, location=location.belowbar, size=size.small) bgcolor(boxCondition ? color.new(color.blue, 90) : na, title="Darvas Box", offset=-1) plot(emaValue, title="EMA", color=color.orange, linewidth=2) // Plot Buy and Sell signals for Darvas Box (optional) boxBuyCondition = boxCondition and close > open boxSellCondition = boxCondition and close < open plotshape(boxBuyCondition, title="Box Buy Signal", color=color.green, style=shape.labelup, location=location.belowbar, text="Buy") plotshape(boxSellCondition, title="Box Sell Signal", color=color.red, style=shape.labeldown, location=location.abovebar, text="Sell")
WEEKLY AND TWO DAY HIGH LOW
https://www.tradingview.com/script/Qj9wpjpC-WEEKLY-AND-TWO-DAY-HIGH-LOW/
487551
https://www.tradingview.com/u/487551/
1
study
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 indicator("TWO DAY AND WEEKLY HIGH LOW", shorttitle="TWO DAY AND WEEKLY HIGH LOW", overlay=true) // Calculate the high and low of the two most recent candles high1 = request.security(syminfo.tickerid, "W", high[1]) low1 = request.security(syminfo.tickerid, "W", low[1]) high2 = request.security(syminfo.tickerid, "D", high[2]) low2 = request.security(syminfo.tickerid, "D", low[2]) // Plot lines to connect the high and low of the two most recent candles plot(high1, title="WEEK High", color=color.green, linewidth=2, style=plot.style_line) plot(low1, title="WEEK Low", color=color.red, linewidth=2, style=plot.style_line) plot(high2, title="2 DAY High", color=color.green, linewidth=2, style=plot.style_line) plot(low2, title="2 DAY Low", color=color.red, linewidth=2, style=plot.style_line)
Variable Keltner Channel For DCA
https://www.tradingview.com/script/MMDuM9yq-Variable-Keltner-Channel-For-DCA/
BrandonLimJH
https://www.tradingview.com/u/BrandonLimJH/
4
study
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/ // © BrandonLimJH //@version=5 indicator("Variable Keltner Channel For DCA", "DCA KC", true, timeframe="D") // EMAs & ATR EMA21 = ta.ema(close, 21) EMA34 = ta.ema(close, 34) ATR = ta.atr(10) // Calculation Bull_ATR = EMA21 - ATR * 1 Bear_ATR = EMA21 - ATR * 2 DCA_ATR = EMA21 > EMA34 ? Bull_ATR : Bear_ATR ATR_Color = EMA21 > EMA34 ? color.new(color.green, 50) : color.new(color.red, 50) // Plot plot(DCA_ATR, "DCA KC", ATR_Color)
Tick Gaps
https://www.tradingview.com/script/LLt0WnCq-Tick-Gaps/
JackDL92
https://www.tradingview.com/u/JackDL92/
0
study
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/ // © JackDL92 //@version=5 indicator("Tick Gaps", overlay=true) // Input for symbol type symbolType = input("triangleup", title="Symbol Type") // Function to check for gap-up isGapUp(open, close) => open > close[1] // Function to check for gap-down isGapDown(open, close) => open < close[1] // Plot symbols for gap-ups plotshape(series=isGapUp(open, close), title="Gap Up", color=color.new(color.green, 0), style=shape.triangleup, size=size.small, location=location.belowbar) // Plot symbols for gap-downs plotshape(series=isGapDown(open, close), title="Gap Down", color=color.new(color.red, 0), style=shape.triangledown, size=size.small, location=location.abovebar)
Autocorrelation State Stability [AlgoAlpha]
https://www.tradingview.com/script/bdmWVk2y-Autocorrelation-State-Stability-AlgoAlpha/
AlgoAlpha
https://www.tradingview.com/u/AlgoAlpha/
0
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/ // © AlgoAlpha X © Sushiboi77 //@version=5 indicator("⩰ Autocorrelation State Stability [AlgoAlpha]") len = input.int(14, "correlation Period") plotcol = input.color(#000000, "Color") //#00ffbb r = close corr1 = ta.correlation(r, r[1], len) corr2 = ta.correlation(r, r[2], len) corr3 = ta.correlation(r, r[3], len) corr4 = ta.correlation(r, r[4], len) corr5 = ta.correlation(r, r[5], len) corr6 = ta.correlation(r, r[6], len) corr7 = ta.correlation(r, r[7], len) corr8 = ta.correlation(r, r[8], len) corr9 = ta.correlation(r, r[9], len) corr10 = ta.correlation(r, r[10], len) dist1 = 1 - corr1 dist2 = 1 - corr2 dist3 = 1 - corr3 dist4 = 1 - corr4 dist5 = 1 - corr5 dist6 = 1 - corr6 dist7 = 1 - corr7 dist8 = 1 - corr8 dist9 = 1 - corr9 dist10 = 1 - corr10 var dist = array.new_float(size = 10) array.insert(dist, 0, dist1) array.insert(dist, 0, dist2) array.insert(dist, 0, dist3) array.insert(dist, 0, dist4) array.insert(dist, 0, dist5) array.insert(dist, 0, dist6) array.insert(dist, 0, dist7) array.insert(dist, 0, dist8) array.insert(dist, 0, dist9) array.insert(dist, 0, dist10) // Compute the standard deviation of distances over length stdDist = array.stdev(dist) for i = 1 to 10 array.remove(dist, 10) plot(1, color = color.gray) plot(0, color = color.gray) plot(-1, color = color.gray) plot(corr1, color = color.new(plotcol, 0)) plot(corr2, color = color.new(plotcol, 10)) plot(corr3, color = color.new(plotcol, 20)) plot(corr4, color = color.new(plotcol, 30)) plot(corr5, color = color.new(plotcol, 40)) plot(corr6, color = color.new(plotcol, 50)) plot(corr7, color = color.new(plotcol, 60)) plot(corr8, color = color.new(plotcol, 70)) plot(corr9, color = color.new(plotcol, 80)) plot(corr10, color = color.new(plotcol, 90)) bg = color.from_gradient(-stdDist, -1, 0, color.new(color.yellow, 50), color.new(color.red, 50)) bgcolor(bg)
DK RAYAK NEW BN STOCKS
https://www.tradingview.com/script/z1gkKJJU-DK-RAYAK-NEW-BN-STOCKS/
deep54321
https://www.tradingview.com/u/deep54321/
2
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/ //@version=5 indicator(title="DK RAYAK NEW", shorttitle = "BN DK Dashboard", overlay=true) TF1 = input.timeframe("15",title="Trade Entry Tf1") TF2 = input.timeframe("60",title="Higher Tf2") //TF3 = input(title="Higher Tf3",type=input.resolution, defval="60") ///// -- Table Inputs max = input.int(120,'Maximum Length',minval=2) min = input.int(10 ,'Minimum Length',minval=2) dash_loc = input.session("Top Right","Bank Dashboard Location" ,options=["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"] ,group='Style Settings') text_size = input.session('Small',"Dashboard Size" ,options=["Tiny","Small","Normal","Large"] ,group='Style Settings') cell_up = input(#4caf50,'Bullish Cell Color' ,group='Style Settings') cell_dn = input(#FF5252,'Bearish Cell Color' ,group='Style Settings') cell_netural = input(color.gray,'Neutral Cell Color' ,group='Style Settings') txt_col = input(color.black,'Text/Frame Color' ,group='Style Settings') cell_transp = input.int(50,'Cell Transparency' ,minval=0 ,maxval=100 ,group='Style Settings') //---- ////////////////// tUS = input.symbol("CURRENCYCOM:US30","TickerUS") [tsUS,tsUSC1] = request.security(tUS,'D',[close,close[1]]) tsUSTF1 = request.security(tUS,TF1,close[1]) tsUSTF2 = request.security(tUS,TF2,close[1]) //tsUSTF3 = request.security(tUS,TF3,close[1]) tsUSChng = (tsUS-tsUSC1) tsUSp = (tsUS-tsUSC1)*100/tsUSC1 tsUS1 = (tsUS-tsUSTF1)*100/tsUSTF1 tsUS2 = (tsUS-tsUSTF2)*100/tsUSTF2 //tsUS3 = (tsUS-tsUSC1)*100/tsUSTF3 cdow = tsUSp >= 0 ? cell_up : cell_dn //cdow = color.from_gradient(tsUSp,-10,10,cell_dn,cell_up) cdow1 = tsUS1 >= 0 ? cell_up : cell_dn cdow2 = tsUS2 >= 0 ? cell_up : cell_dn //cdow3 = tsUS3 >= 0 ? cell_up : cell_dn // Vix indvixin = input.symbol("NSE:INDIAVIX","Ticker Vix" ) [indvix,indvixC] = request.security(indvixin,'D',[close,close[1]]) indvixTF1 = request.security(indvixin,TF1,close[1]) indvixTF2 = request.security(indvixin,TF2,close[1]) //indvixTF3 = request.security(indvixin,TF3,close[1]) indvixChng = (indvix-indvixC) indvixp = (indvix - indvixC)*100/indvixC indvix1 = (indvix - indvixTF1)*100/indvixTF1 indvix2 = (indvix - indvixTF2)*100/indvixTF2 //indvix3 = (indvix - indvixTF3)*100/indvixTF3 cvix = indvixp >= 0 ? cell_up : cell_dn //textVix = 'VIX :' +str.tostring(indvix)+' ' +str.tostring(truncate((indvix - indvixC),3)) +' (' + str.tostring(truncate(indvixp,2)) +'%)' // t1 = input.symbol("NSE:HDFCBANK","Ticker1") t2 = input.symbol("NSE:ICICIBANK" , "Ticker2") t3 = input.symbol("NSE:KOTAKBANK", "Ticker3") t4 = input.symbol("NSE:SBIN", "Ticker4") t5 = input.symbol("NSE:AXISBANK" , "Ticker5") t6 = input.symbol("NSE:INDUSINDBK" , "Ticker6") t7 = input.symbol("NSE:AUBANK" , "Ticker7") t8 = input.symbol("NSE:BANDHANBNK" , "Ticker8") //t9 = input("NSE:PNB", "Ticker9", type=input.symbol) //t10 = input("NSE:FEDERALBNK" , "Ticker10", type=input.symbol) //t11 = input("NSE:RBLBANK", "Ticker11", type=input.symbol ) //t12 = input("NSE:YESBANK", "Ticker12", type=input.symbol ) [ts1,ts1C] = request.security(t1,'D',[close,close[1]]) ts1TF1 = request.security(t1,TF1,close[1]) ts1TF2 = request.security(t1,TF2,close[1]) //ts1TF3 = request.security(t1,TF3,close[1]) ts1Chng = (ts1-ts1C) ts1p = (ts1-ts1C)*100/ts1C ts1p1 = (ts1 - ts1TF1)*100/ts1TF1 ts1p2 = (ts1 - ts1TF2)*100/ts1TF2 //ts1p3 = (ts1 - ts1TF3)*100/ts1TF3 //------------------ [ts2,ts2C] = request.security(t2,'D',[close,close[1]]) ts2TF1 = request.security(t2,TF1,close[1]) ts2TF2 = request.security(t2,TF2,close[1]) //ts2TF3 = request.security(t2,TF3,close[1]) ts2Chng = (ts2-ts2C) ts2p = (ts2-ts2C)*100/ts2C ts2p1 = (ts2 - ts2TF1)*100/ts2TF1 ts2p2 = (ts2 - ts2TF2)*100/ts2TF2 //ts2p3 = (ts2 - ts2TF3)*100/ts2TF3 //--------------- [ts3,ts3C] = request.security(t3,'D',[close,close[1]]) ts3TF1 = request.security(t3,TF1,close[1]) ts3TF2 = request.security(t3,TF2,close[1]) //ts3TF3 = request.security(t3,TF3,close[1]) ts3Chng = (ts3-ts3C) ts3p = (ts3-ts3C)*100/ts3C ts3p1 = (ts3 - ts3TF1)*100/ts3TF1 ts3p2 = (ts3 - ts3TF2)*100/ts3TF2 //ts3p3 = (ts3 - ts3TF3)*100/ts3TF3 //---------------- [ts4,ts4C] = request.security(t4,'D',[close,close[1]]) ts4TF1 = request.security(t4,TF1,close[1]) ts4TF2 = request.security(t4,TF2,close[1]) //ts4TF3 = request.security(t4,TF3,close[1]) ts4Chng = (ts4-ts4C) ts4p = (ts4-ts4C)*100/ts4C ts4p1 = (ts4 - ts4TF1)*100/ts4TF1 ts4p2 = (ts4 - ts4TF2)*100/ts4TF2 //ts4p3 = (ts4 - ts4TF3)*100/ts4TF3 [ts5,ts5C] = request.security(t5,'D',[close,close[1]]) ts5TF1 = request.security(t5,TF1,close[1]) ts5TF2 = request.security(t5,TF2,close[1]) //ts5TF3 = request.security(t5,TF3,close[1]) ts5Chng = (ts5-ts5C) ts5p = (ts5-ts5C)*100/ts5C ts5p1 = (ts5 - ts5TF1)*100/ts5TF1 ts5p2 = (ts5 - ts5TF2)*100/ts5TF2 //ts5p3 = (ts5 - ts5TF3)*100/ts5TF3 [ts6,ts6C] = request.security(t6,'D',[close,close[1]]) //ts6C = request.security(t6,'D',close[1]) ts6TF1 = request.security(t6,TF1,close[1]) ts6TF2 = request.security(t6,TF2,close[1]) //ts6TF3 = request.security(t6,TF3,close[1]) ts6Chng = (ts6-ts6C) ts6p = (ts6-ts6C)*100/ts6C ts6p1 = (ts6 - ts6TF1)*100/ts6TF1 ts6p2 = (ts6 - ts6TF2)*100/ts6TF2 //ts6p3 = (ts6 - ts6TF3)*100/ts6TF3 [ts7,ts7C] = request.security(t7,'D',[close,close[1]]) ts7TF1 = request.security(t7,TF1,close[1]) ts7TF2 = request.security(t7,TF2,close[1]) //ts6TF3 = request.security(t6,TF3,close[1]) ts7Chng = (ts7-ts7C) ts7p = (ts7-ts7C)*100/ts7C ts7p1 = (ts7 - ts7TF1)*100/ts7TF1 ts7p2 = (ts7 - ts7TF2)*100/ts7TF2 //ts6p3 = (ts6 - ts6TF3)*100/ts6TF3 [ts8,ts8C] = request.security(t8,'D',[close,close[1]]) ts8TF1 = request.security(t8,TF1,close[1]) ts8TF2 = request.security(t8,TF2,close[1]) //ts6TF3 = request.security(t6,TF3,close[1]) ts8Chng = (ts8-ts8C) ts8p = (ts8-ts8C)*100/ts8C ts8p1 = (ts8 - ts8TF1)*100/ts8TF1 ts8p2 = (ts8 - ts8TF2)*100/ts8TF2 //ts6p3 = (ts6 - ts6TF3)*100/ts6TF3 /// -------------- Table Start ------------------- var table_position = dash_loc == 'Top Left' ? position.top_left : dash_loc == 'Bottom Left' ? position.bottom_left : dash_loc == 'Middle Right' ? position.middle_right : dash_loc == 'Bottom Center' ? position.bottom_center : dash_loc == 'Top Right' ? position.top_right : position.bottom_right var table_text_size = text_size == 'Tiny' ? size.tiny : text_size == 'Small' ? size.small : text_size == 'Normal' ? size.normal : size.large var t = table.new(table_position,8,math.abs(max-min)+2, frame_color=txt_col, frame_width=1, border_color=txt_col, border_width=1) if (barstate.islast) table.cell(t,1,0,'Symbol',text_color=txt_col,text_size=table_text_size) table.cell(t,2,0,'LTP',text_color=txt_col,text_size=table_text_size) table.cell(t,3,0,'Chng',text_color=txt_col,text_size=table_text_size) table.cell(t,4,0,'%Chng',text_color=txt_col,text_size=table_text_size) table.cell(t,5,0, TF1 ,text_color=txt_col,text_size=table_text_size) table.cell(t,6,0, TF2 ,text_color=txt_col,text_size=table_text_size) //table.cell(t,7,0, TF3 ,text_color=txt_col,text_size=table_text_size) // Dow table.cell(t,1,1,'Dow',text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,1, str.tostring(tsUS) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cdow,cell_transp)) table.cell(t,3,1, str.tostring(tsUSChng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cdow,cell_transp)) table.cell(t,4,1, str.tostring(tsUSp, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cdow,cell_transp)) table.cell(t,5,1, str.tostring(tsUS1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cdow1,cell_transp)) table.cell(t,6,1, str.tostring(tsUS2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cdow2,cell_transp)) //table.cell(t,7,1, str.tostring(tsUS3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cdow3,cell_transp)) // Vix table.cell(t,1,2, str.replace_all(indvixin, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,2, str.tostring(indvix) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(indvixp >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,2, str.tostring(indvixChng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(indvixp >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,2, str.tostring(indvixp, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(indvixp >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,2, str.tostring(indvix1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(indvix1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,2, str.tostring(indvix2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(indvix2 >= 0 ? cell_up : cell_dn ,cell_transp)) //table.cell(t,7,2, str.tostring(indvix3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(indvix3 >= 0 ? cell_up : cell_dn ,cell_transp)) // 1 table.cell(t,1,3, str.replace_all(t1, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,3, str.tostring(ts1) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts1p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,3, str.tostring(ts1Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts1p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,3, str.tostring(ts1p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts1p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,3, str.tostring(ts1p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts1p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,3, str.tostring(ts1p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts1p2 >= 0 ? cell_up : cell_dn ,cell_transp)) //table.cell(t,7,3, str.tostring(ts1p3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts1p3 >= 0 ? cell_up : cell_dn ,cell_transp)) // 2 table.cell(t,1,4, str.replace_all(t2, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,4, str.tostring(ts2) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts2p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,4, str.tostring(ts2Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts2p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,4, str.tostring(ts2p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts2p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,4, str.tostring(ts2p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts2p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,4, str.tostring(ts2p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts2p2 >= 0 ? cell_up : cell_dn ,cell_transp)) //table.cell(t,7,4, str.tostring(ts2p3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts2p3 >= 0 ? cell_up : cell_dn ,cell_transp)) // 3 table.cell(t,1,5, str.replace_all(t3, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,5, str.tostring(ts3) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts3p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,5, str.tostring(ts3Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts3p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,5, str.tostring(ts3p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts3p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,5, str.tostring(ts3p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts3p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,5, str.tostring(ts3p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts3p2 >= 0 ? cell_up : cell_dn ,cell_transp)) //table.cell(t,7,5, str.tostring(ts3p3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts3p3 >= 0 ? cell_up : cell_dn ,cell_transp)) // 4 table.cell(t,1,6, str.replace_all(t4, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,6, str.tostring(ts4) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts4p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,6, str.tostring(ts4Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts4p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,6, str.tostring(ts4p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts4p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,6, str.tostring(ts4p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts4p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,6, str.tostring(ts4p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts4p2 >= 0 ? cell_up : cell_dn ,cell_transp)) //table.cell(t,7,6, str.tostring(ts4p3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts4p3 >= 0 ? cell_up : cell_dn ,cell_transp)) // 5 table.cell(t,1,7, str.replace_all(t5, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,7, str.tostring(ts5) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts5p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,7, str.tostring(ts5Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts5p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,7, str.tostring(ts5p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts5p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,7, str.tostring(ts5p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts5p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,7, str.tostring(ts5p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts5p2 >= 0 ? cell_up : cell_dn ,cell_transp)) //table.cell(t,7,7, str.tostring(ts5p3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts5p3 >= 0 ? cell_up : cell_dn ,cell_transp)) // 6 table.cell(t,1,8, str.replace_all(t6, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,8, str.tostring(ts6) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts6p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,8, str.tostring(ts6Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts6p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,8, str.tostring(ts6p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts6p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,8, str.tostring(ts6p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts6p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,8, str.tostring(ts6p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts6p2 >= 0 ? cell_up : cell_dn ,cell_transp)) //table.cell(t,7,8, str.tostring(ts6p3, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts6p3 >= 0 ? cell_up : cell_dn ,cell_transp)) // 7 table.cell(t,1,9, str.replace_all(t7, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,9, str.tostring(ts7) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts7p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,9, str.tostring(ts7Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts7p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,9, str.tostring(ts7p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts7p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,9, str.tostring(ts7p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts7p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,9, str.tostring(ts7p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts7p2 >= 0 ? cell_up : cell_dn ,cell_transp)) // 8 table.cell(t,1,10, str.replace_all(t8, 'NSE:', ''),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(t,2,10, str.tostring(ts8) ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts8p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,3,10, str.tostring(ts8Chng),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts8p >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,4,10, str.tostring(ts8p, '#.##') +'%',text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts8p >= 0 ? cell_up : cell_dn ,cell_transp) ) table.cell(t,5,10, str.tostring(ts8p1, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts8p1 >= 0 ? cell_up : cell_dn ,cell_transp)) table.cell(t,6,10, str.tostring(ts8p2, '#.##') +'%' ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new(ts8p2 >= 0 ? cell_up : cell_dn ,cell_transp)) //========== Indicators Logic ShowEma = input(false, "──── Show EMA ─────") LenEma = input.int(defval=20) EMA = ta.ema(close, LenEma) //rsi = rsi(close, 14) plot(ShowEma?EMA:na, title="EMA", style=plot.style_line, color=color.orange) //study("Supertrend", overlay=true) ShowSuperTrend = input(true, "──── Show SuperTrend Indicator ─────") highlighting = input.bool(title="Show HIghlights", defval=false) len = input.int( defval=10) mult = input.int( defval=2) [superTrend, dir] = ta.supertrend(mult, len) colResistance = dir == 1 and dir == dir[1] ? color.new(color.red, 0) : color.new(color.red, 100) colSupport = dir == -1 and dir == dir[1] ? color.new(color.green, 0) : color.new(color.green, 100) upPlot = plot(ShowSuperTrend?superTrend:na, color = colSupport, linewidth=1) dnPlot = plot(ShowSuperTrend?superTrend:na , color = colResistance, linewidth=1) hPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0, editable = false) longFill = highlighting ? (dir == -1 ? color.new(color.green, 20) : na) : na shortFill = highlighting ? (dir == 1 ? color.new(color.red, 20) : na ) : na fill(hPlot, upPlot, color=longFill) fill(hPlot, dnPlot, color=shortFill) //Plot Buy Signal buySignal = dir == -1 and dir[1] == 1 plotshape(buySignal ? superTrend : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green) //plotshape(buySignal ? superTrend : na, title="BUY", text="BUY", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white) //Plot Sell Signal sellSignal = dir == 1 and dir[1] == -1 plotshape(sellSignal ? superTrend : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red) //plotshape(sellSignal ? superTrend : na, title="SELL", text="SELL", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white) // === Volume === ShowHighVolume = input(true, 'Show Strong Volume ') Averageval1 = input.int(title='Average Volume BankNifty: (in K)', defval=40, minval=1) Averageval2 = input.int(title='Average Volume Nifty: (in K)', defval=100, minval=1) Averageval = syminfo.ticker == 'BANKNIFTY1!' ? Averageval1 * 1000 : syminfo.ticker == 'NIFTY1!' ? Averageval2 * 1000 : ta.sma(volume, 20) //plotshape(varstrong,style=shape.square, location=location.bottom, color=color.blue) /// Marking bull bear Bull = close >= open and volume >= Averageval colB = close > ta.vwap ? color.green : color.yellow plotshape(ShowHighVolume ? Bull : na, title='Bull', style=shape.triangleup, location=location.bottom, color=colB) Bear = close <= open and volume >= Averageval colR = close < ta.vwap ? color.red : color.yellow plotshape(ShowHighVolume ? Bear : na, title='Bear', style=shape.triangledown, location=location.bottom, color=colR) //VWAP showVwap = input(true, "────Show VWAP ─────") VWAP = ta.vwap plot(showVwap?VWAP :na,title="VWAP", linewidth=1) //RSI rsiPeriod = input.int(title="RSI Period", defval=14, minval=2, maxval=365 , group='RSI' ) RSI = ta.rsi(close, rsiPeriod) rsitxt = RSI > 50 ? 'UP' : 'Down' // mfiPeriod = input.int(title="MFI Period", defval=10, minval=2, maxval=365) MFI = ta.mfi(hlc3,mfiPeriod) MFItxt = MFI > 50 ? 'UP' : 'Down' //ADX-DMI dmiPeriod = input.int(title="DMI Period", defval=13, minval=2, maxval=365, group='ADX') dmiSmoothing = input.int(title="+/-DMI Smoothing", defval=8, minval=2, maxval=365, group='ADX') [diplus, diminus, adx] = ta.dmi(dmiPeriod, dmiSmoothing) f_col_adx(diplus,diminus,adx) => var ADXColor = color.white var ADXText = '' var DI1Color = color.white var DI1Text = '' var DI2Color = color.white var DI2Text = '' if adx >= 25 and diplus > diminus ADXColor:= color.new( cell_up ,cell_transp) ADXText:= 'Strong UP' else if adx >= 25 and diplus < diminus ADXColor:= color.new( cell_dn ,cell_transp) ADXText:= 'Strong Down' else if adx < 25 and adx >= 20 and diplus > diminus ADXColor:= color.new( color.orange ,cell_transp) ADXText:= 'UP' else if adx < 25 and adx >= 20 and diplus < diminus ADXColor:= color.new( color.orange ,cell_transp) ADXText:= 'Down' else if adx < 20 and adx > 15 ADXColor:= color.new( cell_netural ,cell_transp) ADXText:= 'Neutral' else if adx <= 15 ADXColor:= color.new( cell_netural ,cell_transp) ADXText:= 'Neutral' if diplus >= 25 and diplus > diminus DI1Color:= color.new( cell_up ,cell_transp) DI1Text:= 'UP' else DI1Color:= color.new( cell_netural ,cell_transp) DI1Text:= '-' if diminus >= 25 and diplus < diminus DI2Color:= color.new( cell_dn ,cell_transp) DI2Text:= 'Down' else DI2Color:= color.new( cell_netural ,cell_transp) DI2Text:= '-' [ADXColor,ADXText,DI1Color,DI1Text,DI2Color,DI2Text] [ADXColor,ADXText,DI1Color,DI1Text,DI2Color,DI2Text] = f_col_adx(diplus,diminus,adx) f_combo(srcInput,LenSma,rsiPeriod,dmiPeriod, dmiSmoothing, mult, len) => [Sdip,Sdim,Sadx] = ta.dmi(dmiPeriod, dmiSmoothing) [Sst,Sdir] = ta.supertrend(mult, len) Svwap = ta.vwap(srcInput) Sma = ta.ema(srcInput,LenSma) Srsi = ta.rsi(srcInput,rsiPeriod) Svol = volume SAvol = ta.sma(volume,20) [Svwap,Sma,Srsi, Sdip, Sdim, Sadx, Sst, Sdir,Svol,SAvol] [Svwap1,Sma1,Srsi1,Sdip1,Sdim1,Sadx1, Sst1, Sdir1,Svol1,SAvol1] = request.security(syminfo.tickerid,TF1,f_combo(close,LenEma,rsiPeriod,dmiPeriod, dmiSmoothing ,mult, len)) [ADXColor1,ADXText1,DI1Color1,DI1Text1,DI2Color1,DI2Text1] = f_col_adx(Sdip1,Sdim1,Sadx1) [Svwap2,Sma2,Srsi2,Sdip2,Sdim2,Sadx2, Sst2, Sdir2,Svol2,SAvol2] = request.security(syminfo.tickerid,TF2,f_combo(close,LenEma,rsiPeriod,dmiPeriod, dmiSmoothing ,mult, len)) [ADXColor2,ADXText2,DI1Color2,DI1Text2,DI2Color2,DI2Text2] = f_col_adx(Sdip2,Sdim2,Sadx2) //-------------- Table Start ------------------- dash_loc1 = input.session("Bottom Right","Indicator Dashboard Location" ,options=["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"] ,group='Indicator Table Settings') var table_position1 = dash_loc1 == 'Top Left' ? position.top_left : dash_loc1 == 'Bottom Left' ? position.bottom_left : dash_loc1 == 'Middle Right' ? position.middle_right : dash_loc1 == 'Bottom Center' ? position.bottom_center : dash_loc1 == 'Top Right' ? position.top_right : position.bottom_right var tb1 = table.new(table_position1,8,math.abs(max-min)+2, frame_color=txt_col, frame_width=1, border_color=txt_col, border_width=1) if (barstate.islast) table.cell(tb1,1,0,'Indicator',text_color=txt_col,text_size=table_text_size) table.cell(tb1,2,0,'Value',text_color=txt_col,text_size=table_text_size) table.cell(tb1,3,0,'Trend' ,text_color=txt_col,text_size=table_text_size) table.cell(tb1,4,0, TF1 ,text_color=txt_col,text_size=table_text_size) table.cell(tb1,5,0, TF2 ,text_color=txt_col,text_size=table_text_size) // table.cell(tb1,1,1,'Vwap',text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(tb1,2,1,str.tostring(VWAP, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > VWAP ? cell_up : cell_dn ,cell_transp)) vwaptxt = close >VWAP ? 'UP' : 'Down' table.cell(tb1,3,1, vwaptxt ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > VWAP ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,4,1,str.tostring(Svwap1, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > Svwap1 ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,5,1,str.tostring(Svwap2, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > Svwap2 ? cell_up : cell_dn ,cell_transp)) //VWMA table.cell(tb1,1,2,'EMA '+str.tostring(LenEma),text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(tb1,2,2,str.tostring(EMA, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > EMA ? cell_up : cell_dn ,cell_transp)) vwmatxt = close > EMA ? 'UP' : 'Down' table.cell(tb1,3,2, vwmatxt ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > EMA ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,4,2,str.tostring(Sma1, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > Sma1 ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,5,2,str.tostring(Sma2, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > Sma2 ? cell_up : cell_dn ,cell_transp)) //SuperTrend table.cell(tb1,1,3,'ST',text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(tb1,2,3,str.tostring(superTrend, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > superTrend ? cell_up : cell_dn ,cell_transp)) STtxt = close > superTrend ? 'UP' : 'Down' table.cell(tb1,3,3, STtxt ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > superTrend ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,4,3,str.tostring(Sst1, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > Sst1 ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,5,3,str.tostring(Sst2, '#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( close > Sst2 ? cell_up : cell_dn ,cell_transp)) //RSI table.cell(tb1,1,4,'RSI',text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(tb1,2,4,str.tostring(RSI, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( RSI > 50 ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,3,4, rsitxt ,text_color=txt_col,text_size=table_text_size, bgcolor=color.new( RSI > 50 ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,4,4,str.tostring(Srsi1, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( Srsi1 > 50 ? cell_up : cell_dn ,cell_transp)) table.cell(tb1,5,4,str.tostring(Srsi2, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new( Srsi2 > 50 ? cell_up : cell_dn ,cell_transp)) //ADX table.cell(tb1,1,5,'ADX',text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(tb1,2,5,str.tostring(adx, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= ADXColor) table.cell(tb1,3,5, ADXText ,text_color=txt_col,text_size=table_text_size, bgcolor=ADXColor) table.cell(tb1,4,5,str.tostring(Sadx1, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= ADXColor1) table.cell(tb1,5,5,str.tostring(Sadx2, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= ADXColor2) //DI+ table.cell(tb1,1,6,'DI +',text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(tb1,2,6,str.tostring(diplus, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= DI1Color) table.cell(tb1,3,6, DI1Text ,text_color=txt_col,text_size=table_text_size, bgcolor=DI1Color) table.cell(tb1,4,6,str.tostring(Sdip1, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= DI1Color1) table.cell(tb1,5,6,str.tostring(Sdip2, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= DI1Color2) //DI- table.cell(tb1,1,7,'DI -',text_color=color.white,text_size=table_text_size,bgcolor=color.black) table.cell(tb1,2,7,str.tostring(diminus, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= DI2Color) table.cell(tb1,3,7, DI2Text ,text_color=txt_col,text_size=table_text_size, bgcolor=DI2Color) table.cell(tb1,4,7,str.tostring(Sdim1, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= DI2Color1) table.cell(tb1,5,7,str.tostring(Sdim2, '#.#'),text_color=txt_col,text_size=table_text_size, bgcolor= DI2Color2)