| | |
| | | import logging |
| | | import socketserver |
| | | from http.server import BaseHTTPRequestHandler |
| | | import cv2 |
| | | import numpy |
| | | |
| | | import constant |
| | | from utils import ths_industry_util |
| | |
| | | datas = self.ocr_temp_data[matId] |
| | | if rows * cols == len(datas): |
| | | self.ocr_temp_data.pop(matId) |
| | | mat = cv2.numpy.zeros((rows, cols, 1), cv2.numpy.uint8) |
| | | mat = numpy.zeros((rows, cols, 1), numpy.uint8) |
| | | for r in range(0, rows): |
| | | for c in range(0, cols): |
| | | mat[r][c] = [datas[r * cols + c]] |
| | |
| | | datas = self.ocr_temp_data[matId] |
| | | if rows * cols == len(datas): |
| | | self.ocr_temp_data.pop(matId) |
| | | mat = cv2.numpy.zeros((rows, cols, 1), cv2.numpy.uint8) |
| | | mat = numpy.zeros((rows, cols, 1), numpy.uint8) |
| | | for r in range(0, rows): |
| | | for c in range(0, cols): |
| | | mat[r][c] = [datas[r * cols + c]] |
| | |
| | | logger.add(self.get_path("contact", "debug"), |
| | | filter=lambda record: record["extra"].get("name") == "debug", |
| | | rotation="00:00", compression="zip", enqueue=True) |
| | | |
| | | logger.add(self.get_path("trade", "trade_callback"), |
| | | filter=lambda record: record["extra"].get("name") == "trade_callback", |
| | | rotation="00:00", compression="zip", enqueue=True) |
| | | logger.add(self.get_path("trade", "debug"), |
| | | filter=lambda record: record["extra"].get("name") == "trade_debug", |
| | | rotation="00:00", compression="zip", enqueue=True) |
| | | |
| | | def get_path(self, dir_name, log_name): |
| | | return "/home/userzjj/logs/{}/{}".format(dir_name, log_name) + ".{time:YYYY-MM-DD}.log" |
| | | return "/home/logs/huaxin/{}/{}".format(dir_name, log_name) + ".{time:YYYY-MM-DD}.log" |
| | | |
| | | def get_logger(self, log_name): |
| | | return logger.bind(name=log_name) |
| | |
| | | logger_l2_orderdetail = __mylogger.get_logger("orderdetail") |
| | | logger_l2_upload = __mylogger.get_logger("upload") |
| | | logger_l2_error = __mylogger.get_logger("error") |
| | | logger_contact_debug = __mylogger.get_logger("debug") |
| | | logger_contact_debug = __mylogger.get_logger("debug") |
| | | logger_trade_callback = __mylogger.get_logger("trade_callback") |
| | | logger_trade_debug = __mylogger.get_logger("trade_debug") |
| | |
| | | |
| | | # 委托记录 |
| | | import datetime |
| | | import json |
| | | |
| | | from utils import tool |
| | | from db import mysql_data |
| | | from db import mysql_data, redis_manager |
| | | from third_data.history_k_data_util import HistoryKDatasUtils |
| | | |
| | | |
| | | # 委托列表 |
| | | class DelegateRecordManager: |
| | | @classmethod |
| | | def add(cls, datas): |
| | |
| | | pass |
| | | |
| | | |
| | | # 持仓记录 |
| | | class PositionManager: |
| | | @classmethod |
| | | def add(cls, datas): |
| | | mysqldb = mysql_data.Mysqldb() |
| | | try: |
| | | if datas: |
| | | for d in datas: |
| | | _id = f"{d['investorID']}-{d['tradingDay']}-{d['securityID']}" |
| | | # 查询是否有数据 |
| | | result = mysqldb.select_one( |
| | | f"select * from hx_trade_position where id='{_id}'") |
| | | if not result: |
| | | # 新增数据 |
| | | mysqldb.execute( |
| | | "insert into hx_trade_position values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % ( |
| | | _id, d["tradingDay"], d["investorID"], d["securityName"], d["securityID"], |
| | | d["historyPos"], d["historyPosFrozen"], d["todayBSPos"], d["todayBSPosFrozen"], |
| | | d["historyPosPrice"], |
| | | d["totalPosCost"], d["prePosition"], d["availablePosition"], d["currentPosition"], |
| | | d["openPosCost"], |
| | | d["todayCommission"], d["todayTotalBuyAmount"], d["todayTotalSellAmount"], |
| | | tool.get_now_datetime_str(), |
| | | tool.get_now_datetime_str())) |
| | | else: |
| | | # 修改数据 |
| | | updateDict = {} |
| | | if result[5] != d['historyPos']: |
| | | updateDict['historyPos'] = d['historyPos'] |
| | | if result[6] != d['historyPosFrozen']: |
| | | updateDict['historyPosFrozen'] = d['historyPosFrozen'] |
| | | if result[7] != d['todayBSPos']: |
| | | updateDict['todayBSPos'] = d['todayBSPos'] |
| | | if result[8] != d['todayBSPosFrozen']: |
| | | updateDict['todayBSPosFrozen'] = d['todayBSPosFrozen'] |
| | | if result[9] != f"{d['historyPosPrice']}": |
| | | updateDict['historyPosPrice'] = d['historyPosPrice'] |
| | | if result[10] != f"{d['totalPosCost']}": |
| | | updateDict['totalPosCost'] = d['totalPosCost'] |
| | | if result[11] != d['prePosition']: |
| | | updateDict['prePosition'] = d['prePosition'] |
| | | if result[12] != d['availablePosition']: |
| | | updateDict['availablePosition'] = d['availablePosition'] |
| | | if result[13] != d['currentPosition']: |
| | | updateDict['currentPosition'] = d['currentPosition'] |
| | | if result[14] != f"{d['openPosCost']}": |
| | | updateDict['openPosCost'] = d['openPosCost'] |
| | | if result[15] != f"{d['todayCommission']}": |
| | | updateDict['todayCommission'] = d['todayCommission'] |
| | | if result[16] != f"{d['todayTotalBuyAmount']}": |
| | | updateDict['todayTotalBuyAmount'] = d['todayTotalBuyAmount'] |
| | | if result[17] != f"{d['todayTotalSellAmount']}": |
| | | updateDict['todayTotalSellAmount'] = d['todayTotalSellAmount'] |
| | | if updateDict: |
| | | # 有更新数据 |
| | | updateDict['updateTime'] = tool.get_now_datetime_str() |
| | | where_list = [] |
| | | for k in updateDict: |
| | | if type(updateDict[k]) == str: |
| | | where_list.append(f"{k}='{updateDict[k]}'") |
| | | else: |
| | | where_list.append(f"{k}={updateDict[k]}") |
| | | mysqldb.execute( |
| | | f"update hx_trade_position set {','.join(where_list)} where id='{result[0]}'") |
| | | finally: |
| | | pass |
| | | |
| | | @classmethod |
| | | def list_by_day(cls, day): |
| | | mysqldb = mysql_data.Mysqldb() |
| | | try: |
| | | results = mysqldb.select_all( |
| | | f"select * from hx_trade_position r where r.tradingDay='{day}' order by createTime") |
| | | # 转dict |
| | | key_list = ["id", "investorID", "securityName", "securityID", "historyPos", "historyPosFrozen", |
| | | "todayBSPos", "todayBSPosFrozen", "historyPosPrice", "totalPosCost", "prePosition", |
| | | "availablePosition", "currentPosition", |
| | | "openPosCost", "todayCommission", "todayTotalBuyAmount", "todayTotalSellAmount", "createTime", |
| | | "updateTime"] |
| | | fresults = [] |
| | | |
| | | if results: |
| | | for r in results: |
| | | temp = {} |
| | | for i in range(len(r)): |
| | | if type(r[i]) == datetime.datetime: |
| | | temp[key_list[i]] = r[i].strftime("%Y-%m-%d %H:%M:%S") |
| | | else: |
| | | temp[key_list[i]] = r[i] |
| | | fresults.append(temp) |
| | | return fresults |
| | | finally: |
| | | pass |
| | | |
| | | |
| | | # 成交记录 |
| | | class DealRecordManager: |
| | | pass |
| | | @classmethod |
| | | def add(cls, datas): |
| | | mysqldb = mysql_data.Mysqldb() |
| | | try: |
| | | if datas: |
| | | for d in datas: |
| | | # 查询是否有数据 |
| | | result = mysqldb.select_one( |
| | | f"select * from hx_trade_deal_record where id='{d['tradeID']}'") |
| | | if not result: |
| | | # 新增数据 |
| | | mysqldb.execute( |
| | | "insert into hx_trade_deal_record values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % ( |
| | | d["tradeID"], d["securityID"], d["orderLocalID"], d["direction"], |
| | | d["orderSysID"], d["price"], d["tradeTime"], d["volume"], |
| | | d["tradeDate"], |
| | | d["tradingDay"], d["pbuID"], d["accountID"], |
| | | tool.get_now_datetime_str(), |
| | | tool.get_now_datetime_str())) |
| | | finally: |
| | | pass |
| | | |
| | | @classmethod |
| | | def list_by_day(cls, day): |
| | | mysqldb = mysql_data.Mysqldb() |
| | | try: |
| | | results = mysqldb.select_all( |
| | | f"select * from hx_trade_deal_record r where r.tradeID='{day}' order by createTime") |
| | | # 转dict |
| | | key_list = ["tradeID", "securityID", "orderLocalID", "direction", "orderSysID", "price", |
| | | "tradeTime", "volume", "tradeDate", "tradingDay", "pbuID", |
| | | "accountID", "createTime", |
| | | "updateTime"] |
| | | fresults = [] |
| | | if results: |
| | | for r in results: |
| | | temp = {} |
| | | for i in range(len(r)): |
| | | if type(r[i]) == datetime.datetime: |
| | | temp[key_list[i]] = r[i].strftime("%Y-%m-%d %H:%M:%S") |
| | | else: |
| | | temp[key_list[i]] = r[i] |
| | | fresults.append(temp) |
| | | return fresults |
| | | finally: |
| | | pass |
| | | |
| | | |
| | | |
| | | # 资金管理 |
| | | class MoneyManager: |
| | | __redisMananger = redis_manager.RedisManager(2) |
| | | |
| | | @classmethod |
| | | def get_redis(cls): |
| | | return cls.__redisMananger.getRedis() |
| | | |
| | | @classmethod |
| | | def save_data(cls, data): |
| | | cls.get_redis().setex("huaxin_money", tool.get_expire(), json.dumps(data)) |
| | | |
| | | @classmethod |
| | | def get_data(cls): |
| | | val = cls.get_redis().get("huaxin_money") |
| | | if not val: |
| | | return None |
| | | return json.loads(val) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | |
| | | import hashlib |
| | | import json |
| | | import logging |
| | | import queue |
| | | import random |
| | | import socket |
| | | import socketserver |
| | | import threading |
| | | import time |
| | | |
| | | import constant |
| | | from trade.huaxin.huaxin_log import logger_l2_orderdetail, logger_l2_transaction, logger_l2_upload, logger_contact_debug |
| | | from trade.huaxin.huaxin_log import logger_l2_orderdetail, logger_l2_transaction, logger_l2_upload, \ |
| | | logger_contact_debug, logger_trade_callback, logger_trade_debug |
| | | |
| | | from trade.huaxin import huaxin_trade_api as trade_api |
| | | from utils import socket_util |
| | | from trade.huaxin import huaxin_trade_api as trade_api, huaxin_trade_api, huaxin_trade_record_manager |
| | | from utils import socket_util, tool |
| | | |
| | | trade_data_request_queue = queue.Queue() |
| | | |
| | | |
| | | class MyTCPServer(socketserver.TCPServer): |
| | |
| | | elif data_json["type"] == "response": |
| | | # 主动触发的响应 |
| | | client_id = data_json["client_id"] |
| | | |
| | | # 设置响应内容 |
| | | trade_api.set_response(client_id, data_json["request_id"], data_json['data']) |
| | | sk.sendall(json.dumps({"code": 0}).encode(encoding='utf-8')) |
| | | elif data_json["type"] == "trade_callback": |
| | | # 交易回调 |
| | | data_json = data_json["data"] |
| | | type_ = data_json["type"] |
| | | # 记录交易反馈日志 |
| | | logger_trade_callback.info(data_json) |
| | | sk.sendall(json.dumps({"code": 0}).encode(encoding='utf-8')) |
| | | # 重新请求委托列表与资金 |
| | | trade_data_request_queue.put_nowait({"type": "delegate_list"}) |
| | | trade_data_request_queue.put_nowait({"type": "money"}) |
| | | trade_data_request_queue.put_nowait({"type": "deal_list"}) |
| | | # print("响应结果:", data_json['data']) |
| | | elif data_json["type"] == "l2_order": |
| | | # L2逐笔委托 |
| | |
| | | # 验证签名 |
| | | if not socket_util.is_client_params_sign_right(data_json): |
| | | sk.sendall( |
| | | socket_util.load_header(json.dumps({"code": constant.RESPONSE_CODE_SIGIN_ERROR, "msg": "签名错误"}).encode("utf-8"))) |
| | | socket_util.load_header( |
| | | json.dumps({"code": constant.RESPONSE_CODE_SIGIN_ERROR, "msg": "签名错误"}).encode( |
| | | "utf-8"))) |
| | | continue |
| | | |
| | | codes_data = data_json["data"] |
| | |
| | | socket_util.load_header( |
| | | json.dumps({"code": 1, "msg": str(e)}).encode( |
| | | "utf-8"))) |
| | | |
| | | |
| | | elif data_json["type"] == 'sell': |
| | | # 验证签名 |
| | |
| | | price_type=price_type) |
| | | print("---卖出结果----") |
| | | print(result) |
| | | |
| | | # 查询委托列表 |
| | | elif data_json["type"] == 'test': |
| | | # 卖出 |
| | | # trade_api.order(trade_api.TRADE_DIRECTION_SELL, "600854", 100, 5.45) |
| | |
| | | super().finish() |
| | | |
| | | |
| | | def read_trade_data_queue(): |
| | | while True: |
| | | try: |
| | | data = trade_data_request_queue.get() |
| | | if data: |
| | | type_ = data["type"] |
| | | logger_trade_debug.info(f"获取交易数据开始:{type_}") |
| | | |
| | | if type_ == "delegate_list": |
| | | data = huaxin_trade_api.get_delegate_list(False) |
| | | dataJSON = json.loads(data) |
| | | if dataJSON["data"]["code"] == 0: |
| | | data = dataJSON["data"]["data"] |
| | | huaxin_trade_record_manager.DelegateRecordManager.add(data) |
| | | elif type_ == "money": |
| | | data = huaxin_trade_api.get_money() |
| | | dataJSON = json.loads(data) |
| | | if dataJSON["data"]["code"] == 0: |
| | | data = dataJSON["data"]["data"] |
| | | huaxin_trade_record_manager.MoneyManager.save_data(data) |
| | | elif type_ == "deal_list": |
| | | data = huaxin_trade_api.get_deal_list() |
| | | dataJSON = json.loads(data) |
| | | if dataJSON["data"]["code"] == 0: |
| | | data = dataJSON["data"]["data"] |
| | | huaxin_trade_record_manager.DealRecordManager.add(data) |
| | | |
| | | logger_trade_debug.info(f"获取交易数据成功:{type_}") |
| | | except Exception as e: |
| | | logger_trade_debug.exception(e) |
| | | finally: |
| | | # 有1s的间隔 |
| | | time.sleep(1) |
| | | |
| | | |
| | | def run(): |
| | | t1 = threading.Thread(target=lambda: read_trade_data_queue()) |
| | | # 后台运行 |
| | | t1.setDaemon(True) |
| | | t1.start() |
| | | |
| | | laddr = "0.0.0.0", 10008 |
| | | tcpserver = MyThreadingTCPServer(laddr, MyBaseRequestHandle) # 注意:参数是MyBaseRequestHandle |
| | | # tcpserver.handle_request() # 只接受一个客户端连接 |
| | |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | |
| | | run() |
| | | # ClientSocketManager.add_client(ClientSocketManager.CLIENT_TYPE_TRADE, "1", None) |
| | | # ClientSocketManager.add_client(ClientSocketManager.CLIENT_TYPE_TRADE, "2", None) |