Help with Strategy Builder, 2 moving avg's with ATR

Big_Mirror

New member
I used @JoeDV "Potential P/L From Study For ThinkOrSwim" posting code, plugged into Google Gemini to use some of the code to build me a 2 moving average with ATR. Using ema length 50 and wilders length 126. If price is above these two go long and if its below go short, works on all time frames. Add labels for "PROFIT TARGET" and "STOP LOSS". Other labels as Market Open, Tick Size, Open bought, Open trade and more labels in the code. See screenshot below:
1764214569443.png


ISSUE: When i added this as a strategy and right click on the chart, selected "Show Report" I am getting this as blank. My dates are off, P/L is $0 and Total Orders is 0
1764214823768.png


I do NOT know coding, i am using Google Gemini to help me with coding. Can someone please take a look at this and tell me how i can make this report to show the results?

@JoeDV @merryDay @BenTen @HODL-Lay-HE-hoo! or anyone else who is reading this post. I would really appreciate any help.....thank you so much and Happy Thanksgiving.

here is the code snippet

Code:
# =================================================================
# MA-Filter Strategy with ATR Stop Loss & Profit Target (FINAL V9)
# Fixes: Removed redundant dashboard labels and stopped bubble over-plotting.
# =================================================================

declare once_per_bar;

# --- Template & Strategy Inputs ---
input showSignals = yes;
input showLabels  = yes;
input showBubbles = yes;
input useStops = yes;   
input useAlerts = no;   
input tradeDaytimeOnly = no;
input OpenTime = 0930;
input CloseTime = 1600;

# --- FIX 1: New Input to Disable Labels ---
input disableDuplicateLabels = yes;

# --- Custom ATR Inputs ---
input atrLength = 14;             
input stopLossMultiple = 2.0;     
input profitTargetMultiple = 4.0;
input PositionSize = 1;

# --- Indicator Inputs ---
input emaLength = 50;
input wsLength = 126;

# --- Declarations (For Scope) ---
def CurrentPosition; 
def profitWinners;
def profitLosers;
def profitPush;

# --- Market Time Definitions ---
def Begin = secondsfromTime(OpenTime);
def End = secondsTillTime(CloseTime);
def isIntraDay = if getaggregationperiod() > 14400000 then 0 else 1;
def MarketOpen = if tradeDaytimeOnly AND isIntraDay then ((Begin > 0) and (End > 0)) else 1;

# --- Indicators and Distances ---
def EMA50 = ExpAverage(close, emaLength);
def WS126 = WildersAverage(close, wsLength);
def ATR = Average(TrueRange(high, close, low), atrLength);
def StopDistance = ATR * stopLossMultiple;
def TargetDistance = ATR * profitTargetMultiple;


########################################################
##  Signals, Exits, and Position Tracking
######################################################

# --- Entry Signals (Only true when flat and conditions are met) ---
def MA_LongSignal = close > EMA50 and close > WS126;
def PLBuySignal = if MarketOpen AND MA_LongSignal AND CurrentPosition[1] == 0 then 1 else 0 ;

def MA_ShortSignal = close < EMA50 and close < WS126;
def PLSellSignal =  if MarketOpen AND MA_ShortSignal AND CurrentPosition[1] == 0 then 1 else 0;

# --- Order Price and Status ---
def isOrder = if CurrentPosition != CurrentPosition[1] then 1 else 0;
def orderPrice = if (isOrder and (PLBuySignal or PLSellSignal)) then close else orderPrice[1];
def isLong  = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;

# --- ATR Exit Prices ---
def LongStopPrice = if PLBuySignal then orderPrice - StopDistance else LongStopPrice[1];
def LongTargetPrice = if PLBuySignal then orderPrice + TargetDistance else LongTargetPrice[1];
def ShortStopPrice = if PLSellSignal then orderPrice + StopDistance else ShortStopPrice[1];
def ShortTargetPrice = if PLSellSignal then orderPrice - TargetDistance else ShortTargetPrice[1];

# --- Stop/Target Triggers ---
def LongExitSL = if isLong[1] and close < LongStopPrice[1] then 1 else 0;
def LongExitPT = if isLong[1] and close > LongTargetPrice[1] then 1 else 0;
def PLBuyStop  = if useStops and (LongExitSL or LongExitPT) then 1 else 0;

def ShortExitSL = if isShort[1] and close > ShortStopPrice[1] then 1 else 0;
def ShortExitPT = if isShort[1] and close < ShortTargetPrice[1] then 1 else 0;
def PLSellStop = if useStops and (ShortExitSL or ShortExitPT) then 1 else 0;

# --- Market Stop ---
def PLMktStop = if MarketOpen[-1] == 0 then 1 else 0;


#########################################  Position Maintenance (Actual Calculation) #######################################

if (BarNumber()==1) OR isNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
}else{
        if CurrentPosition[1] == 0 {            # FLAT
            if (PLBuySignal) {
                CurrentPosition = 1;
            } else if (PLSellSignal){
                CurrentPosition = -1;
            } else {
                CurrentPosition = CurrentPosition[1];
            }
       } else if CurrentPosition[1] == 1 {      # LONG
            # Exit Long on Stop/Target, Market Stop, OR opposing MA signal
            if (PLBuyStop or PLMktStop or PLSellSignal){
                CurrentPosition = if PLSellSignal then -1 else 0; # Reverse if opposite signal, else flat
            } else {
                CurrentPosition = CurrentPosition[1];
            }
       } else if CurrentPosition[1] == -1 {     # SHORT
            # Exit Short on Stop/Target, Market Stop, OR opposing MA signal
            if (PLSellStop or PLMktStop or PLBuySignal){
                CurrentPosition = if PLBuySignal then 1 else 0; # Reverse if opposite signal, else flat
            } else {
                CurrentPosition = CurrentPosition[1];
            }
       } else {
            CurrentPosition = CurrentPosition[1];
       }
}


#########################################  Plots and Dashboard #######################################

# --- Plot MAs ---
plot PlotEMA50 = EMA50; PlotEMA50.SetDefaultColor(Color.BLUE); PlotEMA50.SetStyle(Curve.FIRM);
plot PlotWS126 = WS126; PlotWS126.SetDefaultColor(Color.PLUM); PlotWS126.SetStyle(Curve.POINTS);

# --- Entry Arrows (White/Orange) ---
plot BuySig = if (PLBuySignal and showSignals) then low - TickSize() else Double.NaN;
BuySig.AssignValueColor(Color.WHITE);
BuySig.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySig.SetLineWeight(5);

plot SellSig = if (PLSellSignal and showSignals) then high + TickSize() else Double.NaN;
SellSig.AssignValueColor(Color.ORANGE);
SellSig.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSig.SetLineWeight(5);

# --- Exit Signals (Grey DOTS) ---
def LongExitPlot = PLBuyStop or (isLong[1] and PLMktStop);
plot BuyStpSig = if LongExitPlot then high + TickSize() else Double.NaN;
BuyStpSig.AssignValueColor(color.LIGHT_GRAY);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.POINTS);
BuyStpSig.SetLineWeight(3);

def ShortExitPlot = PLSellStop or (isShort[1] and PLMktStop);
plot SellStpSig = if ShortExitPlot then low - TickSize() else Double.NaN;
SellStpSig.AssignValueColor(color.LIGHT_GRAY);
SellStpSig.SetPaintingStrategy(PaintingStrategy.POINTS);
SellStpSig.SetLineWeight(3);

