這回測不能停損的問題,我爬文猜測應該是因為條件觸發 SetPosition 的話只能執行第一次SetPosition
但我的腳本應該沒有這個問題, 思考了許久一直想不出來問題在哪......缺高人指點...只好上來當伸手牌...我先道歉
在先謝謝各位
一個單純的當沖腳本
跌破月線放空 漲2.5%停損
時間13.20回補
// 設定參數
input: capital(10, "下單金額(萬)"), // 開倉金額
stop_loss_percentage(2.5, "停損百分比 (%)"),
ma_length(20, "月均線天數");
// 宣告變數
var: ma_value(0), // 月均線值(使用日級別)
position_size(0), // 開倉股數
stop_loss_price(0), // 停損價格
current_time(0), // 當前時間
day_close(0), // 日級別收盤價
day_high(0); // 日級別最高價
// 取得日級別數據
day_close = GetField("收盤價", "D");
day_high = GetField("最高價", "D");
// 計算日級別的 20 日均線
ma_value = Average(GetField("收盤價", "D"), ma_length);
// 取得當前時間
current_time = GetField("時間");
// 開倉邏輯:日級別股價剛從月線上方跌破月線,且在交易時間內
if Position = 0 and day_close < ma_value and day_high >= ma_value and current_time < 132000 then begin
// 計算開倉股數(取整數)
position_size = IntPortion((capital * 10000) / (Close * 1000)); // 使用 5 分鐘收盤價作為進場價格
if position_size > 0 then begin
SetPosition(-position_size); // 掛出空單委託
end;
end;
// 初始化停損價格
if Position < 0 and Filled < 0 and stop_loss_price = 0 then begin
stop_loss_price = FilledAvgPrice * (1 + stop_loss_percentage * 0.01); // 設定初始停損價格
end;
// 停損邏輯
if Position < 0 and Filled < 0 and Close > stop_loss_price then begin
SetPosition(0); // 停損出場
end;
// 強制平倉邏輯:在 13:20 時間平倉
if Position < 0 and Filled < 0 and current_time >= 132000 then begin
SetPosition(0); // 強制平倉
end;
// 輸出測試資訊
print("當前價格:", Close, " | 月均線:", ma_value,
" | 庫存成本:", FilledAvgPrice, " | 停損價格:", stop_loss_price,
" | 當前時間:", current_time, " | 日級別收盤價:", day_close,
" | 日級別最高價:", day_high);
9 評論