回測如何用FilledRecordDate實現持有五天後才加碼的邏輯

  •   29 
  • 最後發表   蓬蘇王杜  2025 八月 28
蓬蘇王杜 發文於   2025/08/25

如題  我用以下的寫法可以在實際的交易腳本抓到第一單庫存進場多久的天數

var : hold_days (0) ;
if filled >0 THEN hold_days = DateDiff( CurrentDate,FilledRecordDate(1) ) + 1 ;

 

所以我以此為構想 ,想寫出一個持有至少五天線且最近五天的低點有跌破五日  ,意思是有一段小區間整理後再加碼的邏輯,程式碼如下

 

//第三次加碼
if filled >0 then
   value6 = DateDiff( CurrentDate,FilledRecordDate(1) ) + 1 ;  //持有天數

condition4 = lowest(close,5) <= average(close,5) ;  //最近五天有跌破五日線
condition5 = value6 >= 10 ;  //母單進場超過五天
condition6 = close >= highest(close,5)[1] ; //突破小盤整區


if filled = 3 and condition4 and condition5 and condition6 and close > filledavgPrice then
   setposition(4 , label:="第2次加碼") ;

 

但我發現回測並不會實現我想要的邏輯 我把資料print出來看後 ,發現 持有天數會無止境的提升,這邊我附上檔案

這個腳本有2次加碼 ,第一次加碼條件為母單獲利5% ,第二次條件就是持有五天後再判斷的邏輯 ,但回測會在第一次加碼後馬上加碼第二次,大部分情況都是這樣  , 實在不知道如何處理 ,想上來請教一下 謝謝大家  ,以下附上全部程式碼

value1 = 12 ;  //停損  
value2 = 30 ; //停利點  
value4 = lowest (low,value2)[1] ; //停利點  
value5 = GetField("股本(億)");   


condition1 = close >= close[1]*1.08 ;  
condition2 = close >= close[3]*1.08 ;  
condition3 = value5 >= 50 ;  

//第三次加碼
if filled >0 then
   value6 = DateDiff( CurrentDate,FilledRecordDate(1) ) + 1 ;  //持有天數

condition4 = lowest(close,5) <= average(close,5) ;  //最近五天有跌破五日線
condition5 = value6 >= 10 ;  //母單進場超過五天
condition6 = close >= highest(close,5)[1] ; //突破小盤整區




if filled = 0 and condition3 then begin  
   if condition1 or condition1 then   
   setposition(1 , label:="進場") ;  

end;  

if filled = 1 and close < filledavgPrice*(1-value1*0.01) then  
   setposition(0 , label:="停損") ;  


if filled = 1 and close > filledavgPrice*1.05 then   
   setposition(3 , label:="加碼") ;  

if filled = 3 and close < filledavgPrice*0.96 then  
   setposition(0 , label:="加碼停損") ;

if filled = 3 and condition4 and condition5 and condition6 and close > filledavgPrice then
   setposition(4 , label:="第2次加碼") ;

if filled = 4 and close < filledavgPrice*0.97 then  
   setposition(0 , label:="加碼2停損") ;

if filled = 4 and close > filledavgPrice and close < value4 then  
   setposition(0 , label:="停利") ; 



 if filled > 0 then print("持有天數",value6) ;

 

 

附加文件

排序方式: 標準 | 最新
虎科大許教授 發文於   2025/08/25

(1)建議你不要往未來處理資料,而應該往前。例如進場之後,持有5天才加碼,不應該在進場時計算未來的5天,而應該在當下往前算進場至今有幾天。

(2)你的加碼、減碼的每個IF,都會逐一被執行。這種寫法有風險。若所有狀況,在當下只應出現一種,應該試著用IF的巢狀結構或Switch Case結構處理。

蓬蘇王杜 發文於   2025/08/25

謝謝教授這麼晚回答,

關於第一點我好奇我在實際腳本 ,也就是圖1 hold_days = 13 ,應該就是教授所說的當下往前推算有幾天的邏輯,不應該在進場時計算未來的五天是什麼意思

第二點我會再去研究寫法 ,謝謝教授

XS小編 發文於   2025/08/28

Hello 蓬蘇王杜,

 

小編補充,FilledRecordDate(1) 取得的會是回測期間內 "第一筆" 成交發生的日期。

因此在發生第一筆交易後,每經過一天 hold_days  都會增加1。

filled > 0 只會限制 hold_days 在有庫存的時候才更新,沒庫存的時候則維持在最後一次更新的狀況。

 

如果您要取得庫存為1時 (多方條件符合時的第一次進場) 的該筆交易日期,您應該用變數來保存 FilledRecordCount 才對。

舉例來說 

if filled = 1 then value1 = FilledRecordCount;

if filled >0 THEN hold_days = DateDiff( CurrentDate,FilledRecordDate(value1) ) + 1  else hold_days = 0;

這樣 hold_days 就會是距離每次多方進場時的第一次進場日期,且當平倉後 (沒庫存的時候) hold_days 會歸0。

蓬蘇王杜 發文於   2025/08/28

謝謝小編

發表回覆
Close