我写了一个简单的策略,在 20 天内关闭。我认为它显示了如何在 N 天内平仓。
//@version=4
strategy("My Strategy", overlay=true)
entryTime = 0.0
entryTime := entryTime[1]
if not na(strategy.position_size) and strategy.position_size > 0 and na(entryTime)
entryTime := time
longCondition = dayofweek == dayofweek.monday
if longCondition
strategy.entry("buy", true)
MILLIS_IN_DAY = 24 * 60 * 60 * 1000
CLOSE_AFTER_DAYS = 20
if not na(entryTime) and time - entryTime >= CLOSE_AFTER_DAYS * MILLIS_IN_DAY
strategy.close("buy")
entryTime := na
如果在 N 个柱后收盘:
//@version=4
strategy("My Strategy", overlay=true)
enterIndex = 0.0
enterIndex := enterIndex[1]
inPosition = not na(strategy.position_size) and strategy.position_size > 0
if inPosition and na(enterIndex)
enterIndex := bar_index
longCondition = dayofweek == dayofweek.monday
if longCondition
strategy.entry("buy", true)
CLOSE_AFTER_BARS = 20
if not na(enterIndex) and bar_index - enterIndex + 1 >= CLOSE_AFTER_BARS
strategy.close("buy")
enterIndex := na
Ver.3:更改了 OP 的脚本
//@version=3
strategy("StoJor", overlay=true)
// enterIndex is index of the bar where we've entered in the position. It's empty at the begin
// put here 0.0 just to give to Pine-Script compiller understanding
// what the type of enterIndex is (float)
enterIndex = 0.0
enterIndex := enterIndex[1] // here it's becoming 'na' till we've entered to a position
// check that we are not in the position. As an order is filled strategy.position_size becomes a number
inPosition = not na(strategy.position_size) and strategy.position_size != 0
if inPosition and na(enterIndex)
enterIndex := n // preserve an index of the bar where we entered to current position
// the function checks if we've reached N bars in position
itNthBarInPos(closeAfterBars) => not na(enterIndex) and n - enterIndex + 1 >= closeAfterBars
len = input(25, minval=1, title="Tiempo Stochastic")
smoothK = input(1, minval=1, title="SmoothK Stochastic")
smoothD = input(1, minval=1, title="SmoothD Stochastic")
k = sma(stoch(close, high, low, len), smoothK)
d = sma(k, smoothD)
min = input(6, minval=1, title="Min")
max = input(96, minval=1, title="Max")
// position's direction. constants for easier using of it:
NONE = 0
SHORT = -1
LONG = 1
direction = NONE
direction := direction[1]
// I don't know Spanish, but suppose the minutos_cierre input meand close after 'minutos_cierre' bars
minutos_cierre = input(3, title='Minutos cierre', minval=1)
STOLONG = crossunder(k, min)
STOSHORT = crossover(k, max)
if STOLONG
strategy.entry("STOLONG", strategy.long)
direction := LONG
if itNthBarInPos(minutos_cierre) and direction == LONG
strategy.close(id = "STOLONG")
enterIndex := na // set na to enterIndex to mark that we've exited from the position
direction := NONE
if STOSHORT
strategy.entry("EMASHORT", strategy.short)
direction := SHORT
if itNthBarInPos(minutos_cierre) and direction == SHORT
strategy.close(id = "EMASHORT")
enterIndex := na // set na to enterIndex to mark that we've exited from the position
direction := NONE