예제 #1
0
    def post(self):
        action = self.get_argument('action')
        if action == 'restart_all':

            for acc in self.dbclient.account.find({'status': 500}):
                self.dbclient.account.update_one({'_id': acc['_id']},
                                                 {'$set': {
                                                     'status': 100
                                                 }})
        elif action == 'kill':
            tradetype = self.get_argument('type', 'sim')
            if tradetype == 'sim':
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            else:
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            p.pub(json.dumps({'topic': 'kill'}),
                  routing_key=self.get_argument('account_cookie'))
        elif action == 'killall':
            for acc in self.dbclient.account.find({'status': 200}):
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
                print(acc['account_cookie'])
                p.pub(json.dumps({'topic': 'kill'}),
                      routing_key=acc['account_cookie'])
예제 #2
0
    def post(self):
        client = pymongo.MongoClient().QAREALTIME
        action = self.get_argument('action')
        if action == 'restart_all':

            for acc in client.account.find({'status': 500}):
                client.account.update_one({'_id': acc['_id']},
                                          {'$set': {
                                              'status': 100
                                          }})
        elif action == 'kill':
            tradetype = self.get_argument('type', 'sim')
            if tradetype == 'sim':
                p = producer.publisher_routing(user=trade_server_user,
                                               password=trade_server_password,
                                               host=simtrade_server_ip,
                                               exchange='QAORDER_ROUTER')
            else:
                p = producer.publisher_routing(user=trade_server_user,
                                               password=trade_server_password,
                                               host=trade_server_ip,
                                               exchange='QAORDER_ROUTER')
            p.pub(json.dumps({'topic': 'kill'}),
                  routing_key=self.get_argument('account_cookie'))
        elif action == 'killall':
            for acc in client.account.find({'status': 200}):
                p = producer.publisher_routing(user=trade_server_user,
                                               password=trade_server_password,
                                               host=simtrade_server_ip,
                                               exchange='QAORDER_ROUTER')
                print(acc['account_cookie'])
                p.pub(json.dumps({'topic': 'kill'}),
                      routing_key=acc['account_cookie'])
예제 #3
0
def debug_pub(exchange, model, routing_key, user, password, host, port,
              content):
    if model == 'fanout':
        publisher(host=host,
                  port=port,
                  user=user,
                  password=password,
                  exchange=exchange).pub(content)
    elif model == 'direct':
        print(routing_key)
        publisher_routing(host=host,
                          port=port,
                          user=user,
                          password=password,
                          exchange=exchange,
                          routing_key=routing_key).pub(content,
                                                       routing_key=routing_key)
    elif model == 'topic':
        publisher_topic(host=host,
                        port=port,
                        user=user,
                        password=password,
                        exchange=exchange,
                        routing_key=routing_key).pub(content,
                                                     routing_key=routing_key)
예제 #4
0
    def _debug_sim(self):
        self.running_mode = 'sim'

        self._old_data = QA.QA_fetch_stock_min(self.code, QA.QA_util_get_last_day(
            QA.QA_util_get_real_date(str(datetime.date.today()))), str(datetime.datetime.now()), format='pd', frequence=self.frequence).set_index(['datetime', 'code'])

        self._old_data = self._old_data.loc[:, [
            'open', 'high', 'low', 'close', 'volume']]

        self.database = pymongo.MongoClient(mongo_ip).QAREALTIME

        self.client = self.database.account
        self.subscriber_client = self.database.subscribe

        self.acc = QIFI_Account(
            username=self.strategy_id, password=self.strategy_id, trade_host=mongo_ip)
        self.acc.initial()

        self.pub = publisher_routing(exchange='QAORDER_ROUTER', host=self.trade_host,
                                     port=self.trade_port, user=self.trade_user, password=self.trade_password)

        self.subscribe_data(self.code, self.frequence, self.data_host,
                            self.data_port, self.data_user, self.data_password)

        self.database.strategy_schedule.job_control.update(
            {'strategy_id': self.strategy_id},
            {'strategy_id': self.strategy_id, 'taskid': self.taskid,
             'filepath': os.path.abspath(__file__), 'status': 200}, upsert=True)

        # threading.Thread(target=, daemon=True).start()
        self.sub.start()
예제 #5
0
    def _debug_sim(self):

        self.running_mode = 'sim'

        if self.frequence.endswith('min'):
            self._old_data = QA.QA_fetch_get_future_min('tdx', self.code.upper(), QA.QA_util_get_last_day(
                QA.QA_util_get_real_date(str(datetime.date.today()))), str(datetime.datetime.now()), self.frequence)[:-1].set_index(['datetime', 'code'])
            self._old_data = self._old_data.assign(volume=self._old_data.trade).loc[:, [
                'open', 'high', 'low', 'close', 'volume']]
        else:
            self._old_data = pd.DataFrame()

        self.database = pymongo.MongoClient(mongo_ip).QAREALTIME

        self.client = self.database.account
        self.subscriber_client = self.database.subscribe

        self.acc = QIFI_Account(
            username=self.strategy_id, password=self.strategy_id, trade_host=mongo_ip, init_cash=self.init_cash)
        self.acc.initial()

        self.pub = publisher_routing(exchange='QAORDER_ROUTER', host=self.trade_host,
                                     port=self.trade_port, user=self.trade_user, password=self.trade_password)

        self.subscribe_data(self.code.lower(), self.frequence, self.data_host,
                            self.data_port, self.data_user, self.data_password)

        self.database.strategy_schedule.job_control.update(
            {'strategy_id': self.strategy_id},
            {'strategy_id': self.strategy_id, 'taskid': self.taskid,
             'filepath': os.path.abspath(__file__), 'status': 200}, upsert=True)
예제 #6
0
    def __init__(self):
        super().__init__(name='qasubclient')

        self.req = publisher_routing(exchange='QARealtime_Market',
                                     routing_key='stock')
        self.last_ab = pd.DataFrame()
        self.sub = subscriber(exchange='stocktransaction')
        self.sub.callback = self.callback
예제 #7
0
 def __init__(self, simid, realid, realamount=1):
     self.sub = subscriber_routing(exchange='QAORDER_ROUTER',
                                   host=eventmq_ip,
                                   routing_key=simid)
     self.pub = publisher_routing(exchange='QAORDER_ROUTER',
                                  host=eventmq_ip,
                                  routing_key=realid)
     self.realamount = realamount
     self.realid = realid
     self.simid = simid
예제 #8
0
 def __init__(self, name, app=None):
     super().__init__(name, app)
     self.tick_database_name = "tick"
     self.bar_base_name = "bar"
     self.shared_data = {}
     self.created = False
     self.recover = False
     self.move = []
     self.mimi = set()
     self.pub = publisher_routing(exchange='CTPX', routing_key='')
예제 #9
0
 def __init__(self, name, app=None, model='ctpx'):
     super().__init__(name, app)
     if model == 'ctpx':
         self.pub = publisher_routing(host=eventmq_ip,
                                      exchange='CTPX',
                                      routing_key='')
     else:
         self.pub = publisher_topic(host=eventmq_ip,
                                    exchange='CTPPRO',
                                    routing_key='')
예제 #10
0
    def __init__(self, code, date, price, interval):
        self.code = code
        self.date = date
        self.price = price
        self.interval = interval

        self.pub = publisher_routing(exchange='tick',
                                     routing_key=code,
                                     host=eventmq_ip,
                                     user='******',
                                     password='******')
