Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //@version=3
- // // BEGIN UNCOMMENT FOR BACKTESTING
- // strategy(title="[Autoview][BackTest] Blank R0.13B", shorttitle="[BT]Blank R0.13B", overlay=true,
- // pyramiding=0, default_qty_value=100, default_qty_type=strategy.cash,currency="USD",
- // commission_value=0.2,commission_type=strategy.commission.percent, initial_capital=1000)
- // // END UNCOMMENT FOR BACKTESTING
- // COMMENT OUT FOR BACKTESTING
- study(title="[Autoview][Alerts]Blank R0.13B", shorttitle="[AL]Blank R0.13B", overlay=true)
- // END COMMENT OUT FOR BACKTESTING
- //This does not capture all the pieces of code that need to be commented out/in
- //strategyEntry(RUNNING, AS, STUDY) => RUNNING=='This is only used when we are generating alerts' ? -9999.0001 : -9999.0001
- //strategyClose(ALERTS, NOT_STRATEGY) => ALERTS=='I know it is weird, just uncmment it' ? -9999.0001 : -9999.0001
- // END UNCOMMENT FOR ALERTS
- //
- // Author: yatrader2 / Mrbit
- // Adapted from: JustUncleL R0.13
- // Revision: R0.13B Branch by MrBit
- // Date: 9-June-2018
- //
- // Description:
- // ============
- //
- // Trade Management options:
- // -------------------------
- // - Option to specify Backtest start and end time.
- // - Trailing Stop, with Activate Level (as % of price) and Trailing Stop (as % of price)
- // - Target Profit Level, (as % of price)
- // - Stop Loss Level, (as % of price)
- // - BUY green triandles and SELL dark red triangles
- // - Trade Order closed colour coded Label:
- // > Dark Red = Stop Loss Hit
- // > Green = Target Profit Hit
- // > Purple = Trailing Stop Hit
- // > Orange = Opposite (Sell) Order Close
- //
- // Trade Management Indication:
- // ----------------------------
- // - Trailing Stop Activate Price = Blue dotted line
- // - Trailing Stop Price = Fuschia solid stepping line
- // - Target Profit Price = Lime '+' line
- // - Stop Loss Price = Red '+' line
- //
- // Dealing With Renko Charts:
- // --------------------------
- // - If you choose to use Renko charts, make sure you have enabled the "IS This a RENKO Chart"
- // option, (I have not so far found a way to Detect the type of chart is running).
- // - If you want non-repainting Renko charts you MUST use TRADITIONAL Renko Bricks. This
- // type of brick is fixed and will not change size.
- // - Also use Renko bricks with WICKS DISABLED. Wicks are not part of Renko, the whole
- // idea of using Renko bricks is not to see the wick noise.
- // - Set you chart Time Frame to the lowest possible one that will build enough bricks
- // to give a reasonable history, start at 1min TimeFrame. Renko bricks are not dependent
- // on time, they represent a movement in price. But the chart candlestick data is used
- // to create the bricks, so lower TF gives more accurate Brick creation.
- // - You want to size your bricks to 2/1000 of the pair price, so for ETHBTC the price is say 0.0805
- // then your Renko Brick size should be about 2*0.0805/1000 = 0.0002 (round up).
- // - You may find there is some slippage in value, but this can be accounted for in the Backtes
- // by setting your commission a bit higher, for Binance for example I use 0.2
- //
- // Dealing HA Candles:
- // -------------------
- // They are supported, but be aware backtest will provide impossible trades...
- // https://getsatisfaction.com/tradingview/topics/strategy-tester-places-incorrect-orders-in-backtesting-when-using-heikin-ashi-candles
- // By default even if you are using HA candles, the normal candle values are used
- //
- // References:
- // ===========
- // - MA Ribbon R0.13 by JustUncleL
- // - "How to automate this strategy for free using a chrome extension" by CryptoRox
- //
- // Revisions:
- // ==========
- // R0.12 - Beta 2 Version
- // R0.13 - Beta 3 version
- // > Resolve issue with Orange Close alerts not showing up in the TV
- // alarm notifications when using Candlestick Charts.
- // > Resolve issue with multiple Long/Short signals before Close by
- // better use of the tradeState engine to keep control. This also
- // made some of the Risk Management Code simplier.
- // R0.13B - [MrBit] Branch from JustUncleL R0.13
- // > Remove actual algo
- // > Establish functions for long Signal, long Close Signal
- // and short Signal, short Close Signal to minimize the places code
- // must be editted to update / replace algos
- // > Make allow Long and allow short and invert trade directions
- // independent options
- // > Added support for alternate candle types
- // > Added autoset backtest period feature, and optional coloring
- // > Moved strategy calls in to functions so they can all be comment
- // out or activated / disabled in a single block at the top of the script
- //
- //
- // -----------------------------------------------------------------------------
- // Copyright 2018 @JustUncleL, @yatrader2
- //
- // This program is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // any later version.
- //
- // This program is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // The GNU General Public License can be found here
- // <http://www.gnu.org/licenses/>.
- //
- // -----------------------------------------------------------------------------
- //
- useRenko = input(false, title="This a RENKO Chart?")
- useHeikin = input(false, title="Use Heikin-Ashi Candles? (BT WILL BE UNRELIABLE)")
- // WARNING: Using Heikin-Ashi may result in inaccurate backtest results
- open_ = useHeikin ? security(heikinashi(tickerid), period, open) : security(tickerid, period, open)
- close_ = useHeikin ? security(heikinashi(tickerid), period, close) : security(tickerid, period, close)
- high_ = useRenko? max(close_,open_) : useHeikin ? security(heikinashi(tickerid), period, high) : security(tickerid, period, high)
- low_ = useRenko? min(close_,open_) : useHeikin ? security(heikinashi(tickerid), period, low) : security(tickerid, period, low)
- uPrice = input(title="Price", defval="close", options=["close", "high", "low"])
- src= uPrice=="close" ? close_ : uPrice=="high" ? high_ : uPrice=="low" ? low_ : na
- // Use Alternate Anchor TF for MAs
- anchor = input(0,minval=0,maxval=1440,title="Alternate TimeFrame Multiplier (0=none)")
- // If have anchor specified, calculate the base multiplier.
- //mult = isintraday ? anchor==0 or interval<=0 or interval>=anchor or anchor>1440? 1 : round(anchor/interval) : 1
- //mult := isdwm? 1 : mult // Only available Daily or less
- mult = anchor>0 ? anchor : 1
- // - FUNCTIONS
- longSignal()=>
- false
- shortSignal()=>
- false
- closeLongSignal()=>
- false
- closeShortSignal()=>
- false
- // Generate Buy Sell signals,
- buy = 0
- sell= 0
- //
- buy := longSignal() ? 1 : 0
- sell := shortSignal() ? 1 : 0
- //
- //////////////////////////////////////////////////////////////////////////////////////////
- //*** This Trade Management Section of code is a modified version of that found in ***//
- //*** "How to automate this strategy for free using a chrome extension" by CryptoRox ***//
- //*** Modifications and tradeState engine by JustUncleL. ***//
- //////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////
- //* Backtesting Period Selector | Component *//
- ///////////////////////////////////////////////
- //* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *//
- //* https://www.tradingview.com/u/pbergden/ *//
- //* Modifications made by JustUncleL*//
- //* Modifications made by MrBit*//
- // // BEGIN UNCOMMENT FOR BACKTESTING
- //// A switch to control background coloring of the test period
- //testPeriodBackground = input(title="Color Test Period?", type=bool, defval=false)
- //
- // Autoset Backtest Period
- // Based on code from WellSpentTime
- //autolen = input(title="Auto set backtest Start", defval=true)
- //custom_candle_start = 0
- //timecondition_hourly = n > round(76.5633 * pow((interval / 60), 2) - 1745.19 * (interval / 60) + 10649)
- //timecondition_daily = n > round(1000 / interval) // Only for bitcoin, need a separate quadratic fit for other securities
- //time_condition = (interval >= 60 and interval <= 720 and timecondition_hourly) or (interval < 60 and timecondition_daily)
- //
- //// Or set a specifc period
- //// From https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component/
- //testStartMonth = input(title="Backtest Start Month", type=integer, defval=1, step=1, minval=1, maxval=12)
- //testStartYear = input(title="Backtest Start Year", type=integer, defval=2018, step=1, minval=2013, maxval=2019)
- ////testStartDay = input(title="Backtest Start Day", defval=28, step=1, minval=1, maxval=31)
- //testStartDay = 1
- //testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
- //
- //testStopMonth = input(title="Backtest Stop Month", type=integer, defval=12, step=1, minval=1, maxval=12)
- //testStopYear = input(title="Backtest Stop Year", type=integer, defval=2018, step=1, minval=2013, maxval=2020)
- ////testStopDay = input(title="Backtest Stop Day", type=integer, defval=31, step=1, minval=1, maxval=31)
- //testStopDay=31
- //testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)
- //
- //// Set the time period
- //testPeriod() => autolen ? time_condition : time >= testPeriodStart and time <= testPeriodStop ? true : false
- //
- //// Color the period (or don't)
- //testPeriodBackgroundColor = testPeriodBackground and testPeriod() ? #000055 : na
- //bgcolor(testPeriodBackgroundColor, transp=90)
- // // END UNCOMMENT FOR BACKTESTING
- //////////////////////////
- //* Strategy Component *//
- //////////////////////////
- AQUA = #00FFFFFF
- BLUE = #0000FFFF
- RED = #FF0000FF
- LIME = #00FF00FF
- GRAY = #808080FF
- DARKRED = #8B0000FF
- DARKGREEN = #006400FF
- //
- fastExit = input(false,title="Use Opposite Trade as a Close Signal")
- clrBars = input(true,title="Colour Candles to Trade Order state")
- orderType = input("Longs+Shorts",title="What type of Orders", options=["Longs+Shorts","LongsOnly","ShortsOnly","Flips"])
- isLong = orderType!="ShortsOnly" //input(true,title="Allow Longs")
- isShort = orderType!="LongsOnly" //input(true,title="Allow Shorts")
- //Flips only work when both Longs+Shorts is used
- //invertTrade = input(false,title="Invert Trade Direction")
- //
- //////////////////////////
- //* Trade State Engine *//
- //////////////////////////
- // Keep track of current trade state
- longClose = false, longClose := nz(longClose[1],false)
- shortClose = false, shortClose := nz(shortClose[1],false)
- tradeState = 0, tradeState := nz(tradeState[1])
- tradeState := tradeState==0 ? buy==1 and (barstate.isconfirmed or barstate.ishistory) and isLong and not longClose and not shortClose? 1 :
- sell==1 and (barstate.isconfirmed or barstate.ishistory) and isShort and not longClose and not shortClose? -1 :
- tradeState : tradeState
- //////////////////////////////////////////////////
- //* Put Entry and special Exit conditions here *//
- //////////////////////////////////////////////////
- //Entry Conditions, when state changes direction.
- //
- longCondition = false
- shortCondition = false
- longCondition := change(tradeState) and tradeState==1
- shortCondition := change(tradeState) and tradeState==-1
- if orderType=="Flips"
- temp = longCondition
- longCondition := shortCondition
- shortCondition := temp
- //end if
- // Exit on Sell signal
- longExitC = closeLongSignal() ? 1 : 0
- shortExitC = closeShortSignal() ? 1 : 0
- // Exit condition for no SL.
- longExit = change(longExitC) and longExitC==1 and tradeState==1
- shortExit = change(shortExitC) and shortExitC==1 and tradeState==-1
- // -- debugs
- //plotchar(tradeState,"tradeState at Event",location=location.bottom, color=na)
- //plotchar(longCondition, title="longCondition",color=na)
- //plotchar(shortCondition, title="shortCondition",color=na)
- //plotchar(tradeState, title="tradeState",color=na)
- // -- /debugs
- /////////////////////////////////////
- //======[ Deal Entry Prices ]======//
- /////////////////////////////////////
- last_open_longCondition = na
- last_open_shortCondition = na
- last_open_longCondition := longCondition ? close : nz(last_open_longCondition[1])
- last_open_shortCondition := shortCondition ? close : nz(last_open_shortCondition[1])
- //////////////////////////////////
- //======[ Position State ]======//
- //////////////////////////////////
- in_longCondition = tradeState == 1
- in_shortCondition = tradeState == -1
- /////////////////////////////////
- //======[ Trailing Stop ]======//
- /////////////////////////////////
- isTS = input(true, "Trailing Stop")
- ts = input(3.0, "Trailing Stop (%)", minval=0,step=0.1, type=float) /100
- last_high = na
- last_low = na
- last_high_short = na
- last_low_long = na
- last_high := not in_longCondition ? na : in_longCondition and (na(last_high[1]) or high_ > nz(last_high[1])) ? high_ : nz(last_high[1])
- last_high_short := not in_shortCondition ? na : in_shortCondition and (na(last_high[1]) or high_ > nz(last_high[1])) ? high_ : nz(last_high[1])
- last_low := not in_shortCondition ? na : in_shortCondition and (na(last_low[1]) or low_ < nz(last_low[1])) ? low_ : nz(last_low[1])
- last_low_long := not in_longCondition ? na : in_longCondition and (na(last_low[1]) or low_ < nz(last_low[1])) ? low_ : nz(last_low[1])
- long_ts = isTS and in_longCondition and not na(last_high) and (low_ <= last_high - last_high * ts) //and (last_high >= last_open_longCondition + last_open_longCondition * tsi)
- short_ts = isTS and in_shortCondition and not na(last_low) and (high_ >= last_low + last_low * ts) //and (last_low <= last_open_shortCondition - last_open_shortCondition * tsi)
- ///////////////////////////////
- //======[ Take Profit ]======//
- ///////////////////////////////
- isTP = input(true, "Take Profit")
- tp = input(3.0, "Take Profit (%)",minval=0,step=0.1,type=float) / 100
- ttp = input(1.0, "Trailing Profit (%)",minval=0,step=0.1,type=float) / 100
- ttp := ttp>tp ? tp : ttp
- long_tp = isTP and in_longCondition and (last_high >= last_open_longCondition + last_open_longCondition * tp) and (low_ <= last_high - last_high * ttp)
- short_tp = isTP and in_shortCondition and (last_low <= last_open_shortCondition - last_open_shortCondition * tp) and (high_ >= last_low + last_low * ttp)
- /////////////////////////////
- //======[ Stop Loss ]======//
- /////////////////////////////
- isSL = input(false, "Stop Loss")
- sl = input(3.0, "Stop Loss (%)", minval=0,step=0.1, type=float) / 100
- long_sl = isSL and in_longCondition and (low_ <= last_open_longCondition - last_open_longCondition * sl)
- short_sl = isSL and in_shortCondition and (high_ >= last_open_shortCondition + last_open_shortCondition * sl)
- ////////////////////////////////////
- //======[ Stop on Opposite ]======//
- ////////////////////////////////////
- //NOTE Short exit signal is non-repainting, no need to force it, if Pyramiding keep going
- long_sos = (fastExit or (not isTS and not isSL)) and longExit and in_longCondition
- short_sos = (fastExit or (not isTS and not isSL)) and shortExit and in_shortCondition
- /////////////////////////////////
- //======[ Close Signals ]======//
- /////////////////////////////////
- // Create a single close for all the different closing conditions, all conditions here are non-repainting
- longClose := isLong and (long_tp or long_sl or long_ts or long_sos) and not longCondition
- shortClose := isShort and (short_tp or short_sl or short_ts or short_sos) and not shortCondition
- ///////////////////////////////
- //======[ Plot Colors ]======//
- ///////////////////////////////
- longCloseCol = na
- shortCloseCol = na
- longCloseCol := long_tp ? green : long_sl ? maroon : long_ts ? purple : long_sos ? orange :longCloseCol[1]
- shortCloseCol := short_tp ? green : short_sl ? maroon : short_ts ? purple : short_sos ? orange : shortCloseCol[1]
- //
- tpColor = isTP and in_longCondition ? lime : isTP and in_shortCondition ? lime : na
- slColor = isSL and in_longCondition ? red : isSL and in_shortCondition ? red : na
- //////////////////////////////////
- //======[ Strategy Plots ]======//
- //////////////////////////////////
- plot(isTS and in_longCondition?
- last_high - last_high * ts : na, "Long Trailing", fuchsia, style=2, linewidth=2,offset=1)
- plot(isTP and in_longCondition and last_high < last_open_longCondition + last_open_longCondition * tp ?
- last_open_longCondition + last_open_longCondition * tp : na, "Long TP Active", tpColor, style=3,join=false, linewidth=2,offset=1)
- plot(isTP and in_longCondition and last_high >= last_open_longCondition + last_open_longCondition * tp ?
- last_high - last_high * ttp : na, "Long Trailing", black, style=2, linewidth=2,offset=1)
- plot(isSL and in_longCondition and last_low_long > last_open_longCondition - last_open_longCondition * sl ?
- last_open_longCondition - last_open_longCondition * sl : na, "Long SL", slColor, style=3,join=false, linewidth=2,offset=1)
- //
- plot(isTS and in_shortCondition?
- last_low + last_low * ts : na, "Short Trailing", fuchsia, style=2, linewidth=2,offset=1)
- plot(isTP and in_shortCondition and last_low > last_open_shortCondition - last_open_shortCondition * tp ?
- last_open_shortCondition - last_open_shortCondition * tp : na, "Short TP Active", tpColor, style=3,join=false, linewidth=2,offset=1)
- plot(isTP and in_shortCondition and last_low <= last_open_shortCondition - last_open_shortCondition * tp ?
- last_low + last_low * ttp : na, "Short Trailing", black, style=2, linewidth=2,offset=1)
- plot(isSL and in_shortCondition and last_high_short < last_open_shortCondition + last_open_shortCondition * sl ?
- last_open_shortCondition + last_open_shortCondition * sl : na, "Short SL", slColor, style=3,join=false, linewidth=2,offset=1)
- //
- bclr = not clrBars ? na : tradeState==0 ? GRAY :
- in_longCondition ? close<last_open_longCondition? DARKGREEN : LIME :
- in_shortCondition ? close>last_open_shortCondition? DARKRED : RED : GRAY
- barcolor(bclr,title="Trade State Bar Colouring")
- ///////////////////////////////
- //======[ Alert Plots ]======//
- ///////////////////////////////
- // // START OF COMMENT OUT FOR BACKTESTING
- plotshape(longCondition?close:na, title="Long", color=green, textcolor=green, transp=0,
- style=shape.triangleup, location=location.belowbar, size=size.small,text="LONG",offset=0)
- plotshape(longClose?close:na, title="Long Close", color=longCloseCol, textcolor=white, transp=0,
- style=shape.labeldown, location=location.abovebar, size=size.small,text="Long\nClose",offset=0)
- plotshape(shortCondition?close:na, title="Short", color=red, textcolor=red, transp=0,
- style=shape.triangledown, location=location.abovebar, size=size.small,text="SHORT",offset=0)
- plotshape(shortClose?close:na, title="Short Close", color=shortCloseCol, textcolor=white, transp=0,
- style=shape.labelup, location=location.belowbar, size=size.small,text="Short\nClose",offset=0)
- // Autoview alert syntax - This assumes you are trading coins BUY and SELL on Binance Exchange
- // WARNING*** Only use Autoview to automate a strategy after you've sufficiently backtested and forward tested the strategy.
- // You can learn more about the syntax here:
- // http://autoview.with.pink/#syntax and you can watch this video here: https://www.youtube.com/watch?v=epN5Tjinuxw
- // For the opens you will want to trigger BUY orders on LONGS (eg ETHBTC) with alert option "Once Per Bar Close"
- // and SELL orders on SHORTS (eg BTCUSDT)
- // b=buy q=0.001 e=binance s=ethbtc t=market ( LONG )
- // or b=sell q=0.001 e=binance s=btcusdt t=market ( SHORT )
- alertcondition(longCondition, "Open Long", "LONG")
- alertcondition(shortCondition, "Open Short", "SHORT")
- // For the closes you will want to trigger these alerts on condition with alert option "Once Per Bar"
- // (NOTE: with Renko you can only use "Once Per Bar Close" option)
- // b=sell q=99% e=binance s=ethbtc t=market ( CLOSE LONGS )
- // or b=buy q=99% e=binance s=btcusdt t=market ( CLOSE SHORTS )
- // This gets it as it happens and typically results in a better exit live than in the backtest.
- // It works really well for counteracting some market slippage
- alertcondition(longClose, "Close Longs", "CLOSE LONGS")
- alertcondition(shortClose, "Close Shorts", "CLOSE SHORTS")
- // // END COMMENT OUT FOR BACKTESTING
- ////////////////////////////////////////////
- //======[ Strategy Entry and Exits ]======//
- ////////////////////////////////////////////
- // // BEGIN UNCOMMENT FOR BACKTESTING
- //if testPeriod() and isLong
- // strategyEntry("Long", 1, longCondition)
- // strategyClose("Long", longClose)
- //
- //if testPeriod() and isShort
- // strategyEntry("Short", 0, shortCondition)
- // strategyClose("Short", shortClose)
- // // END UNCOMMENT FOR BACKTESTING
- // --- Debugs
- //plotchar(longExit,title="longExit",location=location.bottom,color=na)
- //plotchar(longCondition,title="longCondition",location=location.bottom,color=na)
- //plotchar(in_longCondition,title="in_longCondition",location=location.bottom,color=na)
- //plotchar(longClose,title="longClose",location=location.bottom,color=na,color=na)
- //plotchar(buy,title="buy",location=location.bottom,color=na)
- // --- /Debugs
- ///////////////////////////////////
- //======[ Reset Variables ]======//
- ///////////////////////////////////
- if longClose or not in_longCondition
- last_high := na
- last_high_short := na
- if shortClose or not in_shortCondition
- last_low := na
- last_low_long := na
- if longClose or shortClose
- tradeState := 0
- in_longCondition := false
- in_shortCondition := false
- //plotchar(tradeState,"tradeState at EOF",location=location.bottom, color=na)
- // EOF
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement