Convert TradingView Indicator to ThinkorSwim

javin82

New member
I need help converting a pine script indicator into a think script study for Thinkorswim. The name of the indicator is called Range. It is a reversal indicator and plots long and short signals. If you can help me with this, please let me know. Thank you!

PineScript code below:
Code:
//////////////
//@version=3
study("Range fv2",overlay=true)
showTrendLine = input(false, title="Show Trend Line")
colorBars = input(true, title="Color Bars?")
filterTrend = input(true, title="Filter Trend?")

//Source
src = close

//Sampling Period
per = input(defval=25, minval=1, title="Sampling Period")

//Range Multiplier
mult = input(defval=2, minval=0, title="Range Multiplier")

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Definitions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

//Smooth Average Range
smoothrng(x, t, m)=>
    wper      = (t/3) - 1
    avrng     = sma(abs(x - x[1]), t)
    smoothrng = sma(avrng, wper)*m
    smoothrng
smrng = smoothrng(src, per, mult)

//Range Filter
rngfilt(x, r)=>
    rngfilt  = x
    rngfilt := x > nz(rngfilt[1]) ? ((x - r) < nz(rngfilt[1]) ? nz(rngfilt[1]) : (x - r)) : ((x + r) > nz(rngfilt[1]) ? nz(rngfilt[1]) : (x + r))
    rngfilt
filt = rngfilt(src, smrng)

//Filter Direction
upward   = 0.0
upward  := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])

//Target Bands
hband = filt + smrng
lband = filt - smrng

//Colors
filtcolor = upward > 0 ? lime : downward > 0 ? red : orange
barcolor  = (src > filt) and (src > src[1]) and (upward > 0) ? lime : (src > filt) and (src < src[1]) and (upward > 0) ? green : (src < filt) and (src < src[1]) and (downward > 0) ? red : (src < filt) and (src > src[1]) and (downward > 0) ? maroon : orange
barcolor(colorBars ? barcolor : na)

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Plots
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

//Range Filter
if filterTrend == true
    showTrendLine := false
filtplot = plot(filterTrend ? filt : na, color=filtcolor, linewidth=4, title="Range Filter")
//
Factor=input(3, minval=1,maxval = 100)
Pd=input(3, minval=1,maxval = 100)

Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp = 0.0
TrendDown = 0.0
linecolor = na
up = na
down = na
Tsl = 0.0
Trend = 0.0
TrendUp := close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown := close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend := close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl := Trend==1? TrendUp: TrendDown
linecolor := Trend == 1 ? green : red
plot(showTrendLine ? Tsl : na, color = linecolor , style = line , linewidth = 3,title = "SuperTrend")

// Strategy


longCond = na
shortCond = na
longCond :=crossunder(Tsl,filt)
shortCond :=crossover(Tsl,filt)

// Count your long short conditions for more control with Pyramiding

sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])

if longCond
    sectionLongs := sectionLongs + 1
    sectionShorts := 0

if shortCond
    sectionLongs := 0
    sectionShorts := sectionShorts + 1

// Pyramiding

pyrl = 1


// These check to see your signal and cross references it against the pyramiding settings above

longCondition = longCond and sectionLongs <= pyrl
shortCondition = shortCond and sectionShorts <= pyrl

// Get the price of the last opened long or short

last_open_longCondition = na
last_open_shortCondition = na
last_open_longCondition := longCondition ? open : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? open : nz(last_open_shortCondition[1])

// Check if your last postion was a long or a short

last_longCondition = na
last_shortCondition = na
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])

in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition

// Take profit

isTPl = input(true, "Take Profit Long")
isTPs = input(true, "Take Profit Short")
tp = input(5, "Take Profit ", type=float)
long_tp = isTPl and crossover(high, (1+(tp/100))*last_open_longCondition) and longCondition == 0 and in_longCondition  == 1
short_tp = isTPs and crossunder(low, (1-(tp/100))*last_open_shortCondition) and shortCondition == 0 and in_shortCondition == 1


// Create a single close for all the different closing conditions.

long_close = long_tp  ? 1 : 0
short_close = short_tp ? 1 : 0

// Get the time of the last close

last_long_close = na
last_short_close = na
last_long_close := long_close ? time : nz(last_long_close[1])
last_short_close := short_close ? time : nz(last_short_close[1])


// Alerts & Signals

bton(b) => b ? 1 : 0
plotshape(longCondition , title="Long", color=green, textcolor=green, transp=0,
          style=shape.triangleup, location=location.belowbar, size=size.small,text="LONG",offset=0)


plotshape(shortCondition, title="Short", color=red, textcolor=red, transp=0,
          style=shape.triangledown, location=location.abovebar, size=size.small,text="SHORT",offset=0)


//plotshape(longCondition, title = "BUY Signal", text = "Buy", style=shape.triangleup, location=location.belowbar, color = blue, editable = false, transp = 0)
//plotshape(shortCondition, title = "SELL Signal", text = "Sell", style=shape.triangledown, location=location.abovebar, color = black, editable = false, transp = 0)

plotshape(long_tp and last_longCondition > nz(last_long_close[1]), text ="TP", title="Take Profit Long", style=shape.triangledown,
   location=location.abovebar, color = red, editable = false, transp = 0)
plotshape(short_tp and last_shortCondition > nz(last_short_close[1]) , text ="TP", title="Take Profit Short", style=shape.triangleup,
   location=location.belowbar, color = lime, editable = false, transp = 0)

alertcondition(bton(longCondition), title="Long Alert")
alertcondition(bton(shortCondition), title="Short Alert")
alertcondition(bton(long_tp and last_longCondition > nz(last_long_close[1])), title="Take Profit Long")
alertcondition(bton(short_tp and last_shortCondition > nz(last_short_close[1])), title="Take Profit Short")

Any help I can get with this will be greatly appreciated! Thank you!

Admin's Notes:

You can now use this thread to make your own request. If there is a TradingView script that you would like to see in ThinkorSwim, please post the source code and link to that script below. We'll try our best to help you with the conversion.

Below are the TradingView scripts that have been converted to TOS.
 
Last edited by a moderator:

BenTen

Administrative
Staff
VIP
@borntostun Not exactly the whole thing in one package but hopefully this helps.

Zero Lag EMA

Code:
# Zero Lag Exponential Moving Average
# Mobius
# V01.07.2010
# Maintains the weighting of most recent price but removes the infinite weighting of past price.

nput length = 10;

def K = 2 / (length + 1);
def lag = (length - 1) / 2;
def ZLEMA = K * (2 * close - close[lag]) + (1 - K) * ZLEMA[1];
plot data = ZLEMA;
# End Code Zero Lag EMA

Zero Lag MACD

Code:
# Super Zero Lag MACD
# Mobius

declare lower;
input Fast_Length = 5;
input Slow_Length = 13;
input MACD_Length = 3;
plot MACD5 = (MACD("fast length" = Fast_Length,
                   "slow length" = Slow_Length,
                   "macd length" = MACD_Length).Avg /
        StDev(MACD("fast length" = Fast_Length,
                   "slow length" = Slow_Length,
                   "macd length" = MACD_Length).Diff, Slow_Length));
MACD5.SetDefaultColor(Color.CYAN);
plot Squeeze = if BollingerBandsSMA().UpperBand < KeltnerChannels().Upper_Band
               then 0
               else Double.NaN;
Squeeze.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeeze.SetLineWeight(3);
Squeeze.SetDefaultColor(Color.GREEN);
plot zero = if IsNaN(close) or !IsNaN(Squeeze) then Double.NaN else 0;
zero.SetPaintingStrategy(PaintingStrategy.POINTS);
zero.SetLineWeight(2);
zero.SetDefaultColor(Color.BLUE);
AddCloud(zero, MACD5, Color.RED, Color.GREEN);
AddCloud(Squeeze, MACD5, Color.RED, Color.GREEN);
AddLabel(!IsNaN(Squeeze), "Squeeze", if MACD5 > MACD5[1] and
                                MACD5 < 0
                             then Color.GREEN
                             else Color.RED);
def day = GetValue(GetYYYYMMDD(), 1);
def trend = if close > (Highest(high, 21) + Lowest(low, 21)) / 2
            then 1
            else 0;
AddLabel(1, if trend == 1
            then "Trend Up"
            else "Trend Dn",
            if trend == 1
            then Color.Green
            else Color.Red);
 

borntostun

New member
Lifetime
Thanks Ben. The secret sauce for scanning seems to be that HAZEMA direction in the code I posted . . . that's what I'm really looking for to scan in ToS. ;).

