def get_tq_auth() -> TqAuth: print(get_application_path()) if 'TQ_ACCOUNT' not in os.environ or 'TQ_PASSWORD' not in os.environ: load_dotenv(find_dotenv()) tq_account: str = os.environ['TQ_ACCOUNT'] tq_password: str = os.environ['TQ_PASSWORD'] del os.environ['TQ_ACCOUNT'] del os.environ['TQ_PASSWORD'] pprint.pprint(dict(os.environ), width=1) return TqAuth(tq_account, tq_password)
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'mayanqiong' from datetime import date from tqsdk import TqApi, TqAuth, TqReplay ''' 复盘模式示例: 指定日期行情完全复盘 复盘 2020-05-26 行情 ''' # 在创建 api 实例时传入 TqReplay 就会进入复盘模式 api = TqApi(backtest=TqReplay(date(2020, 5, 26)), auth=TqAuth("信易账户", "账户密码")) quote = api.get_quote("SHFE.cu2009") while True: api.wait_update() if api.is_changing(quote): print("最新价", quote.datetime, quote.last_price)
data = pd.read_excel(para['io_in'], sheet_name=0, converters={'stk_code': str}) # excel读取的品种集合 log.logger.info('品种数:{0}'.format(len(data['stk_code']))) g_security = data['stk_code'].tolist() # "'a' 品种前缀 g_security open_num_list = data['open_num'].tolist() stg = pd.read_excel('stg_cfg.xlsx', sheet_name=0) # excel读stg对应关系 para['STG_NUM1'] = stg['k' + str(para['BAR_UNIT'])].iloc[0] para['STG_NUM2'] = stg['k' + str(para['BAR_UNIT'])].iloc[1] # wt_data = pd.DataFrame(columns=['date', 'stk_code', 'win_rate', 'short_val', 'long_val']) #输出落地的excel字段 # wt_data.to_excel(io_out, index=False) # 登录连接信易快期账户 api = TqApi(TqAccount(para['FUT_BROKER'], para['FUT_USER'], para["FUT_PWD"]), auth=TqAuth(para['ACCT_ID'], para['ACCT_PWD'])) account = api.get_account() log.logger.info('初始账户权益:{0}'.format(account.balance)) log.logger.info('初始浮动盈亏:{0}'.format(account.float_profit)) SEC_LIST = [] for g_sec in g_security: ls = api.get_quote('KQ.m@%s' % g_sec) SEC_LIST.append(ls.underlying_symbol) log.logger.info('品种集合:{0}'.format(SEC_LIST)) # 获取主力合约 # domain = api.get_quote("[email protected]") # 获取主力合约的K线引用 for sec in SEC_LIST: positions[sec] = api.get_position(sec) klines_dict[sec] = api.get_kline_serial(sec, para['BAR_UNIT'], para['BAR_NUM'])
ma_list = [np.mean(data_list[-n:])] for i in range(1, len(data_list) - n + 1): ma = np.mean(data_list[-n - i:-i]) ma_list.append(ma) return np.array(ma_list) if __name__ == '__main__': data = pd.read_excel(io_in, sheet_name=0, converters={'stk_code': str}) # excel读取的品种集合 log.logger.info('品种数:{0}'.format(len(data['stk_code']))) g_security = data['stk_code'].tolist() # "'a' 品种前缀 g_security # wt_data = pd.DataFrame(columns=['date', 'stk_code', 'win_rate', 'short_val', 'long_val']) #输出落地的excel字段 # wt_data.to_excel(io_out, index=False) # 登录连接信易快期账户 api = TqApi(TqKq(), web_gui=True, auth=TqAuth(ACCT_ID, ACCT_PWD)) account = api.get_account() log.logger.info('初始账户权益:{0}'.format(account.balance)) log.logger.info('初始浮动盈亏:{0}'.format(account.float_profit)) SEC_LIST = [] for g_sec in g_security: ls = api.query_cont_quotes(product_id=g_sec) SEC_LIST.append(ls[0]) log.logger.info('品种集合:{0}'.format(SEC_LIST)) # 获取主力合约 # domain = api.get_quote("[email protected]") # 获取主力合约的K线引用 for sec in SEC_LIST: positions[sec] = api.get_position(sec) klines_dict[sec] = api.get_kline_serial(sec, BAR_UNIT, BAR_NUM + 1) quotes[sec] = api.get_quote(sec)
wma_data = ema2(close_prices, 30)[-n:] # WMA指标 mom_data = trma(close_prices, 30)[-n:] # MOM指标 x_all = list(zip(sma_data, wma_data, mom_data)) # 样本特征组 y_all = list(klines.close.iloc[i] >= klines.close.iloc[i - 1] for i in list(reversed(range(-1, -n - 1, -1)))) # 样本标签组 # x_all: 大前天指标 前天指标 昨天指标 (今天指标) # y_all: (大前天) 前天 昨天 今天 -明天- # 准备算法需要用到的数据 x_train = x_all[: -1] # 训练数据: 特征 x_predict = x_all[-1] # 预测数据(用本交易日的指标预测下一交易日的涨跌) y_train = y_all[1:] # 训练数据: 标签 (去掉第一个数据后让其与指标隔一位对齐(例如: 昨天的特征 -> 对应预测今天的涨跌标签)) return x_train, y_train, x_predict predictions = [] # 用于记录每次的预测结果(在每个交易日收盘时用收盘数据预测下一交易日的涨跌,并记录在此列表里) api = TqApi(backtest=TqBacktest(start_dt=datetime.date(2018, 7, 2), end_dt=datetime.date(2018, 9, 26)), auth=TqAuth("信易账户", "账户密码")) quote = api.get_quote(symbol) klines = api.get_kline_serial(symbol, duration_seconds=24 * 60 * 60) # 日线 target_pos = TargetPosTask(api, symbol) with closing(api): try: while True: while not api.is_changing(klines.iloc[-1], "datetime"): # 等到达下一个交易日 api.wait_update() while True: api.wait_update() # 在收盘后预测下一交易日的涨跌情况 if api.is_changing(quote, "datetime"): now = datetime.datetime.strptime(quote.datetime, "%Y-%m-%d %H:%M:%S.%f") # 当前quote的时间 # 判断是否到达预定收盘时间: 如果到达 则认为本交易日收盘, 此时预测下一交易日的涨跌情况, 并调整为对应仓位 if now.hour == close_hour and now.minute >= close_minute:
from matplotlib.pyplot import rcParams, xticks, autoscale, figure, show from matplotlib.animation import FuncAnimation from matplotlib import style system("mode con cols=71 lines=30") stdout.write(f"+{'-' * 68}+\n" f"|{'期货跨月偏离度监测':^59}|\n" f"+{'-' * 68}+\n" f"|{' ':68}|\n" f"|{'数据行情由天勤量化提供支持,如不同意天勤量化使用条款,请终止使用':^36}|\n" f"|{' ':68}|\n" f"+{'-' * 68}+\n\n") tq_account = input('天勤量化账号: ') tq_password = input('天勤量化密码: ') try: api = TqApi(auth=TqAuth(tq_account, tq_password)) except Exception as err: print(err, '\n') input(f"{'连接失败, 按任意键程序将退出, 请检查后重试'}") raise SystemExit() quotes = [] labels = [] product = input("\n请输入品种代码(例rb/hc): ").lower() try: available_contracts = sorted( api.query_quotes(ins_class="FUTURE", product_id=product, expired=False)) m_contract = api.query_cont_quotes(product_id=product)[0] except IndexError: available_contracts = sorted( api.query_quotes(ins_class="FUTURE",
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'chengzhi' import datetime from tqsdk import TqApi, TqAuth from tqsdk.ta import * api = TqApi(auth=TqAuth("信易账户", "账户密码")) # 获得 cu1909 10秒K线的引用 klines = api.get_kline_serial("SHFE.cu1910", 10, data_length=3000) print("K线时间", datetime.datetime.fromtimestamp(klines.iloc[-1]["datetime"] / 1e9)) print(klines) print("ATR", ATR(klines, 26)) print("BIAS", BIAS(klines, 6)) print("BOLL", BOLL(klines, 3, 5)) print("DMI", DMI(klines, 14, 6)) print("KDJ", KDJ(klines, 9, 3, 3)) print("MA", MA(klines, 3)) print("MACD", MACD(klines, 20, 35, 10)) print("SAR", SAR(klines, 4, 0.02, 0.2)) api.close()
# -*- coding: utf-8 -*- __author__ = 'limin' ''' 菲阿里四价 策略(日内突破策略, 在每日收盘前对所持合约进行平仓) 参考: https://www.shinnytech.com/blog/fairy-four-price/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from tqsdk import TqApi, TqAuth, TargetPosTask from datetime import datetime import time symbol = "SHFE.ni2012" # 合约代码 close_hour, close_minute = 14, 50 # 平仓时间 api = TqApi(auth=TqAuth("信易账户", "账户密码")) # 使用模拟帐号直连行情和交易服务器 quote = api.get_quote(symbol) # 获取指定合约的盘口行情 klines = api.get_kline_serial(symbol, 24 * 60 * 60) # 获取日线 position = api.get_position(symbol) # 持仓信息 target_pos = TargetPosTask(api, symbol) # 目标持仓 top_rail = klines.high.iloc[-2] # 上轨: 昨日高点 bottom_rail = klines.low.iloc[-2] # 下轨: 昨日低点 print("上轨:", top_rail, ",下轨:", bottom_rail, ",昨日收盘价:", klines.close.iloc[-2], ",今日开盘价:", klines.open.iloc[-1]) while True: api.wait_update() if api.is_changing(klines.iloc[-1], "datetime"): # 如果产生一根新日线 (即到达下一个交易日): 重新获取上下轨 top_rail = klines.high.iloc[-2]
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'hongyan' from tqsdk import TqApi, TqAuth, TqAccount, TqKq, TqSim, TqMultiAccount # 多账户模式下, 同时操作实盘、模拟交易和快期模拟账户交易 tqact = TqAccount("H海通期货", "123456", "123456") sim = TqSim() kq = TqKq() with TqApi(TqMultiAccount([tqact, sim, kq]), auth=TqAuth("信易账户", "账户密码")) as api: order1 = api.insert_order(symbol="DCE.m2101", direction="BUY", offset="OPEN", volume=5, account=tqact) order2 = api.insert_order(symbol="SHFE.au2012C308", direction="BUY", offset="OPEN", volume=5, limit_price=78.1, account=sim) order3 = api.insert_order(symbol="SHFE.cu2101", direction="Sell", offset="OPEN", volume=10, limit_price=51610, account=kq) api.cancel_order(order3, kq) while order1.status != "FINISHED" or order2.status != "FINISHED":
elif n == 60 or n % 60 == 0: return 'minute' if n == 60 else f'{n // 60}minute' else: return 'second' if n == 1 else f'{n}second' if __name__ == '__main__': # 加载 .env 变量 load_dotenv(find_dotenv()) # 天勤账号 TQ_ACCOUNT: str = os.environ.get('TQ_ACCOUNT') TQ_PASSWORD: str = os.environ.get('TQ_PASSWORD') # 天勤API tq_api: TqApi = TqApi(auth=TqAuth(TQ_ACCOUNT, TQ_PASSWORD)) # Application path application_path: str = get_application_path() # 下载需求 download_request_list: List[dict] = [] csv_path: str = os.path.join(application_path, 'download.csv') with open(csv_path, newline='', encoding='utf-8') as csv_file: reader = csv.DictReader(csv_file) for row in reader: download_request: dict = { 'symbol': row['symbol'], 'start': date(int(row['start'][:4]), int(row['start'][4:6]), int(row['start'][6:8])), 'end': date(int(row['end'][:4]), int(row['end'][4:6]), int(row['end'][6:8])), 'period': int(row['period']),
画图示例: 在附图中画 macd 指标示例 注意: 画图示例中用到的数据不含有实际意义,请根据自己的实际策略情况进行修改 ''' def calc_macd_klines(klines): # 计算 macd 指标 macd = MACD(klines, 12, 26, 9) # 用 K 线图模拟 MACD 指标柱状图 klines["MACD.open"] = 0.0 klines["MACD.close"] = macd["bar"] klines["MACD.high"] = klines["MACD.close"].where(klines["MACD.close"] > 0, 0) klines["MACD.low"] = klines["MACD.close"].where(klines["MACD.close"] < 0, 0) klines["MACD.board"] = "MACD" # 在 board=MACD 上添加 diff、dea 线 klines["diff"] = macd["diff"] klines["diff.board"] = "MACD" klines["diff.color"] = "gray" klines["dea"] = macd["dea"] klines["dea.board"] = "MACD" klines["dea.color"] = "rgb(255,128,0)" api = TqApi(auth=TqAuth("信易账户", "账户密码"), web_gui=True) klines = api.get_kline_serial("SHFE.rb2105", 5 * 60, 200) while True: calc_macd_klines(klines) api.wait_update()
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'limin' from tqsdk import TqApi, TqAuth ''' 画图示例: 在附图中画K线 注意: 画图示例中用到的数据不含有实际意义,请根据自己的实际策略情况进行修改 ''' api = TqApi(web_gui=True, auth=TqAuth("信易账户", "账户密码")) klines = api.get_kline_serial("SHFE.rb2104", 86400) klines2 = api.get_kline_serial("SHFE.rb2105", 86400) while True: # 将画图代码放在循环中即可使图像随着行情推进而更新 # 在附图画出 rb2105 的K线: 需要将open、high、log、close的数据都设置正确 klines["rb2105.open"] = klines2["open"] klines["rb2105.high"] = klines2["high"] klines["rb2105.low"] = klines2["low"] klines["rb2105.close"] = klines2["close"] klines["rb2105.board"] = "B2" api.wait_update()
# api = TqApi(account=TqKq(), auth=TqAuth(LG_ACC, LG_PWD)) rule = api.get_risk_management_rule(exchange_id="SSE") logger.info(rule) logger.info("自成交限制:", rule.self_trade) logger.info("频繁报撤单限制:", rule.frequent_cancellation) logger.info("成交持仓比限制:", rule.trade_position_ratio) except Exception as e: logger.info(e) if __name__ == "__main__": logger.info( "*************************** strategy start *******************************" ) api = TqApi(account=TqKq(), auth=TqAuth(LG_ACC, LG_PWD)) # api.set_risk_management_rule(exchange_id="SSE", enable=True) # # 等待发送数据 # api.wait_update() # tr = Timer(10,risk_controller,(api,)) # 资金管理 cm = CapitalManager.CapitalManager(api, 10000, 0.80) # 根据资金情况 调整初始化建仓单位? quoteList = cm.query_quotes( [Tao.EXCHANGE_SHFE, Tao.EXCHANGE_DCE, Tao.EXCHANGE_CZCE]) pos_pd = cm.calc_pos_list_by_turle(quoteList, 20) pos_pd.apply(lambda x: init_turtle(api, x), axis=1) with closing(api): while True:
config_params = get_yaml_data(yaml_path) if config_params['run_level'] == 'replay': acc = str(config_params['sim_account']) pwd = str(config_params['sim_pwd']) start_text = config_params['start_from'] end_text = config_params['to_end'] start_date = datetime.strptime(start_text, "%Y-%m-%d").date() end_date = datetime.strptime(end_text, "%Y-%m-%d").date() api = TqApi(web_gui=config_params['web_url'], backtest=TqBacktest(start_dt=start_date, end_dt=end_date), auth=TqAuth(acc, pwd)) else: if config_params['future_company'] == '' or config_params[ 'future_account'] == '' or config_params['future_pwd'] == '': print('没有配置期货账号') exit(0) future_account = TqAccount(config_params['future_company'], config_params['future_account'], config_params['sim_pwd']) api = TqApi(future_account, auth=TqAuth(config_params['sim_account'], config_params['sim_pwd'])) # replay.set_replay_speed(10.0) account = api.get_account()
from tqsdk import TqApi, TqAuth, TqKq, TqAccount import json import pandas as pd import time import sys sys.path.append("E:/coderepo/skwquant/") from skwutils import RawList pd.set_option('display.max_columns', None) api = TqApi(TqKq(), auth=TqAuth("keviniiii", "qkyhpys,1")) # api = TqApi(TqAccount("G国海良时", "88500007", "702211"), auth=TqAuth("keviniiii", "qkyhpys,1")) def open_order_json(unit, holding_set, alive_open_set): symbol_raw = unit['symbol'] vc = unit['ans'] v_prob = unit['prob'] v_prone = unit['v_prone'] buynum = int(float(unit['buynum'])) price_limit = 0 open_order(symbol_raw, vc, v_prob, v_prone, buynum, price_limit=price_limit, holding_set=holding_set, alive_open_set=alive_open_set) return unit
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'chengzhi' from datetime import date from tqsdk import TqApi, TqAuth, TqBacktest, TargetPosTask ''' 如果当前价格大于5分钟K线的MA15则开多仓 如果小于则平仓 回测从 2018-05-01 到 2018-10-01 ''' # 在创建 api 实例时传入 TqBacktest 就会进入回测模式 api = TqApi(backtest=TqBacktest(start_dt=date(2018, 5, 1), end_dt=date(2018, 10, 1)), auth=TqAuth("信易账户", "账户密码")) # 获得 m1901 5分钟K线的引用 klines = api.get_kline_serial("DCE.m1901", 5 * 60, data_length=15) # 创建 m1901 的目标持仓 task,该 task 负责调整 m1901 的仓位到指定的目标仓位 target_pos = TargetPosTask(api, "DCE.m1901") while True: api.wait_update() if api.is_changing(klines): ma = sum(klines.close.iloc[-15:]) / 15 print("最新价", klines.close.iloc[-1], "MA", ma) if klines.close.iloc[-1] > ma: print("最新价大于MA: 目标多头5手") # 设置目标持仓为多头5手 target_pos.set_target_volume(5) elif klines.close.iloc[-1] < ma: print("最新价小于MA: 目标空仓")
"instrument_id", "direction", "offset", "price", "volume", "trade_date_time" ] def write_csv(file_name, cols, datas): file_exists = os.path.exists(file_name) and os.path.getsize(file_name) > 0 with open(file_name, 'a', newline='') as csvfile: csv_writer = csv.writer(csvfile, dialect='excel') if not file_exists: csv_writer.writerow(['datetime'] + cols) for item in datas.values(): if 'insert_date_time' in cols: dt = datetime.fromtimestamp( item['insert_date_time'] / 1e9).strftime('%Y-%m-%d %H:%M:%S.%f') elif 'trade_date_time' in cols: dt = datetime.fromtimestamp( item['trade_date_time'] / 1e9).strftime('%Y-%m-%d %H:%M:%S.%f') else: dt = None row = [dt] + [item[k] for k in cols] csv_writer.writerow(row) with TqApi(TqKq(), auth=TqAuth("信易账户", "账户密码")) as api: # 将当前账户下全部委托单、成交信息写入 csv 文件中 write_csv("orders.csv", order_cols, api.get_order()) write_csv("trades.csv", trade_cols, api.get_trade())
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'chengzhi' from tqsdk import TqApi, TqAuth # 可以指定debug选项将调试信息写入指定的文件中 api = TqApi(debug="debug.log", auth=TqAuth("信易账户", "账户密码")) quote = api.get_quote("CZCE.FG209") print(quote.datetime, quote.last_price, quote.ask_price1, quote.ask_price2) while True: # 调用 wait_update 等待业务信息发生变化,例如: 行情发生变化, 委托单状态变化, 发生成交等等 # 注意:其他合约的行情的更新也会触发业务信息变化,因此下面使用 is_changing 判断 FG209 的行情是否有变化 api.wait_update() # 如果 FG209 的任何字段有变化,is_changing就会返回 True if api.is_changing(quote): print("行情变化", quote) # 只有当 FG209 的最新价有变化,is_changing才会返回 True if api.is_changing(quote, "last_price"): print("最新价变化", quote.last_price) # 当 FG209 的买1价/买1量/卖1价/卖1量中任何一个有变化,is_changing都会返回 True if api.is_changing(quote, ["ask_price1", "ask_volume1", "bid_price1", "bid_volume1"]): print("盘口变化", quote.ask_price1, quote.ask_volume1, quote.bid_price1, quote.bid_volume1)
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'limin' from tqsdk import TqApi, TqAuth ''' 画图示例: 在主图中画线和方框 注意: 画图示例中用到的数据不含有实际意义,请根据自己的实际策略情况进行修改 ''' api = TqApi(web_gui=True, auth=TqAuth("信易账户", "账户密码")) # web_gui=True, 开启使用 web 界面查看绘图结果的功能 klines = api.get_kline_serial("SHFE.rb2105", 60) # 由于需要在浏览器中查看绘图结果,因此程序不能退出 while True: api.wait_update() # 当有业务信息发生变化时执行 # 当最后 1 根柱子最大最小值价差大于 0.05 时,在主图绘制信号 high = klines.iloc[-1].high low = klines.iloc[-1].low if high - low > 0.05: # 绘制直线, 每一个 id 对应同一条直线 api.draw_line(klines, -1, high, -1, low, id="box%.0f" % (klines.iloc[-1].id), color=0xaa662244, width=4) # 绘制字符串
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'limin' from tqsdk import TqApi, TqAuth from tqsdk.ta import MA ''' 画图示例: 在附图中画指标线 (将画图代码放在循环中即可使图像随着行情推进而更新) 注意: 画图示例中用到的数据不含有实际意义,请根据自己的实际策略情况进行修改 ''' api = TqApi(web_gui=":9878", auth=TqAuth("信易账户", "账户密码")) # web_gui="[ip]:port", 指定 web 界面地址的 ip 和 port klines = api.get_kline_serial("SHFE.rb2105", 24 * 60 * 60) while True: # 将画图代码放在循环中即可使图像随着行情推进而更新 ma = MA(klines, 30) # 使用tqsdk自带指标函数计算均线 # 示例1: 在附图中画一根绿色的ma指标线 klines["ma_B2"] = ma.ma klines["ma_B2.board"] = "B2" # 设置附图: 可以设置任意字符串,同一字符串表示同一副图 klines[ "ma_B2.color"] = "green" # 设置为绿色. 以下设置颜色方式都可行: "green", "#00FF00", "rgb(0,255,0)", "rgba(0,125,0,0.5)" # 示例2: 在另一个附图画一根比ma小4的宽度为4的紫色指标线 klines["ma_4"] = ma.ma - 4 klines["ma_4.board"] = "MA4" # 设置为另一个附图 klines["ma_4.color"] = 0xFF9933CC # 设置为紫色, 或者 "#9933FF"