Exemple #1
0
def order(trade_account, type_, symbol, price, quantity):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    if type_ == 'buy':
        r = t.buy(symbol, price, quantity)
    else:
        r = t.sell(symbol, price, quantity)
    return r, t.last_error
Exemple #2
0
def order(trade_account, type_, symbol, price, quantity):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    if type_ == 'buy':
        r = t.buy(symbol, price, quantity)
    else:
        r = t.sell(symbol, price, quantity)
    return r, t.last_error
Exemple #3
0
def quote_detail(trade_account, symbol):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    qd = t.quote_detail(symbol)
    ci = t.list_collection(symbol)[0]
    qd['highest'] = ci['highest']
    qd['lowest'] = ci['lowest']
    return qd
Exemple #4
0
def quote_detail(trade_account, symbol):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    qd = t.quote_detail(symbol)
    ci = t.list_collection(symbol)[0]
    qd['highest'] = ci['highest']
    qd['lowest'] = ci['lowest']
    return qd
Exemple #5
0
def transfer(trade_account, inout, amount):
    ta = trade_account
    if not ta.money_password:
        return False, '未登录资金密码'
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    if inout == 'in':
        r = t.money_in(amount, ta.money_password)
    else:
        r = t.money_out(amount, ta.money_password)
    return r, t.last_error
Exemple #6
0
def transfer(trade_account, inout, amount):
    ta = trade_account
    if not ta.money_password:
        return False, '未登录资金密码'
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    if inout == 'in':
        r = t.money_in(amount, ta.money_password)
    else:
        r = t.money_out(amount, ta.money_password)
    return r, t.last_error
Exemple #7
0
def call_api():
    login_name = request.form.get('login_name')
    method = request.form.get('method')
    login_name = login_name.strip()
    a = Account.query_one({'login_name': login_name})
    t = Trader('中港邮币卡', a.login_name, a.login_password)
    t.keep_alive()
    namedict = {c['symbol']: c['name'] for c in t.list_collection()}
    result = getattr(t, method)()
    for r in result:
        if 'symbol' in r:
            r['name'] = namedict[r['symbol']]
    return jsonify(status=200, **{method: result})
Exemple #8
0
def call_api():
    login_name = request.form.get('login_name')
    method = request.form.get('method')
    login_name = login_name.strip()
    a = Account.query_one({'login_name': login_name})
    t = Trader('中港邮币卡', a.login_name, a.login_password)
    t.keep_alive()
    namedict = {c['symbol']: c['name'] for c in t.list_collection()}
    result = getattr(t, method)()
    for r in result:
        if 'symbol' in r:
            r['name'] = namedict[r['symbol']]
    return jsonify(status=200,
                   **{method: result})
Exemple #9
0
 def check_account(account):
     print('检查账号{}_{}'.format(account.exchange,
                              account.login_name))
     try:
         Trader(account.exchange,
                account.login_name,
                account.login_password)
     except:
         pass
Exemple #10
0
def trade_account_change_password():
    exchanges = request.form.getlist('exchanges[]')
    login_names = request.form.getlist('login_names[]')
    new_login_password = request.form.get('new_login_password')
    # TODO: add new_money_password support
    errors = []
    for ex, name in zip(exchanges, login_names):
        ta = TradeAccount.query_one({'exchange': ex, 'login_name': name})
        pwd = ta.login_password
        t = Trader(ex, name, pwd)
        t.change_password(new_login_password)
        if t.last_error:
            errors.append([ex, name, t.last_error])
        else:
            ta.login_password = new_login_password
            ta.upsert()
    if errors:
        log.exception(str(errors))
        return jsonify(status=500, reason='部分账号修改失败', details=errors)
    else:
        return jsonify(status=200, reason='')
Exemple #11
0
def call_trader():
    """ 直接调用trader的方法, 返回{方法名: 调用结果} """
    exchange = request.form.get('exchange')
    login_name = request.form.get('login_name')
    method = request.form.get('method')
    login_name = login_name.strip()
    a = Account.query_one({'exchange': exchange,
                           'login_name': login_name})
    if a:
        t = Trader(exchange, a.login_name, a.login_password)
        if not t.is_logged_in:
            return jsonify(status=403, reason='登录失败 {}:{} {}'
                           ''.format(exchange, login_name, t.last_error))
        namedict = {c['symbol']: c['name'] for c in t.list_collection()}
        result = getattr(t, method)()
        for r in result:
            if 'symbol' in r:
                r['name'] = namedict[r['symbol']]
        return jsonify(status=200,
                       **{method: result})
    else:
        return jsonify(status=404, reason='未找到账号 {}:{}'
                       ''.format(exchange, login_name))
