我有一個「空單」的自動交易程式,運作上還算正常,但目前遇到一個問題,就是「不能手動回補」,一旦手動回補,自動交易無法判別已經沒有張數,會變成停利的時候會自動買進,就會變成多一張。請問我該如何解決?
附上部份程式碼
SettotalBar(270);
if barfreq <> "Min" or Barinterval <> 1 then RaiseRuntimeError("請設定頻率為1分鐘");
input: _orderSize(20, "萬");
var: _qty(0); //下單部位
var: _price(0); //下單價格, 後接 _price = addSpread(Close, -1); //Close 為目前成交價 -1檔, 台股適用, 可回測
_qty = maxlist(Floor(_orderSize / getField("參考價", "D") * 10), 1); //換算張數的計算方式
inputs:
_VolDiff(500, "張"), // 成交量差距濾網 (單位: 張)
_StopLossPercent(2, "%"), // 停損百分比 (例如 2 代表 2%)
_TakeProfitPercent(3, "%"); // 停利百分比 (例如 3 代表 3%)
vars:
_TypicalPrice(0), // 當期的典型價格 (H+L+C)/3
_TPV(0), // 當期的 (典型價格 * 成交量)
_CumulativeTPV(0), // 累計的 (典型價格 * 成交量)
_CumulativeVol(0), // 累計的成交量
_VWAP(0), // 計算出的VWAP值
_VWAP_UpperBand(0), // VWAP 上通道線 (+1%)
_AvgVol5(0); // 前5根K棒的成交均量
// ------------------------------
// 1. 判斷是否為新的一天,並重置每日累計值
// ------------------------------
if date <> date[1] then
begin
_CumulativeTPV = 0;
_CumulativeVol = 0;
end;
// 3. 交易邏輯判斷 (進場與出場)
// ------------------------------
// 3.1. 進場邏輯:判斷是否滿足空單進場條件
// ------------------------------
// 檢查目前是否無在倉部位 (position = 0)
if position = 0 then
begin
// 時間濾網:只在 09:05:00 之後才開始判斷進場
if time >= 093000 and Time <= 123000 then
begin
// 確保有足夠K棒計算均量,且上軌已計算出來
if currentbar > 5 and _VWAP_UpperBand > 0 then
begin
_AvgVol5 = Average(volume[1], 5); // 計算前5根K棒均量
// 判斷逆勢空方進場條件:
// 1. (成交量 - 均量) > 指定張數
// 2. 收盤價 > VWAP上通道
if (volume - _AvgVol5) > _VolDiff
and close > _VWAP_UpperBand
and close <= GetField("參考價", "D") * 1.08 then
begin
_price = addSpread(Close, -1);
// 使用 SetPosition 建立空單部位
SetPosition(-_qty, _price, label:="拉高進場");
end;
end;
end;
end;
// ------------------------------
// 3.2. 出場邏輯:判斷是否滿足停損停利條件
if Filled <> 0 then
begin
_price = addSpread(Close, 1);
// 停損條件:當前價格 >= 進場均價 * (1 + 停損%)
if close >= filledavgprice * (1 + _StopLossPercent / 100) then SetPosition(0, _price, label:="停損出場"); // 平倉
if close <= filledavgprice * (1 - _TakeProfitPercent / 100) then SetPosition(0, _price, label:="停利出場"); // 平倉
if Time >= 132000 and Close <> getField("漲停價", "D") then setposition(0, _price, label:="尾盤出場"); //有風險
end;
5 評論