Repaints Trend Reversal for ThinkorSwim

Repaints
Status
Not open for further replies.
@MerryDay I reached out to @BenTen and he asked me to post the request on the forum. I know is not a perfect system and it repaints. Just need help with the details of the code to get it working per my description. If anyone is able to help with the code I will appreciate it. Below is the idea of the code and what I would like for it to do.

I am using the Trend Reversal Indicator as a trading strategy for an auto trading robot for TOS (BETA PAPER TRADING). The Robot takes signals from the Labels and Alert notifications to execute trades. What I need help with is to make sure the Robot enters the trade on “Buy” signals and closes the trade on “Sell” signal ( I am able to get this part done perfectly). What is giving trouble is adding a delay of 3-5 seconds for robot to reset and start scanning to enter “Short”. This needs to be accomplished via the Labels and Alert notifications. I also have a Stop-Loss incorporated in the study and need that working on a switch basis. Need to alert based on CASE 1 “LONG” or CASE 2 “SHORT” on a trade.

Below is the coded strategy (work in progress).

Code:
#Date: Dec-13-2020
#TrendReversal Version 2.1
#Updated


# Removed fibs
# Changed bubbles from Reversal to BUY and SELL
# Added Tradesize and Order Entry

### TradeSIZE Size
input TRADESIZE = 100;

### EXIT BAD
input stop = 20;
input offsetType = {default tick, percent, value};

def price = close;
def superfast_length = 9;
def fast_length = 14;
def slow_length = 21;
def displace = 0;

def mov_avg9 = ExpAverage(price[-displace], superfast_length);
def mov_avg14 = ExpAverage(price[-displace], fast_length);
def mov_avg21 = ExpAverage(price[-displace], slow_length);

#moving averages
def Superfast = mov_avg9;
def Fast = mov_avg14;
def Slow = mov_avg21;

def buy = mov_avg9 > mov_avg14 and mov_avg14 > mov_avg21 and low > mov_avg9;
def stopbuy = mov_avg9 <= mov_avg14;
def buynow = !buy[1] and buy;
def buysignal = CompoundValue(1, if buynow and !stopbuy then 1 else if buysignal[1] == 1 and stopbuy then 0 else buysignal[1], 0);

def Buy_Signal = buysignal[1] == 0 and buysignal == 1;
def Momentum_Down = buysignal[1] == 1 and buysignal == 0;

def sell = mov_avg9 < mov_avg14 and mov_avg14 < mov_avg21 and high < mov_avg9;
def stopsell = mov_avg9 >= mov_avg14;
def sellnow = !sell[1] and sell;
def sellsignal = CompoundValue(1, if sellnow and !stopsell then 1 else if sellsignal[1] == 1 and stopsell then 0 else sellsignal[1], 0);
def Sell_Signal = sellsignal[1] == 0 and sellsignal;


plot Colorbars = if buysignal == 1 then 1 else if sellsignal == 1 then 2 else if buysignal == 0 or sellsignal == 0 then 3 else 0;
Colorbars.Hide();
Colorbars.DefineColor("Buy_Signal_Bars", Color.GREEN);
Colorbars.DefineColor("Sell_Signal_Bars", Color.RED);
Colorbars.DefineColor("Neutral", Color.YELLOW);
#___________________________________________________________________________

input method = {default average, high_low};
def bubbleoffset = .0005;
def percentamount = .01;
def revAmount = .05;
def atrreversal = 2.0;
def atrlength = 5;
def pricehigh = high;
def pricelow = low;
def averagelength = 5;
def averagetype = AverageType.EXPONENTIAL;
def mah = MovingAverage(averagetype, pricehigh, averagelength);
def mal = MovingAverage(averagetype, pricelow, averagelength);
def priceh = if method == method.high_low then pricehigh else mah;
def pricel = if method == method.high_low then pricelow else mal;
def EI = ZigZagHighLow("price h" = priceh, "price l" = pricel, "percentage reversal" = percentamount, "absolute reversal" = revAmount, "atr length" = atrlength, "atr reversal" = atrreversal);
rec EISave = if !IsNaN(EI) then EI else GetValue(EISave, 1);
def chg = (if EISave == priceh then priceh else pricel) - GetValue(EISave, 1);
def isUp = chg >= 0;
def EIL = if !IsNaN(EI) and !isUp then pricel else GetValue(EIL, 1);
def EIH = if !IsNaN(EI) and isUp then priceh else GetValue(EIH, 1);
def dir = CompoundValue(1, if EIL != EIL[1] or pricel == EIL[1] and pricel == EISave then 1 else if EIH != EIH[1] or priceh == EIH[1] and priceh == EISave then -1 else dir[1], 0);
def signal = CompoundValue(1, if dir > 0 and pricel > EIL then if signal[1] <= 0 then 1 else signal[1] else if dir < 0 and priceh < EIH then if signal[1] >= 0 then -1 else signal[1] else signal[1], 0);

