Strategy Test

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 11

// This source code is subject to the terms of the Mozilla Public License 2.

0 at
https://mozilla.org/MPL/2.0/
// © Samuel Ralte

//@version=5
strategy("Strategy TEST1", overlay=true, initial_capital = 1000, default_qty_type =
strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.0)

group_ut_bot2 = "UT Bot Alert"


a1 = input(3, title='Key Value . \'This changes the sensitivity\'', group =
group_ut_bot2)
c1 = input(20, title='ATR Period ',group = group_ut_bot2)
h1 = input(false, title='Signals from Heikin Ashi Candles', group = group_ut_bot2)
xATR1 = ta.atr(c1)
nLoss1 = a1 * xATR1
src1 = h1 ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period,
close, lookahead=barmerge.lookahead_off) : close
xATRTrailingStop1 = 0.0
iff_11 = src1 > nz(xATRTrailingStop1[1], 0) ? src1 - nLoss1 : src1 + nLoss1
iff_21 = src1 < nz(xATRTrailingStop1[1], 0) and src1[1] < nz(xATRTrailingStop1[1],
0) ? math.min(nz(xATRTrailingStop1[1]), src1 + nLoss1) : iff_11
xATRTrailingStop1 := src1 > nz(xATRTrailingStop1[1], 0) and src1[1] >
nz(xATRTrailingStop1[1], 0) ? math.max(nz(xATRTrailingStop1[1]), src1 - nLoss1) :
iff_21
pos1 = 0
iff_31 = src1[1] > nz(xATRTrailingStop1[1], 0) and src1 < nz(xATRTrailingStop1[1],
0) ? -1 : nz(pos1[1], 0)
pos1 := src1[1] < nz(xATRTrailingStop1[1], 0) and src1 > nz(xATRTrailingStop1[1],
0) ? 1 : iff_31
xcolor1 = pos1 == -1 ? color.red : pos1 == 1 ? color.green : color.blue
ema1 = ta.ema(src1, 1)
above1 = ta.crossover(ema1, xATRTrailingStop1)
below1 = ta.crossover(xATRTrailingStop1, ema1)
buy1 = src1 > xATRTrailingStop1 and above1
sell1 = src1 < xATRTrailingStop1 and below1
group_linear = "linear regression candle"
signal_length2 = input.int(title='Signal Smoothing', minval=1, maxval=200,
defval=6,group = group_linear)
sma_signal2 = input(title='Simple MA (Signal Line)', defval=true,group =
group_linear)
lin_reg = input(title='Lin Reg', defval=true,group = group_linear)
linreg_length = input.int(title='Linear Regression Length', minval=1, maxval=200,
defval=6,group = group_linear)
bopen = lin_reg ? ta.linreg(open, linreg_length, 0) : open
bhigh = lin_reg ? ta.linreg(high, linreg_length, 0) : high
blow = lin_reg ? ta.linreg(low, linreg_length, 0) : low
bclose = lin_reg ? ta.linreg(close, linreg_length, 0) : close
r = bopen < bclose
signal2 = sma_signal2 ? ta.sma(bclose, signal_length2) : ta.ema(bclose,
signal_length2)
plotcandle(r ? bopen : na, r ? bhigh : na, r ? blow : na, r ? bclose : na,
title='LinReg Candles', color=color.green, wickcolor=color.green,
bordercolor=color.green, editable=true)
plotcandle(r ? na : bopen, r ? na : bhigh, r ? na : blow, r ? na : bclose,
title='LinReg Candles', color=color.red, wickcolor=color.red,
bordercolor=color.red, editable=true)
buy_condition = r and bclose > signal2
sell_condition = not r and bclose < signal2
cond1 = buy_condition ? 1 : 0
cond2 = sell_condition ? 1 : 0
longCondition1 = buy1 and cond1
shortCondition1 = sell1 and cond2
plotshape(longCondition1, title='Buy', text='Buy', style=shape.labelup,
location=location.belowbar, color=color.new(color.green, 0),
textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(shortCondition1, title='Sell', text='Sell', style=shape.labeldown,
location=location.abovebar, color=color.new(color.red, 0),
textcolor=color.new(color.white, 0), size=size.tiny)
enable_supertrend = input.bool(true, "Enable Supertrend Filter", group= "
################# Supertrend ################ " )
atrPeriod = input(14, 'ATR Length', group = " ################# Supertrend
################ ")
factor = input(2, 'Factor', group = " ################# Supertrend
################ ")
time1 = input.string(title='Short Time Period', defval='05 30m', options=['01
1m','02 3m','03 5m', '04 15m', '05 30m', '06 45m', '07 1h', '08 2h', '09 3h', '10
4h', '11 1D', '12 1W' ], group = " ################# Supertrend ################
",tooltip = "this timeframe is the value of our short-time supertrend indicator")
res(Resolution) =>
if Resolution == '00 Current'
timeframe.period
else
if Resolution == '01 1m'
'1'
else
if Resolution == '02 3m'
'3'
else
if Resolution == '03 5m'
'5'
else
if Resolution == '04 15m'
'15'
else
if Resolution == '05 30m'
'30'
else
if Resolution == '06 45m'
'45'
else
if Resolution == '07 1h'
'60'
else
if Resolution == '08 2h'
'120'
else
if Resolution == '09 3h'
'180'
else
if Resolution == '10 4h'
'240'
else
if Resolution == '11 1D'
'1D'
else
if Resolution == '12 1W'
'1W'
else
if Resolution == '13 1M'
'1M'

[supertrend1, direction1] = request.security(syminfo.tickerid, res(time1),


ta.supertrend(factor, atrPeriod))
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction1 < 0 ? supertrend1 : na, 'Up Trend',
color=color.new(color.green, 0), style=plot.style_linebr)
downTrend = plot(direction1 > 0 ? supertrend1 : na, 'Down Trend',
color=color.new(color.red, 0), style=plot.style_linebr)
bool isLongSupertrendFilterEnable = enable_supertrend ? direction1 < 0 ?
supertrend1 : na : true
bool isShortSupertrendFilterEnable = enable_supertrend ? direction1 > 0 ?
supertrend1 : na : true
longCondition = longCondition1
shortCondition = shortCondition1
group_vol_osc = "volume oscillator"
enable_filter_osc = input.bool (true,"Enable VOL OSC", group =group_vol_osc)
fast_length1 = input.int(title="Fast MA Length", defval=5, minval=1,group =
group_vol_osc)
slow_length1 = input.int(title="Slow MA Length", defval=10, minval=1,group =
group_vol_osc)
fast_ma1 = ta.ema(volume, fast_length1)
slow_ma1 = ta.ema(volume, slow_length1)
osc = (fast_ma1 - slow_ma1) / slow_ma1
bool isVoloscenableAndAboveZero = enable_filter_osc ? osc > 0 : true
i_startPeriodEnabled = input.bool(true, 'Start', group='Date Range', inline='Start
Period')
i_startPeriodTime = input.time(timestamp('1 Jan 2023'), '', group='Date Range',
inline='Start Period')
i_endPeriodEnabled = input.bool(true, 'End', group='Date Range', inline='End
Period')
i_endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range',
inline='End Period')
isStartPeriodEnabledAndInRange = i_startPeriodEnabled ? i_startPeriodTime <= time :
true
isEndPeriodEnabledAndInRange = i_endPeriodEnabled ? i_endPeriodTime >= time : true
useCustomTimezone = input.bool(false, 'Custom Timezone', inline='tz',
group='Session Entry Filter')
timezoneStr = input.string("UTC", "", ["UTC-10", "UTC-8", "UTC-7", "UTC-6", "UTC-
5", "UTC-4", "UTC-3",
"UTC", "UTC+1", "UTC+2", "UTC+3",
"UTC+3:30", "UTC+4", "UTC+5", "UTC+5:30", "UTC+5:45",
"UTC+6", "UTC+6:30", "UTC+7", "UTC+8",
"UTC+9", "UTC+9:30", "UTC+10", "UTC+11", "UTC+12", "UTC+12:45", "UTC+13"],
inline='tz', group='Session Entry Filter',
tooltip='Use custom timezone. If not
selected, default chart timezone is used')
allowMon = input.bool(true, 'Mon', inline = "weekdays", group='Session Entry
Filter')
allowTue = input.bool(true, 'Tue', inline = "weekdays", group='Session Entry
Filter')
allowWed = input.bool(true, 'Wed', inline = "weekdays", group='Session Entry
Filter')
allowThu = input.bool(true, 'Thu', inline = "weekdays", group='Session Entry
Filter')
allowFri = input.bool(true, 'Fri', inline = "weekdays", group='Session Entry
Filter')
allowSat = input.bool(false, 'Sat', inline = "weekdays", group='Session Entry
Filter')
allowSun = input.bool(true, 'Sun', inline = "weekdays", group='Session Entry
Filter', tooltip = 'Filter entry based on days of the week')
filterBySession1 = input.bool(true, 'Session 1', inline='s1', group='Session Entry
Filter')
session1 = input.session("2100-0600", '', inline='s1', group='Session Entry
Filter', tooltip = 'Filter by custom session option1')
filterBySession2 = input.bool(true, 'Session 2', inline='s2', group='Session Entry
Filter')
session2 = input.session("0000-0900", '', inline='s2', group='Session Entry
Filter', tooltip = 'Filter by custom session option2')
filterBySession3 = input.bool(true, 'Session 3', inline='s3', group='Session Entry
Filter')
session3 = input.session("0700-1600", '', inline='s3', group='Session Entry
Filter', tooltip = 'Filter by custom session option3')

filterBySession4 = input.bool(true, 'Session 4', inline='s4', group='Session Entry


Filter')
session4 = input.session("1300-2200", '', inline='s4', group='Session Entry
Filter', tooltip = 'Filter by custom session option4')

forceExitOutsideSession = input.bool(true, 'Force Exit Outside Session Filter')


timezoneToUse = useCustomTimezone? timezoneStr : syminfo.timezone
allowEntry = (
(not na(time(timeframe.period, session1, timezoneToUse))?
filterBySession1:false) or
(not na(time(timeframe.period, session2, timezoneToUse))?
filterBySession2:false) or
(not na(time(timeframe.period, session3, timezoneToUse))?
filterBySession3:false) or
(not na(time(timeframe.period, session4, timezoneToUse))?
filterBySession4:false)
) and
(
(dayofweek(time, timezoneToUse) == 1? allowSun:false) or
(dayofweek(time, timezoneToUse) == 2? allowMon:false) or
(dayofweek(time, timezoneToUse) == 3? allowTue:false) or
(dayofweek(time, timezoneToUse) == 4? allowWed:false) or
(dayofweek(time, timezoneToUse) == 5? allowThu:false) or
(dayofweek(time, timezoneToUse) == 6? allowFri:false) or
(dayofweek(time, timezoneToUse) == 7? allowSat:false)
)

forceExit = forceExitOutsideSession ? not allowEntry : false


bgcolor(allowEntry? color.new(color.green, 90) : forceExit? color.new(color.red,
90) : na)

signal = allowEntry? 2 : forceExit? -2 : 0


startTradeSignal = signal == 2?2:0
stopTradeSignal= signal == -2?2:0
isStartEndPeriodsAndTimeInRange = isStartPeriodEnabledAndInRange and
isEndPeriodEnabledAndInRange//and stopTradeSignal//isTimeFilterEnabledAndInRange
//define as 0 if do not want to have a conditional close
closeLongCondition = sell1//stopTradeSignal // default: 0
closeShortCondition = buy1//stopTradeSignal // default: 0
i_tradeDirection = input.string('Long and Short', title='Trade Direction',
options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
longConditionFinal = (longCondition and isLongSupertrendFilterEnable and
isVoloscenableAndAboveZero and startTradeSignal) and i_tradeDirection != 'Short
Only' and isInLongPosition == false
shortConditionFinal = (shortCondition and isShortSupertrendFilterEnable and
isVoloscenableAndAboveZero and startTradeSignal ) and i_tradeDirection != 'Long
Only' and isInShortPosition == false
bool openingLongPosition = longConditionFinal and not
(strategy.opentrades.size(strategy.opentrades - 1) > 0)
bool openingShortPosition = shortConditionFinal and not
(strategy.opentrades.size(strategy.opentrades - 1) < 0)
bool openingAnyPosition = openingLongPosition or openingShortPosition
float closePriceWhenPositionOpened = ta.valuewhen(openingAnyPosition,close,0)
var groupStopLoss = "🛑 Stop Loss"
i_useStopLoss = input.bool (title="Use Stop Loss", defval = true,
group=groupStopLoss)
i_typeOfStopLoss = input.string (title="Type Of Stop Loss", defval="ATR",
options=["Fixed %","Last Swing High/Low","ATR"], group=groupStopLoss)
i_fixedPercentSL = input.float(title='Fixed %', defval=1, minval=0, step=0.5,
group=groupStopLoss) * 0.01
i_swingHighLowLookbackSL = input.int(21, title="Swing High/Low Lookback",
group=groupStopLoss)
i_atrLengthSL = input.int(title="ATR Length", defval=14, minval = 1,
group=groupStopLoss)
i_atrMultiplierSL = input.float(title="ATR Multiplier", defval=1.0, minval = 0,
step=0.1, group=groupStopLoss)
float fixedPercentSLPriceWhenLongPositionEntered =
ta.valuewhen(openingLongPosition,close,0) * (1 - i_fixedPercentSL)
float fixedPercentSLPriceWhenShortPositionEntered =
ta.valuewhen(openingShortPosition,close,0) * (1 + i_fixedPercentSL)
float swingLowPriceWhenLongPostionEntered = ta.valuewhen(openingLongPosition,
source = ta.lowest(low, i_swingHighLowLookbackSL), occurrence = 0)
float swingHighPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition,
source = ta.highest(high, i_swingHighLowLookbackSL), occurrence = 0)
float ATRSLPriceWhenLongPositionEntered = ta.valuewhen(openingLongPosition, close -
(ta.atr(i_atrLengthSL) * i_atrMultiplierSL) ,0)
float ATRSLPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition, close
+ (ta.atr(i_atrLengthSL) * i_atrMultiplierSL) ,0)

f_calculateStopLoss(string direction, string typeOfStopLoss) =>


// TODO init these to be 0 and "" as slPriceLong/Short is referenced by TP
Risk:Reward calculation
float slOrderClosePrice = na
string slOrderComment = na

switch typeOfStopLoss
"Fixed %" =>
slOrderClosePrice := direction == "long" ?
fixedPercentSLPriceWhenLongPositionEntered :
fixedPercentSLPriceWhenShortPositionEntered
slOrderComment := direction == "long" ? "SL Fixed % Long" : "SL Fixed %
Short"
"Last Swing High/Low" =>
slOrderClosePrice := direction == "long" ?
swingLowPriceWhenLongPostionEntered : swingHighPriceWhenShortPositionEntered
slOrderComment := direction == "long" ? "SL Swing Low Long" : "SL Swing
High Short"
"ATR" =>
slOrderClosePrice := direction == "long" ?
ATRSLPriceWhenLongPositionEntered : ATRSLPriceWhenShortPositionEntered
slOrderComment := direction == "long" ? "SL ATR Long" : "SL ATR Short"

[slOrderClosePrice,slOrderComment]

[slPriceLong, slCommentLong] = f_calculateStopLoss( "long",i_typeOfStopLoss)


[slPriceShort, slCommentShort] = f_calculateStopLoss("short",i_typeOfStopLoss)

slLongCondition = close <= slPriceLong


slShortCondition = close >= slPriceShort
var groupTakeProfit = "🟢 Take Profit"
i_useTakeProfit = input.bool (title="Use Take Profit", defval = false,
group=groupTakeProfit)
i_typeOfTakeProfit = input.string (title="Type Of Take Profit", defval="Risk:Reward
Ratio", options=["Single Fixed %","Multiple Fixed %","Risk:Reward Ratio","ATR"],
group=groupTakeProfit)
i_fixedPercentTP = input.float(title='Single Fixed %', defval=1, minval=0,
step=0.5, group=groupTakeProfit) * 0.01
i_takeProfitTargetPercent1 = input.float(title='Take Profit 1 - Target %',
defval=1, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 1')
i_takeProfitQuantityPercent1 = input.int(title='% Of Position', defval=50,
minval=0, group=groupTakeProfit, inline='Take Profit 1')
i_takeProfitTargetPercent2 = input.float(title='Take Profit 2 - Target %',
defval=2.5, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 2')
i_takeProfitQuantityPercent2 = input.int(title='% Of Position', defval=100,
minval=0, group=groupTakeProfit, inline='Take Profit 2')
i_takeProfitTargetPercent3 = input.float(title='Take Profit 3 - Target %',
defval=100, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 3')
i_takeProfitQuantityPercent3 = input.int(title='% Of Position', defval=100,
minval=0, group=groupTakeProfit, inline='Take Profit 3')
i_takeProfitTargetPercent4 = input.float(title='Take Profit 4 - Target %',
defval=100, minval=0.0, step=0.5, group=groupTakeProfit)
i_RiskRewardRatioTP = input.float(title="Risk:Reward Ratio 1:#", defval=1.0,
minval=0 , step=0.1, group=groupTakeProfit)
i_atrLengthTP = input.int(title="ATR Length", defval=14, minval = 1,
group=groupTakeProfit)
i_atrMultiplierTP = input.float(title="ATR Multiplier", defval=1, minval = 0,
step=0.1, group=groupTakeProfit)
float fixedPercentTPPriceWhenLongPositionEntered =
ta.valuewhen(openingLongPosition,close,0) * (1 + i_fixedPercentTP)
float fixedPercentTPPriceWhenShortPositionEntered =
ta.valuewhen(openingShortPosition,close,0) * (1 - i_fixedPercentTP)
tpRRPriceWhenLongPositionEntered = closePriceWhenPositionOpened +
((closePriceWhenPositionOpened - slPriceLong) * i_RiskRewardRatioTP)
tpRRPriceWhenShortPositionEntered = closePriceWhenPositionOpened +
((closePriceWhenPositionOpened - slPriceShort) * i_RiskRewardRatioTP)
float ATRTPPriceWhenLongPositionEntered = ta.valuewhen(openingLongPosition, close +
(ta.atr(i_atrLengthTP) * i_atrMultiplierTP) ,0)
float ATRTPPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition, close
- (ta.atr(i_atrLengthTP) * i_atrMultiplierTP) ,0)
f_calculateTakeProfit(string direction, string typeOfTakeProfit) =>
float tpOrderClosePrice = na
string tpOrderComment = na

switch typeOfTakeProfit
"Single Fixed %" =>
tpOrderClosePrice := direction == "long" ?
fixedPercentTPPriceWhenLongPositionEntered :
fixedPercentTPPriceWhenShortPositionEntered
tpOrderComment := direction == "long" ? "TP Single Fixed % Long" : "TP
Single Fixed % Short"
"Multiple Fixed %" =>
tpOrderClosePrice := na
tpOrderComment := ""
"Risk:Reward Ratio" =>
tpOrderClosePrice := direction == "long" ?
tpRRPriceWhenLongPositionEntered : tpRRPriceWhenShortPositionEntered
tpOrderComment := direction == "long" ? "TP R:R Long" : "TP R:R Short"
"ATR" =>
tpOrderClosePrice := direction == "long" ?
ATRTPPriceWhenLongPositionEntered : ATRTPPriceWhenShortPositionEntered
tpOrderComment := direction == "long" ? "TP ATR Long" : "TP ATR Short"

[tpOrderClosePrice,tpOrderComment]

[tpPriceLong, tpCommentLong] = f_calculateTakeProfit( "long",i_typeOfTakeProfit)


[tpPriceShort, tpCommentShort] = f_calculateTakeProfit("short",i_typeOfTakeProfit)

tpLongCondition = close >= tpPriceLong


tpShortCondition = close <= tpPriceShort

//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 *
strategy.position_avg_price / syminfo.mintick) : float(na)

i_plotTPSL=input(true, title="Plot TP and SL", group='Plotting')


slbp=plot(i_plotTPSL and i_useStopLoss and strategy.position_size > 0 ?
slPriceLong[1] : na, color=color.red, style=plot.style_linebr, title="SL")
tpbp=plot(i_plotTPSL and i_useTakeProfit and strategy.position_size > 0 ?
tpPriceLong[1] : na, color=color.lime, style=plot.style_linebr, title="TP")
epbp=plot(i_plotTPSL and strategy.position_size > 0 ? strategy.position_avg_price :
na, color=color.gray, style=plot.style_linebr, title="Entry")
fill(slbp, epbp, color=color.new(color.red, 90))
fill(tpbp, epbp, color=color.new(color.green, 90))
slsp=plot(i_plotTPSL and i_useStopLoss and strategy.position_size < 0 ?
slPriceShort[1] : na, color=color.red, style=plot.style_linebr, title="SL")
tpsp=plot(i_plotTPSL and i_useTakeProfit and strategy.position_size < 0 ?
tpPriceShort[1] : na, color=color.lime, style=plot.style_linebr, title="TP")
epsp=plot(i_plotTPSL and strategy.position_size < 0 ? strategy.position_avg_price :
na, color=color.gray, style=plot.style_linebr, title="Entry")
fill(slsp, epsp, color=color.new(color.red, 90))
fill(tpsp, epsp, color=color.new(color.green, 90))
if isStartEndPeriodsAndTimeInRange
if longConditionFinal
strategy.entry('Long', strategy.long)
// alert(message=alertSyntaxBase + 'side:long',
freq=alert.freq_once_per_bar_close)

if shortConditionFinal
strategy.entry('Short', strategy.short)
// alert(message=alertSyntaxBase + 'side:short',
freq=alert.freq_once_per_bar_close)

if i_useTakeProfit
//Inspired from Multiple %% profit exits example by adolgo
https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
if i_typeOfTakeProfit == "Multiple Fixed %"
strategy.exit('TP1', qty_percent=i_takeProfitQuantityPercent1,
profit=per(i_takeProfitTargetPercent1))
strategy.exit('TP2', qty_percent=i_takeProfitQuantityPercent2,
profit=per(i_takeProfitTargetPercent2))
strategy.exit('TP3', qty_percent=i_takeProfitQuantityPercent3,
profit=per(i_takeProfitTargetPercent3))
strategy.exit('i_takeProfitTargetPercent4',
profit=per(i_takeProfitTargetPercent4))
if tpLongCondition
strategy.close('Long', comment= 'tpCommentLong')
if tpShortCondition
strategy.close('Short', comment= 'tpCommentShort')
if i_useStopLoss
if slLongCondition
strategy.close('Long', comment='slCommentLong')
if slShortCondition
strategy.close('Short', comment= 'slCommentShort')
if closeLongCondition
strategy.close('Long', comment='Conditional Close Long')
if closeShortCondition
strategy.close('Short', comment='Conditional Close Short')

i_tableTextSize = input.string(title="Dashboard Size", defval="Small",


options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group="Dashboards")
table_text_size(s) =>
switch s
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
=> size.tiny
tableTextSize = table_text_size(i_tableTextSize)

i_showDashboard = input.bool(title="Performance Summary", defval=true,


group="Dashboards", inline="Show Dashboards")

f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>


_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor,
text_color=_txtcolor, text_size=tableTextSize)
if i_showDashboard
var bgcolor = color.new(color.black,0)

// Keep track of Wins/Losses streaks


newWin = (strategy.wintrades > strategy.wintrades[1]) and
(strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades ==
strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and
(strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades ==
strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0

if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow

if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow

// Prepare stats table


var table dashTable = table.new(position.top_right, 1, 15, border_width=1)

if barstate.islastconfirmedhistory
// Update table
lastTime = strategy.position_size == 0 ?
strategy.closedtrades.exit_time(strategy.closedtrades-1) : time
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}",
strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format("
{0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", lastTime) ,
bgcolor, color.white) // + str.format(" {0,time,HH:mm}",
strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') +
"%", _profit > 0 ? color.teal : color.maroon, color.white)
_numOfDaysInStrategy = (lastTime - strategy.closedtrades.entry_time(0)) /
(1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit /
_numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ?
color.teal : color.maroon, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate,
'##.##') + "%", _winRate < 50 ? color.maroon : _winRate < 75 ? #999900 :
color.teal, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:",
str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'),
strategy.grossprofit > strategy.grossloss ? color.teal : color.maroon, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:",
str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 7, "Winning Trades:",
str.tostring(strategy.wintrades), strategy.wintrades > strategy.losstrades ?
color.teal : color.maroon, color.white)
f_fillCell(dashTable, 0, 8, "Losing Trades:",
str.tostring(strategy.losstrades), strategy.wintrades < strategy.losstrades ?
color.teal : color.maroon, color.white)
f_fillCell(dashTable, 0, 9, "Max Wins In A Row:", str.tostring(maxWinRow,
'######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 10, "Max Losses In A Row:",
str.tostring(maxLossRow, '######') , bgcolor, color.white)
i_showMonthlyPerformance = input.bool(true, 'Monthly Performance',
group='Dashboards', inline="Show Dashboards")
i_monthlyReturnPercision = 2

if i_showMonthlyPerformance
new_month = month(time) != month(time[1])
new_year = year(time) != year(time[1])

eq = strategy.equity

bar_pnl = eq / eq[1] - 1

cur_month_pnl = 0.0
cur_year_pnl = 0.0

// Current Monthly P&L


cur_month_pnl := new_month ? 0.0 :
(1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1

// Current Yearly P&L


cur_year_pnl := new_year ? 0.0 :
(1 + cur_year_pnl[1]) * (1 + bar_pnl) - 1

// Arrays to store Yearly and Monthly P&Ls


var month_pnl = array.new_float(0)
var month_time = array.new_int(0)

var year_pnl = array.new_float(0)


var year_time = array.new_int(0)

last_computed = false

if (not na(cur_month_pnl[1]) and (new_month or


barstate.islastconfirmedhistory))
if (last_computed[1])
array.pop(month_pnl)
array.pop(month_time)

array.push(month_pnl , cur_month_pnl[1])
array.push(month_time, time[1])

if (not na(cur_year_pnl[1]) and (new_year or barstate.islastconfirmedhistory))


if (last_computed[1])
array.pop(year_pnl)
array.pop(year_time)

array.push(year_pnl , cur_year_pnl[1])
array.push(year_time, time[1])

last_computed := barstate.islastconfirmedhistory ? true : nz(last_computed[1])

// Monthly P&L Table


var monthly_table = table(na)

if (barstate.islastconfirmedhistory)
monthly_table := table.new(position.bottom_right, columns = 14, rows =
array.size(year_pnl) + 1, border_width = 1)

table.cell(monthly_table, 0, 0, "", bgcolor = #cccccc,


text_size=tableTextSize)
table.cell(monthly_table, 1, 0, "Jan", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 2, 0, "Feb", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 3, 0, "Mar", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 4, 0, "Apr", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 5, 0, "May", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 6, 0, "Jun", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 7, 0, "Jul", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 8, 0, "Aug", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 9, 0, "Sep", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 10, 0, "Oct", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 11, 0, "Nov", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 12, 0, "Dec", bgcolor = #cccccc,
text_size=tableTextSize)
table.cell(monthly_table, 13, 0, "Year", bgcolor = #999999,
text_size=tableTextSize)

for yi = 0 to array.size(year_pnl) - 1
table.cell(monthly_table, 0, yi + 1,
str.tostring(year(array.get(year_time, yi))), bgcolor = #cccccc,
text_size=tableTextSize)

y_color = array.get(year_pnl, yi) > 0 ? color.new(color.teal, transp =


40) : color.new(color.gray, transp = 40)
table.cell(monthly_table, 13, yi + 1,
str.tostring(math.round(array.get(year_pnl, yi) * 100, i_monthlyReturnPercision)),
bgcolor = y_color, text_color=color.new(color.white, 0),text_size=tableTextSize)

for mi = 0 to array.size(month_time) - 1
m_row = year(array.get(month_time, mi)) - year(array.get(year_time,
0)) + 1
m_col = month(array.get(month_time, mi))
m_color = array.get(month_pnl, mi) > 0 ? color.new(color.teal, transp =
40) : color.new(color.maroon, transp = 40)

table.cell(monthly_table, m_col, m_row,


str.tostring(math.round(array.get(month_pnl, mi) * 100, i_monthlyReturnPercision)),
bgcolor = m_color, text_color=color.new(color.white, 0), text_size=tableTextSize)

You might also like