Reinvest FloatingPL on Multiple Candle Strategy For ThinkOrSwim

esolis2014

New member
Hello,

I’ve been working on thinkscript for a while and although I’m no expert, I have managed to patch together a group of strategies to be used primary on /NQ, using Daily Candles (AggregationPeriod.DAY)

My strategy has a sub-routine where it gets the PnL of itself and then calculates how many contracts the strategy can use, based on the margin requirements specified.

My question is: When I use the backtesting (and FloatingPL) for /NQ and 10 year time interval, the reinvest doesn’t seem to work correctly, the FloatingPL results changes each time y press apply.

Is there something that can be done to fix this?

Also feel free to check, use, test and comment the rest of the strategy if there is anything that can be added or modded to make it a better strategy.

Should work fine with /NQ and /ES.

The setup looks like this: https://tos.mx/A7JRCjQ

Code:
#Designed by esolis 2021
#Credits to:
#Heiken Ashi Strategy:
# Software modified by Pete Hahn for #L.J.Jedrychowski
# Leslie Jedrychowski V 7.0 2grn HA bars after a HA red bar.
#SpectrumBarsLE
# TD Ameritrade IP Company, Inc. (c) 2011-2021
#As soon as I find info on the authors I based this script on, I will update the credits here.

#---------- Strategy Inputs -----------
# Reinvesting parameters
def contracts = 2;
def FPL = FPL();
def MarginReq = 20000;
#Defining reinvesting param.
def reinvestcontracts = rounddown(FPL[1]/MarginReq, 0);
def incrementalFPL = if IsNaN(reinvestcontracts) then incrementalFPL[+1] else reinvestcontracts; #MAX(FPL, minFPL)

def YesOrNoReinvest;

input ReinvestPnL = {default NoReinvestPnL, ReinvestPnL};
#hint ReinvestPnL: Defines if the cumulative profit (PnL) can be reinvested.
switch (ReinvestPnL) {
case NoReinvestPnL:
    YesOrNoReinvest = contracts;
case ReinvestPnL:
    YesOrNoReinvest = Max (incrementalFPL, contracts);
}
def tradeSize = YesOrNoReinvest;
#--------------------------------------
#-----esolis 50 or 200 day SMA limit---
def averageType = AverageType.SIMPLE;
def SMAPrice = FundamentalType.CLOSE;
input lengthSMAday = 50; #It can be 200 too
def aggregationPeriod = AggregationPeriod.DAY;
#def SMA200day = MovingAverage(averageType, SMAPrice, length200day);
def DailySMA = Average(fundamental(SMAPrice, period = aggregationPeriod), lengthSMAday);
#--------------------------------------
#--------- Strategy Open Selection-----


#SpectrumBarsLE Buy Strategy
def lengthSpectrumBarsLE = 5;
def buySpectrumBarsLE = close > close[lengthSpectrumBarsLE];

#Heiken_Ashi Buy Strategy
def haClose = ohlc4;
def haOpen = if haOpen[1] == 0 then haClose[1] else (haOpen[1] + haClose[1]) / 2;
def haHigh = Max(high, Max(haClose, haOpen));
def haLow = Min(low, Min(haClose, haOpen));
def greenCandle = haClose > haOpen;
#def redCandle = haClose < haOpen;
#Heiken_Ashi Buy Strategy Original
def trendUp = greenCandle and greenCandle[1] and !greenCandle[2];
#def trendDown = redCandle and redCandle[1] and !redCandle[2]; #not used here
#Heiken_Ashi Buy Strategy Modified by esolis
def trendUp_mod = greenCandle[0]; #Added by esolis
#def trendDown_mod = redCandle[0]; #Added by esolis #not used here

#ReversalCandleOpen
def redbar = open > close;
def buyReversalCandle =
#   (open[2] > close[2] and close[1] > high[2])
#   or (open[3] > close[3] and open[2] < close[2] and close[2] < open[3] and  close[1] > (high[3] or high[2]));

    (open[1] > close[1] and close > high[1]) or
    (open[2] > close[2] and close > high[2]) or
    (open[3] > close[3] and close > high[3]) or
    (open[4] > close[4] and close > high[4]) or
    (open[5] > close[5] and close > high[5]);

#def price = if IsNaN(entryPrice[1]) then entryPrice else if !IsNaN(entryPrice) then Max(high, price[1]) else entryPrice;

#    if (open[1] > close[1] and high[0] > high[1], yes,
#    if (open[2] > close[2] and high[0] > high[2], yes,
#    if (open[3] > close[3] and high[0] > high[3], yes,
#    if (open[4] > close[4] and high[0] > high[4], yes,
#    if (open[5] > close[5] and high[0] > high[5], yes, no)))));

#def reversalCandleBuyPrice =
#    if (open[1] > close[1] and high > high[1], high[1],
#    if (open[2] > close[2] and high > high[2], high[2],
#    if (open[3] > close[3] and high > high[3], high[3],
#    if (open[4] > close[4] and high > high[4], high[4],
#    if (open[5] > close[5] and high > high[5], high[5], open[-1])))));

input OpenStrategy = {default SpectrumBarsLE, GreenHeikenAshi_Original, GreenHeikenAshi_Modified, ReversalCandleOpen};

def buyStratSignal;
def stratBuyPrice;
def buyPrice = stratBuyPrice;

switch (OpenStrategy) {
case SpectrumBarsLE:
    buyStratSignal =  buySpectrumBarsLE;
    stratBuyPrice = open[-1];
case GreenHeikenAshi_Original:
    buyStratSignal = trendUp; #Heiken_Ashi trendUp_Original
    stratBuyPrice = open[-1];
case GreenHeikenAshi_Modified:
    buyStratSignal = trendUp_mod; #Heiken_Ashi trendUp_Modified by esolis
    stratBuyPrice = open[-1];
case ReversalCandleOpen:
    buyStratSignal = buyReversalCandle; #buySigReversal
    stratBuyPrice = open[-1];
}

input SMAbuyBlock = {default No_SMA, With_SMA};
def buySignal;
switch (SMAbuyBlock) {
case No_SMA:
    buySignal = buyStratSignal;
case With_SMA:
    buySignal = buyStratSignal and (close[1] > DailySMA); #for v1
}

AddOrder(OrderType.BUY_TO_OPEN, buySignal[0], price = buyPrice, tradeSize = tradeSize, tickcolor = GetColor(1), name = "buy", arrowcolor = GetColor(1));

AddLabel(1, "Buy Strategy = " + OpenStrategy + " - " + SMAbuyBlock, Color.LIGHT_GREEN);
#--------------------------------------
#--------- Strategy Close Selection----


#Heiken_Ashi Close Strategy
def haRedClose = ohlc4;
def haRedOpen = if haRedOpen[1] == 0 then haRedClose[1] else (haRedOpen[1] + haRedClose[1]) / 2;
def redCandleClose = haRedClose < haRedOpen;

input CloseStrategy = {default ReversalCandle, RedHeikenAshi, InsideBarExit};

def closeSignal;
def stratClosePrice;
def sellPrice = stratClosePrice;

switch (CloseStrategy) {
case ReversalCandle: #I know this might repaint but it works somehow.
    closeSignal = close[0] < low[1]; # Low[-1] #close[0] < low[1]; #closeSigReversalCandle
    stratClosePrice = open[-1]; #low[0]
case RedHeikenAshi:
    closeSignal = redCandleClose and redCandleClose[1] and !redCandleClose[2]; #Heiken_Ashi trendDown
    stratClosePrice = open[-1];
case InsideBarExit:
    closeSignal = high < high[1] and low > low[1] and close < open ; #sellInsideBarExit
    stratClosePrice = open[-1];
}

AddOrder(OrderType.SELL_TO_CLOSE, closeSignal[0], price = sellPrice, name = "close", CreateColor(249, 233, 167));

AddLabel(2, "Close Strategy = " + CloseStrategy, Color.LIGHT_ORANGE );
#--------------------------------------
#----------- Strategy Win/Loss Ratio---
#This plots a label to identify the win/loss ratio
def longPrice = CompoundValue(1,
    if !longPrice[1] && buySignal[-1] then buyPrice
    else if longPrice[1] && closeSignal[-1] then 0
    else longPrice[1]
    , 0
);
def shortPrice = CompoundValue(1,
    if !shortPrice[1] && closeSignal[-1] then sellPrice
    else if shortPrice[1] && buySignal[-1] then 0
    else shortPrice[1]
    , 0
);
def wincntr = CompoundValue(1,
    if longPrice[1] && closeSignal[-1] && sellPrice > longPrice[1] then wincntr[1] + 1
    else if shortPrice[1] && buySignal[-1] && shortPrice[1] > buyPrice then wincntr[1] + 1
    else wincntr[1]
    , 0
);
def winNum = if IsNaN(wincntr) then winNum[1] else wincntr ;
def losscntr = CompoundValue(1,
    if longPrice[1] && closeSignal[-1] && sellPrice <= longPrice[1] then losscntr[1] + 1
    else if shortPrice[1] && buySignal[-1] && shortPrice[1] <= buyPrice then losscntr[1] + 1
    else losscntr[1]
    , 0
);
def lossNum = if IsNaN(losscntr) then lossNum[1] else losscntr ;

AddLabel(1,
    Concat( "Win ratio: ",
    Concat( Round( 100 * winNum / (winNum + lossNum), 1),
    Concat( "% of ", winNum + lossNum))),
        Color.CYAN);
AddLabel(2,
    Concat( "Contracts: ",
    Concat( reinvestcontracts,
    Concat( " est.", " Qty."))),
        Color.CYAN);
#--------------------------------------
#--------------------------------------
 
Last edited:
Give this a shot, I already have a similar routine that I run in my live strategies.

You have to define a start date and set the FPL to a beginning amount on that date with 2 AddOrder Lines.
Make sure the bar of the start date is displayed on the chart.
without-reinvest.png


I adjusted your margin requirements to actual requirements for /NQ.
Code:
#Designed by esolis 2021
#Credits to:
#Heiken Ashi Strategy:
# Software modified by Pete Hahn for #L.J.Jedrychowski
# Leslie Jedrychowski V 7.0 2grn HA bars after a HA red bar.
#SpectrumBarsLE
# TD Ameritrade IP Company, Inc. (c) 2011-2021
#As soon as I find info on the authors I based this script on, I will update the credits here.

###########################################################################
#Code edit by Svanoy - Set FPL to beginning amount.
#Define Date to start strategy (Chart must display bar for date specified.)
input StartDate = 20120206;

def Days = DaysFromDate(StartDate);
def StartAmount = 46750.00;
def TickSize = .25;
def TickValue = 5.00;

AddOrder(OrderType.BUY_TO_OPEN, condition = Days == 0, price = close, tradeSize = 1, tickcolor = Color.WHITE, arrowcolor = Color.WHITE);
AddOrder(OrderType.SELL_TO_CLOSE, condition = Days == 0, price = ((StartAmount/TickValue)*TickSize) + close, tradeSize = 1, tickcolor = Color.WHITE, arrowcolor = Color.WHITE);
###########################################################################


#---------- Strategy Inputs -----------
# Reinvesting parameters
def contracts = 2;
def FPL = FPL();
#Svanoy updated margin requirements for 2 contracts.
def MarginReq = 46750.00;
#Defining reinvesting param.
def reinvestcontracts = rounddown(FPL[1]/MarginReq, 0);
def incrementalFPL = if IsNaN(reinvestcontracts) then incrementalFPL[+1] else reinvestcontracts; #MAX(FPL, minFPL)

def YesOrNoReinvest;

input ReinvestPnL = {default NoReinvestPnL, ReinvestPnL};
#hint ReinvestPnL: Defines if the cumulative profit (PnL) can be reinvested.
switch (ReinvestPnL) {
case NoReinvestPnL:
    YesOrNoReinvest = contracts;
case ReinvestPnL:
    YesOrNoReinvest = Max (incrementalFPL, contracts);
}
def tradeSize = YesOrNoReinvest;
#--------------------------------------
#-----esolis 50 or 200 day SMA limit---
def averageType = AverageType.SIMPLE;
def SMAPrice = FundamentalType.CLOSE;
input lengthSMAday = 50; #It can be 200 too
def aggregationPeriod = AggregationPeriod.DAY;
#def SMA200day = MovingAverage(averageType, SMAPrice, length200day);
def DailySMA = Average(fundamental(SMAPrice, period = aggregationPeriod), lengthSMAday);
#--------------------------------------
#--------- Strategy Open Selection-----


