from tqsdk import TqApi, TqSim, TargetPosTask
import threading
class WorkerThread(threading.Thread):
def __init__(self, api, symbol):
threading.Thread.__init__(self)
self.api = api
self.symbol = symbol
def run(self):
NDAY = 5 # 天数
K1 = 0.2 # 上轨K值
K2 = 0.2 # 下轨K值
api = TqApi(TqSim())
quote = self.api.get_quote(self.symbol)
klines = self.api.get_kline_serial(self.symbol, 5.75 * 60 * 60) # 86400使用日线
target_pos = TargetPosTask(self.api, self.symbol)
def dual_thrust(quote, klines):
current_open = klines.iloc[-1][“open”]
HH = max(klines.high.iloc[-NDAY – 1:-1]) # N日最高价的最高价
HC = max(klines.close.iloc[-NDAY – 1:-1]) # N日收盘价的最高价
LC = min(klines.close.iloc[-NDAY – 1:-1]) # N日收盘价的最低价
LL = min(klines.low.iloc[-NDAY – 1:-1]) # N日最低价的最低价
range = max(HH – LC, HC – LL)
buy_line = current_open + range * K1 # 上轨
sell_line = current_open – range * K2 # 下轨
print(“当前开盘价: %f, 上轨: %f, 下轨: %f” % (current_open, buy_line, sell_line))
return buy_line, sell_line
buy_line, sell_line = dual_thrust(quote, klines) # 获取上下轨
while True:
self.api.wait_update()
if self.api.is_changing(klines.iloc[-1], [“datetime”, “open”]): # 新产生一根日线或开盘价发生变化: 重新计算上下轨
buy_line, sell_line = dual_thrust(quote, klines)
if self.api.is_changing(quote, “last_price”):
if quote.last_price > buy_line: # 高于上轨
print(“高于上轨,目标持仓 多头3手”)
target_pos.set_target_volume(1) # 交易
elif quote.last_price < sell_line: # 低于下轨
print(“低于下轨,目标持仓 空头3手”)
target_pos.set_target_volume(-1) # 交易
else:
print(‘未穿越上下轨,不调整持仓’)
if __name__ == “__main__”:
api_master = TqApi(TqSim())
# Create new threads
thread1 = WorkerThread(api_master.copy(), “DCE.i2009”)
thread2 = WorkerThread(api_master.copy(), “DCE.j2009”)
# Start new Threads
thread1.start()
thread2.start()
while True:
api_master.wait_update()
运行后总是报错:
quote = self.api.get_quote(self.symbol)
NameError: name ‘self’ is not defined
这是什么原因?应如何解决?