def bullish2 = signal > 0 and signal[1] <= 0;
plot upArrow = bullish2;
upArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
upArrow.SetDefaultColor(CreateColor(145, 210, 144));

def bearish2 = signal < 0 and signal[1] >= 0;
plot downArrow = bearish2;
downArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
downArrow.SetDefaultColor(CreateColor(255, 15, 10));



def showarrows = yes;
def U1 = showarrows and signal > 0 and signal[1] <= 0;
#U1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#U1.SetDefaultColor(Color.GREEN);
#U1.SetLineWeight(4);
def D1 = showarrows and signal < 0 and signal[1] >= 0;
#D1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#D1.SetDefaultColor(Color.RED);
#D1.SetLineWeight(4);

def barnumber = BarNumber()[10];

#START
AddChartBubble((barnumber and U1), if isUp then low else high, if showarrows and signal > 0 and signal[1] <= 0 then " BUY " else "" , if Colorbars == 3 then Color.YELLOW else Color.UPTICK, no);
AddChartBubble((barnumber and D1), if isUp then low else high, if showarrows and signal < 0 and signal[1] >= 0 then " SELL " else "" , if Colorbars == 3 then Color.YELLOW else Color.DOWNTICK, yes);
#END

def revLineTop;
def revLineBot;

if barnumber and D1 {
    revLineBot = Double.NaN;
    revLineTop = high[1];
} else if barnumber and U1 {
    revLineTop = Double.NaN;
    revLineBot = low[1];
} else if !IsNaN(revLineBot[1]) and (Colorbars[2] == 2 or Colorbars[1] == 2) {
    revLineBot = revLineBot[1];
    revLineTop = Double.NaN;
} else if !IsNaN(revLineTop[1]) and (Colorbars[2] == 1 or Colorbars[1] == 1) {
    revLineTop = revLineTop[1];
    revLineBot = Double.NaN;
} else {
    revLineTop = Double.NaN;
    revLineBot = Double.NaN;
}

plot botLine = revLineBot[-1];
botLine.SetDefaultColor(Color.LIGHT_GREEN);
plot topLine = revLineTop[-1];
topLine.SetDefaultColor(Color.LIGHT_RED);

################ EXIT BAD
def entryPrice = EntryPrice();
def mult;
switch (offsetType) {
case percent:
    mult = entryPrice / 100;
case value:
    mult = 1;
case tick:
    mult = TickSize();
}
def stopPriceLE = entryPrice - stop * mult;
def stopPriceSE = entryPrice + stop * mult;

plot BAD_LONG_STOP = stopPriceLE;
plot BAD_SHORT_STOP = stopPriceSE;


### ORDERS
AddOrder(OrderType.BUY_AUTO, upArrow[1] == 1, open, TRADESIZE, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "ENTER TRADE");
AddOrder(OrderType.SELL_AUTO, downArrow[1] == 1, open, TRADESIZE, tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "EXIT  TRADE");
AddOrder(OrderType.BUY_TO_CLOSE, high >= stopPriceSE from 1 bars ago crosses above stopPriceSE, close, TRADESIZE, tickcolor = GetColor(3), arrowcolor = GetColor(3), name = "EXIT BAD SHORT");
AddOrder(OrderType.SELL_TO_CLOSE, low <= stopPriceLE from 1 bars ago crosses below stopPriceLE, close, TRADESIZE, tickcolor = GetColor(3), arrowcolor = GetColor(3), name = "EXIT BAD LONG");