Exemple #12
0
def trade_account_change_password():
    exchanges = request.form.getlist('exchanges[]')
    login_names = request.form.getlist('login_names[]')
    new_login_password = request.form.get('new_login_password')
    # TODO: add new_money_password support
    errors = []
    for ex, name in zip(exchanges, login_names):
        ta = TradeAccount.query_one({'exchange': ex,
                                     'login_name': name})
        pwd = ta.login_password
        t = Trader(ex, name, pwd)
        t.change_password(new_login_password)
        if t.last_error:
            errors.append([ex, name, t.last_error])
        else:
            ta.login_password = new_login_password
            ta.upsert()
    if errors:
        log.exception(str(errors))
        return jsonify(status=500,
                       reason='部分账号修改失败',
                       details=errors)
    else:
        return jsonify(status=200, reason='')
Exemple #13
0
def update_trade_account(trade_account):
    ta = trade_account
    log.info('更新账号{}的信息'.format(ta._id))
    if not ta.login_password:
        ta.verified = False
        ta.verify_message = '没有密码不能登录'
    else:
        try:
            t = Trader(ta.exchange, ta.login_name, ta.login_password)
        except KeyError:
            ta.verified = False
            ta.verify_message = '该交易所协议未破解'
        except Exception as e:
            ta.verified = False
            ta.verify_message = str(e)
        else:
            if not t.is_logged_in:
                ta.verified = False
                ta.verify_message = t.last_error
            else:
                ta.verified = True

                # update money
                ta.money = t.money()
                # update position
                position = t.position()
                if position is not None:
                    for p in position:
                        p['name'] = Collection.get_name(
                            ta.exchange, p['symbol']) or ''
                    ta.position = position

                # update orders
                orders = t.orders()
                aggorders = {}
                for o in orders:
                    o['name'] = Collection.get_name(
                        ta.exchange, o['symbol']) or ''
                    st = (o['symbol'], o['type_'])
                    if st not in aggorders:
                        aggorders[st] = o
                    else:
                        # 把成交汇总一下
                        oo = aggorders[st]
                        if oo['quantity'] > 0:
                            amount = oo['price'] * oo['quantity'] + \
                                o['price'] * o['quantity']
                            oo['quantity'] += o['quantity']
                            oo['price'] = amount / oo['quantity']

                orders = aggorders.values()

                ta.orders = orders

                # update order_status
                order_status = t.order_status()
                for o in order_status:
                    o['name'] = Collection.get_name(
                        ta.exchange, o['symbol']) or ''
                ta.order_status = order_status

    ta.upsert()
    user = User.query_one({'_id': ta.user})
    accounting(user)
Exemple #14
0
def update_user_account(user):
    position = {}
    orders = {}
    status_list = []
    namedict = {}
    total_money = 0
    for a in Account.query({'user_id': user._id}):
        t = Trader('中港邮币卡', a.login_name, a.login_password)
        if not t.is_logged_in:
            print('{}:{}不是合法账号'.format(a.login_name, a.login_password))
            continue
        if not namedict:
            namedict = {c['symbol']: c['name']
                        for c in t.list_collection()}
        for p in t.position() or []:
            if p['symbol'] not in position:
                position[p['symbol']] = p
                p['name'] = namedict[p['symbol']]
            else:
                p2 = position[p['symbol']]
                price1, quantity1 = p['average_price'], p['quantity']
                price2, quantity2 = p2['average_price'], p2['quantity']
                amount = price1 * quantity1 + price2 * quantity2
                quantity = quantity1 + quantity2
                if quantity > 0:
                    p2['quantity'] = quantity
                    p2['average_price'] = amount / quantity
                    p2['sellable'] = p['sellable']
                    p2['profit'] += p['profit']

        for o in t.orders() or []:
            if (o['type_'], o['symbol']) not in orders:
                orders[(o['type_'], o['symbol'])] = o
                o['name'] = namedict[o['symbol']]
            else:
                o2 = orders[(o['type_'], o['symbol'])]
                price1, quantity1 = o['price'], o['quantity']
                price2, quantity2 = o2['price'], o2['quantity']
                amount = price1 * quantity1 + price2 * quantity2
                quantity = quantity1 + quantity2
                if quantity > 0:
                    o2['quantity'] = quantity
                    o2['price'] = amount / quantity
                    o2['commision'] += o['commision']
                    o2['profit'] += o['profit']

        for s in t.order_status() or []:
            s['name'] = namedict[s['symbol']]
            status_list.append(s)

        total_money += t.money()['usable']

    total_capital = sum(p['price'] * p['quantity']
                        for p in position.values()
                        if p['symbol'] in symbols)
    total_profit = sum(p['profit'] for p in position.values()
                       if p['symbol'] in symbols)

    print(user._id, total_capital, total_profit)

    position_list = sorted(
        position.values(), key=lambda x: x['profit'], reverse=True)
    order_list = sorted(
        orders.values(), key=lambda x: x['profit'], reverse=True)
    status_list = sorted(status_list, key=lambda x: x['order'])

    d = datetime.utcnow() + timedelta(hours=8)
    if d.hour < 9:
        d -= timedelta(days=1)
    d = d.replace(hour=0, minute=0, second=0, microsecond=0)

    Position({
        'user_id': user._id,
        'date': d,
        'position_list': position_list,
    }).upsert()

    Order({
        'user_id': user._id,
        'date': d,
        'order_list': order_list,
    }).upsert()

    if status_list:
        # 有委托单才更新, 以免被覆盖
        Status({
            'user_id': user._id,
            'date': d,
            'status_list': status_list,
        }).upsert()

    user.total_money = total_money
    user.total_capital = total_capital
    user.total_profit = total_profit
    user.upsert()
Exemple #15
0
def withdraw(trade_account, order):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    r = t.withdraw(order)
    return r, t.last_error
Exemple #16
0
def list_offers(trade_account):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    return t.list_offer_details()
Exemple #17
0
def withdraw(trade_account, order):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    r = t.withdraw(order)
    return r, t.last_error
Exemple #18
0
def apply_offer(trade_account, symbol, quantity):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    r = t.apply(symbol, quantity)
    err = t.last_error
    return r, err
Exemple #19
0
def apply_status(trade_account):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    return t.apply_status()
Exemple #20
0
    def __init__(self):
        # [(trader, usable), ...]
        self.moneys = []

        # {symbol -> [(trader, quantity), ... ]}
        self.position = {}

        # {symbol -> price}
        self.prices = {}

        # {symbol -> {asks: [], bids: [], ...}}
        self.quotes = {}

        # {symbol -> {buy/sell: quantity, buys/sells: [(username, quantity), ...]}}
        self.pendings = {}

        # {symbol -> price}
        self.highests = {}
        self.lowests = {}

        # [str, ...]
        self.logs = []

        self.traders = [
            Trader('中港邮币卡', '1000000090138', 'caibahaha'),
            Trader('中港邮币卡', '0021000013948', 'caibahaha'),
            Trader('中港邮币卡', '0021000013954', 'caibahaha'),
            Trader('中港邮币卡', '0021000013956', 'caibahaha'),
            Trader('中港邮币卡', '0021000013959', 'caibahaha'),
            Trader('中港邮币卡', '1000000040434', '140718'),
            Trader('中港邮币卡', '1000000090430', '100219'),
            Trader('中港邮币卡', '1000000053321', '100219'),
            Trader('中港邮币卡', '0021000013440', '100219'),
            Trader('中港邮币卡', '0021000013441', '100219'),
            Trader('中港邮币卡', '0021000013439', '100219'),
            Trader('中港邮币卡', '0001000020505', '100219'),
            Trader('中港邮币卡', '0001000020511', '100219'),
            Trader('中港邮币卡', '0002000013882', 'cwf111111'),
            Trader('中港邮币卡', '0002000013890', 'cwf111111'),
            Trader('中港邮币卡', '0002000013903', 'cwf111111'),
            Trader('中港邮币卡', '0002000013916', 'cwf111111'),
            Trader('中港邮币卡', '0002000013924', 'cwf111111'),
            Trader('中港邮币卡', '0002000013931', 'cwf111111'),
            Trader('中港邮币卡', '0021000020181', '27271414q'),

            # Trader('中港邮币卡', '0021000013954', 'caibahaha'),
            # Trader('中港邮币卡', '1000000090430', '100219'),
        ]
        self.investors = [t.investor_info() for t in self.traders]
        self.executor = ThreadPoolExecutor(20)
        self.last_quotes = {}
        self.last_syncs = {}
        self.init_names()
Exemple #21
0
def apply_status(trade_account):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    return t.apply_status()
Exemple #22
0
def apply_offer(trade_account, symbol, quantity):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    r = t.apply(symbol, quantity)
    err = t.last_error
    return r, err
Exemple #23
0
def update_account(account):
    print('更新账号 {}/{}/{}'.format(account.exchange,
                                 account.login_name,
                                 account.login_password))

    try:
        t = Trader(account.exchange,
                   account.login_name,
                   account.login_password)

        namedict = {c['symbol']: c['name']
                    for c in t.list_collection()}

        money = t.money()['usable']
        profit = 0
        capital = 0
        earned = 0
        lost = 0

        # update position
        position = t.position() or []
        for p in position:
            p['name'] = namedict[p['symbol']]
            profit += p['profit']
            capital += p['amount']

        # update order_status
        order_status = t.order_status() or []
        for o in order_status:
            o['name'] = namedict[o['symbol']]

        # update orders
        orders_dict = {}
        for o in t.orders() or []:
            pair = (o['type_'], o['symbol'])
            if o['profit'] > 0:
                earned += o['profit']
            else:
                lost -= o['profit']
            if pair not in orders_dict:
                o['name'] = namedict[o['symbol']]
                orders_dict[pair] = o
            else:
                o2 = orders_dict[pair]
                amount1 = o.price * o.quantity + \
                    o2.price * o2.quantity
                amount2 = o['current_price'] * o.quantity + \
                    o2['current_price'] * o2.quantity
                o2.quantity += o.quantity
                if o2.quantity:
                    o2.price = amount1 / o2.quantity
                    o2['current_price'] = amount2 / o2.quantity
        orders = list(orders_dict.values())

        cond = {
            'date': thisdate(),
            'account': account._id
        }
        update = {
            'money': money,
            'profit': profit,
            'capital': capital,
            'earned': earned,
            'lost': lost,
            'position': position,
            'orders': orders,
        }
        if order_status:
            # only update when there's order_status
            # because orders will be cleared out after everyday's closing
            update['order_status'] = order_status

        DailyTrading.update_one(cond, {'$set': update}, upsert=True)

        # update collections to acount
        collections = ['{}_{}'.format(account.exchange, p['symbol'])
                       for p in position]
        update['collections'] = collections
        Account.update_one({'_id': account._id},
                           {'$set': update}, upsert=True)
    except Exception as e:
        log.exception(str(e))
        return
Exemple #24
0
def withdraw_apply(trade_account, applyid):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    return t.withdraw_apply(applyid)
Exemple #25
0
def update_trade_account(trade_account):
    ta = trade_account
    log.info('更新账号{}的信息'.format(ta._id))
    if not ta.login_password:
        ta.verified = False
        ta.verify_message = '没有密码不能登录'
    else:
        try:
            t = Trader(ta.exchange, ta.login_name, ta.login_password)
        except KeyError:
            ta.verified = False
            ta.verify_message = '该交易所协议未破解'
        except Exception as e:
            ta.verified = False
            ta.verify_message = str(e)
        else:
            if not t.is_logged_in:
                ta.verified = False
                ta.verify_message = t.last_error
            else:
                ta.verified = True

                # update money
                ta.money = t.money()
                # update position
                position = t.position()
                if position is not None:
                    for p in position:
                        p['name'] = Collection.get_name(
                            ta.exchange, p['symbol']) or ''
                    ta.position = position

                # update orders
                orders = t.orders()
                aggorders = {}
                for o in orders:
                    o['name'] = Collection.get_name(ta.exchange,
                                                    o['symbol']) or ''
                    st = (o['symbol'], o['type_'])
                    if st not in aggorders:
                        aggorders[st] = o
                    else:
                        # 把成交汇总一下
                        oo = aggorders[st]
                        if oo['quantity'] > 0:
                            amount = oo['price'] * oo['quantity'] + \
                                o['price'] * o['quantity']
                            oo['quantity'] += o['quantity']
                            oo['price'] = amount / oo['quantity']

                orders = aggorders.values()

                ta.orders = orders

                # update order_status
                order_status = t.order_status()
                for o in order_status:
                    o['name'] = Collection.get_name(ta.exchange,
                                                    o['symbol']) or ''
                ta.order_status = order_status

    ta.upsert()
    user = User.query_one({'_id': ta.user})
    accounting(user)
