Strategy Based on EMAs, TSI, MACD, and Premarket Highs/Lows For ThinkOrSwim

I have posted an updated and hopefully better functioning watchlist indicator in Post #1. You won't see very many (if any) visual changes and it may or may not show "loading" but it will better match the changes made to the strategy. I have removed every possible line and changed all inputs to def, removed all bubbles, and removed all labels so HOPEFULLY it doesn’t show loading anymore. Fingers crossed it works better.

Don’t think I can code a setting to allow users to change the colors, sorry.
Seemed to work much better today. Only saw "loading" this morning. Hopefully not a fluke.
 
Wonderful results for AMZN. Congratulations for devising such a great strategy. I am consistently using it.
I agree with your comments about SPY. However, could you please look at SPY for 4/29/2022. It consistently had a GOLD candle and it consistently went down below 5EMA. Is this possible to finetune your algo(s) to catch this type of up/down movement? I saw that DARK_BLUE candles were forming and then were beinbg colored to GOLD.
 
@a1cturner, How hard would it be to modify the strategy to a daily time frame to swing trade? Remove the Premarket and just use the EMA separation?

I'm offshore for the next 3 weeks and the internet is to slow to day trade. If I have time is it ok if I try and modify it?
 
Last edited by a moderator:
@a1cturner, How hard would it be to modify the strategy to a daily time frame to swing trade? Remove the Premarket and just use the EMA separation?

I'm offshore for the next 3 weeks and the internet is to slow to day trade. If I have time is it ok if I try and modify it?

Go for it. Probably only have to remove the premarket, time constraints, EMA separation, and that may be it. Let us know how it turns out.
 
Wonderful results for AMZN. Congratulations for devising such a great strategy. I am consistently using it.
I agree with your comments about SPY. However, could you please look at SPY for 4/29/2022. It consistently had a GOLD candle and it consistently went down below 5EMA. Is this possible to finetune your algo(s) to catch this type of up/down movement? I saw that DARK_BLUE candles were forming and then were beinbg colored to GOLD.
It was the EMA Separation Threshold. SPY sits around 0.2 but less than 0.25. The quick fix would be to change the time frame to 5 minutes because that time frame is set to 0.2. The only difference will be the final candle will not be a set candle if you change to the 5 minute time frame.
 
Wonderful results for AMZN. Congratulations for devising such a great strategy. I am consistently using it.
I agree with your comments about SPY. However, could you please look at SPY for 4/29/2022. It consistently had a GOLD candle and it consistently went down below 5EMA. Is this possible to finetune your algo(s) to catch this type of up/down movement? I saw that DARK_BLUE candles were forming and then were beinbg colored to GOLD.
Better yet, look at 30 minute / 10 day time frame with the strategy set to 30 minutes.
 
Last edited:
Trying to figure out how to "predict" the next candles EMA separation to try to get an entry 1 bar earlier or at least get an entry just prior to the EMAs meeting the EMA Separation Criteria.

Not getting very far.

Anyone have ideas?

What I am trying to accomplish. If the 5EMA is greater than the 5EMA from 1 bar ago then get that difference. Do this for the 5 previous bars. Take those 5 differences and average them out. Do the same thing for the 12EMA. Then add the average of the 5EMA differences to the current 5 EMA and add the average of the 12EMA differences to the current 12EMA. Finally calculate the percent separation using the (((FastEMA1 / Fast EMA2) * 100) - 100) formula. If that number is greater than the threshold built in the code for the current time frame (10 minutes is 0.25) than that will trigger a buy signal.

Repeat for Bearish EMAs.

Sounds easier when I write it down but I am running on a lack of sleep right now. Maybe tomorrow.

This is what I have tried so far. The first half definitely didn't work. Attempt 3 is the beat yet but I don't think it's the best.

Code:
##################################################################
#                                TESTING                         #
##################################################################

#def EMA1Pred1 = if FastEMA1[0] > FastEMA1[1] then FastEMA1[0]-FastEMA1[1] else EMA1Pred1[1];
#def EMA1Pred2 = if FastEMA1[1] > FastEMA1[2] then FastEMA1[1]-FastEMA1[2] else EMA1Pred2[1];
#def EMA1Pred3 = if FastEMA1[2] > FastEMA1[3] then FastEMA1[2]-FastEMA1[3] else EMA1Pred3[1];
#def EMA1Pred4 = if FastEMA1[3] > FastEMA1[4] then FastEMA1[3]-FastEMA1[4] else EMA1Pred4[1];
#def EMA1Pred5 = if FastEMA1[4] > FastEMA1[5] then FastEMA1[4]-FastEMA1[5] else EMA1Pred5[1];

#def EMA2Pred1 = if FastEMA2[0] > FastEMA2[1] then FastEMA2[0]-FastEMA2[1] else EMA2Pred1[1];
#def EMA2Pred2 = if FastEMA2[1] > FastEMA2[2] then FastEMA2[1]-FastEMA2[2] else EMA2Pred2[1];
#def EMA2Pred3 = if FastEMA2[2] > FastEMA2[3] then FastEMA2[2]-FastEMA2[3] else EMA2Pred3[1];
#def EMA2Pred4 = if FastEMA2[3] > FastEMA2[4] then FastEMA2[3]-FastEMA2[4] else EMA2Pred4[1];
#def EMA2Pred5 = if FastEMA2[4] > FastEMA2[5] then FastEMA2[4]-FastEMA2[5] else EMA2Pred5[1];

#def FastEMAAvg = ((((EMA2Pred1 / EMA1Pred1) *100) - 100) + (((EMA2Pred2 / EMA1Pred2) *100) - 100) + (((EMA2Pred3 / EMA1Pred3) *100) - 100) + (((EMA2Pred4 / EMA1Pred4) *100) - 100) + (((EMA2Pred5 / EMA1Pred5) *100) - 100)) / 5;

###################### ATTEMPT 2 ##########################

#def FastEMAPred1 = if FastEMA1[0] > FastEMA1[1] then (((FastEMA1 / FastEMA2) * 100) - 100) else FastEMAPred1[1];
#def FastEMAPred2 = if FastEMA1[1] > FastEMA1[2] then (((FastEMA1[1] / FastEMA2[1]) * 100) - 100) else FastEMAPred2[1];
#def FastEMAPred3 = if FastEMA1[2] > FastEMA1[3] then (((FastEMA1[2] / FastEMA2[2]) * 100) - 100) else FastEMAPred3[1];
#def FastEMAPred4 = if FastEMA1[3] > FastEMA1[4] then (((FastEMA1[3] / FastEMA2[3]) * 100) - 100) else FastEMAPred4[1];
#def FastEMAPred5 = if FastEMA1[4] > FastEMA1[5] then (((FastEMA1[4] / FastEMA2[4]) * 100) - 100) else FastEMAPred5[1];

#def FastEMAAvg = (FastEMAPred1 + FastEMAPred2 + FastEMAPred3 + FastEMAPred4 + FastEMAPred5) / 5;
#plot FastEMAPlot1 = (FastEMA1[-1] + FastEMAAvg);
#plot FastEMAPlot2 = FastEMA2[-1] + FastEMAAvg;

#addlabel(yes, FastEMAAvg);

###################### ATTEMPT 3 ##########################

def FastEMA1Avg = (FastEMA1 + ((FastEMA1 + FastEMA1[1] + FastEMA1[2] + FastEMA1[3] + FastEMA1[4]) / 5) / 2);
def FastEMA2Avg = (FastEMA2 + ((FastEMA2 + FastEMA2[1] + FastEMA2[2] + FastEMA2[3] + FastEMA2[4]) / 5) / 2);
def FastEMAPctBullAvg = (((FastEMA1Avg / FastEMA2Avg) *100) - 100);
def FastEMAPctBullAvgRound = Round(FastEMAPctBullAvg, 2);
def FastEMAPctBearAvg = (((FastEMA2Avg / FastEMA1Avg) *100) - 100);
def FastEMAPctBearAvgRound = Round(FastEMAPctBearAvg, 2);


addlabel(yes, FastEMAPctBullRound, color.green);
addlabel(yes, FastEMAPctBearRound, color.red);
addlabel(yes, FastEMAPctBullAvgRound, color.dark_green);
addlabel(yes, FastEMAPctBearAvgRound, color.dark_red);

##################################################################
#                                TESTING                         #
##################################################################
 
Last edited:
Trying to figure out how to "predict" the next candles EMA separation to try to get an entry 1 bar earlier or at least get an entry just prior to the EMAs meeting the EMA Separation Criteria.

Not getting very far.

