Exemple #1
0
def run_tianqin_code(bid, user_id, pwd, td_url):
    api = TqApi(TqAccount(bid, user_id, pwd),
                auth="[email protected],MaYanQiong",
                _stock=True,
                _td_url=td_url,
                debug="c.log")
    is_ctp = False if bid == "快期模拟" else True
    account = api.get_account()
    if bid == "快期模拟":
        assert account.ctp_balance == '-' or math.isnan(account.ctp_balance)
        assert account.ctp_available == '-' or math.isnan(
            account.ctp_available)
    else:
        logger.info(f"{account.ctp_balance}, {account.ctp_available}")

    logger.info(f"{'='*30} 登录成功后,账户初始状态 {'='*30}")
    positions = api._data["trade"][user_id]["positions"]
    orders = api._data["trade"][user_id]["orders"]
    check_orders(orders, api, is_ctp)
    check_positions(positions, api, is_ctp)
    check_account(account, positions, is_ctp)
    check_risk_rule(api, None)
    check_risk_data(api, "SSE.10002504")

    api.set_risk_management_rule("SZSE", True)

    logger.info(f"{'='*12} 期权 开仓 {'='*12}")
    # quote = api.get_quote("SZSE.91000999")  # ETF 期权  SSE.10002504
    # print(quote)
    # 挂单
    # order = api.insert_order(symbol="SSE.10002504", direction="BUY", offset="OPEN", limit_price=quote.lower_limit + quote.price_tick, volume=2)
    # order = api.insert_order(symbol="SSE.10002504", direction="SELL", offset="OPEN", limit_price=quote.upper_limit - quote.price_tick, volume=2)
    # 可成交
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price=quote.ask_price1, volume=3)
    # 可成交 FAK 下单失败,CTP:交易所不支持的价格类型
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price=quote.ask_price1, volume=2, advanced="FAK")
    # 可成交 FOK
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price=quote.ask_price1, volume=2, advanced="FOK")

    # BEST
    order = api.insert_order(symbol="SZSE.91000999",
                             direction="BUY",
                             offset="OPEN",
                             limit_price="BEST",
                             volume=5)
    # BEST FOK 下单失败,已撤单报单被拒绝12038,合约代码:SSE.10002513,下单方向:买,开平标志:开仓,委托价格:最优价,委托手数:3
    # order = api.insert_order(symbol="SSE.10002513", direction="SELL", offset="CLOSE", limit_price="BEST", volume=3, advanced="FOK")

    # any_price 通知: 下单失败,CTP:交易所不支持的价格类型
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", volume=3)
    # FIVELEVEL 通知: 下单失败,CTP:交易所不支持的价格类型
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price="FIVELEVEL", volume=3)
    api.wait_update()
    # api.cancel_order(order)
    while order.status == "ALIVE":
        api.wait_update()
    check_all(api, bid, user_id)
    # check_risk_rule(api,None)
    check_risk_data(api, "SZSE.91000999")
    api.close()
def sell_close():
    api = TqApi(TqAccount(bid, user_id, pwd),
                url=td_url,
                auth="ringo,Shinnytech123")
    test_logger.info(f"{'='*12} 期权 卖平仓 {'='*12}")
    quote = api.get_quote(symbol)  # ETF 期权
    order = api.insert_order(symbol=symbol,
                             direction="SELL",
                             offset="CLOSE",
                             limit_price=quote.bid_price1,
                             volume=3)
    while order.status == "ALIVE":
        api.wait_update()
    api.wait_update()
    api.close()
 def test_insert_order_shfe_anyprice(self):
     dir_path = os.path.dirname(os.path.realpath(__file__))
     self.mock.run(
         os.path.join(dir_path, "log_file",
                      "test_insert_order_shfe_anyprice.script"))
     # 测试
     account = TqAccount("H海通期货", "83011119", "********")
     utils.RD = random.Random(4)
     # 测试
     with self.assertRaises(Exception):
         with TqApi(account=account,
                    _ins_url=self.ins_url_2020_06_16,
                    _md_url=self.md_url,
                    _td_url=self.td_url,
                    debug=False) as api:
             order1 = api.insert_order("SHFE.au2012", "BUY", "OPEN", 1)
 def test_insert_order_shfe_limit_fak(self):
     dir_path = os.path.dirname(os.path.realpath(__file__))
     self.mock.run(
         os.path.join(dir_path, "log_file",
                      "test_insert_order_shfe_limit_fak.script"))
     # 测试
     account = TqAccount("H海通期货", "83011119", "********")
     utils.RD = random.Random(4)
     with TqApi(account=account,
                _ins_url=self.ins_url_2020_06_16,
                _md_url=self.md_url,
                _td_url=self.td_url,
                debug=False) as api:
         order1 = api.insert_order("SHFE.rb2010",
                                   "BUY",
                                   "OPEN",
                                   2,
                                   limit_price=3500,
                                   advanced="FAK",
                                   order_id="PYSDK_insert_SHFE_limit_FAK")
         while True:
             api.wait_update()
             if order1.status == "FINISHED":
                 break
         self.assertEqual("PYSDK_insert_SHFE_limit_FAK", order1.order_id)
         self.assertEqual("    25308102", order1.exchange_order_id)
         self.assertEqual("SHFE", order1.exchange_id)
         self.assertEqual("rb2010", order1.instrument_id)
         self.assertEqual("BUY", order1.direction)
         self.assertEqual("OPEN", order1.offset)
         self.assertEqual(2, order1.volume_orign)
         self.assertEqual(2, order1.volume_left)
         self.assertEqual(3500.0, order1.limit_price)
         self.assertEqual(1593585743000000000, order1.insert_date_time)
         self.assertEqual("FINISHED", order1.status)
         self.assertEqual("LIMIT", order1.price_type)
         self.assertEqual("ANY", order1.volume_condition)
         self.assertEqual("IOC", order1.time_condition)
         self.assertEqual("已撤单报单已提交", order1.last_msg)
         self.assertEqual(
             "{'order_id': 'PYSDK_insert_SHFE_limit_FAK', 'exchange_order_id': '    25308102', 'exchange_id': 'SHFE', 'instrument_id': 'rb2010', 'direction': 'BUY', 'offset': 'OPEN', 'volume_orign': 2, 'volume_left': 2, 'limit_price': 3500.0, 'price_type': 'LIMIT', 'volume_condition': 'ANY', 'time_condition': 'IOC', 'insert_date_time': 1593585743000000000, 'last_msg': '已撤单报单已提交', 'status': 'FINISHED', 'seqno': 21, 'user_id': '83011119'}",
             str(order1))
 def test_insert_order_dce_limit_fok1(self):
     dir_path = os.path.dirname(os.path.realpath(__file__))
     self.mock.run(
         os.path.join(dir_path, "log_file",
                      "test_insert_order_dce_limit_fok1.script"))
     # 测试
     account = TqAccount("H海通期货", "83011119", "********")
     utils.RD = random.Random(4)
     with TqApi(account=account,
                _ins_url=self.ins_url_2020_06_16,
                _md_url=self.md_url,
                _td_url=self.td_url,
                debug=False) as api:
         order1 = api.insert_order("DCE.m2009",
                                   "SELL",
                                   "OPEN",
                                   2,
                                   limit_price=2905,
                                   advanced="FOK",
                                   order_id="PYSDK_insert_DCE_limit_FOK1")
         while True:
             api.wait_update()
             if order1.status == "FINISHED":
                 break
         self.assertEqual("PYSDK_insert_DCE_limit_FOK1", order1.order_id)
         self.assertEqual("    13619123", order1.exchange_order_id)
         self.assertEqual("DCE", order1.exchange_id)
         self.assertEqual("m2009", order1.instrument_id)
         self.assertEqual("SELL", order1.direction)
         self.assertEqual("OPEN", order1.offset)
         self.assertEqual(2, order1.volume_orign)
         self.assertEqual(0, order1.volume_left)
         self.assertEqual(2905.0, order1.limit_price)
         self.assertEqual(1593657671000000000, order1.insert_date_time)
         self.assertEqual("FINISHED", order1.status)
         self.assertEqual("LIMIT", order1.price_type)
         self.assertEqual("ALL", order1.volume_condition)
         self.assertEqual("IOC", order1.time_condition)
         self.assertEqual("全部成交", order1.last_msg)
         self.assertEqual(
             "{'order_id': 'PYSDK_insert_DCE_limit_FOK1', 'exchange_order_id': '    13619123', 'exchange_id': 'DCE', 'instrument_id': 'm2009', 'direction': 'SELL', 'offset': 'OPEN', 'volume_orign': 2, 'volume_left': 0, 'limit_price': 2905.0, 'price_type': 'LIMIT', 'volume_condition': 'ALL', 'time_condition': 'IOC', 'insert_date_time': 1593657671000000000, 'last_msg': '全部成交', 'status': 'FINISHED', 'seqno': 2, 'user_id': '83011119'}",
             str(order1))
 def test_insert_order_dec_best(self):
     dir_path = os.path.dirname(os.path.realpath(__file__))
     self.mock.run(
         os.path.join(dir_path, "log_file",
                      "test_insert_order_dec_best.script"))
     # 测试
     account = TqAccount("H海通期货", "83011119", "********")
     utils.RD = random.Random(4)
     # 测试
     with self.assertRaises(Exception):
         with TqApi(account=account,
                    _ins_url=self.ins_url_2020_06_16,
                    _md_url=self.md_url,
                    _td_url=self.td_url,
                    debug=False) as api:
             order1 = api.insert_order("DCE.m2009",
                                       "BUY",
                                       "OPEN",
                                       1,
                                       limit_price="BEST",
                                       order_id="PYSDK_insert_DCE_BEST")
 def test_insert_order_dce_anyprice(self):
     dir_path = os.path.dirname(os.path.realpath(__file__))
     self.mock.run(
         os.path.join(dir_path, "log_file",
                      "test_insert_order_dce_anyprice.script"))
     # 测试
     account = TqAccount("H海通期货", "83011119", "********")
     utils.RD = random.Random(4)
     with TqApi(account=account,
                _ins_url=self.ins_url_2020_06_16,
                _md_url=self.md_url,
                _td_url=self.td_url,
                debug=False) as api:
         order1 = api.insert_order("DCE.m2009",
                                   "BUY",
                                   "OPEN",
                                   1,
                                   order_id="PYSDK_insert_DCE_any")
         while True:
             api.wait_update()
             if order1.status == "FINISHED":
                 break
         self.assertEqual("PYSDK_insert_DCE_any", order1.order_id)
         self.assertEqual("    15350014", order1.exchange_order_id)
         self.assertEqual("DCE", order1.exchange_id)
         self.assertEqual("m2009", order1.instrument_id)
         self.assertEqual("BUY", order1.direction)
         self.assertEqual("OPEN", order1.offset)
         self.assertEqual(1, order1.volume_orign)
         self.assertEqual(0, order1.volume_left)
         self.assertEqual(0.0, order1.limit_price)
         self.assertEqual(1593586583000000000, order1.insert_date_time)
         self.assertEqual("FINISHED", order1.status)
         self.assertEqual("ANY", order1.price_type)
         self.assertEqual("ANY", order1.volume_condition)
         self.assertEqual("IOC", order1.time_condition)
         self.assertEqual("全部成交", order1.last_msg)
         self.assertEqual(
             "{'order_id': 'PYSDK_insert_DCE_any', 'exchange_order_id': '    15350014', 'exchange_id': 'DCE', 'instrument_id': 'm2009', 'direction': 'BUY', 'offset': 'OPEN', 'volume_orign': 1, 'volume_left': 0, 'limit_price': 0.0, 'price_type': 'ANY', 'volume_condition': 'ANY', 'time_condition': 'IOC', 'insert_date_time': 1593586583000000000, 'last_msg': '全部成交', 'status': 'FINISHED', 'seqno': 38, 'user_id': '83011119'}",
             str(order1))
Exemple #8
0
    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()
print(account)

# 获取目标期货代码
symbol = config_params['symbol_code']
long_short_judgment = None

position = api.get_position(symbol)
Exemple #9
0
            'trading_code': trading_code,
            'weight': signal.loc[symbol]['weight'],
            'last_price': close_dict[symbol],
            'VolumeMultiple':
            VolumeMultiple_dict[main_contract]['VolumeMultiple']
        }
    trading_info = pd.DataFrame(signal_dict).T
    trading_info['position'] = aum * balance / len(symbol_lst) * trading_info[
        'weight'] / trading_info['last_price'] / trading_info['VolumeMultiple']
    # trading_info['position'] = trading_info['position'].apply(lambda x: int(np.around(x, 0)))
    print(trading_info)
    return trading_info


if __name__ == '__main__':
    api = TqApi(TqAccount("simnow", "168694", "zg19491001"), web_gui=False)
    Trd = Trading(api)

    aum = 10000000
    balance = 6
    strategy_id = 'hmm'
    fold_path = 'c://g//trading_hmm//'
    # 收件人为多个收件人
    # receiver = ['*****@*****.**','*****@*****.**','*****@*****.**', '*****@*****.**', '*****@*****.**']
    receiver = ['*****@*****.**', '*****@*****.**', '*****@*****.**']
    today = datetime.date.today()
    index_code_lst = [
        'AG', 'I', 'JM', 'MA', 'PP', 'RM', 'RU', 'SC', 'SM', 'TA', 'IF', 'Y',
        'SN', 'ZC', 'AP', 'HC', 'AU', 'P', 'RB', 'V', 'B', 'CU', 'CF', 'L',
        'IH', 'J', 'NI', 'IC', 'AL', 'BU', 'FG', 'JD', 'M', 'ZN', 'A', 'SF',
        'OI', 'SR'
import datetime
from trading_future.future_singleton import Future
from trading_simulate.trading_fuction import Trading

# auth('18610039264', 'zg19491001')
from configDB import *
auth(JOINQUANT_USER, JOINQUANT_PW)

if __name__ == '__main__':
    signal_path = 'G://trading_strategy//'
    aum = 1000000
    balance = 10
    bars = 5
    # api = TqApi(TqAccount("simnow", "163919", "yo193846"), web_gui=True)
    # api = TqApi(TqAccount("快期模拟", "*****@*****.**", "zf1991"), web_gui=True)
    api = TqApi(TqAccount("G国泰君安", "85030120", "jz04282020"), web_gui=True)
    Trd = Trading(api)
    account = api.get_account()
    quote = api.get_quote("INE.sc2012")  # 获取SHFE.cu1812合约的10秒K线
    time_allowed_lst = quote.trading_time.day
    time_allowed_lst.extend(quote.trading_time.night)
    print(time_allowed_lst)

    times = 0

    # while datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') > '2020-05-18 09:00:00' and times == 0:
    #     print(times)

    for i in range(3):
        order = Trd.insert_order_sk_limit('INE.sc2012', 1)
        order = Trd.insert_order_bk_limit('INE.sc2007', 1)
#!/usr/bin/env python
#  -*- coding: utf-8 -*-

from tqsdk import TqApi, TqAccount

from otg_check_helper import check_orders, check_positions, check_account, check_risk_rule, check_risk_data, check_all
from test_for_etf.base_info import bid, user_id, pwd, td_url, test_logger

if __name__ == '__main__':
    api = TqApi(TqAccount(bid, user_id, pwd),
                auth="ringo,Shinnytech123",
                _stock=True,
                _td_url=td_url)

    # 成交持仓比风控规则
    rule = api.set_risk_management_rule("SSE",
                                        True,
                                        trade_units_limit=6,
                                        trade_position_ratio_limit=150)

    test_logger.info(f"{'='*12} 期权 开仓 {'='*12}")
    symbol = "SSE.10002477"
    quote = api.get_quote(symbol)  # ETF 期权
    # 挂单
    buy_order = api.insert_order(symbol=symbol,
                                 direction="BUY",
                                 offset="OPEN",
                                 limit_price=quote.ask_price1,
                                 volume=10)
    while buy_order.status == "ALIVE":
        api.wait_update()
Exemple #12
0
t2 = str(t2.year) + str(t2.month).zfill(2) + str(t2.day).zfill(2)
df = pro.query('trade_cal', exchange='DCE', start_date=t1, end_date=t2)
trade_dates = df[df['is_open'] == 1]['cal_date'].unique()
trade_dates = list(trade_dates)
last_time_2 = None

if __name__ == '__main__':
    if backtest:
        acc = TqSim(init_balance=1000000)
        print(start_date, end_date)
        api = TqApi(acc,
                    backtest=TqBacktest(start_dt=start_date, end_dt=end_date),
                    web_gui='127.0.0.1:9999')
        quote1 = api.get_quote('SHFE.ag2005')
    else:
        api = TqApi(TqAccount("快期模拟", "******", "*******"))

    # load model
    model_path = 'model/model.pickle'
    with open(model_path, 'rb+') as f:
        clf = pickle.load(f)

    while True:
        if backtest:
            now_time_ = datetime.datetime.strptime(quote1.datetime,
                                                   "%Y-%m-%d %H:%M:%S.%f")
            trade_date = str(now_time_.year) + str(
                now_time_.month).zfill(2) + str(now_time_.day).zfill(2)
            zhuli = ZhuLi_HeYue(trade_date=trade_date, now_time=now_time_)
        else:
            now_time_ = datetime.datetime.now()
Exemple #13
0
from tqsdk import TqApi, TqAccount

api = TqApi(TqAccount("华鑫期货", "910890802", "1503p.o."), auth="论坛邮箱账户,论坛密码")
order = api.insert_order("DCE.i2009-C-520", "BUY", "OPEN", 1, 110)

while True:
    api.wait_update()
    if order.status == "FINISHED" and order.volume_left == 0:
        print("权限已开通,订单已完成")
        break

api.close()
Exemple #14
0
from tqsdk import TqApi, TqSim, TqAccount
api = TqApi(TqAccount("simnow", "093391", "hz2327300"))
account = api.get_account()
print("登录成功,账户权益: %.2f" % (account.balance))
买卖开平选择 = int(input('1.买开卖平;2.卖开买平;3.买平卖开;4.卖平买开;其他退出,请选择:'))
while 买卖开平选择 == 1 or 买卖开平选择 == 2 or 买卖开平选择 == 3 or 买卖开平选择 == 4:
    api.wait_update()
    if 买卖开平选择 == 1:
        首价格 = int(input('首价格:'))
        单笔数量 = int(input('单笔数量:'))
        总数量 = int(input('总数量:'))
        价格间隔 = int(input('价格间隔:'))
        平仓参数 = int(input('平仓参数:'))
        while 总数量:
            print('玉米2001' + '●买开/' + '%d/%d/%d' % (首价格, 单笔数量, 首价格 + 平仓参数) +
                  '●卖平')
            order = api.insert_order(symbol="DCE.c2001",
                                     direction="BUY",
                                     offset="OPEN",
                                     limit_price=首价格,
                                     volume=单笔数量)
            #对应循环单 order = api.insert_order(symbol="DCE.c2001", direction="SELL", offset="CLOSE", limit_price=首价格+平仓参数,volume=单笔数量)
            总数量 -= 1
            首价格 -= 价格间隔
    elif 买卖开平选择 == 2:
        首价格 = int(input('首价格:'))
        单笔数量 = int(input('单笔数量:'))
        总数量 = int(input('总数量:'))
        价格间隔 = int(input('价格间隔:'))
        平仓参数 = int(input('平仓参数:'))
        while 总数量:
Exemple #15
0
 def test_api_vipuser_account(self):
     api = TqApi(account=TqAccount("simnow", "103988", "MaYanQiong"),
                 auth="[email protected],MaYanQiong")
     self.assertEqual(api._md_url,
                      "wss://api.shinnytech.com/t/nfmd/front/mobile")
     api.close()
Exemple #16
0
          [sg.Text('长周期'), sg.Input(60, key="long")],
          [sg.OK(), sg.Cancel()]]
window = sg.Window('请输入策略运行参数', layout)

# 读取用户输入值
event, values = window.Read()
print(event, values)
window.close()


# 正常运行策略代码
SHORT = int(values["short"])  # 短周期
LONG = int(values["long"])  # 长周期
SYMBOL = values["symbol"]

api = TqApi(TqAccount(values["broker_id"], values["user_id"], values["password"]))
print("策略开始运行")

data_length = LONG + 2  # k线数据长度
klines = api.get_kline_serial(SYMBOL, duration_seconds=60, data_length=data_length)
target_pos = TargetPosTask(api, SYMBOL)

while True:
    api.wait_update()

    if api.is_changing(klines.iloc[-1], "datetime"):  # 产生新k线:重新计算SMA
        short_avg = ma(klines["close"], SHORT)  # 短周期
        long_avg = ma(klines["close"], LONG)  # 长周期

        # 均线下穿,做空
        if long_avg.iloc[-2] < short_avg.iloc[-2] and long_avg.iloc[-1] > short_avg.iloc[-1]:
Exemple #17
0
# -*- coding: utf-8 -*-
# @Time    : 2020/4/27 14:53
# @Author  : zhangfang
from tqsdk import TqApi, TqSim, TqAccount

api = TqApi(TqAccount("快期模拟", "*****@*****.**", "zf1991"), web_gui=True)
#!/usr/bin/env python
#  -*- coding: utf-8 -*-


from tqsdk import TqApi, TqAccount

from otg_check_helper import check_orders, check_positions, check_account, check_risk_rule, check_risk_data, check_all
from test_for_etf.base_info import bid, user_id, pwd, td_url, test_logger


if __name__ == '__main__':
    api = TqApi(TqAccount(bid, user_id, pwd), auth="ringo,Shinnytech123", _stock=True, _td_url=td_url)

    # 频繁报撤单风控规则
    rule = api.set_risk_management_rule("SSE", True, insert_order_count_limit=6, cancel_order_count_limit=4, cancel_order_percent_limit=50)
    api.wait_update()

    test_logger.info(f"{'='*12} 期权 开仓 {'='*12}")
    symbol = "SSE.10002477"
    quote = api.get_quote(symbol)  # ETF 期权
    # 挂单
    order = api.insert_order(symbol=symbol, direction="SELL", offset="OPEN", limit_price=quote.ask_price1, volume=3)
    api.wait_update()
    api.cancel_order(order)
    while order.status == "ALIVE":
        api.wait_update()
    # check_all(api, bid, user_id, show_risk=True)
    # check_risk_rule(api, None)
    # check_risk_data(api, symbol)
    api.close()
Exemple #19
0
#!/usr/bin/env python
#  -*- coding: utf-8 -*-
import time

from tqsdk import TqApi, TqAccount

api = TqApi(TqAccount('快期模拟', 'yhlz714', '86888196'), web_gui=True)
# 获得 m2005 的持仓引用,当持仓有变化时 position 中的字段会对应更新
position = api.get_position("SHFE.rb2010")
# 获得资金账户引用,当账户有变化时 account 中的字段会对应更新
account = api.get_account()
# 下单并返回委托单的引用,当该委托单有变化时 order 中的字段会对应更新
# order = api.insert_order(symbol="SHFE.rb2010", direction="BUY", offset="OPEN", volume=5, limit_price=3575)
orders = api.get_order()
for i in orders:
    api.cancel_order(orders[i])
count = 0
while True:

    api.wait_update()
    # if api.is_changing(order, ["status", "volume_orign", "volume_left"]):
    #     print("单状态: %s, 已成交: %d 手" % (order.status, order.volume_orign - order.volume_left))
    # print(order.status)
    if api.is_changing(position, "pos_long_today"):
        print("今多头: %d 手" % (position.pos_long_today))
    if api.is_changing(account, "available"):
        print("可用资金: %.2f" % (account.available))
    count += 1
    if 50 < count < 52:
        pass
        # api.cancel_order(order)
            'trading_code': trading_code,
            'weight': signal.loc[symbol]['weight'],
            'last_price': close_dict[symbol],
            'VolumeMultiple':
            VolumeMultiple_dict[main_contract]['VolumeMultiple']
        }
    trading_info = pd.DataFrame(signal_dict).T
    trading_info['position'] = aum * balance / len(symbol_lst) * trading_info[
        'weight'] / trading_info['last_price'] / trading_info['VolumeMultiple']
    # trading_info['position'] = trading_info['position'].apply(lambda x: int(np.around(x, 0)))
    print(trading_info)
    return trading_info


if __name__ == '__main__':
    api = TqApi(TqAccount("simnow", "176793", "yo193846"), web_gui=False)
    Trd = Trading(api)

    aum = 10000000
    balance = 2
    strategy_id = 'hmm'
    fold_path = 'c://g//trading_hmm_stockindex//'
    resualt_path = 'c:/e/hmm/resualt/stockindex/'
    # 收件人为多个收件人
    # receiver = ['*****@*****.**','*****@*****.**','*****@*****.**', '*****@*****.**', '*****@*****.**']
    receiver = ['*****@*****.**', '*****@*****.**', '*****@*****.**']
    today = datetime.date.today()
    StartDate = '2017-01-01'

    index_code_lst = ['IF', 'IH', 'IC']
    asset_lst = ['000300.XSHG', '000016.XSHG', '000905.XSHG']
Exemple #21
0
# logger.addHandler(mail_handler)
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)
logger.propagate = False

# try:
if __name__ == '__main__':
    logger.debug('This is yhlz\'s trading server,now started!\n')

    # 定义常量
    durationTransDict = {'1m': 60, '1d': 86400}

    try:
        # api=TqApi(TqAccount('快期模拟','284837','86888196'))
        api = TqApi(TqAccount('simnow', '133492', 'Yhlz0000'), web_gui=True)
        logger.info('success sign in! with simnow')
        # api = TqApi(TqAccount('H华安期货', '100909186', 'Yhlz0000'))
        # Yhlz.info('success sign in! with 100909186')

    except Exception as e:
        logger.info('problem with sign in!')
        exit(1)

    f = open('strategytorun.txt')
    temp = f.readlines()
    f.close()

    '---------------------------------------------------初始化数据------------------------------------------------------'

    strategys = {}
Exemple #22
0
#  -*- coding: utf-8 -*-
from tqsdk import TqApi, TqSim, TqAccount
import time
import subprocess
'''
下单

order = api.insert_order(symbol="SHFE.rb2005", direction="BUY", offset="OPEN", volume=1, limit_price=3570)
CFFEX: 中金所 SHFE: 上期所 DCE: 大商所 CZCE: 郑商所 INE: 能源交易所(原油)

'''
try:
    # api = TqApi(TqAccount("H华安期货", "117889998", "262010",front_broker='6020',front_url='tcp://183.11.217.235:41207'),web_gui="0.0.0.0:9876")
    api = TqApi(TqAccount("快期模拟", "cjj208", "Chenjj1230"))
    # api = TqApi(TqAccount("simnow", "090828", "jimc1230",front_broker='9999',front_url='tcp://180.168.146.187:10100'),web_gui="0.0.0.0:9876")#web_gui="0.0.0.0:9876"
    account = api.get_account()  # 获取用户账户资金信息
    klines = api.get_kline_serial('SHFE.rb2005', 5 * 60,
                                  data_length=500)  #获取k线序列数据
    position = api.get_position('SHFE.rb2005')  #指定一个品种查看持仓相关信息
    order = api.get_order('SHFE.rb2005')  # 获取用户委托单信息
    quote = api.get_quote('SHFE.rb2005')  #获取指定合约的盘口行情.
    api.is_changing(position, "pos_long_today")  #判定obj最近是否有更新
    # orderinsert = api.insert_order(symbol="SHFE.rb2005", direction="BUY", offset="OPEN", volume=1, limit_price=3570)
except Exception as e:
    print("行情服务连不上, 或者期货公司服务器关了, 或者账号密码错了, 总之就是有问题")

# 监听下单后有没有成交
api.wait_update()
order = api.insert_order(symbol="SHFE.rb2005",
                         direction="BUY",
                         offset="CLOSE",
Exemple #23
0
                elif change_day > today >= last_change_day:
                    limit_dict = {'FU': 1500, 'SC': 1500}
                else:
                    limit_dict = {'FU': 500, 'SC': 500}
                data_dict[symbol] = limit_dict[product]
            elif product in ['TF', 'TS', 'T']:
                expireDate = pd.to_datetime(expireDate)
                change_day = self.find_tradeday(-1,
                                                date=expireDate.replace(day=1),
                                                exchange=exchange_id)
                if today < change_day:
                    limit_dict = {'TF': 2000, 'TS': 2000, 'T': 2000}
                else:
                    limit_dict = {'TF': 600, 'TS': 600, 'T': 600}
                data_dict[symbol] = limit_dict[product]
        return data_dict


if __name__ == '__main__':
    # DataFactory.config(MONGDB_PW='jz2018*', MONGDB_IP='192.168.2.201', MONGDB_USER='******',
    #                    DATASOURCE_DEFAULT=global_variable.DATASOURCE_REMOTE
    #                    , logging_level=global_variable.logging.INFO)
    # rd = redis.Redis('192.168.1.36')
    api = TqApi(TqAccount("H华安期货", "100921556", "425408"), web_gui=True)
    Trd = Trading(api)
    order = Trd.insert_order_bk_limit('CZCE.TA101', 1)
    # for i in range(1):
    #     order = Trd.insert_order_bp_limit('SHFE.cu2008', 1)
    #     order = Trd.insert_order_sp_limit('SHFE.cu2009', 1)
    #     time.sleep(5)
Exemple #24
0
# -*- coding:utf-8 -*- 
# author: limm_666

from datetime import date, datetime
from functools import reduce
from tqsdk import TqApi, TargetPosTask, TqAccount, TqSim, TqBacktest

SYMBOL = "DCE.c2009"  # 合约代码
START_PRICE = 1874  # 起始价位
GRID_AMOUNT = 7  # 网格在多头、空头方向的格子(档位)数量

api = TqApi(TqAccount())
grid_region_long = [0.02] * GRID_AMOUNT  # 多头每格价格跌幅(网格密度)
grid_region_short = [0.01] * GRID_AMOUNT  # 空头每格价格涨幅(网格密度)
grid_volume_long = [i for i in range(GRID_AMOUNT + 1)]  # 多头每格持仓手数
grid_volume_short = [i for i in range(GRID_AMOUNT + 1)]  # 空头每格持仓手数
grid_prices_long = [reduce(lambda p, r: p * (1 - r), grid_region_long[:i], START_PRICE) for i in
                    range(GRID_AMOUNT + 1)]  # 多头每格的触发价位列表
grid_prices_short = [reduce(lambda p, r: p * (1 + r), grid_region_short[:i], START_PRICE) for i in
                     range(GRID_AMOUNT + 1)]  # 空头每格的触发价位列表

print("策略开始运行, 起始价位: %f, 多头每格持仓手数:%s, 多头每格的价位:%s, 空头每格的价位:%s" % (
    START_PRICE, grid_volume_long, grid_prices_long, grid_prices_short))
quote = api.get_quote(SYMBOL)  # 行情数据
target_pos = TargetPosTask(api, SYMBOL)
position = api.get_position(SYMBOL)  # 持仓信息


def wait_price(layer):
    """等待行情最新价变动到其他档位,则进入下一档位或回退到上一档位; 如果从下一档位回退到当前档位,则设置为当前对应的持仓手数;
        layer : 当前所在第几个档位层次; layer>0 表示多头方向, layer<0 表示空头方向
Exemple #25
0
if __name__ == '__main__':
    loadConfig()
    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'],
Exemple #26
0
def run_tianqin_code(bid, user_id, pwd, td_url):
    api = TqApi(TqAccount(bid, user_id, pwd),
                auth="[email protected],MaYanQiong",
                _td_url=td_url)
    is_ctp = False if bid == "快期模拟" else True
    account = api.get_account()
    if bid == "快期模拟":
        assert account.ctp_balance == '-' or math.isnan(account.ctp_balance)
        assert account.ctp_available == '-' or math.isnan(
            account.ctp_available)
    else:
        logger.info(f"{account.ctp_balance}, {account.ctp_available}")

    logger.info(f"{'='*30} 登录成功后,账户初始状态 {'='*30}")
    positions = api._data["trade"][user_id]["positions"]
    orders = api._data["trade"][user_id]["orders"]
    check_orders(orders, api, is_ctp)
    check_positions(positions, api, is_ctp)
    check_account(account, positions, is_ctp)

    logger.info(f"{'='*30} 全部撤单 & 全部平仓 {'='*30}")
    for order in orders.values():
        if order.status != "FINISHED":
            api.cancel_order(order)

    for pos in positions.values():
        symbol = f"{pos.exchange_id}.{pos.instrument_id}"
        quote = api.get_quote(symbol)
        if pos.pos_long > 0:
            api.insert_order(symbol=symbol,
                             direction="SELL",
                             offset="CLOSE",
                             limit_price=quote.bid_price1,
                             volume=pos.pos_long)
        if pos.pos_short > 0:
            api.insert_order(symbol=symbol,
                             direction="BUY",
                             offset="CLOSE",
                             limit_price=quote.ask_price1,
                             volume=pos.pos_short)

    while True:
        api.wait_update(deadline=time.time() + 30)
        # 全部持仓清 0
        is_all_clear = True
        for pos in positions.values():
            if pos.pos_long > 0 or pos.pos_short > 0:
                is_all_clear = False
        for order in orders.values():
            if order.status != "FINISHED":
                is_all_clear = False
        if is_all_clear:
            logger.info("全部撤单 & 全部平仓 ok")
            break
        else:
            logger.info("还没完成全部撤单 & 全部平仓")

    logger.info(f"{'='*12} 期货 开仓 {'='*12}")
    quote = api.get_quote("CZCE.RM105")
    api.insert_order(symbol="CZCE.RM105",
                     direction="BUY",
                     offset="OPEN",
                     limit_price=quote.lower_limit + quote.price_tick,
                     volume=2)
    api.insert_order(symbol="CZCE.RM105",
                     direction="BUY",
                     offset="OPEN",
                     limit_price=quote.ask_price1,
                     volume=3)
    quote1 = api.get_quote("CZCE.CF105")
    api.insert_order(symbol="CZCE.CF105",
                     direction="SELL",
                     offset="OPEN",
                     limit_price=quote1.upper_limit - quote1.price_tick,
                     volume=2)
    api.insert_order(symbol="CZCE.CF105",
                     direction="SELL",
                     offset="OPEN",
                     limit_price=quote1.bid_price1,
                     volume=3)
    check_all(api, bid, user_id)

    # logger.info(f"{'='*12} 期权 开仓 {'='*12}")
    # quote = api.get_quote("CZCE.RM009C2300")
    # api.insert_order(symbol="CZCE.RM009C2300", direction="BUY", offset="OPEN",
    #                          limit_price=quote.lower_limit + quote.price_tick,
    #                          volume=2)
    # api.insert_order(symbol="CZCE.RM009C2300", direction="BUY", offset="OPEN", limit_price=quote.ask_price1,
    #                          volume=3)
    # quote1 = api.get_quote("CZCE.CF009C11600")
    # api.insert_order(symbol="CZCE.CF009C11600", direction="SELL", offset="OPEN",
    #                          limit_price=quote1.upper_limit - quote1.price_tick,
    #                          volume=2)
    # api.insert_order(symbol="CZCE.CF009C11600", direction="SELL", offset="OPEN", limit_price=quote1.bid_price1,
    #                          volume=3)
    #
    # quote2 = api.get_quote("CZCE.RM009P2300")
    # api.insert_order(symbol="CZCE.RM009P2300", direction="BUY", offset="OPEN",
    #                  limit_price=quote2.lower_limit + quote2.price_tick,
    #                  volume=2)
    # api.insert_order(symbol="CZCE.RM009P2300", direction="BUY", offset="OPEN", limit_price=quote2.ask_price1,
    #                  volume=3)
    # quote3 = api.get_quote("CZCE.CF009C11600")
    # api.insert_order(symbol="CZCE.CF009P11600", direction="SELL", offset="OPEN",
    #                  limit_price=quote3.upper_limit - quote3.price_tick,
    #                  volume=2)
    # api.insert_order(symbol="CZCE.CF009P11600", direction="SELL", offset="OPEN", limit_price=quote3.bid_price1,
    #                  volume=3)

    # PUT
    # check_all(api, bid, user_id)

    # logger.info(f"{'='*30} 发平仓挂单 {'='*30}")
    # positions = api._data["trade"][user_id]["positions"]
    # for pos in positions.values():
    #     symbol = f"{pos.exchange_id}.{pos.instrument_id}"
    #     quote = api.get_quote(symbol)
    #     if pos.pos_long > 0:
    #         api.insert_order(symbol=symbol, direction="SELL", offset="CLOSE",
    #                          limit_price=quote.upper_limit - quote.price_tick,
    #                          volume=pos.pos_long)
    #     if pos.pos_short > 0:
    #         api.insert_order(symbol=symbol, direction="BUY", offset="CLOSE",
    #                          limit_price=quote.lower_limit + quote.price_tick,
    #                          volume=pos.pos_short)
    # check_all(api, bid, user_id)
    api.close()
def run_tianqin_code(bid, user_id, pwd, td_url):
    api = TqApi(TqAccount(bid, user_id, pwd), auth="[email protected],MaYanQiong", _stock=True,
                _md_url="wss://nfmd.shinnytech.com/t/nfmd/front/mobile", _td_url=td_url)
    print(api._md_url)
    is_ctp = False if bid == "快期模拟" else True
    account = api.get_account()
    if bid == "快期模拟":
        assert account.ctp_balance == '-' or math.isnan(account.ctp_balance)
        assert account.ctp_available == '-' or math.isnan(account.ctp_available)
    else:
        logger.info(f"{account.ctp_balance}, {account.ctp_available}")

    logger.info(f"{'='*30} 登录成功后,账户初始状态 {'='*30}")
    positions = api._data["trade"][user_id]["positions"]
    orders = api._data["trade"][user_id]["orders"]
    check_orders(orders, api, is_ctp)
    check_positions(positions, api, is_ctp)
    check_account(account, positions, is_ctp)

    logger.info(f"{'='*12} 期权 开仓 {'='*12}")
    quote = api.get_quote("CZCE.RM105")  # ETF 期权
    print(quote)
    # 挂单
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price=quote.lower_limit + quote.price_tick, volume=2)
    # 可成交
    order = api.insert_order(symbol="CZCE.RM105", direction="BUY", offset="OPEN", limit_price=quote.ask_price1, volume=1)
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price=quote.ask_price1, volume=3)
    # 可成交 FAK 下单失败,CTP:交易所不支持的价格类型
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price=quote.ask_price1, volume=2, advanced="FAK")
    # 可成交 FOK
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price=quote.ask_price1, volume=2, advanced="FOK")

    # BEST
    # order = api.insert_order(symbol="SSE.10002513", direction="SELL", offset="CLOSE", limit_price="BEST", volume=10)
    # BEST FOK 下单失败,已撤单报单被拒绝12038,合约代码:SSE.10002513,下单方向:买,开平标志:开仓,委托价格:最优价,委托手数:3
    # order = api.insert_order(symbol="SSE.10002513", direction="SELL", offset="CLOSE", limit_price="BEST", volume=3, advanced="FOK")

    # any_price 通知: 下单失败,CTP:交易所不支持的价格类型
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", volume=3)
    # FIVELEVEL 通知: 下单失败,CTP:交易所不支持的价格类型
    # order = api.insert_order(symbol="SSE.10002513", direction="BUY", offset="OPEN", limit_price="FIVELEVEL", volume=3)

    while order.status == "ALIVE":
        api.wait_update()
    api.wait_update()
    api.wait_update()
    check_all(api, bid, user_id)

    # logger.info(f"{'='*30} 发平仓挂单 {'='*30}")
    # positions = api._data["trade"][user_id]["positions"]
    # for pos in positions.values():
    #     symbol = f"{pos.exchange_id}.{pos.instrument_id}"
    #     quote = api.get_quote(symbol)
    #     if pos.pos_long > 0:
    #         api.insert_order(symbol=symbol, direction="SELL", offset="CLOSE",
    #                          limit_price=quote.upper_limit - quote.price_tick,
    #                          volume=pos.pos_long)
    #     if pos.pos_short > 0:
    #         api.insert_order(symbol=symbol, direction="BUY", offset="CLOSE",
    #                          limit_price=quote.lower_limit + quote.price_tick,
    #                          volume=pos.pos_short)
    # check_all(api, bid, user_id)
    api.close()
Exemple #28
0
import time
from jqdatasdk import *
import datetime
from trading_simulate.trading_fuction import Trading

# auth('18610039264', 'zg19491001')
from configDB import *
auth(JOINQUANT_USER, JOINQUANT_PW)

if __name__ == '__main__':
    signal_path = 'G://trading_strategy//'
    aum = 1000000
    balance = 10
    bars = 5
    # api = TqApi(TqAccount("快期模拟", "*****@*****.**", "zf1991"), web_gui=True)
    api = TqApi(TqAccount("simnow", "163919", "yo193846"), web_gui=False)
    Trd = Trading(api)
    calen = get_trade_days(count=bars)
    today = datetime.date.today()
    calen = list(calen)
    if today in calen:
        calen, next_tradeday, EndDate, StartDate, hq_last_date = Trd.get_date(
            calen, today)

        temp_ymjh = pd.read_csv(signal_path + 'position_' + 'ymjh' + '_' + hq_last_date + '.csv', index_col=0)[
            ['VolumeMultiple', 'last_price', 'symbol', 'trading_code', 'position']]\
            .rename(columns={'position': 'position_ymjh'})
        temp_tcs = pd.read_csv(signal_path + 'position_' + 'tcs' + '_' + hq_last_date + '.csv', index_col=0)[
            ['VolumeMultiple', 'last_price', 'symbol', 'trading_code', 'position']]\
            .rename(columns={'position': 'position_tcs'})
        temp_momentum = pd.read_csv(signal_path + 'position_' + 'momentum' + '_' + hq_last_date + '.csv', index_col=0)[
Exemple #29
0
#!/usr/bin/env python
#  -*- coding: utf-8 -*-
__author__ = 'chengzhi'
import subprocess
from tqsdk import TqApi, TqAccount
import nest_asyncio
nest_asyncio.apply()
# api = TqApi(TqAccount("H华安期货", "117889998", "262010",front_broker='6020',front_url='tcp://183.11.217.235:41207'),web_gui="0.0.0.0:9876")
# api = TqApi(TqAccount("快期模拟", "cjj208", "Chenjj1230"))
api = TqApi(TqAccount("simnow",
                      "090828",
                      "jimc1230",
                      front_broker='9999',
                      front_url='tcp://180.168.146.187:10100'),
            web_gui="0.0.0.0:9876")

# 获得 m2005 的持仓引用,当持仓有变化时 position 中的字段会对应更新
position = api.get_position("SHFE.rb2005")
# 获得资金账户引用,当账户有变化时 account 中的字段会对应更新
account = api.get_account()
# 下单并返回委托单的引用,当该委托单有变化时 order 中的字段会对应更新
order = api.insert_order(symbol="SHFE.rb2005",
                         direction="BUY",
                         offset="OPEN",
                         volume=2,
                         limit_price=3521)
#canorder = api.cancel_order(order)

while True:
    api.wait_update()
    if api.is_changing(order, ["status", "volume_orign", "volume_left"]):
#!/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":