994 浏览
0

import time
from tqsdk.tafunc import BOLL,KAMA
from tqsdk import TqApi, TqAuth, TargetPosTask,TqAccount
import pandas as pd

trade_value=1 # 交易手数
loss_limit=20 # 止损价格
trade_num= 2 # 每次启动程序开仓次数
SYMBOL = “CZCE.FG409″ # 合约代码
# 模拟交易
try:
# api = TqApi(web_gui=”http://127.0.0.1:50448”, auth=TqAuth(“jonathan1”, “love”))
# 下方添加实盘 账号
api = TqApi(TqAccount(“Q国富期货”, “51008263”, “love”),web_gui=”http://127.0.0.1:50448″, auth=TqAuth(“jonathan1”, “love”))
target_pos = TargetPosTask(api, SYMBOL)
quote = api.get_quote(SYMBOL)
klines = api.get_kline_serial(SYMBOL, 60*60*24)
position = api.get_position(SYMBOL)
target_pos = TargetPosTask(api, SYMBOL)
# 使用BOLL指标计算中轨、上轨和下轨,其中28为周期N ,2为参数p
def boll_line(klines):
boll = BOLL(klines, 28 , 2)
midline = boll[“mid”].iloc[-1]
topline = boll[“top”].iloc[-1]
bottomline = boll[“bottom”].iloc[-1]
print(“策略运行,中轨:%.2f,上轨为:%.2f,下轨为:%.2f” % (midline, topline, bottomline))
return midline, topline, bottomline
midline, topline, bottomline = boll_line(klines)
while True:
api.wait_update()
# 每次生成新的K线时重新计算BOLL指标
if api.is_changing(klines.iloc[-1],”datetime”):
midline, topline, bottomline = boll_line(klines)
# 每次最新价发生变化时进行判断
if api.is_changing(quote,”last_price”):
# 判断开仓条件
if position.pos_long == 0 and position.pos_short == 0:
# 如果最新价大于上轨,K线上穿上轨,开多仓
if quote.last_price > topline:
print(“最新价大于上轨,K线上穿上轨,开多仓”)
target_pos.set_target_volume(20)
# 如果最新价小于轨,K线下穿下轨,开空仓
elif quote.last_price < bottomline:
print(“K线下穿下轨,开空仓”)
target_pos.set_target_volume(-20)
else:
print(“当前最新价%.2f,未穿上轨或下轨,不开仓” % quote.last_price)
# 在多头情况下,空仓条件
elif position.pos_long > 0:
# 如果最新价低于中线,多头清仓离场
if quote.last_price < midline:
print(“最新价低于中线,多头清仓离场”)
target_pos.set_target_volume(0)
else:
print(“当前多仓,未穿越中线,仓位无变化”)
# 在空头情况下,空仓条件
elif position.pos_short > 0:
# 如果最新价高于中线,空头清仓离场
if quote.last_price > midline:
print(“最新价高于中线,空头清仓离场”)
target_pos.set_target_volume(0)
else:
print(“当前空仓,未穿越中线,仓位无变化”)

except Exception as e:
print(‘错误’,e )
time.sleep(3)

无法运行,上面是有语法错误吗,求助

jonathan1 编辑问题 2024年6月7日