Anyone have ideas?

What I am trying to accomplish. If the 5EMA is greater than the 5EMA from 1 bar ago then get that difference. Do this for the 5 previous bars. Take those 5 differences and average them out. Do the same thing for the 12EMA. Then add the average of the 5EMA differences to the current 5 EMA and add the average of the 12EMA differences to the current 12EMA. Finally calculate the percent separation using the (((FastEMA1 / Fast EMA2) * 100) - 100) formula. If that number is greater than the threshold built in the code for the current time frame (10 minutes is 0.25) than that will trigger a buy signal.

Repeat for Bearish EMAs.

Sounds easier when I write it down but I am running on a lack of sleep right now. Maybe tomorrow.

This is what I have tried so far. The first half definitely didn't work. Attempt 3 is the beat yet but I don't think it's the best.

Much closer and more accurate. More to come...

Code:
def FastEMA1Avg = (FastEMA1 + ((FastEMA1 - FastEMA1[1]) + (FastEMA1[1] - FastEMA1[2]) / 2));
def FastEMA2Avg = (FastEMA2 + ((FastEMA2 - FastEMA2[1]) + (FastEMA2[1] - FastEMA2[2]) / 2));
def FastEMAPctBullAvg = (((FastEMA1Avg / FastEMA2Avg) *100) - 100);
def FastEMAPctBullAvgRound = Round(FastEMAPctBullAvg, 2);
def FastEMAPctBearAvg = (((FastEMA2Avg / FastEMA1Avg) *100) - 100);
def FastEMAPctBearAvgRound = Round(FastEMAPctBearAvg, 2);


addlabel(yes, FastEMAPctBullRound, color.green);
addlabel(yes, FastEMAPctBearRound, color.red);
addlabel(yes, FastEMAPctBullAvgRound, color.dark_green);
addlabel(yes, FastEMAPctBearAvgRound, color.dark_red);
 
Much closer and more accurate. More to come...

Code:
def FastEMA1Avg = (FastEMA1 + ((FastEMA1 - FastEMA1[1]) + (FastEMA1[1] - FastEMA1[2]) / 2));
def FastEMA2Avg = (FastEMA2 + ((FastEMA2 - FastEMA2[1]) + (FastEMA2[1] - FastEMA2[2]) / 2));
def FastEMAPctBullAvg = (((FastEMA1Avg / FastEMA2Avg) *100) - 100);
def FastEMAPctBullAvgRound = Round(FastEMAPctBullAvg, 2);
def FastEMAPctBearAvg = (((FastEMA2Avg / FastEMA1Avg) *100) - 100);
def FastEMAPctBearAvgRound = Round(FastEMAPctBearAvg, 2);


addlabel(yes, FastEMAPctBullRound, color.green);
addlabel(yes, FastEMAPctBearRound, color.red);
addlabel(yes, FastEMAPctBullAvgRound, color.dark_green);
addlabel(yes, FastEMAPctBearAvgRound, color.dark_red);

Predictions are accurate about 25% of the time. Going to have to add something that accounts for the open of the current candle and probably avg movement of the last 2 to 5 candles to get a better prediction average.

Sorry for the multiple post. If I don’t write it down I will forget and I figure it’s better to write my thoughts for everyone to see in case they have ideas.
 
Lets make it simple what if i want to add rule
To consider bullish if it is greater than one dollar Or 3 dollars or even percentage And opposite for bearish
Instead of pre market high and low
 
To avoid trading against the trend, besides many available studies, I use one built-in study called TTM_LRC on a 2 HR chart to see the overall trend and use a 10-minute chart for trading. I avoid against the trend trades to avoid losses and as a general rule, if my portfolio drops below 5% from the point in time I started the trades, I close all trades and I do not trade that day.
This current study yields good results/profits on a daily basis and serves its purpose better than any other strategy, that I have used so far. We just need to be a bit careful. Hope this helps.
TTM_LRC is built-in the TOS.
@fskhan I just looked at this using a 4 hour chart on TSLA and WOW it is a great indicator of reversal! I am definitely going to have to add this to my arsenal! Thanks for sharing!

I think if the stock crosses the purple or red line on the LRC study and starts reversing back towards it you could definitely buy some calls or puts for the strike at the white line level and do very well! If you paired that with my study and are in the take profit zone on the 10 minute and over the purple or red line on the 4 hour there is surely a reversal coming. I think I will test this out on Monday. More risky and would be against the trend at the time but dang the payoff would be huge!

Another study to be written!?!? 🤔
 
Last edited:
Lets make it simple what if i want to add rule
To consider bullish if it is greater than one dollar Or 3 dollars or even percentage And opposite for bearish
Instead of pre market high and low
That could probably be changed if you want to write that in your version of the code but I have noticed that a lot of stocks will just bounce around their premarket high and low all day instead of a strong move up or down if it exits that zone. Not only that but a $3 move on a $1000 stock won't tell you much and percentages can get tricky depending on the price of the stock also.
 
Theres is very 2 important point i spent alot of money joining alot of trading group Especially in option trading
First trading around pivot point ( different deff among traders) ( make option to add them manually for example )if it brake it either it will go up or down
Second trade lines like connecting all high and all lows and brake this lines
If you can integrate this in your system you will make alot of money
 
@fskhan I just looked at this using a 4 hour chart on TSLA and WOW it is a great indicator of reversal! I am definitely going to have to add this to my arsenal! Thanks for sharing!

I think if the stock crosses the purple or red line on the LRC study and starts reversing back towards it you could definitely buy some calls or puts for the strike at the white line level and do very well! If you paired that with my study and are in the take profit zone on the 10 minute and over the purple or red line on the 4 hour there is surely a reversal coming. I think I will test this out on Monday. More risky and would be against the trend at the time but dang the payoff would be huge!

Another study to be written!?!? 🤔
Linear Regression channels should be very similar or close for 2 Hour and 4 hour charts. LRC is at least good for trend of the market until it changes.

However, this does not mean that LRC will be same on all Time Frames. For a 5, 10 or 15 minutes chart. Trend could be different or Opposite of 2 Hours or 4 Hours chart.

Additionally, the Pivot point or reversal point on a 4 hour and 2 Hour LRC is pretty decent and shows the current overall trend and then a 15 minute or 10 minute LRC shows current minor trend within the major trend.

To explain this further
1. SPY on 2 or 4 hours chart is in a downtrend.
2. And On a 10 or 5-minute chart is in the uptrend.

So I usually avoid OR am very careful with the trades which are against the major trend as this does not give much returns.
 
Just be carfull every one when i change the time it doesnt reflex in The EMA Separation Threshold.
I dont know if it s just me or any one else it stays .65 all time frame
 
Just be carfull every one when i change the time it doesnt reflex in The EMA Separation Threshold.
I dont know if it s just me or any one else it stays .65 all time frame

The 0.65 that you mention is the percent decrease of the EMA separation at the time of the buy signal (bright green bar) not the separation calculated for the buy signal. You don’t see the EMA separation for the buy signal unless you go into the actual code.

For example. For AAPL to trigger a buy on the 10 minute chart it requires a 0.25 separation which would be somewhere around maybe $159.90 on the 5EMA and 159.50 on the 12EMA.

((159.90 / 159.50) * 100) - 100 = 0.25

Now that has to decrease by 65% (0.65) to 0.16 to trigger a sell. So let’s say the price climbs and climbs and climbs and now the EMAs are at $163.50 for the 5EMA and 163.23 for the 12EMA.

((163.50 / 163.23) * 100) - 100 = 0.16

That would be your sell signal.
 
The 0.65 that you mention is the percent decrease of the EMA separation at the time of the buy signal (bright green bar) not the separation calculated for the buy signal. You don’t see the EMA separation for the buy signal unless you go into the actual code.

For example. For AAPL to trigger a buy on the 10 minute chart it requires a 0.25 separation which would be somewhere around maybe $159.90 on the 5EMA and 159.50 on the 12EMA.

((159.90 / 159.50) * 100) - 100 = 0.25

Now that has to decrease by 65% (0.65) to 0.16 to trigger a sell. So let’s say the price climbs and climbs and climbs and now the EMAs are at $163.50 for the 5EMA and 163.23 for the 12EMA.

((163.50 / 163.23) * 100) - 100 = 0.16

That would be your sell signal.
Thank you for clarifying this point
 
hi ijust added previuos day high and low
And 30 minute high and low beside the premarket
I am getting more entries small constant win
Any one of them flag i will take the trade
 
Current Version 9 - 04/27/2022

Strategy Link: http://tos.mx/GNDZPOw

To use the strategy code below (not the link above) click on the charts tab, studies button, edit studies, strategies tab, create, copy and paste the first code in and change the name at the top to your liking, click ok. Make sure to follow the rules on the first post regarding time frame, extended hours etc.

Watchlist Link: http://tos.mx/e7sxL3g

Watchlist Indicator: http://tos.mx/il7XiiW

For the watchlist custom indicator (again, the code is below not the link above)click the gear icon on your watchlist, customize, type in “custom”, click the small scroll looking icon to the left of an unused custom study, paste the second code in and change the name to your liking (something short), change the “D” to “10m” and check extended hours, click ok.

Flexible Grid Link: http://tos.mx/M2AL2lK

D3KSZ9S.png


I WILL ADD ALL UPDATES HERE! This strategy is changing and I don’t want to confuse anyone with comments from previous versions in the post below!!!

I am pretty dang excited about this one! This is months of trial and error with different strategies and indicators. This is what I have found that works best as of today. I am continually updating this strategy to refine it and/or find better entries and exits. All updates will be posted here on Post #1.

This strategy uses four EMAs (5EMA, 12EMA, 34EMA, and 50EMA), MACD, TSI, and Pre-Market High/Low. The EMAs are arranged in clouds (5EMA / 12EMA and 34EMA / 50EMA). Again this could change over time as I refine the strategy.

The triggers I am using are:
  • Signal only between 9:00 A.M. CST until 3:00 P.M. CST
  • Both EMAs Bullish (5EMA>12EMA and 34EMA>50EMA) or Both EMAs Bearish (5EMA<12EMA and 34EMA<50EMA)
  • MACD Trending Up or MACD Trending Down
  • TSI >10 and trending up or TSI <-10 and trending down
  • Low > the Pre-Market High or High < the Pre-Market Low
  • Last candle of the day is always a sell candle
Again, subject to change.

Of note, I use this for options so the wording I use in the strategy is geared towards that.
  • Gray Candles - Criteria Not Met
  • Yellow Candle - "Get Ready" candles (Both EMA Clouds Bullish and Over PreMarket High or Both EMA Clouds Bearish and Below PreMarket Low)
  • Blue Candle - Put Buy or Sell to Open (Short) (Entry is on the 5EMA or When you get the Buy Bubble)
  • Light Blue Candle - Put Hold or Short Hold
  • Green Candle - Call Buy or Buy to Open (Long) (Entry is on 5EMA or when you get the Buy Bubble)
  • Light Green Candle - Call Hold or Long Hold
  • Red Candle - Sell Call or Sell Put or Sell to Close Long or Buy to Close Short (Exit is on close)
  • Orange/Red Candle - Take Profit. Set Trailing Stop the minute you enter the Over Extended Cloud or when you get the "Tk Pft" Bubble

Candle colors can be changed using the gear icon, scrolling to the very bottom and changing the "globals" settings.

LNa4WlH.png


Very simple instructions using the bubbles.
  • If you FOMO in at the beginning of the day, which you shouldn't, and you get a Tk Pft Bubble than GET OUT!
  • If you were patient and waited on the Buy (Now "Long" or "Short" in Version 7a) Bubble then get in on that 5EMA or better.
    • You should not get a Buy ("Long" or "Short" in 7a) Bubble unless the price is already at the 5EMA.
    • If you are confident in your order placing abilities and the spread isn't too wide you can even set a trailing stop buy order to try to get the best price.
    • If you don't get in on the first Buy (you get the point) Bubble you will have a good chance on the next candle or maybe the one after that.
    • I wouldn't wait too long though because as we all know the market can change drastically in minutes.
  • If you get a Tk Pft Bubble than again, GET OUT!
    • This is a great spot for a trailing stop depending on the spread!
  • If you get a Sell Bubble than GET OUT!
    • Market, Limit, Stop.....Just Get Out!
  • Rinse and Repeat. Don't Get Fancy! Let It work or move on to a stock that is working!

--------(OLD INSTRUCTIONS BEFORE BUBBLES) I get in on the green (not light green) or blue (not light blue) candles but only, and this is very important especially for options, only when the stock price is at the 5 EMA or even better the 12 EMA. You sell on the close of the red candles.

Of note, the candles do change sometimes until closed at the end of the time period (10 minutes) This is not a big deal on the sell side since I am using the close price of the sell candle but if you do miss the 5 EMA entry of the buy candle than try to catch it as soon as possible on the next candle. Personally if I miss my entry and have to wait too long and the price moves against me, I just move on to the next opportunity and keep an eye on that stock if it really catches my attention.

The difference in my trading waiting on that 5EMA entry was a game changer. In options, if I rushed into a trade that gave me a buy signal before it came back to the 5EMA I might be down 50% within seconds before maybe recovering. However, if I wait on that 5 EMA entry I may never be down or at worst 15%-20% before becoming profitable.

To reiterate, the exit is on the CLOSE of the red candle. Sometimes it will turn red in the middle of the time period but then keep trending in the direction it was going and go back to blue, green, or whatever.-------(END OF OLD INSTRUCTIONS)

UiwzrgP.png


I added labels to the top of the chart for each criteria this strategy is looking for. This will help you "get ready" to buy. If they are all blue than get ready to go short or buy puts on that 5EMA. If they are all green than again, get ready to go long or buy calls on that 5EMA.

I THINK the labels should go green/blue from left to right if the stock cooperates. I have noticed that the biggest thing holding up the entry is MACD direction and price at the 5EMA at the same time but then again, that is what makes it mostly* dependable.

Once you are in the trade you can stop looking at the labels. At that point you are just waiting for the red candle or tk pft candle for your exit.

Ji6Y2d4.png


WIth that being said, be careful with options and this study! I chose my stocks based on my 2+ years of trading experience and look at support/resistance to chose the right strike. I am excited about this strategy because every single backtest I ran on every ticker on my watchlist was profitable over the past 10 days when trading 100 shares at a time.

Backtesting was done using a 5 EMA entry on the buy candles and a close price of the sell candles or better yet just below the high or just above the low when the tk pft candle appears depending on long or short.

Few Rules:
  • To be used on 10 minute charts. That is all I have tested it on.
  • Must have Extended Hours on and I prefer 10 Day / 10 Min zoomed in.
  • Copy the code and paste it as a STRATEGY not study.
  • If you so choose, turn on the "Over Ext Clouds". That is a take profit spot that I can't quite figure out how to code in and give it a unique bar color without screwing up the entire study. (help accepted)
  • Profit and Loss Labels are for the last long trade profit/loss and last short trade profit/loss if applicable.
  • And Finally, There are notes all over the place so just ignore those or use them to try to modify to your liking.

There is no scanner yet but some users are trying to create one that works (one or two are floating around the comments now). I use a flexible grid with 16 charts and load the tickers that I am looking at that particular day. This allows for the fastest response for me personally.

BDt0hOg.png


Code:
#JT Newest Strategy Based on EMAs, TSI, Premarket Highs/Lows, and MACD
#VERSION 9 - 04/27/2022

#Notes
#Changed the EMA Percent Sell Threshold from Buy Signal to 0.5 from 0.65
#Added a Parameter that CallBuyBubble must be a (CallBuy or CallHold) Candle or (PutBuy or PutHold) Candle. Basically it cannot be grey
#Changed !CallSell to !CallSellInd and !PutSell to !PutSellInd which fixed the sell candle not appearing
#Changed the EMA Percent Sell Threshold back to 0.65
#Added the ability to turn off EMA clouds. User still has to turn the plot off in the plots tab
#Added the ability for the user to change the EMA Percent Sell Threshold from default "EMAPctDecFromBuy"


Declare Upper;

##################################################################
#                                 TIMES                          #
##################################################################
#START AND END TIMES
input TimeFrame = {default "10-Min", "1-Min", "5-Min", "15-Min", "30-Min", "1-Hour"};
input PreMarketStart = 0700; #EST
input PreMarketEnd = 0929; #EST
input StartTime = 0930; #EST
input BuySignalDelay = 29;
input EndTime = 1600; #EST
input BuySignalStop = 60; #Minutes Before End of Day
def LastCandleStop; #Last Candle is Sell Candle

        switch (TimeFrame) {
        case "1-min": LastCandleStop = 1;
        case "5-Min": LastCandleStop = 5;
        case "15-Min": LastCandleStop = 15;
        case "30-Min": LastCandleStop = 30;
        case "1-Hour": LastCandleStop = 60;
        default: LastCandleStop = 10;
        }

def TradingDayStart= SecondsFromTime(StartTime);
def BuySignalDelaySeconds = BuySignalDelay * 60;
def SignalStart = TradingDayStart > BuySignalDelaySeconds;
def TradingDayEnd = SecondsTillTime(EndTime);
def EndSignalDelaySeconds = BuySignalStop * 60;
def SignalEnd = TradingDayEnd > EndSignalDelaySeconds;
def TradingDay = SignalStart and SignalEnd; #10:00EST - 1500EST
def LastStopDelaySeconds = LastCandleStop * 60;
def EndDay = TradingDayEnd == LastStopDelaySeconds; #1550EST
def TradingDayExt = TradingDayEnd > LastStopDelaySeconds;

##################################################################
#                              INDICATORS                        #
##################################################################
input ShowTestBubbles = no;

#EMAS
input Ema1Length = 5;
input Ema2Length = 12;
input Ema3Length = 34;
input Ema4Length = 50;
#input Ema5Length = 8; #If Needed
#input Ema6LEngth = 9; #If Needed

input ShowEMAClouds = yes;

plot FastEMA1 = ExpAverage(close, Ema1Length);
FastEMA1.SetDefaultColor(color.light_green);
FastEMA1.HideBubble();
plot FastEMA2 = ExpAverage(close, Ema2Length);
FastEMA2.SetDefaultColor(color.light_red);
FastEMA2.HideBubble();
AddCloud(if ShowEMAClouds then FastEMA1 else double.nan, if ShowEMAClouds then FastEMA2 else double.nan, createcolor(0, 255, 153), createcolor(0, 153, 255));
plot SlowEMA1 = ExpAverage(close, Ema3Length);
SlowEMA1.SetDefaultColor(color.light_green);
SlowEMA1.HideBubble();
plot SlowEMA2 = ExpAverage(close, Ema4Length);
SlowEMA2.SetDefaultColor(color.light_red);
SlowEMA2.HideBubble();
AddCloud(if ShowEMAClouds then SlowEMA1 else double.nan, if ShowEMAClouds then SlowEMA2 else double.nan, createcolor(0, 255, 0), createcolor(0, 0, 255));
#def FastEMA3 = ExpAverage(close, EMA5Length); #If Needed
#def FastEMA4 = ExpAverage(close, EMA6Length); #If Needed
#AddCloud(FastEMA3, FastEMA4, Color.light_gray, Color.light_gray); #If Needed

    #EMAS BULLISH OR BEARISH
    def FastEMABullish = FastEMA1 > FastEMA2;
    def SlowEMABullish = SlowEMA1 > SlowEMA2;
    def FastEMABearish = FastEMA1 < FastEMA2;
    def SlowEMABearish = SlowEMA1 < SlowEMA2;
    #EMA BUY SIGNAL
    def BothEMASBullish = FastEMABullish and SlowEMABullish;
    def BothEMASBearish = FastEMABearish and SlowEMABearish;

        #EMA PERCENT SEPERATION
        def FastEMAPctBull = ((FastEMA1 / FastEMA2) * 100) - 100; #Distance Between Fast EMA 1 and Fast EMA 2
        def FastEMAPctBullRound = Round(FastEMAPctBull, 2);
        def FastEMAPctBear = ((FastEMA2 / FastEMA1) * 100) - 100; #Distance Between Fast EMA 2 and Fast EMA 1
        def FastEMAPctBearRound = Round(FastEMAPctBear, 2);

        #FAST EMA PERCENT SEPERATION BUY SIGNAL
        def EMASepThrHld;
        switch (TimeFrame) {
        case "1-min": EMASepThrHld = 0.1;
        case "5-Min": EMASepThrHld = 0.2;
        case "15-Min": EMASepThrHld = 0.25;
        case "30-Min": EMASepThrHld = 0.3;
        case "1-Hour": EMASepThrHld = 0.3;
        default: EMASepThrHld = 0.25;
        }

        def FastEMAPctBullish = BothEMASBullish and FastEMAPctBullRound > EMASepThrHld and FastEMAPctBullRound >= FastEMAPctBullRound[1];
        def FastEMAPctBearish = BothEMASBearish and FastEMAPctBearRound > EMASepThrHld and FastEMAPctBearRound >= FastEMAPctBearRound[1];
        #TESTING
        addchartbubble(if ShowTestBubbles and FastEMAPctBullish == 1 then 1 else 0, SlowEMA2*0.995, FastEMAPctBullRound, color.dark_green, no);
        addchartbubble(if ShowTestBubbles and FastEMAPctBearish == 1 then 1 else 0, SlowEMA2*1.005, FastEMAPctBearRound, color.dark_green, yes);

        def SlowEMAPctBull = ((SlowEMA1 / SlowEMA2) * 100) - 100; #Distance Between Slow EMA 1 and Slow EMA 2
        def SlowEMAPctBullRound = Round(SlowEMAPctBull, 2);
        def SlowEMAPctBear = ((SlowEMA2 / SlowEMA1) * 100) - 100; #Distance Between Slow EMA 1 and Slow EMA 2
        def SlowEMAPctBearRound = Round(SlowEMAPctBear, 2);

        #SLOW EMA PERCENT SEPERATION BULLISH
        def SlowEMAPctBullish = BothEMASBullish and SlowEMAPctBullRound >= SlowEMAPctBullRound[1];
        def SlowEMAPctBearish = BothEMASBearish and SlowEMAPctBearRound <= SlowEMAPctBearRound[1];

            #EMA SELL SIGNALS
            def FastEMACrossDown = FastEMA1 crosses below FastEMA2;
            def FastEMACrossUp = FastEMA1 crosses above FastEMA2;
            def FastEMAPctBullDecrease = if BothEMASBullish and FastEMAPctBullRound < (FastEMAPctBullRound[1] * 0.75) then 1 else 0;
            def FastEMAPctBearDecrease = if BothEMASBearish and FastEMAPctBearRound < (FastEMAPctBearRound[1] * 0.75) then 1 else 0;
            #TESTING
            addchartbubble(if ShowTestBubbles and FastEMAPctBullDecrease == 1 then 1 else 0, SlowEMA2*0.995, FastEMAPctBullRound, color.dark_red, no);
            addchartbubble(if ShowTestBubbles and FastEMAPctBearDecrease == 1 then 1 else 0, SlowEMA2*1.005, FastEMAPctBearRound, color.dark_red, yes);

                #SLOWEMA2 SLOPE (NOT USING AT THIS TIME)
                def Height = SlowEMA2 - SlowEMA2[11];
                def SlopeDeg = Round((ATan(Height / 10) * 180 / Double.Pi), 0);
                #SLOWEMA2 SLOPE SELL SIGNAL
                def BullSlopeSell = BothEMASBullish and SlopeDeg < SlopeDeg[1];
                def BearSlopeSell = BothEMASBearish and SlopeDeg > SlopeDeg[1];
                #TESTING
                #addchartbubble(if ShowTestBubbles and BullSlopeSell == 1 then 1 else 0, SlowEMA2*0.995, "Slope", color.dark_red, no);
                #addchartbubble(if ShowTestBubbles and BearSlopeSell == 1 then 1 else 0, SlowEMA2*1.005, "Slope", color.dark_red, yes);

#MACD
input MACDFast = 10;
input MACDSlow = 22;
input MACDLength = 8;

def MACDValue = ExpAverage(close, MACDFast) - ExpAverage(close, MACDSlow);
def MACDAverage = ExpAverage(MACDValue, MACDLength);
def MACDDiff = MACDValue - MACDAverage;
def ZeroLine = 0;

    #MACD BUY SIGNAL
    def MACDBull = MACDDiff >= MACDDiff[1];
    def MACDBear = MACDDiff <= MACDDiff[1];

        #MACD SELL SIGNAL
        #No Sell SIgnals At This Time

#TSI
input TSILongLength = 25;
input TSIShortLength = 13;
input TSISignalLength = 8;

def TSIDiff = close - close[1];
def DoubleSmoothedAbsDiff = ExpAverage(ExpAverage(AbsValue(TSIDiff), TSILongLength), TSIShortLength);
def TSIRound = Round((100 * (ExpAverage(ExpAverage(TSIDiff, TSILongLength), TSIShortLength)) / DoubleSmoothedAbsDiff), 2);

    #TSI BUY SIGNAL
    def TSIBull = (TSIRound > 10) and (TSIRound >= TSIRound[1]);
    def TSIBear = (TSIRound < -10) and (TSIRound <= TSIRound[1]);

        #TSI SELL SIGNAL
        def TSICrossDown = TSIRound < (TSIRound[1] * 0.91);
        def TSICrossUp = TSIRound > (TSIRound[1] * 0.91);

        #TSI TAKE PROFIT
        #No TSI Take Profit At This Time

#PREMARKET HIGHS AND LOWS
input ShowPreMarketCloud = yes;
input ShowPreMarketLabel = yes;

def PreMarketTimeRange = secondsFromTime(PreMarketStart) >= 0 and secondsTillTime(PreMarketEnd) >= 0;
def PreMarket = PreMarketTimeRange and !PremarketTimeRange[1];
def Pre_Market_High = compoundValue(1, if((high > Pre_Market_High[1] and PremarketTimeRange) or PreMarket, high, Pre_Market_High[1]), high);
def Pre_Market_Low = compoundValue(1, if((low < Pre_Market_Low[1] and PremarketTImeRange) or PreMarket, low, Pre_Market_Low[1]), low);

plot PreMarketHigh = if ShowPreMarketCloud then Pre_Market_High else double.nan;
PreMarketHigh.SetStyle(curve.short_dash);
PreMarketHigh.SetDefaultColor(color.light_gray);
PreMarketHigh.setLineWeight(1);
plot PreMarketLow = if ShowPreMarketCloud then Pre_Market_Low else double.nan;
PreMarketLow.SetStyle(curve.short_dash);
PreMarketLow.SetDefaultColor(color.light_gray);
PreMarketLow.setLineWeight(1);
AddCloud (PreMarketHigh, PreMarketLow, color.light_gray, color.light_gray);

AddLabel(if ShowPreMarketLabel then yes else no, "     ", color.black);
AddLabel(if ShowPreMarketLabel then yes else no, " PM High - $" + PreMarketHigh, color.gray);
AddLabel(if ShowPreMArketLabel then yes else no, " PM Low - $" + PreMarketLow, color.gray);

    #PREMARKET HIGH/LOW BUY SIGNAL
    def PreMarketBull = low > Pre_Market_High;
    def PreMarketBear = high < Pre_Market_Low;
    #TESTING
    addchartbubble(if ShowTestBubbles and PreMarketBull == 1 then 1 else 0, SlowEMA2*0.995, "Pre", color.dark_green, no);
    addchartbubble(if ShowTestBubbles and PreMarketBear == 1 then 1 else 0, SlowEMA2*1.005, "Pre", color.dark_green, yes);

        #PREMARKET HIGH/LOW SELL SIGNAL
        def PreMarketBullSell = PreMarketBull[1] and low < Pre_Market_High;
        def PreMarketBearSell = PreMarketBear[1] and high > Pre_Market_Low;
        #TESTING
        addchartbubble(if ShowTestBubbles and PreMarketBullSell == 1 then 1 else 0, SlowEMA2*0.995, "Pre", color.dark_red, no);
        addchartbubble(if ShowTestBubbles and PreMarketBearSell == 1 then 1 else 0, SlowEMA2*1.005, "Pre", color.dark_red, yes);

##################################################################
#                               SIGNALS                          #
##################################################################
#GET READY
def GetReadyBull = TradingDay and BothEMASBullish and PreMarketBull;
def GetReadyBear = TradingDay and BothEMASBearish and PreMarketBear;

#INDICATOR BUY SIGNALS
def CallBuyInd = BothEMASBullish and FastEMAPctBullish and MACDBull and TSIBull and PreMarketBull;
def PutBuyInd = BothEMASBearish and FastEMAPctBearish and MACDBear and TSIBear and PreMarketBear;
#TESTING
addchartbubble(if ShowTestBubbles and CallBuyInd == 1 then 1 else 0, SlowEMA2*0.995, "C-Ind", color.light_green, no);
addchartbubble(if ShowTestBubbles and PutBuyInd == 1 then 1 else 0, SlowEMA2*1.005, "P-Ind", color.light_green, yes);

##################################################################
#         ADDED FAST EMA PCT HERE BASED OFF BUY SIGNAL           #
##################################################################
            def EMAPctAtCallBuy = if CallBuyInd then FastEMAPctBullRound else EMAPctAtCallBuy[1]; #Used to Calculate Sell Trigger
            def EMAPctAtPutBuy = if PutBuyInd then FastEMAPctBearRound else EMAPctAtPutBuy[1]; #Used to Calculate Sell Trigger

                #FAST EMA CLOUD SELL TRIGGER BASED OFF BUY INDICATOR
                input EMAPctDecFromBuy = 0.65;
                def CallEMAPctSell = FastEMAPctBullRound < (EMAPctAtCallBuy * EMAPctDecFromBuy);
                addchartbubble(ShowTestBubbles and EMAPctAtCallBuy, SlowEMA2*1.005, "CB-Pct" + EMAPctAtCallBuy, color.green, yes);
                addchartbubble(ShowTestBubbles and CallEMAPctSell, SlowEMA2*1.005, "CS-Pct" + FastEMAPctBullRound, color.red, yes);
                def PutEMAPctSell = FastEMAPctBearRound < (EMAPctAtPutBuy * EMAPctDecFromBuy);
                addchartbubble(ShowTestBubbles and EMAPctAtPutBuy, SlowEMA2*0.995, "PB-Pct" + EMAPctAtPutBuy, color.green, no);
                addchartbubble(ShowTestBubbles and PutEMAPctSell, SlowEMA2*0.995, "PS-Pct" + FastEMAPctBearRound, color.red, no);

##################################################################
#                         SIGNALS CONT.                          #
##################################################################
#INDICATOR HOLD SIGNALS
def CallHoldInd = BothEMASBullish and PreMarketBull;
def PutHoldInd = BothEMASBearish and PreMarketBear;
#TESTING
addchartbubble(if ShowTestBubbles and CallHoldInd == 1 then 1 else 0, SlowEMA2*0.995, "CH_Ind", color.light_green, no);
addchartbubble(if ShowTestBubbles and PutHoldInd == 1 then 1 else 0, SlowEMA2*1.005, "PH-Ind", color.light_green, yes);

##################################################################
# EMA TAKE PROFIT CLOUD (IDENTIFY IF PRICE IS EXTENDED FROM EMAS)#
##################################################################
            input ShowOverExtCloud = yes;

            def OvrExtUp1 = if ShowOverExtCloud and SignalStart and TradingDayExt and (CallBuyInd or CallHoldInd) then FastEMA1 * 1.01 else Double.NaN;
            #addchartbubble(if High > OvrExtUp1 == 1 then 1 else 0, OvrExtUp1*1.005, "TkPft1", color.light_green, yes);
            def OvrExtUp2 = if ShowOverExtCloud and SignalStart and TradingDayExt and (CallBuyInd or CallHoldInd) then FastEMA1 * 1.02 else Double.NaN;
            #addchartbubble(if High > OvrExtUp2 == 1 then 1 else 0, OvrExtUp2*1.005, "TkPft2", color.light_green, yes);
            AddCloud(OvrExtUp1, OvrExtUp2, color.light_green, color.light_green);
            def OvrExtDn1 = if ShowOverExtCloud and SignalStart and TradingDayExt and (PutBuyInd or PutHoldInd) then FastEMA1 * 0.99 else Double.NaN;
            #addchartbubble(if Low < OvrExtDn1 == 1 then 1 else 0, OvrExtDn1*0.995, "TkPft1", color.light_green, no);
            def OvrExtDn2 = if ShowOverExtCloud and SignalStart and TradingDayExt and (PutBuyInd or PutHoldInd) then FastEMA1 * 0.98 else Double.NaN;
            #addchartbubble(if Low < OvrExtDn2 == 1 then 1 else 0, OvrExtDn2*0.995, "TkPft2", color.light_green, no);
            AddCloud(OvrExtDn1, OvrExtDn2, color.light_green, color.light_green);

##################################################################
#                         SIGNALS CONT.                          #
##################################################################
#INDICATOR SELL SIGNALS
def CallSellInd = FastEMACrossDown or TSICrossDown or CallEMAPctSell;
def PutSellInd = FastEMACrossUp or TSICrossUp or PutEMAPctSell;
#TESTING
addchartbubble(if ShowTestBubbles and CallSellInd == 1 then 1 else 0, SlowEMA2*0.995, "CS-Ind", color.light_red, no);
addchartbubble(if ShowTestBubbles and PutSellInd == 1 then 1 else 0, SlowEMA2*1.005, "PS-Ind", color.light_red, yes);

    #BUY SIGNALS
    def CallBuy = TradingDay and CallBuyInd;
    def PutBuy = TradingDay and PutBuyInd;
    #TESTING
    addchartbubble(if ShowTestBubbles and CallBuy == 1 then 1 else 0, SlowEMA2*0.995, "Call", color.green, no);
    addchartbubble(if ShowTestBubbles and PutBuy == 1 then 1 else 0, SlowEMA2*1.005, "Put", color.green, yes);

    #HOLD SIGNALS
    def CallHold = TradingDayExt and CallHoldInd and (CallBuy[1] or CallHold[1]);
    def PutHold = TradingDayExt and PutHoldInd and (PutBuy[1] or PutHold[1]);
    #TESTING
    addchartbubble(if ShowTestBubbles and CallHold == 1 then 1 else 0, SlowEMA2*0.995, "C-Hold", color.green, no);
    addchartbubble(if ShowTestBubbles and PutHold == 1 then 1 else 0, SlowEMA2*1.005, "P-Hold", color.green, yes);

    #SELL SIGNALS
    def CallSell = TradingDayExt and CallSellInd and !CallSellInd[1]; #and (CallBuy[1] or CallHold[1])
    def PutSell = TradingDayExt and PutSellInd and !PutSellInd[1]; #and (PutBuy[1] or PutHold[1])
    #TESTING
    addchartbubble(if ShowTestBubbles and CallSell == 1 then 1 else 0, SlowEMA2*0.995, "C-Sell", color.red, no);
    addchartbubble(if ShowTestBubbles and PutSell == 1 then 1 else 0, SlowEMA2*1.005, "P-Sell", color.red, yes);

##################################################################
#                                 BARS                           #
##################################################################
DefineGlobalColor("OpenLongPosition", createcolor (0, 255, 0));
DefineGlobalColor("OpenShortPosition", createcolor (0, 0, 255));
DefineGlobalColor("HoldLongPosition", createcolor (204, 255, 204));
DefineGlobalColor("HoldShortPosition", createcolor (102, 255, 255));
DefineGlobalColor("GetReady", createcolor (204, 153, 0));
DefineGlobalColor("SellPosition", createcolor (255, 0, 0));
DefineGlobalColor("TakeProfit", createcolor (255, 0, 255));
DefineGlobalColor("CriteriaNotMet", createcolor (102, 102, 102));

#COLOR BARS
AssignPriceColor(if CallSell then GlobalColor("SellPosition") else if CallBuy then GlobalColor("OpenLongPosition") else if CallHold then GlobalColor("HoldLongPosition") else if PutSell then GlobalColor("SellPosition") else if PutBuy then GlobalColor("OpenShortPosition") else if PutHold then GlobalColor("HoldShortPosition") else if EndDay then GlobalColor("SellPosition") else if GetReadyBull then GlobalColor("GetReady") else if GetReadyBear then GlobalColor("GetReady") else GlobalColor("CriteriaNotMet"));

##################################################################
#                                LABELS                          #
##################################################################
#LABELS
AddLabel(yes, "     ", color.black);
AddLabel(yes, "PREMKT", if PreMarketBull then GlobalColor("OpenLongPosition") else if PreMarketBear then GlobalColor("OpenShortPosition") else color.gray);
AddLabel(yes, "CLOUDS", if BothEMASBullish then GlobalColor("OpenLongPosition") else if BothEMASBearish then GlobalColor("OpenShortPosition") else color.gray);
AddLabel(yes, "EMA SEP", if FastEMAPctBullish then GlobalColor("OpenLongPosition") else if FastEMAPctBearish then GlobalColor("OpenShortPosition") else color.gray);
AddLabel(yes, "TSI", if TSIBull then GlobalColor("OpenLongPosition") else if TSIBear then GlobalColor("OpenShortPosition") else color.gray);
AddLabel(yes, "MACD", if MACDBull then GlobalColor("OpenLongPosition") else if MACDBear then GlobalColor("OpenShortPosition") else color.gray);

##################################################################
#                  CHART BUBBLES FOR BUY/SELL                    #
##################################################################
input ShowBuySellBubbles = Yes;
input ShowTkPftBubble = Yes;

#BUY
def CallBuyBub = TradingDay and !CallSellInd and (CallBuy or CallHold) and (CallBuy or CallBuy[1] or CallBuy[2] or CallBuy[3]) and low <= FastEMA1 and low >= FastEMA2;
addchartbubble(ShowBuySellBubbles and CallBuybub, low * 0.999, "Long", GlobalColor("OpenLongPosition"), no);
def PutBuyBub = TradingDay and !PutSellInd and (PutBuy or PutHold) and (PutBuy or PutBuy[1] or PutBuy[2] or PutBuy[3]) and high >= FastEMA1 and high <=FastEMA2;
addchartbubble(ShowBuySellBubbles and PutBuyBub, high * 1.001, "Short", GlobalColor("OpenShortPosition"), yes);

#SELL
def CallSellBub = TradingDayExt and CallSell; #and (CallBuy[1] or CallHold[1])
addchartbubble(ShowBuySellBubbles and CallSellBub, low * 0.999, "Sell", GlobalColor("SellPosition"), no);
def PutSellBub = TradingDayExt and PutSell; #and (PutBuy[1] or PutHold[1])
addchartbubble(ShowBuySellBubbles and PutSellBub, high * 1.001, "Sell", GlobalColor("SellPosition"), yes);

#TAKE PROFIT
def TkPftBubCall = TradingDayExt and (CallBuyInd or CallHoldInd) and high > FastEMA1 * 1.01;
addchartbubble(ShowTkPftBubble and TkPftBubCall, high * 1.001, "Tk Pft", GlobalColor("TakeProfit"), yes);
def TkPftBubPut = TradingDayExt and (PutBuyInd or PutHoldInd) and low < FastEMA1 * 0.99;
addchartbubble(ShowTkPftBubble and TkPftBubPut, low * 0.999, "Tk Pft", GlobalColor("TakeProfit"), no);

##################################################################
#                                ORDERS                          #
##################################################################
#ORDERS
input ShowOrders = no;

#OLD BUY ORDERS
#AddOrder(OrderType.BUY_TO_OPEN, ShowOrders and (CallBuy or CallBuy[1] or CallBuy[2] or CallBuy[3]) and low <= FastEMA1 and low >= FastEMA2, FastEMA1, 100, Color.GREEN, Color.LIGHT_GREEN);
#AddOrder(OrderType.SELL_TO_OPEN, ShowOrders and (PutBuy or PutBuy[1] or PutBuy[2] or PutBuy[3]) and high >= FastEMA1 and high <=FastEMA2, FastEMA1, 100, Color.GREEN, Color.LIGHT_GREEN);

#BUY ORDERS
AddOrder(OrderType.BUY_TO_OPEN, ShowOrders and CallBuyBub, FastEMA1, 100, Color.GREEN, Color.LIGHT_GREEN);
AddOrder(OrderType.SELL_TO_OPEN, ShowOrders and PutBuyBub, FastEMA1, 100, Color.GREEN, Color.LIGHT_GREEN);

#SELL ORDERS
AddOrder(OrderType.SELL_TO_CLOSE, ShowOrders and TkPftBubCall, high * 0.999, 100, Color.RED, Color.LIGHT_RED);
AddOrder(OrderType.SELL_TO_CLOSE, ShowOrders and (CallSellBub or EndDay[-1]), close, 100, Color.RED, Color.LIGHT_RED);
AddOrder(OrderType.BUY_TO_CLOSE, ShowOrders and TkPftBubPut, low * 1.001, 100, Color.RED, Color.LIGHT_RED);
AddOrder(OrderType.BUY_TO_CLOSE, ShowOrders and (PutSellBub or EndDay[-1]), close, 100, Color.RED, Color.LIGHT_RED);

##################################################################
#                                ALERTS                          #
##################################################################
#ALERTS
input AlertOn = yes;

Alert(AlertOn and (CallSellBub or PutSellBub or TkPftBubCall or TkPftBubPut), "SELL", Alert.BAR, Sound.Bell);
Alert(AlertOn and (CallBuyBub or PutBuyBub), "BUY", Alert.BAR, Sound.Chimes);

##################################################################
#                        PROFIT/LOSS LABEL                       #
##################################################################
input ShowPLLabel = Yes;

#CALL
AddLabel(if ShowPLLabel then yes else no, "     ", color.black);
def CallOpen = if CallBuy and !CallHold then FastEMA1 else CallOpen[1];
def CallEnd = if TkPftBubCall then high * 0.999 else if CallSellBub then close else CallEnd[1];
def CallOpenCost = CallOpen * 100;
def CallCloseCost = CallEnd * 100;
def CallDiff = round(CallCloseCost - CallOpenCost, 2);
AddLabel(if ShowPLLabel then yes else no, "Long Trade P/L - $ " + CallDiff + " ", if CallDiff > 0 then color.light_green else if CallDiff < 0 then color.light_red else color.gray);

#PUT
def PutOpen = if PutBuy and !PutHold then FastEMA1 else PutOpen[1];
def PutEnd = if TkPftBubPut then low * 1.001 else if PutSellBub then close else PutEnd[1];
def PutOpenCost = PutOpen * 100;
def PutCloseCost = PutEnd * 100;
def PutDiff = round(PutOpenCost - PutCloseCost, 2);
AddLabel(if ShowPLLabel then yes else no, "Short Trade P/L - $ " + PutDiff + " ", if PutDiff > 0 then color.light_green else if PutDiff < 0 then color.light_red else color.gray);

##################################################################
#                       CANDLE COLOR LABEL                       #
##################################################################
#LABELS
input ShowColorDefLabels = yes;

AddLabel(if ShowColorDefLabels == 1 then yes else no, "     ", color.black);
AddLabel(if ShowColorDefLabels == 1 then yes else no, "Long Ind", GlobalColor("OpenLongPosition"));
AddLabel(if ShowColorDefLabels == 1 then yes else no, "Long Hld", GlobalColor("HoldLongPosition"));
AddLabel(if ShowColorDefLabels == 1 then yes else no, "Short Ind", GlobalColor("OpenShortPosition"));
AddLabel(if ShowColorDefLabels == 1 then yes else no, "Short Hld", GlobalColor("HoldShortPosition"));
AddLabel(if ShowColorDefLabels == 1 then yes else no, "Get Ready", GlobalColor("GetReady"));
AddLabel(if ShowColorDefLabels == 1 then yes else no, "Sell", GlobalColor("SellPosition"));
AddLabel(if ShowColorDefLabels == 1 then yes else no, "Tk Pft", GlobalColor("TakeProfit"));
AddLabel(if ShowColorDefLabels == 1 then yes else no, "No Criteria", GlobalColor("CriteriaNotMet"));

##################################################################
#                BACKGROUND COLOR FOR FLEX GRID                  #
##################################################################
#BACKGROUND
input ShowFlexGridBackgroundColor = no;

AssignBackgroundColor(if ShowFlexGridBackgroundColor and (CallSellBub or PutSellBub) then GlobalColor("SellPosition") else if ShowFlexGridBackgroundColor and CallBuyBub then GlobalColor("OpenLongPosition") else if ShowFlexGridBackgroundColor and PutBuyBub then GlobalColor("OpenShortPosition") else if ShowFlexGridBackgroundColor and (TkPftBubCall or TkPftBubPut) then GlobalColor("TakeProfit") else color.current);

chotPBc.png


- And last but not least, my watchlist indicator. I only use this to visually tell me when to take a closer look at a stock. I have whittled down my watchlist to ones that I know move and have plenty of options flow. Make sure your watchlist study is set to 10 Min and Extended Hours are turned On.

The numbers mean nothing. It is just my way of sorting. You can change the labels to whatever you want in the bottom of the code under “Label”

You will only get a signal on the chart and the watchlist between 9:00 A.M. CST and 3:30 P.M. CST.

Code:
#JT Newest Strategy Based on EMAs, TSI, Premarket Highs/Lows, and MACD
#VERSION 9 - 04/28/2022
#WATCHLIST INDICATOR

##################################################################
#                                 TIMES                          #
##################################################################
#START AND END TIMES
def PreMarketStart = 0700;
def PreMarketEnd = 0929;
def StartTime = 0930;
def BuySignalDelay = 29;
def EndTime = 1600;
def BuySignalStop = 60;
def LastCandleStop = 10;

def TradingDayStart= SecondsFromTime(StartTime);
def BuySignalDelaySeconds = BuySignalDelay * 60;
def SignalStart = TradingDayStart > BuySignalDelaySeconds;
def TradingDayEnd = SecondsTillTime(EndTime);
def EndSignalDelaySeconds = BuySignalStop * 60;
def SignalEnd = TradingDayEnd > EndSignalDelaySeconds;
def TradingDay = SignalStart and SignalEnd;
def LastStopDelaySeconds = LastCandleStop * 60;
def EndDay = TradingDayEnd == LastStopDelaySeconds;
def TradingDayExt = TradingDayEnd > LastStopDelaySeconds;

##################################################################
#                              INDICATORS                        #
##################################################################
#EMAS
def Ema1Length = 5;
def Ema2Length = 12;
def Ema3Length = 34;
def Ema4Length = 50;

def FastEMA1 = ExpAverage(close, Ema1Length);
def FastEMA2 = ExpAverage(close, Ema2Length);
def SlowEMA1 = ExpAverage(close, Ema3Length);
def SlowEMA2 = ExpAverage(close, Ema4Length);

    #EMAS BULLISH OR BEARISH
    def FastEMABullish = FastEMA1 > FastEMA2;
    def SlowEMABullish = SlowEMA1 > SlowEMA2;
    def FastEMABearish = FastEMA1 < FastEMA2;
    def SlowEMABearish = SlowEMA1 < SlowEMA2;
    #EMA BUY SIGNAL
    def BothEMASBullish = FastEMABullish and SlowEMABullish;
    def BothEMASBearish = FastEMABearish and SlowEMABearish;

        #EMA PERCENT SEPERATION
        def FastEMAPctBull = ((FastEMA1 / FastEMA2) * 100) - 100;
        def FastEMAPctBullRound = Round(FastEMAPctBull, 2);
        def FastEMAPctBear = ((FastEMA2 / FastEMA1) * 100) - 100;
        def FastEMAPctBearRound = Round(FastEMAPctBear, 2);

        def FastEMAPctBullish = BothEMASBullish and FastEMAPctBullRound > 0.25 and FastEMAPctBullRound >= FastEMAPctBullRound[1];
        def FastEMAPctBearish = BothEMASBearish and FastEMAPctBearRound > 0.25 and FastEMAPctBearRound >= FastEMAPctBearRound[1];
      
        def SlowEMAPctBull = ((SlowEMA1 / SlowEMA2) * 100) - 100;
        def SlowEMAPctBullRound = Round(SlowEMAPctBull, 2);
        def SlowEMAPctBear = ((SlowEMA2 / SlowEMA1) * 100) - 100;
        def SlowEMAPctBearRound = Round(SlowEMAPctBear, 2);

        #SLOW EMA PERCENT SEPERATION BULLISH
        def SlowEMAPctBullish = BothEMASBullish and SlowEMAPctBullRound >= SlowEMAPctBullRound[1];
        def SlowEMAPctBearish = BothEMASBearish and SlowEMAPctBearRound <= SlowEMAPctBearRound[1];

            #EMA SELL SIGNALS
            def FastEMACrossDown = FastEMA1 crosses below FastEMA2;
            def FastEMACrossUp = FastEMA1 crosses above FastEMA2;
            def FastEMAPctBullDecrease = if BothEMASBullish and FastEMAPctBullRound < (FastEMAPctBullRound[1] * 0.75) then 1 else 0;
            def FastEMAPctBearDecrease = if BothEMASBearish and FastEMAPctBearRound < (FastEMAPctBearRound[1] * 0.75) then 1 else 0;
        
                #SLOWEMA2 SLOPE (NOT USING AT THIS TIME)
                def Height = SlowEMA2 - SlowEMA2[11];
                def SlopeDeg = Round((ATan(Height / 10) * 180 / Double.Pi), 0);
                #SLOWEMA2 SLOPE SELL SIGNAL
                def BullSlopeSell = BothEMASBullish and SlopeDeg < SlopeDeg[1];
                def BearSlopeSell = BothEMASBearish and SlopeDeg > SlopeDeg[1];
              
#MACD
input MACDFast = 10;
input MACDSlow = 22;
input MACDLength = 8;

def MACDValue = ExpAverage(close, MACDFast) - ExpAverage(close, MACDSlow);
def MACDAverage = ExpAverage(MACDValue, MACDLength);
def MACDDiff = MACDValue - MACDAverage;
def ZeroLine = 0;

    #MACD BUY SIGNAL
    def MACDBull = MACDDiff >= MACDDiff[1];
    def MACDBear = MACDDiff <= MACDDiff[1];

#TSI
input TSILongLength = 25;
input TSIShortLength = 13;
input TSISignalLength = 8;

def TSIDiff = close - close[1];
def DoubleSmoothedAbsDiff = ExpAverage(ExpAverage(AbsValue(TSIDiff), TSILongLength), TSIShortLength);
def TSIRound = Round((100 * (ExpAverage(ExpAverage(TSIDiff, TSILongLength), TSIShortLength)) / DoubleSmoothedAbsDiff), 2);

    #TSI BUY SIGNAL
    def TSIBull = (TSIRound > 10) and (TSIRound >= TSIRound[1]);
    def TSIBear = (TSIRound < -10) and (TSIRound <= TSIRound[1]);

        #TSI SELL SIGNAL
        def TSICrossDown = TSIRound < (TSIRound[1] * 0.91);
        def TSICrossUp = TSIRound > (TSIRound[1] * 0.91);

##################################################################
#                          PREMARKET                             #
##################################################################
#PREMARKET HIGHS AND LOWS

def PreMarketTimeRange = secondsFromTime(PreMarketStart) >= 0 and secondsTillTime(PreMarketEnd) >= 0;
def PreMarket = PreMarketTimeRange and !PremarketTimeRange[1];
def Pre_Market_High = compoundValue(1, if((high > Pre_Market_High[1] and PremarketTimeRange) or PreMarket, high, Pre_Market_High[1]), high);
def Pre_Market_Low = compoundValue(1, if((low < Pre_Market_Low[1] and PremarketTImeRange) or PreMarket, low, Pre_Market_Low[1]), low);

def PreMarketHigh = Pre_Market_High;
def PreMarketLow = Pre_Market_Low;

    #PREMARKET HIGH/LOW BUY SIGNAL
    def PreMarketBull = low > Pre_Market_High;
    def PreMarketBear = high < Pre_Market_Low;
 
        #PREMARKET HIGH/LOW SELL SIGNAL
        def PreMarketBullSell = PreMarketBull[1] and low < Pre_Market_High;
        def PreMarketBearSell = PreMarketBear[1] and high > Pre_Market_Low;

##################################################################
#                               SIGNALS                          #
##################################################################
#GET READY
def GetReadyBull = TradingDay and BothEMASBullish and PreMarketBull;
def GetReadyBear = TradingDay and BothEMASBearish and PreMarketBear;

#INDICATOR BUY SIGNALS
def CallBuyInd = BothEMASBullish and FastEMAPctBullish and MACDBull and TSIBull and PreMarketBull;
def PutBuyInd = BothEMASBearish and FastEMAPctBearish and MACDBear and TSIBear and PreMarketBear;

##################################################################
#         ADDED FAST EMA PCT HERE BASED OFF BUY SIGNAL           #
##################################################################
            def EMAPctAtCallBuy = if CallBuyInd then FastEMAPctBullRound else EMAPctAtCallBuy[1]; #Used to Calculate Sell Trigger
            def EMAPctAtPutBuy = if PutBuyInd then FastEMAPctBearRound else EMAPctAtPutBuy[1]; #Used to Calculate Sell Trigger

                #FAST EMA CLOUD SELL TRIGGER BASED OFF BUY INDICATOR
                def CallEMAPctSell = FastEMAPctBullRound < (EMAPctAtCallBuy * 0.65);
                def PutEMAPctSell = FastEMAPctBearRound < (EMAPctAtPutBuy * 0.65);
               
##################################################################
#                         SIGNALS CONT.                          #
##################################################################
#INDICATOR HOLD SIGNALS
def CallHoldInd = BothEMASBullish and PreMarketBull;
def PutHoldInd = BothEMASBearish and PreMarketBear;

##################################################################
# EMA TAKE PROFIT CLOUD (IDENTIFY IF PRICE IS EXTENDED FROM EMAS)#
##################################################################
            def OvrExtUp1 = if SignalStart and TradingDayExt and (CallBuyInd or CallHoldInd) then FastEMA1 * 1.01 else Double.NaN;
            def OvrExtUp2 = if SignalStart and TradingDayExt and (CallBuyInd or CallHoldInd) then FastEMA1 * 1.02 else Double.NaN;

            def OvrExtDn1 = if SignalStart and TradingDayExt and (PutBuyInd or PutHoldInd) then FastEMA1 * 0.99 else Double.NaN;
            def OvrExtDn2 = if SignalStart and TradingDayExt and (PutBuyInd or PutHoldInd) then FastEMA1 * 0.98 else Double.NaN;

##################################################################
#                         SIGNALS CONT.                          #
##################################################################
#INDICATOR SELL SIGNALS
def CallSellInd = FastEMACrossDown or TSICrossDown or CallEMAPctSell;
def PutSellInd = FastEMACrossUp or TSICrossUp or PutEMAPctSell;

    #BUY SIGNALS
    def CallBuy = TradingDay and CallBuyInd;
    def PutBuy = TradingDay and PutBuyInd;

    #HOLD SIGNALS
    def CallHold = TradingDayExt and CallHoldInd and (CallBuy[1] or CallHold[1]);
    def PutHold = TradingDayExt and PutHoldInd and (PutBuy[1] or PutHold[1]);

    #SELL SIGNALS
    def CallSell = TradingDayExt and CallSellInd and !CallSellInd[1];
    def PutSell = TradingDayExt and PutSellInd and !PutSellInd[1];

##################################################################
#                  CHART BUBBLES FOR BUY/SELL                    #
##################################################################

#BUY
#def CallBuyBub = TradingDay and !CallSellInd and (CallBuy or CallHold) and (CallBuy or CallBuy[1] or CallBuy[2] or CallBuy[3]) and low <= FastEMA1 and low >= FastEMA2;
#def PutBuyBub = TradingDay and !PutSellInd and (PutBuy or PutHold) and (PutBuy or PutBuy[1] or PutBuy[2] or PutBuy[3]) and high >= FastEMA1 and high <=FastEMA2;

#SELL
#def CallSellBub = TradingDayExt and CallSell; #and (CallBuy[1] or CallHold[1])
#def PutSellBub = TradingDayExt and PutSell; #and (PutBuy[1] or PutHold[1])

#TAKE PROFIT
def TkPftBubCall = TradingDayExt and (CallBuyInd or CallHoldInd) and high > FastEMA1 * 1.01;
def TkPftBubPut = TradingDayExt and (PutBuyInd or PutHoldInd) and low < FastEMA1 * 0.99;

##################################################################
#                        WATCHLIST INDICATOR                     #
##################################################################

#LABEL
AddLabel(yes, if CallSell or PutSell or EndDay then "4. SELL" else if CallBuy then "1 CALL BUY" else if CallHold then "5. CALL HOLD" else if PutBuy then "2. PUT BUY" else if PutHold then "6. PUT HOLD" else if GetReadyBull or GetReadyBear then "7. GET READY" else if TkPftBubCall or TkPftBubPut then "3. TAKE PROFIT" else "8. NO GO");

#BACKGROUND
AssignBackgroundColor(if CallSell or PutSell or EndDay then createcolor (255, 0, 0) else if CallBuy then createcolor (0, 255, 0) else if CallHold then createcolor (204, 255, 204) else if PutBuy then createcolor (0, 0, 255) else if PutHold then createcolor (102, 255, 255) else if GetReadyBull or GetReadyBear then createcolor (204, 153, 0) else if TkPftBubCall or TkPftBubPut then createcolor (255, 0, 255) else createcolor (102, 102, 102));

What can go wrong....?

If you see this buy signal (1.) and then the price get so extended from the EMAs (circle) that is a red flag for me. It is almost certainly going to drop right back to where it was (2.) and then possibly continue lower (3.) I think this is what the market makers do to trap the longs and people who have FOMO. Don't buy at (2.) if the price action looks like that prior. Just wait for a better opportunity.

I didn't just pull that over extended cloud out of nowhere. That was me looking at multiple charts and coming up with the best number (probably has something to do with other algos).

To the right is what it's supposed to look like.

Em5Im29.png


Some light backtesting here. This is over 90 days and BEFORE I backtested with the tk pft bubbles.

3ntuPXd.png


If you happen to have something of value to add please don't hesitate to post that here. This is however about 6 months of trial and error in the making.
thanks for sharing this. Fantastic results. Is there way to use $ value for backtesting with thinkorswim instead of 100 or any other number contracts? I see this is not a real comparison if one ticker is 100$ and another is 10$.
 
thanks for sharing this. Fantastic results. Is there way to use $ value for backtesting with thinkorswim instead of 100 or any other number contracts? I see this is not a real comparison if one ticker is 100$ and another is 10$.
I'm not sure. I just use the backtesting to see if the strategy is profitable or not.
 

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
330 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