### ALERTS
Alert(upArrow[1] == 1, " BUY SIGNAL ", Alert.BAR, Sound.Chimes);
Alert(downArrow[1] == 1, " SELL SIGNAL ", Alert.BAR, Sound.Chimes);
Alert(high >= stopPriceSE from 1 bars ago crosses above stopPriceSE and TRADESIZE * -100 <= -1 == 1, " BAD SHORT EXIT TRADE ", Alert.BAR, Sound.Chimes);
Alert(low <= stopPriceLE from 1 bars ago crosses below stopPriceLE and TRADESIZE * 100 >= 1 == 1, " BAD LONG EXIT TRADE ", Alert.BAR, Sound.Chimes);

### LABELS
AddLabel(yes, if (upArrow[1] >= 1 within 2 bars) or (high >= stopPriceSE from 1 bars ago crosses above stopPriceSE) then " BUY BUY BUY " else " NO SIGNAL ", Color.YELLOW);
AddLabel(yes, if (downArrow[1] >= 1 within 2 bars) or (low <= stopPriceLE from 1 bars ago crosses below stopPriceLE) then " SELL SELL SELL " else " NO SIGNAL ", Color.WHITE);

### The Robot uses the Labels and Alerts for order execution. A long order must be closed and after a 3-5 seconds delay I would like the robot to enter a "short" trade that will be closed by a "Buy" signal from the study. This will run on a loop.

### STOP-LOSS, The Stop-loss should be on a switch or similar code. Trigger stop-loss alert and label only if price goes against the trade in place at the time.

### Plan on running strategy on Renko Charts.

### If there's unnessessary code on this study that can be removed without affecting functionality please do so to make code cleaner and easier to read.
 
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

I tried it using a short watchlist. It's not working, do you need to run it during market hours for it to work? Error: "Trying to self-assign a non-initialized rec : state." I only have 20 stocks in the watchlist
I couldn't get the scan to work either. It has something incomplete because it returns an error any time I've tried to use it.
 
Please forgive the seemingly novice question, but what do you mean by repaint? I have tried to catch its meaning by its contextual usage but sometimes it seems to be a good thing and sometimes a bad thing. A quick search has left me confused still.
Many thanks in advance!
 
@Marvin187 I have also been working on a bot that plugs into ToS. So far, I can receive signals and target button functions. I’m working on connecting the signals to actions next. It takes about 100ms from ToS signal to order execution. It only runs on macOS for now, since it is my primary platform. I’ll work on windows next.

May be we can compare notes.
 
@horserider Does the reversal indicator you posted repaint? So far, I have not noticed a repaint. But it is so accurate with my Renko chart that I wanted to make sure. :) And, do you have an audible alert for it? Thanks for any info/help you can provide.
 
Last edited:
I am a newbie on this platform & this is my first post.
I was trying to use the scanner version. I tried with condition "uparrow is true" & then again with "uparrow >= 0" & in both cases, ran Into an error issue - "Error: Trying to self assign a non-initialized rec: state".
Can some one help me with fixing this issue?
Thanks in anticipation.
 
Hello, I wanted to know if anyone has made or can help make this exact same trend reversal indicator but with MTF(multi-time-frame). On different time frames this indicator provides different alerts and price entries. The goal would be to have the same bubble show up but also include MTF in its calculation (1min, 5min, 15min, 30min, 60min, 4hr, 1day)...and if possible display that data in the bubble or have multiple color options depending on how many give that signal or what the average price would be.
 
what's the different to add it as indicator and as strategy ?
I noticed some talked about ( repaint ) can anyone explain what does it mean. ?
 
The "AddChartBubble" lines are numerous in this study and liberally sprinkled throughout. If somehow, you are overlooking the specific one that you want to change; I recommend that you copy and paste the script into an editor or word processor that has a search and find function.
Search for AddChartBubble.
HTH
 
Status
Not open for further replies.

BenTen's Watchlist + Setup + Trade Recaps

Get access to Ben's watchlist, swing trading strategy, ThinkorSwim setup, and trade examples.

Learn more

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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