Beispiel #1
0
def init0(broker = 'yh'):
	print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n')
	inited = True
	
	try:
		global g_yhUser, g_gfUser
		if broker == 'yh':
			g_yhUser = easytrader.use('yh',debug=False)
			g_yhUser.prepare('u:\yh.json')
		
		if broker == 'gf':
			g_gfUser = easytrader.use('gf',debug=False)
			g_gfUser.prepare('u:\gf.json')
		
		#print(str(inited) + ': YinHe config initialized')
	except Exception as e:
		print(e)
		inited = False
	msg0 = '{0}: config initialized @ {1}'	
	msg0 = msg0.format(str(inited), dateTime())
	print(msg0)
	
	_sendMsg(msg=msg0)
	print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n')
	return msg0
Beispiel #2
0
def ths():
    config_path = Path(
        r"D:\github\easytrader\tests\config\Accoun_configure.yml")
    with open(config_path, mode="r", encoding="utf-8") as rf:
        config = yaml.load(rf, Loader=yaml.Loader)

    person = config['acc1']
    # 下单程序路径
    broker_name = person["broker_name"]
    app_path = person["application_path"]
    # 帐号数据
    account_no = person["account_no"]
    password = person["password"]
    commu_code = person["commu_code"]
    if broker_name == "中信山东":
        ths = easytrader.use("zx_client")
    elif broker_name == "华泰证券":
        ths = easytrader.use("ht_client")
    elif broker_name == "长江证券":
        ths = easytrader.use("cj_client")
    try:
        ths.login(user=account_no,
                  password=password,
                  comm_password=commu_code,
                  exe_path=app_path)
        ths.close_pop_dialog()
    except:
        pass

    yield ths

    ths.exit()
Beispiel #3
0
 def __enter__(self):
     self.user_ = easytrader.use('yh_client')
     self.user_.prepare(user=self.username_,
                        password=self.password_,
                        exe_path=self.exePath_)
     time.sleep(2)
     return self
Beispiel #4
0
 def __makeSureConnect(cls):
     '''
     一些确保账户连接可用的操作
     :return:
     '''
     count = 0
     while count < 3:
         try:
             #验证连接
             cls.user.balance
             break
         except:
             count += 1
             print('账户未连接,现在开始执行第{}次连接操作!'.format(str(count)))
             try:
                 cls.user = et.use('yh_client')
                 cls.user.prepare(
                     user='******',
                     password='******',
                     exe_path='D:/双子星金融终端独立交易-中国银河证券/xiadan.exe')
                 cls.user.connect(
                     exe_path='D:/双子星金融终端独立交易-中国银河证券/xiadan.exe')
             except:
                 time.sleep(1)
                 pass
Beispiel #5
0
    def __init__(self,
                 broker,
                 need_data='me.json',
                 quotation_engines=[DefaultQuotationEngine],
                 log_handler=DefaultLogHandler()):
        """初始化事件 / 行情 引擎并启动事件引擎
        """
        # 登录账户
        self.user = easytrader.use(broker)
        self.user.prepare(need_data)

        self.event_engine = EventEngine()
        self.clock_engine = ClockEngine(self.event_engine)

        if type(quotation_engines) != list:
            quotation_engines = [quotation_engines]
        self.quotation_engines = []
        for quotation_engine in quotation_engines:
            self.quotation_engines.append(quotation_engine(self.event_engine))

        # 保存读取的策略类
        self.strategies = OrderedDict()
        self.strategy_list = list()
        self.log = log_handler

        self.log.info('启动主引擎')
Beispiel #6
0
    def __init__(self, broker=None, need_data=None, quotation_engines=None,
                 log_handler=DefaultLogHandler(), now=None, tzinfo=None):
        """初始化事件 / 行情 引擎并启动事件引擎
        """
        self.log = log_handler

        # 登录账户
        if (broker is not None) and (need_data is not None):
            self.user = easytrader.use(broker)
            need_data_file = pathlib.Path(need_data)
            if need_data_file.exists():
                self.user.prepare(need_data)
            else:
                log_handler.warn("券商账号信息文件 %s 不存在, easytrader 将不可用" % need_data)
        else:
            self.user = None
            self.log.info('选择了无交易模式')

        self.event_engine = EventEngine()
        self.clock_engine = ClockEngine(self.event_engine, now, tzinfo)

        quotation_engines = quotation_engines or [DefaultQuotationEngine]

        if type(quotation_engines) != list:
            quotation_engines = [quotation_engines]
        self.quotation_engines = []
        for quotation_engine in quotation_engines:
            self.quotation_engines.append(quotation_engine(self.event_engine, self.clock_engine))

        # 保存读取的策略类
        self.strategies = OrderedDict()
        self.strategy_list = list()

        self.log.info('启动主引擎')
 def __init__(self):
     self.db = MongoDB(XUEQIU_DB_NAME)
     self.logger = get_logger(COLLECTION)
     self.xq = easytrader.use('xq')
     self.xq.prepare('config/xq1.json')
     self.email = Email()
     self.trade_time = get_date_now("CN")
 def test_login(self):
     user_str = '050000006***'
     password_str = '123123'  # bytes.decode(base64.decodebytes(b'123123'))
     user = easytrader.use('ht_client')
     # user.prepare(user='******', password=password_str)
     # user = easytrader.use('hb_client')
     user.prepare(user=user_str, password=password_str)
 def __init__(self):
     self.db = MongoDB(XUEQIU_DB_NAME)
     self.logger = get_logger(COLLECTION)
     self.xq = easytrader.use('xq')
     self.xq.prepare('config/xq1.json')
     self.email = Email()
     self.trade_time = get_date_now("CN")
Beispiel #10
0
    def test_format_response_data_type(self):
        user = easytrader.use('ht')

        test_data = [{
            'current_amount': '187.00',
            'current_balance': '200.03',
            'stock_code': '000001'
        }]
        result = user.format_response_data_type(test_data)

        self.assertIs(type(result[0]['current_amount']), int)
        self.assertIs(type(result[0]['current_balance']), float)
        self.assertIs(type(result[0]['stock_code']), str)

        test_data = [{'position_str': '',
                      'date': '',
                      'fund_account': '',
                      'stock_account': '',
                      'stock_code': '',
                      'entrust_bs': '',
                      'business_price': '',
                      'business_amount': '',
                      'business_time': '',
                      'stock_name': '',
                      'business_status': '',
                      'business_type': ''}]
        result = user.format_response_data_type(test_data)
Beispiel #11
0
def main(prepare, use, do, get, params, debug):
    if get is not None:
        do = get
    if prepare is not None and use in [
            'ht_client', 'yjb', 'yh_client', 'yh', 'ht', 'gf', 'xq', 'yjb',
            'gzzq'
    ]:
        user = easytrader.use(use, debug)
        user.prepare(prepare)
        with open(ACCOUNT_OBJECT_FILE, 'wb') as f:
            dill.dump(user, f)
    if do is not None:
        with open(ACCOUNT_OBJECT_FILE, 'rb') as f:
            user = dill.load(f)

        if get is not None:
            result = getattr(user, do)
        else:
            result = getattr(user, do)(*params)

        json_result = json.dumps(result,
                                 indent=4,
                                 ensure_ascii=False,
                                 sort_keys=True)
        click.echo(json_result)
Beispiel #12
0
    def test_format_response_data_type(self):
        user = easytrader.use("ht")

        test_data = [{"current_amount": "187.00", "current_balance": "200.03", "stock_code": "000001"}]
        result = user.format_response_data_type(test_data)

        self.assertIs(type(result[0]["current_amount"]), int)
        self.assertIs(type(result[0]["current_balance"]), float)
        self.assertIs(type(result[0]["stock_code"]), str)

        test_data = [
            {
                "position_str": "",
                "date": "",
                "fund_account": "",
                "stock_account": "",
                "stock_code": "",
                "entrust_bs": "",
                "business_price": "",
                "business_amount": "",
                "business_time": "",
                "stock_name": "",
                "business_status": "",
                "business_type": "",
            }
        ]
        result = user.format_response_data_type(test_data)
Beispiel #13
0
    def test_format_response_data_type(self):
        user = easytrader.use('ht')

        test_data = [{
            'current_amount': '187.00',
            'current_balance': '200.03',
            'stock_code': '000001'
        }]
        result = user.format_response_data_type(test_data)

        self.assertIs(type(result[0]['current_amount']), int)
        self.assertIs(type(result[0]['current_balance']), float)
        self.assertIs(type(result[0]['stock_code']), str)

        test_data = [{
            'position_str': '',
            'date': '',
            'fund_account': '',
            'stock_account': '',
            'stock_code': '',
            'entrust_bs': '',
            'business_price': '',
            'business_amount': '',
            'business_time': '',
            'stock_name': '',
            'business_status': '',
            'business_type': ''
        }]
        result = user.format_response_data_type(test_data)
Beispiel #14
0
def get_position(broker='yh',user_file='yh.json'):
    user = easytrader.use(broker)
    user.prepare(user_file)
    holding_stocks_df = user.position#['证券代码']  #['code']
    user_balance = user.balance#['证券代码']  #['code']
    account = '36005'
    if user_file== 'yh1.json':
        account = '38736'
    holding_stocks_df['account'] = account
    this_day=datetime.datetime.now()
    date_format='%Y/%m/%d'
    time_format = date_format + ' %X'
    time_str=this_day.strftime(time_format)
    holding_stocks_df['update'] = time_str
    #holding_stocks_df['valid'] = 1
    """
            当前持仓  股份可用     参考市值   参考市价  股份余额    参考盈亏 交易市场   参考成本价 盈亏比例(%)        股东代码  \
            0  6300  6300  24885.0   3.95  6300  343.00   深A   3.896   1.39%  0130010635   
            1   400   400   9900.0  24.75   400  163.00   深A  24.343   1.67%  0130010635   
            2   600   600  15060.0  25.10   600  115.00   深A  24.908   0.77%  0130010635   
            3  1260     0  13041.0  10.35  1260  906.06   沪A   9.631   7.47%  A732980330   
            
                 证券代码  证券名称  买入冻结 卖出冻结  
            0  000932  华菱钢铁     0    0  
            1  000977  浪潮信息     0    0  
            2  300326   凯利泰     0    0  
            3  601009  南京银行     0    0  
    """
    #print(holding_stocks_df)
    return holding_stocks_df,user_balance       
Beispiel #15
0
def main(prepare, use, do, get, params, debug):
    if get is not None:
        do = get
    if prepare is not None and use in [
            "ht_client",
            "yjb",
            "yh_client",
            "yh",
            "ht",
            "gf",
            "xq",
    ]:
        user = easytrader.use(use, debug)
        user.prepare(prepare)
        with open(ACCOUNT_OBJECT_FILE, "wb") as f:
            dill.dump(user, f)
    if do is not None:
        with open(ACCOUNT_OBJECT_FILE, "rb") as f:
            user = dill.load(f)

        if get is not None:
            result = getattr(user, do)
        else:
            result = getattr(user, do)(*params)

        json_result = json.dumps(result,
                                 indent=4,
                                 ensure_ascii=False,
                                 sort_keys=True)
        click.echo(json_result)
Beispiel #16
0
    def __init__(self, broker, need_data='me.json', quotation_engines=[DefaultQuotationEngine],
                 log_handler=DefaultLogHandler()):
        """初始化事件 / 行情 引擎并启动事件引擎
        """
        # 登录账户
        self.user = easytrader.use(broker)
        need_data_file = pathlib.Path(need_data)
        if need_data_file.exists():
            self.user.prepare(need_data)
        else:
            log_handler.warn("券商账号信息文件 %s 不存在, easytrader 将不可用" % need_data)

        self.event_engine = EventEngine()
        self.clock_engine = ClockEngine(self.event_engine)

        if type(quotation_engines) != list:
            quotation_engines = [quotation_engines]
        self.quotation_engines = []
        for quotation_engine in quotation_engines:
            self.quotation_engines.append(quotation_engine(self.event_engine))

        # 保存读取的策略类
        self.strategies = OrderedDict()
        self.strategy_list = list()
        self.log = log_handler

        self.log.info('启动主引擎')
Beispiel #17
0
def main(prepare, use, do, get, params, debug):
    print("main")
    if get is not None:
        do = get
    if prepare is not None:
        print("Initial ths")
        user = easytrader.use('ths')
        user.connect(r'C:\ths\xiadan.exe')  # 类似 r'C:\htzqzyb2\xiadan.exe'
        print("connected")
        with open(ACCOUNT_OBJECT_FILE, 'wb') as f:
            dill.dump(user, f)
    if do is not None:
        with open(ACCOUNT_OBJECT_FILE, 'rb') as f:
            user = dill.load(f)

        if get is not None:
            result = getattr(user, do)
        else:
            result = getattr(user, do)(*params)

        json_result = json.dumps(result,
                                 indent=4,
                                 ensure_ascii=False,
                                 sort_keys=True)
        click.echo(json_result)

    print("mission complete")
Beispiel #18
0
def get_position(broker='yh',user_file='yh.json'):
    user = easytrader.use(broker)
    user.prepare(user_file)
    holding_stocks_df = user.position#['证券代码']  #['code']
    user_balance = user.balance#['证券代码']  #['code']
    account = '36005'
    if user_file== 'yh1.json':
        account = '38736'
    holding_stocks_df['account'] = account
    this_day=datetime.datetime.now()
    date_format='%Y/%m/%d'
    time_format = date_format + ' %X'
    time_str=this_day.strftime(time_format)
    holding_stocks_df['update'] = time_str
    #holding_stocks_df['valid'] = 1
    """
            当前持仓  股份可用     参考市值   参考市价  股份余额    参考盈亏 交易市场   参考成本价 盈亏比例(%)        股东代码  \
            0  6300  6300  24885.0   3.95  6300  343.00   深A   3.896   1.39%  0130010635   
            1   400   400   9900.0  24.75   400  163.00   深A  24.343   1.67%  0130010635   
            2   600   600  15060.0  25.10   600  115.00   深A  24.908   0.77%  0130010635   
            3  1260     0  13041.0  10.35  1260  906.06   沪A   9.631   7.47%  A732980330   
            
                 证券代码  证券名称  买入冻结 卖出冻结  
            0  000932  华菱钢铁     0    0  
            1  000977  浪潮信息     0    0  
            2  300326   凯利泰     0    0  
            3  601009  南京银行     0    0  
    """
    #print(holding_stocks_df)
    return holding_stocks_df,user_balance       
Beispiel #19
0
def main():

    #stock account
    trader = easytrader.use('ht', debug=False)
    trader.config['entrust']['cssweb_type'] = 'GET_TODAY_ENTRUST'
    #quotation
    quota = easyquotation.use('sina')

    print('login huatai system......')
    trader.prepare('ht.json')
    print('login successfully')

    show_balance(trader.balance[0])

    # if cash less than investment, quit and check
    if (trader.balance[0]['enable_balance'] < g_investment):
        print(
            '**WARNING: total cash is less than the investment you want to use, please check!'
        )
        return

    print('calculate the allocation for each stock...')
    stockbook = prepare(quota, g_stocks)

    print(stockbook)

    # process the orders
    process(trader, quota, stockbook)
Beispiel #20
0
def main():

	#stock account
	trader = easytrader.use('ht', debug=False)
	trader.config['entrust']['cssweb_type'] = 'GET_TODAY_ENTRUST'
	#quotation
	quota = easyquotation.use('sina')

	print('login huatai system......')
	trader.prepare('ht.json')
	print('login successfully')

	show_balance(trader.balance[0])

	# if cash less than investment, quit and check
	if (trader.balance[0]['enable_balance'] < g_investment):
		print('**WARNING: total cash is less than the investment you want to use, please check!')
		return

	print('calculate the allocation for each stock...')
	stockbook = prepare(quota, g_stocks)

	print(stockbook)

	# process the orders
	process(trader, quota, stockbook)
Beispiel #21
0
 def __init__(self, logger, **kwargs):
     TraderBase.__init__(self)
     self._logger = logger
     self._client = easytrader.use('yh', debug=kwargs.get('debug', False))
     self.user = kwargs.get('user', '')
     self.password = kwargs.get('password', '')
     self._client.prepare(user=self.user, password=self.password)
Beispiel #22
0
def autoGfIpo(securityID):	
	user = easytrader.use('gf',debug=False)
	user.prepare('u:\gf.json')
	marketValue = user.balance['data'][0]['market_value']
	enableBalance = user.balance['data'][0]['enable_balance']
	total = float(marketValue) + float(enableBalance)
	msg = 'gf, '+ marketValue +', '+ enableBalance + ', ' + str(total) + ', ' + datetime.now().date().isoformat()
	ipo_data = helpers.get_today_ipo_data()
	ipo_limit = user.today_ipo_limit()
	Dic_amount = {'上海':0.0,'深圳':0.0}
	for limit in ipo_limit['data']:
		Dic_amount[limit['exchange_type_dict']] = float(limit['enable_amount'])
		
	rst = '';
	for data in ipo_data:
		apply_code = data['apply_code']
		price = data['price']
		stock_code = data['stock_code']
		amount = 0
		if 'SZ' in stock_code:
			amount = Dic_amount['深圳']
		if 'SH' in stock_code:
			amount = Dic_amount['上海']
		if amount > 0:
			e = user.buy(apply_code,float(price),amount)
			rst = rst + str(e)
			sleep(0.5)
		
	user.exit()
	return rst
Beispiel #23
0
 def test_login(self):
     # user_str = '3300055265'
     # password_str = '541130'  # bytes.decode(base64.decodebytes(b'123123'))
     user = easytrader.use('gzzq')
     # user.prepare(user='******', password=password_str)
     # user = easytrader.use('hb_client')
     # user.prepare(user=user_str, password=password_str)
     user.prepare(config_path="gzzq.json")
    def test_set_initial_assets(self):
        # default set to 1e6
        xq_user = easytrader.use('xq')
        self.assertEqual(xq_user.multiple, 1e6)

        xq_user = easytrader.use('xq', initial_assets=1000)
        self.assertEqual(xq_user.multiple, 1000)

        # cant low than 1000
        with self.assertRaises(ValueError):
            xq_user = easytrader.use('xq', initial_assets=999)

        # initial_assets must be number
        cases = [None, '', b'', bool]
        for v in cases:
            with self.assertRaises(TypeError):
                xq_user = easytrader.use('xq', initial_assets=v)
Beispiel #25
0
    def setUpClass(cls):
        # input your test account and password
        cls._ACCOUNT = os.environ.get('EZ_TEST_YH_ACCOUNT') or 'your account'
        cls._PASSWORD = os.environ.get(
            'EZ_TEST_YH_password') or 'your password'

        cls._user = easytrader.use('yh_client')
        cls._user.prepare(user=cls._ACCOUNT, password=cls._PASSWORD)
Beispiel #26
0
    def test_set_initial_assets(self):
        # default set to 1e6
        xq_user = easytrader.use('xq')
        self.assertEqual(xq_user.multiple, 1e6)

        xq_user = easytrader.use('xq', initial_assets=1000)
        self.assertEqual(xq_user.multiple, 1000)

        # cant low than 1000
        with self.assertRaises(ValueError):
            xq_user = easytrader.use('xq', initial_assets=999)

        # initial_assets must be number
        cases = [None, '', b'', bool]
        for v in cases:
            with self.assertRaises(TypeError):
                xq_user = easytrader.use('xq', initial_assets=v)
Beispiel #27
0
def htLogin():
    # 登录 easytrader 支持的用户
    user = easytrader.use('ht_client')
    # print("user是:", user)
    user.prepare(user='******',
                 password='******',
                 comm_password="******")
    return user
Beispiel #28
0
 def __init__(self, p):
     super(WBTrade, self).__init__()
     # 固定部分
     self.wb = easytrader.use('wb')
     self.logger = get_logger(COLLECTION)
     self.db = MongoDB(DB_NAME)
     self.p_path = os.path.dirname(os.path.abspath(__file__)) + '/config/'+p+'.json'
     self.portfolio_list = helpers.file2dict(self.p_path)
Beispiel #29
0
 def __init__(self,
              user="******",
              password="******",
              zuhe="ZH995042"):
     self.user = easytrader.use('xq')
     self.user.prepare(user=user, password=password, portfolio_code=zuhe)
     self.buylist = []
     self.limitnum = 20
Beispiel #30
0
    def __init__(self,
                 broker=None,
                 need_data=None,
                 quotation_engines=None,
                 log_handler=DefaultLogHandler(),
                 tzinfo=None):
        """初始化事件 / 行情 引擎并启动事件引擎
        """
        self.log = log_handler
        self.broker = broker

        # 登录账户
        if (broker is not None) and (need_data is not None):
            self.user = easytrader.use(broker)
            need_data_file = pathlib.Path(need_data)
            if need_data_file.exists():
                self.user.prepare(need_data)
                with open(ACCOUNT_OBJECT_FILE, 'wb') as f:
                    dill.dump(self.user, f)
            else:
                log_handler.warn("券商账号信息文件 %s 不存在, easytrader 将不可用" %
                                 need_data)
        else:
            self.user = None
            self.log.info('选择了无交易模式')

        self.event_engine = EventEngine()
        self.clock_engine = ClockEngine(self.event_engine, tzinfo)

        quotation_engines = quotation_engines or [DefaultQuotationEngine]

        if type(quotation_engines) != list:
            quotation_engines = [quotation_engines]
        self.quotation_engines = []
        for quotation_engine in quotation_engines:
            self.quotation_engines.append(
                quotation_engine(self.event_engine, self.clock_engine))

        # 保存读取的策略类
        self.strategies = OrderedDict()
        self.strategy_list = list()

        # 是否要动态重载策略
        self.is_watch_strategy = False
        # 修改时间缓存
        self._cache = {}
        # # 文件进程映射
        # self._process_map = {}
        # 文件模块映射
        self._modules = {}
        self._names = None
        # 加载锁
        self.lock = Lock()
        # 加载线程
        self._watch_thread = Thread(target=self._load_strategy,
                                    name="MainEngine.watch_reload_strategy")

        self.log.info('启动主引擎')
Beispiel #31
0
    def setUpClass(cls):
        import easytrader

        # input your test account and password
        cls._ACCOUNT = os.environ.get("EZ_TEST_YH_ACCOUNT") or account
        cls._PASSWORD = (os.environ.get("EZ_TEST_YH_PASSWORD") or password)

        cls._user = easytrader.use("gj_client")
        cls._user.prepare(user=cls._ACCOUNT, password=cls._PASSWORD)
Beispiel #32
0
    def test_login(self):
        _ACCOUNT = os.environ.get("EZ_TEST_YH_ACCOUNT") or account
        _PASSWORD = (os.environ.get("EZ_TEST_YH_PASSWORD") or password)

        self._user = easytrader.use("ct_client")
        self._user.prepare(user=_ACCOUNT, password=_PASSWORD)
        time.sleep(3)
        result = self._user.balance
        print(result)
Beispiel #33
0
def get_push_stocks(additional_stocks=[]):
    broker = 'yh'
    need_data = 'yh.json'
    user = easytrader.use('yh')
    user.prepare('yh.json')
    holding_stocks = user.position['证券代码'].values.tolist()
    #print('holding_stocks',holding_stocks)
    init_push_stocks = list(set(holding_stocks) | set(additional_stocks))
    return init_push_stocks
Beispiel #34
0
def get_push_stocks(additional_stocks=[]):
    broker = 'yh'
    need_data = 'yh.json'
    user = easytrader.use('yh')
    user.prepare('yh.json')
    holding_stocks = user.position['证券代码'].values.tolist()
    #print('holding_stocks',holding_stocks)
    init_push_stocks = list(set( holding_stocks) | set(additional_stocks))
    return init_push_stocks
Beispiel #35
0
    def __init__(self):
        self.user = easytrader.use('yh')
        self.user.prepare('../easytrader/yh.json')

        print('position', self.user.position)
        print('entrust', self.user.entrust)
        print('balance', self.user.balance)

        self.sell()
Beispiel #36
0
    def __init__(self):
        app = QtWidgets.QApplication(sys.argv)
        main_window = QtWidgets.QMainWindow()
        self.ui = ui.Ui_ant()
        self.ui.setupUi(main_window)

        convert_bond_raw_path = r"C:\quanttime\src\convertbond\raw_data.csv"
        self.ui.lineEdit.setText(convert_bond_raw_path)
        convert_bond_raw_after_process_path = r"C:\quanttime\src\convertbond\raw_data_after_process.csv"
        self.ui.lineEdit_2.setText(convert_bond_raw_after_process_path)

        # 生信息转换pushbutton的signal连接
        self.ui.pushButton.clicked.connect(
            self.process_convertbond_raw_basic_info)

        # 显示可转债基本信息表pushbotton的signal连接
        self.ui.pushButton_2.clicked.connect(self.display_convert_basic_info)

        # 可转债实时折溢价情况刷新pushbutton的signal连接
        self.ui.pushButton_4.clicked.connect(self.display_premium)

        # 更新是否到转股期到csv表格
        self.ui.pushButton_3.clicked.connect(self.update_bond2stock_period)

        # 重点监测可转债checkboxsignal
        self.ui.checkBox.stateChanged.connect(
            self.select_or_cancel_all_bond_status)

        # 转债的基本信息,从本地csv中读取的信息
        self.df_convertbond_basic_info = pd.DataFrame()

        # 转债基本信息以及转债实时行情,股票实时行情
        self.df_bond_total = pd.DataFrame()

        # 点击premium表的单元格,发射信号,生成转债与正股的2档价量信息
        self.ui.tableWidget_2.cellClicked.connect(self.display_buy_sell_info)

        # 点击可转债折溢价交易按钮触发交易信号
        self.ui.pushButton_5.clicked.connect(self.trade_convert_bond_premium)

        # tushare connect context
        token = "17e7755e254f02cc312b8b7e22ded9a308924147f8546fdfbe653ba1"
        ts.set_token(token)
        self.cons = ts.get_apis()
        # ts 授权
        self.pro = ts.pro_api()

        # 注册交易接口
        self.user = easytrader.use('ht_client')
        # self.user.prepare(user='******', password='******', comm_password='******')
        self.user.prepare(user='******',
                          password='******',
                          comm_password='******')

        main_window.show()
        sys.exit(app.exec_())
Beispiel #37
0
    def __init__(self):
        self.today = datetime.date.today().strftime('%Y-%m-%d')

        # self.stock_candidates = self.get_candidates()
        # self.stock_candidates = self.get_candidates()
        self.logger = self.llogger('auto_trader_{}'.format(self.today))
        self.logger.info('程序启动')
        self.user = easytrader.use('gj_client')
        # self.user = easytrader.use('ths')
        self.user.prepare('user.json')
    def setUpClass(cls):
        if 'yh' not in TEST_CLIENTS:
            return

        # input your test account and password
        cls._ACCOUNT = os.environ.get('EZ_TEST_YH_ACCOUNT') or 'your account'
        cls._PASSWORD = os.environ.get('EZ_TEST_YH_password') or 'your password'

        cls._user = easytrader.use('yh_client')
        cls._user.prepare(user=cls._ACCOUNT, password=cls._PASSWORD)
Beispiel #39
0
 def __init__(self,
              user="******",
              password="******",
              zuhe="ZH1008383"):
     self.user = easytrader.use('xq')
     self.user.prepare(user=user, password=password, portfolio_code=zuhe)
     self.buylist = []
     self.selllist = []
     self.limitnum = 20
     self.m = MongoDB()
Beispiel #40
0
def init():
    user = easytrader.use('ht_client')
    user.prepare('C:/codes/easytrader/account.json')
    user.refresh()
    ipo_data = helpers.get_today_ipo_data()
    print(ipo_data)
    # if len(ipo_data) > 0:
    #     ipo_info = user.auto_ipo()
    #     print(ipo_info)
    # balance, position = account(user)
    return (user)
Beispiel #41
0
 def __init__(self):
     self.user = easytrader.use('yh_client')
     self.user.prepare(yh_client_file_url)
     self.current_record = {}
     self.today_done = {}
     self.opt_dict_init = {
         'b_opt': [],
         's_opt': [],
         'usable_balance': 0,
         'has_flashed_flag': True
     }
Beispiel #42
0
    def setUpClass(cls):
        import easytrader

        if "yh" not in TEST_CLIENTS:
            return

        # input your test account and password
        cls._ACCOUNT = os.environ.get("EZ_TEST_YH_ACCOUNT") or "your account"
        cls._PASSWORD = os.environ.get("EZ_TEST_YH_PASSWORD") or "your password"

        cls._user = easytrader.use("yh_client")
        cls._user.prepare(user=cls._ACCOUNT, password=cls._PASSWORD)
Beispiel #43
0
    def setUpClass(cls):
        import easytrader
        if 'ht' not in TEST_CLIENTS:
            return

        # input your test account and password
        cls._ACCOUNT = os.environ.get('EZ_TEST_HT_ACCOUNT') or 'your account'
        cls._PASSWORD = os.environ.get('EZ_TEST_HT_password') or 'your password'
        cls._COMM_PASSWORD = os.environ.get('EZ_TEST_HT_comm_password') or 'your comm password'

        cls._user = easytrader.use('ht_client')
        cls._user.prepare(user=cls._ACCOUNT, password=cls._PASSWORD, comm_password=cls._COMM_PASSWORD)
    def test_gf_check_account_live(self):
        user = easytrader.use('gf')

        test_data = None
        with self.assertRaises(easytrader.webtrader.NotLoginError):
            user.check_account_live(test_data)
        self.assertFalse(user.heart_active)

        test_data = {'success': False, 'data': [{}], 'total': 1}
        with self.assertRaises(easytrader.webtrader.NotLoginError):
            user.check_account_live(test_data)
        self.assertFalse(user.heart_active)
Beispiel #45
0
    def test_ht_fix_error_data(self):
        user = easytrader.use("ht")
        test_data = {"cssweb_code": "error", "cssweb_type": "GET_STOCK_POSITON"}

        return_data = user.fix_error_data(test_data)
        self.assertEqual(test_data, return_data)

        test_data = [{"stock_code": "162411", "entrust_bs": "2"}, {"no_use_index": "hello"}]

        normal_return_data = [{"stock_code": "162411", "entrust_bs": "2"}]

        return_data = user.fix_error_data(test_data)
        self.assertEqual(return_data, normal_return_data)
Beispiel #46
0
    def test_format_response_data_type(self):
        user = easytrader.use('ht')

        test_data = [{
            'current_amount': '187.00',
            'current_balance': '200.03',
            'stock_code' : '000001'
        }]
        result = user.format_response_data_type(test_data)

        self.assertIs(type(result[0]['current_amount']), int)
        self.assertIs(type(result[0]['current_balance']), float)
        self.assertIs(type(result[0]['stock_code']), str)
Beispiel #47
0
    def __init__(self, broker=None, need_data=None, quotation_engines=None,
                 log_handler=DefaultLogHandler(), tzinfo=None):
        """初始化事件 / 行情 引擎并启动事件引擎
        """
        self.log = log_handler
        self.broker = broker

        # 登录账户
        if (broker is not None) and (need_data is not None):
            self.user = easytrader.use(broker)
            need_data_file = pathlib.Path(need_data)
            if need_data_file.exists():
                self.user.prepare(need_data)
                with open(ACCOUNT_OBJECT_FILE, 'wb') as f:
                    dill.dump(self.user, f)
            else:
                log_handler.warn("券商账号信息文件 %s 不存在, easytrader 将不可用" % need_data)
        else:
            self.user = None
            self.log.info('选择了无交易模式')

        self.event_engine = EventEngine()
        self.clock_engine = ClockEngine(self.event_engine, tzinfo)

        quotation_engines = quotation_engines or [DefaultQuotationEngine]

        if type(quotation_engines) != list:
            quotation_engines = [quotation_engines]
        self.quotation_engines = []
        for quotation_engine in quotation_engines:
            self.quotation_engines.append(quotation_engine(self.event_engine, self.clock_engine))

        # 保存读取的策略类
        self.strategies = OrderedDict()
        self.strategy_list = list()

        # 是否要动态重载策略
        self.is_watch_strategy = False
        # 修改时间缓存
        self._cache = {}
        # # 文件进程映射
        # self._process_map = {}
        # 文件模块映射
        self._modules = {}
        self._names = None
        # 加载锁
        self.lock = Lock()
        # 加载线程
        self._watch_thread = Thread(target=self._load_strategy, name="MainEngine.watch_reload_strategy")

        self.log.info('启动主引擎')
Beispiel #48
0
    def setUpClass(cls):
        import easytrader

        if "yh" not in TEST_CLIENTS:
            return

        # input your test account and password
        cls._ACCOUNT = os.environ.get("EZ_TEST_YH_ACCOUNT") or "your account"
        cls._PASSWORD = (
            os.environ.get("EZ_TEST_YH_PASSWORD") or "your password"
        )

        cls._user = easytrader.use("yh_client")
        cls._user.prepare(user=cls._ACCOUNT, password=cls._PASSWORD)
Beispiel #49
0
 def __new__(cls, account_code):
     instance = cls.INSTANCES[account_code] if account_code in cls.INSTANCES else None
     
     if instance is None:
         instance = super(Account,cls).__new__(cls)
         instance.logger = ahelper.get_custom_logger('account.%s' % account_code)
         if not Config.IS_TEST:
             instance.user = easytrader.use('ht', debug=False)
             instance.user.prepare(ahelper.get_config_path('%s.json' % account_code))
             instance.quotation_server = easyquotation.use("lf")
         cls.INSTANCES[account_code] = instance
         instance.logger.info("initialized Account(%s)", account_code)
         
     return instance
Beispiel #50
0
    def __init__(self):
        self.today = datetime.date.today().strftime('%Y-%m-%d')
        self.engine = get_engine('db_stock', True)

        self.stock_candidates = self.get_candidates()
        # self.stock_candidates = self.get_candidates()
        self.logger = self.llogger('auto_trader_{}'.format(self.today))
        self.logger.info('程序启动')
        input('请运行下单程序,按Enter\n')
        self.user = easytrader.use('ths')
        # self.user.prepare('user.json')
        self.user.connect(PROGRAM_PATH)
        # self.position = self.get_position()
        self.blacklist_bond = self.get_blacklist()
        self.q=easyquotation.use('qq')
Beispiel #51
0
 def __init__(self):
     self.xq = easytrader.use('xq')
     self.xq.prepare('config/xq3.json')
     self.xq.set_attr("portfolio_code", "ZH776826")
     self.logger = get_logger(HISTORY_OPERATION_XQ)
     self.db_xq = MongoDB(XUEQIU_DB_NAME)
     # self.db_ib = MongoDB(IB_DB_NAME)
     self.last_trade_time = get_trade_date_series("US")
     self.trade_time = get_date_now("US")
     self.callback = IBWrapper()
     self.ibcontract = IBcontract()
     self.ibcontract.secType = "STK"
     self.ibcontract.exchange = "SMART"
     self.ibcontract.currency = "USD"
     self.client = IBclient(self.callback)
     self.position_ib = PorfolioPosition(IB_DB_NAME, IB_POSITION)
Beispiel #52
0
 def __init__(self, p):
     # 固定部分
     self.xq = easytrader.use('xq')
     self.xq.prepare('config/xq'+p+'.json')
     self.xq.set_attr("portfolio_code", "ZH776826")
     self.logger = get_logger(COLLECTION)
     self.db = MongoDB(XUEQIU_DB_NAME)
     self.email = Email()
     self.client = client(host="10.104.236.87")
     self.p_path = os.path.dirname(os.path.abspath(__file__)) + '/config/'+p+'.json'
     self.portfolio_list = helpers.file2dict(self.p_path)
     # 每日更新
     self.last_trade_time = get_trade_date_series("CN")
     self.trade_time = get_date_now("CN")
     self.is_update_stocks = False
     self.all_stocks_data = None
Beispiel #53
0
    def __init__(self, broker, need_data='me.json'):
        """初始化事件 / 行情 引擎并启动事件引擎
        """
        self.user = easytrader.use(broker)
        self.user.prepare(need_data)

        self.event_engine = EventEngine()
        self.quotation_engine = Quotation(self.event_engine)
        self.clock_engine = ClockEngine(self.event_engine)

        self.event_engine.register(EventType.TIMER, self.second_click)

        # 保存读取的策略类
        self.strategies = OrderedDict()
        self.process_list = list()

        print('启动主引擎')
Beispiel #54
0
def main(prepare, use, do, get, params):
    if get is not None:
        do = get
    if prepare is not None and use in ['ht', 'yjb']:
        user = easytrader.use(use)
        user.prepare(prepare)
        with open(ACCOUNT_OBJECT_FILE, 'wb') as f:
            dill.dump(user, f)
    if do is not None:
        with open(ACCOUNT_OBJECT_FILE, 'rb') as f:
            user = dill.load(f)

        if len(params) > 0:
            result = getattr(user, do)(*params)
        else:
            result = getattr(user, do)

        json_result = json.dumps(result)
        click.echo(json_result)
Beispiel #55
0
def main(prepare, use, do, get, params, debug):
    if get is not None:
        do = get
    if prepare is not None and use in ['ht', 'yjb', 'yh', 'gf', 'xq']:
        user = easytrader.use(use, debug)
        user.prepare(prepare)
        with open(ACCOUNT_OBJECT_FILE, 'wb') as f:
            dill.dump(user, f)
    if do is not None:
        with open(ACCOUNT_OBJECT_FILE, 'rb') as f:
            user = dill.load(f)

        if get is not None:
            result = getattr(user, do)
        else:
            result = getattr(user, do)(*params)

        json_result = json.dumps(result, indent=4, ensure_ascii=False, sort_keys=True)
        click.echo(json_result)
Beispiel #56
0
def main():

	#stock account
	trader = easytrader.use('ht', debug=False)
	trader.config['entrust']['cssweb_type'] = 'GET_TODAY_ENTRUST'
	#quotation
	quota = easyquotation.use('sina')

	print('login huatai system......')
	trader.prepare('ht.json')
	print('login successfully')

	show_balance(trader.balance[0])

	print('collect the stocks needed be sold')
	stockbook = prepare(trader, g_stocks)

	# process the orders
	process(trader, quota, stockbook)
Beispiel #57
0
    def __get_user_info_from_stock_seller(self, name, stock_seller):
        user = easytrader.use(stock_seller)
        cfg_file = self.__get_user_cfg_file(name) 

        try:
            print cfg_file
            user.prepare(cfg_file)
            user.login()
        except Exception as e:
            print e
            print "login stock seller failed"
            _logger.exception("User login failed")
            return None, None

        _logger.debug("%s login success" % name)

        balance = user.get_balance()
        position = user.get_position()

        return balance, position    
Beispiel #58
0
    def test_ht_fix_error_data(self):
        user = easytrader.use('ht')
        test_data = {
            'cssweb_code': 'error',
            'cssweb_type': 'GET_STOCK_POSITON'
        }

        return_data = user.fix_error_data(test_data)
        self.assertEqual(test_data, return_data)

        test_data = [{
            'stock_code': '162411',
            'entrust_bs': '2'},
            {'no_use_index': 'hello'}]

        normal_return_data = [{
            'stock_code': '162411',
            'entrust_bs': '2'}]

        return_data = user.fix_error_data(test_data)
        self.assertEqual(return_data, normal_return_data)
Beispiel #59
0
 def __init__(self):
     self.user = easytrader.use(PLATFORM)
     self.user.prepare(CONFIG_FILE)
     self.holding = {i['stock_code'][2:]:i for i in self.user.position}
     self.balance = self.user.balance[0]
     self.enable_balance = self.balance['enable_balance']
Beispiel #60
0
            if now >= (15, 2, 0):
                account_amount = balance[0]['asset_balance']
                market_value = balance[0]['market_value']
                MASSAGE = '%s,%f,%f,%d,\n' %(stop_time, account_amount, market_value, account_flag.read_flag())
                f = open(filep, 'a')
                f.write(MASSAGE)
                f.close()
                break
            time.sleep(10)
        except:
            pass




user = et.use('ht')
user.prepare('/data/pyquant/ht.json')
user.keepalive()

account_flag = flag.flag()
limit = zxb_limit.zxb_limit(-2.31)
#添加trade
if ed.is_tradetime_now():
    file_name = '/home/way/signal/chicang'
    file_name1 = '/home/way/signal/zhenfu'
#        with open(file_name) as f:
#            yiyue = str(f.readlines()[0])

    m = multiprocessing.Process(target=account_info,args=(account_flag,))
    m.start()
    if account_flag.read_flag() == 2: