# CTA策略之商品期货吞没形态

Author: Hukybo, Date: 2021-05-26 16:42:25
Tags:

#### 一、摘要

“一买就跌，一卖就涨”或许是很多交易初学者心中的困惑，难道真的有庄家能通过后台看到自己的账户吗？答案是否定的，准确的说不是庄家盯上了你，而是盯上了“你们这群散户”。比如开车时遇到障碍物，大部分人都会躲避，交易也是同样的道理，大部分散户看到利好时也会有相同的反映，都会开多仓冲进去，当看多的散户都买入后，在越来越多散户落袋为安卖出时，由于没有买力的支撑，价格就会随之下跌，这就是羊群效应。

#### 四、策略实现

``````'''backtest
start: 2015-02-22 00:00:00
end: 2021-05-25 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
'''
``````

``````import talib
import numpy as np
``````

``````def on_tick():
pass

def main():
while True:
on_tick()
Sleep(1000)
``````

``````def get_ohlc(records):
dic = {}
open_price = []
high_price = []
low_price = []
close_price = []
for i in records:
open_price.append(i['Open'])
high_price.append(i['High'])
low_price.append(i['Low'])
close_price.append(i['Close'])
return {
'open': np.array(open_price),
'high': np.array(high_price),
'low': np.array(low_price),
'close': np.array(close_price),
}

def on_tick():
records = exchange.GetRecords()
ohlc = get_ohlc(records)
engulfed = talib.CDLENGULFING(ohlc['open'], ohlc['high'], ohlc['low'], ohlc['close']).tolist()
depth = exchange.GetDepth()
bid = depth.Bids[0].Price
``````

``````    global mp
if mp == 1 and engulfed[-1] == 100:
exchange.Sell(bid, 1)
mp = 0
if mp == -1 and engulfed[-1] == -100:
exchange.SetDirection("closesell")
mp = 0
if mp == 0 and engulfed[-1] == -100:
mp = 1
if mp == 0 and engulfed[-1] == 100:
exchange.SetDirection("sell")
exchange.Sell(bid, 1)
mp = -1
``````

#### 五、策略回测

• 回测开始日期：2015-02-22
• 回测结束日期：2021-04-18
• 数据品种：菜粕指数
• 数据周期：日线
• 滑点：开平仓各2跳

```'''backtest
start: 2015-02-22 00:00:00
end: 2021-05-25 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
'''

import talib
import numpy as np

mp = 0

def get_ohlc(records):
dic = {}
open_price = []
high_price = []
low_price = []
close_price = []
for i in records:
open_price.append(i['Open'])
high_price.append(i['High'])
low_price.append(i['Low'])
close_price.append(i['Close'])
return {
'open': np.array(open_price),
'high': np.array(high_price),
'low': np.array(low_price),
'close': np.array(close_price),
}

def on_tick():
records = exchange.GetRecords()
ohlc = get_ohlc(records)
engulfed = talib.CDLENGULFING(ohlc['open'], ohlc['high'], ohlc['low'], ohlc['close']).tolist()
atr = TA.ATR(records, 14)[-1]
depth = exchange.GetDepth()
bid = depth.Bids[0].Price
global mp
if mp == 1 and engulfed[-1] == 100:
exchange.Sell(bid, 1)
mp = 0
if mp == -1 and engulfed[-1] == -100:
exchange.SetDirection("closesell")
mp = 0
if mp == 0 and engulfed[-1] == -100 and atr > 30:
mp = 1
if mp == 0 and engulfed[-1] == 100 and atr > 30:
exchange.SetDirection("sell")
exchange.Sell(bid, 1)
mp = -1

def main():
exchange.SetContractType('RM000')
while True:
on_tick()
Sleep(1000)

```

More