# Color Bars when Buy Signal UNTIL Sell Signal

#### a1cturner

##### Well-known member
I have over 300 lines of code written but I can’t figure this one problem out.

I have several criteria that must all align to create a buy signal. I have that defined properly right now.

The next step I would like is to color the bars (green for long) or (red for short) until I get a defined Sell Signal. Not to be confused with “until my buy signal is no longer true.

The next thing I would like to do is define my actual entry. At least 1 bar after I get the buy signal but before I get a sell signal I would like to enter the trade when the low is <= 5EMA for long or high >= 5EMA for short. I need this defined because I am calculating a sell signal based on the percent decrease of 5EMA - 12 EMA separation from trade entry.

That’s where my problem lies. I obviously start with my buy signal but I need the sell signal defined so I can define my “hold period” but I also need to define the EMA Separation on trade entry which is based on entering a trade during the hold period.

I would prefer no buy signals after the first until I get a sell signal which would then make available the opportunity for a buy signal whether long or short. I have tried using multiple chart bubbles just to see where my triggers are at and try to eliminate them on by one but haven’t been successful in weeks.

Is there a certain function I should be looking for? I get a headache just trying to figure out the order of things and a lot of times if I write:
def hold = (a[1] or b[1]) and !c;
I get no plot at all.

I’ll admit that my strategy “appears” to work but it is not perfect which is where I am trying to get it.

Link to my strategy. https://usethinkscript.com/threads/...d-premarket-highs-lows-for-thinkorswim.10866/

The problem code is under the section “Signals” all the way down to “Bars”

Pleas help!! Lol

Solution
@halcyonguy

Q. why try to define a hold? is that a continuation of a long or short?

A. It is a continuation of a long or short. I just don’t know how to define it better than “hold”. The buy criteria may not be met anymore but it also hasn’t met the sell criteria.

Q. why have entry ? why not just buy and sell?

A. Because I want to ensure the buy criteria is still met on the second bar if the price comes back to the 5EMA.

Q. is post 3 a summary of the buy and sell rules?

A. Better viewed in the code on post 4 in the “SIGNALS” section of the code.

Q. i'm not quite following this paragraph , with the ema difference numbers.
you are talking about buy signals , then you switch to talking about a sell signal 0.8 * 0.65...
I have over 300 lines of code written but I can’t figure this one problem out.

I have several criteria that must all align to create a buy signal. I have that defined properly right now.

The next step I would like is to color the bars (green for long) or (red for short) until I get a defined Sell Signal. Not to be confused with “until my buy signal is no longer true.

The next thing I would like to do is define my actual entry. At least 1 bar after I get the buy signal but before I get a sell signal I would like to enter the trade when the low is <= 5EMA for long or high >= 5EMA for short. I need this defined because I am calculating a sell signal based on the percent decrease of 5EMA - 12 EMA separation from trade entry.

That’s where my problem lies. I obviously start with my buy signal but I need the sell signal defined so I can define my “hold period” but I also need to define the EMA Separation on trade entry which is based on entering a trade during the hold period.

I would prefer no buy signals after the first until I get a sell signal which would then make available the opportunity for a buy signal whether long or short. I have tried using multiple chart bubbles just to see where my triggers are at and try to eliminate them on by one but haven’t been successful in weeks.

Is there a certain function I should be looking for? I get a headache just trying to figure out the order of things and a lot of times if I write:
def hold = (a[1] or b[1]) and !c;
I get no plot at all.

I’ll admit that my strategy “appears” to work but it is not perfect which is where I am trying to get it.

Link to my strategy. https://usethinkscript.com/threads/...d-premarket-highs-lows-for-thinkorswim.10866/

The problem code is under the section “Signals” all the way down to “Bars”

Pleas help!! Lol

try adding a 2nd set of signal formulas
then if needed a 3rd...
then use buy2, or buy3 in the addorders

Code:
``````# The next thing I would like to do is define my actual entry.
# At least 1 bar after I get the buy signal,
#  but before I get a sell signal,
#  I would like to enter the trade when,
#   call ,  low <= 5EMA for long
#   put ,   high >= 5EMA for short.
#    5ema = FastEMA1
def buy2call = CallBuy[1] and !callsell and low <= FastEMA1;
def buy2put = putbuy[1] and !putsell and high >= FastEMA1;
#``````

I need this defined because I am calculating a sell signal based on the percent decrease of 5EMA - 12 EMA separation from trade entry.

i understand this . it is a bar to bar change , of a subtraction
percent decrease of 5EMA - 12 EMA

i don't know what this means
separation from trade entry. what does separation mean?

try adding a 2nd set of signal formulas
then if needed a 3rd...
then use buy2, or buy3 in the addorders

Code:
``````# The next thing I would like to do is define my actual entry.
# At least 1 bar after I get the buy signal,
#  but before I get a sell signal,
#  I would like to enter the trade when,
#   call ,  low <= 5EMA for long
#   put ,   high >= 5EMA for short.
#    5ema = FastEMA1
def buy2call = CallBuy[1] and !callsell and low <= FastEMA1;
def buy2put = putbuy[1] and !putsell and high >= FastEMA1;
#``````

I need this defined because I am calculating a sell signal based on the percent decrease of 5EMA - 12 EMA separation from trade entry.

i understand this . it is a bar to bar change , of a subtraction
percent decrease of 5EMA - 12 EMA

i don't know what this means
separation from trade entry. what does separation mean?
I have tried and tried and tried to do this but I still can't figure it out. I am still currently working on it.

On the second point...by separation I mean the difference between the 5 EMA and 12 EMA.

For the entry I require a separation of at least 0.25 on a 10 minute chart. The formula I use is: ((FastEMA1 / FastEMA2) * 100) - 100

The point of this is to make sure that the current trend has at least a little momentum in the direction I am trying to trade.

My sell trigger is based on this the separation of the EMAs at the time of entry decreasing by 65%. The issue is that because I am defining this in my code after the buy signal, not the entry at the 5 EMA, the separation may be different which is throwing off my sell signal and possibly giving a false sell signal.

To explain a different way....Lets say I have met all but 1 criteria for a buy signal, including the EMA separation of 0.25. Finally, the last criteria is met a few bars later and now the EMA separation is 0.8. My current code uses this 0.8 for the calculation of the sell signal 0.8 * 0.65 = 0.52. If a few bars later the EMA separation dropped to 0.51 than I would get a sell signal. The issue is that most times I get a buy signal the low is well above the 5EMA "entry" requirement, again not to be confused with the buy signal. The price has to come down to the 5EMA after the buy signal before I actually enter the trade. This movement in turn reduces the EMA separation at the time of entry. Lets say that the EMA Separation at entry is now 0.6. I want the EMA Separation Sell Signal to be based on 0.6 instead of 0.8 so I don't get that false sell signal. It gives me a little more breathing room.

I just cannot wrap my head around the code. I have tried over and over, drawn it out on a white board, tested and tested and I can't ever get it to work. Either my code completely stops working, I get all red bars, I get a buy signal followed by hold, hold, hold, hold, then nothing for a bar or two then a sell signal etc.

I don't really need any hold criteria defined. For the sake of aesthetics I would like the long buy signal to be green followed by all green candles until I get a sell signal in which the next candles would just turn a default color (maybe grey or yellow) this would continue until I get another buy signal green for long or red for short.

In my head it should look like this:

Code:
``````def CallBuy = Criteria1 and Criteria2 and Criteria3 and Criteria4;
def Put Buy = Criteria5 and Criteria6 and Criteria7 and Criteria8;

def CallSell = Criteria_A or Criteria_B or Criteria_C;
def PutSell = Criteria_D or Criteria_E or Criteria_F;

def CallHold = !CallSell and (CallBuy[1] or CallHold[1]);
def PutHold = !PutSell and (PutBuy[1] or PutHold[1]);

def CallEntry = CallHold and low <= FastEMA1;
def PutEntry = PutHold and high >= FastEMA1;

def EMAPctAtCallBuy = if CallEntry then FastEMAPctBullRound else EMAPctAtCallBuy[1]; #Used to Calculate Sell Trigger
def EMAPctAtPutBuy = if PutEntry then FastEMAPctBearRound else EMAPctAtPutBuy[1]; #Used to Calculate Sell Trigger

input EMAPctDecFromBuy = 0.65;
def CallEMAPctSell = FastEMAPctBullRound < (EMAPctAtCallBuy * EMAPctDecFromBuy);
def PutEMAPctSell = FastEMAPctBearRound < (EMAPctAtPutBuy * EMAPctDecFromBuy);

def CallSell2 = CallSell or CallEMAPctSell;
def PutSell2 = PutSell or PutEMAPctSell;

def CallHold2 = !CallSell2 and CallHold;
def PutHold2 = !PutSell2 and PutHold;``````

This doesn't work and I can't figure it out.

@halcyonguy I am a little further. Here is the whole new strategy. I am updating multiple things but only burdening you with one problem.

Code:
``````#JT TEMP Strategy Based on TSI, EMAs, MACD, and Premarket Highs/Lows
#VERSION 1 - 05/16/2022

#NOTES MACD Above 0? Add or No? Move EMA Pct At Call Buy after actual entry

Declare Upper;

##################################################################
#                                OPTIONS                         #
##################################################################
input ShowTestBubbles = no;
input Show200EMA = yes;
input ShowEMAClouds = yes;
input ShowPreMarketCloud = yes;
input ShowPreMarketLabel = yes;
input ShowPrevHighLowLabel = no;

##################################################################
#                                COLORS                          #
##################################################################
DefineGlobalColor("200EMA", createcolor (255, 255, 255));
DefineGlobalColor("FastCloudUp", createcolor (102, 255, 102));
DefineGlobalColor("FastCloudDown", createcolor (255, 102, 102));
DefineGlobalColor("SlowCloudUp", createcolor (102, 255, 102));
DefineGlobalColor("SlowCloudDown", createcolor (255, 102, 102));
DefineGlobalColor("OpenLongPosition", createcolor (0, 255, 0));
DefineGlobalColor("OpenShortPosition", createcolor (255, 0, 0));
DefineGlobalColor("HoldLongPosition", createcolor (204, 255, 204));
DefineGlobalColor("HoldShortPosition", createcolor (255, 102, 102));
DefineGlobalColor("GetReady", createcolor (204, 153, 0));
DefineGlobalColor("SellPosition", createcolor (255, 0, 0));
DefineGlobalColor("TakeProfit", createcolor (255, 0, 255));
DefineGlobalColor("CriteriaNotMet", createcolor (255, 255, 102));

##################################################################
#                                 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                        #
##################################################################
#200 EMA
plot EMA200 = ExpAverage(HL2, 200);
EMA200.SetDefaultColor(globalcolor("200EMA"));
EMA200.HideBubble();
EMA200.sethiding(!Show200EMA);

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

plot EMA3 = ExpAverage(close, Ema3Length);
EMA3.SetDefaultColor(globalcolor("FastCloudUp"));
EMA3.HideBubble();
plot EMA4 = ExpAverage(close, Ema4Length);
EMA4.SetDefaultColor(globalcolor("FastCloudDown"));
EMA4.HideBubble();
EMA4.sethiding(!ShowEMAClouds);
AddCloud(if ShowEMAClouds then EMA3 else double.nan, if ShowEMAClouds then EMA4 else double.nan, globalcolor("FastCloudUp"), globalcolor("FastCloudDown"));
plot EMA1 = ExpAverage(close, Ema1Length);
EMA1.SetDefaultColor(globalcolor("SlowCloudUp"));
EMA1.HideBubble();
EMA1.sethiding(!ShowEMAClouds);
plot EMA2 = ExpAverage(close, Ema2Length);
EMA2.SetDefaultColor(globalcolor("SlowCloudDown"));
EMA2.HideBubble();
EMA2.sethiding(!ShowEMAClouds);
AddCloud(if ShowEMAClouds then EMA1 else double.nan, if ShowEMAClouds then EMA2 else double.nan, globalcolor("SlowCloudUp"), globalcolor("SlowCloudDown"));

#EMAS BULLISH OR BEARISH
def FastEMABullish = EMA3 > EMA4;
def SlowEMABullish = EMA1 > EMA2;
def FastEMABearish = EMA3 < EMA4;
def SlowEMABearish = EMA1 < EMA2;
#EMA BUY SIGNAL
def BothEMASBullish = FastEMABullish and SlowEMABullish;
def BothEMASBearish = FastEMABearish and SlowEMABearish;

#EMA PERCENT SEPERATION
def FastEMAPctBull = ((EMA3 / EMA4) * 100) - 100; #Distance Between EMA3 and EMA4
def FastEMAPctBullRound = Round(FastEMAPctBull, 2);
def FastEMAPctBear = ((EMA4 / EMA3) * 100) - 100; #Distance Between EMA4 and EMA3
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(ShowTestBubbles and FastEMAPctBullish, High * 1.005, FastEMAPctBullRound, color.dark_green, yes);
addchartbubble(ShowTestBubbles and FastEMAPctBearish, Low * 0.995, FastEMAPctBearRound, color.dark_green, no);

def SlowEMAPctBull = ((EMA1 / EMA2) * 100) - 100; #Distance Between EMA1 and EMA2
def SlowEMAPctBullRound = Round(SlowEMAPctBull, 2);
def SlowEMAPctBear = ((EMA1 / EMA2) * 100) - 100; #Distance Between EMA1 and EMA2
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 = EMA3 crosses below EMA4;
def FastEMACrossUp = EMA3 crosses above EMA4;
def FastEMAPctBullDecrease = BothEMASBullish and FastEMAPctBullRound < (FastEMAPctBullRound[1] * 0.75) and !FastEMAPctBullDecrease[1];
def FastEMAPctBearDecrease = BothEMASBearish and FastEMAPctBearRound < (FastEMAPctBearRound[1] * 0.75) and !FastEMAPctBearDecrease[1];
#TESTING
addchartbubble(ShowTestBubbles and FastEMAPctBullDecrease, High * 1.005, FastEMAPctBullRound, color.dark_red, yes);
addchartbubble(ShowTestBubbles and FastEMAPctBearDecrease, Low * 0.995, FastEMAPctBearRound, color.dark_red, no);

#SLOWEMA2 SLOPE (NOT USING AT THIS TIME)
#def Height = EMA2 - EMA2[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                             #
##################################################################
#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);

plot PreMarketHigh = Pre_Market_High;
PreMarketHigh.SetStyle(curve.short_dash);
PreMarketHigh.SetDefaultColor(color.light_gray);
PreMarketHigh.Sethiding(!ShowPreMarketCloud);
plot PreMarketLow = Pre_Market_Low;
PreMarketLow.SetStyle(curve.short_dash);
PreMarketLow.SetDefaultColor(color.light_gray);
PreMarketLow.Sethiding(!ShowPreMarketCloud);
AddCloud(if ShowPreMarketCloud then PreMarketHigh else double.nan, if ShowPreMarketCloud then PreMarketLow else double.nan, 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 = close > Pre_Market_High; #was low
def PreMarketBear = close < Pre_Market_Low; #was high
#TESTING
#addchartbubble(ShowTestBubbles and PreMarketBull, EMA2*0.995, "Pre", color.dark_green, no);
#addchartbubble(ShowTestBubbles and PreMarketBear, EMA2*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(ShowTestBubbles and PreMarketBullSell, EMA2*0.995, "Pre", color.dark_red, no);
#addchartbubble(ShowTestBubbles and PreMarketBearSell, EMA2*1.005, "Pre", color.dark_red, yes);

##################################################################
#                      YESTERDAY HIGH/LOW                        #
##################################################################
def PrevHigh = high(period = "day")[1];
def PrevLow = low(period = "day")[1];

AddLabel(if ShowPrevHighLowLabel then 1 else 0, "   ", color.black);
AddLabel(if ShowPrevHighLowLabel then 1 else 0, "Prev High " + "\$ " + PrevHigh + " ", color.gray);
AddLabel(if ShowPrevHighLowLabel then 1 else 0, "Prev Low " + "\$ " + PrevLow + " ", color.gray);

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

#INDICATOR SELL SIGNALS
def CallSellInd = TradingDayExt;
def PutSellInd = TradingDayExt;

#INDICATOR HOLD SIGNALS
def CallHoldInd = TradingDayExt and (CallBuyInd[1] or CallHoldInd[1]);
def PutHoldInd = TradingDayExt and (PutBuyInd[1] or PutHoldInd[1]);

#INDICATOR ENTRY SIGNALS
def CallEntryInd = CallHoldInd and low <= EMA3;
def PutEntryInd = PutHoldInd and high >= EMA3;

##################################################################
#         ADDED FAST EMA PCT HERE BASED OFF BUY SIGNAL           #
##################################################################
def EMAPctAtCallBuy = if CallEntryInd then FastEMAPctBullRound else EMAPctAtCallBuy[1]; #Used to Calculate Sell Trigger
def EMAPctAtPutBuy = if PutEntryInd 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);
def PutEMAPctSell = FastEMAPctBearRound < (EMAPctAtPutBuy * EMAPctDecFromBuy);