Anyone?
 

scott69

Member
The biggest problem with these types of studies with multiple moving averages is that they can detrimentally diminish the overall performance of Thinkorswim... A single study implementing them is fine but if you keep multiple charts up, as I do, you will see a drastic reduction in performance... I tried running the Madrid Moving Average Ribbons on about eight charts and ended up having to remove the study from my charts and I don't even consider eight charts to be an excessive number... For example, the Madrid Moving Average Ribbons paints 20 moving averages per chart... Multiply that times 8 charts and you've got 160 moving averages being repainted... And that is without calculating any other additional studies... I even tried turning off every other moving average plot to help with performance but decided I could get the same or better results without them... Just be aware that having to constantly repaint 12 - 20 moving averages on a chart takes a good amount of time and overhead... While they may look sexy, do they really give you any more information than a leaner and cleaner setup...??? Many traders would say that simpler is better...
I was starting to get concerned about performance as well with all of the different indicators that I was testing, in addition to the ones that I already designed myself and used all day to trade. I must say that I have a fairly new laptop with a 10th gen i7, 16 GB ram, ssd, 4k, nvid graphics, running a 40" external monitor. OK, so I haven't yet seen any perf or speed compromises, but I do notice that the laptop temperature gets much hotter than my previous laptop, especially when the price is rapidly moving. My research indicated that because it is a gaming laptop, critics said that, "gaming laptops just 'run' hotter:" Not much help. I did design a small 3 inch fan that blows over the laoptop bottom which helps alleviate the heat. So my only advice would be to look at the computer system if you want to run a lot of charts and complex indicators. It seems like the TOS programmers are making their system more and more complex with each upgrade (on the weekend, so BIG surprise sunday night or monday morning when you start trading), forcing users to continually upgrade to keep up with the changes. As an aside, the reason why I have a new laptop is because after using my old laptop for a while on TOS successfully, suddenly they did an update that kept crashing TOS (laptop continued to run). We all know what it is like to have TOS crash while a trade is on (actually I hope you never experienced that). Thank god for stops. Anyway, I had a new laptop after three days of crashes. So the moral of the story for me was I was forced to upgrade my system (happy I did now).
 
Last edited:

J007RMC

Well-known member
2019 Donor
Can't remember who posted but is it possible to convert this indicator into tos this is an excellent stochastic I also use on trading view?

Code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © opiumfive

//@version=4
study("Drake Delay Stochastic")

pds = input(title="pds", type=input.integer, defval=13, minval=1)
slw = input(title="ema", type=input.integer, defval=8, minval=1)
slwsignal = input(title="trigger", type=input.integer, defval=9, minval=1)

MAValue = 0.0
MAValue2 = 0.0
MAValue3 = 0.0

smconst = 2.0 / (1 + slw)
smconst1 = 2.0 / (1 + slwsignal)

prev = na(MAValue2[1]) ? 0.0 : MAValue2[1]

AA = 0.0
tmpDevAA = highest(pds) - lowest(pds)

if tmpDevAA != 0
    AA := 100* ((close - lowest(pds)) / tmpDevAA)
   
MAValue2 := smconst * (AA-prev) + prev


MyHigh = -999999.0
MyLow = 999999.0
for i = 0 to pds
    Price = na(MAValue2) ? 0.0 : MAValue2
    if Price != 0.0
        if Price > MyHigh
            MyHigh := Price
        if pds <= 0
            MyHigh := Price
        if Price < MyLow
            MyLow := Price
        if pds <= 0
            MyLow := Price

prev1 = na(MAValue[1]) ? 0.0 : MAValue[1]
aa1=MAValue2

bb= 0.0
if MyHigh-MyLow != 0 
    bb:=100*(aa1-MyLow)/(MyHigh-MyLow)

MAValue := smconst * (bb-prev1) + prev1

MAValue3:= ema(MAValue, slwsignal)

plot(MAValue, color = MAValue >= MAValue3 ? color.lime : color.red, linewidth = 2)
plot(MAValue3, color = color.black)
hline(20, title="Sell", color=color.gray, linestyle=hline.style_dashed)
hline(80, title="Buy", color=color.gray, linestyle=hline.style_dashed)

bgcolor(MAValue >= MAValue3 ? #38a32a : #da680f, transp=80)
 
Last edited by a moderator:

sgummalla

New member
VIP
Can someone help me convert to indicator to TradingView?

Code:
input ChartBubblesOn = no;



input price = close;

input length = 10;



def tmp1 = if price > price[1] then price - price[1] else 0;

def tmp2 = if price[1] > price then price[1] - price else 0;

def d2 = sum(tmp1, length);

def d4 = sum(tmp2, length);

def cond = d2 + d4 == 0;

def ad3 = if cond then 0 else (d2 - d4) / (d2 + d4) * 100;

def coeff = 2 / (length + 1) * AbsValue(ad3) / 100;

def asd = compoundValue("visible data" = coeff * price + (if IsNaN(asd[1]) then 0 else asd[1]) * (1 - coeff), "historical data" = price);

plot VMA = asd;

VMA.setDefaultColor(GetColor(0));



def vwma8 = sum(volume * close, 8) / sum(volume, 8);

def vwma21 = sum(volume * close, 21) / sum(volume, 21);

def vwma34 = sum(volume * close, 34) / sum(volume, 34);



def bullish = if vwma8 > vwma21 and vwma21 > vwma34 then 1 else 0;

def bearish = if vwma8 < vwma21 and vwma21 < vwma34 then 1 else 0;

def distribution = if !bullish and !bearish then 1 else 0;



AddLabel(yes, if bullish then "Stage: Acceleration" else if bearish then "Stage: Deceleration" else if close>=VMA then "Stage: Accumulation" else "Stage: Distribution", if bullish then color.green else if bearish then color.red else if close >=VMA then color.yellow else color.orange);



VMA.AssignValueColor(if bearish and close<= VMA then color.red

else if bullish and close >= VMA then color.green

else color.gray);



def accumulationToAcceleration = if (bullish and close>=VMA) then 1 else 0;

AddChartBubble(ChartBubblesOn and accumulationToAcceleration and !accumulationToAcceleration[1], close, "Entering Acceleration", color.green);



def distributionToDeceleration = if (bearish and close <= VMA) then 1 else 0;

AddChartBubble(ChartBubblesOn and distributionToDeceleration and !distributionToDeceleration[1], close, "Entering Deceleration", color.red);
 
Last edited by a moderator:

rad14733

Well-known member
VIP
There are several Average Daily Range indicators here... Please make sure you have expended all avenues to locate Indicators/Studies before asking others to convert scripts from other platforms... Contrary to what some believe, we're not here to convert code upon request... If we kept busy doing that then we wouldn't have any time to work on the Indicators/Studies that we want... That would be akin to mowing all of our neighbors lawns, for whatever reasons our neighbors provide us, while letting our own lawns grow into hayfields... Sometimes you've just got to tend to your own lawn, ya know... Heck, I could spends all day finding studies from other platforms and posting requests to convert them, but . . . . You get my point - I hope...

I say all of this because your second post here was a request for others to do your work for you... 💡
 

Troy

New member
Hello, I was wondering if someone can convert this tradingview indicator, here is the code. Thanks
GZFIZmh.png
 
Last edited by a moderator:

scott69

Member
I hope I don't offend anyone, but my experience with Tradingview, at least in regard to real time NQ quotes, is that they are never right. I can't imagine placing a trade based on their system, and it comes back filled at $1000 difference. Not good...So, I can see why people are trying to convert their trusty indicators. I do agree with others that out of respect for the VERY generous, intelligent, skilled and helpful members here, it is important to do much research first, and then ask for help. As a new member, I really adhere to that premise, studying as much as I can to convert some of my Metastock indicators that I developed over the years. Again, please don't be offended, as most people ask for help innocently with appreciative intentions. Good luck to everyone trading in the "Tweet" markets, LOL
 

Troy

New member
@gsquared28 I wish I could help, but you will more than likely run into issues, for some strange reason people here kind of shun others who trade forex, even though forex is offered on TD Amerirade using thinkorswim. Anything related to range expansions, drawing boxes from high to low in specific times, Asia range, London Range, New York range seems to not get any feedback. That indicator you posted appears to be a simple Asian range with emas on the chart in my eyes. I see plenty of these in Tradingview obviously and also a lot of range box indicators in MT4. I really hope you find what your looking for, as I am myself searching for something slightly related your request except that for me it does not have emas, just session boxes drawn for specific times. Good luck.
 

rad14733

Well-known member
VIP
@Troy it could be that very few members here actually trade Forex... Either that or those who do keep their trade secrets to themselves... But in all fairness, charting patterns are charting patterns regardless of the instrument... I've never followed Forex so I can't be of any help there, although I have watched a bunch of YouTube videos where people have shared their strategies and they don't seem any different for Forex than for any other instrument - hence my previous comment...
 

Troy

New member
@Troy it could be that very few members here actually trade Forex... Either that or those who do keep their trade secrets to themselves... But in all fairness, charting patterns are charting patterns regardless of the instrument... I've never followed Forex so I can't be of any help there, although I have watched a bunch of YouTube videos where people have shared their strategies and they don't seem any different for Forex than for any other instrument - hence my previous comment...
Your reply has nothing to do with his indicator request, you are talking in circles, you yourself admitted to not knowing much about forex except for watching YouTube videos, that in itself is not enough, personally I trade forex and stocks so I have a good perspective in both areas, in which I prefer forex for a number of reasons, you can trade almost anytime of the day, you can short the market anytime you like without having to worry about borrowing shares, you can get in and out of a position quickly, pretty much the only thing driving the market is the banks for the most part, so you know who is doing the manipulation along with the broker,, you don't have to worry about hidden buyers, people spoofing the level 2 etc. I could go on and on but I think you get the point. Just let people ask for their indicator request and if you do not have anything valuable to say just don't say anything.
 

rad14733

Well-known member
VIP
Your reply has nothing to do with his indicator request, you are talking in circles, you yourself admitted to not knowing much about forex except for watching YouTube videos, that in itself is not enough, personally I trade forex and stocks so I have a good perspective in both areas, in which I prefer forex for a number of reasons, you can trade almost anytime of the day, you can short the market anytime you like without having to worry about borrowing shares, you can get in and out of a position quickly, pretty much the only thing driving the market is the banks for the most part, so you know who is doing the manipulation along with the broker,, you don't have to worry about hidden buyers, people spoofing the level 2 etc. I could go on and on but I think you get the point. Just let people ask for their indicator request and if you do not have anything valuable to say just don't say anything.
My apologies... I had a lot of balls in the air this afternoon... I see now that I was answering the wrong member anyway... :rolleyes:
 

BiPolarBear

New member
I was wondering if someone is able to help me turn an indicator from tradingview to thinkscript. The creator of the indicator gave me the script used to create it. Its a combination of the Money Flow Index and the RSI. It takes out all the noise and make the indicator a lot smoother to see the movement. I was told that this was all it took to create this but not sure if there is more to it. Any help would be greatly appreciated.

mix = (moneyFlowIndex + rsi)/2
RSI_MFI = ema(mix, input(7))

S8UZo4Ky
 

BenTen

Administrative
Staff
VIP
@BiPolarBear Here you go

Code:
# MFI + RSI all-in-one
# Assembled by BenTen at UseThinkScript.com

declare lower;

input length = 14;
input ema_length = 7;
input over_Bought = 70;
input over_Sold = 30;
input price = close;
input averageType = AverageType.WILDERS;

def NetChgAvg = MovingAverage(averageType, price - price[1], length);
def TotChgAvg = MovingAverage(averageType, AbsValue(price - price[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;

def RSI = 50 * (ChgRatio + 1);

input movingAvgLength = 1;

def MoneyFlowIndex = Average(moneyflow(high, close, low, volume, length), movingAvgLength);

def mix = (moneyFlowIndex + rsi)/2;
plot RSI_MFI = expAverage(mix, ema_length);
plot ob = over_Bought;
plot os = over_Sold;
 

tem2005

Member
VIP
Hello, can anyone convert the below indicator from tradingview? i found it good promising . It's named as Order Block Finder

Code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wugamlo


// This experimental Indicator helps identifying instituational Order Blocks.
// Often these blocks signal the beginning of a strong move, but there is a significant probability that these price levels will be revisited at a later point in time again.
// Therefore these are interesting levels to place limit orders (Buy Orders for Bullish OB / Sell Orders for Bearish OB).
//
// A Bullish Order block is defined as the last down candle before a sequence of up candles. (Relevant price range "Open" to "Low" is marked)  / Optionally full range "High" to "Low"
// A Bearish Order Block is defined as the last up candle before a sequence of down candles. (Relevant price range "Open" to "High" is marked) / Optionally full range "High" to "Low"
//
// In the settings the number of required sequential candles can be adjusted.
// Furthermore a %-threshold can be entered. It defines which %-change the sequential move needs to achieve in order to identify a relevant Order Block.
// Channels for the last Bullish/Bearish Block can be shown/hidden.
//
// In addition to the upper/lower limits of each Order Block, also the equlibrium (average value) is marked as this is an interesting area for price interaction.


//@version=4
study("Order Block Finder", overlay = true)              

periods   = input(5,     "Relevant Periods to identify OB")                // Required number of subsequent candles in the same direction to identify Order Block
threshold = input(0.0,   "Min. Percent move to identify OB", step = 0.1)   // Required minimum % move (from potential OB close to last subsequent candle to identify Order Block)
usewicks  = input(false, "Use whole range [High/Low] for OB marking?" )    // Display High/Low range for each OB instead of Open/Low for Bullish / Open/High for Bearish
showbull  = input(true,  "Show latest Bullish Channel?")                   // Show Channel for latest Bullish OB?
showbear  = input(true,  "Show latest Bearish Channel?")                   // Show Channel for latest Bearish OB?
showdocu  = input(true,  "Show Label for documentation tooltip?")          // Show Label which shows documentation as tooltip?

ob_period = periods + 1                                                    // Identify location of relevant Order Block candle
absmove   = ((abs(close[ob_period] - close[1]))/close[ob_period]) * 100    // Calculate absolute percent move from potential OB to last candle of subsequent candles
relmove   = absmove >= threshold                                           // Identify "Relevant move" by comparing the absolute move to the threshold

// Bullish Order Block Identification
bullishOB = close[ob_period] < open[ob_period]                             // Determine potential Bullish OB candle (red candle)

int upcandles  = 0
for i = 1 to periods
    upcandles := upcandles + (close[i] > open[i]? 1 : 0)                   // Determine color of subsequent candles (must all be green to identify a valid Bearish OB)

OB_bull      = bullishOB and (upcandles == (periods)) and relmove          // Identification logic (red OB candle & subsequent green candles)
OB_bull_high = OB_bull? usewicks? high[ob_period] : open[ob_period] : na   // Determine OB upper limit (Open or High depending on input)
OB_bull_low  = OB_bull? low[ob_period]  : na                               // Determine OB lower limit (Low)
OB_bull_avg  = (OB_bull_high + OB_bull_low)/2                              // Determine OB middle line


// Bearish Order Block Identification
bearishOB = close[ob_period] > open[ob_period]                             // Determine potential Bearish OB candle (green candle)

int downcandles  = 0
for i = 1 to periods
    downcandles := downcandles + (close[i] < open[i]? 1 : 0)               // Determine color of subsequent candles (must all be red to identify a valid Bearish OB)

OB_bear      = bearishOB and (downcandles == (periods)) and relmove        // Identification logic (green OB candle & subsequent green candles)
OB_bear_high = OB_bear? high[ob_period] : na                               // Determine OB upper limit (High)
OB_bear_low  = OB_bear? usewicks? low[ob_period] : open[ob_period] : na    // Determine OB lower limit (Open or Low depending on input)
OB_bear_avg  = (OB_bear_low + OB_bear_high)/2                              // Determine OB middle line


// Plotting

plotshape(OB_bull, title="Bullish OB", style = shape.triangleup,   color = color.white, size = size.tiny, location = location.belowbar, offset = -ob_period, text = "Bullish OB")     // Bullish OB Indicator
bull1 = plot(OB_bull_high, title="Bullish OB open", style = plot.style_linebr, color = color.white, offset = -ob_period, linewidth = 3)                                               // Bullish OB Upper Limit
bull2 = plot(OB_bull_low,  title="Bullish OB low",  style = plot.style_linebr, color = color.white, offset = -ob_period, linewidth = 3)                                               // Bullish OB Lower Limit
fill(bull1, bull2, color=color.white, transp = 0, title = "Bullish OB fill")                                                                                                          // Fill Bullish OB
plotshape(OB_bull_avg, title="Bullish OB Average", style = shape.cross,   color = color.white, size = size.normal, location = location.absolute, offset = -ob_period)                 // Bullish OB Average


plotshape(OB_bear, title="Bearish OB", style = shape.triangledown, color = color.blue,  size = size.tiny, location = location.abovebar, offset = -ob_period, text = "Bearish OB")     // Bearish OB Indicator
bear1 = plot(OB_bear_low,  title="Bearish OB open", style = plot.style_linebr, color = color.blue, offset = -ob_period, linewidth = 3)                                                // Bearish OB Lower Limit
bear2 = plot(OB_bear_high, title="Bearish OB high", style = plot.style_linebr, color = color.blue, offset = -ob_period, linewidth = 3)                                                // Bearish OB Upper Limit
fill(bear1, bear2, color=color.blue, transp = 0, title = "Bearish OB fill")                                                                                                           // Fill Bearish OB
plotshape(OB_bear_avg, title="Bearish OB Average", style = shape.cross,   color = color.blue, size = size.normal, location = location.absolute, offset = -ob_period)                  // Bullish OB Average

var line linebull1 = na       // Bullish OB average
var line linebull2 = na       // Bullish OB open
var line linebull3 = na       // Bullish OB low
var line linebear1 = na       // Bearish OB average
var line linebear2 = na       // Bearish OB high
var line linebear3 = na       // Bearish OB open


if OB_bull and showbull
    line.delete(linebull1)
    linebull1 := line.new(x1 = bar_index, y1 = OB_bull_avg, x2 = bar_index - 1, y2 = OB_bull_avg, extend = extend.left, color = color.white, style = line.style_solid, width = 1)
   
    line.delete(linebull2)
    linebull2 := line.new(x1 = bar_index, y1 = OB_bull_high, x2 = bar_index - 1, y2 = OB_bull_high, extend = extend.left, color = color.white, style = line.style_dashed, width = 1)
   
    line.delete(linebull3)
    linebull3 := line.new(x1 = bar_index, y1 = OB_bull_low, x2 = bar_index - 1, y2 = OB_bull_low, extend = extend.left, color = color.white, style = line.style_dashed, width = 1)

if OB_bear and showbear
    line.delete(linebear1)
    linebear1 := line.new(x1 = bar_index, y1 = OB_bear_avg, x2 = bar_index - 1, y2 = OB_bear_avg, extend = extend.left, color = color.blue,  style = line.style_solid, width = 1)
   
    line.delete(linebear2)
    linebear2 := line.new(x1 = bar_index, y1 = OB_bear_high, x2 = bar_index - 1, y2 = OB_bear_high, extend = extend.left, color = color.blue,  style = line.style_dashed, width = 1)
   
    line.delete(linebear3)
    linebear3 := line.new(x1 = bar_index, y1 = OB_bear_low, x2 = bar_index - 1, y2 = OB_bear_low, extend = extend.left, color = color.blue,  style = line.style_dashed, width = 1)


// === Label for Documentation/Tooltip ===
chper = time - time[1]
chper := change(chper) > 0 ? chper[1] : chper

// === Tooltip text ===

var vartooltip = "Indicator to help identifying instituational Order Blocks. Often these blocks signal the beginning of a strong move, but there is a high probability, that these prices will be revisited at a later point in time again and therefore are interesting levels to place limit orders. \nBullish Order block is the last down candle before a sequence of up candles. \nBearish Order Block is the last up candle before a sequence of down candles. \nIn the settings the number of required sequential candles can be adjusted. \nFurthermore a %-threshold can be entered which the sequential move needs to achieve in order to validate a relevant Order Block. \nChannels for the last Bullish/Bearish Block can be shown/hidden."

// === Print Label ===
var label l_docu = na
label.delete(l_docu)

if showdocu
    l_docu := label.new(x = time + chper * 35, y = close, text = "DOCU OB", color=color.gray, textcolor=color.white, style=label.style_label_center, xloc = xloc.bar_time, yloc=yloc.price, size=size.tiny, textalign = text.align_left, tooltip = vartooltip)
 
Last edited:

New Indicator: Buy the Dip

Check out our Buy the Dip indicator and see how it can help you find profitable swing trading ideas. Scanner, watchlist columns, and add-ons are included.

Download the indicator

Similar threads

Top