def add_account(user, exchange, login_name, login_password, money_password='', bank_password=''): """ 添加账号 """ try: u = User.query_one({'_id': user}) if not u: log.info('找不到用户{}, 无法创建账号'.format(user)) return False if exchange not in exchanges: log.info('找不到交易所{}, 无法创建账号'.format(exchange)) return False a = Account({ 'user': user, 'exchange': exchange, 'login_name': login_name, 'login_password': login_password, 'money_password': money_password, 'bank_password': bank_password, }) a.upsert() log.info('创建/更新账号{}成功'.format(a._id)) return True except Exception as e: log.exception(str(e)) return False
def delete_account(): user = request.form.get('user') exchange = request.form.get('exchange') login_name = request.form.get('login_name') Account.delete_one({'user': user, 'exchange': exchange, 'login_name': login_name}) return jsonify(status=200)
def update_accounts(accounts=None, users=None, exchanges=None, collections=None): """ 批量更新账号信息 """ logging.basicConfig(level=logging.ERROR, format='[%(asctime)s] %(name)s' '<%(levelname)s> %(message)s') cond = {} if accounts: assert isinstance(accounts, list) cond['_id'] = {'$in': accounts} if users: assert isinstance(users, list) cond['user'] = {'$in': users} if exchanges: assert isinstance(exchanges, list) cond['exchange'] = {'$in': exchanges} if collections: assert isinstance(collections, list) cond['collections'] = {'$in': collections} accounts = list(Account.query(cond)) random.shuffle(accounts) for account in accounts: executor.submit(update_account, account) executor.shutdown() update_users() update_exchanges() update_collections()
def update_exchange(exchange): """ 更新交易所的账号信息 """ accounts = list(Account.query({'exchange': exchange})) e = Exchange.query_one({'_id': exchange}) for key, value in accounts_summary(accounts).items(): setattr(e, key, value) e.num_users = len(set(a.user for a in accounts)) e.num_accounts = len(accounts) e.upsert()
def update_user(user): """ 更新用户的账号信息 """ accounts = list(Account.query({'user': user})) u = User.query_one({'_id': user}) for key, value in accounts_summary(accounts).items(): setattr(u, key, value) u.num_accounts = len(accounts) u.num_exchanges = len(set(a.exchange for a in accounts)) u.upsert()
def check_accounts(): logging.basicConfig(level=logging.ERROR, format='[%(asctime)s] %(name)s' '<%(levelname)s> %(message)s') def check_account(account): print('检查账号{}_{}'.format(account.exchange, account.login_name)) try: Trader(account.exchange, account.login_name, account.login_password) except: pass accounts = list(Account.query()) random.shuffle(accounts) for account in accounts: executor.submit(check_account, account)
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))
def update_collection(collection): """ 更新藏品的账号信息 """ accounts = list(Account.query({'collections': collection})) users = set() exchange, symbol = collection.split('_') name = '' quantity = 0 buy_price = 0 for account in accounts: users.add(account.user) summary = accounts_summary(accounts) for p in summary['position']: if collection.endswith(p.symbol): quantity = p.quantity buy_price = p.average_price name = p.name break users = list(users) c = Collection.query_one({'_id': collection}) if not c: c = Collection({'_id': collection}) if exchange: c.exchange = exchange if symbol: c.symbol = symbol if name: c.name = name c.users = users or [] c.accounts = [a._id for a in accounts] or [] c.quantity = quantity c.buy_price = buy_price try: c.upsert() except: pass
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
def admin_account(): users = list(User.query()) accounts = list(Account.query()) locals()['exchanges'] = exchanges return render_template('admin/account.html', **locals())
def admin(): num_users = User.count() num_accounts = Account.count() return render_template('admin/index.html', **locals())