Exemple #26
0
def withdraw_apply(trade_account, applyid):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    return t.withdraw_apply(applyid)
Exemple #27
0
def list_offers(trade_account):
    ta = trade_account
    t = Trader(ta.exchange, ta.login_name, ta.login_password)
    return t.list_offer_details()
Exemple #28
0
def update_user_account(user):
    position = {}
    orders = {}
    status_list = []
    namedict = {}
    total_money = 0
    for a in Account.query({'user_id': user._id}):
        t = Trader('中港邮币卡', a.login_name, a.login_password)
        if not t.is_logged_in:
            print('{}:{}不是合法账号'.format(a.login_name, a.login_password))
            continue
        if not namedict:
            namedict = {c['symbol']: c['name'] for c in t.list_collection()}
        for p in t.position() or []:
            if p['symbol'] not in position:
                position[p['symbol']] = p
                p['name'] = namedict[p['symbol']]
            else:
                p2 = position[p['symbol']]
                price1, quantity1 = p['average_price'], p['quantity']
                price2, quantity2 = p2['average_price'], p2['quantity']
                amount = price1 * quantity1 + price2 * quantity2
                quantity = quantity1 + quantity2
                if quantity > 0:
                    p2['quantity'] = quantity
                    p2['average_price'] = amount / quantity
                    p2['sellable'] = p['sellable']
                    p2['profit'] += p['profit']

        for o in t.orders() or []:
            if (o['type_'], o['symbol']) not in orders:
                orders[(o['type_'], o['symbol'])] = o
                o['name'] = namedict[o['symbol']]
            else:
                o2 = orders[(o['type_'], o['symbol'])]
                price1, quantity1 = o['price'], o['quantity']
                price2, quantity2 = o2['price'], o2['quantity']
                amount = price1 * quantity1 + price2 * quantity2
                quantity = quantity1 + quantity2
                if quantity > 0:
                    o2['quantity'] = quantity
                    o2['price'] = amount / quantity
                    o2['commision'] += o['commision']
                    o2['profit'] += o['profit']

        for s in t.order_status() or []:
            s['name'] = namedict[s['symbol']]
            status_list.append(s)

        total_money += t.money()['usable']

    total_capital = sum(p['price'] * p['quantity'] for p in position.values()
                        if p['symbol'] in symbols)
    total_profit = sum(p['profit'] for p in position.values()
                       if p['symbol'] in symbols)

    print(user._id, total_capital, total_profit)

    position_list = sorted(position.values(),
                           key=lambda x: x['profit'],
                           reverse=True)
    order_list = sorted(orders.values(),
                        key=lambda x: x['profit'],
                        reverse=True)
    status_list = sorted(status_list, key=lambda x: x['order'])

    d = datetime.utcnow() + timedelta(hours=8)
    if d.hour < 9:
        d -= timedelta(days=1)
    d = d.replace(hour=0, minute=0, second=0, microsecond=0)

    Position({
        'user_id': user._id,
        'date': d,
        'position_list': position_list,
    }).upsert()

    Order({
        'user_id': user._id,
        'date': d,
        'order_list': order_list,
    }).upsert()

    if status_list:
        # 有委托单才更新, 以免被覆盖
        Status({
            'user_id': user._id,
            'date': d,
            'status_list': status_list,
        }).upsert()

    user.total_money = total_money
    user.total_capital = total_capital
    user.total_profit = total_profit
    user.upsert()