回測當天策略賣出後,不再進場的策略該怎麼寫

  •   429 
  • 最後發表   小金  2024 十月 17
小金 發文於   2024/10/09

我想撰寫一個無條件買入,
停損N%的交易策略。

但是我發現回測時
常常有賣出後1分鐘馬上進場
又再隔了1分鐘馬上賣出的訊號(請看附件檔案)

想問使用日頻率回測
如何設定當天賣出後不再進場?


以下是程式碼:

// 宣告變數
vars: myEntryPrice(0), myStopLossPrice(0), lastExitDate(0);

// 無條件進場,使用市價買入
if position = 0 and date <> lastExitDate then begin
    setposition(1, market);
    myEntryPrice = close; // 記錄進場價格
    myStopLossPrice = myEntryPrice * 0.85; // 設置停損價為進場價的85%
end;

// 檢查是否達到停損條件
if position = 1 and close <= myStopLossPrice then begin
    setposition(0); // 停損出場
    lastExitDate = date; // 記錄賣出日期
end;

附加文件

排序方式: 標準 | 最新
虎科大許教授 發文於   2024/10/09

你需要一個變數來控制。

var: intraBarPersist hasOrdered(false);

if position = 0 and date <> lastExitDate and hasOrdered=false then 

begin

setposition(1, market);

hasOrdered=true;

myEntryPrice = close; // 記錄進場價格

myStopLossPrice = myEntryPrice * 0.85; // 設置停損價為進場價的85%

end;

  • 按讚來自於
  • garyoling
小金 發文於   2024/10/09

感謝許教授的回復,我原本就有用lastExitDate來做控制,

加了您的建議,新增一個變數條件var: intraBarPersist hasOrdered(false);

反而變成回測沒有任何執行結果了

我一直覺得false的控制條件常常有問題

另外 intraBarPersist 也不是很確定使用的時機

希望能得到更多回復!

虎科大許教授 發文於   2024/10/09

用來回測時,你必須在每天開始時恢復這個變數為false,否則它一直是true,就不會再進場。

小金 發文於   2024/10/09

教授好,謝謝教授的回覆。

我修改了程式碼,

但發現好像還是有問題

會有賣出後又馬上買進的問題,

所以我錄了一段小影片來呈現問題。

影片網址:
https://vento.so/view/9c7ebb6c-2e23-4352-826e-840c46e2ce73?utm_medium=share

我認為可能是XQ的Bug

希望XQ小編或者教授能夠指點,謝謝!

程式碼如下:

// 宣告變數
vars: intraBarPersist myEntryPrice(0), myStopLossPrice(0), lastExitDate(0);
var: intraBarPersist hasOrdered(false);

if Date > lastExitDate and position = 0 then hasOrdered = false;

if position = 0 and hasOrdered = false then 

begin

setposition(1, market);

hasOrdered = true;

myEntryPrice = close; // 記錄進場價格

myStopLossPrice = myEntryPrice * 0.85; // 設置停損價為進場價的85%
end;

if position = 1 and close <= myStopLossPrice then begin
    setposition(0); // 停損出場
lastExitDate = date;

hasOrdered = false;

end;

虎科大許教授 發文於   2024/10/09

lastExitDate要加 intraBarPersist,不然出場後,儘管你設定它為今天,它仍然恢復到0而再次進場。

vars: intraBarPersist lastExitDate(0);

小金 發文於   2024/10/09

謝謝許教授的回覆!
原來intraBarPersist要每個變數前面都要宣告一次!

我以為最前面宣告就好了,
感謝教授!

XS小編 發文於   2024/10/17

Hello 小金,

 

小編補充,為了可以交替使用intrabarpersist的變數,故此功能是針對單一變數作宣告。

若您使用的四個變數都要宣告為 intrabarpersist 的話,應該要這樣寫:

vars: intraBarPersist myEntryPrice(0), intraBarPersist myStopLossPrice(0), intraBarPersist lastExitDate(0), intraBarPersist hasOrdered(false);

發表回覆
Close