help improving backtesting strategy

ewaynem

New member
Hi, ive been a lurker for a long time and have used pieces of code from here to try to develop a winning trading strategy (unsuccessful yet). but I came across this "backtest" code that has been helpful, but it only closes the trade when the ATR stop is reached. Id like to add code to this to be able to set a specific profit take or a specific stop loss or the ATR stop , whichever one comes first, to better understand which strategy works best for my goals. but I don't know how to code that.

its currently part of an ema cross over strategy that I don't think works, but I included the entire script for completeness. mostly interested in adding the specific profit take and stop loss to the code in addition to the ATR stop . creating buy or sell signals when trying to incorporate above or below ichimoku cloud levels doesn't seem to work either if anyone can identify the reasoning that would also be helpful. I also haven't been able to figure out how to add a "pull back strategy" to the code (ie, there is a 9/21 ema cross over and then within the next 4 bars, price crosses back over the 9 ema again then it creates the buy or sell signal), so if you know how to do that too, please let me know.

thanks again for your help and insights.

Code:
##combined 9 and 21 ema cross over

input ShowVerticalLine = yes;
input ma_type = {SMA, EMA, WMA, HullMA, VWMA, RMA, default TEMA};
input useChartTimeframeForSlowMa = {default "Yes", "No"};
input manualSlowMaTimeframe = AggregationPeriod.FIFTEEN_MIN;
input slow_ma_period = 21; # "Slow MA Period"
input useChartTimeframeForFastMa = {default "Yes", "No"};
input manualFastMaTimeframe = AggregationPeriod.FIFTEEN_MIN;
input fast_ma_period = 9; # "Fast MA Period"
input price = close;
input data = close;
input length = 10;
input displace = 0;
input nFE = 8;#hint nFE: length for Fractal Energy calculation.
input Glength  = 13;
input betaDev =  8;
input tenkan_period = 9;
input kijun_period = 26;

def ema = ExpAverage(price[-displace], length);
def ema9 = ExpAverage (price, length = 9);
def ema21 = ExpAverage (price, length = 21);
def ema50 = ExpAverage (price, length = 50);
def ema200 = ExpAverage (price, length = 200);
def adxFilter = ADX(length = 14) > 15;
def iv = imp_volatility();
def highiv = iv > 0.30; # Example condition for high IV


# Define Ichimoku Cloud components
def Tenkan = (Highest(high, tenkan_period) + Lowest(low, tenkan_period)) / 2;
def Kijun = (Highest(high, kijun_period) + Lowest(low, kijun_period)) / 2;
def "Span A" = (Tenkan[kijun_period] + Kijun[kijun_period]) / 2;
def "Span B" = (Highest(high[kijun_period], 2 * kijun_period) + Lowest(low[kijun_period], 2 * kijun_period)) / 2;
def Chikou = close[-kijun_period];

# Determine the boundaries of the cloud
def cloudTop = Max("Span A", "Span B");   # Top of the cloud (whichever is greater)
def cloudBottom = Min("Span A", "Span B");# Bottom of the cloud (whichever is lower)


def na = Double.NaN;

def c;
def v;
def l;
def h;
def c1;
def v1;

switch (useChartTimeframeForSlowMa) {
case "Yes" :
    c = close;
    v = volume;
    l = low;
    h = high;
case "No" :
    c = close(Period = manualSlowMaTimeframe);
    v = volume(Period = manualSlowMaTimeframe);
    l = low(Period = manualSlowMaTimeframe);
    h = high(Period = manualSlowMaTimeframe);
}
switch (useChartTimeframeForFastMa) {
case "Yes" :
    c1 = close;
    v1 = volume;
case "No" :
    c1 = close(Period = manualFastMaTimeframe);
    v1 = volume(Period = manualFastMaTimeframe);
}

#get_ma(src, ma_type, len) =>
script get_ma {
    input src = close;
    input ma_type = "TEMA";
    input len = 100;
    input v = Volume;

    def hullma = HullMovingAvg(src, len);
    def vwma = Average(src * v, len) / Average(v, len);
    def ema1 = ExpAverage(src, len);
    def ema2 = ExpAverage(ema1, len);
    def ema3 = ExpAverage(ema2, len);
    def tema = 3 * (ema1 - ema2) + ema3;
    def ma = if ma_type == "SMA" then Average(src, len) else
if ma_type == "EMA" then ExpAverage(src, len) else
if ma_type == "WMA" then WMA(src, len) else
if ma_type == "HullMA" then hullma else
if ma_type == "VWMA" then vwma else
if ma_type == "RMA" then WildersAverage(src, len) else tema;
    plot out = ma;
}

#// Calculate Fast and Slow Moving averages
def fast_ma = get_ma(c1, ma_type, fast_ma_period, v1);
def slow_ma = get_ma(c, ma_type, slow_ma_period, v);
def slow_ma_up = slow_ma > slow_ma[1];
def slow_ma_dn = slow_ma < slow_ma[1];

#// Buy signal: MA Crossover, with slow MA trending upwards
#def buy = crosses(fast_ma, slow_ma, CrossingDirection.ABOVE) and slow_ma_up;
#def buyabove = close > open and low < low[1] and high < high[1] and close > ema and ema > ema20 and ema20 > ema50;
#def sellbelow = close < open and low > low[1] and high > high[1] and close < ema and ema < ema20 and ema20 < ema50;
#def crossBelow9Next3Bars = (low[0] < ema9[0] or  low[-1] < ema9[-1] or  low[-2] < ema9[-2]);

#def crossAbove9Next3Bars =  (high[0] > ema9[0] or  high[-1] > ema9[-1] or  high[-2] > ema9[-2]);

#  price is above Ichimoku Cloud
def ICbuySignal = close > cloudTop;

# price is below Ichimoku Cloud
def ICsellSignal = close < cloudBottom;

def buy = ((fast_ma > slow_ma) and (fast_ma[1] <= slow_ma[1]) and slow_ma_up);
def sell = ((fast_ma < slow_ma) and (fast_ma[1] >= slow_ma[1]) and slow_ma_dn);

#// Low-pass filter to avoid generating too many consecutive orders
def checkbuy = buy and !buy[1] and !buy[2] and !buy[3] and !buy[4] and !buy[5] and !buy[6];
def checksell = sell and !sell[1] and !sell[2] and !sell[3] and !sell[4] and !sell[5] and !sell[6];
def buy_signal = checkbuy;
def sell_signal = checksell;



def bull = buy_signal;
def bear = sell_signal;

def upsignal = bull;
def downsignal = bear;
#UpSignal.SetDefaultColor(Color.UPTICK);
#UpSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#DownSignal.SetDefaultColor(Color.DOWNTICK);
#DownSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

###------------------------------------------------------------------------------------------
# Profit and Loss Labels
#
# Fill in the 0>0 in the Create Signals section below to match your buy and sell signal conditions
#
# When using large amounts of hisorical data, P/L may take time to calculate
###------------------------------------------------------------------------------------------

input showSignals = yes; #hint showSignals: show buy and sell arrows
input LongTrades = yes; #hint LongTrades: perform long trades
input ShortTrades = yes; #hint ShortTrades: perform short trades
input showLabels  = yes; #hint showLabels: show PL labels at top
input showBubbles = yes; #hint showBubbles: show PL bubbles at close of trade
input useStops = no;     #hint useStops: use stop orders
input useAlerts = no;    #hint useAlerts: use alerts on signals
input tradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input OpenTime = 2100; #hint OpenTime: Opening time of market
input CloseTime = 2300; #hint CloseTime: Closing time of market

#----- ATR Trail ----
input trailType = {default modified, unmodified};
input ATRPeriod = 10;
input ATRFactor = 1.75;
input firstTrade = {default long, short};
input averageType = { default WILDERS, SIMPLE, EXPONENTIAL, HULL, WEIGHTED};

plot ATRStop = ATRTrailingStop(trailType, ATRPeriod, ATRFactor, firstTrade, averageType);

#---------------------


def Begin = SecondsFromTime(OpenTime);
def End = SecondsTillTime(CloseTime);
# Only use market hours when using intraday timeframe
def isIntraDay = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen = if !tradeDaytimeOnly or !isIntraDay then 1 else if tradeDaytimeOnly and isIntraDay and Begin > 0 and End > 0 then 1 else 0;
###------------------------------------------------------------------------------------------

##fractal energy and RSI langerhans
def w = (2 * Double.Pi / Glength);
def beta = (1 - Cos(w)) / (Power(1.414, 2.0 / betaDev) - 1 );
def alpha = (-beta + Sqrt(beta * beta + 2 * beta));
def Go = Power(alpha, 4) * open +
             4 * (1 – alpha) * Go[1] – 6 * Power( 1 - alpha, 2 ) * Go[2] +
             4 * Power( 1 - alpha, 3 ) * Go[3] - Power( 1 - alpha, 4 ) * Go[4];
def Gh = Power(alpha, 4) * high +
             4 * (1 – alpha) * Gh[1] – 6 * Power( 1 - alpha, 2 ) * Gh[2] +
             4 * Power( 1 - alpha, 3 ) * Gh[3] - Power( 1 - alpha, 4 ) * Gh[4];
def Gl = Power(alpha, 4) * low +
             4 * (1 – alpha) * Gl[1] – 6 * Power( 1 - alpha, 2 ) * Gl[2] +
             4 * Power( 1 - alpha, 3 ) * Gl[3] - Power( 1 - alpha, 4 ) * Gl[4];
def Gc = Power(alpha, 4) * data +
             4 * (1 – alpha) * Gc[1] – 6 * Power( 1 - alpha, 2 ) * Gc[2] +
             4 * Power( 1 - alpha, 3 ) * Gc[3] - Power( 1 - alpha, 4 ) * Gc[4];
# Variables:
def o;
def q;
def r;
def s;
def CU1;
def CU2;
def CU;
def CD1;
def CD2;
def CD;
def L0;
def L1;
def L2;
def L3;
def RSI;


# Calculations
o = (Go + Gc[1]) / 2;
q = Max(Gh, Gc[1]);
r = Min(Gl, Gc[1]);
s = (o + h + l + Gc) / 4;
def gamma = Log(Sum((Max(Gh, Gc[1]) - Min(Gl, Gc[1])), nFE) /
        (Highest(Gh, nFE) - Lowest(Gl, nFE)))
            / Log(nFE);

L0 = (1 – gamma) * Gc + gamma * L0[1];
L1 = -gamma * L0 + L0[1] + gamma * L1[1];
L2 = -gamma * L1 + L1[1] + gamma * L2[1];
L3 = -gamma * L2 + L2[1] + gamma * L3[1];
if L0 >= L1
then {
    CU1 = L0 - L1;
    CD1 = 0;
} else {
    CD1 = L1 - L0;
    CU1 = 0;
}
if L1 >= L2
then {
    CU2 = CU1 + L1 - L2;
    CD2 = CD1;
} else {
    CD2 = CD1 + L2 - L1;
    CU2 = CU1;
}
if L2 >= L3
then {
    CU = CU2 + L2 - L3;
    CD = CD2;
} else {
    CU = CU2;
    CD = CD2 + L3 - L2;
}

RSI = if CU + CD <> 0 then CU / (CU + CD) else 0;
def rsiFilterBuy = rsi < .8;
def rsiFilterSell = rsi > .2;

######################################################
##  Create Signals -
##  FILL IN THIS SECTION
##      replace 0>0 with your conditions for signals
######################################################

def PLBuySignal = if  MarketOpen and (upsignal) and (ATRStop < close) and (rsiFilterBuy) AND (gamma > .4) then 1 else 0 ; # insert condition to create long position in place of the 0>0
#AND (rsiFilterBuy) AND (gamma > .4) AND ICbuySignal
# may consider these limits as well AND (volume>100) AND (highiv)
 
 
def PLSellSignal =  if MarketOpen and (downsignal) and (ATRStop > close) AND (rsiFilterSell) AND (gamma > .4) then 1 else 0; # insert condition to create short position in place of the 0>0
#AND (rsiFilterSell) AND (gamma > .4) AND ICsellSignal
#AND may consider these limits as well (volume>100) AND (highiv)


def PLBuyStop  = if !useStops then 0 else if (ATRStop > close ) then 1 else 0  ; # insert condition to stop in place of the 0<0
def PLSellStop = if !useStops then 0 else if (ATRStop < close ) then 1 else 0  ; # insert condition to stop in place of the 0>0

def PLMktStop = if MarketOpen[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day


#######################################
##  Maintain the position of trades
#######################################

def CurrentPosition;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
} else {
    if CurrentPosition[1] == 0 {            # FLAT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == 1 {      # LONG
        if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else if ((PLBuyStop and useStops) or PLMktStop or (PLSellSignal and ShortTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == -1 {     # SHORT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if ((PLSellStop and useStops) or PLMktStop or (PLBuySignal and LongTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else {
        CurrentPosition = CurrentPosition[1];
    }
}


def isLong  = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat  = if CurrentPosition == 0 then 1 else 0;

# If not already long and get a PLBuySignal
#Plot BuySig = if (!isLong[1] and PLBuySignal and showSignals and LongTrades) then 1 else 0;
plot BuySig = if (((isShort[1] and LongTrades) or (isFlat[1] and LongTrades)) and PLBuySignal and showSignals) then 1 else 0;
BuySig.AssignValueColor(Color.CYAN);
BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySig.SetLineWeight(5);

Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);

# If not already short and get a PLSellSignal
plot SellSig = if (((isLong[1] and ShortTrades) or (isFlat[1] and ShortTrades)) and PLSellSignal and showSignals) then 1 else 0;
SellSig.AssignValueColor(Color.CYAN);
SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSig.SetLineWeight(5);

Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);
Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);

#####calculate specefic profit takes before ATR spot hits
# Calculate 20-tick (5-point) profit target for NQ (1 tick = 0.25 points, so 20 ticks = 5 points)
def tick_size = 0.25;
def profit_target_ticks = 20;
def profit_target = profit_target_ticks * tick_size;

# Define profit stop condition (exit if price moves up 5 points from entry price for a long trade)
def profitStopbuy = close >= PLBuySignal + profit_target;
def profitStopsell = close <= PLsellSignal + profit_target;

# Add the profit stop condition to the existing stop logic
def ProfitTakeStopbuy = if isLong[1] and profitStopbuy then 1 else 0;
def ProfitTakeStopsell = if isShort[1] and profitStopsell then 1 else 0;

# If long and get a PLBuyStop
plot BuyStpSig = if (PLBuyStop and isLong[1] and showSignals and useStops) or (isLong[1] and PLMktStop) or (isLong[1] and PLSellSignal and !ShortTrades) then 1 else 0;
##or (isLong[1] and profitStopbuy)
BuyStpSig.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(3);

Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);


# If short and get a PLSellStop
plot SellStpSig = if (PLSellStop and isShort[1] and showSignals and useStops) or (isShort[1] and PLMktStop) or (isShort[1] and PLBuySignal and !LongTrades) then 1 else 0;
##or (isShort[1] and profitStopsell)
SellStpSig.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(3);

Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);


#######################################
##  Orders
#######################################

def isOrder = if ((isFlat[1] and (BuySig and LongTrades) or (SellSig and ShortTrades)) or (isLong[1] and BuyStpSig or (SellSig and ShortTrades)) or (isShort[1] and SellStpSig or (BuySig and LongTrades))) then 1 else 0 ;
# If there is an order, then the price is the next days close
def orderPrice = if (isOrder and ((BuySig and LongTrades) or (SellSig and ShortTrades))) then close else orderPrice[1];

def orderCount = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if (BuySig or SellSig) then orderCount[1] + 1 else orderCount[1], 0);


#######################################
##  Price and Profit
#######################################

def profitLoss;


if (!isOrder or orderPrice[1] == 0) {
    profitLoss = 0;
} else if ((isOrder and isLong[1]) and (SellSig or BuyStpSig)) {
    profitLoss = close - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
    profitLoss = orderPrice[1] - close;
} else {
    profitLoss = 0;
}


# Total Profit or Loss
def profitLossSum = CompoundValue(1, if IsNaN(isOrder)  or BarNumber() == 1 then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);

# How many trades won or lost
def profitWinners = CompoundValue(1, if IsNaN(profitWinners[1]) or BarNumber() == 1 then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = CompoundValue(1, if IsNaN(profitLosers[1])  or BarNumber() == 1 then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = CompoundValue(1, if IsNaN(profitPush[1])  or BarNumber() == 1 then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);

# Current Open Trade Profit or Loss
def TradePL = if isLong then Round(((close - orderPrice) / TickSize()) * TickValue()) else if isShort then Round(((orderPrice - close) / TickSize()) * TickValue()) else 0;

# Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss = if orderPrice[1] == 0 or IsNaN(orderPrice[1]) then 0 else Round((profitLoss / TickSize()) * TickValue());

# Closed Orders dollar P/L
def dollarPLSum = Round((profitLossSum / TickSize()) * TickValue());


# Split profits or losses by long and short trades
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);

# What was the biggest winning and losing trade
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 ClosedTradeCount = if (isLong or isShort) then orderCount - 1 else orderCount;
def OpenTrades = if (isLong or isShort) then 1 else 0;


# What percent were winners
def PCTWin = if (OpenTrades and (TradePL < 0)) then Round((profitWinners / (ClosedTradeCount + 1)) * 100, 2)
else if (OpenTrades and (TradePL > 0)) then Round(((profitWinners + 1) / (ClosedTradeCount + 1)) * 100, 2) else Round(((profitWinners) / (ClosedTradeCount)) * 100, 2) ;

# Average trade
def avgTrade = if (OpenTrades and (TradePL < 0)) then Round(((dollarPLSum - TradePL) / (ClosedTradeCount + 1)), 2)
else if (OpenTrades and (TradePL > 0)) then Round(((dollarPLSum + TradePL) / (ClosedTradeCount + 1)), 2) else Round(((dollarPLSum) / (ClosedTradeCount)), 2) ;


#######################################
##  Create 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(showLabels and (LongTrades and ShortTrades), "Long+Short Trades", Color.WHITE);
AddLabel(showLabels and (LongTrades and !ShortTrades), "Long Trades Only", Color.WHITE);
AddLabel(showLabels and (!LongTrades and ShortTrades), "Short Trades Only", Color.WHITE);
AddLabel(showLabels and (tradeDaytimeOnly), "Daytime Only", Color.WHITE);
AddLabel(showLabels, "Closed Orders: " + ClosedTradeCount + " 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 showLabels then 1 else 0, "Closed+Open P/L: " + AsDollars(TradePL + dollarPLSum), if ((TradePL + dollarPLSum) > 0) then Color.GREEN else if ((TradePL + dollarPLSum) < 0) then Color.RED else Color.GRAY);

AddLabel(showLabels, "Avg per Trade: " + AsDollars(avgTrade), if avgTrade > 0 then Color.GREEN else if avgTrade < 0 then Color.RED else Color.GRAY);
AddLabel(showLabels, "Winners: " + PCTWin + "%", if PCTWin > 50 then Color.GREEN else if PCTWin > 40 then Color.YELLOW else Color.GRAY);

AddLabel(showLabels, "MaxUp: " + AsDollars(biggestWin) + " MaxDown: " + AsDollars(biggestLoss), Color.WHITE);
AddLabel(showLabels, "Long Profit: " + AsDollars(profitLong), if profitLong > 0 then Color.GREEN else if profitLong < 0 then Color.RED else Color.GRAY);
AddLabel(showLabels, "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 and OpenTrades then 1 else 0, "Open: " + (if isLong then "Bought" else "Sold") + " @ " + orderPrice, Color.WHITE);
AddLabel(if !IsNaN(orderPrice) and showLabels and OpenTrades then 1 else 0, "Open Trade P/L: " + AsDollars(TradePL), if (TradePL > 0) then Color.GREEN else if (TradePL < 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);

#AssignPriceColor(if CurrentPosition == 1 then color.green else if CurrentPosition == -1 then color.red else color.gray);;

#// Plot color: Green if fast MA higher than slow MA
def col = fast_ma >= slow_ma;
plot FastMovingAverage = fast_ma;#, title="Fast Moving Average"
plot SlowMovingAverage = slow_ma;#, title="Slow Moving Average"

FastMovingAverage.SetLineWeight(2);
FastMovingAverage.AssignValueColor(if col then Color.GREEN else Color.RED);
SlowMovingAverage.AssignValueColor(if col then Color.GREEN else Color.RED);

#AddChartBubble(buy_signal, l, "Buy", Color.GREEN, no);
#AddChartBubble(sell_signal, h, "Sell", Color.RED, yes);

AddVerticalLine(ShowVerticalLine and PLBuySignal, "Buy", Color.GREEN, Curve.SHORT_DASH);
AddVerticalLine(ShowVerticalLine and PLSellSignal, "Sell", Color.RED, Curve.SHORT_DASH);
 

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