請問各位高手大大,利用自動交易寫個波段持股OR當天達到停利OR停損 出場,但是觸發進場條件後就出場了
if BarFreq <> "D" And BarFreq <> "AD" then RaiseRunTimeError("本策略限用日線或調整後日線週期");
// 檢查商品類型(限台灣股票)
if SymbolExchange <> "TW" then
RaiseRunTimeError("本策略限交易台灣證券交易所(上市&上櫃)商品");
// 輸入參數設定
input: ProfitPct(9, "停利百分比(%)"); // 停利百分比,預設9%
input: StopLossPct(7, "停損百分比(%)"); // 停損百分比,預設7%
input: MaxHoldDays(8, "最大持股天數"); // 最大持股天數,預設8天
// 變數宣告
variable: _EAM5(0); // 5日指數移動平均線
variable: _EAM10(0); // 10日指數移動平均線
variable: _MA60(0); // 季線 (60日簡單移動平均線)
variable: _MA120(0); // 半年線 (120日簡單移動平均線)
variable: _MA240(0); // 年線 (240日簡單移動平均線)
variable: _EntryPrice(0); // 進場價格
variable: _EntryBar(0); // 進場時的CurrentBar
variable: _CurrentProfitLossPct(0); // 當前損益百分比
// 計算各均線
_EAM5 = XAverage(C, 5); // 計算5日EAM (指數移動平均)
_EAM10 = XAverage(C, 10); // 計算10日EAM (指數移動平均)
_MA60 = Average(C, 60); // 計算60日MA (簡單移動平均)
_MA120 = Average(C, 120); // 計算120日MA (簡單移動平均)
_MA240 = Average(C, 240); // 計算240日MA (簡單移動平均)
// 進場條件判斷
If CrossOver(_EAM5, _EAM10) // 5日EAM向上突破10日EAM
And C > _MA60 // 收盤價大於季線
And C > _MA120 // 收盤價大於半年線
And C > _MA240 // 收盤價大於年線
And Position = 0 // 當前沒有委託單 (預計部位)
And Filled = 0 // 當前沒有實際持股
Then Begin
SetPosition(1, Market); // 設定目標部位為1張,並以市價買進
_EntryPrice = FilledAvgPrice; // 記錄實際成交的平均進場價格
_EntryBar = CurrentBar; // 記錄進場時的K棒序號
Print(Date, " 進場!股票代碼: ", Symbol, ", 進場價: ", NumToStr(_EntryPrice, 2));
End;
// 計算當前持股天數 (從進場K棒到當前K棒的間隔)
variable: _CurrentHoldDays(0);
if Position = 1 And Filled = 1 Then Begin
_CurrentHoldDays = CurrentBar - _EntryBar;
// 計算當前損益百分比
if _EntryPrice <> 0 then // 避免除以零
_CurrentProfitLossPct = (C - _EntryPrice) / _EntryPrice * 100;
Print(Date, " 股票代碼: ", Symbol, ", 當前持股天數: ", NumToStr(_CurrentHoldDays, 0), ", 損益: ", NumToStr(_CurrentProfitLossPct, 2), "%");
End;
// 出場條件判斷
// 停利條件: 當有持股且獲利達到設定百分比
If Position = 1 And Filled = 1 And C >= _EntryPrice * (1 + ProfitPct / 100) Then Begin
SetPosition(0, Market); // 設定目標部位為0張,並以市價賣出停利
Print(Date, " 停利出場!股票代碼: ", Symbol, ", 出場價: ", NumToStr(C, 2), ", 獲利: ", NumToStr(ProfitPct, 2), "%");
End;
// 停損條件: 當有持股且虧損達到設定百分比
If Position = 1 And Filled = 1 And C <= _EntryPrice * (1 - StopLossPct / 100) Then Begin
SetPosition(0, Market); // 設定目標部位為0張,並以市價賣出停損
Print(Date, " 停損出場!股票代碼: ", Symbol, ", 出場價: ", NumToStr(C, 2), ", 虧損: ", NumToStr(StopLossPct, 2), "%");
End;
// 最大持股天數判斷: 當有持股且持股天數超過設定值
If Position = 1 And Filled = 1 And _CurrentHoldDays >= MaxHoldDays Then Begin
SetPosition(0, Market); // 設定目標部位為0張,並以市價賣出,強制出場
Print(Date, " 超過最大持股天數出場!股票代碼: ", Symbol, ", 出場價: ", NumToStr(C, 2));
End;
2 評論