예제 #11
0
    def _debug_sim(self):
        self.running_mode = 'sim'

        #QA_SU_save_huobi_min(frequency= self.frequence, fetch_range= self.code)

        frequence_int = int(re.findall("\d+", self.frequence)[0])
        self.frequenceInt = frequence_int
        start = (datetime.datetime.now() + datetime.timedelta(
            minutes=-500 * frequence_int)).strftime("%Y-%m-%d %H:%M:%S")
        end = (datetime.datetime.now() + datetime.timedelta(
            minutes=-frequence_int)).strftime("%Y-%m-%d %H:%M:%S")
        code_list = [huobi_SYMBOL.format(x) for x in self.code]
        self._old_data = QA.QA_fetch_cryptocurrency_min(
            code_list, start, end, format='pd',
            frequence=self.frequence).set_index(['datetime', 'code'])

        #print(self._old_data)
        self._old_data = self._old_data.loc[:, [
            'open', 'high', 'low', 'close', 'volume'
        ]]

        self.database = pymongo.MongoClient(mongo_ip).QAREALTIME

        self.client = self.database.account
        self.subscriber_client = self.database.subscribe
        self.acc = QIFI_Account(username=self.strategy_id,
                                password=self.strategy_id,
                                trade_host=mongo_ip)
        self.acc.initial()
        self.pub = publisher_routing(exchange='QAORDER_ROUTER',
                                     host=self.trade_host,
                                     port=self.trade_port,
                                     user=self.trade_user,
                                     password=self.trade_password)
        '''
        self.subscribe_data(self.code, self.frequence, self.data_host,
                            self.data_port, self.data_user, self.data_password)
        '''

        self.database.strategy_schedule.job_control.update(
            {'strategy_id': self.strategy_id}, {
                'strategy_id': self.strategy_id,
                'taskid': self.taskid,
                'filepath': os.path.abspath(__file__),
                'status': 200
            },
            upsert=True)

        # threading.Thread(target=, daemon=True).start()
        #print(self.subscribe_data)
        #self.sub.start()
        #self.subscriber.start()
        self.callback(1, 2, 3, 4)
예제 #12
0
    def __init__(self, account_cookie, password, wsuri, broker_name='simnow', portfolio='default',
                 eventmq_ip=eventmq_ip, eventmq_port=eventmq_port, sig=True, ping_gap=1,
                 bank_password=None, capital_password=None, appid=None,
                 if_restart=True, taskid=None, database_ip = mongo_ip):

        super().__init__(name='QATRADER_{}'.format(account_cookie))
        self.account_cookie = account_cookie
        self.password = password
        self.broker_name = broker_name
        self.wsuri = wsuri
        self.pub = producer.publisher_routing(
            exchange=trade_server_account_exchange, host=eventmq_ip, port=eventmq_port)
        self.ws = self.generate_websocket()
        """几个涉及跟数据库交互的client
        """
        database = pymongo.MongoClient(mongo_ip)
        self.account_client = database.QAREALTIME.account
        self.settle_client = database.QAREALTIME.history
        self.xhistory = database.QAREALTIME.hisaccount
        self.orders_client = database.QAREALTIME.orders
        self.portfolio = portfolio
        self.connection = True
        self.message = {'password': password, 'wsuri': wsuri, 'broker_name': broker_name, 'portfolio': portfolio, 'taskid': taskid, 'updatetime': str(
            datetime.datetime.now()), 'accounts': {}, 'orders': {}, 'positions': {}, 'trades': {}, 'banks': {}, 'transfers': {}, 'event': {},  'eventmq_ip': eventmq_ip,
            'ping_gap': ping_gap, 'account_cookie': account_cookie, 'bank_password': bank_password, 'capital_password': capital_password, 'settlement': {},
            'bankid': 0, 'money': 0, 'investor_name': ''}
        self.last_update_time = datetime.datetime.now()
        self.sig = sig
        self.if_restart = if_restart
        self.ping_gap = ping_gap
        self.bank_password = bank_password
        self.capital_password = capital_password
        self.tempPass = ''
        self.appid = appid

        self.sub = consumer.subscriber_routing(host=eventmq_ip, port=eventmq_port, user=trade_server_user, password=trade_server_password,
                                               exchange=trade_server_order_exchange, routing_key=self.account_cookie)
        self.pub_transaction = producer.publisher_routing(
            host=eventmq_ip, exchange='QATRANSACTION')
        self.sub.callback = self.callback
