Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //@version=3
- // Put the name of your system here. This string is used in study(), strategy() and alertconditon() statements.
- SystemName = "Armando Strategy V2"
- // This string is to personalize the text that appears with your orders on the chart through strategy() calls and entry/exit markers, and in the alert default message.
- // Although leaving it empty will not cause problems in study mode,
- TradeId = "AMD"
- // These values are used both in the strategy() header and in the script's relevant inputs as default values so they match.
- // Unless these values match in the script's Inputs and the TV backtesting Properties, results between them cannot be compared.
- InitCapital = 1000000
- InitPosition = 10.0
- InitCommission = 0.075
- InitPyramidMax = 1
- CalcOnorderFills = true
- strategy(title="Armando Strategy V2", shorttitle=SystemName, overlay=true, pyramiding=InitPyramidMax, initial_capital=InitCapital, default_qty_type=strategy.percent_of_equity, default_qty_value=InitPosition, commission_type=strategy.commission.percent, commission_value=InitCommission, calc_on_order_fills=CalcOnorderFills, precision=6)
- //Strategy_label = input(true, title="=============Strategy Parameters==========")
- OpenDirection = input(defval="ALL", options=["ALL", "LONG", "SHORT"])
- // Set the max losing streak length with an input
- setmaxLosingStreak = input(title="============Set Max number of consecutive loss trades=========", type=bool, defval=false)
- maxLosingStreak = input(title="Max of consecutive loss trades", type=integer, defval=15, minval=1)
- setmaxWinStreak = input(title="============Set Max number of consecutive won trades=========", type=bool, defval=false)
- maxWinStreak = input(title="Max Winning Streak Length", type=integer, defval=15, minval=1)
- // Set the max consecutive days with a loss
- setmaxLosingDaysStreak = input(title="Set MAX consecutive days with a loss in a row", type=bool, defval=false)
- maxLosingDaysStreak = input(title="Max of consecutive days with a loss in a row", type=integer, defval=3, minval=1)
- setMaxDrawdown = input(title="Set Max Total DrawDown", type=bool, defval=false)
- // Input for the strategy's maximum drawdown (in % of strategy equity)
- maxPercDd = input(title="Max Drawdown (%)", type=integer, defval=10, minval=1, maxval=100)
- setMaxIntradayLoss = input(title="Set Max Intraday Loss", type=bool, defval=false)
- // Input for the strategy's maximum intraday loss (in % of strategy equity)
- maxIntradayLoss = input(title="Max Intraday Loss (%)", type=integer, defval=3, minval=1, maxval=100)
- setNumberDailyTrades = input(title="=========Limit the number of trades per day=======", type=bool, defval=false)
- maxDailyTrades = input(title="Number MAX of daily trades", type=integer, defval=10, minval=1, maxval=100)
- setNumberWeeklyTrades = input(title="Limit the number of trades per week", type=bool, defval=false)
- maxWeeklyTrades = input(title="Number MAX of weekly trades", type=integer, defval=50, minval=1, maxval=100)
- // Stop loss management
- StopType = input("None", "=======Stop Type Selection=======", options=["None", "Percent", "Trailing"])
- LossPerc = input(title="Stop Loss (%)", type=float, minval=0.0, step=0.5, defval=1) * 0.01
- TrailPerc = input(title="Trail Stop Loss (%)", type=float, minval=0.0, step=0.5, defval=3) * 0.01
- // Take Profit
- useTakeProfit = input(false, "===== Use Take profit =======")
- ProfitPerc = input(title="Take Profit (%)", type=float, minval=0.0, step=0.5, defval=3) / 100
- // ————— M. Date range filtering
- DateFilter = input(false, "═════════════ Date Range Filtering")
- FromYear = input(2019, "From Year", minval=1900), FromMonth = input(4, "From Month", minval=1, maxval=12), FromDay = input(1, "From Day", minval=1, maxval=31)
- ToYear = input(2019, "To Year", minval=1900), ToMonth = input(4, "To Month", minval=1, maxval=12), ToDay = input(1, "To Day", minval=1, maxval=31)
- FromDate = timestamp(FromYear, FromMonth, FromDay, 00, 00), ToDate = timestamp(ToYear, ToMonth, ToDay, 23, 59)
- TradeDateIsAllowed() => DateFilter ? (time >= FromDate and time <= ToDate) : true
- CloseSession = input(false, title="Close positions at market at the end of each session ?")
- Session = input(title="Trading session", type=session, defval="0830-1630")
- CloseDirection = input(defval="ALL", options=["ALL", "LONG", "SHORT"])
- // HourFilter = input(false, "═════════════ Hourly Range Filtering")
- // FromHour = input(0, "From Hour", minval=0)
- // FromMinute = input(0, "From Minute", minval=0)
- // ToHour = input(23, "To Hour", minval=0)
- // ToMinute = input(59, "To Year", minval=0)
- // TradeHourlyIsAllowed() =>
- // if HourFilter
- // cond_hour = hour >= FromHour and hour <= ToHour
- // cond_minute = minute >= FromMinute and minute <= ToMinute
- // cond_hour and cond_minute
- // else
- // true
- // setNumberMonthlyTrades = input(title="Limit the number of trades per month", type=bool, defval=false)
- // maxMonthlyTrades = input(title="Number MAX of monthly trades", type=integer, defval=200, minval=1, maxval=100)
- // global variables
- // ————— Colors
- MyGreenRaw = color(lime,0), MyGreenMedium = color(#00b300,0), MyGreenSemiDark = color(#009900,0), MyGreenDark = color(#006600,0), MyGreenDarkDark = color(#003300,0)
- MyRedRaw = color(red,0), MyRedMedium = color(#cc0000,0), MyRedSemiDark = color(#990000,0), MyRedDark = color(#330000,0), MyRedDarkDark = color(#330000,0)
- MyFuchsiaRaw = color(fuchsia,0), MyFuchsiaMedium = color(#c000c0,0), MyFuchsiaDark = color(#800080,0), MyFuchsiaDarkDark = color(#400040,0)
- MyYellowRaw = color(yellow,0), MyYellowMedium = color(#c0c000,0), MyYellowDark = color(#808000,0), MyYellowDarkDark = color(#404000,0)
- MyOrangeRaw = color(#ffa500,0), MyOrangeMedium = color(#cc8400,0), MyOrangeDark = color(#996300,0)
- MyBlueRaw = color(#4985E7,0), MyBlueMedium = color(#4985E7,0)
- MyGreenBackGround = color(#00FF00,93), MyRedBackGround = color(#FF0000,90)
- // Standout color and another one a bit darker.
- AAA = orange
- AA2 = #ff6500
- // Same color as TV dark Theme background color to hide value of titles.
- BLK = #171b29
- // Plus/Minus color
- PMC( _val) => _val>=0.0? MyGreenMedium:MyRedRaw
- // True/False color
- PMB( _val) => _val? MyGreenMedium:MyRedMedium
- // Compare two input colors
- COMPARE_COLOR(val1, val2) => val1 > val2 ? MyGreenMedium : MyRedRaw
- // Global stats blues
- GF1 = #6c9cec
- GF2 = #4978e7
- // Trade info Aquas
- TI1 = #009a9a
- TI2 = #00cdcd
- BIG_NUMBER_COUNT = 1000
- // indicator code
- source = close
- Indicator_label = input(true, title="=============Indicator Parameters==========")
- typeofMA1 = input(title="Type of MA 1", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "KMA", "TMA", "HullMA", "DEMA", "TEMA", "CTI"])
- length_ma1 = input(20, title = "MA 1", type=integer)
- typeofMA2 = input(title="Type of MA 2", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "KMA", "TMA", "HullMA", "DEMA", "TEMA", "CTI"])
- length_ma2 = input(50, title = "MA 2", type=integer)
- cti(sm, src, cd) =>
- di = (sm - 1.0) / 2.0 + 1.0
- c1 = 2 / (di + 1.0)
- c2 = 1 - c1
- c3 = 3.0 * (cd * cd + cd * cd * cd)
- c4 = -3.0 * (2.0 * cd * cd + cd + cd * cd * cd)
- c5 = 3.0 * cd + 1.0 + cd * cd * cd + 3.0 * cd * cd
- i1 = 0.0
- i2 = 0.0
- i3 = 0.0
- i4 = 0.0
- i5 = 0.0
- i6 = 0.0
- i1 := c1*src + c2*nz(i1[1])
- i2 := c1*i1 + c2*nz(i2[1])
- i3 := c1*i2 + c2*nz(i3[1])
- i4 := c1*i3 + c2*nz(i4[1])
- i5 := c1*i4 + c2*nz(i5[1])
- i6 := c1*i5 + c2*nz(i6[1])
- bfr = -cd*cd*cd*i6 + c3*(i5) + c4*(i4) + c5*(i3)
- bfr
- smma(src, len) =>
- smma = 0.0
- smma := na(smma[1]) ? sma(src, len) : (smma[1] * (len - 1) + src) / len
- smma
- ma(smoothing, src, length) =>
- if smoothing == "RMA"
- rma(src, length)
- else
- if smoothing == "SMA"
- sma(src, length)
- else
- if smoothing == "EMA"
- ema(src, length)
- else
- if smoothing == "WMA"
- wma(src, length)
- else
- if smoothing == "VWMA"
- vwma(src, length)
- else
- if smoothing == "SMMA"
- smma(src, length)
- else
- if smoothing == "HullMA"
- wma(2 * wma(src, length / 2) - wma(src, length), round(sqrt(length)))
- else
- if smoothing == "LSMA"
- src
- else
- if smoothing == "KMA"
- xPrice = src
- xvnoise = abs(xPrice - xPrice[1])
- nfastend = 0.666
- nslowend = 0.0645
- nsignal = abs(xPrice - xPrice[length])
- nnoise = sum(xvnoise, length)
- nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
- nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
- nAMA = 0.0
- nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))
- nAMA
- else
- if smoothing == "TMA"
- sma(sma(close, length), length)
- else
- if smoothing == "DEMA"
- emaValue = ema(src, length)
- 2 * emaValue - ema(emaValue, length)
- else
- if smoothing == "TEMA"
- ema1 = ema(src, length)
- ema2 = ema(ema1, length)
- ema3 = ema(ema2, length)
- (3 * ema1) - (3 * ema2) + ema3
- else
- src
- MA1 = ma(typeofMA1, source, length_ma1)
- MA2 = ma(typeofMA2, source, length_ma2)
- macrossover = crossover(MA1, MA2)
- macrossunder = crossunder(MA1, MA2)
- condintradayloss = (setMaxIntradayLoss) ? maxIntradayLoss : 100
- strategy.risk.max_intraday_loss(value=condintradayloss, type=strategy.percent_of_equity)
- condmaxdrawdown = (setMaxDrawdown) ? maxPercDd : 100
- strategy.risk.max_drawdown(value=condmaxdrawdown, type=strategy.percent_of_equity)
- // daily trades calculation
- oktoTradeDaily = true
- tradesIntradayCount = (setNumberDailyTrades) ? maxDailyTrades : BIG_NUMBER_COUNT
- strategy.risk.max_intraday_filled_orders(count=tradesIntradayCount)
- // weekly trades calculation
- tradesLastWeek = 0
- tradesLastWeek := if (dayofweek == monday) and (dayofweek != dayofweek[1])
- strategy.closedtrades[1] + strategy.opentrades[1]
- else
- tradesLastWeek[1]
- // Calculate number of trades this week
- weeklyTrades = (strategy.closedtrades + strategy.opentrades) - tradesLastWeek
- okToTradeWeekly = (setNumberWeeklyTrades) ? (weeklyTrades < maxWeeklyTrades) : true
- // consecutive loss days in a row
- countConsLossDays = (setmaxLosingDaysStreak) ? maxLosingDaysStreak : BIG_NUMBER_COUNT
- strategy.risk.max_cons_loss_days(countConsLossDays)
- // Calculate the total losing streaks
- // Check if there's a new losing trade that increased the streak
- newLoss = (strategy.losstrades > strategy.losstrades[1]) and
- (strategy.wintrades == strategy.wintrades[1]) and
- (strategy.eventrades == strategy.eventrades[1])
- // Determine current losing streak length
- streakLossLen = 0
- streakLossLen := if (newLoss)
- nz(streakLossLen[1]) + 1
- else
- if (strategy.wintrades > strategy.wintrades[1]) or
- (strategy.eventrades > strategy.eventrades[1])
- 0
- else
- nz(streakLossLen[1])
- // Check if losing streak is under max allowed
- okToTradeLossStreak = (setmaxLosingStreak) ? streakLossLen < maxLosingStreak : true
- // Calculate the total winning streaks
- // See if there's a new winner that increased the streak
- newWin = (strategy.wintrades > strategy.wintrades[1]) and
- (strategy.losstrades == strategy.losstrades[1]) and
- (strategy.eventrades == strategy.eventrades[1])
- // Figure out current winning streak length
- streakWinLen = 0
- streakWinLen := if (newWin)
- nz(streakWinLen[1]) + 1
- else
- if (strategy.losstrades > strategy.losstrades[1]) or
- (strategy.eventrades > strategy.eventrades[1])
- 0
- else
- nz(streakWinLen[1])
- // Check if winning streak is under max allowed
- okToTradeWinStreak = (setmaxWinStreak) ? streakWinLen < maxWinStreak : true
- // Stop loss management
- longPercStopPrice = strategy.position_avg_price * (1 - LossPerc)
- shortPercStopPrice = strategy.position_avg_price * (1 + LossPerc)
- // trailing
- // Determine trail stop loss prices
- longTrailStopPrice = 0.0, shortTrailStopPrice = 0.0
- final_SL_Long = 0.0, final_SL_Short = 0.0
- longTrailStopPrice := if (strategy.position_size > 0)
- stopValue = close * (1 - TrailPerc)
- max(stopValue, longTrailStopPrice[1])
- else
- 0
- shortTrailStopPrice := if (strategy.position_size < 0)
- stopValue = close * (1 + TrailPerc)
- min(stopValue, shortTrailStopPrice[1])
- else
- 999999
- useSL = StopType != "None"
- use_SL_Percent = StopType == "Percent"
- use_SL_Trail = StopType == "Trailing"
- final_SL_Long := if use_SL_Percent
- longPercStopPrice
- else
- if use_SL_Trail
- longTrailStopPrice
- final_SL_Short := if use_SL_Percent
- shortPercStopPrice
- else
- if use_SL_Trail
- shortTrailStopPrice
- // Plot stop loss values for confirmation
- plot(series=(strategy.position_size > 0 and useSL) ? final_SL_Long : na,
- color=red, style=cross,
- linewidth=2, title="Long Stop Loss")
- plot(series=(strategy.position_size < 0 and useSL) ? final_SL_Short : na,
- color=red, style=cross,
- linewidth=2, title="Short Stop Loss")
- // Take Profit Manangement
- TPlongPrice = strategy.position_avg_price * (1 + ProfitPerc)
- TPshortPrice = strategy.position_avg_price * (1 - ProfitPerc)
- // Plot take profit values for confirmation
- plot(series=(strategy.position_size > 0) and useTakeProfit ? TPlongPrice : na,
- color=green, style=circles,
- linewidth=3, title="Long Take Profit")
- plot(series=(strategy.position_size < 0) and useTakeProfit ? TPshortPrice : na,
- color=red, style=circles,
- linewidth=3, title="Short Take Profit")
- // Session calculations
- // The BarInSession function returns true when
- // the current bar is inside the session parameter
- BarInSession(sess) => time(period, sess) != 0
- in_session = BarInSession(Session)
- okToTradeInSession = CloseSession ? in_session : true
- new_session = in_session and not in_session[1]
- bgcolor(color=(CloseSession and BarInSession(Session)[1]) ? green : na,
- title="Trading Session", transp=85)
- // close all at the end of each session
- ///////////////////////////////
- ///////////////////////
- // consolidation of the conditions
- okToTrade = okToTradeWeekly and okToTradeLossStreak and okToTradeWinStreak
- and TradeDateIsAllowed() and okToTradeInSession// and TradeHourlyIsAllowed()
- // Orders part
- longs_opened = strategy.position_size > 0
- shorts_opened = strategy.position_size < 0
- trades_opened = strategy.position_size != 0
- longs_opened_in_session = CloseSession and longs_opened
- shorts_opened_in_session = CloseSession and shorts_opened
- trades_opened_in_session = CloseSession and trades_opened
- OpenLong = OpenDirection != "SHORT"
- OpenShort = OpenDirection != "LONG"
- // Go long
- longCondition = macrossover
- plotchar(longCondition, "longCondition", "", text="▲", color=color(lime,0))
- plotchar(okToTrade, "okToTrade", "", text="T\n")
- plotchar(okToTradeInSession, "okToTradeInSession", "", text="S\n\n")
- plotchar(OpenLong, "OpenLong", "", text="G\n\n\n")
- if (longCondition and okToTrade and okToTradeInSession and OpenLong)
- strategy.entry("Long", strategy.long)
- // Go short
- shortCondition = macrossunder
- plotchar(shortCondition, "shortCondition", "", text="\n\n\n▼", color=color(red,0), location=location.belowbar)
- plotchar(okToTrade, "okToTrade", "", text="\n\nT", location=location.belowbar)
- plotchar(okToTradeInSession, "okToTradeInSession", "", text="\nS", location=location.belowbar)
- plotchar(OpenShort, "OpenShort", "", text="G", location=location.belowbar)
- if (shortCondition and okToTrade and okToTradeInSession and OpenShort)
- strategy.entry("Short", strategy.short)
- // Execute stop losses
- if (strategy.position_size > 0 and useSL)
- strategy.exit(id="SL Long", stop=final_SL_Long)
- if (strategy.position_size < 0 and useSL)
- strategy.exit(id="SL Short", stop=final_SL_Short)
- // Execute take profits
- if (strategy.position_size > 0 and useTakeProfit)
- strategy.exit(id="TP Long", limit=TPlongPrice)
- if (strategy.position_size < 0 and useTakeProfit)
- strategy.exit(id="TP Short", limit=TPshortPrice)
- close_all = CloseDirection == "ALL"
- close_all_longs = CloseDirection == "LONG"
- close_all_shorts = CloseDirection == "SHORT"
- // Close all Longs only
- if not okToTradeInSession and close_all_longs and longs_opened_in_session
- strategy.close(id="Long")
- //Close all Shorts only
- //strategy.close(id="Short", when=not okToTradeInSession and close_all_shorts and shorts_opened_in_session)
- if not okToTradeInSession and close_all_shorts and shorts_opened_in_session
- strategy.close(id="Short")
- //// Close all positions at the end of each session regardeless of their profit/loss
- if not okToTradeInSession and close_all and trades_opened
- strategy.close_all()
- // Flatten strategy when max losing streak is reached
- close_strat = not okToTradeWeekly or not okToTradeLossStreak or not okToTradeWinStreak
- or not TradeDateIsAllowed()
- if (close_strat)
- // close all existing orders
- strategy.close_all()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement