How to create strategy for IUSmartSystem on ES futures

serendipity2020

Member
Plus
Hello

I've converted below tradingview indicator in thinkscript and would like to backtest it.

https://www.tradingview.com/script/bj6RTTnd-IU-Smart-Flow-System/

Does thinkorswim support calculations for /ES futures in backtest? Since I'd like to backtest it for /ES on 5 min timeframe, how do I write strategy that will give me profit/loss report accurately?

I'd like to implement following in strategy:

1. Trade only within US regular session.
2. If future is bought, then sell it immediately after 2 (configurable) ticks. Similarly, if sold first, buy it immediately after 2 (configurable) ticks for profit.
3. For stop loss, use the candle's low that triggered alert. Ex: If buy alert is triggered, then stop loss at low of that candle's price. If sell alert is triggered first, then stop loss at candles's high price.
4. At any given point, keep only 1 contract open so that report will never consider more than 1 contract for calculations.

I'll appreciate if someone can help in implementing this strategy!

Thanks!

Code:
declare upper;

input length = 10;                     # Imbalance length
input trendLength = 50;               # Trend length
input rsiLength = 14;                 # RSI length
input showCloud = No;

def price = close;
def bullishImbalance = Highest(price, length) - price[length];
def bearishImbalance = price[length] - Lowest(price, length);
def atr = Average(TrueRange(high, close, low), 14);
def orderFlowScore = bullishImbalance - bearishImbalance;

def bullTrend = Average(price, trendLength) + atr;
def bearTrend = Average(price, trendLength) - atr;

def trendUp = price > bullTrend;
def trendDown = price < bearTrend;

def rsi = RSI(rsiLength);

def longEntryCond = orderFlowScore > 0 and trendUp and rsi > 50;
def shortEntryCond = orderFlowScore < 0 and trendDown and rsi < 50;

# Persistent state tracking
def inLong = CompoundValue(1,
    if longEntryCond then 1
    else if shortEntryCond then 0
    else inLong[1], 0);

def inShort = CompoundValue(1,
    if shortEntryCond then 1
    else if longEntryCond then 0
    else inShort[1], 0);

def longEntry = longEntryCond and !inLong[1];
def shortEntry = shortEntryCond and !inShort[1];

# Labels
AddChartBubble(longEntry, low, "Buy", Color.GREEN, no);
AddChartBubble(shortEntry, high, "Sell", Color.RED, yes);
 
Solution
Hello @whoDAT

Thanks for the quick reply. This looks good but I'm still trying to figure out how do I make it work to take profit by configurable tick count and stop loss by configurable tickcount?

What should I put condition under PLBuyStop variable to make it work for configurable tick count loss?

In other words, could you update this script so that it will take profit immediately after say 5 ticks and stop loss would be at 2 ticks?

Thanks!
I believe this ties your strategy to the P/L script.

I added the # of limit and stop ticks as input variables.

Enjoy!

Code:
declare upper;

input length = 10;                     # Imbalance length
input trendLength = 50;               # Trend length
input rsiLength = 14...
I recommend @JoeDV 's very neat Potential P/L Study.

https://usethinkscript.com/threads/potential-p-l-from-study-for-thinkorswim.8884/post-148987

Add these 2 lines below your study.
def BuySignal = longEntry;
def SellSignal = shortEntry;

Then copy/paste JoeDV's study below those 2 lines.
Hello @whoDAT

Thanks for the quick reply. This looks good but I'm still trying to figure out how do I make it work to take profit by configurable tick count and stop loss by configurable tickcount?

What should I put condition under PLBuyStop variable to make it work for configurable tick count loss?

In other words, could you update this script so that it will take profit immediately after say 5 ticks and stop loss would be at 2 ticks?

Thanks!
 
Last edited:
Hello @whoDAT

Thanks for the quick reply. This looks good but I'm still trying to figure out how do I make it work to take profit by configurable tick count and stop loss by configurable tickcount?

What should I put condition under PLBuyStop variable to make it work for configurable tick count loss?

In other words, could you update this script so that it will take profit immediately after say 5 ticks and stop loss would be at 2 ticks?

Thanks!
I believe this ties your strategy to the P/L script.

I added the # of limit and stop ticks as input variables.

Enjoy!

Code:
declare upper;

input length = 10;                     # Imbalance length
input trendLength = 50;               # Trend length
input rsiLength = 14;                 # RSI length
input showCloud = No;

def price = close;
def bullishImbalance = Highest(price, length) - price[length];
def bearishImbalance = price[length] - Lowest(price, length);
def atr = Average(TrueRange(high, close, low), 14);
def orderFlowScore = bullishImbalance - bearishImbalance;

def bullTrend = Average(price, trendLength) + atr;
def bearTrend = Average(price, trendLength) - atr;

def trendUp = price > bullTrend;
def trendDown = price < bearTrend;

def rsi = RSI(rsiLength);

def longEntryCond = orderFlowScore > 0 and trendUp and rsi > 50;
def shortEntryCond = orderFlowScore < 0 and trendDown and rsi < 50;

# Persistent state tracking
def inLong = CompoundValue(1,
    if longEntryCond then 1
    else if shortEntryCond then 0
    else inLong[1], 0);

def inShort = CompoundValue(1,
    if shortEntryCond then 1
    else if longEntryCond then 0
    else inShort[1], 0);

def BuySignal = longEntryCond and !inLong[1];
def SellSignal = shortEntryCond and !inShort[1];

input LimitTicks = 3;
input StopTicks = 2;

def BuyPrice = close;

def Limit = BuyPrice + (LimitTicks * TickSize());
def Stop = BuyPrice - (StopTicks * TickSize());


###------------------------------------------------------------------------------------------
# Profit and Loss Labels
#
# Set two variables Buysignal and Sellsignal to your buy and sell signal conditions,
# or replace them below with your 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 stopLimitDisplay = 50;  #hint stopLimit in dollars
input useAlerts = no;    #hint useAlerts: use alerts on signals
input tradeDefinedHours = no; #hint tradeDefinedHours:
input OpenTime = 0900; #hint OpenTime: Opening time of market
input CloseTime = 1600; #hint CloseTime: Closing time of market
input UseFuturesFees = no; #hint UseFutureFees: $6 round-trip

#Get actual trading time
def TradingHours = GetTime() between RegularTradingStart(GetYYYYMMDD()) and RegularTradingEnd(GetYYYYMMDD());

#Get time to do trading
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 TradingWindow = if !tradeDefinedHours or !isIntraDay then 1 else if tradeDefinedHours and isIntraDay and Begin > 0 and End > 0 then 1 else 0;
###------------------------------------------------------------------------------------------

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

def PLBuySignal = if  TradingWindow and (Buysignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal =  if TradingWindow and (Sellsignal) then 1 else 0; # insert condition to create short position in place of the 0>0

def PLBuyStop  = if !useStops then 0 else if  (Limit > close) then 1 else 0  ; # insert condition to stop in place of the 0<0
def PLSellStop = if !useStops then 0 else if (Stop < close) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLMktStop = if TradingWindow[-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);

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

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


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

def orderPrice = if (isOrder and ((BuySig and LongTrades) or (SellSig and ShortTrades))) then (if IsNaN(open[-1]) then close else open[-1]) else orderPrice[1];

plot OPL = if !isFlat and isLong then orderPrice else Double.NaN;
OPL.AssignValueColor(Color.GREEN);
OPL.SetPaintingStrategy(PaintingStrategy.LINE);
OPL.SetStyle(Curve.SHORT_DASH);
OPL.SetLineWeight(1);

#addcloud(OPL,close,color.red, color.green);

plot OPS = if !isFlat and isShort then orderPrice else Double.NaN;
OPS.AssignValueColor(Color.RED);
OPS.SetPaintingStrategy(PaintingStrategy.LINE);
OPS.SetStyle(Curve.SHORT_DASH);
OPS.SetLineWeight(1);

#addcloud(OPS,close,color.green, color.red);

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 = (if IsNaN(open[-1]) then close else open[-1]) - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
    profitLoss = orderPrice[1] - (if IsNaN(open[-1]) then close else open[-1]);
} 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());
def maxUpSum = CompoundValue(1, if IsNaN(maxUpSum[1]) or BarNumber() == 1 then 0 else if dollarPLSum > 0 and dollarPLSum > maxUpSum[1] then dollarPLSum else maxUpSum[1], 0);
def maxDnSum = CompoundValue(1, if IsNaN(maxDnSum[1]) or BarNumber() == 1 then 0 else if dollarPLSum < 0 and dollarPLSum < maxDnSum[1] then dollarPLSum else maxDnSum[1], 0);

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

def FuturesCommission = 6 * ClosedTradeCount;


# 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, if TradingHours then "Market Open" else "Market Closed", Color.WHITE);
AddLabel(showLabels and tradeDefinedHours, "Defined Hours", Color.WHITE);
AddLabel(showLabels and tradeDefinedHours, "Trade between: "+AsPrice(OpenTime)+" and "+AsPrice(CloseTime),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 (UseFuturesFees), "Future Fees Incl", Color.WHITE);

AddLabel(showLabels, "Closed Orders: " + ClosedTradeCount + " P/L: " + AsDollars(dollarPLSum - if UseFuturesFees then FuturesCommission else 0), 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 UseFuturesFees then FuturesCommission else 0), if ((TradePL + dollarPLSum) > 0) then Color.GREEN else if ((TradePL + dollarPLSum - if UseFuturesFees then FuturesCommission else 0) < 0) then Color.RED else Color.GRAY);

AddLabel(showLabels, "Avg per Trade: " + AsDollars(avgTrade  - if UseFuturesFees then 6 else 0), 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, "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(showLabels, "MaxUpTrade: " + AsDollars(biggestWin) + " MaxDownTrade: " + AsDollars(biggestLoss), Color.WHITE);
AddLabel(showLabels, "MaxUpPL: " + AsDollars(maxUpSum) + " MaxDownPL: " + AsDollars(maxDnSum), Color.WHITE);

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

plot BuyStopLvl =  if isLong then OrderPrice - ((stopLimitDisplay/TickValue())*TickSize()) else double.nan;
plot ShortStopLvl =  if isShort then OrderPrice + ((stopLimitDisplay/TickValue())*TickSize()) else double.nan;
BuyStopLvl.AssignValueColor(Color.YELLOW);
BuyStopLvl.SetPaintingStrategy(PaintingStrategy.LINE);
BuyStopLvl.SetStyle(Curve.SHORT_DASH);
BuyStopLvl.SetLineWeight(1);
ShortStopLvl.AssignValueColor(Color.YELLOW);
ShortStopLvl.SetPaintingStrategy(PaintingStrategy.LINE);
ShortStopLvl.SetStyle(Curve.SHORT_DASH);
ShortStopLvl.SetLineWeight(1);

#######################################
##  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);
 
Solution
I believe this ties your strategy to the P/L script.

I added the # of limit and stop ticks as input variables.

Enjoy!

Code:
declare upper;

input length = 10;                     # Imbalance length
input trendLength = 50;               # Trend length
input rsiLength = 14;                 # RSI length
input showCloud = No;

def price = close;
def bullishImbalance = Highest(price, length) - price[length];
def bearishImbalance = price[length] - Lowest(price, length);
def atr = Average(TrueRange(high, close, low), 14);
def orderFlowScore = bullishImbalance - bearishImbalance;

def bullTrend = Average(price, trendLength) + atr;
def bearTrend = Average(price, trendLength) - atr;

def trendUp = price > bullTrend;
def trendDown = price < bearTrend;

def rsi = RSI(rsiLength);

def longEntryCond = orderFlowScore > 0 and trendUp and rsi > 50;
def shortEntryCond = orderFlowScore < 0 and trendDown and rsi < 50;

# Persistent state tracking
def inLong = CompoundValue(1,
    if longEntryCond then 1
    else if shortEntryCond then 0
    else inLong[1], 0);

def inShort = CompoundValue(1,
    if shortEntryCond then 1
    else if longEntryCond then 0
    else inShort[1], 0);

def BuySignal = longEntryCond and !inLong[1];
def SellSignal = shortEntryCond and !inShort[1];

input LimitTicks = 3;
input StopTicks = 2;

def BuyPrice = close;

def Limit = BuyPrice + (LimitTicks * TickSize());
def Stop = BuyPrice - (StopTicks * TickSize());


###------------------------------------------------------------------------------------------
# Profit and Loss Labels
#
# Set two variables Buysignal and Sellsignal to your buy and sell signal conditions,
# or replace them below with your 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 stopLimitDisplay = 50;  #hint stopLimit in dollars
input useAlerts = no;    #hint useAlerts: use alerts on signals
input tradeDefinedHours = no; #hint tradeDefinedHours:
input OpenTime = 0900; #hint OpenTime: Opening time of market
input CloseTime = 1600; #hint CloseTime: Closing time of market
input UseFuturesFees = no; #hint UseFutureFees: $6 round-trip

#Get actual trading time
def TradingHours = GetTime() between RegularTradingStart(GetYYYYMMDD()) and RegularTradingEnd(GetYYYYMMDD());

#Get time to do trading
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 TradingWindow = if !tradeDefinedHours or !isIntraDay then 1 else if tradeDefinedHours and isIntraDay and Begin > 0 and End > 0 then 1 else 0;
###------------------------------------------------------------------------------------------

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

def PLBuySignal = if  TradingWindow and (Buysignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal =  if TradingWindow and (Sellsignal) then 1 else 0; # insert condition to create short position in place of the 0>0

def PLBuyStop  = if !useStops then 0 else if  (Limit > close) then 1 else 0  ; # insert condition to stop in place of the 0<0
def PLSellStop = if !useStops then 0 else if (Stop < close) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLMktStop = if TradingWindow[-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);

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

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


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

def orderPrice = if (isOrder and ((BuySig and LongTrades) or (SellSig and ShortTrades))) then (if IsNaN(open[-1]) then close else open[-1]) else orderPrice[1];

plot OPL = if !isFlat and isLong then orderPrice else Double.NaN;
OPL.AssignValueColor(Color.GREEN);
OPL.SetPaintingStrategy(PaintingStrategy.LINE);
OPL.SetStyle(Curve.SHORT_DASH);
OPL.SetLineWeight(1);

#addcloud(OPL,close,color.red, color.green);

plot OPS = if !isFlat and isShort then orderPrice else Double.NaN;
OPS.AssignValueColor(Color.RED);
OPS.SetPaintingStrategy(PaintingStrategy.LINE);
OPS.SetStyle(Curve.SHORT_DASH);
OPS.SetLineWeight(1);

#addcloud(OPS,close,color.green, color.red);

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 = (if IsNaN(open[-1]) then close else open[-1]) - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
    profitLoss = orderPrice[1] - (if IsNaN(open[-1]) then close else open[-1]);
} 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());
def maxUpSum = CompoundValue(1, if IsNaN(maxUpSum[1]) or BarNumber() == 1 then 0 else if dollarPLSum > 0 and dollarPLSum > maxUpSum[1] then dollarPLSum else maxUpSum[1], 0);
def maxDnSum = CompoundValue(1, if IsNaN(maxDnSum[1]) or BarNumber() == 1 then 0 else if dollarPLSum < 0 and dollarPLSum < maxDnSum[1] then dollarPLSum else maxDnSum[1], 0);

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

def FuturesCommission = 6 * ClosedTradeCount;


# 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, if TradingHours then "Market Open" else "Market Closed", Color.WHITE);
AddLabel(showLabels and tradeDefinedHours, "Defined Hours", Color.WHITE);
AddLabel(showLabels and tradeDefinedHours, "Trade between: "+AsPrice(OpenTime)+" and "+AsPrice(CloseTime),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 (UseFuturesFees), "Future Fees Incl", Color.WHITE);

AddLabel(showLabels, "Closed Orders: " + ClosedTradeCount + " P/L: " + AsDollars(dollarPLSum - if UseFuturesFees then FuturesCommission else 0), 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 UseFuturesFees then FuturesCommission else 0), if ((TradePL + dollarPLSum) > 0) then Color.GREEN else if ((TradePL + dollarPLSum - if UseFuturesFees then FuturesCommission else 0) < 0) then Color.RED else Color.GRAY);

AddLabel(showLabels, "Avg per Trade: " + AsDollars(avgTrade  - if UseFuturesFees then 6 else 0), 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, "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(showLabels, "MaxUpTrade: " + AsDollars(biggestWin) + " MaxDownTrade: " + AsDollars(biggestLoss), Color.WHITE);
AddLabel(showLabels, "MaxUpPL: " + AsDollars(maxUpSum) + " MaxDownPL: " + AsDollars(maxDnSum), Color.WHITE);

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

plot BuyStopLvl =  if isLong then OrderPrice - ((stopLimitDisplay/TickValue())*TickSize()) else double.nan;
plot ShortStopLvl =  if isShort then OrderPrice + ((stopLimitDisplay/TickValue())*TickSize()) else double.nan;
BuyStopLvl.AssignValueColor(Color.YELLOW);
BuyStopLvl.SetPaintingStrategy(PaintingStrategy.LINE);
BuyStopLvl.SetStyle(Curve.SHORT_DASH);
BuyStopLvl.SetLineWeight(1);
ShortStopLvl.AssignValueColor(Color.YELLOW);
ShortStopLvl.SetPaintingStrategy(PaintingStrategy.LINE);
ShortStopLvl.SetStyle(Curve.SHORT_DASH);
ShortStopLvl.SetLineWeight(1);

#######################################
##  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);
Oh, and not bad.. 61% winning percentage on SPX for the past 10 days.
+15% return in two weeks on only 12 trades.
spxx.jpg
 
Oh, and not bad.. 61% winning percentage on SPX for the past 10 days.
+15% return in two weeks on only 12 trades.
View attachment 24613
Thanks @whoDAT But something is not right. I tried changing values for limit ticks and stop ticks but no matter what values I put, it shows same P/L. Note that I've set defined NY trading hours between 9:30 to 4 PM and useStop set to Yes. Would it also be possible to print buy and sell price in chart bubble on each purchase and sell so that it will be easier to debug?
 
Thanks @whoDAT But something is not right. I tried changing values for limit ticks and stop ticks but no matter what values I put, it shows same P/L. Note that I've set defined NY trading hours between 9:30 to 4 PM and useStop set to Yes. Would it also be possible to print buy and sell price in chart bubble on each purchase and sell so that it will be easier to debug.

I see that the limits aren't changing the output. I see that @JoeDV hardcoded dollar value limits instead of ticks. I'm not into options at all. There's probably an easy trick to tick limits that I'm unaware. (In other words, I feel I'm over my head on your request at this time to develop this further.)
 

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