老师好。我想实现这一个交易策略,以多仓交易为例。
开仓条件:
1. 最多同方向开两次仓。
2. 当收盘价上穿布林线上轨时,在下根Bar的开盘价开第一次多单。计算第一次多单的跟踪止损位。
3. 当有一次多单时,K线收盘价二次上穿布林线上轨时,在下根Bar的开盘价开第二次多单。计算第二次多单的跟踪止损位。
4. 跟踪止损位是开仓后的最高价大于开仓价的1.06倍时进行跟踪,当最高价下跌2%时平仓。
平仓条件:
1. 收盘价下穿布林线下轨,全部平仓。
2. 当收盘价低于第一次多单的跟踪止损位时,在下根Bar的开盘平掉第一次多单。
3. 当收盘价低于第二次多单的跟踪止损位时,在下根Bar的开盘平掉第二次多单。
请教的问题是:
我不知道如何实现平仓条件的第2和第3个。即如何分别计算和记录两个止损位,并在价位到达时平仓。
以下是简易的代码,但是跟踪止损那部分是错误的,请老师指教。
Vars
Series<Numeric> UpperBand;
Series<Numeric> LowerBand;
Series<Numeric> AveMa;
Series<Numeric> StdValue;
Series<Numeric> buylasthigh;
Series<Numeric> buyfirst; // 第一次开多仓价
Series<Numeric> buysecond; // 第二次开多仓价
Series<Numeric> jishulong(0);
Events
OnInit()
{
//=========除权换月相关设置==============
AddDataFlag(Enum_Data_RolloverBackWard()); //设置后复权
AddDataFlag(Enum_Data_RolloverRealPrice()); //设置映射真实价格
AddDataFlag(Enum_Data_AutoSwapPosition()); //设置自动换仓
AddDataFlag(Enum_Data_IgnoreSwapSignalCalc()); //设置忽略换仓信号计算
}
onBar(ArrayRef<Integer> indexs)
{
Range[0:0]
{
// ===================== 计算boll ==========================
AveMa = Average(Close, 100);
StdValue = StandardDev(Close, 100, 2);
UpperBand = Avema + 1 * StdValue;
LowerBand = Avema - 1 * StdValue;
PlotNumeric("upperband", upperband);
PlotNumeric("lowerband", lowerband);
PlotNumeric("AveMa", AveMa);
// 首次开多单
If(MarketPosition <>1 and c[1] > UpperBand[1] and jishulong < 2)
{
Buy(1, Open);
jishulong = 1;
buyfirst = open;
}
//二次开多单
If(MarketPosition == 1 and BarsSinceEntry > 1 and c[2] <= UpperBand[2] and c[1] >= UpperBand[1] and jishulong < 2) //Crossover(close[1],UpperBand[1])
{
Buy(1, Open);
jishulong = jishulong + 1;
buysecond = open;
}
//多单平仓
If(MarketPosition == 1 and BarsSinceEntry > 0 and close[1] <= LowerBand[1] )
{
sell(0, open);
jishulong = 0;
}
// ================ 【追踪止损不会,请教如何编写】 =================
If(MarketPosition == 1 )
{
If(BarsSinceEntry == 0)
buylasthigh = EntryPrice;
Else
buylasthigh = Max(High, buylasthigh);
}
If(MarketPosition == 1 and close[1] <= buylasthigh * 0.98 and buylasthigh > EntryPrice * 1.06 and BarsSinceEntry > 0)
Sell(0, Open);
}
}