//@version=5 strategy("negative_qty", default_qty_type = strategy.percent_of_equity)
if strategy.equity > 0 strategy.entry("Short", strategy.short)
hline(0, "zero line", color = color.black, linestyle = hline.style_dashed) plot(strategy.equity, color = color.black, linewidth = 3)
在第二根K線開盤時 (bar_index = 1),策略進入空頭倉位。但隨著AAPL值的增長,空頭倉位Short的利潤(strategy.openprofit 變量的值)直線下降,最終策略的資本(strategy.equity = strategy.initial_capital + strategy.netprofit + strategy.openprofit ) 變為負數。策略引擎計算的合約數量計算為 qty = (order size * equity / 100) / close.。策略資本變為負值的區域可以顯示如下://@version=5 strategy("negative_qty", default_qty_type = strategy.percent_of_equity)
if strategy.equity > 0 strategy.entry("Short", strategy.short)
hline(0, "zero line", color = color.black, linestyle = hline.style_dashed) plot(strategy.equity, color = color.black, linewidth = 3) equity_p = 1 // percents of equity order size value (1% is default) qty = (equity_p * strategy.equity / 100) / close if qty <= -1 var l1 = label.new(bar_index, strategy.equity, text = "Negative qty_value at \n bar index: " + str.tostring(bar_index) + ".\n" + "Order size: " + str.tostring(math.round(qty)), color = color.white) var l2 = label.new(bar_index - 1, strategy.equity[1], text = "Order size : " + str.tostring(math.round(qty[1])), color = color.white) var l3 = label.new(bar_index - 2, strategy.equity[2], text = "Order size: " + str.tostring(math.round(qty[2])), color = color.white) bgcolor(qty > -1 ? color.green : color.red)
螢幕截圖顯示了位於負資產部分的標簽,其中生成的合約數量為 - 2。綠色部分的合約數量 >= 0: 如果在計算策略時,在淨值為負(且合約數量為負)的K線上調用 strategy.entry(),則策略計算將因錯誤而停止。我該如何解決?
通常,此錯誤不會出現在正確實施的策略中。為避免錯誤,該策略應使用進入和退出倉位、止損和保證金的條件。如果發生錯誤,調試策略的正確方法是: 1. 使用保證金槓桿(策略屬性中的多頭/空頭倉位保證金或 strategy() 函數中的 margin_long 和 margin_short 參數)。如果指定,如果策略沒有足夠的淨值來維持它,部分倉位將被自動清算。您可以在我們的用戶手冊中的文章或部落格文章中找到有關此功能的更多資訊。 //@version=5 strategy("", default_qty_type = strategy.percent_of_equity, default_qty_value = 10, margin_long = 100, margin_short = 100)
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) if (longCondition) strategy.entry("Long", strategy.long)
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28)) if (shortCondition) strategy.entry("Short", strategy.short)
2. 在調用 strategy.entry() 或 strategy.order() 函數或額外重新定義入場合約數量之前,檢查淨值是否大於零。//@version=5 strategy("", default_qty_type = strategy.percent_of_equity, default_qty_value = 10)
if strategy.equity > 0 strategy.entry("Short", strategy.short) // enter at 10 % of currently available equity else strategy.entry("Long", strategy.long, qty = 1) // Reverse position with fixed contract size
3. 使用 strategy.risk 類別的變數進行風險管理。您可以在我們的用戶手冊中閱讀有關這些的更多資訊。