예제 #13
0
    def post(self):
        action = self.get_argument('action')
        market_type = self.get_argument('market_type')
        code = self.get_argument('code')
        if action == 'new_handler':

            if code not in self.handler.keys():
                if market_type == 'future_cn':
                    self.handler[market_type][code] = QARTC_CtpBeeCollector(
                        code)
                    self.handler[market_type][code].start()
                    self.write({'result': 'success'})
                else:
                    publisher_routing(host=eventmq_ip,
                                      exchange='QARealtime_Market',
                                      routing_key='stock').pub(
                                          json.dumps({
                                              'topic': 'subscribe',
                                              'code': code
                                          }),
                                          routing_key='stock')
                    self.handler[market_type][code] = True
                    self.write({'result': 'success'})

            else:
                self.write({'result': 'already exist'})
        elif action == 'new_resampler':
            frequence = self.get_argument('frequence')
            if (code, frequence) not in self.resampler.keys():
                if market_type == 'future_cn':
                    self.resampler[market_type][(code,
                                                 frequence)] = QARTC_Resampler(
                                                     code, frequence)
                    self.resampler[market_type][(code, frequence)].start()
                    self.write({'result': 'success'})
                else:
                    pass
            else:
                self.write({'result': 'already exist'})
예제 #14
0
    def __init__(self, username, password, model="SIM", broker_name="QAPaperTrading", trade_host=mongo_ip, init_cash=1000000,
                 eventmq_ip=eventmq_ip, eventmq_port=eventmq_port):
        super().__init__(username, password, model, broker_name, trade_host, init_cash)

        self.pub = producer.publisher_routing(
            exchange='qamdgateway', host=eventmq_ip, port=eventmq_port, durable=True)
        self.subrealtime = subscriber_topic(
            host=eventmq_ip, port=eventmq_port, exchange='QASMG', routing_key=username)

        self.ordersub = subscriber_routing(
            host=eventmq_ip, port=eventmq_port, exchange='QAORDER_ROUTER', routing_key=username)

        self.subrealtime.callback = self.realtime_data_callback
        self.ordersub.callback = self.listen_order_callback

        threading.Thread(target=self.subrealtime.start).start()
        threading.Thread(target=self.ordersub.start).start()

        self.pub_acc = producer.publisher_topic(
            exchange='qaStandardAcc', host=eventmq_ip, port=eventmq_port,  durable=True)
예제 #15
0
def qasimstock_sendorder(user, eventmq_ip, eventmq_port, code, price, amount,
                         direction, offset):
    p = producer.publisher_routing(user='******',
                                   password='******',
                                   host=eventmq_ip,
                                   port=eventmq_port,
                                   exchange='QAORDER_ROUTER')

    p.pub(json.dumps({
        'topic': 'sendorder',
        'account_cookie': user,
        'strategy_id': 'test',
        'code': code,
        'price': price,
        'order_direction': direction,
        'order_offset': offset,
        'volume': amount,
        'order_time': str(datetime.datetime.now()),
        'exchange_id': 'test'
    }),
          routing_key=user)
예제 #16
0
def test_send_order(host='127.0.0.1'):
    p = producer.publisher_routing(user='******',
                                   password='******',
                                   host=host,
                                   exchange='QAORDER_ROUTER')

    price = {'rb1905': 4171}
    for acc in ['1010101']:
        for code in price.keys():
            p.pub(json.dumps({
                'topic': 'sendorder',
                'account_cookie': acc,
                'strategy_id': 'test',
                'code': code,
                'price': price[code],
                'order_direction': 'SELL',
                'order_offset': 'OPEN',
                'volume': 1,
                'order_time': str(datetime.datetime.now()),
                'exchange_id': 'SHFE'
            }),
                  routing_key=acc)
예제 #17
0
def test_send_order(host='192.168.2.117'):
    p = producer.publisher_routing(user='******',
                                   password='******',
                                   host=host,
                                   exchange='QAORDER_ROUTER')

    ulist = [{
        'code': '300078',
        'price': 13.25
    }, {
        'code': '601966',
        'price': 19.03
    }, {
        'code': '601163',
        'price': 12.81
    }, {
        'code': '600469',
        'price': 4.93
    }, {
        'code': '000589',
        'price': 3.81
    }, {
        'code': '601500',
        'price': 5.63
    }, {
        'code': '000599',
        'price': 3.78
    }, {
        'code': '600048',
        'price': 13.97
    }, {
        'code': '000002',
        'price': 24.51
    }, {
        'code': '000671',
        'price': 6.39
    }, {
        'code': '600383',
        'price': 12.14
    }, {
        'code': '000961',
        'price': 7.01
    }, {
        'code': '600466',
        'price': 5.76
    }, {
        'code': '600325',
        'price': 6.06
    }, {
        'code': '002146',
        'price': 7.25
    }]
    for acc in ['jf1']:

        for x in ulist:
            p.pub(json.dumps({
                'topic': 'sendorder',
                'account_cookie': acc,
                'strategy_id': 'test',
                'code': x['code'],
                'price': x['price'],
                'order_direction': 'BUY',
                'order_offset': 'OPEN',
                'volume': 100,
                'order_time': str(datetime.datetime.now()),
                'exchange_id': 'SH'
            }),
                  routing_key=acc)
            time.sleep(10)
예제 #18
0
    def get_data(self):
        data = self.get_realtime_concurrent(self.user.subscribed_code)
        print(data)

    def run(self):
        while 1:
            self.get_data()
            import time
            time.sleep(1)


if __name__ == "__main__":
    r = QARTC_Stock('yutiansut', '940809')
    r.subscribe('000001')
    r.subscribe('000002')
    r.start()

    r.subscribe('600010')

    import json
    import time
    time.sleep(2)
    publisher_routing(exchange='QARealtime_Market',
                      routing_key='stock').pub(json.dumps({
                          'topic': 'subscribe',
                          'code': '600012'
                      }),
                                               routing_key='stock')

    r.unsubscribe('000001')
예제 #19
0
 def __init__(self, name, app=None):
     super().__init__(name, app)
     self.pub = publisher_routing(host=eventmq_ip, exchange='CTPX', routing_key='')
예제 #20
0
#!/usr/bin/env python

import QAPUBSUB
import threading

from QAPUBSUB.consumer import subscriber_routing
from QAPUBSUB.producer import publisher_routing

z1 = subscriber_routing(exchange='xx', routing_key='x1')
z2 = subscriber_routing(exchange='xx', routing_key='x2')
z3 = subscriber_routing(exchange='xx', routing_key='x2')

z1.callback = lambda a, b, c, x: print('FROM X1 {}'.format(x))
z2.callback = lambda a, b, c, x: print('FROM X2 {}'.format(x))
z3.callback = lambda a, b, c, x: print('FROM X3 {}'.format(x))
p = publisher_routing(exchange='xx')

threading.Thread(target=z1.start).start()

threading.Thread(target=z2.start).start()
threading.Thread(target=z3.start).start()
p.pub('xxxxx', routing_key='x1')

p.pub('1', routing_key='x2')
"""
在exchange为 xx的mq中


routing_key = x1 ==>  有一个订阅者 z1
routing_key = x2 ==>  有两个订阅者 z2, z3
예제 #21
0
    def post(self):
        action = self.get_argument('action')

        acc = self.get_argument('acc')
        xtime = datetime.datetime.now()

        if acc not in self.event.keys():
            self.event[acc] = {}
        if action not in self.event[acc].keys():
            self.event[acc][action] = []
        if action == 'sendorder':
            price = self.get_argument('price')
            code = self.get_argument('code')
            direction = self.get_argument('direction')
            offset = self.get_argument('offset')
            volume = self.get_argument('volume')
            exchange_id = self.get_argument('exchange')
            accounttrade = self.get_argument('type')
            price = adaptChange(price)
            volume = adaptChange(volume)
            if accounttrade == 'real':
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            else:
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            self.event[acc][action].append({
                'reqesttime': str(xtime),
                'account_cookie': acc,
                'topic': action,
                'strategy_id': 'test',
                'code': code,
                'price': price,
                'order_direction': direction,
                'order_offset': offset,
                'volume': volume,
                'order_time': str(xtime),
                'exchange_id': exchange_id
            })
            p.pub(json.dumps({
                'topic': action,
                'account_cookie': acc,
                'strategy_id': 'test',
                'code': code,
                'price': price,
                'order_direction': direction,
                'order_offset': offset,
                'volume': volume,
                'order_time': str(datetime.datetime.now()),
                'exchange_id': exchange_id
            }),
                  routing_key=acc)
            self.dbclient.event.update_one(
                {
                    'starttime': self.starttime,
                    'account_cookie': acc
                }, {'$set': self.event[acc]},
                upsert=True)
            self.write({
                'status': 200,
                'result': {
                    'topic': action,
                    'account_cookie': acc,
                    'strategy_id': 'test',
                    'code': code,
                    'price': price,
                    'order_direction': direction,
                    'order_offset': offset,
                    'volume': volume,
                    'exchange_id': exchange_id
                }
            })
        elif action == 'cancel_order':
            orderid = self.get_argument('order_id')
            accounttrade = self.get_argument('type')
            if accounttrade == 'real':
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            else:
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            p.pub(json.dumps({
                'topic': action,
                'account_cookie': acc,
                'order_id': orderid
            }),
                  routing_key=acc)
            self.event[acc][action].append({
                'topic': action,
                'reqesttime': str(xtime),
                'account_cookie': acc,
                'order_id': orderid
            })
            self.dbclient.event.update_one(
                {
                    'starttime': self.starttime,
                    'account_cookie': acc
                }, {'$set': self.event[acc]},
                upsert=True)
        elif action == 'transfer':
            #bankid = self.get_argument('bankid')
            # bankpassword = self.get_argument('bankpassword')
            # capitalpassword = self.get_argument('capitalpassword')
            """
            此处需要控制请求:

            1分钟内单账户 不允许 相同金额的出入金

            """

            amount = self.get_argument('amount')
            accounttrade = self.get_argument('type')

            xflag = False
            lastrequest = list(self.event[acc][action])
            # print(lastrequest)
            if len(lastrequest) == 0:
                xflag = True
            else:
                if float(amount) == float(lastrequest[-1]['amount']):
                    if xtime - lastrequest[-1][
                            'reqesttime'] > datetime.timedelta(seconds=60):
                        #print('true for >60')
                        xflag = True
                    else:
                        # print('wrong in 60s')
                        xflag = False
                else:
                    # print(amount)
                    # print(lastrequest[-1]['amount'])
                    # print('true for not equal amount')
                    xflag = True
            if xflag:
                client = self.dbclient.account
                res = client.find_one({'account_cookie': acc})
                if res is not None:
                    bank = res['banks']
                    accounts1 = res['accounts']
                    if len(bank) == 0:
                        self.write({'status': 400, 'result': '没有银行'})
                    else:

                        bankid = self.get_argument('bankid', bank[0]['bankid'])
                        before = bank[bankid]['fetch_amount']
                        if before == -1:
                            self.write({'status': 400, 'result': '查询银行未就绪'})
                        else:

                            if accounttrade == 'real':
                                staticbalance1 = accounts1['pre_balance']
                                p = producer.publisher_routing(
                                    user=eventmq_username,
                                    password=eventmq_password,
                                    host=eventmq_ip,
                                    exchange='QAORDER_ROUTER')
                                p.pub(json.dumps({
                                    'topic': action,
                                    'account_cookie': acc,
                                    'amount': float(amount)
                                }),
                                      routing_key=acc)
                                self.event[acc][action].append({
                                    'topic':
                                    action,
                                    'account_cookie':
                                    acc,
                                    'amount':
                                    float(amount),
                                    'reqesttime':
                                    xtime,
                                })
                                self.dbclient.event.update_one(
                                    {
                                        'starttime': self.starttime,
                                        'account_cookie': acc
                                    }, {'$set': self.event[acc]},
                                    upsert=True)
                                time.sleep(2)
                                p.pub(json.dumps({
                                    'topic': 'query_bank',
                                    'account_cookie': acc,
                                }),
                                      routing_key=acc)

                                time.sleep(2)
                                res2 = client.find_one({'account_cookie': acc})
                                bank2 = res2['banks']
                                accounts2 = res2['accounts']
                                staticbalance2 = accounts2['pre_balance']
                                after = bank2[bankid]['fetch_amount']

                                # print(res2['banks'])

                                if before - after == float(
                                        amount
                                ) or staticbalance1 - staticbalance2 == float(
                                        amount):

                                    self.write({
                                        'status': 200,
                                        'result': float(amount),
                                        'before': before,
                                        'after': after,
                                        'amount': float(amount)
                                    })
                                else:
                                    p.pub(json.dumps({
                                        'topic': 'query_bank',
                                        'account_cookie': acc,
                                    }),
                                          routing_key=acc)
                                    time.sleep(4)
                                    res = client.find_one(
                                        {'account_cookie': acc})
                                    bank = res['banks']
                                    after = bank[bankid]['fetch_amount']
                                    accounts2 = res2['accounts']
                                    staticbalance2 = accounts2['pre_balance']
                                    # print(res['banks'])
                                    if before - after == float(
                                            amount
                                    ) or staticbalance1 - staticbalance2 == float(
                                            amount):
                                        self.write({
                                            'status': 200,
                                            'result': float(amount),
                                            'before': before,
                                            'after': after,
                                            'amount': float(amount)
                                        })
                                    else:
                                        self.write({
                                            'status': 500,
                                            'result': '等待时间过长',
                                            'before': before,
                                            'after': after,
                                            'amount': float(amount)
                                        })

                            else:
                                self.write({
                                    'status': 400,
                                    'result': '请使用实盘账户字段 real'
                                })
            else:
                self.write({
                    'status':
                    400,
                    'result':
                    '1min重复提交, 请于下次 {} 提交'.format(lastrequest[-1]['datetime'] +
                                                  datetime.timedelta(60))
                })

        elif action == 'query_bank':
            accounttrade = self.get_argument('type')
            bankid = self.get_argument('bankid', False)
            if accounttrade == 'real':
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            else:
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            self.event[acc][action].append({
                'topic': action,
                'account_cookie': acc,
                'lastrequesttime': xtime
            })
            print(self.event)
            self.dbclient.event.update_one(
                {
                    'starttime': self.starttime,
                    'account_cookie': acc
                }, {'$set': self.event[acc]},
                upsert=True)
            if bankid:
                p.pub(json.dumps({
                    'topic': action,
                    'account_cookie': acc,
                    'bankid': bankid
                }),
                      routing_key=acc)
            else:
                p.pub(json.dumps({
                    'topic': action,
                    'account_cookie': acc,
                }),
                      routing_key=acc)
        elif action == 'change_password':
            newpw = self.get_argument('newpassword')
            accounttrade = self.get_argument('type')
            if accounttrade == 'real':
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')
            else:
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')

            p.pub(json.dumps({
                'topic': action,
                'newPass': newpw
            }),
                  routing_key=acc)
            self.event[acc][action].append({
                'topic': action,
                'account_cookie': acc,
                'lastrequesttime': xtime,
                'newPass': newpw
            })
            self.dbclient.event.update_one(
                {
                    'starttime': self.starttime,
                    'account_cookie': acc
                }, {'$set': self.event[acc]},
                upsert=True)

        elif action == 'query_settlement':
            dates = self.get_argument('day')
            res = self.dbclient.account.find_one({'account_cookie': acc}, {
                'settlement': 1,
                '_id': 0
            })['settlement']
            if dates in res.keys():
                self.write({'status': 200, 'result': res[dates]})
            else:
                p = producer.publisher_routing(user=eventmq_username,
                                               password=eventmq_password,
                                               host=eventmq_ip,
                                               exchange='QAORDER_ROUTER')

                p.pub(json.dumps({
                    'topic': action,
                    'day': dates
                }),
                      routing_key=acc)
                self.event[acc][action].append({'topic': action, 'day': dates})
                self.dbclient.event.update_one(
                    {
                        'starttime': self.starttime,
                        'account_cookie': acc
                    }, {'$set': self.event[acc]},
                    upsert=True)
                time.sleep(2)
                res = self.dbclient.account.find_one({'account_cookie': acc}, {
                    'settlement': 1,
                    '_id': 0
                })['settlement']
                if dates in res.keys():
                    self.write({'status': 200, 'result': res[dates]})
                else:
                    self.write({'status': 400, 'result': '尚未就绪'})
예제 #22
0
from QAPUBSUB import producer

import json

c = producer.publisher_routing(exchange='qamdgateway',
                               host='192.168.2.117',
                               durable=True)

c.pub(json.dumps({
    'account_cookie': 'aa',
    'code': '000001'
}),
      routing_key='All')