EMA 9/21 with Target Price [SS] For ThinkOrSwim

Chocolate

New member
The author states: This indicator is unique. It combines 2 EMAs (the 9 and 21) with an ATR based analysis to calculate the average range a ticker undergoes after an EMA 9 / 21 Cross-over and Cross-under.

SlhIMpK.png


Original Tradingview code:
https://www.tradingview.com/script/bH92P2FE-EMA-9-21-with-Target-Price-SS/

New ThinkOrSwim code can be found below.
 
Last edited by a moderator:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Hey everyone,
Would someone be willing to convert this TradingView script to ThinkScript? It came from this website: EMA 9/21 with Target Price [SS]
https://www.tradingview.com/script/bH92P2FE-EMA-9-21-with-Target-Price-SS/

Code:
indicator("EMA 9/21 with Target Price [SS]", overlay=true)

arraylookback =     input.float(500, "ATR Lookback Length")
showlbls =          input.bool(true, "Show Target Price Labels")



ema9 = ta.ema(close, 9)
ema21 = ta.ema(close, 21)

// determine the crossover points
ema9_cross_ema21 = ta.crossover(ema9, ema21)
ema21_cross_ema9 = ta.crossover(ema21, ema9)

// plot arrows on the chart at the crossover points
plotshape(ema9_cross_ema21 ? close : na, title="Up Arrow", location=location.belowbar, style=shape.triangleup, size=size.small, color=color.green)
plotshape(ema21_cross_ema9 ? close : na, title="Down Arrow", location=location.abovebar, style=shape.triangledown, size=size.small, color=color.red)

// sentiment

bool bullish = close >= ema9 and close >= ema21
bool bearish = close <= ema9 and close <= ema21
bool neutral = close < ema9 and close > ema21

// define colours

bull =          color.new(color.lime, 50)
bear =          color.new(color.red, 50)
white =         color.white
neutralcolor = color.new(color.gray, 50)

crossovercolor = color.new(color.purple, 75)
crossundercolor = color.new(color.orange, 75)

color pallette = bullish ? bull : bearish ? bear : neutralcolor
color emacolor = ema9_cross_ema21 ? crossovercolor : ema21_cross_ema9 ? crossundercolor : pallette

filla = plot(ema9, color=emacolor, linewidth=1)
fillb = plot(ema21, color=emacolor, linewidth=1)

fill(filla, fillb, color=pallette)

bool above_ema = close >= ema9 and close >= ema21
bool below_ema = close < ema9 and close <= ema21
bool crossover = ema9_cross_ema21
bool crossunder = ema21_cross_ema9

bull_a = array.new_float()
open_a = array.new_float()
crossover_a = array.new_float()
crossunder_a = array.new_float()
bear_a = array.new_float()


for i = 0 to arraylookback
    if above_ema[i]
        array.push(bull_a, close[i])
    if crossover[i]
        array.push(crossover_a, close[i])
        array.push(open_a, open[i])
    if below_ema[i]
        array.push(bear_a, close[i])
    if crossunder[i]
        array.push(crossunder_a, close[i])

  
max_above = array.max(bull_a)
crossover_avg = array.avg(crossover_a)
max_below = array.min(bear_a)
crossunder_avg = array.avg(crossunder_a)

bull_dif1 = (max_above - crossover_avg) / 2
bull_dif2 = (max_above - crossover_avg)
bear_dif1 = (crossunder_avg - max_below) / 2
bear_dif2 = (crossunder_avg - max_below)

float op = 0.0
float bull_tgt = 0.0
float bull_tgt_2 = 0.0
float bear_tgt = 0.0
float bear_tgt_2 = 0.0
var label bull_tgt_1_lbl = na
var label bull_tgt_2_lbl = na
var label bear_tgt_1_lbl = na
var label bear_tgt_2_lbl = na
var line bull_tgt_lin = na
var line bull_tgt_lin_2 = na
var line bear_tgt_lin = na
var line bear_tgt_lin_2 = na

if crossover
    if array.size(open_a) > 0
        op := array.get(open_a, 0)
    bull_tgt := op + bull_dif1
    bull_tgt_2 := op + bull_dif2
if crossunder
    if array.size(open_a) > 0
        op := array.get(open_a, 0)
    bear_tgt := op - bear_dif1
    bear_tgt_2 := op - bear_dif2

 
if crossover and barstate.isconfirmed
    line.delete(bull_tgt_lin)
    line.delete(bull_tgt_lin_2)
    label.delete(bull_tgt_1_lbl)
    label.delete(bull_tgt_2_lbl)
    bull_tgt_lin := line.new(bar_index[1], y1 = bull_tgt, x2= bar_index, y2 = bull_tgt, extend = extend.right, color = bull, width=3)
    bull_tgt_lin_2 := line.new(bar_index[1], y1 = bull_tgt_2, x2= bar_index, y2 = bull_tgt_2, extend = extend.right, color = bull, width=3)
    if showlbls
        bull_tgt_1_lbl := label.new(bar_index[1], y = bull_tgt, text = "Bull Target 1 \n" + str.tostring(math.round(bull_tgt,2)), color = bull, textcolor = white)
        bull_tgt_2_lbl := label.new(bar_index[1], y = bull_tgt_2, text = "Bull Target 2 \n" + str.tostring(math.round(bull_tgt_2,2)), color = bull, textcolor = white)

if crossunder and barstate.isconfirmed
    line.delete(bear_tgt_lin)
    line.delete(bear_tgt_lin_2)
    label.delete(bear_tgt_1_lbl)
    label.delete(bear_tgt_2_lbl)
    bear_tgt_lin := line.new(bar_index[1], y1 = bear_tgt, x2= bar_index, y2 = bear_tgt, extend = extend.right, color = bear, width=3)
    bear_tgt_lin_2 := line.new(bar_index[1], y1 = bear_tgt_2, x2= bar_index, y2 = bear_tgt_2, extend = extend.right, color = bear, width=3)
    if showlbls
        bear_tgt_1_lbl := label.new(bar_index[1], y = bear_tgt, text = "Bear Target 1 \n" + str.tostring(math.round(bear_tgt,2)), color = bear, style=label.style_label_up, textcolor = white)
        bear_tgt_2_lbl := label.new(bar_index[1], y = bear_tgt_2, text = "Bear Target 2 \n" + str.tostring(math.round(bear_tgt_2,2)), color = bear, style=label.style_label_up, textcolor = white)




alertcondition(crossover, "EMA 9/21 Crossover", "Bullish Cross")
alertcondition(crossunder, "EMA 9/21 Crossunder", "Bearish Cross")
check the below:

CSS:
# Indicator for TOS
#// © Steversteves
#indicator("EMA 9/21 with Target Price [SS]", overlay=true)
# Converted by Sam4Cok@Samer800    - 10/2024

input atrLookbackLength = 500;#, "ATR Lookback Length")
input ShowTargetPriceLabels = yes;#, "ShowTargetPriceLabels")
input source = close;
input MovAvgType = AverageType.EXPONENTIAL;
input shortMovAvgLength = 9;
input LongMovAvgLength = 21;

def na = Double.NaN;
def last = isNaN(close);
def bn = BarNumber();
def startCnt = bn > HighestAll(bn) - atrLookbackLength;

#-- Color
DefineGlobalColor("up", CreateColor(41, 98, 255));
DefineGlobalColor("Dn", CreateColor(233, 30, 99));
DefineGlobalColor("dup", CreateColor(0, 27, 100));
DefineGlobalColor("dDn", CreateColor(97, 9, 39));
DefineGlobalColor("noCol", CreateColor(57, 57, 57));

def ema9 = MovingAverage(MovAvgType, source, shortMovAvgLength);
def ema21 = MovingAverage(MovAvgType, source, LongMovAvgLength);

#// determine the crossover points
def ema9_cross_ema21 = (ema9 > ema21) and (ema9[1] <= ema21[1]);
def ema21_cross_ema9 = (ema21 > ema9) and (ema21[1] <= ema9[1]);

#// plot arrows on the chart at the crossover points
plot UpArrow = if ema9_cross_ema21 then low else na;#, title="Up Arrow"
plot DnArrow = if ema21_cross_ema9 then high else na;#, title="Down Arrow"
UpArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
DnArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
UpArrow.SetDefaultColor(Color.CYAN);
DnArrow.SetDefaultColor(Color.MAGENTA);
#// sentiment

def bullish = source >= ema9 and source >= ema21;
def bearish = source <= ema9 and source <= ema21 ;
def neutral = source < ema9 and source > ema21 ;

#// define colours

def pallette = if bullish then 1 else if bearish then -1 else 0;
def emacolor = if ema9_cross_ema21 then 2 else
               if ema21_cross_ema9 then -2 else pallette;

plot filla = ema9;#, color=emacolor, linewidth=1)
plot fillb = ema21;#, color=emacolor, linewidth=1)

filla.AssignValueColor(if emacolor==2 then Color.CYAN else
                       if emacolor==-2 then Color.MAgENTA else
                       if emacolor == 1 then GlobalColor("up") else
                       if emacolor == -1 then GlobalColor("dn") else Color.GRAY);
fillb.AssignValueColor(if emacolor==2 then Color.CYAN else
                       if emacolor==-2 then Color.MAgENTA else
                       if emacolor > 0 then GlobalColor("up") else
                       if emacolor < 0 then GlobalColor("dn") else Color.DARK_GRAY);
AddCloud(if pallette then filla else na, fillb, GlobalColor("dup"), GlobalColor("dn"));
AddCloud(filla, fillb, GlobalColor("noCol"), GlobalColor("noCol"));

def above_ema = source >= ema9 and source >= ema21;
def below_ema = source < ema9 and source <= ema21;
def crossover = ema9_cross_ema21;
def crossunder = ema21_cross_ema9;

def bull_a = fold i = 0 to atrLookbackLength with p=source do
             if above_ema[i] then
             max(p, source[i]) else p;
def bear_a = fold i1 = 0 to atrLookbackLength with p1=source do
             if below_ema[i1] then
             min(p1, source[i1]) else p1;

def bulla = fold j = 0 to atrLookbackLength with q do
             if crossover[j] then q + source[j] else q;

def bullCnt = fold j1 = 0 to atrLookbackLength with q1 do
             if crossover[j1] then q1 + 1 else q1;

def beara = fold j2 = 0 to atrLookbackLength with q2 do
             if crossunder[j2] then q2 + source[j2] else q2;
def bearCnt = fold j4 = 0 to atrLookbackLength with q4 do
             if crossunder[j4] then q4 + 1 else q4;

def open_a;def open_Size;
if crossover and startCnt {
    open_Size = open_Size[1]+1;
    open_a = open;
    } else {
    open_Size = open_Size[1];
    open_a = open_a[1];
}

def max_above = (bull_a);
def crossover_avg = bulla / bullCnt;
def max_below = (bear_a);
def crossunder_avg = beara / bearCnt;

def bull_dif1 = (max_above - crossover_avg) / 2;
def bull_dif2 = (max_above - crossover_avg);
def bear_dif1 = (crossunder_avg - max_below) / 2 ;
def bear_dif2 = (crossunder_avg - max_below) ;

def op;def bull_tgt;def bull_tgt_2;def bear_tgt;def bear_tgt_2;
if crossover {
    op = if open_Size > 0 then open_a else op[1];
    bull_tgt = op + bull_dif1;
    bull_tgt_2 = op + bull_dif2;
    bear_tgt = bear_tgt[1];
    bear_tgt_2 = bear_tgt_2[1];
    } else
if crossunder {
    op = if open_Size > 0 then open_a else op[1];
    bear_tgt = op - bear_dif1;
    bear_tgt_2 = op - bear_dif2;
    bull_tgt = bull_tgt[1];
    bull_tgt_2 =  bull_tgt_2[1];
    } else {
    op = op[1];
    bull_tgt = bull_tgt[1];
    bull_tgt_2 =  bull_tgt_2[1];
    bear_tgt = bear_tgt[1];
    bear_tgt_2 = bear_tgt_2[1];
}

def bull_tgt_lin;def bull_tgt_lin_2;
if crossover and !last {
    bull_tgt_lin = bull_tgt;
    bull_tgt_lin_2 = bull_tgt_2;
    } else {
    bull_tgt_lin = bull_tgt[1];
    bull_tgt_lin_2 = bull_tgt_2[1];
}
def bear_tgt_lin;def bear_tgt_lin_2;
if crossunder and !last {
    bear_tgt_lin = bear_tgt;
    bear_tgt_lin_2 = bear_tgt_2;
    } else {
    bear_tgt_lin = bear_tgt_lin[1];
    bear_tgt_lin_2 = bear_tgt_lin_2[1];
}
def BullCond = if crossover then bn-1 else BullCond[1];
def BearCond = if crossunder then bn-1 else BearCond[1];
def bullBar = bn > highestAll(BullCond) and !last[3];
def bearBar = bn > highestAll(BearCond) and !last[3];

plot bull1 = if bullBar then bull_tgt_lin else na;
plot bull2 = if bullBar then bull_tgt_lin_2 else na;

plot bear1 = if bearBar then bear_tgt_lin else na;
plot bear2 = if bearBar then bear_tgt_lin_2 else na;

bull1.SetDefaultColor(GlobalColor("up"));
bull2.SetDefaultColor(GlobalColor("up"));
bear1.SetDefaultColor(GlobalColor("dn"));
bear2.SetDefaultColor(GlobalColor("dn"));

def firstBarBull = ShowTargetPriceLabels and isNaN(bull1[1]) and !isNaN(bull1);
def firstBarBear = ShowTargetPriceLabels and isNaN(bear1[1]) and !isNaN(bear1);

def bull1Round = ROUND(bull1, 2);
def bull2Round = ROUND(bull2, 2);
def bear1Round = ROUND(bear1, 2);
def bear2Round = ROUND(bear2, 2);

AddChartBubble(firstBarBull, bull1, bull1Round, Color.GREEN);
AddChartBubble(firstBarBull, bull2, bull2Round, Color.GREEN);

AddChartBubble(firstBarBear, bear1, bear1Round, Color.RED, no);
AddChartBubble(firstBarBear, bear2, bear2Round, Color.RED, no);

#-- END of CODE
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
493 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top