Smart Entry For ThinkOrSwim

dmegara

New member
The author states:
(My goal creating this indicator) : Provide a way to enter the market systematically, automatically create Stop Loss Levels and Take Profit Levels, and provide the position size of each entry based on a fix Percentage of the traders account.

The Underlying Concept :

What is Momentum?
The Momentum shown is derived from a Mathematical Formula, SUPERTREND. When price closes above Supertrend Its bullish Momentum when its below Supertrend its Bearish Momentum. This indicator scans for candle closes on the current chart and when there is a shift in momentum (price closes below or above SUPERTREND) it notifies the trader with a Bar Color change.
Capture.PNG

is anyone able to convert this indicator to thinkorswim?
https://www.tradingview.com/script/vLyl4omf-SuperTrend-Entry/
 
Last edited by a moderator:
is anyone able to convert this indicator to thinkorswim?

https://www.tradingview.com/script/vLyl4omf-SuperTrend-Entry/


Code:
//@version=5
indicator("Smart Entry", shorttitle="Smart Entry", overlay=true , max_bars_back=5000)


factor = input.float(1, "Factor", step = 0.01, group="Smart Momentum", inline="z")
atrPeriod = input.int(1, "ATR Period", step = 1, group="Smart Momentum", inline="z")
smartOverlay = input.bool(true, title="[Smart Overlay]", inline="z", group="Momentum Colors")
bullColor1 = input.color(#22ad22, title="[-Momentum Bull-]", inline="z", group="Momentum Colors")
bearColor1 = input.color(#e10000, title="[Momentum Bear]", inline="z", group="Momentum Colors")
momentumSwitch = input.bool(true, title="[Momentum Switch]", inline="z", group="Momentum Colors")
momentumSwitchBull = input.color(#ffe900, title="[--Switch Bull--]", inline="z", group="Momentum Colors")
momentumSwitchBear = input.color(#0006ff, title="[--Switch Bear--]", inline="z", group="Momentum Colors")
hlowRClose = input.bool(defval=true, title="High & Low or Highest Close & Lowest Close", tooltip="Use HIGH & LOW as stop loss refrence or Highest CLOSE & Lowest Close", group="Stops and Targets")
buyColorsl = input.color(#22ad22, title="*Long Stop Loss Color", inline="1", group="Stops and Targets")
sellColorsl = input.color(#e10000, title="*Short Stop Loss Color", inline="1", group="Stops and Targets")
buyColortp = input.color(color.white, title="Long Take Profit Color", inline="1", group="Stops and Targets")
sellColortp = input.color(color.gray, title="Short Take Profit Color", inline="1", group="Stops and Targets")
stopLossMultiplier = input.float(title="Stop Loss Multiplier", tooltip="0 Disables Take Profit", defval=0.08, step=0.05, group="Money Management", inline="2")
takeProfitMultiplier = input.float(title="Take Profit Multiplier", defval=0, step=0.05, group="Money Management", inline="2")
accountSize = input.float(title="Account Size", defval=200000.0, group="Money Management", inline="2")
betPercentage = input.float(title="------- Bet Percentage", defval=0.25, group="Money Management", inline="2")
spread = input.float(title="Spread", defval=0.00002,step=0.00001, group="Money Management", inline="2")

chartSizex = input.string("Small", title="Table Size", options=["Tiny","Small","Normal","Large","Huge"],inline="8",group="Entry Table")
chartPositionx = input.string(title="Table Position",group="Entry Table", defval="Top Right", inline="8",
options=["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"])


// Dynamic Table Position using user input string
var chartSize = size.tiny

if chartSizex == "Tiny"
chartSize := size.tiny

if chartSizex == "Small"
chartSize := size.small

if chartSizex == "Normal"
chartSize := size.normal

if chartSizex == "Large"
chartSize := size.large

if chartSizex == "Huge"
chartSize := size.huge

// Dynamic Table Position using user input string
var chartPosition = position.top_right

if chartPositionx == "Top Right"
chartPosition := position.top_right

if chartPositionx == "Top Center"
chartPosition := position.top_center

if chartPositionx == "Top Left"
chartPosition := position.top_left

if chartPositionx == "Middle Right"
chartPosition := position.middle_right

if chartPositionx == "Middle Center"
chartPosition := position.middle_center

if chartPositionx == "Middle Left"
chartPosition := position.middle_left

if chartPositionx == "Bottom Right"
chartPosition := position.bottom_right

if chartPositionx == "Bottom Center"
chartPosition := position.bottom_center

if chartPositionx == "Bottom Left"
chartPosition := position.bottom_left

//Wait for candle to close before you show signal or change in realtime
closeRrealtime = true
barState = (closeRrealtime == true) ? barstate.isconfirmed : barstate.isrealtime

HRC = hlowRClose ? high : close
LRC = hlowRClose ? low : close
HRO = hlowRClose ? high : open
LRO = hlowRClose ? low : open

// Get SuperTrend Values
[supertrend, direction] = ta.supertrend(factor, atrPeriod)

// Get ATR Filter
atr = ta.atr(14)


//Entry signal
bull_STC = close > supertrend and close[1] < supertrend[1]
bear_STC = close < supertrend and close[1] > supertrend[1]

//To get around runtime issue
bar_DEX =(bar_index > 10)


// How Many Green Bars Before the condtion hapeens again
howManyGB = (ta.barssince(bull_STC)) + 1
howManyRB = (ta.barssince(bear_STC)) + 1

howManyGBX = ta.barssince(bull_STC)
howManyRBX =ta.barssince(bear_STC)

howManyGBText = str.tostring(howManyGBX)
howManyRBText = str.tostring(howManyRBX)

// lookbackperiod so i dont get ZEROS in my look back period
lookBack = howManyGB > howManyRB ? howManyGB : howManyRB

// Get level using a changing lookback period added bar_DEX to fix loading on to chart issues
// get open values for the rare occurance that its actually the high rare but happens
lowLevel = bar_DEX ? ta.lowest(LRC,lookBack + 1) : na
lowLevelOpen = bar_DEX ? ta.lowest(open,lookBack + 1) : na

lowLevelX = lowLevelOpen < lowLevel ? lowLevelOpen : lowLevel

highLevel = bar_DEX ? ta.highest(HRC,lookBack + 1) : na
highLevelOpen = bar_DEX ? ta.highest(open,lookBack + 1) : na

highLevelX= highLevelOpen > highLevel ? highLevelOpen : highLevel

// include entry cand high or low in the lookback
lowLevelB = lowLevelX < LRO ? lowLevelX : LRO
highLevelB = highLevelX > HRO ? highLevelX : HRO


// Create StopLoss Point
sellStopLoss = highLevelB + (atr*stopLossMultiplier) + spread
buyStopLoss = lowLevelB - (atr*stopLossMultiplier) - spread

// Create TakeProfit / a reflection of stop loss
sellTakeProfit = (close - (sellStopLoss - close) * takeProfitMultiplier)
buyTakeProfit = (takeProfitMultiplier * (close - buyStopLoss) + close)

//position Sizing accountSize default 100,000 betpercentage default = 1 and
//0.01 to turn it into a percentage divide: stoploss too entry candle close is = sellTakeProfit (reflection)
// Minus close from sellTakeProfit to just get entry candle's stoploss to its close only
//multilpy by 10000 to get number of pips multiply by 10 to get answer in LOTs! (not micro or mini)

sellbuyPositionSizeA =(accountSize * (betPercentage * 0.01))


sellPositionSizeB= (sellStopLoss - close) * 10000 * 10

buyPositionSizeB= (close - buyStopLoss) * 10000 * 10

sellPositionSizeC = sellbuyPositionSizeA / sellPositionSizeB

buyPositionSizeC = sellbuyPositionSizeA / buyPositionSizeB


// change color based on current charts momentum
trendColor = bull_STC and momentumSwitch and smartOverlay ? momentumSwitchBull : bear_STC and momentumSwitch and smartOverlay ? momentumSwitchBear : close > supertrend and smartOverlay ? bullColor1 : close < supertrend and smartOverlay ? bearColor1 : na
barcolor(trendColor, title="Current Chart Momentum",editable=false)

// Prepare a table
var table myTable = table.new(chartPosition, 2, 3, border_width=1)

// Draw table
if barstate.islast and bear_STC
table.cell(myTable, column = 0, row = 2 ,text="SellStopLoss: " + str.tostring(math.round(sellStopLoss, 5)), text_color=#e10000, bgcolor=color.new(color.black,70), text_size=chartSize)
table.cell(myTable, column = 0, row = 1 ,text="Position Size: " + str.tostring(math.round(sellPositionSizeC, 2)), text_color=color.white, bgcolor=color.new(color.black,70), text_size=chartSize)
table.cell(myTable, column = 0, row = 0 ,text= takeProfitMultiplier > 0 ?"SellTakeProfit: " + str.tostring(math.round(sellTakeProfit, 5)) : na, text_color=#22ad22, bgcolor=color.new(color.black,takeProfitMultiplier > 0 ? 70 : 100), text_size=chartSize)

if barstate.islast and bull_STC
table.cell(myTable, column = 1, row = 2 ,text="BuyStopLoss: " + str.tostring(math.round(buyStopLoss, 5)), text_color=#e10000, bgcolor=color.new(color.gray,50), text_size=chartSize)
table.cell(myTable, column = 1, row = 1 ,text="Position Size: " + str.tostring(math.round(buyPositionSizeC, 2)), text_color=color.white, bgcolor=color.new(color.gray,50), text_size=chartSize)
table.cell(myTable, column = 1, row = 0 ,text= takeProfitMultiplier > 0 ? "BuyTakeProfit: " + str.tostring(math.round(buyTakeProfit, 5)) : na, text_color=#22ad22, bgcolor=color.new(color.gray,takeProfitMultiplier > 0 ? 50: 100), text_size=chartSize)

// Draw Take Profit and Stop Loss points
plot(bull_STC ? buyStopLoss : na, title = "Buy Stop Loss", color= #22ad22, linewidth=1, style=plot.style_linebr)
plot(bear_STC ? sellStopLoss : na, title = "Sell Stop Loss", color = #e10000, linewidth=1, style=plot.style_linebr)
plot(bull_STC ? buyTakeProfit : na, title = "Buy Take Profit", color = color.new(color.white, 0), linewidth=1, style=plot.style_linebr)
plot(bear_STC ? sellTakeProfit : na, title = "Sell Take Profit", color = color.new(color.gray, 0), linewidth=1, style=plot.style_linebr)View attachment 20720
find below

CSS:
#//@version=5
#indicator("Smart Entry", shorttitle="Smart Entry", overlay=true , max_bars_back=5000)
# Converted by Sam4Cok@Samer800    - 01/2024

input factor = 1.0;#, "Factor", step = 0.01, group="Smart Momentum", inline="z")
input atrPeriod = 1;#, "ATR Period", step = 1, group="Smart Momentum", inline="z")
input smartOverlay    = yes;#, title="[Smart Overlay]", inline="z", group="Momentum Colors")
input momentumSwitch  = yes;#, title="[Momentum Switch]", inline="z", group="Momentum Colors")
input highLowClose  = yes;#, title="High & Low or Highest Close & Lowest Close", tooltip="Use HIGH & LOW as stop loss refrence or Highest CLOSE & Lowest Close", group="Stops and Targets")
input stopLossMultiplier = 0.08;    # "Stop Loss Multiplier", tooltip="0 Disables Take Profit",
input takeProfitMultiplier = 0.0;#(title="Take Profit Multiplier", defval=0, step=0.05, group="Money Management", inline="2")
input accountSize = 200000;#(title="Account Size", defval=200000.0, group="Money Management", inline="2")
input betPercentage = 0.25;#(title="------- Bet Percentage", defval=0.25, group="Money Management", inline="2")
input spread = 0.00002;#(title="Spread", defval=,step=0.00001, group="Money Management", inline="2")

def na = Double.NaN;
def atr = ATR(Length = 14);
def HRC = if highLowClose then high else close;
def LRC = if highLowClose then low else close;
def HRO = if highLowClose then high else open;
def LRO = if highLowClose then low else open;

#pine_supertrend(src, factor, atrPeriod) =>
script supertrend {
    input factor = 3;
    input Period = 10;
    def src = hl2;
    def atr = ATR(Length = Period);
    def up = src + factor * atr;
    def dn = src - factor * atr;
    def lowerBand;
    def upperBand;
    def up1 = if (IsNaN(upperBand[1]) or upperBand[1] == 0) then up else upperBand[1];
    def dn1 = if (IsNaN(lowerBand[1]) or lowerBand[1] == 0) then dn else lowerBand[1];
    upperBand = if (up < up1) or (close[1] > up1) then up else up1;
    lowerBand = if (dn > dn1) or (close[1] < dn1) then dn else dn1;
    def trend;# = na
    def superTrend;# = na
    def prevSuperTrend = if superTrend[1] then superTrend[1] else up1;
    if (IsNaN(up) or IsNaN(dn)) {
        trend = 1;
    } else
    if prevSuperTrend == up1 {
        trend = if close > upperBand then -1 else 1;
    } else {
        trend = if close < lowerBand then  1 else -1;
    }
    superTrend = if trend == -1 then lowerBand else upperBand;
    plot ST = superTrend;
    plot DIR = trend;
}
#// Get SuperTrend Values
def supertrend = supertrend(factor, atrPeriod).ST;

#//Entry signal
def bull_STC = close > supertrend and close[1] < supertrend[1];
def bear_STC = close < supertrend and close[1] > supertrend[1];

#//To get around runtime issue
#// How Many Green Bars Before the condtion hapeens again
def howManyGB = if bull_STC then 1 else bull_STC[1] + 1;#(barssince(bull_STC)) + 1;
def howManyRB = if bear_STC then 1 else bear_STC[1] + 1;#(barssince(bear_STC)) + 1;

#// lookbackperiod so i dont get ZEROS in my look back period
def LB  = if howManyGB > howManyRB then howManyGB else howManyRB;
def lookBack = if isNaN(LB) then 1 else LB + 1;
#// Get level using a changing lookback period added bar_DEX to fix loading  on to chart issues
#// get open values for the rare occurance that its actually the high rare but happens
def lowLevel  = fold i = 0 to lookBack with p = LRC do
                Min(p, GetValue(LRC, i));#if p <= GetValue(LRC, i) then p else GetValue(LRC, i);
def lowLevelOpen  = fold i1 = 0 to lookBack with p1 = open do
                    Min(p1, GetValue(open, i1)); #if p1 <= GetValue(open, i1) then p1 else GetValue(open, i1);
#--
def highLevel = fold i2 = 0 to lookBack with p2=HRC do
                Max(p2, GetValue(HRC, i2)); #if p2 >= GetValue(HRC, i2) then p2 else GetValue(HRC, i2);
def highLevelOpen = fold i3 = 0 to lookBack with p3 = open do
                    Max(p3, GetValue(open, i3)); #if p3 >= GetValue(open, i3) then p3 else GetValue(open, i3);

def lowLevelX = if lowLevelOpen < lowLevel then lowLevelOpen else lowLevel;
def highLevelX = if highLevelOpen > highLevel then highLevelOpen else highLevel;

#// include entry cand high or low in the lookback
def lowLevelB = if lowLevelX < LRO then lowLevelX else LRO;
def highLevelB = if highLevelX > HRO then highLevelX else HRO;
#// Create StopLoss Point
def sellStopLoss = highLevelB + (atr * stopLossMultiplier) + spread;
def buyStopLoss  = lowLevelB - (atr * stopLossMultiplier) - spread;
#// Create TakeProfit / a reflection of stop loss
def sellTakeProfit =  (close - (sellStopLoss - close) * takeProfitMultiplier);
def buyTakeProfit  = (takeProfitMultiplier * (close - buyStopLoss) + close);

#// change color based  on current charts momentum
def trendColor  = if bull_STC and momentumSwitch and smartOverlay then 2 else
                  if bear_STC and momentumSwitch and smartOverlay then -2 else
                  if close > supertrend and smartOverlay then 1 else
                  if close < supertrend and smartOverlay then -1 else 0;

AssignPriceColor(if trendColor == 2 then Color.CYAN else
                 if trendColor == 1 then Color.DARK_GREEN else
                 if trendColor ==-2 then Color.MAGENTA else
                 if trendColor ==-1 then Color.DARK_RED else Color.GRAY);

#// Draw Take Profit and Stop Loss points
plot BuySL  = if bull_STC then buyStopLoss else na;    # "Buy Stop Loss"
plot SellSL = if bear_STC then sellStopLoss else na;   # "Sell Stop Loss"
plot BuyTP  = if bull_STC then buyTakeProfit else na;  # "Buy Take Profit"
plot SellTP = if bear_STC then sellTakeProfit else na; # "Sell Take Profit"

BuySL.SetPaintingStrategy(PaintingStrategy.DASHES);
SellSL.SetPaintingStrategy(PaintingStrategy.DASHES);
BuyTP.SetPaintingStrategy(PaintingStrategy.DASHES);
SellSL.SetPaintingStrategy(PaintingStrategy.DASHES);

BuySL.SetDefaultColor(Color.GREEN);
SellSL.SetDefaultColor(Color.RED);
BuyTP.SetDefaultColor(Color.WHITE);
SellTP.SetDefaultColor(Color.GRAY);
#/position Sizing accountSize default 100,000 betpercentage default = 1  and
#//0.01 to turn it into a percentage    divide:   stoploss too entry candle close  is = sellTakeProfit (reflection)
#// Minus close from sellTakeProfit to just get entry candle's stoploss to its close only
#//multilpy by 10000 to get number of pips  multiply by 10  to get answer in LOTs! (not micro or mini)

def sellbuyPositionSizeA  =(accountSize * (betPercentage * 0.01));
def sellPositionSizeB= (sellStopLoss - close) * 10000 * 10;
def buyPositionSizeB= (close - buyStopLoss) * 10000 * 10;
def sellPositionSizeC = sellbuyPositionSizeA / sellPositionSizeB;
def buyPositionSizeC = sellbuyPositionSizeA / buyPositionSizeB;

def dir = if bear_STC then -1 else if bull_STC then 1 else dir[1];
AddLabel(dir<0, "Sell Stop Loss: $" + Round(sellStopLoss, 2), color.RED);
AddLabel(dir<0, "Position Size: " + Round(sellPositionSizeC, 2), color.RED);
AddLabel(dir<0 and takeProfitMultiplier > 0, "SellTakeProfit: " + Round(sellTakeProfit, 2), color.RED);

AddLabel(dir>0, "Buy Stop Loss: $" + Round(buyStopLoss, 2), color.GREEN);
AddLabel(dir>0, "Position Size: " + Round(buyPositionSizeC, 2), color.GREEN);
AddLabel(dir>0 and takeProfitMultiplier > 0, "BuyTakeProfit: " + Round(buyTakeProfit, 2), color.GREEN);


#-- END of CODE
 
Anyone script savy enough to create a scanner for this indicator?

I am looking for a scanner that would scan for the change in candle stick colors. specifically the yellow entry for going long and cyan entry for going short. and also add a feature that you could enter within 1 bar of the entry.
 
Anyone script savy enough to create a scanner for this indicator?


Change this line of code:
def trendColor = if bull_STC and momentumSwitch and smartOverlay then 2 else
To:
plot trendColor = if bull_STC and momentumSwitch and smartOverlay then 2 else

Your buy filter condition is:
trendColor == 2

Your sell filter condition is:
trendColor == -2

Follow the Scan Hacker tutorial to set up your scan and to learn how to scan within x bars:
https://usethinkscript.com/threads/how-to-use-thinkorswim-stock-hacker-scans.284/

Unfortunately, you will probably get a "too complex" error when you attempt to run your scan.
There are workarounds to this error, but generally they don't work:
https://usethinkscript.com/threads/answers-to-commonly-asked-questions.6006/#post-57834
Schwab purposefully throttles the use of these types of scans to prevent high loads hits to their servers.
 
Last edited:

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
347 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