在满足价格条件时才会执行订单。 如果要关闭当前蜡烛图的仓位,此选项很有用。 默认值为“false”。
close_entries_rule
max_lines_count
max_labels_count
max_boxes_count
margin_long
margin_short
explicit_plot_zorder
initial_capital
risk_free_rate
备注 每个策略脚本必须有一个 strategy 调用。 使用参数calc_on_every_tick = true的PineScript代码可以对历史记录和实时数据进行不同的计算。 当使用非标准类型的图表作为策略基础时,你需要知道结果会有所不同。订单将在该表的价格执行(e.g.for Heikin Ashi将使用Heikin Ashi的价格(平均的)不是真正的市场价格)。因此,我们强烈建议您在您的策略中使用标准图表类型。
另见
indicator
这是进入市场的命令。 如果具有相同ID的订单已经挂起,则可修改订单。 如果没有指定ID的订单,则会发出新的订单。 要停用进场指令,应使用命令strategy.cancel或strategy.cancel_all。 与函数strategy.order相比,strategy.entry功能受金字塔影响,可以正确反转市场位置。 如果“Limit”和“stop”参数均为“NaN”,则订单类型为市场订单。
strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message)
例子
strategy(title = "simple strategy entry example")
strategy.entry("enter long", strategy.long, 1, when = open > high[1]) // enter long by market if current open great then previous high
strategy.entry("enter short", strategy.short, 1, when = open < low[1]) // enter short by market if current open less then previous low
参数
id
(series string) 必要参数。 订单标识符。 可以通过引用其标识来取消或修改订单。direction
(strategy_direction) 一个必需的参数。市场持仓方向:'strategy.long’为多头,'strategy.short’为空头。qty
(series int/float) 可选参数。交易的合约/股数/手数/单位数量。预设值为’NaN’。limit
(series int/float) 可选参数。订单的限价。若已指定,订单类型是"limit" 或"stop-limit"。其他订单类型为"NaN"。stop
(series int/float) 可选参数。订单的止损价。如果已指定,订单类型为"stop"或"stop-limit"。其他订单类型则为"NaN"。oca_name
oca_type
comment
(series string) 可选参数。订单的其他说明。when
(series bool) 可选参数。订单的状况。若为"true",订单被放置。若为"false",则没有任何事情发生(之前放置的相同 ID 的订单没有被撤销)。默认值为"true"。alert_message
(series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。这是一个具有指定ID的退出订单的命令。 如果有多个具有相同ID的进场订单,则它们都将同一时间退出。 如果在触发命令时没有指定ID的开放订单,该命令则不会生效。 该命令使用市场订单。 每个进场都由分开的市场订单关闭。
strategy.close(id, when, comment, qty, qty_percent, alert_message)
例子
strategy("closeEntry Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close("buy", when = open < close, qty_percent = 50, comment = "close buy entry for 50%")
plot(strategy.position_size)
参数
id
(series string) 必要参数。 订单标识符。可以通过引用其标识来关闭订单。when
(series bool) 可选参数。命令的条件。qty
(series int/float) 可选参数。退出交易的合约/股数/手数/单位的数量。默认值为’NaN’。qty_percent
(series int/float) 定义平仓的百分比(0-100)。它的优先级低于 ‘qty’ 参数的优先级。可选。默认值为100。comment
(series string) 可选参数。订单的其他说明。alert_message
(series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。退出当前市场仓位,使其持平。
strategy.close_all(when, comment, alert_message)
例子
strategy("closeAll Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close_all(when = open < close, comment = "close all entries")
plot(strategy.position_size)
参数
when
(series bool) 可选参数。命令的条件。comment
(series string) 可选参数。订单的其他说明。alert_message
(series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。这是一个退出指定进场或整个市场地位的命令。 如果具有相同ID的订单已经挂起,则可修改订单。 如果进场订单未成交,但是出现退场订单,该退场订单将暂待,直到进场订单成交后方可放置退场订单。 要停用退场订单,应使用命令strategy.cancel或strategy.cancel_all。 如果函数strategy.exit被调用一次,则只会退出一次。 如果要退出多次,应该多次调用命令strategy.exit。 如果您使用止损和追踪止损,其订单类型是“stop”,只有其中一个会被放置(会首先被成交)。 如果以下所有参数 ‘profit’, ‘limit’, ‘loss’, ‘stop’, ‘trail_points’, ‘trail_offset’ 皆为“NaN”,则命令将失败。 要使用市场订单离场,应使用命令strategy.close或strategy.close_all。
strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, oca_name, comment, when, alert_message)
例子
strategy(title = "simple strategy exit example")
strategy.entry("long", strategy.long, 1, when = open > high[1]) // enter long by market if current open great then previous high
strategy.exit("exit", "long", profit = 10, loss = 5) // generate full exit bracket (profit 10 points, loss 5 points per contract) from entry with name "long"
参数
id
(series string) 必要参数。 订单标识符。 可以通过引用其标识来取消或修改订单。from_entry
(series string) 可选参数。以指定进场指令标识符退出。 要退出所有头寸,应使用空字符串。 默认值为空字符串。qty
(series int/float) 可选参数。退出交易的合约/股数/手数/单位的数量。默认值为’NaN’。qty_percent
(series int/float) 定义平仓的百分比(0-100)。它的优先级低于 ‘qty’ 参数的优先级。可选。默认值为100。profit
(series int/float) 可选参数。 利润目标(以点表示)。 如果已指定,当达到指定的利润额(点)时,则以限价订单退出市场头寸。 默认值为“NaN”。limit
(series int/float) 可选参数。 利润目标(需指定价格)。 若已指定,则以指定价格(或更好)退出市场头寸。 参数’limit’的优先级高于参数’profit’的优先级(若值非’NaN’,则’limit’取代’profit’)。 默认值为“NaN”。loss
(series int/float) 可选参数。 止损(以点表示)。 如果已指定,当达到指定的亏损额(点)时,则以停损单退出市场头寸。 默认值为“NaN”。stop
(series int/float) 可选参数。 止损(需指定价格)。 如果已指定,则将以指定价格(或更差)退出市场头寸。 参数’止损’的优先级高于参数’损失’的优先级(若值非’NaN’,则’止损’代替’损失’)。 默认值为“NaN”。trail_price
(series int/float) 可选参数。跟踪止损激活水平(需指定价格)。如果已指定,当达到指定价格水平时,将放置跟踪止损单。在“trail_offset”参数中指定用于确定跟踪止损单初始价格的偏移量(以点计):X 点低于激活水平以退出多头; X点高于激活水平以退出空头。默认值为“NaN”。trail_points
(series int/float) 可选参数。跟踪止损激活水平(利润以点表示)。如果已指定,当达到已计算价格水平(指定利润金额)时,将放置跟踪止损单。在“trail_offset”参数中指定用于确定跟踪止损单初始价格的偏移量(以点计):X 点低于激活水平以退出多头; X点高于激活水平以退出空头。默认值为“NaN”。trail_offset
(series int/float) 可选参数。跟踪止损激活水平(以点表示)。以点计的偏移量用于确定跟踪止损单的初始价格:X 点低于’trail_price’ or 'trail_points’以退出多头; X点高于 ‘trail_price’ or 'trail_points’以退出空头。默认值为“NaN”。oca_name
comment
(series string) 可选参数。订单的其他说明。when
(series bool) 可选参数。订单的状况。若为"true",订单被放置。若为"false",则没有任何事情发生(之前放置的相同 ID 的订单没有被撤销)。默认值为"true"。alert_message
(series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。这是引用名称来取消/停用所有预挂单的命令,由以下功能生成:strategy.order, strategy.entry and strategy.exit。
strategy.cancel(id, when)
例子
strategy(title = "simple order cancellation example")
conditionForBuy = open > high[1]
strategy.entry("long", strategy.long, 1, limit = low, when = conditionForBuy) // enter long using limit order at low price of current bar if conditionForBuy is true
strategy.cancel("long", when = not conditionForBuy) // cancel the entry order with name "long" if conditionForBuy is false
参数
id
(series string) 必选参数。订单标识。定位该标识以撤销一个订单。when
(series bool) 可选参数。根据 ID 取消一个订单。若为"true",该订单将被取消。默认值为"true"。这是取消/停用所有预挂单命令,由以下功能生成:strategy.order,strategy.entry和strategy.exit。
strategy.cancel_all(when)
例子
strategy(title = "simple all orders cancellation example")
conditionForBuy1 = open > high[1]
strategy.entry("long entry 1", strategy.long, 1, limit = low, when = conditionForBuy1) // enter long by limit if conditionForBuy1 is true
conditionForBuy2 = conditionForBuy1 and open[1] > high[2]
strategy.entry("long entry 2", strategy.long, 1, limit = ta.lowest(low, 2), when = conditionForBuy2) // enter long by limit if conditionForBuy2 is true
conditionForStopTrading = open < ta.lowest(low, 2)
strategy.cancel_all(conditionForStopTrading) // cancel both limit orders if the conditon conditionForStopTrading is true
参数
when
(series bool) 可选参数。取消所有订单的条件。如果条件为真,则所有活动订单将被取消。默认值为“true”。这是下订单的命令。 如果具有相同ID的订单已经挂起,则可以修改订单。 如果没有指定ID的订单,则会发出新的订单。 要停止订单,应使用命令strategy.cancel或strategy.cancel_all。 与函数strategy.entry相比,函数strategy.order不受金字塔形式的影响。 如果“限制”和“止损”参数均为“NaN”,则订单类型为市场订单。
strategy.order(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message)
例子
strategy(title = "simple strategy order example")
strategy.order("buy", strategy.long, 1, when = open > high[1]) // buy by market if current open great then previous high
strategy.order("sell", strategy.short, 1, when = open < low[1]) // sell by market if current open less then previous low
参数
id
(series string) 必要参数。 订单标识符。 可以通过引用其标识来取消或修改订单。direction
(strategy_direction) 一个必需的参数。订单方向:'strategy.long’为买入,'strategy.short’为卖出。qty
(series int/float) 可选参数。交易的合约/股数/手数/单位数量。预设值为’NaN’。limit
(series int/float) 可选参数。订单的限价。若已指定,订单类型是"limit" 或"stop-limit"。其他订单类型为"NaN"。stop
(series int/float) 可选参数。订单的止损价。如果已指定,订单类型为"stop"或"stop-limit"。其他订单类型则为"NaN"。oca_name
oca_type
comment
(series string) 可选参数。订单的其他说明。when
(series bool) 可选参数。订单的状况。若为"true",订单被放置。若为"false",则没有任何事情发生(之前放置的相同 ID 的订单没有被撤销)。默认值为"true"。alert_message
(series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。返回未平仓交易入场的bar_index。
strategy.opentrades.entry_bar_index(trade_num)
等待10根K线并平仓
例子
strategy("`strategy.opentrades.entry_bar_index` Example")
barsSinceLastEntry() =>
strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
// Enter a long position if there are no open positions.
if strategy.opentrades == 0
strategy.entry("Long", strategy.long)
// Close the long position after 10 bars.
if barsSinceLastEntry() >= 10
strategy.close("Long")
参数
trade_num
(series int) 未平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.entry_bar_index
strategy.closedtrades.exit_bar_index
返回未平仓交易的入场的ID。
strategy.opentrades.entry_id(trade_num)
例子
strategy("`strategy.opentrades.entry_id` Example", overlay = true)
// We enter a long position when 14 period sma crosses over 28 period sma.
// We enter a short position when 14 period sma crosses under 28 period sma.
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
// Strategy calls to enter a long or short position when the corresponding condition is met.
if longCondition
strategy.entry("Long entry at bar #" + str.tostring(bar_index), strategy.long)
if shortCondition
strategy.entry("Short entry at bar #" + str.tostring(bar_index), strategy.short)
// Display ID of the latest open position.
if barstate.islastconfirmedhistory
runtime.log("Last opened position is " + strategy.opentrades.entry_id(strategy.opentrades - 1))
返回值 返回未平仓交易的入场的ID。
参数
trade_num
(series int) 未平仓交易的交易编号。第一笔交易的编号为零。备注 如果 trade_num 不在范围内,则该函数返回 na:0 到 strategy.opentrades-1。
另见
strategy.opentrades.entry_bar_index
strategy.opentrades.entry_time
返回未平仓交易的入场价格。
strategy.opentrades.entry_price(trade_num)
例子
strategy("strategy.closedtrades.entry_price Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Return the entry price for the latest closed trade.
entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
plot(entryPrice, "Long entry price")
计算平均未平仓价格
例子
strategy("strategy.opentrades.entry_price Example 2", pyramiding = 2)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate average open position price.
avgOpenPositionPrice() =>
sumOpenPositionPrice = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenPositionPrice += strategy.opentrades.entry_price(tradeNo) * strategy.opentrades.size(tradeNo) / strategy.position_size
result = nz(sumOpenPositionPrice / strategy.opentrades)
plot(avgOpenPositionPrice())
参数
trade_num
(series int) 未平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.exit_price
返回未平仓交易入场的UNIX时间。
strategy.opentrades.entry_time(trade_num)
例子
strategy("strategy.opentrades.entry_time Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculates duration in milliseconds since the last position was opened.
timeSinceLastEntry()=>
strategy.opentrades > 0 ? (time - strategy.opentrades.entry_time(strategy.opentrades - 1)) : na
plot(timeSinceLastEntry() / 1000 * 60 * 60 * 24, "Days since last entry")
参数
trade_num
(series int) 未平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.entry_time
strategy.closedtrades.exit_time
返回未平仓交易的盈亏。损失表示为负值。
strategy.opentrades.profit(trade_num)
返回最后开仓交易的利润
例子
strategy("`strategy.opentrades.profit` Example 1", commission_type = strategy.commission.percent, commission_value = 0.1)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
plot(strategy.opentrades.profit(strategy.opentrades - 1), "Profit of the latest open trade")
计算所有未平仓交易的利润
例子
strategy("`strategy.opentrades.profit` Example 2", pyramiding = 5)
// Strategy calls to enter 5 long positions every 2 bars.
if bar_index % 2 == 0
strategy.entry("Long", strategy.long, qty = 5)
// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
sumProfit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
plot(tradeOpenPL(), "Profit of all open trades")
参数
trade_num
(series int) 未平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.profit
strategy.openprofit
strategy.netprofit
strategy.grossprofit
返回未平仓交易中的交易方向和合约数量。如果该值>0,则市场仓位为多头。如果该值<0,则市场仓位为空头。
strategy.opentrades.size(trade_num)
例子
strategy("`strategy.opentrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtShares = math.floor(strategy.equity / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = amtShares)
if bar_index % 20 == 0
strategy.close("Long")
// Plot the number of contracts in the latest open trade.
plot(strategy.opentrades.size(strategy.opentrades - 1), "Amount of contracts in latest open trade")
计算未平仓交易的平均利润百分比
例子
strategy("`strategy.opentrades.size` Example 2")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate profit for all open trades.
profitPct = 0.0
for tradeNo = 0 to strategy.opentrades - 1
entryP = strategy.opentrades.entry_price(tradeNo)
exitP = close
profitPct += (exitP - entryP) / entryP * strategy.opentrades.size(tradeNo) * 100
// Calculate average profit percent for all open trades.
avgProfitPct = nz(profitPct / strategy.opentrades)
参数
trade_num
(series int) 未平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.size
strategy.position_size
strategy.opentrades
strategy.closedtrades
返回已平仓交易入场的bar_index。
strategy.closedtrades.entry_bar_index(trade_num)
例子
strategy("strategy.closedtrades.entry_bar_index Example")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars in a trade.
avgBarsPerTrade() =>
sumBarsPerTrade = 0
for tradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumBarsPerTrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumBarsPerTrade / strategy.closedtrades)
plot(avgBarsPerTrade())
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.exit_bar_index
strategy.opentrades.entry_bar_index
返回已平仓交易的出场价格。
strategy.closedtrades.exit_price(trade_num)
例子
strategy("strategy.closedtrades.exit_price Example 1")
// We are creating a long trade every 5 bars
if bar_index % 5 == 0
strategy.entry("Long", strategy.long)
strategy.close("Long")
// Return the exit price from the latest closed trade.
exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)
plot(exitPrice, "Long exit price")
计算所有已平仓交易的平均利润百分比
例子
strategy("strategy.closedtrades.exit_price Example 2")
// Strategy calls to create single short and long trades.
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("Short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("Short")
// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)
plot(avgProfitPct)
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.entry_price
返回已平仓交易退出的bar_index。
strategy.closedtrades.exit_bar_index(trade_num)
例子
strategy("strategy.closedtrades.exit_bar_index Example 1")
// Strategy calls to place a single short trade. We enter the trade at the first bar and exit the trade at 10 bars before the last chart bar.
if bar_index == 0
strategy.entry("Short", strategy.short)
if bar_index == last_bar_index - 10
strategy.close("Short")
// Calculate the amount of bars since the last closed trade.
barsSinceClosed = strategy.closedtrades > 0 ? bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) : na
plot(barsSinceClosed, "Bars since last closed trade")
计算每笔交易的平均K线数。
例子
strategy("strategy.closedtrades.exit_bar_index Example 2")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars per trade.
avgBarsPerTrade() =>
sumBarsPerTrade = 0
for tradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumBarsPerTrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumBarsPerTrade / strategy.closedtrades)
plot(avgBarsPerTrade())
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
bar_index
返回已平仓交易的入场的id。
strategy.closedtrades.entry_id(trade_num)
例子
strategy("strategy.closedtrades.entry_id Example", overlay = true)
var isOpen = false
var openIndex = -1
// Enter a short position and close at the previous to last bar.
if not barstate.ishistory and not isOpen
strategy.entry("Short at bar #" + str.tostring(bar_index), strategy.short)
isOpen := true
openIndex := bar_index
if openIndex != -1 and bar_index > openIndex + 100
strategy.close_all()
// Display ID of the last entry position.
if barstate.islastconfirmedhistory
runtime.log("Last Entry ID is: " + strategy.closedtrades.entry_id(strategy.closedtrades - 1))
返回值 返回已平仓交易的入场的id。
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。备注 如果 trade_num 不在范围内,则该函数返回 na:0 到 strategy.closedtrades-1。
另见
strategy.closedtrades.entry_bar_index
strategy.closedtrades.entry_time
返回已平仓交易的入场价格。
strategy.closedtrades.entry_price(trade_num)
例子
strategy("strategy.closedtrades.entry_price Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Return the entry price for the latest entry.
entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
plot(entryPrice, "Long entry price")
计算所有已平仓交易的平均利润百分比
例子
strategy("strategy.closedtrades.entry_price Example 2")
// Strategy calls to create single short and long trades
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("Short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("Short")
// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)
plot(avgProfitPct)
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.exit_price
strategy.closedtrades.size
strategy.closedtrades
返回已平仓交易入场的UNIX时间。
strategy.closedtrades.entry_time(trade_num)
例子
strategy("strategy.closedtrades.entry_time Example", overlay = true)
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Calculate the average trade duration
avgTradeDuration() =>
sumTradeDuration = 0
for i = 0 to strategy.closedtrades - 1
sumTradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumTradeDuration / strategy.closedtrades)
// Display average duration converted to seconds and formatted using 2 decimal points
if barstate.islastconfirmedhistory
runtime.log(str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.opentrades.entry_time
strategy.closedtrades.exit_time
time
返回已平仓交易的盈亏。损失表示为负值。
strategy.closedtrades.profit(trade_num)
例子
strategy("`strategy.closedtrades.profit` Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate average gross profit by adding the difference between gross profit and commission.
avgGrossProfit() =>
sumGrossProfit = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
sumGrossProfit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
result = nz(sumGrossProfit / strategy.closedtrades)
plot(avgGrossProfit(), "Average gross profit")
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.opentrades.profit
strategy.closedtrades.commission
返回已平仓交易中的交易方向和合约数量。如果该值>0,则市场仓位为多头。 如果该值<0,则市场仓位为空头。
strategy.closedtrades.size(trade_num)
例子
strategy("`strategy.closedtrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtShares = math.floor(strategy.equity / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = amtShares)
if bar_index % 20 == 0
strategy.close("Long")
// Plot the number of contracts traded in the last closed trade.
plot(strategy.closedtrades.size(strategy.closedtrades - 1), "Number of contracts traded")
计算平仓交易的平均利润百分比
例子
strategy("`strategy.closedtrades.size` Example 2")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)
plot(avgProfitPct)
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.opentrades.size
strategy.position_size
strategy.closedtrades
strategy.opentrades
返回已平仓交易退出的UNIX时间。
strategy.closedtrades.exit_time(trade_num)
例子
strategy("strategy.closedtrades.exit_time Example 1")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Calculate the average trade duration.
avgTradeDuration() =>
sumTradeDuration = 0
for i = 0 to strategy.closedtrades - 1
sumTradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumTradeDuration / strategy.closedtrades)
// Display average duration converted to seconds and formatted using 2 decimal points.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")
X秒后重新打开已平仓交易
例子
strategy("strategy.closedtrades.exit_time Example 2")
// Strategy calls to emulate a single long trade at the first bar.
if bar_index == 0
strategy.entry("Long", strategy.long)
reopenPositionAfter(timeSec) =>
if strategy.closedtrades > 0
if time - strategy.closedtrades.exit_time(strategy.closedtrades - 1) >= timeSec * 1000
strategy.entry("Long", strategy.long)
// Reopen last closed position after 120 sec.
reopenPositionAfter(120)
if ta.change(strategy.opentrades)
strategy.exit("Long", stop = low * 0.9, profit = high * 2.5)
参数
trade_num
(series int) 已平仓交易的交易编号。第一笔交易的编号为零。另见
strategy.closedtrades.entry_time
此函数可用于指定strategy.entry函数允许在哪个市场方向开仓。
strategy.risk.allow_entry_in(value)
例子
strategy("strategy.risk.allow_entry_in")
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", strategy.long, when = open > close)
// Instead of opening a short position with 10 contracts, this command will close long entries.
strategy.entry("Short", strategy.short, when = open < close, qty = 10)
参数
value
(simple string) 允许的方向。可能的值:strategy.direction.all
、strategy.direction.long
、strategy.direction.short
此规则的目的是确定市场头寸的最大值。 该规则影响以下功能:strategy.entry
。 “entry”数量可以减少(如果需要)到合同/股/手/单位数,所以头寸总值不超过’strategy.risk.max_position_size’中指定的值。如果最低数量仍然违反规则,则不会放置订单。
strategy.risk.max_position_size(contracts)
例子
strategy("risk.max_position_size Demo", default_qty_value = 100)
strategy.risk.max_position_size(10)
strategy.entry("buy", strategy.long, when = open > close)
plot(strategy.position_size) // max plot value will be 10
参数
contracts
(simple int/float) 必要参数。仓位的合同/股/手/单位的最大数。如果 number
>= 0,number
的绝对值为 number
,否则为 -number
。
math.abs(number)
返回值
number
的绝对值。
acos函数返回数字的反余弦(以弧度表示),如cos(acos(y)) = y 在 y 范围内 [-1, 1]。
math.acos(angle)
返回值 反余弦值。如果y超出范围[-1,1],返回角度在[0,Pi]或na的范围内。
返回伪随机值。该函数将为每个脚本执行生成不同的值序列。对可选的seed参数使用相同的值将产生可重复的序列。
math.random(min, max, seed)
返回值 一个随机值。
参数
min
(series int/float) 随机值范围的下限。该值不包括在范围内。默认值为0。max
(series int/float) 随机值范围的上限。该值不包括在范围内。默认值为1。seed
(input int) 可选参数。当使用相同的seed时,允许连续调用该函数以产生一组可重复的值。asin函数返回数字的反正弦(以弧度表示),正弦(asin(y)) = y 在 y 范围内[-1, 1]。
math.asin(angle)
返回值 反正弦值。如果y超出范围[-1,1],返回角度在[-Pi / 2,Pi / 2]或na的范围内。
atan函数返回数字的反正切(以弧度表示),tan(atan(y)) = 任何 y 中的 y。
math.atan(angle)
返回值 反正切值; 返回角度在[-Pi / 2,Pi / 2]的范围内。
向上取整函数返回大于或等于参数的最小(最接近负无穷)整数。
math.ceil(number)
返回值 小于或等于给定数字的最小整数
另见
math.floor
math.round
cos函数返回角度的三角余弦。
math.cos(angle)
返回值 角的三角余弦。
参数
angle
(series int/float) 角度,以弧度number
的 exp 函数是 e 的 number
次方,其中 e 是欧拉数。
math.exp(number)
返回值
一个表示 e 的值,它是 number
的幂。
另见
math.pow
math.floor(number)
返回值 小于或等于给定数字的最大整数。
另见
math.ceil
math.round
任何 number
> 0 的自然对数是唯一的 y,使得 e^y = number
。
math.log(number)
返回值
number
的自然对数。
另见
math.log10
number
的常用(或以10为底的)对数是必须将10提高到的幂才能获得number
。10^y = number
。
math.log10(number)
返回值
number
的以10为底的对数。
另见
math.log
数学幂函数
math.pow(base, exponent)
例子
// math.pow
plot(math.pow(close, 2))
返回值
base
提高到exponent
的幂。如果base
是一个系列,它是按元素计算的。
参数
base
(series int/float) 指定要使用的基础。exponent
(series int/float) 指定指数。另见
math.sqrt
math.exp
如果“number”为零,则“number”的符号(signum)为零,如果“number”大于0,则为1.0,如果“number”小于0,则为-1.0。
math.sign(number)
返回值 参数的标志。
正弦函数返回一个角度的三角正弦。
math.sin(angle)
返回值 角的三角正弦。
参数
angle
(series int/float) 角度,以弧度任何number
>= 0的平方根是唯一的y >= 0使得y^2 = number
。
math.sqrt(number)
返回值
number
的平方根。
另见
math.pow
tan函数返回角度的三角正切。
math.tan(angle)
返回值 角的三角正切。
参数
angle
(series int/float) 角度,以弧度返回 number
的值,四舍五入到最接近的整数,并向上取整。如果使用了 precision
参数,则返回一个四舍五入到小数位数的浮点值。
math.round(number)
math.round(number, precision)
返回值
number
的值四舍五入到最接近的整数,或根据精度。
参数
number
(series int/float) 要四舍五入的值。precision
(series int) 可选参数。number
将被四舍五入的小数位数。当没有提供参数时,四舍五入到最接近的整数。备注 请注意,对于’na’值,函数返回’na’。
另见
math.ceil
math.floor
返回多个值中最大的一个。
math.max(number0, number1, ...)
例子
// math.max
plot(math.max(close, open))
plot(math.max(close, math.max(open, 42)))
返回值 多个给定值中最大的。
另见
math.min
返回多个值中最小的一个。
math.min(number0, number1, ...)
例子
// math.min
plot(math.min(close, open))
plot(math.min(close, math.min(open, 42)))
返回值 多个给定值中的最小值。
另见
math.max
计算所有系列的平均值(对应元素)。
math.avg(number0, number1, ...)
返回值 平均
另见
math.sum
ta.cum
ta.sma
返回四舍五入到商品的mintick的值,即可以除以syminfo.mintick的最接近的值,没有余数,并向上舍入。
math.round_to_mintick(number)
返回值
number
四舍五入以精确到tick。
参数
number
(series int/float) 要四舍五入的值。另见
math.ceil
math.floor
sum函数返回x的最后y值的滑动综合。
math.sum(source, length)
返回值
length
K线返回的source
总和。
参数
source
(series int/float) 待执行的系列值。length
(series int) K线数量(长度).另见
ta.cum
for
从以弧度为单位的角度,返回以度为单位的近似等效角度。
math.todegrees(radians)
返回值 以度为单位的角度值。
参数
radians
(series int/float) 以弧度为单位的角度。从以度为单位的角度,返回以弧度为单位的近似等效角度。
math.toradians(degrees)
返回值 以弧度为单位的角度值。
参数
degrees
(series int/float) 以度为单位的角度。对于给定的系列,将NaN值替换为先前的非NaN值。
fixnan(source)
返回值 无na间隙的系列。
参数
source
(series int/float/bool/color)另见
na
nz
以系列中的零(或指定数)替换NaN值。
nz(source, replacement)
nz(source)
例子
// nz
plot(nz(ta.sma(close, 100)))
返回值
source
的值,如果它不是na
。如果source
的值为na
,则返回0,如果使用1,则返回replacement
参数。
参数
source
(series int/float/bool/color) 待执行的系列值。replacement
(series int/float/bool/color) 将替换“source”系列中的所有“na”值的值。另见
na
fixnan
如为NaN,则测试价值。
na(x)
返回值 如果x非有效数字,则为true(x为NaN),否则为false。
另见
fixnan
nz
转换na或将float值截断为int。
int(x)
返回值 转换为int后的参数值。
另见
float
bool
color
string
将na设置为浮动。
float(x)
返回值 转换为float后的参数值。
另见
int
bool
color
string
在实时K线期间调用时触发警报事件,并且之前通过“创建警报”对话框为指标或策略创建了基于警报功能事件的警报。
alert(message, freq)
例子
// alert() example
ma = ta.sma(close, 14)
xUp = ta.crossover(close, ma)
if xUp
// Trigger the alert the first time a cross occurs during the real-time bar.
alert("Price (" + str.tostring(close) + ") crossed over MA (" + str.tostring(ma) + ").", alert.freq_once_per_bar)
plot(ma)
plotchar(xUp, "xUp", "▲", location.top, size = size.tiny)
参数
message
(series string) 警报触发时发送的消息。必填参数。freq
(input string) 触发频率。可能的值为:alert.freq_all(所有函数调用触发警报),alert.freq_once_per_bar(K线中的第一个函数调用触发警报),alert.freq_once_per_bar_close(函数调用仅在实时K线的最后一个脚本迭代期间发生时,在关闭时才触发警报)。默认值为alert.freq_once_per_bar。备注 帮助中心介绍了如何创建此类警报。 与alertcondition相反,alert调用不算作额外的绘图。 函数调用可以位于全局和局部范围内。 函数调用在图表上不显示任何内容。 ‘freq‘参数仅影响使用此函数调用之处的触发频率。
另见
alertcondition
创建警报条件,在创建警报话框中可用。 请注意,alertcondition不会创建警报,它只会在创建警报对话框中为您提供更多选项。 此外,alertcondition效果在图表上是看不见的。
alertcondition(condition, title, message)
例子
// alertcondition
alertcondition(close >= open, title='Alert on Green Bar', message='Green Bar!')
参数
condition
(series bool) 用于警报的系列布尔值。 True值代表警报触发,false - 无警报。 必要参数。title
(const string) 警报条件的标题。 可选参数。message
(const string) 当警报触发时显示消息。可选参数。备注 请注意,在Pine v4中,警报条件调用会生成一个额外的图。 当我们计算每个脚本的输出系列的数量时,会考虑所有这些调用。
另见
alert
为了兼容Trading View
策略代码,实际不需要调用。
另见
strategy
time函数返回指定时间范围和交易时段的当前K线的UNIX时间,如果时间点不在交易时段中,则返回NaN。注意:FMZ不支持session
参数。
time(timeframe, session, timezone)
time(timeframe, session)
time(timeframe)
例子
timeinrange(res, sess) => not na(time(res, sess, "America/New_York")) ? 1 : 0
plot(timeinrange("1", "1300-1400"), color=color.red)
// This plots 1.0 at every start of 10 minute bar on a 1 minute chart:
newbar(res) => ta.change(time(res)) == 0 ? 0 : 1
plot(newbar("10"))
当设置某个会话时,您不仅可以指定小时与分钟,也可以指定某一周内的日期。 如果没有指定日期,则认为交易时段设置为从星期日 (1) 到星期六 (7),即“1100-2000”与“1100-1200:1234567”相同。 您可以通过指定日期来更改它。例如,对于每周7天交易且24小时交易时段的商品,以下脚本不会为周六和周日着色:
例子
// Time
t1 = time(timeframe.period, "0000-0000:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)
一个session
参数可以包含多个不同的交易时段,以逗号分隔。例如,以下脚本将突出显示从10:00到11:00以及从14:00到15:00(仅限工作日)的K线图:
例子
// Time
t1 = time(timeframe.period, "1000-1100,1400-1500:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)
返回值 Unix时间。
参数
timeframe
(simple string) 时间周期。空字符串被解释为图表的当前时间周期。session
timezone
(simple string) session
参数的时区。只能在指定了“会话”时使用。可选。默认值为syminfo.timezone。可以用GMT表示法(例如“GMT-5”)或 IANA 时区数据库名称(例如“America/New_York”)指定。备注 UNIX时间是自1970年1月1日UTC 00:00:00起已经过去的毫秒数。
year(time)
year(time, timezone)
返回值 提供UNIX时间的年份(交换时区)。
参数
time
(series int) 以毫秒为单位的unix时间。timezone
(series string) 可选参数。时区。备注 UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。 请注意,此函数根据K线的打开时间返回年份。对于隔夜交易时段(例如EURUSD周一交易时段从周日17:00 UTC-4开始),该值可以比交易日的年份低1。
另见
year
time
month
dayofmonth
dayofweek
hour
minute
second
month(time)
month(time, timezone)
返回值 提供UNIX时间的月份(交换时区)。
参数
time
(series int) 以毫秒为单位的unix时间。timezone
(series string) 可选参数。时