JayRogers

Strategy Code Example 2 - Time Limiting

*** THIS IS JUST AN EXAMPLE OF STRATEGY TIME LIMITING CODE IMPLEMENTATION ***

This is a follow up to my example for risk management implementation here:


Code remains mostly unchanged, but now includes a time limiting implementation.

Relevant code blocks for the time factor are preceded with a comment stating:
  • *** FOCUS OF EXAMPLE ***

Cheers!
Open-source Skript

Ganz im Sinne von TradingView hat der Autor dieses Skripts es als Open-Source veröffentlicht, damit Trader es verstehen und überprüfen können. Ein Hoch auf den Autor! Sie können es kostenlos verwenden, aber die Wiederverwendung dieses Codes in einer Publikation unterliegt den Hausregeln. Sie können das Skript den Favoriten hinzufügen, um es auf dem Chart zu verwenden.

Möchten Sie dieses Skript auf einem Chart verwenden?
//@version=2

strategy(title = "Strategy Code Example", shorttitle = "Strategy Code Example", overlay = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, currency = currency.GBP)

// Revision:        1
// Author:          @JayRogers
//
// *** THIS IS JUST AN EXAMPLE OF STRATEGY TIME LIMITING ***
//
//  This is a follow up to my previous strategy example for risk management, extended to include a time limiting factor.

// === GENERAL INPUTS ===
// short ma
maFastSource   = input(defval = open, title = "Fast MA Source")
maFastLength   = input(defval = 14, title = "Fast MA Period", minval = 1)
// long ma
maSlowSource   = input(defval = open, title = "Slow MA Source")
maSlowLength   = input(defval = 21, title = "Slow MA Period", minval = 1)

// === STRATEGY RELATED INPUTS ===
tradeInvert     = input(defval = false, title = "Invert Trade Direction?")
// Risk management
inpTakeProfit   = input(defval = 1000, title = "Take Profit", minval = 0)
inpStopLoss     = input(defval = 200, title = "Stop Loss", minval = 0)
inpTrailStop    = input(defval = 200, title = "Trailing Stop Loss", minval = 0)
inpTrailOffset  = input(defval = 0, title = "Trailing Stop Loss Offset", minval = 0)
// *** FOCUS OF EXAMPLE ***
// Time limiting
// a toggle for enabling/disabling
useTimeLimit    = input(defval = true, title = "Use Start Time Limiter?")
// set up where we want to run from
startYear       = input(defval = 2016, title = "Start From Year", type = integer, minval = 0, step = 1)
startMonth      = input(defval = 05, title = "Start From Month", type = integer, minval = 0,step = 1)
startDay        = input(defval = 01, title = "Start From Day", type = integer, minval = 0,step = 1)
startHour       = input(defval = 00, title = "Start From Hour", type = integer, minval = 0,step = 1)
startMinute     = input(defval = 00, title = "Start From Minute", type = integer, minval = 0,step = 1)

// === RISK MANAGEMENT VALUE PREP ===
// if an input is less than 1, assuming not wanted so we assign 'na' value to disable it.
useTakeProfit   = inpTakeProfit  >= 1 ? inpTakeProfit  : na
useStopLoss     = inpStopLoss    >= 1 ? inpStopLoss    : na
useTrailStop    = inpTrailStop   >= 1 ? inpTrailStop   : na
useTrailOffset  = inpTrailOffset >= 1 ? inpTrailOffset : na

// *** FOCUS OF EXAMPLE ***
// === TIME LIMITER CHECKING FUNCTION ===
// using a multi line function to return true or false depending on our input selection
// multi line function logic must be indented.
startTimeOk() =>
    // get our input time together
    inputTime   = timestamp(syminfo.timezone, startYear, startMonth, startDay, startHour, startMinute)
    // check the current time is greater than the input time and assign true or false
    timeOk      = time > inputTime ? true : false
    // last line is the return value, we want the strategy to execute if..
    // ..we are using the limiter, and the time is ok -OR- we are not using the limiter
    r = (useTimeLimit and timeOk) or not useTimeLimit

// === SERIES SETUP ===
/// a couple of ma's..
maFast = ema(maFastSource, maFastLength)
maSlow = ema(maSlowSource, maSlowLength)

// === PLOTTING ===
fast = plot(maFast, title = "Fast MA", color = green, linewidth = 2, style = line, transp = 50)
slow = plot(maSlow, title = "Slow MA", color = red, linewidth = 2, style = line, transp = 50)

// === LOGIC ===
// is fast ma above slow ma?
aboveBelow = maFast >= maSlow ? true : false
// are we inverting our trade direction?
tradeDirection = tradeInvert ? aboveBelow ? false : true : aboveBelow ? true : false

// *** FOCUS OF EXAMPLE ***
// wrap our strategy execution in an if statement which calls the time checking function to validate entry
// like the function logic, content to be included in the if statement must be indented.
if( startTimeOk() )
    // === STRATEGY - LONG POSITION EXECUTION ===
    enterLong = not tradeDirection[1] and tradeDirection
    exitLong = tradeDirection[1] and not tradeDirection
    strategy.entry( id = "Long", long = true, when = enterLong )
    strategy.close( id = "Long", when = exitLong )
    
    // === STRATEGY - SHORT POSITION EXECUTION ===
    enterShort = tradeDirection[1] and not tradeDirection
    exitShort = not tradeDirection[1] and tradeDirection
    strategy.entry( id = "Short", long = false, when = enterShort )
    strategy.close( id = "Short", when = exitShort )
    
    // === STRATEGY RISK MANAGEMENT EXECUTION ===
    strategy.exit("Exit Long", from_entry = "Long", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
    strategy.exit("Exit Short", from_entry = "Short", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
If you like what I do, consider buying me a nice fresh cup of tea :)

https://paypal.me/JayRogersKreations

Kommentare

anyway to make it close a trade after a certain expiry time?

eg for binary options 5mins expiry
+9 Antworten
Would it be possible to make a strategy only run during a certain time? Like between 9:00 to 10:00 for example.
+5 Antworten
JayRogers TheYangGuizi
Yes it should be entirely possible. Have a look at this script in the public library
+18 Antworten
worthy7 JayRogers
@JayRogers, How do we filter by day of the week? Only want to execute trades on tue+wed but I can't see any documentation about how to get these values. The link is broken (at least for me)
Antworten
Objredline worthy7
@worthy7, Link is broken. Did you ever figure out how to filter the backtest on a period in the past? Especially if that period is outside of Tradingview's ~8000 bar hard cap?
Antworten
worthy7 Objredline
@Objredline, I took a quick look at some of my old code, found this line:
`tradingallowed = (not na(k) and not na(d) and (dayofweek==3 or dayofweek==4 or dayofweek==5)) and (getTakeProfitInTicks(tradedirection)/10 > MinimumPredictedProfitPerTrade)`
Antworten
Objredline worthy7
@worthy7, Thank you! is tradingallowed a TV built in function? Thanks again.
Antworten
worthy7 Objredline
@Objredline, no just part of my code, the important point is dayofweek==3, which I think is a Tuesday.
Antworten
Dear Jay.
How can I change EMA to HullMA
+2 Antworten
Hi Jay.
Thanks
+1 Antworten