#SpectrumBarsLE Buy Strategy
def lengthSpectrumBarsLE = 5;
def buySpectrumBarsLE = close > close[lengthSpectrumBarsLE];

#Heiken_Ashi Buy Strategy
def haClose = ohlc4;
def haOpen = if haOpen[1] == 0 then haClose[1] else (haOpen[1] + haClose[1]) / 2;
def haHigh = Max(high, Max(haClose, haOpen));
def haLow = Min(low, Min(haClose, haOpen));
def greenCandle = haClose > haOpen;
#def redCandle = haClose < haOpen;
#Heiken_Ashi Buy Strategy Original
def trendUp = greenCandle and greenCandle[1] and !greenCandle[2];
#def trendDown = redCandle and redCandle[1] and !redCandle[2]; #not used here
#Heiken_Ashi Buy Strategy Modified by esolis
def trendUp_mod = greenCandle[0]; #Added by esolis
#def trendDown_mod = redCandle[0]; #Added by esolis #not used here

#ReversalCandleOpen
def redbar = open > close;
def buyReversalCandle =
#   (open[2] > close[2] and close[1] > high[2])
#   or (open[3] > close[3] and open[2] < close[2] and close[2] < open[3] and  close[1] > (high[3] or high[2]));

    (open[1] > close[1] and close > high[1]) or
    (open[2] > close[2] and close > high[2]) or
    (open[3] > close[3] and close > high[3]) or
    (open[4] > close[4] and close > high[4]) or
    (open[5] > close[5] and close > high[5]);

#def price = if IsNaN(entryPrice[1]) then entryPrice else if !IsNaN(entryPrice) then Max(high, price[1]) else entryPrice;

#    if (open[1] > close[1] and high[0] > high[1], yes,
#    if (open[2] > close[2] and high[0] > high[2], yes,
#    if (open[3] > close[3] and high[0] > high[3], yes,
#    if (open[4] > close[4] and high[0] > high[4], yes,
#    if (open[5] > close[5] and high[0] > high[5], yes, no)))));

#def reversalCandleBuyPrice =
#    if (open[1] > close[1] and high > high[1], high[1],
#    if (open[2] > close[2] and high > high[2], high[2],
#    if (open[3] > close[3] and high > high[3], high[3],
#    if (open[4] > close[4] and high > high[4], high[4],
#    if (open[5] > close[5] and high > high[5], high[5], open[-1])))));

input OpenStrategy = {default SpectrumBarsLE, GreenHeikenAshi_Original, GreenHeikenAshi_Modified, ReversalCandleOpen};

def buyStratSignal;
def stratBuyPrice;
def buyPrice = stratBuyPrice;

switch (OpenStrategy) {
case SpectrumBarsLE:
    buyStratSignal =  buySpectrumBarsLE;
    stratBuyPrice = open[-1];
case GreenHeikenAshi_Original:
    buyStratSignal = trendUp; #Heiken_Ashi trendUp_Original
    stratBuyPrice = open[-1];
case GreenHeikenAshi_Modified:
    buyStratSignal = trendUp_mod; #Heiken_Ashi trendUp_Modified by esolis
    stratBuyPrice = open[-1];
case ReversalCandleOpen:
    buyStratSignal = buyReversalCandle; #buySigReversal
    stratBuyPrice = open[-1];
}

input SMAbuyBlock = {default No_SMA, With_SMA};
def buySignal;
switch (SMAbuyBlock) {
case No_SMA:
    buySignal = buyStratSignal;
case With_SMA:
    buySignal = buyStratSignal and (close[1] > DailySMA); #for v1
}

######################################################
#Code edit by Svanoy
#Added condition to not buy before start date.
AddOrder(OrderType.BUY_TO_OPEN, buySignal[0] and Days >= 0, price = buyPrice, tradeSize = tradeSize, tickcolor = GetColor(1), name = "buy", arrowcolor = GetColor(1));
#######################################################

AddLabel(1, "Buy Strategy = " + OpenStrategy + " - " + SMAbuyBlock, Color.LIGHT_GREEN);
#--------------------------------------
#--------- Strategy Close Selection----


#Heiken_Ashi Close Strategy
def haRedClose = ohlc4;
def haRedOpen = if haRedOpen[1] == 0 then haRedClose[1] else (haRedOpen[1] + haRedClose[1]) / 2;
def redCandleClose = haRedClose < haRedOpen;

input CloseStrategy = {default ReversalCandle, RedHeikenAshi, InsideBarExit};

def closeSignal;
def stratClosePrice;
def sellPrice = stratClosePrice;

switch (CloseStrategy) {
case ReversalCandle: #I know this might repaint but it works somehow.
    closeSignal = close[0] < low[1]; # Low[-1] #close[0] < low[1]; #closeSigReversalCandle
    stratClosePrice = open[-1]; #low[0]
case RedHeikenAshi:
    closeSignal = redCandleClose and redCandleClose[1] and !redCandleClose[2]; #Heiken_Ashi trendDown
    stratClosePrice = open[-1];
case InsideBarExit:
    closeSignal = high < high[1] and low > low[1] and close < open ; #sellInsideBarExit
    stratClosePrice = open[-1];
}

######################################################
#Code edit by Svanoy
#Added condition to not sell before start date.
AddOrder(OrderType.SELL_TO_CLOSE, closeSignal[0] and Days >= 0, price = sellPrice, name = "close", CreateColor(249, 233, 167));
######################################################

AddLabel(2, "Close Strategy = " + CloseStrategy, Color.LIGHT_ORANGE );
#--------------------------------------
#----------- Strategy Win/Loss Ratio---
#This plots a label to identify the win/loss ratio
def longPrice = CompoundValue(1,
    if !longPrice[1] && buySignal[-1] then buyPrice
    else if longPrice[1] && closeSignal[-1] then 0
    else longPrice[1]
    , 0
);
def shortPrice = CompoundValue(1,
    if !shortPrice[1] && closeSignal[-1] then sellPrice
    else if shortPrice[1] && buySignal[-1] then 0
    else shortPrice[1]
    , 0
);
def wincntr = CompoundValue(1,
    if longPrice[1] && closeSignal[-1] && sellPrice > longPrice[1] then wincntr[1] + 1
    else if shortPrice[1] && buySignal[-1] && shortPrice[1] > buyPrice then wincntr[1] + 1
    else wincntr[1]
    , 0
);
def winNum = if IsNaN(wincntr) then winNum[1] else wincntr ;
def losscntr = CompoundValue(1,
    if longPrice[1] && closeSignal[-1] && sellPrice <= longPrice[1] then losscntr[1] + 1
    else if shortPrice[1] && buySignal[-1] && shortPrice[1] <= buyPrice then losscntr[1] + 1
    else losscntr[1]
    , 0
);
def lossNum = if IsNaN(losscntr) then lossNum[1] else losscntr ;

AddLabel(1,
    Concat( "Win ratio: ",
    Concat( Round( 100 * winNum / (winNum + lossNum), 1),
    Concat( "% of ", winNum + lossNum))),
        Color.CYAN);
AddLabel(2,
    Concat( "Contracts: ",
    Concat( reinvestcontracts,
    Concat( " est.", " Qty."))),
        Color.CYAN);
#--------------------------------------
#--------------------------------------

Also, FPL does not account for RT cost.
You will need to adjust your sell price to adjust FPL for RT cost.
 
Thanks for this. I have tried to add pieces of this code to my strategies to reinvest the Profits/Losses of each trade in the report, but I have been unsuccessful.

Is it possible to add a universal code to any strategy that makes the strategy buy the maximum amount of shares possible while reinvesting the profits/losses of each trade?

For example, we would start with totalcash of $2,000, then buy the max shares for the next trade with that totalcash, then either add to or subtract from the totalcash the P/L for the trade, then buy the max shares for the next trade with that totalcash, then either add to or subtract from the totalcash the P/L for the trade, and repeat like this until the end of the strategy.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Thread starter Similar threads Forum Replies Date
S Multiple Windicator Chart Setups For ThinkOrSwim Strategies & Chart Setups 18

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
580 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