Exemple #1
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 #2
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 #3
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 #4
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 #5
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()