MACD 计算方法 第 1 步:计算 EMA12 和 EMA26 EMA12 = XAverage(Close, 12) EMA26 = XAverage(Close, 26)
第 2 步:计算 DIF DIF = EMA12 - EMA26
第 3 步:计算 DEA DEA = XAverage(DIF, 9)
第 4 步:计算 MACD 直方图(Histogram) Histogram = 2(DIF - DEA)
MACD 策略逻辑 多头开仓:DIF 大于 DEA 空头开仓:DIF 小于 DEA 多头平仓:DIF 小于 DEA 空头平仓:DIF 大于 DEA
'''backtest start: 2022-10-12 09:00:00 end: 2022-11-10 15:00:00 period: 1d basePeriod: 1h exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}] ''' p = ext.NewPositionManager() vp = 0 def onTick(): symbol = _C(exchange.SetContractType,"rb888") r = _C(exchange.GetRecords) if len(r) < 100 : return macd = TA.MACD(r) dif = macd[0][-2] dea = macd[1][-2] #lastprice = r[-1]["Close"] global vp if vp == 0 and dif > dea : p.OpenLong(symbol["InstrumentID"], 1) vp = 1 if vp == 0 and dif < dea : p.OpenShort(symbol["InstrumentID"], 1) vp = -1 if vp == 1 and dif < dea : p.Cover(symbol["InstrumentID"]) vp = 0 if vp == -1 and dif > dea : p.Cover(symbol["InstrumentID"]) vp = 0 def main(): while True: if exchange.IO("status"): onTick() LogStatus(_D(), "已连接") else: LogStatus(_D(), "未连接") Sleep(1000)