def trade_account_edit(): investor_name = request.form.get('investor') i = Investor.query_one({'name': investor_name}) if not i: return jsonify( status=404, reason='投资人name={}未找到'.format(investor_name)) user = current_user._id ta = { 'user': user, 'investor': i._id, 'exchange': request.form.get('exchange'), 'bank': request.form.get('bank'), 'login_name': request.form.get('login_name'), 'login_password': request.form.get('login_password'), 'money_password': request.form.get('money_password'), } try: TradeAccount(ta).upsert() except Exception as e: TradeAccount.delete_one({'investor': ta['investor'], 'exchange': ta['exchange']}) try: TradeAccount(ta).upsert() except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) return jsonify(status=200, reason='')
def trade_account_edit(): investor_name = request.form.get('investor') i = Investor.query_one({'name': investor_name}) if not i: return jsonify(status=404, reason='投资人name={}未找到'.format(investor_name)) user = current_user._id ta = { 'user': user, 'investor': i._id, 'exchange': request.form.get('exchange'), 'bank': request.form.get('bank'), 'login_name': request.form.get('login_name'), 'login_password': request.form.get('login_password'), 'money_password': request.form.get('money_password'), } try: TradeAccount(ta).upsert() except Exception as e: TradeAccount.delete_one({ 'investor': ta['investor'], 'exchange': ta['exchange'] }) try: TradeAccount(ta).upsert() except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) return jsonify(status=200, reason='')
def trade_account_delete(): ids = request.form.getlist('ids[]') try: TradeAccount.delete_many({'_id': {'$in': ids}}) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) return jsonify(status=200, reason='')
def trade_account_update(): ids = request.form.getlist('ids[]') try: trade_accounts = TradeAccount.query({'_id': {'$in': ids}}) for ta in trade_accounts: update_trade_account(ta) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) return jsonify(status=200, reason='')
def trade_account_apply_status(): account_id = request.form.get('account_id') ta = TradeAccount.query_one({'_id': account_id}) if ta: try: result = apply_status(ta) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: return jsonify(status=200, apply_status=result) else: return jsonify(status=500, reason='账号未找到')
def trade_account_list_offers(): account_id = request.form.get('account_id') ta = TradeAccount.query_one({'_id': account_id}) if ta: try: offers = list_offers(ta) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: return jsonify(status=200, offers=offers) else: return jsonify(status=500, reason='账号未找到')
def trade_account_withdraw_apply(): account_id = request.form.get('account_id') applyid = request.form.get('applyid') ta = TradeAccount.query_one({'_id': account_id}) if ta: try: withdraw_apply(ta, applyid) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: return jsonify(status=200, reason='撤单已提交') else: return jsonify(status=500, reason='账号未找到')
def personal_info(): nav = 'accounts' tab = 'personal_info' user = current_user._id investors = Investor.user_investors(user) investor_ids = [i._id for i in investors] trade_accounts = TradeAccount.user_accounts(user) account_table = {} for ta in trade_accounts: if ta.exchange not in account_table: account_table[ta.exchange] = [None] * len(investors) order = investor_ids.index(ta.investor) account_table[ta.exchange][order] = ta colspan = len(investors) + 1 return render_template('user/personal_info.html', **locals())
def trade_account_apply_offer(): account_id = request.form.get('account_id') symbol = request.form.get('symbol') quantity = int(request.form.get('quantity')) ta = TradeAccount.query_one({'_id': account_id}) if ta: try: r, err = apply_offer(ta, symbol, quantity) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: return jsonify(status=200, reason=str(err)) else: return jsonify(status=500, reason='账号未找到')
def trade_account_withdraw(): account_id = request.form.get('account_id') order = request.form.get('order') ta = TradeAccount.query_one({'_id': account_id}) if ta: try: r, err = withdraw(ta, order) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: if r: return jsonify(status=200, reason='撤单成功') else: return jsonify(status=400, reason=err) else: return jsonify(status=500, reason='账号未找到')
def trade_account_transfer(): account_id = request.form.get('account_id') inout = request.form.get('inout') amount = float(request.form.get('amount') or 0) ta = TradeAccount.query_one({'_id': account_id}) if ta: try: r, err = transfer(ta, inout, amount) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: if r: return jsonify(status=200, reason='出入金已提交') else: return jsonify(status=400, reason=err) else: return jsonify(status=500, reason='账号未找到')
def trade_account_update_quote(): account_id = request.form.get('account_id') symbol = request.form.get('symbol') ta = TradeAccount.query_one({'_id': account_id}) if ta: try: qd = quote_detail(ta, symbol) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: return jsonify(status=200, price=qd['price'], highest=qd['highest'], lowest=qd['lowest'], asks=qd['asks'], bids=qd['bids']) else: return jsonify(status=500, reason='账号未找到')
def trade_account_order(): account_id = request.form.get('account_id') ta = TradeAccount.query_one({'_id': account_id}) if ta: type_ = request.form.get('type_') symbol = request.form.get('symbol') price = float(request.form.get('price')) quantity = int(request.form.get('quantity')) try: r, err = order(ta, type_, symbol, price, quantity) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) else: if r: return jsonify(status=200, reason='下单成功') else: return jsonify(status=400, reason=err) else: return jsonify(status=500, reason='账号未找到')
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='')
def trade_account_refresh_status(): account_id = request.form.get('account_id') ta = TradeAccount.query_one({'_id': account_id}) if ta: try: update_trade_account(ta) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) return jsonify( status=200, position=sorted([p.to_dict() for p in ta.position], key=lambda p: p['symbol']), money=ta.money.to_dict(), orders=sorted([o.to_dict() for o in ta.orders], key=lambda o: o['symbol']), order_status=sorted([o.to_dict() for o in ta.order_status], key=lambda o: o['symbol']), ) else: return jsonify(status=500, reason='账号未找到')
def trade_account_refresh_status(): account_id = request.form.get('account_id') ta = TradeAccount.query_one({'_id': account_id}) if ta: try: update_trade_account(ta) except Exception as e: log.exception(str(e)) return jsonify(status=500, reason=str(e)) return jsonify(status=200, position=sorted([p.to_dict() for p in ta.position], key=lambda p: p['symbol']), money=ta.money.to_dict(), orders=sorted([o.to_dict() for o in ta.orders], key=lambda o: o['symbol']), order_status=sorted([o.to_dict() for o in ta.order_status], key=lambda o: o['symbol']), ) else: return jsonify(status=500, reason='账号未找到')
def accounting(user): """ 对账号进行自动记账(如果用户已配置) """ operated_at = datetime.utcnow() + timedelta(hours=8) def add_transaction(type_, exchange, symbol, price, quantity): t = Transaction({ 'user': user._id, 'type_': type_, 'operated_at': operated_at, 'exchange': exchange, 'symbol': symbol, 'price': price, 'quantity': quantity, }) t.save() if not Position.do_op(t): t.remove() if user.auto_accounting: op = Position.user_position(user._id) p2pairs = {} for ta in TradeAccount.query({'user': user._id}): for p in ta.position or []: pair = (ta.exchange, p.symbol) if pair not in p2pairs: p2pairs[pair] = p else: pp = p2pairs[pair] amount = p.average_price * p.quantity + \ pp.average_price * pp.quantity p.quantity += pp.quantity if p.quantity > 0: p.average_price = amount / p.quantity p2pairs[pair] = p p1pairs = {(p1['exchange'], p1['symbol']): p1 for p1 in op} # 检查更改项 for p1 in op: pair = p1['exchange'], p1['symbol'] if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡', '上海文交所', '中俄邮币卡']: continue if pair in p2pairs: p2 = p2pairs[pair] quantity = p2.quantity - p1['quantity'] if quantity != 0: type_ = 'buy' if quantity > 0 else 'sell' if type_ == 'buy': price = ( p2.average_price * p2.quantity - p1['avg_buy_price'] * p1['quantity']) / quantity else: price = p2.price if price < 0.01: price = Quote.latest_price(p1['exchange'], p1['symbol']) price = int(price * 100) / 100. add_transaction(type_, pair[0], pair[1], price, abs(quantity)) else: # 按现价计算已卖出 if p1['quantity'] > 0: price = Quote.latest_price(p1['exchange'], p1['symbol']) price = int(price * 100) / 100. add_transaction('sell', pair[0], pair[1], price, p1['quantity']) # 检查新增项 for pair, p2 in p2pairs.items(): if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡', '上海文交所', '中俄邮币卡']: continue if pair not in p1pairs and p2.quantity > 0: price = int(p2.average_price * 100) / 100. add_transaction('buy', pair[0], pair[1], price, p2.quantity)
def trade_account_all(): """ 更新全部账户 """ for ta in TradeAccount.query(): Trader.traders = {} update_trade_account(ta)
def accounting(user): """ 对账号进行自动记账(如果用户已配置) """ operated_at = datetime.utcnow() + timedelta(hours=8) def add_transaction(type_, exchange, symbol, price, quantity): t = Transaction({ 'user': user._id, 'type_': type_, 'operated_at': operated_at, 'exchange': exchange, 'symbol': symbol, 'price': price, 'quantity': quantity, }) t.save() if not Position.do_op(t): t.remove() if user.auto_accounting: op = Position.user_position(user._id) p2pairs = {} for ta in TradeAccount.query({'user': user._id}): for p in ta.position or []: pair = (ta.exchange, p.symbol) if pair not in p2pairs: p2pairs[pair] = p else: pp = p2pairs[pair] amount = p.average_price * p.quantity + \ pp.average_price * pp.quantity p.quantity += pp.quantity if p.quantity > 0: p.average_price = amount / p.quantity p2pairs[pair] = p p1pairs = {(p1['exchange'], p1['symbol']): p1 for p1 in op} # 检查更改项 for p1 in op: pair = p1['exchange'], p1['symbol'] if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡', '上海文交所', '中俄邮币卡']: continue if pair in p2pairs: p2 = p2pairs[pair] quantity = p2.quantity - p1['quantity'] if quantity != 0: type_ = 'buy' if quantity > 0 else 'sell' if type_ == 'buy': price = (p2.average_price * p2.quantity - p1['avg_buy_price'] * p1['quantity']) / quantity else: price = p2.price if price < 0.01: price = Quote.latest_price(p1['exchange'], p1['symbol']) price = int(price * 100) / 100. add_transaction( type_, pair[0], pair[1], price, abs(quantity)) else: # 按现价计算已卖出 if p1['quantity'] > 0: price = Quote.latest_price(p1['exchange'], p1['symbol']) price = int(price * 100) / 100. add_transaction( 'sell', pair[0], pair[1], price, p1['quantity']) # 检查新增项 for pair, p2 in p2pairs.items(): if pair[0] in ['湖南文交所', '海西文交所', '上海邮币卡', '上海文交所', '中俄邮币卡']: continue if pair not in p1pairs and p2.quantity > 0: price = int(p2.average_price * 100) / 100. add_transaction('buy', pair[0], pair[1], price, p2.quantity)
def trade_account(): nav = 'accounts' tab = 'trade_account' investor = request.args.get('investor', '') exchange = request.args.get('exchange', '') add_investor = request.args.get('add_investor', '') add_exchange = request.args.get('add_exchange', '') bank = request.args.get('bank', '') investor = Investor.query_one({'_id': investor}) exchange = Exchange.query_one({'abbr': exchange}) user = current_user._id trade_accounts = TradeAccount.user_accounts(user) if investor: trade_accounts = [ta for ta in trade_accounts if ta.investor == investor._id] if exchange: trade_accounts = [ta for ta in trade_accounts if ta.exchange == exchange.abbr] if bank: trade_accounts = [ta for ta in trade_accounts if ta.bank == bank] investors = Investor.user_investors(user) exchanges = sorted(list(Exchange.query()), key=lambda x: x.abbr) exchange_list = [{'text': e.abbr, 'value': e.abbr} for e in exchanges] investor_list = [{'text': i.name, 'value': i.name} for i in investors] investor_banks = {i.name: sorted([ba.bank for ba in i.bank_accounts]) for i in investors} exchange_banks = {conf['abbr']: sorted(conf['opening']['bank']) for conf in CONFS} bank_exchanges = {} for ex, banks in exchange_banks.items(): for b in banks: if b not in bank_exchanges: bank_exchanges[b] = [] bank_exchanges[b].append(ex) investor_exchanges = { invesotr: sorted(set(sum( [bank_exchanges[b] for b in banks], []))) for invesotr, banks in investor_banks.items() } avail_investors = set(ta.investor for ta in trade_accounts) avail_exchanges = set(ta.exchange for ta in trade_accounts) avail_banks = set(ta.bank for ta in trade_accounts) investors = [i for i in investors if i._id in avail_investors] exchanges = [e for e in exchanges if e.abbr in avail_exchanges] thebanks = sorted(list(avail_banks)) account_positions = {ta._id: sorted([p.to_dict() for p in ta.position], key=lambda p: p['symbol']) for ta in trade_accounts} account_moneys = {ta._id: ta.money.to_dict() if ta.money else {} for ta in trade_accounts} account_order_status = {ta._id: sorted([o.to_dict() for o in ta.order_status], key=lambda o: o['order']) for ta in trade_accounts} account_orders = {ta._id: sorted([o.to_dict() for o in ta.orders], key=lambda o: o['symbol']) for ta in trade_accounts} return render_template('user/trade_account.html', **locals())
def trade_account(): nav = 'accounts' tab = 'trade_account' investor = request.args.get('investor', '') exchange = request.args.get('exchange', '') add_investor = request.args.get('add_investor', '') add_exchange = request.args.get('add_exchange', '') bank = request.args.get('bank', '') investor = Investor.query_one({'_id': investor}) exchange = Exchange.query_one({'abbr': exchange}) user = current_user._id trade_accounts = TradeAccount.user_accounts(user) if investor: trade_accounts = [ ta for ta in trade_accounts if ta.investor == investor._id ] if exchange: trade_accounts = [ ta for ta in trade_accounts if ta.exchange == exchange.abbr ] if bank: trade_accounts = [ta for ta in trade_accounts if ta.bank == bank] investors = Investor.user_investors(user) exchanges = sorted(list(Exchange.query()), key=lambda x: x.abbr) exchange_list = [{'text': e.abbr, 'value': e.abbr} for e in exchanges] investor_list = [{'text': i.name, 'value': i.name} for i in investors] investor_banks = { i.name: sorted([ba.bank for ba in i.bank_accounts]) for i in investors } exchange_banks = { conf['abbr']: sorted(conf['opening']['bank']) for conf in CONFS } bank_exchanges = {} for ex, banks in exchange_banks.items(): for b in banks: if b not in bank_exchanges: bank_exchanges[b] = [] bank_exchanges[b].append(ex) investor_exchanges = { invesotr: sorted(set(sum([bank_exchanges[b] for b in banks], []))) for invesotr, banks in investor_banks.items() } avail_investors = set(ta.investor for ta in trade_accounts) avail_exchanges = set(ta.exchange for ta in trade_accounts) avail_banks = set(ta.bank for ta in trade_accounts) investors = [i for i in investors if i._id in avail_investors] exchanges = [e for e in exchanges if e.abbr in avail_exchanges] thebanks = sorted(list(avail_banks)) account_positions = { ta._id: sorted([p.to_dict() for p in ta.position], key=lambda p: p['symbol']) for ta in trade_accounts } account_moneys = { ta._id: ta.money.to_dict() if ta.money else {} for ta in trade_accounts } account_order_status = { ta._id: sorted([o.to_dict() for o in ta.order_status], key=lambda o: o['order']) for ta in trade_accounts } account_orders = { ta._id: sorted([o.to_dict() for o in ta.orders], key=lambda o: o['symbol']) for ta in trade_accounts } return render_template('user/trade_account.html', **locals())