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