變數更新行為不一致異常

  •   84 
  • 最後發表   竭力鼠  2024 一月 25
竭力鼠 發文於   2023/12/30

我想使用XS實現一個簡單的移動停利,程式碼如下

想請問為什麼: 我設定的StopPoint變數,在買入瞬間就已經進行數值更新

但在else if這部分的程式碼中再次使用到StopPoint,卻無法連貫,上述買入瞬間被更新的數值呢?

 

var: StopPoint(0);

 

value1=summation(GetField("外資買賣超", "D"),5);

condition1 = value1 > 1000;

 

if position = 0 and condition1 then 

begin

StopPoint = (close*0.9); // StopPoint更新位置1

print("Date=",Date,"Price*0.9=",StopPoint, "BUY");

setposition(1, close);

end

else if position > 0 then  // 更新位置1的更新結果,這邊的判斷皆會忽視他 

begin

print("Date=",Date,"Price*0.9=",StopPoint);

if (close*0.9) > StopPoint then

begin 

StopPoint = (close*0.9);

end

else if close <= StopPoint then

begin      

setposition(0, close);

end;

end;

 

會發現無法連貫,是因為我使用Print進行除錯時出現以下結果: (順帶一提,我只先使用2330進行回測,回測時間是20230102開始)

Date= 20230106.000000 Price*0.9= 409.950000 BUY 

Date= 20230106.000000 Price*0.9= 0.000000 

 

Date= 20230106.000000 Price*0.9= 0.000000 

 

... StopPoint=0 出現很多次,為了讀取方便,先將其省略

Date= 20230106.000000 Price*0.9= 0.000000 

Date= 20230106.000000 Price*0.9= 0.000000 

Date= 20230109.000000 Price*0.9= 412.650000 

Date= 20230109.000000 Price*0.9= 412.650000 

...

XQ小幫手 發文於   2024/01/25

Hello, 竭力鼠.

由於您沒有說明自動交易的設定,所以小幫手這邊回測試用日頻率,沒有遇到同樣的狀況,

小幫手將您的CODE 修改了一下,您可以在StopPoint賦值的時候Print,這樣可以確認這個StopPoint 是不是如您預想的一樣,

另外 您也可以在 StopPoint(0) 前面加上intrabarpersist,保護變數,

https://xshelp.xq.com.tw/XSHelp/?HelpName=IntraBarPersist&group=DECLARATION

 

var: intrabarpersist StopPoint(0);

value1=summation(GetField("外資買賣超", "D"),5);
condition1 = value1 > 1000;

if 
    position = 0 
    and condition1 
then begin
    StopPoint = (close*0.9); // StopPoint更新位置1
    print("Date=",Date,"Price*0.9=",StopPoint, "BUY");
    setposition(1, close);
end
else if 
    position > 0 
then  begin// 更新位置1的更新結果,這邊的判斷皆會忽視他 
    print("position > 0 Date=",Date,"Price*0.9=",StopPoint);
    if 
        (close*0.9) > StopPoint 
    then begin 
        StopPoint = (close*0.9);
        print("ReSet StopPoint Date=",Date,"Price*0.9=",StopPoint);
    end
    else if 
        close <= StopPoint 
    then begin      
        setposition(0, close);
        print("setposition(0) Date=",Date,"Price=",close,"Price*0.9=",StopPoint);
    end;
end;

謝謝。

發表回覆
Close