0% found this document useful (0 votes)
346 views14 pages

Mizo Trading Strategy Overview

Uploaded by

fcgh383
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
346 views14 pages

Mizo Trading Strategy Overview

Uploaded by

fcgh383
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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

0 at
[Link]
// © Samuel Ralte
// whatsapp = 8787604374

//@version=5
strategy("Samuel Ralte(MIZO)", overlay=true,initial_capital = 1000,
default_qty_type = strategy.percent_of_equity, currency =
[Link],default_qty_value = 100, commission_value = 0.0)

// Get user settings


sensitivity = [Link](1.4, "Sensitivity (1-6)", 1, 6, group="BUY & SELL
SIGNALS", tooltip = "1-6 thleng a set [Link] ah chuan 3.5 aia sang in set
suh")
offsetSignal = [Link](5, "Signals Offset", 0, group="BUY & SELL
SIGNALS",tooltip = "hei chu pawihmawh lo..Buy/Sell signal lan na hlat zawng set
na")
groupMACD = "MACD Filter"
//filterMACD = [Link](true, "Enable MACD Filter", group=groupMACD,tooltip =
"MACD settings...On/Off in awmzia awmlo hemi strategy ah chuan/turning on or off
deosn't effect a thing,cause i use as 1 of the main indicator in this strategy")
fast_length = input(title="Fast Length", defval=34, group=groupMACD)
slow_length = input(title="Slow Length", defval=55, group=groupMACD)
//src = input(title="Source", defval=close)
src = close
signal_length = [Link](title="Signal Smoothing", minval = 1, maxval = 50,
defval = 9, group=groupMACD)
sma_source = [Link](title="Oscillator MA Type", defval="EMA",
options=["SMA", "EMA"], group=groupMACD)
sma_signal = [Link](title="Signal Line MA Type", defval="EMA",
options=["SMA", "EMA"], group=groupMACD)
enable_supertrend = [Link](false, "Enable Supertrend Filter", group= "
################# Supertrend ################ ",tooltip = "Filter atan Supertrend
i hmang duh em?...I hman/ON chuan LONG-SuperTend chunga price a awm in a Execute
ang...Short - LONG Opposite" )
atrPeriod = input(10, 'ATR Length', group = " ################# Supertrend
################ ")
factor = input(3, 'Factor', group = " ################# Supertrend
################ ")
time1 = [Link](title='Multi Timeframe', defval='04 15m', 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 ################ ")
i_emaFilterEnabled = [Link](defval = true , title = "Enable EMA Filter",
tooltip = "Filter atan EMA i hmang duh em?...i ON chuan- Price EMA hnuai a awmin
SHORT,EMA chunga price a awmin LONG a EXECUTE ang...", group ="EMA Filter" )
i_emaLength = [Link](21, title="EMA Length", minval=1, group ="EMA Filter")
i_emaSource = [Link](close,"EMA Source" , group ="EMA Filter")
i_adxFilterEnabled = [Link](defval = true , title = "Enable ADX Filter",
tooltip = "ADX Filter i hmang duh em?...i ON chuan- ADX in ADX threshold a cross ah
emaw a threshold chunga a awm chiahin Long/Short a Enter ang", group ="ADX
Filter" )
i_adxVariant = [Link]('MASANAKAMURA', title='ADX Variant',
options=['ORIGINAL', 'MASANAKAMURA'], group ="ADX Filter" )
i_adxSmoothing = [Link](14, title="ADX Smoothing", group="ADX Filter")
i_adxDILength = [Link](14, title="DI Length", group="ADX Filter")
i_adxLowerThreshold = [Link](7, title="ADX Threshold", step=.5, group="ADX
Filter")
i_timeFilterEnabled = [Link](defval = false , title = "Enable Time-Of-Day
Window", tooltip = "Limit the time of day for trade execution", group ="Time
Window" )
i_timeZone = [Link](title="Select Local Time Zone", defval="GMT-5",
options=["GMT-8","GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1",
"GMT", "GMT+1", "GMT+2",
"GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GM
T+12","GMT+13"], group="Time Window")
i_betweenTime = [Link]('0700-0900', title = "Time Filter", group="Time
Window") // '0000-0000' is anytime to enter
var groupStopLoss = "🛑 Stop Loss"
i_useStopLoss = [Link] (title="Use Stop Loss", defval = true,
group=groupStopLoss)
i_typeOfStopLoss = [Link] (title="Type Of Stop Loss", defval="ATR",
options=["Fixed %","Last Swing High/Low","ATR"], group=groupStopLoss)
i_fixedPercentSL = [Link](title='Fixed %', defval=1, minval=0, step=0.5,
group=groupStopLoss) * 0.01
i_swingHighLowLookbackSL = [Link](21, title="Swing High/Low Lookback",
group=groupStopLoss)
i_atrLengthSL = [Link](title="ATR Length", defval=14, minval = 1, inline="ATR
SL", group=groupStopLoss)
i_atrMultiplierSL = [Link](title="ATR Multiplier", defval=2, minval = 0,
step=0.1, inline="ATR SL", group=groupStopLoss)
i_startPeriodEnabled = [Link](true, 'Start', group='Date Range', inline='Start
Period')
i_startPeriodTime = [Link](timestamp('1 Jan 2019'), '', group='Date Range',
inline='Start Period')
i_endPeriodEnabled = [Link](true, 'End', group='Date Range', inline='End
Period')
i_endPeriodTime = [Link](timestamp('31 Dec 2030'), '', group='Date Range',
inline='End Period')
var groupTakeProfit = "🟢 Take Profit"
i_useTakeProfit = [Link] (title="Use Take Profit", defval = true,
group=groupTakeProfit)
i_typeOfTakeProfit = [Link] (title="Type Of Take Profit", defval="Multiple
Fixed %", options=["Single Fixed %","Multiple Fixed %","Risk:Reward Ratio","ATR"],
group=groupTakeProfit)
i_fixedPercentTP = [Link](title='Single Fixed %', defval=1, minval=0,
step=0.5, group=groupTakeProfit) * 0.01
i_takeProfitTargetPercent1 = [Link](title='Take Profit 1 - Target %',
defval=1.1, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 1')
i_takeProfitQuantityPercent1 = [Link](title='% Of Position', defval=30,
minval=0, group=groupTakeProfit, inline='Take Profit 1')
i_takeProfitTargetPercent2 = [Link](title='Take Profit 2 - Target %',
defval=2, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 2')
i_takeProfitQuantityPercent2 = [Link](title='% Of Position', defval=100,
minval=0, group=groupTakeProfit, inline='Take Profit 2')
i_takeProfitTargetPercent3 = [Link](title='Take Profit 3 - Target %',
defval=100, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 3')
i_takeProfitQuantityPercent3 = [Link](title='% Of Position', defval=100,
minval=0, group=groupTakeProfit, inline='Take Profit 3')
i_takeProfitTargetPercent4 = [Link](title='Take Profit 4 - Target %',
defval=100, minval=0.0, step=0.5, group=groupTakeProfit)
i_RiskRewardRatioTP = [Link](title="Risk:Reward Ratio 1:#", defval=1.8,
minval=0 , step=0.1, group=groupTakeProfit)
i_atrLengthTP = [Link](title="ATR Length", defval=14, minval = 1, inline="ATR
TP", group=groupTakeProfit)
i_atrMultiplierTP = [Link](title="ATR Multiplier", defval=1, minval = 0,
step=0.1, inline="ATR TP", group=groupTakeProfit)

// Functions
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = [Link]([Link](x - x[1]), t)
smoothrng = [Link](avrng, wper) * m
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r
: x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
percWidth(len, perc) => ([Link](len) - [Link](len)) * perc / 100
securityNoRep(sym, res, src) => [Link](sym, res, src, barmerge.gaps_off,
barmerge.lookahead_on)
swingPoints(prd) =>
pivHi = [Link](prd, prd)
pivLo = [Link] (prd, prd)
last_pivHi = [Link](pivHi, pivHi, 1)
last_pivLo = [Link](pivLo, pivLo, 1)
hh = pivHi and pivHi > last_pivHi ? pivHi : na
lh = pivHi and pivHi < last_pivHi ? pivHi : na
hl = pivLo and pivLo > last_pivLo ? pivLo : na
ll = pivLo and pivLo < last_pivLo ? pivLo : na
[hh, lh, hl, ll]
f_chartTfInMinutes() =>
float _resInMinutes = [Link] * (
[Link] ? 1 :
[Link] ? 1. :
[Link] ? 60. * 24 :
[Link] ? 60. * 24 * 7 :
[Link] ? 60. * 24 * 30.4375 : na)
f_kc(src, len, sensitivity) =>
basis = [Link](src, len)
span = [Link](len)
[basis + span * sensitivity, basis - span * sensitivity]
wavetrend(src, chlLen, avgLen) =>
esa = [Link](src, chlLen)
d = [Link]([Link](src - esa), chlLen)
ci = (src - esa) / (0.015 * d)
wt1 = [Link](ci, avgLen)
wt2 = [Link](wt1, 3)
[wt1, wt2]
f_top_fractal(src) => src[4] < src[2] and src[3] < src[2] and src[2] > src[1] and
src[2] > src[0]
f_bot_fractal(src) => src[4] > src[2] and src[3] > src[2] and src[2] < src[1] and
src[2] < src[0]
f_fractalize (src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit) =>
fractalTop = f_fractalize(src) > 0 and src[2] >= topLimit ? src[2] : na
fractalBot = f_fractalize(src) < 0 and src[2] <= botLimit ? src[2] : na
highPrev = [Link](fractalTop, src[2], 0)[2]
highPrice = [Link](fractalTop, high[2], 0)[2]
lowPrev = [Link](fractalBot, src[2], 0)[2]
lowPrice = [Link](fractalBot, low[2], 0)[2]
bearSignal = fractalTop and high[2] > highPrice and src[2] < highPrev
bullSignal = fractalBot and low[2] < lowPrice and src[2] > lowPrev
[bearSignal, bullSignal]
// Get components
source = close
smrng1 = smoothrng(source, 27, 1.5)
smrng2 = smoothrng(source, 55, sensitivity)
smrng = (smrng1 + smrng2) / 2
filt = rngfilt(source, smrng)
up = 0.0, up := filt > filt[1] ? nz(up[1]) + 1 : filt < filt[1] ? 0 :
nz(up[1])
dn = 0.0, dn := filt < filt[1] ? nz(dn[1]) + 1 : filt > filt[1] ? 0 :
nz(dn[1])
bullCond = bool(na), bullCond := source > filt and source > source[1] and up > 0
or source > filt and source < source[1] and up > 0
bearCond = bool(na), bearCond := source < filt and source < source[1] and dn > 0
or source < filt and source > source[1] and dn > 0
lastCond = 0, lastCond := bullCond ? 1 : bearCond ? -1 : lastCond[1]
bull = bullCond and lastCond[1] == -1
bear = bearCond and lastCond[1] == 1
countBull = [Link](bull)
countBear = [Link](bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
rsi = [Link](close, 21)
rsiOb = rsi > 70 and rsi > [Link](rsi, 10)
rsiOs = rsi < 30 and rsi < [Link](rsi, 10)
dHigh = securityNoRep([Link], "D", high [1])
dLow = securityNoRep([Link], "D", low [1])
dClose = securityNoRep([Link], "D", close[1])

// Colors
cyan = #00DBFF, cyan30 = [Link](cyan, 70)
pink = #E91E63, pink30 = [Link](pink, 70)
red = #FF5252, red30 = [Link](red , 70)
// Plot
off = percWidth(300, offsetSignal)
// plotshape(bull ? low - off : na, "Buy Label" , [Link] ,
[Link], cyan, 0, "B" , [Link], size=[Link])
// plotshape(bear ? high + off : na, "Sell Label", [Link],
[Link], pink, 0, "S", [Link], size=[Link])

// Calculating
fast_ma = sma_source == "SMA" ? [Link](src, fast_length) : [Link](src, fast_length)
slow_ma = sma_source == "SMA" ? [Link](src, slow_length) : [Link](src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? [Link](macd, signal_length) : [Link](macd,
signal_length)
hist = macd - signal
buy = hist > 0
sell = hist < 0

long = bull and buy


short = bear and sell
// plotshape(long ? low - off : na, "Buy Label" , [Link] ,
[Link], cyan, 0, "Buy" , [Link], size=[Link])
// plotshape(short ? high + off : na, "Sell Label", [Link],
[Link], pink, 0, "Sell", [Link], size=[Link])

res(Resolution) =>
if Resolution == '00 Current'
[Link]
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] = [Link]([Link], res(time1),
[Link](factor, atrPeriod))
bodyMiddle = plot((open + close) / 2, display=[Link])
upTrend = plot(direction1 < 0 ? supertrend1 : na, 'Up Trend',
color=[Link]([Link], 0), style=plot.style_linebr)
downTrend = plot(direction1 > 0 ? supertrend1 : na, 'Down Trend',
color=[Link]([Link], 0), style=plot.style_linebr)
bool isLongSupertrendFilterEnable = enable_supertrend ? direction1 < 0 ?
supertrend1 : na : true
bool isShortSupertrendFilterEnable = enable_supertrend ? direction1 > 0 ?
supertrend1 : na : true
longCondition = long ? low - off : na
shortCondition = short ? high + off : na
plotshape(longCondition, "Buy Label" , [Link] , [Link], cyan, 0,
"Buy" , [Link], size=[Link])
plotshape(shortCondition, "Sell Label", [Link], [Link], pink,
0, "Sell", [Link], size=[Link])

//close long and short condition


closeLongCondition = false // default: 0
closeShortCondition = false // default: 0
//
emaValue = i_emaFilterEnabled ? [Link](i_emaSource, i_emaLength) : na
bool isEMAFilterEnabledAndCloseAboveMA = i_emaFilterEnabled ? i_emaSource >
emaValue : true
bool isEMAFilterEnabledAndCloseBelowMA = i_emaFilterEnabled ? i_emaSource <
emaValue : true
//
calcADX_Masanakamura(int _len) =>
_smoothedTrueRange = 0.0
_smoothedDirectionalMovementPlus = 0.0
_smoothed_directionalMovementMinus = 0.0
_trueRange = [Link]([Link](high - low, [Link](high - nz(close[1]))),
[Link](low - nz(close[1])))
_directionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ?
[Link](high - nz(high[1]), 0) : 0
_directionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ?
[Link](nz(low[1]) - low, 0) : 0
_smoothedTrueRange := nz(_smoothedTrueRange[1]) - nz(_smoothedTrueRange[1]) /
_len + _trueRange
_smoothedDirectionalMovementPlus := nz(_smoothedDirectionalMovementPlus[1]) -
nz(_smoothedDirectionalMovementPlus[1]) / _len + _directionalMovementPlus
_smoothed_directionalMovementMinus := nz(_smoothed_directionalMovementMinus[1])
- nz(_smoothed_directionalMovementMinus[1]) / _len + _directionalMovementMinus
DIP = _smoothedDirectionalMovementPlus / _smoothedTrueRange * 100
DIM = _smoothed_directionalMovementMinus / _smoothedTrueRange * 100
_DX = [Link](DIP - DIM) / (DIP + DIM) * 100
adx = [Link](_DX, _len)
[DIP, DIM, adx]

[DIPlusO, DIMinusO, ADXO] = [Link](i_adxDILength, i_adxSmoothing)


[DIPlusM, DIMinusM, ADXM] = calcADX_Masanakamura(i_adxDILength)

adx = i_adxFilterEnabled and i_adxVariant == "ORIGINAL" ? ADXO : ADXM


bool isADXFilterEnabledAndAboveThreshold = i_adxFilterEnabled ? adx >
i_adxLowerThreshold : true
// Start / End Time Periods
isStartPeriodEnabledAndInRange = i_startPeriodEnabled ? i_startPeriodTime <= time :
true
isEndPeriodEnabledAndInRange = i_endPeriodEnabled ? i_endPeriodTime >= time : true

// Time-Of-Day Window
//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired from [Link]
Window-Simple-Hours-Time-of-Day-Filter/
isWithinWindowOfTime(_position) =>
currentTimeIsWithinWindowOfTime = not na(time([Link], _position +
':1234567', i_timeZone))
bool isTimeFilterEnabledAndInRange = i_timeFilterEnabled ?
isWithinWindowOfTime(i_betweenTime) : true

isStartEndPeriodsAndTimeInRange = isStartPeriodEnabledAndInRange and


isEndPeriodEnabledAndInRange and isTimeFilterEnabledAndInRange

// Trade Direction and State Management


//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

i_tradeDirection = [Link]('Long and Short', title='Trade Direction',


options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Todo Add logic to reenter trade only if condition is still met only on TP
//i_reenterPosition = [Link](defval=true, title='Re-Enter Position on TP' ,
group='Trade Direction')
//longConditionFinal = i_reenterPosition ? longCondition : longCondition and not
longCondition[1]
//shortConditionFinal = i_reenterPosition ? shortCondition : shortCondition and not
shortCondition[1]

isInLongPosition = strategy.position_size > 0


isInShortPosition = strategy.position_size < 0

longConditionFinal = (longCondition and isADXFilterEnabledAndAboveThreshold and


isEMAFilterEnabledAndCloseAboveMA and isLongSupertrendFilterEnable) and
i_tradeDirection != 'Short Only' and isInLongPosition == false
shortConditionFinal = (shortCondition and isADXFilterEnabledAndAboveThreshold and
isEMAFilterEnabledAndCloseBelowMA and isShortSupertrendFilterEnable) and
i_tradeDirection != 'Long Only' and isInShortPosition == false

// Trade Entry variables (not in position yet)


bool openingLongPosition = longConditionFinal and not
([Link]([Link] - 1) > 0)
bool openingShortPosition = shortConditionFinal and not
([Link]([Link] - 1) < 0)
bool openingAnyPosition = openingLongPosition or openingShortPosition
float closePriceWhenPositionOpened = [Link](openingAnyPosition,close,0)
// Fixed Percent Stop Loss
float fixedPercentSLPriceWhenLongPositionEntered =
[Link](openingLongPosition,close,0) * (1 - i_fixedPercentSL)
float fixedPercentSLPriceWhenShortPositionEntered =
[Link](openingShortPosition,close,0) * (1 + i_fixedPercentSL)

// Swing High/Low Stop Loss


float swingLowPriceWhenLongPostionEntered = [Link](openingLongPosition,
source = [Link](low, i_swingHighLowLookbackSL), occurrence = 0)
float swingHighPriceWhenShortPositionEntered = [Link](openingShortPosition,
source = [Link](high, i_swingHighLowLookbackSL), occurrence = 0)

// Debug Start
// drawLabel(_offset, _pivot, _style, _color) =>
// if not na(_pivot)
// [Link](bar_index[_offset], _pivot, [Link](_pivot,
[Link]), style=_style, color=_color, textcolor=#131722)

// drawLabel(i_swingHighLowLookbackSL, [Link](high, i_swingHighLowLookbackSL,


i_swingHighLowLookbackSL), label.style_label_down, [Link])
// drawLabel(i_swingHighLowLookbackSL, [Link](low, i_swingHighLowLookbackSL,
i_swingHighLowLookbackSL), label.style_label_up, [Link])
// Debug End

//ATR
//todo determine if close should be source for both long/short or if high/low
should be used?
float ATRSLPriceWhenLongPositionEntered = [Link](openingLongPosition, close -
([Link](i_atrLengthSL) * i_atrMultiplierSL) ,0)
float ATRSLPriceWhenShortPositionEntered = [Link](openingShortPosition, close
+ ([Link](i_atrLengthSL) * i_atrMultiplierSL) ,0)
//plot(close + ([Link](i_atrLengthSL) * i_atrMultiplierSL),
color=[Link]([Link], 0))
//plot(close - ([Link](i_atrLengthSL) * i_atrMultiplierSL),
color=[Link]([Link], 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
// Single Fixed Percent Take Profit
float fixedPercentTPPriceWhenLongPositionEntered =
[Link](openingLongPosition,close,0) * (1 + i_fixedPercentTP)
float fixedPercentTPPriceWhenShortPositionEntered =
[Link](openingShortPosition,close,0) * (1 - i_fixedPercentTP)

// Multiple

// Risk:Reward Ratio Take Profit


tpRRPriceWhenLongPositionEntered = closePriceWhenPositionOpened +
((closePriceWhenPositionOpened - slPriceLong) * i_RiskRewardRatioTP)
tpRRPriceWhenShortPositionEntered = closePriceWhenPositionOpened +
((closePriceWhenPositionOpened - slPriceShort) * i_RiskRewardRatioTP)

//ATR
//todo determine if close should be source for both long/short or if high/low
should be used?
float ATRTPPriceWhenLongPositionEntered = [Link](openingLongPosition, close +
([Link](i_atrLengthTP) * i_atrMultiplierTP) ,0)
float ATRTPPriceWhenShortPositionEntered = [Link](openingShortPosition, close
- ([Link](i_atrLengthTP) * i_atrMultiplierTP) ,0)
// plot(close + ([Link](i_atrLengthTP) * i_atrMultiplierTP),
color=[Link]([Link], 0))
// plot(close - ([Link](i_atrLengthTP) * i_atrMultiplierTP),
color=[Link]([Link], 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

// Functions
//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? [Link](pcnt / 100 *
strategy.position_avg_price / [Link]) : float(na)

// Plotting
//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

//Plot SL and TP
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=[Link], style=plot.style_linebr, title="SL")
tpbp=plot(i_plotTPSL and i_useTakeProfit and strategy.position_size > 0 ?
tpPriceLong[1] : na, color=[Link], style=plot.style_linebr, title="TP")
epbp=plot(i_plotTPSL and strategy.position_size > 0 ? strategy.position_avg_price :
na, color=[Link], style=plot.style_linebr, title="Entry")
fill(slbp, epbp, color=[Link]([Link], 90))
fill(tpbp, epbp, color=[Link]([Link], 90))

slsp=plot(i_plotTPSL and i_useStopLoss and strategy.position_size < 0 ?


slPriceShort[1] : na, color=[Link], style=plot.style_linebr, title="SL")
tpsp=plot(i_plotTPSL and i_useTakeProfit and strategy.position_size < 0 ?
tpPriceShort[1] : na, color=[Link], style=plot.style_linebr, title="TP")
epsp=plot(i_plotTPSL and strategy.position_size < 0 ? strategy.position_avg_price :
na, color=[Link], style=plot.style_linebr, title="Entry")
fill(slsp, epsp, color=[Link]([Link], 90))
fill(tpsp, epsp, color=[Link]([Link], 90))

// Alerts
//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_alert_txt_entry_long = input.text_area(defval = "i alert message", title = "Long
Entry Message", group = "Alerts")
i_alert_txt_entry_short = input.text_area(defval = "", title = "Short Entry
Message", group = "Alerts")
i_alert_txt_exit_long = input.text_area(defval = "", title = "Long Exit Message",
group = "Alerts")
i_alert_txt_exit_short = input.text_area(defval = "", title = "Short Exit Message",
group = "Alerts")

/// Trade Execution


//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

if isStartEndPeriodsAndTimeInRange
if longConditionFinal
[Link]('Long', [Link])
alert(message=i_alert_txt_entry_long, freq=alert.freq_once_per_bar_close)

if shortConditionFinal
[Link]('Short', [Link])
alert(message=i_alert_txt_entry_short, freq=alert.freq_once_per_bar_close)

if i_useTakeProfit
//Inspired from Multiple %% profit exits example by adolgo
[Link]
if i_typeOfTakeProfit == "Multiple Fixed %"
[Link]('TP1', qty_percent=i_takeProfitQuantityPercent1,
profit=per(i_takeProfitTargetPercent1))
[Link]('TP2', qty_percent=i_takeProfitQuantityPercent2,
profit=per(i_takeProfitTargetPercent2))
[Link]('TP3', qty_percent=i_takeProfitQuantityPercent3,
profit=per(i_takeProfitTargetPercent3))
[Link]('i_takeProfitTargetPercent4',
profit=per(i_takeProfitTargetPercent4))
if tpLongCondition
[Link]('Long', alert_message = i_alert_txt_exit_long ,comment=
'tpCommentLong')
if tpShortCondition
[Link]('Short', alert_message =
i_alert_txt_exit_short ,comment= 'tpCommentShort')
if i_useStopLoss
if slLongCondition
[Link]('Long', alert_message = i_alert_txt_exit_long,
comment='slCommentLong')
if slShortCondition
[Link]('Short', comment= 'slCommentShort')
if closeLongCondition
[Link]('Long', alert_message = i_alert_txt_exit_long,
comment='Conditional Close Long')
if closeShortCondition
[Link]('Short', alert_message = i_alert_txt_exit_short,
comment='Conditional Close Short')

// Global Dashboard Variables


//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

// Dashboard Table Text Size


i_tableTextSize = [Link](title="Dashboard Size", defval="Small",
options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group="Dashboards")
table_text_size(s) =>
switch s
"Auto" => [Link]
"Huge" => [Link]
"Large" => [Link]
"Normal" => [Link]
"Small" => [Link]
=> [Link]
tableTextSize = table_text_size(i_tableTextSize)

/// Performance Summary Dashboard


//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by [Link] - Thanks VertMT

i_showDashboard = [Link](title="Performance Summary", defval=true,


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

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


_cellText = _title + "\n" + _value
[Link](_table, _column, _row, _cellText, bgcolor=_bgcolor,
text_color=_txtcolor, text_size=tableTextSize)

// Draw dashboard table


if i_showDashboard
var bgcolor = [Link]([Link],0)

// Keep track of Wins/Losses streaks


newWin = ([Link] > [Link][1]) and
([Link] == [Link][1]) and ([Link] ==
[Link][1])
newLoss = ([Link] == [Link][1]) and
([Link] > [Link][1]) and ([Link] ==
[Link][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 = [Link](position.top_right, 1, 15, border_width=1)

if [Link]
// Update table
lastTime = strategy.position_size == 0 ?
[Link].exit_time([Link]-1) : time
dollarReturn = [Link]
f_fillCell(dashTable, 0, 0, "Start:", [Link]("{0,date,long}",
[Link].entry_time(0)) , bgcolor, [Link]) // + [Link]("
{0,time,HH:mm}", [Link].entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", [Link]("{0,date,long}", lastTime) ,
bgcolor, [Link]) // + [Link](" {0,time,HH:mm}",
[Link].entry_time(0))
_profit = ([Link] / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", [Link](_profit, '##.##') +
"%", _profit > 0 ? [Link] : [Link], [Link])
_numOfDaysInStrategy = (lastTime - [Link].entry_time(0)) /
(1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", [Link](_profit /
_numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ?
[Link] : [Link], [Link])
_winRate = ( [Link] / [Link] ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", [Link](_winRate,
'##.##') + "%", _winRate < 50 ? [Link] : _winRate < 75 ? #999900 :
[Link], [Link])
f_fillCell(dashTable, 0, 5, "Profit Factor:",
[Link]([Link] / [Link], '##.###'),
[Link] > [Link] ? [Link] : [Link], [Link])
f_fillCell(dashTable, 0, 6, "Total Trades:",
[Link]([Link]), bgcolor, [Link])
f_fillCell(dashTable, 0, 7, "Winning Trades:",
[Link]([Link]), [Link] > [Link] ?
[Link] : [Link], [Link])
f_fillCell(dashTable, 0, 8, "Losing Trades:",
[Link]([Link]), [Link] < [Link] ?
[Link] : [Link], [Link])
f_fillCell(dashTable, 0, 9, "Max Wins In A Row:", [Link](maxWinRow,
'######') , bgcolor, [Link])
f_fillCell(dashTable, 0, 10, "Max Losses In A Row:",
[Link](maxLossRow, '######') , bgcolor, [Link])

// Monthly Table Performance Dashboard By @QuantNomad


//
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_showMonthlyPerformance = [Link](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 = [Link]

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


[Link]))
if (last_computed[1])
[Link](month_pnl)
[Link](month_time)

[Link](month_pnl , cur_month_pnl[1])
[Link](month_time, time[1])

if (not na(cur_year_pnl[1]) and (new_year or [Link]))


if (last_computed[1])
[Link](year_pnl)
[Link](year_time)

[Link](year_pnl , cur_year_pnl[1])
[Link](year_time, time[1])

last_computed := [Link] ? true : nz(last_computed[1])

// Monthly P&L Table


var monthly_table = table(na)

if ([Link])
monthly_table := [Link](position.bottom_right, columns = 14, rows =
[Link](year_pnl) + 1, border_width = 1)

[Link](monthly_table, 0, 0, "", bgcolor = #cccccc,


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

for yi = 0 to [Link](year_pnl) - 1
[Link](monthly_table, 0, yi + 1,
[Link](year([Link](year_time, yi))), bgcolor = #cccccc,
text_size=tableTextSize)

y_color = [Link](year_pnl, yi) > 0 ? [Link]([Link], transp =


40) : [Link]([Link], transp = 40)
[Link](monthly_table, 13, yi + 1,
[Link]([Link]([Link](year_pnl, yi) * 100, i_monthlyReturnPercision)),
bgcolor = y_color, text_color=[Link]([Link], 0),text_size=tableTextSize)

for mi = 0 to [Link](month_time) - 1
m_row = year([Link](month_time, mi)) - year([Link](year_time,
0)) + 1
m_col = month([Link](month_time, mi))
m_color = [Link](month_pnl, mi) > 0 ? [Link]([Link], transp =
40) : [Link]([Link], transp = 40)

[Link](monthly_table, m_col, m_row,


[Link]([Link]([Link](month_pnl, mi) * 100, i_monthlyReturnPercision)),
bgcolor = m_color, text_color=[Link]([Link], 0), text_size=tableTextSize)

You might also like