趋势行情不会永远持续下去,事实上市场大部分时间都处于震荡行情,所以才会有人希望能得到一种交易策略,既可以用在趋势行情,也可以用在震荡行情。那么今天我们就用发明者量化交易平台,构建一个趋势和震荡行情通用的经典恒温器策略。 点击阅读更多
'''backtest start: 2015-02-22 00:00:00 end: 2021-01-10 00:00:00 period: 1h basePeriod: 1h exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}] ''' mp = 0 # 定义一个全局变量,用于控制虚拟持仓 # 策略主函数 def onTick(): exchange.SetContractType("rb000") # 订阅期货品种 bar_arr = exchange.GetRecords() # 获取K线数组 if len(bar_arr) < 100: # 如果K线少于100根 return # 直接返回 close0 = bar_arr[-1]['Close'] # 获取最新价格(卖价),用于开平仓 bar_arr.pop() # 删除K线数组最后一个元素 # 计算CMI指标用以区分震荡市与趋势市 close1 = bar_arr[-1]['Close'] # 最新收盘价 close30 = bar_arr[-30]['Close'] # 前30根K线的收盘价 hh30 = TA.Highest(bar_arr, 30, 'High') # 最近30根K线的最高价 ll30 = TA.Lowest(bar_arr, 30, 'Low') # 最近30根K线的最低价 cmi = abs((close1 - close30) / (hh30 - ll30)) * 100 # 计算市场波动指数 # 震荡市中收盘价大于关键价格为宜卖市,否则为宜买市 high1 = bar_arr[-1]['High'] # 最新最高价 low1 = bar_arr[-1]['Low'] # 最新最低价 kod = (close1 + high1 + low1) / 3 # 计算关键价格 if close1 > kod: be = 1 se = 0 else: be = 0 se = 1 # 计算10根K线ATR指标 atr10 = TA.ATR(bar_arr, 10)[-1] # 定义最高价与最低价3日均线 high2 = bar_arr[-2]['High'] # 上根K线最高价 high3 = bar_arr[-3]['High'] # 前根K线最高价 low2 = bar_arr[-2]['Low'] # 上根K线最低价 low3 = bar_arr[-3]['Low'] # 前根K线最低价 avg3high = (high1 + high2 + high3) / 3 # 最近3根K线最高价的均值 avg3low = (low1 + low2 + low3) / 3 # 最近3根K线最低价的均值 # 计算震荡行情的进场价格 open1 = bar_arr[-1]['Open'] # 最新开盘价 if close1 > kod: # 如果收盘价大于关键价格 lep = open1 + atr10 * 3 sep = open1 - atr10 * 2 else: lep = open1 + atr10 * 2 sep = open1 - atr10 * 3 lep1 = max(lep, avg3high) # 计算震荡市多头进场价格 sep1 = min(sep, avg3low) # 计算震荡市空头进场价格 # 计算趋势行情的进场价格 boll = TA.BOLL(bar_arr, 50, 2) up_line = boll[0][-1] mid_line = boll[1][-1] down_line = boll[2][-1] global mp # 引入全局变量 if cmi < 20: # 如果是震荡行情 if mp == 0 and close1 >= lep1 and se: exchange.SetDirection("buy") # 设置交易方向和类型 exchange.Buy(close0, 1) # 开多单 mp = 1 # 设置虚拟持仓的值,即有多单 if mp == 0 and close1 <= sep1 and be: exchange.SetDirection("sell") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 开空单 mp = -1 # 设置虚拟持仓的值,即有空单 if mp == 1 and (close1 >= avg3high or be): exchange.SetDirection("closebuy") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 平多单 mp = 0 # 设置虚拟持仓的值,即空仓 if mp == -1 and (close1 <= avg3low or se): exchange.SetDirection("closesell") # 设置交易方向和类型 exchange.Buy(close0, 1) # 平空单 mp = 0 # 设置虚拟持仓的值,即空仓 else: # 如果是趋势行情 if mp == 0 and close1 >= up_line: exchange.SetDirection("buy") # 设置交易方向和类型 exchange.Buy(close0, 1) # 开多单 mp = 1 # 设置虚拟持仓的值,即有多单 if mp == 0 and close1 <= down_line: exchange.SetDirection("sell") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 开空单 mp = -1 # 设置虚拟持仓的值,即有空单 if mp == 1 and close1 <= mid_line: exchange.SetDirection("closebuy") # 设置交易方向和类型 exchange.Sell(close0 - 1, 1) # 平多单 mp = 0 # 设置虚拟持仓的值,即空仓 if mp == -1 and close1 >= mid_line: exchange.SetDirection("closesell") # 设置交易方向和类型 exchange.Buy(close0, 1) # 平空单 mp = 0 # 设置虚拟持仓的值,即空仓 # 程序入口 def main(): while True: # 进入无限循环模式 onTick() # 执行策略主函数 Sleep(1000) # 休眠1秒