##################################################################
#                         SIGNALS CONT.                          #
##################################################################
#SELL SIGNALS
def CallSellInd2 = CallSellInd and (FastEMACrossDown or TSICrossDown or CallEMAPctSell);
def PutSellInd2 = PutSellInd and (FastEMACrossUp or TSICrossUp or PutEMAPctSell);

#HOLD SIGNALS
def CallHoldInd2 = CallHoldInd and !CallSellInd2;
def PutHoldInd2 = PutHoldInd and !PutSellInd2;

##################################################################
#                                 BARS                           #
##################################################################
#COLOR BARS
AssignPriceColor(if CallHoldInd2 then GlobalColor("HoldLongPosition") else if PutHoldInd2 then GlobalColor("HoldShortPosition") else if CallBuyInd then GlobalColor("OpenLongPosition") else if PutBuyInd then GlobalColor("OpenShortPosition") else GlobalColor("CriteriaNotMet"));

##################################################################
# 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 EMA3 * 1.01 else Double.NaN;
def OvrExtUp2 = if ShowOverExtCloud and SignalStart and TradingDayExt and (CallBuyInd or CallHoldInd) then EMA3 * 1.02 else Double.NaN;
AddCloud(OvrExtUp1, OvrExtUp2, color.light_green, color.light_green);
def OvrExtDn1 = if ShowOverExtCloud and SignalStart and TradingDayExt and (PutBuyInd or PutHoldInd) then EMA3 * 0.99 else Double.NaN;
def OvrExtDn2 = if ShowOverExtCloud and SignalStart and TradingDayExt and (PutBuyInd or PutHoldInd) then EMA3 * 0.98 else Double.NaN;
AddCloud(OvrExtDn1, OvrExtDn2, color.light_green, color.light_green);``````

This is what I wish it looked like every time. Note: EMA Clouds, Premarket Clouds, and TakeProfit Clouds turned off

But instead this was today on AMZN

I have tried and tried and tried to do this but I still can't figure it out. I am still currently working on it.

On the second point...by separation I mean the difference between the 5 EMA and 12 EMA.

For the entry I require a separation of at least 0.25 on a 10 minute chart. The formula I use is: ((FastEMA1 / FastEMA2) * 100) - 100

The point of this is to make sure that the current trend has at least a little momentum in the direction I am trying to trade.

My sell trigger is based on this the separation of the EMAs at the time of entry decreasing by 65%. The issue is that because I am defining this in my code after the buy signal, not the entry at the 5 EMA, the separation may be different which is throwing off my sell signal and possibly giving a false sell signal.

To explain a different way....Lets say I have met all but 1 criteria for a buy signal, including the EMA separation of 0.25. Finally, the last criteria is met a few bars later and now the EMA separation is 0.8. My current code uses this 0.8 for the calculation of the sell signal 0.8 * 0.65 = 0.52. If a few bars later the EMA separation dropped to 0.51 than I would get a sell signal. The issue is that most times I get a buy signal the low is well above the 5EMA "entry" requirement, again not to be confused with the buy signal. The price has to come down to the 5EMA after the buy signal before I actually enter the trade. This movement in turn reduces the EMA separation at the time of entry. Lets say that the EMA Separation at entry is now 0.6. I want the EMA Separation Sell Signal to be based on 0.6 instead of 0.8 so I don't get that false sell signal. It gives me a little more breathing room.

I just cannot wrap my head around the code. I have tried over and over, drawn it out on a white board, tested and tested and I can't ever get it to work. Either my code completely stops working, I get all red bars, I get a buy signal followed by hold, hold, hold, hold, then nothing for a bar or two then a sell signal etc.

I don't really need any hold criteria defined. For the sake of aesthetics I would like the long buy signal to be green followed by all green candles until I get a sell signal in which the next candles would just turn a default color (maybe grey or yellow) this would continue until I get another buy signal green for long or red for short.

In my head it should look like this:

Code:
``````def CallBuy = Criteria1 and Criteria2 and Criteria3 and Criteria4;
def Put Buy = Criteria5 and Criteria6 and Criteria7 and Criteria8;

def CallSell = Criteria_A or Criteria_B or Criteria_C;
def PutSell = Criteria_D or Criteria_E or Criteria_F;

def CallHold = !CallSell and (CallBuy[1] or CallHold[1]);
def PutHold = !PutSell and (PutBuy[1] or PutHold[1]);

def CallEntry = CallHold and low <= FastEMA1;
def PutEntry = PutHold and high >= FastEMA1;

def EMAPctAtCallBuy = if CallEntry then FastEMAPctBullRound else EMAPctAtCallBuy[1]; #Used to Calculate Sell Trigger
def EMAPctAtPutBuy = if PutEntry then FastEMAPctBearRound else EMAPctAtPutBuy[1]; #Used to Calculate Sell Trigger

input EMAPctDecFromBuy = 0.65;
def CallEMAPctSell = FastEMAPctBullRound < (EMAPctAtCallBuy * EMAPctDecFromBuy);
def PutEMAPctSell = FastEMAPctBearRound < (EMAPctAtPutBuy * EMAPctDecFromBuy);

def CallSell2 = CallSell or CallEMAPctSell;
def PutSell2 = PutSell or PutEMAPctSell;

def CallHold2 = !CallSell2 and CallHold;
def PutHold2 = !PutSell2 and PutHold;``````

This doesn't work and I can't figure it out.

i'm reading your posts .........
will try your new code tonight.

it seems overly complicated.
why try to define a hold? is that a continuation of a long or short?
seems like it would be redundant and just confuse things.

why have entry ? why not just buy and sell?

once all the inputs align for a buy, then buy.
then wait for a sell signal.

i would say , try to write out in short sentences, what are the buy parameters, and sell rules.
is post 3 a summary of the buy and sell rules?

My sell trigger is based on this the separation of the EMAs at the time of entry decreasing by 65%. The issue is that because I am defining this in my code after the buy signal, not the entry at the 5 EMA, the separation may be different which is throwing off my sell signal and possibly giving a false sell signal.

To explain a different way....Lets say I have met all but 1 criteria for a buy signal, including the EMA separation of 0.25. Finally, the last criteria is met a few bars later and now the EMA separation is 0.8. My current code uses this 0.8 for the calculation of the sell signal 0.8 * 0.65 = 0.52. If a few bars later the EMA separation dropped to 0.51 than I would get a sell signal. The issue is that most times I get a buy signal the low is well above the 5EMA "entry" requirement, again not to be confused with the buy signal. The price has to come down to the 5EMA after the buy signal before I actually enter the trade. This movement in turn reduces the EMA separation at the time of entry. Lets say that the EMA Separation at entry is now 0.6. I want the EMA Separation Sell Signal to be based on 0.6 instead of 0.8 so I don't get that false sell signal. It gives me a little more breathing room.

i'm not quite following this paragraph , with the ema difference numbers.
you are talking about buy signals , then you switch to talking about a sell signal 0.8 * 0.65..?? why think about selling? get the buy signals worked out first.
your parameters either line up on 1 bar for a buy or they don't.
are you trying to use buy conditions , that occur on different bars, but within , say 3 bars ?

maybe you need different ranges of values , for the buy parameters, so they will align on a desirable bar.

@halcyonguy

Q. why try to define a hold? is that a continuation of a long or short?

A. It is a continuation of a long or short. I just don’t know how to define it better than “hold”. The buy criteria may not be met anymore but it also hasn’t met the sell criteria.

Q. why have entry ? why not just buy and sell?

A. Because I want to ensure the buy criteria is still met on the second bar if the price comes back to the 5EMA.

Q. is post 3 a summary of the buy and sell rules?

A. Better viewed in the code on post 4 in the “SIGNALS” section of the code.

Q. i'm not quite following this paragraph , with the ema difference numbers.
you are talking about buy signals , then you switch to talking about a sell signal 0.8 * 0.65..?? why think about selling? get the buy signals worked out first.

A. I am trying to define the difference in EMAs when I actually enter the trade because it affects one of my sell signals. I am not necessarily thinking about selling, I just have to put this somewhere before my actual exit definition so that I can use it in my exit definition. The buy signals are good. That’s not an issue at this point.

Thanks for your help! This is even difficult for me to wrap my head around. I know what I want and I know how I want to trade it but coding it and having an accurate backtest is a whole different issue. Let me explain a different way once more.

If all criteria line up for a buy and the price is at the 5EMA then enter the trade. If all criteria are met but the price is not at the 5EMA then wait for it to get there. On the next bar if the price makes it to the 5EMA then make sure all criteria are still met for a buy; if so than enter the trade. Once I am in the trade than wait for a sell signal. If I get a sell signal all the way through the close of the candle (repainting issue) than close on the open of the next candle.

I don’t want the bars to change from green (any shade of green) if long until I get a sell signal. I also don’t necessarily want the bars to be the same color green as the buy signal because it’s necessary as described in the previous paragraph to be able to visually see if all buy criteria are still met when the price moves back to the 5EMA.

Hope that makes sense. I am just trying to lower my risk which is why I’m so dead set on the 5EMA parameter being met.

@halcyonguy here is the full updated code as of right this second. I am a little closer but still appreciate any insight or advice.

Code:
``````#JT TEMP Strategy Based on TSI, EMAs, MACD, and Premarket Highs/Lows
#VERSION 1 - 05/16/2022

#NOTES MACD Above 0?

Declare Upper;

##################################################################
#                                OPTIONS                         #
##################################################################
input ShowTestBubbles = no;
input ShowFlexGridBackgroundColor = no;
input ShowColorDefLabels = yes;
input AlertOn = yes;
input Show200EMA = yes;
input ShowEMAClouds = yes;
input ShowPreMarketCloud = yes;
input ShowPreMarketLabel = yes;
input ShowPrevHighLowLabel = no;
input ShowBuySellBubbles = Yes;
input ShowOverExtCloud = yes;
input ShowTkPftBubble = Yes;
input ShowOrders = no;
input ShowTkPftOrders = no;

##################################################################
#                                COLORS                          #
##################################################################
DefineGlobalColor("200EMA", createcolor (255, 255, 255));
DefineGlobalColor("FastCloudUp", createcolor (102, 255, 102));
DefineGlobalColor("FastCloudDown", createcolor (255, 102, 102));
DefineGlobalColor("SlowCloudUp", createcolor (102, 255, 102));
DefineGlobalColor("SlowCloudDown", createcolor (255, 102, 102));
DefineGlobalColor("OpenLongPosition", createcolor (0, 255, 0));
DefineGlobalColor("OpenShortPosition", createcolor (255, 0, 0));
DefineGlobalColor("HoldLongPosition", createcolor (153, 255, 153));
DefineGlobalColor("HoldShortPosition", createcolor (255, 153, 153));
DefineGlobalColor("SellPosition", createcolor (255, 0, 0));
DefineGlobalColor("TakeProfit", createcolor (255, 0, 255));
DefineGlobalColor("CriteriaNotMet", createcolor (255, 255, 0));

##################################################################
#                                 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                        #
##################################################################
#200 EMA
plot EMA200 = ExpAverage(HL2, 200);
EMA200.SetDefaultColor(globalcolor("200EMA"));
EMA200.HideBubble();
EMA200.sethiding(!Show200EMA);

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

plot EMA3 = ExpAverage(close, Ema3Length);
EMA3.SetDefaultColor(globalcolor("FastCloudUp"));
EMA3.HideBubble();
plot EMA4 = ExpAverage(close, Ema4Length);
EMA4.SetDefaultColor(globalcolor("FastCloudDown"));
EMA4.HideBubble();
EMA4.sethiding(!ShowEMAClouds);
AddCloud(if ShowEMAClouds then EMA3 else double.nan, if ShowEMAClouds then EMA4 else double.nan, globalcolor("FastCloudUp"), globalcolor("FastCloudDown"));
plot EMA1 = ExpAverage(close, Ema1Length);
EMA1.SetDefaultColor(globalcolor("SlowCloudUp"));
EMA1.HideBubble();
EMA1.sethiding(!ShowEMAClouds);
plot EMA2 = ExpAverage(close, Ema2Length);
EMA2.SetDefaultColor(globalcolor("SlowCloudDown"));
EMA2.HideBubble();
EMA2.sethiding(!ShowEMAClouds);
AddCloud(if ShowEMAClouds then EMA1 else double.nan, if ShowEMAClouds then EMA2 else double.nan, globalcolor("SlowCloudUp"), globalcolor("SlowCloudDown"));

#EMAS BULLISH OR BEARISH
def FastEMABullish = EMA3 > EMA4;
def SlowEMABullish = EMA1 > EMA2;
def FastEMABearish = EMA3 < EMA4;
def SlowEMABearish = EMA1 < EMA2;
#EMA BUY SIGNAL
def BothEMASBullish = FastEMABullish and SlowEMABullish;
def BothEMASBearish = FastEMABearish and SlowEMABearish;

#EMA PERCENT SEPERATION
def FastEMAPctBull = ((EMA3 / EMA4) * 100) - 100; #Distance Between EMA3 and EMA4
def FastEMAPctBullRound = Round(FastEMAPctBull, 2);
def FastEMAPctBear = ((EMA4 / EMA3) * 100) - 100; #Distance Between EMA4 and EMA3
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(ShowTestBubbles and FastEMAPctBullish, High * 1.005, FastEMAPctBullRound, color.dark_green, yes);
addchartbubble(ShowTestBubbles and FastEMAPctBearish, Low * 0.995, FastEMAPctBearRound, color.dark_green, no);

def SlowEMAPctBull = ((EMA1 / EMA2) * 100) - 100; #Distance Between EMA1 and EMA2
def SlowEMAPctBullRound = Round(SlowEMAPctBull, 2);
def SlowEMAPctBear = ((EMA1 / EMA2) * 100) - 100; #Distance Between EMA1 and EMA2
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 = EMA3 crosses below EMA4;
def FastEMACrossUp = EMA3 crosses above EMA4;
#def FastEMAPctBullDecrease = BothEMASBullish and FastEMAPctBullRound < (FastEMAPctBullRound[1] * 0.75) and !FastEMAPctBullDecrease[1];
#def FastEMAPctBearDecrease = BothEMASBearish and FastEMAPctBearRound < (FastEMAPctBearRound[1] * 0.75) and !FastEMAPctBearDecrease[1];
#TESTING
#addchartbubble(ShowTestBubbles and FastEMAPctBullDecrease, High * 1.005, FastEMAPctBullRound, color.dark_red, yes);
#addchartbubble(ShowTestBubbles and FastEMAPctBearDecrease, Low * 0.995, FastEMAPctBearRound, color.dark_red, no);

#SLOWEMA2 SLOPE (NOT USING AT THIS TIME)
#def Height = EMA2 - EMA2[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);

def EMABull = EMA3 > EMA200 and (open and close) > EMA3;
def EMABear = EMA3 < EMA200 and (open and close) < EMA3;

#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                             #
##################################################################
#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);

plot PreMarketHigh = Pre_Market_High;
PreMarketHigh.SetStyle(curve.short_dash);
PreMarketHigh.SetDefaultColor(color.light_gray);
PreMarketHigh.Sethiding(!ShowPreMarketCloud);
plot PreMarketLow = Pre_Market_Low;
PreMarketLow.SetStyle(curve.short_dash);
PreMarketLow.SetDefaultColor(color.light_gray);
PreMarketLow.Sethiding(!ShowPreMarketCloud);
AddCloud(if ShowPreMarketCloud then PreMarketHigh else double.nan, if ShowPreMarketCloud then PreMarketLow else double.nan, 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 = close > Pre_Market_High; #was low
def PreMarketBear = close < Pre_Market_Low; #was high
#TESTING
#addchartbubble(ShowTestBubbles and PreMarketBull, EMA2*0.995, "Pre", color.dark_green, no);
#addchartbubble(ShowTestBubbles and PreMarketBear, EMA2*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(ShowTestBubbles and PreMarketBullSell, EMA2*0.995, "Pre", color.dark_red, no);
#addchartbubble(ShowTestBubbles and PreMarketBearSell, EMA2*1.005, "Pre", color.dark_red, yes);

##################################################################
#                      YESTERDAY HIGH/LOW                        #
##################################################################
def PrevHigh = high(period = "day")[1];
def PrevLow = low(period = "day")[1];

AddLabel(if ShowPrevHighLowLabel then 1 else 0, "   ", color.black);
AddLabel(if ShowPrevHighLowLabel then 1 else 0, "Prev High " + "\$ " + PrevHigh + " ", color.gray);
AddLabel(if ShowPrevHighLowLabel then 1 else 0, "Prev Low " + "\$ " + PrevLow + " ", color.gray);

##################################################################
#                               SIGNALS                          #
##################################################################
#INDICATOR BUY SIGNALS
def LongBuyInd = TradingDay and BothEMASBullish and FastEMAPctBullish and MACDBull and TSIBull and PreMarketBull; # EMABull; #PreMarketBull;
def ShortBuyInd = TradingDay and BothEMASBearish and FastEMAPctBearish and MACDBear and TSIBear and PreMarketBear; #EMABear; #PreMarketBear;

#INDICATOR HOLD SIGNALS
def LongHoldInd = TradingDayExt and (LongBuyInd[1] or LongHoldInd[1]);
def ShortHoldInd = TradingDayExt and (ShortBuyInd[1] or ShortHoldInd[1]);

#INDICATOR ENTRY SIGNALS
def LongEntryInd = LongBuyInd[1] and LongBuyInd and low <= (EMA3 * 1.0025);
def ShortEntryInd = ShortBuyInd[1] and ShortBuyInd and high >= (EMA3 * 0.9975);

##################################################################
#         ADDED FAST EMA PCT HERE BASED OFF BUY SIGNAL           #
##################################################################
def EMAPctAtLongBuy = if LongEntryInd then FastEMAPctBullRound else EMAPctAtLongBuy[1]; #Used to Calculate Sell Trigger
def EMAPctAtShortBuy = if ShortEntryInd then FastEMAPctBearRound else EMAPctAtShortBuy[1]; #Used to Calculate Sell Trigger

#FAST EMA CLOUD SELL TRIGGER BASED OFF BUY INDICATOR
input EMAPctDecFromBuy = 0.6;
def LongEMAPctSell = FastEMAPctBullRound < (EMAPctAtLongBuy * EMAPctDecFromBuy);
def ShortEMAPctSell = FastEMAPctBearRound < (EMAPctAtShortBuy * EMAPctDecFromBuy);

##################################################################
#                         SIGNALS CONT.                          #
##################################################################
#SELL SIGNALS
def LongSellInd = TradingDayExt and (FastEMACrossDown or TSICrossDown or LongEMAPctSell);
def ShortSellInd = TradingDayExt and (FastEMACrossUp or TSICrossUp or ShortEMAPctSell);

#HOLD SIGNALS
def CallHoldInd2 = LongHoldInd and !LongSellInd;
def PutHoldInd2 = ShortHoldInd and !ShortSellInd;

##################################################################
#                                 BARS                           #
##################################################################
AssignPriceColor(if LongBuyInd then GlobalColor("OpenLongPosition") else if ShortBuyInd then GlobalColor("OpenShortPosition") else if CallHoldInd2 then GlobalColor("HoldLongPosition") else if PutHoldInd2 then GlobalColor("HoldShortPosition") else GlobalColor("CriteriaNotMet"));

##################################################################
# EMA TAKE PROFIT CLOUD (IDENTIFY IF PRICE IS EXTENDED FROM EMAS)#
##################################################################
def OvrExtUp1 = if ShowOverExtCloud and SignalStart and TradingDayExt and (LongBuyInd or LongHoldInd) then EMA3 * 1.01 else Double.NaN;
def OvrExtUp2 = if ShowOverExtCloud and SignalStart and TradingDayExt and (LongBuyInd or LongHoldInd) then EMA3 * 1.02 else Double.NaN;
AddCloud(OvrExtUp1, OvrExtUp2, color.light_green, color.light_green);
def OvrExtDn1 = if ShowOverExtCloud and SignalStart and TradingDayExt and (ShortBuyInd or ShortHoldInd) then EMA3 * 0.99 else Double.NaN;
def OvrExtDn2 = if ShowOverExtCloud and SignalStart and TradingDayExt and (ShortBuyInd or ShortHoldInd) then EMA3 * 0.98 else Double.NaN;
AddCloud(OvrExtDn1, OvrExtDn2, color.light_green, color.light_green);

#*****************************************************************************#
#*****************STILL EDITING AND CHECKING EVERYTHING BELOW*****************#
#*****************************************************************************#

##################################################################
#                                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                    #
##################################################################
#BUY
addchartbubble(LongEntryInd, High * 1.005, "Long", color.green, yes);
addchartbubble(ShortEntryInd, Low * 0.995, "Short", color.red, no);

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

#TAKE PROFIT
def TkPftBubCall = TradingDayExt and (LongBuyInd or LongHoldInd) and high > EMA3 * 1.01;
addchartbubble(ShowTkPftBubble and TkPftBubCall, high * 1.001, "Tk Pft", GlobalColor("TakeProfit"), yes);
def TkPftBubPut = TradingDayExt and (ShortBuyInd or ShortHoldInd) and low < EMA3 * 0.99;
addchartbubble(ShowTkPftBubble and TkPftBubPut, low * 0.999, "Tk Pft", GlobalColor("TakeProfit"), no);

##################################################################
#                             STOP LOSS                          #
##################################################################
def longstop = if (open < close) then open else close;
def shortstop = if (open > close) then open else close;
addlabel(if (LongBuyInd or LongEntryInd) then yes else no, "STOP \$ " + longstop[2] + " ", color.white);
addlabel(if (ShortBuyInd or ShortEntryInd) then yes else no, "STOP \$ " + shortstop[2] + " ", color.white);

##################################################################
#                                ORDERS                          #
##################################################################
#BUY ORDERS
AddOrder(OrderType.BUY_TO_OPEN, ShowOrders and LongEntryInd, if LongEntryInd then (EMA3 * 1.0025) else double.nan, 100, Color.GREEN, Color.LIGHT_GREEN);
AddOrder(OrderType.SELL_TO_OPEN, ShowOrders and ShortEntryInd, if ShortEntryInd then (EMA3 * 0.9975) else double.nan, 100, Color.GREEN, Color.LIGHT_GREEN);

#SELL ORDERS
AddOrder(OrderType.SELL_TO_CLOSE, ShowOrders and ShowTkPftOrders and TkPftBubCall, high * 0.999, 100, Color.RED, Color.LIGHT_RED);
AddOrder(OrderType.SELL_TO_CLOSE, ShowOrders and (LongSellInd or EndDay[-1]), open[-1], 100, Color.RED, Color.LIGHT_RED);
AddOrder(OrderType.BUY_TO_CLOSE, ShowOrders and ShowTkPftOrders and TkPftBubPut, low * 1.001, 100, Color.RED, Color.LIGHT_RED);
AddOrder(OrderType.BUY_TO_CLOSE, ShowOrders and (ShortSellInd or EndDay[-1]), open[-1], 100, Color.RED, Color.LIGHT_RED);
##################################################################
#                                ALERTS                          #
##################################################################
Alert(AlertOn and (CallSellBub or PutSellBub or TkPftBubCall or TkPftBubPut), "SELL", Alert.BAR, Sound.Bell);
Alert(AlertOn and (LongBuyInd or ShortBuyInd), "BUY", Alert.BAR, Sound.Chimes);

##################################################################
#                       CANDLE COLOR LABEL                       #
##################################################################
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, "No Criteria", GlobalColor("CriteriaNotMet"));

##################################################################
#                BACKGROUND COLOR FOR FLEX GRID                  #
##################################################################
AssignBackgroundColor(if ShowFlexGridBackgroundColor and LongBuyInd then GlobalColor("OpenLongPosition") else if ShowFlexGridBackgroundColor and ShortBuyInd then GlobalColor("OpenShortPosition") else if ShowFlexGridBackgroundColor and (TkPftBubCall or TkPftBubPut) then GlobalColor("TakeProfit") else color.current);``````

Last edited:
@halcyonguy

Q. why try to define a hold? is that a continuation of a long or short?

A. It is a continuation of a long or short. I just don’t know how to define it better than “hold”. The buy criteria may not be met anymore but it also hasn’t met the sell criteria.

Q. why have entry ? why not just buy and sell?

A. Because I want to ensure the buy criteria is still met on the second bar if the price comes back to the 5EMA.

Q. is post 3 a summary of the buy and sell rules?

A. Better viewed in the code on post 4 in the “SIGNALS” section of the code.

Q. i'm not quite following this paragraph , with the ema difference numbers.
you are talking about buy signals , then you switch to talking about a sell signal 0.8 * 0.65..?? why think about selling? get the buy signals worked out first.

A. I am trying to define the difference in EMAs when I actually enter the trade because it affects one of my sell signals. I am not necessarily thinking about selling, I just have to put this somewhere before my actual exit definition so that I can use it in my exit definition. The buy signals are good. That’s not an issue at this point.

Thanks for your help! This is even difficult for me to wrap my head around. I know what I want and I know how I want to trade it but coding it and having an accurate backtest is a whole different issue. Let me explain a different way once more.

If all criteria line up for a buy and the price is at the 5EMA then enter the trade. If all criteria are met but the price is not at the 5EMA then wait for it to get there. On the next bar if the price makes it to the 5EMA then make sure all criteria are still met for a buy; if so than enter the trade. Once I am in the trade than wait for a sell signal. If I get a sell signal all the way through the close of the candle (repainting issue) than close on the open of the next candle.

I don’t want the bars to change from green (any shade of green) if long until I get a sell signal. I also don’t necessarily want the bars to be the same color green as the buy signal because it’s necessary as described in the previous paragraph to be able to visually see if all buy criteria are still met when the price moves back to the 5EMA.

Hope that makes sense. I am just trying to lower my risk which is why I’m so dead set on the 5EMA parameter being met.

typing and talking out loud... let's see if we can fix / simplify this,

there are only 2 actions, buy and sell.
i would simply it by,
.. change hold formulas to be sell criteria ,
.. change entry formulas to be buy criteria.

if your hold formulas are being used to determine if you should stay in a trade (hold) or get out, then they are sell criteria.

do all buy signals have to be true on the same bar ?
can a buy happen if 1 buy condition was true on the previous bar, but is false on current bar?

--------------------

... I just don’t know how to define it better than “hold”. The buy criteria may not be met anymore but it...
what does it matter if a buy doesn't exist anymore? a buy signal happens once, then you buy. then you wait for a sell signal.
if the next bar has a sell , then sell. and maybe reevaluate your formulas.

Q. why have entry ? why not just buy and sell?
A. Because I want to ensure the buy criteria is still met on the second bar if the price comes back to the 5EMA.
what does this mean , ensure the buy criteria is still met ?
are you delaying a buy until something else happens? then entry is a buy signal.

...price comes back to the 5EMA....
i don't know what 'back to' means. when price is = ema5? . or within 65% ?
i am really confused by your ema rules. maybe i have a mental block on your use of the word separation. 'difference' would have clicked with me... i think you are trying to evaluate a difference of 2 ema price levels.
i went back to post#1 and found this
... I need this defined because I am calculating a sell signal based on the percent decrease of 5EMA - 12 EMA separation from trade entry....
this makes sense, if i ignore the word separation.

... difference in EMAs when I actually enter the trade...
then when a buy happens, save a value and keep it until the next buy.
if a condition is true then set a variable , else read the previous value. this will grab a value and keep it until the next trigger
def emadiff = if buy then ( ema stuff ) else emadiff[1];

. If all criteria are met but the price is not at the 5EMA then...
then all the criteria have NOT been met for a buy. i don't understand why you are separating the ema buy condition.

Thanks @halcyonguy You helped me wrap my head around it a little better. I have it figured out now. Thanks for your help once again

### Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
261 Online

## 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.