# --- Exit Plots (Red/Lime Lines) ---
def isFlat  = if CurrentPosition == 0 then 1 else 0;
plot LongSL = if isLong then LongStopPrice else Double.NaN; LongSL.SetDefaultColor(Color.RED); LongSL.SetStyle(Curve.LONG_DASH); LongSL.SetLineWeight(1);
plot ShortSL = if isShort then ShortStopPrice else Double.NaN; ShortSL.SetDefaultColor(Color.RED); ShortSL.SetStyle(Curve.LONG_DASH); ShortSL.SetLineWeight(1);
plot LongPT = if isLong then LongTargetPrice else Double.NaN; LongPT.SetDefaultColor(Color.LIME); LongPT.SetStyle(Curve.LONG_DASH); LongPT.SetLineWeight(1);
plot ShortPT = if isShort then ShortTargetPrice else Double.NaN; ShortPT.SetDefaultColor(Color.LIME); ShortPT.SetStyle(Curve.LONG_DASH); ShortPT.SetLineWeight(1);


# =================================================================
# >> FIX 2: SL/PT Text Bubbles - Show ONLY on the first bar of the trade <<
# =================================================================

# Define the first bar of an active position
def isNewPosition = if (isLong and !isLong[1]) or (isShort and !isShort[1]) then 1 else 0;

# Long Position Bubbles (Only show if new position OR if the previous bar had an open position but current one is not a closed order)
AddChartBubble(isLong and isNewPosition and showSignals, LongStopPrice, "STOP LOSS", Color.LIGHT_GRAY, yes);
AddChartBubble(isLong and isNewPosition and showSignals, LongTargetPrice, "PROFIT TARGET", Color.LIGHT_GRAY, yes);

# Short Position Bubbles
AddChartBubble(isShort and isNewPosition and showSignals, ShortStopPrice, "STOP LOSS", Color.LIGHT_GRAY, no);
AddChartBubble(isShort and isNewPosition and showSignals, ShortTargetPrice, "PROFIT TARGET", Color.LIGHT_GRAY, no);


# --- P/L and Label definitions (Calculations are unchanged) ---
def orderCount_Tracker = compoundValue(1,if isNaN(isOrder) or BarNumber()==1 then 0 else if (PLBuySignal or PLSellSignal) then orderCount_Tracker[1]+1 else orderCount_Tracker[1],0);
def orderCount = (profitWinners + profitLosers + profitPush) - 1;
def SizeFactor = PositionSize / 1;
def profitLoss;
if (!isOrder or orderPrice[1]==0){
    profitLoss = 0;
} else if ((isOrder and isLong[1]) and (PLSellSignal or PLBuyStop or PLMktStop)){
    profitLoss = close - orderPrice[1];
} else if ((isOrder and isShort[1]) and (PLBuySignal or PLSellStop or PLMktStop)) {
    profitLoss = orderPrice[1] - close;
} else {
    profitLoss = 0;
}
def profitLossSum = compoundValue(1, if isNaN(isOrder)  or BarNumber()==1 then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);
if (BarNumber()==1) OR isNaN(profitWinners[1]) {
    profitWinners = 0;
} else {
    profitWinners = if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1];
}
if (BarNumber()==1) OR isNaN(profitLosers[1]) {
    profitLosers = 0;
} else {
    profitLosers = if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1];
}
if (BarNumber()==1) OR isNaN(profitPush[1]) {
    profitPush = 0;
} else {
    profitPush = if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1];
}
def TradePL_Unscaled = If isLong then Round(((close - orderPrice)/TickSize())*TickValue()) else if isShort then Round(((orderPrice - close)/TickSize())*TickValue()) else 0;
def TradePL_Scaled = TradePL_Unscaled * SizeFactor;
def dollarProfitLoss_Unscaled = if orderPrice[1]==0 or isNaN(orderPrice[1]) then 0 else Round((profitLoss/TickSize())*TickValue());
def dollarProfitLoss = dollarProfitLoss_Unscaled * SizeFactor;
def dollarPLSum_Unscaled = Round((profitLossSum/TickSize())*TickValue());
def dollarPLSum = dollarPLSum_Unscaled * SizeFactor;
def profitLong = compoundValue(1, if isNaN(profitLong[1])  or BarNumber()==1 then 0 else if isOrder and isLong[1] then profitLong[1]+dollarProfitLoss else profitLong[1],0);
def profitShort = compoundValue(1, if isNaN(profitShort[1])  or BarNumber()==1 then 0 else if isOrder and isShort[1] then profitShort[1]+dollarProfitLoss else profitShort[1],0);
def countLong = compoundValue(1, if isNaN(countLong[1])  or BarNumber()==1 then 0 else if isOrder and isLong[1] then countLong[1]+1 else countLong[1],0);
def countShort = compoundValue(1, if isNaN(countShort[1])  or BarNumber()==1 then 0 else if isOrder and isShort[1] then countShort[1]+1 else countShort[1],0);
def biggestWin = compoundValue(1, if isNaN(biggestWin[1]) or BarNumber()==1 then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = compoundValue(1, if isNaN(biggestLoss[1]) or BarNumber()==1 then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);
def PCTWin = Round((profitWinners/orderCount)*100,2);
def avgTrade = Round((dollarPLSum/orderCount),2);

#########################################  Create Labels (FIX 1: Conditional on Input) #######################################

def showCustomLabels = if showLabels and !disableDuplicateLabels then 1 else 0; # Controls visibility of all custom labels

AddLabel(showLabels AND isIntraDay, if MarketOpen then "Market Open" else "Market Closed", color.white);
AddLabel(showLabels, GetSymbol()+" Tick Size: "+TickSize()+" Value: "+TickValue(), color.white);
AddLabel(showCustomLabels, "Closed Orders: " + orderCount + " P/L: " + AsDollars(dollarPLSum), if dollarPLSum > 0 then Color.GREEN else if dollarPLSum< 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNan(orderPrice) and showCustomLabels then 1 else 0, "Closed+Open P/L: "+ AsDollars(TradePL_Scaled+dollarPLSum), if ((TradePL_Scaled+dollarPLSum) > 0) then color.green else if ((TradePL_Scaled+dollarPLSum) < 0) then color.red else color.gray);
AddLabel(showCustomLabels, "Avg per Trade: "+ AsDollars(avgTrade), if avgTrade > 0 then Color.GREEN else if avgTrade < 0 then Color.RED else Color.GRAY);
AddLabel(showCustomLabels, "Winners: "+ PCTWin +"%",if PCTWin > 50 then color.green else if PCTWin > 40 then color.YELLOW else color.GRAY);
AddLabel(showCustomLabels, "MaxUp: "+ AsDollars(biggestWin) +" MaxDown: "+AsDollars(biggestLoss), color.WHITE);
AddLabel(showCustomLabels, "Long Profit: " +AsDollars(profitLong), if profitLong > 0 then color.GREEN else if profitLong < 0 then color.RED else color.GRAY);
AddLabel(showCustomLabels, "Short Profit: " +AsDollars(profitShort), if profitShort > 0 then color.GREEN else if profitShort < 0 then color.RED else color.GRAY);
AddLabel(if !IsNan(CurrentPosition) and showLabels then 1 else 0, "Open: "+ (If isLong then "Bought" else "Sold") + " @ "+orderPrice, color.WHITE);
AddLabel(if !IsNan(orderPrice) and showLabels then 1 else 0, "Open Trade P/L: "+ AsDollars(TradePL_Scaled), if (TradePL_Scaled > 0) then color.GREEN else if (TradePL_Scaled < 0) then color.RED else color.GRAY);

#########################################  Chart Bubbles for Profit/Loss #######################################
AddChartBubble(showSignals and showBubbles and isOrder and isLong[1], low, "$"+dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else color.RED, 0);
AddChartBubble(showSignals and showBubbles and isOrder and isShort[1], high,  "$"+dollarProfitLoss, if dollarProfitLoss == 0 then Color.LIGHT_GRAY else if dollarProfitLoss > 0 then Color.GREEN else color.RED, 1);
 

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