Advertisement
PineCoders

Armando Strategy V2

Aug 2nd, 2019
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.79 KB | None | 0 0
  1. //@version=3
  2.  
  3. // Put the name of your system here. This string is used in study(), strategy() and alertconditon() statements.
  4. SystemName = "Armando Strategy V2"
  5. // 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.
  6. // Although leaving it empty will not cause problems in study mode,
  7. TradeId = "AMD"
  8. // These values are used both in the strategy() header and in the script's relevant inputs as default values so they match.
  9. // Unless these values match in the script's Inputs and the TV backtesting Properties, results between them cannot be compared.
  10. InitCapital = 1000000
  11. InitPosition = 10.0
  12. InitCommission = 0.075
  13. InitPyramidMax = 1
  14. CalcOnorderFills = true
  15. 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)
  16.  
  17. //Strategy_label = input(true, title="=============Strategy Parameters==========")
  18.  
  19. OpenDirection = input(defval="ALL", options=["ALL", "LONG", "SHORT"])
  20.  
  21. // Set the max losing streak length with an input
  22. setmaxLosingStreak = input(title="============Set Max number of consecutive loss trades=========", type=bool, defval=false)
  23. maxLosingStreak = input(title="Max of consecutive loss trades", type=integer, defval=15, minval=1)
  24.  
  25. setmaxWinStreak = input(title="============Set Max number of consecutive won trades=========", type=bool, defval=false)
  26. maxWinStreak = input(title="Max Winning Streak Length", type=integer, defval=15, minval=1)
  27.  
  28. // Set the max consecutive days with a loss
  29. setmaxLosingDaysStreak = input(title="Set MAX consecutive days with a loss in a row", type=bool, defval=false)
  30. maxLosingDaysStreak = input(title="Max of consecutive days with a loss in a row", type=integer, defval=3, minval=1)
  31.  
  32. setMaxDrawdown = input(title="Set Max Total DrawDown", type=bool, defval=false)
  33. // Input for the strategy's maximum drawdown (in % of strategy equity)
  34. maxPercDd = input(title="Max Drawdown (%)", type=integer, defval=10, minval=1, maxval=100)
  35.  
  36. setMaxIntradayLoss = input(title="Set Max Intraday Loss", type=bool, defval=false)
  37. // Input for the strategy's maximum intraday loss (in % of strategy equity)
  38. maxIntradayLoss = input(title="Max Intraday Loss (%)", type=integer, defval=3, minval=1, maxval=100)
  39.  
  40.  
  41. setNumberDailyTrades = input(title="=========Limit the number of trades per day=======", type=bool, defval=false)
  42. maxDailyTrades = input(title="Number MAX of daily trades", type=integer, defval=10, minval=1, maxval=100)
  43.  
  44. setNumberWeeklyTrades = input(title="Limit the number of trades per week", type=bool, defval=false)
  45. maxWeeklyTrades = input(title="Number MAX of weekly trades", type=integer, defval=50, minval=1, maxval=100)
  46.  
  47. // Stop loss management
  48. StopType = input("None", "=======Stop Type Selection=======", options=["None", "Percent", "Trailing"])
  49. LossPerc = input(title="Stop Loss (%)", type=float, minval=0.0, step=0.5, defval=1) * 0.01
  50. TrailPerc = input(title="Trail Stop Loss (%)", type=float, minval=0.0, step=0.5, defval=3) * 0.01
  51.  
  52. // Take Profit
  53. useTakeProfit = input(false, "===== Use Take profit =======")
  54. ProfitPerc = input(title="Take Profit (%)", type=float, minval=0.0, step=0.5, defval=3) / 100
  55.  
  56. // ————— M. Date range filtering
  57. DateFilter = input(false, "═════════════ Date Range Filtering")
  58. 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)
  59. 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)
  60. FromDate = timestamp(FromYear, FromMonth, FromDay, 00, 00), ToDate = timestamp(ToYear, ToMonth, ToDay, 23, 59)
  61. TradeDateIsAllowed() => DateFilter ? (time >= FromDate and time <= ToDate) : true
  62.  
  63. CloseSession = input(false, title="Close positions at market at the end of each session ?")
  64. Session = input(title="Trading session", type=session, defval="0830-1630")
  65. CloseDirection = input(defval="ALL", options=["ALL", "LONG", "SHORT"])
  66.  
  67. // HourFilter = input(false, "═════════════ Hourly Range Filtering")
  68. // FromHour = input(0, "From Hour", minval=0)
  69. // FromMinute = input(0, "From Minute", minval=0)
  70. // ToHour = input(23, "To Hour", minval=0)
  71. // ToMinute = input(59, "To Year", minval=0)
  72.  
  73. // TradeHourlyIsAllowed() =>
  74. // if HourFilter
  75. // cond_hour = hour >= FromHour and hour <= ToHour
  76. // cond_minute = minute >= FromMinute and minute <= ToMinute
  77. // cond_hour and cond_minute
  78. // else
  79. // true
  80.  
  81. // setNumberMonthlyTrades = input(title="Limit the number of trades per month", type=bool, defval=false)
  82. // maxMonthlyTrades = input(title="Number MAX of monthly trades", type=integer, defval=200, minval=1, maxval=100)
  83.  
  84. // global variables
  85. // ————— Colors
  86.  
  87. MyGreenRaw = color(lime,0), MyGreenMedium = color(#00b300,0), MyGreenSemiDark = color(#009900,0), MyGreenDark = color(#006600,0), MyGreenDarkDark = color(#003300,0)
  88. MyRedRaw = color(red,0), MyRedMedium = color(#cc0000,0), MyRedSemiDark = color(#990000,0), MyRedDark = color(#330000,0), MyRedDarkDark = color(#330000,0)
  89. MyFuchsiaRaw = color(fuchsia,0), MyFuchsiaMedium = color(#c000c0,0), MyFuchsiaDark = color(#800080,0), MyFuchsiaDarkDark = color(#400040,0)
  90. MyYellowRaw = color(yellow,0), MyYellowMedium = color(#c0c000,0), MyYellowDark = color(#808000,0), MyYellowDarkDark = color(#404000,0)
  91. MyOrangeRaw = color(#ffa500,0), MyOrangeMedium = color(#cc8400,0), MyOrangeDark = color(#996300,0)
  92. MyBlueRaw = color(#4985E7,0), MyBlueMedium = color(#4985E7,0)
  93. MyGreenBackGround = color(#00FF00,93), MyRedBackGround = color(#FF0000,90)
  94.  
  95. // Standout color and another one a bit darker.
  96. AAA = orange
  97. AA2 = #ff6500
  98. // Same color as TV dark Theme background color to hide value of titles.
  99. BLK = #171b29
  100. // Plus/Minus color
  101. PMC( _val) => _val>=0.0? MyGreenMedium:MyRedRaw
  102. // True/False color
  103. PMB( _val) => _val? MyGreenMedium:MyRedMedium
  104. // Compare two input colors
  105. COMPARE_COLOR(val1, val2) => val1 > val2 ? MyGreenMedium : MyRedRaw
  106. // Global stats blues
  107. GF1 = #6c9cec
  108. GF2 = #4978e7
  109. // Trade info Aquas
  110. TI1 = #009a9a
  111. TI2 = #00cdcd
  112.  
  113. BIG_NUMBER_COUNT = 1000
  114.  
  115.  
  116.  
  117. // indicator code
  118. source = close
  119.  
  120. Indicator_label = input(true, title="=============Indicator Parameters==========")
  121.  
  122. typeofMA1 = input(title="Type of MA 1", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "KMA", "TMA", "HullMA", "DEMA", "TEMA", "CTI"])
  123. length_ma1 = input(20, title = "MA 1", type=integer)
  124.  
  125. typeofMA2 = input(title="Type of MA 2", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "KMA", "TMA", "HullMA", "DEMA", "TEMA", "CTI"])
  126. length_ma2 = input(50, title = "MA 2", type=integer)
  127.  
  128.  
  129. cti(sm, src, cd) =>
  130. di = (sm - 1.0) / 2.0 + 1.0
  131. c1 = 2 / (di + 1.0)
  132. c2 = 1 - c1
  133. c3 = 3.0 * (cd * cd + cd * cd * cd)
  134. c4 = -3.0 * (2.0 * cd * cd + cd + cd * cd * cd)
  135. c5 = 3.0 * cd + 1.0 + cd * cd * cd + 3.0 * cd * cd
  136. i1 = 0.0
  137. i2 = 0.0
  138. i3 = 0.0
  139. i4 = 0.0
  140. i5 = 0.0
  141. i6 = 0.0
  142. i1 := c1*src + c2*nz(i1[1])
  143. i2 := c1*i1 + c2*nz(i2[1])
  144. i3 := c1*i2 + c2*nz(i3[1])
  145. i4 := c1*i3 + c2*nz(i4[1])
  146. i5 := c1*i4 + c2*nz(i5[1])
  147. i6 := c1*i5 + c2*nz(i6[1])
  148.  
  149. bfr = -cd*cd*cd*i6 + c3*(i5) + c4*(i4) + c5*(i3)
  150. bfr
  151.  
  152. smma(src, len) =>
  153. smma = 0.0
  154. smma := na(smma[1]) ? sma(src, len) : (smma[1] * (len - 1) + src) / len
  155. smma
  156.  
  157. ma(smoothing, src, length) =>
  158. if smoothing == "RMA"
  159. rma(src, length)
  160. else
  161. if smoothing == "SMA"
  162. sma(src, length)
  163. else
  164. if smoothing == "EMA"
  165. ema(src, length)
  166. else
  167. if smoothing == "WMA"
  168. wma(src, length)
  169. else
  170. if smoothing == "VWMA"
  171. vwma(src, length)
  172. else
  173. if smoothing == "SMMA"
  174. smma(src, length)
  175. else
  176. if smoothing == "HullMA"
  177. wma(2 * wma(src, length / 2) - wma(src, length), round(sqrt(length)))
  178. else
  179. if smoothing == "LSMA"
  180. src
  181. else
  182. if smoothing == "KMA"
  183. xPrice = src
  184. xvnoise = abs(xPrice - xPrice[1])
  185. nfastend = 0.666
  186. nslowend = 0.0645
  187. nsignal = abs(xPrice - xPrice[length])
  188. nnoise = sum(xvnoise, length)
  189. nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
  190. nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
  191. nAMA = 0.0
  192. nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))
  193. nAMA
  194. else
  195. if smoothing == "TMA"
  196. sma(sma(close, length), length)
  197. else
  198. if smoothing == "DEMA"
  199. emaValue = ema(src, length)
  200. 2 * emaValue - ema(emaValue, length)
  201. else
  202. if smoothing == "TEMA"
  203. ema1 = ema(src, length)
  204. ema2 = ema(ema1, length)
  205. ema3 = ema(ema2, length)
  206. (3 * ema1) - (3 * ema2) + ema3
  207. else
  208. src
  209.  
  210.  
  211. MA1 = ma(typeofMA1, source, length_ma1)
  212. MA2 = ma(typeofMA2, source, length_ma2)
  213.  
  214. macrossover = crossover(MA1, MA2)
  215. macrossunder = crossunder(MA1, MA2)
  216.  
  217. condintradayloss = (setMaxIntradayLoss) ? maxIntradayLoss : 100
  218. strategy.risk.max_intraday_loss(value=condintradayloss, type=strategy.percent_of_equity)
  219.  
  220. condmaxdrawdown = (setMaxDrawdown) ? maxPercDd : 100
  221. strategy.risk.max_drawdown(value=condmaxdrawdown, type=strategy.percent_of_equity)
  222.  
  223. // daily trades calculation
  224.  
  225. oktoTradeDaily = true
  226.  
  227. tradesIntradayCount = (setNumberDailyTrades) ? maxDailyTrades : BIG_NUMBER_COUNT
  228. strategy.risk.max_intraday_filled_orders(count=tradesIntradayCount)
  229.  
  230. // weekly trades calculation
  231. tradesLastWeek = 0
  232.  
  233. tradesLastWeek := if (dayofweek == monday) and (dayofweek != dayofweek[1])
  234. strategy.closedtrades[1] + strategy.opentrades[1]
  235. else
  236. tradesLastWeek[1]
  237.  
  238. // Calculate number of trades this week
  239. weeklyTrades = (strategy.closedtrades + strategy.opentrades) - tradesLastWeek
  240. okToTradeWeekly = (setNumberWeeklyTrades) ? (weeklyTrades < maxWeeklyTrades) : true
  241.  
  242.  
  243. // consecutive loss days in a row
  244. countConsLossDays = (setmaxLosingDaysStreak) ? maxLosingDaysStreak : BIG_NUMBER_COUNT
  245. strategy.risk.max_cons_loss_days(countConsLossDays)
  246.  
  247.  
  248. // Calculate the total losing streaks
  249. // Check if there's a new losing trade that increased the streak
  250. newLoss = (strategy.losstrades > strategy.losstrades[1]) and
  251. (strategy.wintrades == strategy.wintrades[1]) and
  252. (strategy.eventrades == strategy.eventrades[1])
  253.  
  254. // Determine current losing streak length
  255. streakLossLen = 0
  256.  
  257. streakLossLen := if (newLoss)
  258. nz(streakLossLen[1]) + 1
  259. else
  260. if (strategy.wintrades > strategy.wintrades[1]) or
  261. (strategy.eventrades > strategy.eventrades[1])
  262. 0
  263. else
  264. nz(streakLossLen[1])
  265.  
  266. // Check if losing streak is under max allowed
  267. okToTradeLossStreak = (setmaxLosingStreak) ? streakLossLen < maxLosingStreak : true
  268.  
  269. // Calculate the total winning streaks
  270. // See if there's a new winner that increased the streak
  271. newWin = (strategy.wintrades > strategy.wintrades[1]) and
  272. (strategy.losstrades == strategy.losstrades[1]) and
  273. (strategy.eventrades == strategy.eventrades[1])
  274.  
  275. // Figure out current winning streak length
  276. streakWinLen = 0
  277.  
  278. streakWinLen := if (newWin)
  279. nz(streakWinLen[1]) + 1
  280. else
  281. if (strategy.losstrades > strategy.losstrades[1]) or
  282. (strategy.eventrades > strategy.eventrades[1])
  283. 0
  284. else
  285. nz(streakWinLen[1])
  286.  
  287. // Check if winning streak is under max allowed
  288. okToTradeWinStreak = (setmaxWinStreak) ? streakWinLen < maxWinStreak : true
  289.  
  290. // Stop loss management
  291. longPercStopPrice = strategy.position_avg_price * (1 - LossPerc)
  292. shortPercStopPrice = strategy.position_avg_price * (1 + LossPerc)
  293.  
  294. // trailing
  295. // Determine trail stop loss prices
  296. longTrailStopPrice = 0.0, shortTrailStopPrice = 0.0
  297. final_SL_Long = 0.0, final_SL_Short = 0.0
  298.  
  299. longTrailStopPrice := if (strategy.position_size > 0)
  300. stopValue = close * (1 - TrailPerc)
  301. max(stopValue, longTrailStopPrice[1])
  302. else
  303. 0
  304.  
  305. shortTrailStopPrice := if (strategy.position_size < 0)
  306. stopValue = close * (1 + TrailPerc)
  307. min(stopValue, shortTrailStopPrice[1])
  308. else
  309. 999999
  310.  
  311. useSL = StopType != "None"
  312. use_SL_Percent = StopType == "Percent"
  313. use_SL_Trail = StopType == "Trailing"
  314.  
  315. final_SL_Long := if use_SL_Percent
  316. longPercStopPrice
  317. else
  318. if use_SL_Trail
  319. longTrailStopPrice
  320.  
  321. final_SL_Short := if use_SL_Percent
  322. shortPercStopPrice
  323. else
  324. if use_SL_Trail
  325. shortTrailStopPrice
  326.  
  327. // Plot stop loss values for confirmation
  328. plot(series=(strategy.position_size > 0 and useSL) ? final_SL_Long : na,
  329. color=red, style=cross,
  330. linewidth=2, title="Long Stop Loss")
  331. plot(series=(strategy.position_size < 0 and useSL) ? final_SL_Short : na,
  332. color=red, style=cross,
  333. linewidth=2, title="Short Stop Loss")
  334.  
  335.  
  336. // Take Profit Manangement
  337. TPlongPrice = strategy.position_avg_price * (1 + ProfitPerc)
  338. TPshortPrice = strategy.position_avg_price * (1 - ProfitPerc)
  339.  
  340. // Plot take profit values for confirmation
  341. plot(series=(strategy.position_size > 0) and useTakeProfit ? TPlongPrice : na,
  342. color=green, style=circles,
  343. linewidth=3, title="Long Take Profit")
  344. plot(series=(strategy.position_size < 0) and useTakeProfit ? TPshortPrice : na,
  345. color=red, style=circles,
  346. linewidth=3, title="Short Take Profit")
  347.  
  348. // Session calculations
  349. // The BarInSession function returns true when
  350. // the current bar is inside the session parameter
  351. BarInSession(sess) => time(period, sess) != 0
  352. in_session = BarInSession(Session)
  353.  
  354. okToTradeInSession = CloseSession ? in_session : true
  355.  
  356. new_session = in_session and not in_session[1]
  357.  
  358. bgcolor(color=(CloseSession and BarInSession(Session)[1]) ? green : na,
  359. title="Trading Session", transp=85)
  360.  
  361. // close all at the end of each session
  362.  
  363. ///////////////////////////////
  364. ///////////////////////
  365. // consolidation of the conditions
  366. okToTrade = okToTradeWeekly and okToTradeLossStreak and okToTradeWinStreak
  367. and TradeDateIsAllowed() and okToTradeInSession// and TradeHourlyIsAllowed()
  368.  
  369. // Orders part
  370.  
  371. longs_opened = strategy.position_size > 0
  372. shorts_opened = strategy.position_size < 0
  373. trades_opened = strategy.position_size != 0
  374. longs_opened_in_session = CloseSession and longs_opened
  375. shorts_opened_in_session = CloseSession and shorts_opened
  376. trades_opened_in_session = CloseSession and trades_opened
  377.  
  378. OpenLong = OpenDirection != "SHORT"
  379. OpenShort = OpenDirection != "LONG"
  380.  
  381. // Go long
  382. longCondition = macrossover
  383. plotchar(longCondition, "longCondition", "", text="▲", color=color(lime,0))
  384. plotchar(okToTrade, "okToTrade", "", text="T\n­")
  385. plotchar(okToTradeInSession, "okToTradeInSession", "", text="S\n\n­")
  386. plotchar(OpenLong, "OpenLong", "", text="G\n\n\n­")
  387. if (longCondition and okToTrade and okToTradeInSession and OpenLong)
  388. strategy.entry("Long", strategy.long)
  389.  
  390. // Go short
  391. shortCondition = macrossunder
  392. plotchar(shortCondition, "shortCondition", "", text="­\n\n\n▼", color=color(red,0), location=location.belowbar)
  393. plotchar(okToTrade, "okToTrade", "", text="­\n\nT", location=location.belowbar)
  394. plotchar(okToTradeInSession, "okToTradeInSession", "", text="­\nS", location=location.belowbar)
  395. plotchar(OpenShort, "OpenShort", "", text="G", location=location.belowbar)
  396. if (shortCondition and okToTrade and okToTradeInSession and OpenShort)
  397. strategy.entry("Short", strategy.short)
  398.  
  399. // Execute stop losses
  400. if (strategy.position_size > 0 and useSL)
  401. strategy.exit(id="SL Long", stop=final_SL_Long)
  402.  
  403. if (strategy.position_size < 0 and useSL)
  404. strategy.exit(id="SL Short", stop=final_SL_Short)
  405.  
  406. // Execute take profits
  407. if (strategy.position_size > 0 and useTakeProfit)
  408. strategy.exit(id="TP Long", limit=TPlongPrice)
  409.  
  410. if (strategy.position_size < 0 and useTakeProfit)
  411. strategy.exit(id="TP Short", limit=TPshortPrice)
  412.  
  413. close_all = CloseDirection == "ALL"
  414. close_all_longs = CloseDirection == "LONG"
  415. close_all_shorts = CloseDirection == "SHORT"
  416.  
  417. // Close all Longs only
  418. if not okToTradeInSession and close_all_longs and longs_opened_in_session
  419. strategy.close(id="Long")
  420.  
  421. //Close all Shorts only
  422. //strategy.close(id="Short", when=not okToTradeInSession and close_all_shorts and shorts_opened_in_session)
  423. if not okToTradeInSession and close_all_shorts and shorts_opened_in_session
  424. strategy.close(id="Short")
  425.  
  426. //// Close all positions at the end of each session regardeless of their profit/loss
  427. if not okToTradeInSession and close_all and trades_opened
  428. strategy.close_all()
  429.  
  430. // Flatten strategy when max losing streak is reached
  431. close_strat = not okToTradeWeekly or not okToTradeLossStreak or not okToTradeWinStreak
  432. or not TradeDateIsAllowed()
  433. if (close_strat)
  434. // close all existing orders
  435. strategy.close_all()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement