def import_exchange_trades(ip, headers): # 获取bct所有标的物 instruments_dic = get_all_instrument_dic(ip, headers) xinhu_exchange_trades = pd.read_csv( import_exchange_trade_excel_file, encoding="gbk").to_dict(orient='records') records = [] for trade in xinhu_exchange_trades: underlyer = instrument_wind_code(trade['code'], instruments_dic.keys()) if trade['code'].find('.') < 0 and underlyer == trade['code']: print('BCT不存在合约代码 {underlyer} '.format(underlyer=str(underlyer))) continue if not instruments_dic.get(underlyer): print('BCT不存在合约代码 {underlyer} '.format(underlyer=str(underlyer))) continue multiplier = instruments_dic.get( underlyer)['multiplier'] if instruments_dic.get( underlyer)['multiplier'] else 1 direction = "BUYER" if trade['direction'] == 1 else "SELLER" open_close = "OPEN" if trade['direction'] == 1 else "CLOSE" # 开平 deal_price = trade['price'] # 交易价格 deal_amount = trade['amount'] # 交易数量 # 2020 - 06 - 18 - 20 - 59 - 00 day_str = trade['dayStr'] deal_time = datetime.datetime.strptime( day_str, _datetime_fmt).strftime(_datetime_fmt1) trade_id = str(trade['order_sys_id']) + "-" + str(trade['trade_id']) trade_account = '新湖场内交易账号' # 交易账户 exchange_trade = { "bookId": book_name, "instrumentId": underlyer, "direction": direction, "openClose": open_close, "dealPrice": deal_price, "dealAmount": deal_amount, "dealTime": deal_time, "tradeId": trade_id, "tradeAccount": trade_account, "multiplier": multiplier } records.append(exchange_trade) for record in records: try: utils.call('exeTradeRecordSave', record, 'exchange-service', ip, headers) except Exception as e: print("场内流水导入失败 {tradeId} msg:{error}".format( tradeId=record['tradeId'], error=repr(e)))
def create_trade(trade, enrichment, valid_time, host, token): return utils.call( 'trdTradeCreate', { 'trade': trade, 'enrichment': enrichment, 'validTime': valid_time.strftime(_datetime_fmt) }, 'trade-service', host, token)
def get_all_position_enrichment_dic(position_ids, ip, headers): position_enrichments = utils.call('trdGetPositionEnrichment', {'positionIds': position_ids}, 'trade-service', ip, headers) position_enrichment_dic = {} for position_enrichment in position_enrichments: position_enrichment_dic[ position_enrichment['positionId']] = position_enrichment return position_enrichment_dic
def get_all_instrument_dic(ip, headers): instrument_dic = {} try: instrument_list = utils.call('mktInstrumentsListPaged', {}, 'market-data-service', ip, headers)['page'] for item in instrument_list: instrument_dic[item['instrumentId']] = item return instrument_dic except Exception as e: print("failed update market data for: " + ip + ",Exception:" + str(e))
def get_all_legal_sales_dic(ip, headers): legal_sales_dic = {} try: legal_list = utils.call('refPartyList', {}, 'reference-data-service', ip, headers) for item in legal_list: legal_sales_dic[item['legalName']] = item['salesName'] return legal_sales_dic except Exception as e: print("failed get legal data for: " + ip + ",Exception:" + str(e))
def get_all_position_unwind_amount_dic(trade_ids, ip, headers): trade_ids_maps = [] for trade_id in trade_ids: trade_ids_maps.append({"tradeId": trade_id}) params = {"positionIds": trade_ids_maps} unwind_amount_list = utils.call('trdTradeLCMUnwindAmountGetAll', params, 'trade-service', ip, headers) position_unwind_amount_dic = {} for unwind_amount in unwind_amount_list: position_unwind_amount_dic[unwind_amount['positionId']] = unwind_amount return position_unwind_amount_dic
def get_all_lcm_events_dic(ip, headers): events = utils.call('trdTradeCashFlowListAll', {}, 'trade-service', ip, headers) lcm_event_dic = {} for event in events: position_events = lcm_event_dic.get(event['positionId']) if position_events: position_events.append(event) position_events.sort(key=lambda x: x['createdAt'], reverse=True) else: lcm_event_dic[event['positionId']] = [event] return lcm_event_dic
def mdl_model_data_get(model_type, underlyer, model_name, instance, ip, headers): try: params = { "modelType": model_type, "underlyer": underlyer, "modelName": model_name, "instance": instance } res = utils.call("mdlModelDataGet", params, "model-service", ip, headers) return res except Exception as e: print("mdl_model_data_get error:", repr(e)) return None
def create_client_cash_flow(account_id, trade_id, cash_flow, margin_flow, host, token): trade = utils.call('trdTradeSearch', {'tradeId': trade_id}, 'trade-service', host, token)[0] position = trade['positions'][0] direction = position['asset']['direction'] client = position['counterPartyCode'] task = utils.call('cliTasksGenerateByTradeId', { 'legalName': client, 'tradeId': trade_id }, 'reference-data-service', host, token)[0] utils.call( 'clientChangePremium', { 'tradeId': trade_id, 'accountId': task['accountId'], 'premium': task['premium'], 'information': None }, 'reference-data-service', host, token) res = utils.call( 'clientSaveAccountOpRecord', { 'accountOpRecord': { 'accountId': task['accountId'], 'cashChange': task['premium'] * -1, 'counterPartyCreditBalanceChange': 0, 'counterPartyFundChange': 0, 'creditBalanceChange': 0, 'debtChange': 0, 'event': 'CHANGE_PREMIUM', 'legalName': client, 'premiumChange': task['premium'], 'tradeId': trade_id } }, 'reference-data-service', host, token) return utils.call('cliMmarkTradeTaskProcessed', {'uuidList': [task['uuid']]}, 'reference-data-service', host, token)
def delete_trade(trade_id, host, token): return utils.call('trdTradeDelete', {'tradeId': trade_id}, 'trade-service', host, token)
def search_account(legal_name, host, token): res = utils.call('clientAccountSearch', {'legalName': legal_name}, 'reference-data-service', host, token) return res
def search_bank(legal_name, bct_host, bct_token): return utils.call('refBankAccountSearch', {'legalName': legal_name}, 'reference-data-service', bct_host, bct_token)
def trade_lcm_process(trade_event, ip, headers): return utils.call("trdTradeLCMEventProcess", trade_event, "trade-service", ip, headers)
def process_trade_cash(trade_id, legal_name, event_name, cash_amount, bct_host, bct_token): try: account_info = search_account(legal_name, bct_host, bct_token) print(account_info[0]) bank_info = search_bank(legal_name, bct_host, bct_token) if not bank_info: bank_dto = create_bank_account(legal_name + '开户行名称', legal_name, legal_name + '银行账号', legal_name + '银行账户名称', 'NORMAL', legal_name + '支付系统行号', bct_host, bct_token) bank_info = [bank_dto] print(bank_info[0]) bank_account = bank_info[0]['bankAccount'] print(bank_account) margin = account_info[0]['margin'] # 保证金 print('margin: ' + str(margin)) cash = account_info[0]['cash'] # 现金余额 print('cash: ' + str(cash)) debt = account_info[0]['debt'] # 负债 print('debt: ' + str(debt)) credit = account_info[0]['credit'] # 授信总额 print('credit: ' + str(credit)) credit_used = account_info[0]['creditUsed'] # 已用授信额度 print('credit(used): ' + str(credit_used)) event = _ACCOUNT_EVENT_UNWIND if event_name == 'UNWIND': event = _ACCOUNT_EVENT_UNWIND if event_name == 'SETTLE': event = _SETTLE_TRADE if event_name == 'START': event = _ACCOUNT_EVENT_START if cash_amount > 0: account_info = utils.call( 'clientSaveAccountOpRecord', { 'accountOpRecord': { "tradeId": trade_id, "accountId": legal_name + '0', "legalName": legal_name, "event": event, "status": 'NORMAL', "cashChange": cash_amount } }, 'reference-data-service', bct_host, bct_token) print(account_info) else: if abs(cash_amount) > cash: record_info = utils.call( 'clientSaveAccountOpRecord', { 'accountOpRecord': { "accountId": legal_name + '0', "legalName": legal_name, "event": 'TRADE_CASH_FLOW', "status": 'NORMAL', "cashChange": abs(cash_amount + cash), "debtChange": abs(cash_amount + cash) } }, 'reference-data-service', bct_host, bct_token) print(record_info) account_info = utils.call( 'clientSaveAccountOpRecord', { 'accountOpRecord': { "tradeId": trade_id, "accountId": legal_name + '0', "legalName": legal_name, "event": event, "status": 'NORMAL', "cashChange": cash_amount } }, 'reference-data-service', bct_host, bct_token) print(account_info) except Exception as e: print("交易资金录入未知异常process_trade_cash" + repr(e))
def import_sheet_0(ip, headers): pd_data = pd.read_csv(import_party_excel_file, encoding="gbk", dtype={'code': str}) xinhu_partys = pd_data.where(pd_data.notnull(), "空").to_dict(orient='records') # 获取bct已经存在的分公司营业部信息 bct_subsidiary_branch_map = get_bct_subsidiary_branch_map(ip, headers) bct_sales_map = get_bct_sales_map(ip, headers) print("create sales start") xinhu_sales_map = {} for xinhu_party in xinhu_partys: subsidiary = xinhu_party['bctsubsidiaryName'] branch = xinhu_party['bctbranchName'] sale = xinhu_party['bctsalesName'] list_to_sales_map(subsidiary, branch, sale, xinhu_sales_map) for subsidiary, branch_map in xinhu_sales_map.items(): bct_branchs = [] if bct_subsidiary_branch_map.get(subsidiary): bct_branchs = bct_subsidiary_branch_map.get(subsidiary) if bct_branchs: subInfo = bct_branchs[0] else: subInfo = create_subsidiary(subsidiary, ip, headers) for branch, sales_list in branch_map.items(): branchInfo = None for bct_branch in bct_branchs: if branch == bct_branch['branchName']: branchInfo = bct_branch break if not branchInfo: branchInfo = create_branch(subInfo['subsidiaryId'], branch, ip, headers) for sale in sales_list: if not check_sale_exist(subsidiary, branch, sale, bct_sales_map): create_sales(branchInfo['branchId'], sale, ip, headers) print("create sales end") bct_sales_map = get_bct_sales_map(ip, headers) # 获取bct所有交易对手 party_sales_dic = get_all_legal_sales_dic(ip, headers) party_names = list(party_sales_dic.keys()) print("create partys start") count = 0 for xinhu_party in xinhu_partys: subsidiary_name = xinhu_party['bctsubsidiaryName'] branch_name = xinhu_party['bctbranchName'] sales_name = xinhu_party['bctsalesName'] if not check_sale_exist(subsidiary_name, branch_name, sales_name, bct_sales_map): print("sale not exist sale info", subsidiary_name, branch_name, sales_name) continue try: legal_name = xinhu_party['bctlegalName'] if legal_name in party_names: print("交易对手{legal_name}已存在".format(legal_name=legal_name)) continue client_type = xinhu_party['bctClientType'] legal_representative = xinhu_party['bctlegalRepresentative'] client_level = xinhu_party['bctclientLevel'] address = xinhu_party['bctaddress'] if xinhu_party[ 'bctaddress'] and xinhu_party['bctaddress'].strip() else '空' contract = xinhu_party['bctcontract'] if xinhu_party[ 'bctcontract'] else '空' trade_phone = xinhu_party['bcttradePhone'] trade_email = xinhu_party['bcttradeEmail'] if not (xinhu_party['bctmasterAgreementId'] and xinhu_party['bctmasterAgreementId'] != '空'): print(legal_name, '主协议编号为空') master_agreementId = xinhu_party['bctmasterAgreementId'] if xinhu_party['bctmasterAgreementId'] and \ xinhu_party['bctmasterAgreementId'] != '空' else \ xinhu_party['bctlegalName'] + '主协议编号' investor_type = xinhu_party['bctinvestorType'] if master_agreementId in [ 'JR-cwqq-190125', 'JR-cwqq-190129', 'JR-cwqq-190429', 'JR-cwqq-191113' ]: # 特殊数据 以上主协议编号有重复 # print(legal_name,master_agreementId) master_agreementId = legal_name + '主协议编号' bct_party = { "legalName": legal_name, "clientType": client_type, "clientLevel": client_level, "investorType": investor_type, "legalRepresentative": legal_representative, "address": address, "salesName": sales_name, "warrantor": None, "warrantorAddress": None, "contact": contract, "tradePhone": trade_phone, "tradeEmail": trade_email, "masterAgreementId": master_agreementId, "trustorEmail": None, "supplementalAgreementId": None, "authorizeExpiryDate": None, "signAuthorizerName": None, "signAuthorizerIdNumber": None, "signAuthorizerIdExpiryDate": None, "masterAgreementNoVersion": None, "masterAgreementSignDate": None, "businessLicense": None, "productName": None, "productCode": None, "productType": None, "recordNumber": None, "productFoundDate": None, "productExpiringDate": None, "fundManager": None, "tradingDirection": None, "tradingPermission": None, "tradingPermissionNote": None, "tradingUnderlyers": None, "marginDiscountRate": None, "subsidiaryName": subsidiary_name, "branchName": branch_name, "tradeAuthorizer": [] # "tradeAuthorizer": [ # { # "tradeAuthorizerName": "0002姓名", # "tradeAuthorizerIdNumber": "411528000000000000", # "tradeAuthorizerIdExpiryDate": "2020-06-08", # "tradeAuthorizerPhone": "18800000000" # } # ] } utils.call('refPartySave', bct_party, 'reference-data-service', ip, headers) count += 1 except Exception as e: # error_msg="create party error"+repr(e)+'party name'+legal_name # if "已经存在主协议编号为" in error_msg: # print(legal_name,master_agreementId) print("create party error", repr(e), 'party name', legal_name) print("create party end") print("create party success num", str(count))
def get_all_bct_trade_dic(ip, headers): bct_trades = utils.call('trdTradeSearch', {}, 'trade-service', ip, headers) bct_trade_dic = {} for bct_trade in bct_trades: bct_trade_dic[bct_trade['tradeId']] = bct_trade return bct_trade_dic
def create_branch(subsidiary_id, branch_name, host, token): return utils.call('refBranchCreate', { 'subsidiaryId': subsidiary_id, 'branchName': branch_name }, 'reference-data-service', host, token)
def create_sales(branch_id, sales_name, host, token): return utils.call('refSalesCreate', { 'branchId': branch_id, 'salesName': sales_name }, 'reference-data-service', host, token)
def create_subsidiary(subsidiary_name, host, token): return utils.call('refSubsidiaryCreate', { 'subsidiaryName': subsidiary_name, }, 'reference-data-service', host, token)
def process_bank_cash(legal_name, cash_amount, transfer_date, bct_host, bct_token): account_info = search_account(legal_name, bct_host, bct_token) print(account_info[0]) bank_info = search_bank(legal_name, bct_host, bct_token) print(bank_info[0]) bank_account = bank_info[0]['bankAccount'] print(bank_account) margin = account_info[0]['margin'] # 保证金 print('margin: ' + str(margin)) cash = account_info[0]['cash'] # 现金余额 print('cash: ' + str(cash)) debt = account_info[0]['debt'] # 负债 print('debt: ' + str(debt)) credit = account_info[0]['credit'] # 授信总额 print('credit: ' + str(credit)) credit_used = account_info[0]['creditUsed'] # 已用授信额度 print('credit(used): ' + str(credit_used)) if cash_amount > 0: try: account_info = utils.call('cliFundEventSave', { "clientId": legal_name, "bankAccount": bank_account, "paymentAmount": cash_amount, "paymentDate": transfer_date, "paymentDirection": "IN", "accountDirection": "PARTY" }, 'reference-data-service', bct_host, bct_token) print(account_info) except Exception as e: print(repr(e)) else: try: if abs(cash_amount) > cash: record_info = utils.call('clientSaveAccountOpRecord', { 'accountOpRecord': { "accountId": legal_name + '0', "legalName": legal_name, "event": 'TRADE_CASH_FLOW', "status": 'NORMAL', "cashChange": abs(cash_amount + cash), "debtChange": abs(cash_amount + cash) } }, 'reference-data-service', bct_host, bct_token) print(record_info) account_info = utils.call('cliFundEventSave', { "clientId": legal_name, "bankAccount": bank_account, "paymentAmount": abs(cash_amount), "paymentDate": transfer_date, "paymentDirection": "OUT", "accountDirection": "PARTY" }, 'reference-data-service', bct_host, bct_token) print(account_info) except Exception as e: print(repr(e))