更改包结构/动态引入windows平台依赖的相关包
6个文件已删除
21 文件已重命名
42个文件已修改
8个文件已添加
File was renamed from big_money_num_manager.py |
| | |
| | | |
| | | # 大单管理 |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | |
| | | __redisManager = redis_manager.RedisManager(0) |
| | | |
File was renamed from code_data_util.py |
| | |
| | | import decimal |
| | | import time |
| | | |
| | | import gpcode_manager |
| | | from code_attribute import gpcode_manager |
| | | from db import mysql_data, redis_manager |
| | | import tool |
| | | from utils import tool |
| | | |
| | | _redisManager = redis_manager.RedisManager(0) |
| | | |
File was renamed from code_nature_analyse.py |
| | |
| | | import copy |
| | | import json |
| | | |
| | | import gpcode_manager |
| | | from code_attribute import gpcode_manager |
| | | |
| | | # 代码股性记录管理 |
| | | import tool |
| | | from utils import tool |
| | | from db.redis_manager import RedisManager |
| | | |
| | | |
File was renamed from code_volumn_manager.py |
| | |
| | | # yesterday 昨天的量 |
| | | import json |
| | | |
| | | import global_util |
| | | import gpcode_manager |
| | | from utils import global_util, tool |
| | | from db import redis_manager |
| | | import tool |
| | | from log import logger_day_volumn |
| | | from logs.log import logger_day_volumn |
| | | |
| | | __redis_manager = redis_manager.RedisManager(0) |
| | | |
| | |
| | | # 设置历史量 |
| | | def set_histry_volumn(code, max60, yesterday, max60_day=''): |
| | | redis = __redis_manager.getRedis() |
| | | global_util.max60_volumn[code] = (max60,max60_day) |
| | | global_util.max60_volumn[code] = (max60, max60_day) |
| | | global_util.yesterday_volumn[code] = yesterday |
| | | redis.setex("volumn_max60-{}".format(code), tool.get_expire(), json.dumps((max60,max60_day))) |
| | | redis.setex("volumn_max60-{}".format(code), tool.get_expire(), json.dumps((max60, max60_day))) |
| | | redis.setex("volumn_yes-{}".format(code), tool.get_expire(), yesterday) |
| | | |
| | | |
File was renamed from global_data_loader.py |
| | |
| | | import code_volumn_manager |
| | | import global_util |
| | | import gpcode_manager |
| | | import ths_industry_util |
| | | from code_data_util import ZYLTGBUtil |
| | | from code_attribute import code_volumn_manager, gpcode_manager |
| | | from utils import global_util, ths_industry_util |
| | | from code_attribute.code_data_util import ZYLTGBUtil |
| | | |
| | | |
| | | def init(): |
File was renamed from gpcode_first_screen_manager.py |
| | |
| | | # 设置首板未筛选的目标票 |
| | | import json |
| | | |
| | | import tool |
| | | from utils import tool |
| | | from db import redis_manager |
| | | from third_data import block_info |
| | | |
File was renamed from gpcode_manager.py |
| | |
| | | 股票代码管理器 |
| | | """ |
| | | import json |
| | | import random |
| | | import time |
| | | |
| | | import client_manager |
| | | import constant |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | import decimal |
| | | |
| | | from ths import l2_listen_pos_health_manager |
| | | from ths import l2_listen_pos_health_manager, client_manager |
| | | |
| | | __redisManager = redis_manager.RedisManager(0) |
| | | |
File was renamed from industry_codes_sort.py |
| | |
| | | # 板块强度排序,根据当前时间是否涨停,涨停时间排序 |
| | | import functools |
| | | |
| | | import global_util |
| | | import limit_up_time_manager |
| | | from utils import global_util |
| | | from code_attribute import limit_up_time_manager |
| | | from trade import trade_data_manager |
| | | |
| | | __codeActualPriceProcessor = trade_data_manager.CodeActualPriceProcessor() |
File was renamed from limit_up_time_manager.py |
| | |
| | | 涨停时间管理器 |
| | | """ |
| | | from db import redis_manager |
| | | import tool |
| | | import global_util |
| | | from utils import global_util, tool |
| | | |
| | | _redisManager = redis_manager.RedisManager(0) |
| | | |
| | |
| | | # 是否为测试 |
| | | import platform |
| | | |
| | | TEST = False |
| | | # 是否允许交易 |
| | | TRADE_ENABLE = True |
| | | |
| | | # 签名错误 |
| | | RESPONSE_CODE_SIGIN_ERROR = 1001 |
| | | |
| | | # 是否需要报警 |
| | | NEED_ALERT = False |
| | | |
| | | |
| | | def is_windows(): |
| | | system = platform.system() |
| | | if system == 'Windows': |
| | | return True |
| | | return False |
| | | |
| | | |
| | | # 获取根路径 |
| | | def get_path_prefix(): |
| | | return 'D:' if is_windows() else '/home' |
| | | |
| | | |
| | | # 水下捞累计连续水下时间最小值 |
| | | UNDER_WATER_PRICE_TIME_AS_SECONDS = 1200 |
| | |
| | | # 大单笔数 |
| | | BIG_MONEY_NUM = 7888 |
| | | |
| | | CACHE_PATH = "D:/trade_cache" |
| | | CACHE_PATH = f"{'D:' if is_windows() else '/home'}/trade_cache" |
| | | |
| | | # S撤比例 |
| | | S_CANCEL_MIN_MONEY = 98 |
| | |
| | | L_CANCEL_RATE = 0.6 |
| | | # 最小金额 |
| | | L_CANCEL_MIN_MONEY = 98 |
| | | |
| | | # 掘金本地API |
| | | JUEJIN_LOCAL_API = True |
| | |
| | | # 调用获取游标的方法 |
| | | self.cursor = self.get_cursor() |
| | | |
| | | def close(self): |
| | | self.conn.close() |
| | | |
| | | # 连接数据库的方法 |
| | | def get_conn(self): |
| | | # **config代表不定长参数 |
| | |
| | | |
| | | import win32gui |
| | | |
| | | import data_export_util |
| | | from utils import data_export_util |
| | | import multiprocessing |
| | | |
| | | import log |
| | | from logs import log |
| | | from db import mysql_data, redis_manager |
| | | import server |
| | | import settings |
| | | from config import settings |
| | | from ths.l2_code_operate import L2CodeOperate |
| | | from trade.l2_trade_factor import L2TradeFactorUtil |
| | | from ocr import ocr_server |
| | |
| | | sv_num.set("获取到收盘价数量:{}".format(count)) |
| | | |
| | | def re_get_close_price(): |
| | | init.re_set_price_pres(gpcode_manager.get_gp_list()) |
| | | inited_data.re_set_price_pres(gpcode_manager.get_gp_list()) |
| | | |
| | | def get_limit_up_codes_win(): |
| | | width = 500 |
| | |
| | | win.mainloop() |
| | | |
| | | def init(): |
| | | init.everyday_init() |
| | | inited_data.everyday_init() |
| | | |
| | | def set_accept_l2(): |
| | | settings.set_accept_l2(accept_l2.get()) |
| | |
| | | if len(account.strip()) < 1 or len(sid.strip()) < 1 or len(token.strip()) < 1: |
| | | showinfo('提示', "数据不完整") |
| | | return |
| | | init.setAccountInfo(account, sid, token) |
| | | inited_data.setAccountInfo(account, sid, token) |
| | | showinfo('提示', "设置成功") |
| | | |
| | | # 设置掘金信息 |
| | |
| | | frame.grid(row=0, column=2, pady=5, padx=5) |
| | | |
| | | # 设置参数 |
| | | account, sid, token = init.getAccountInfo() |
| | | account, sid, token = inited_data.getAccountInfo() |
| | | account_var.set(account) |
| | | sid_var.set(sid) |
| | | token_var.set(token) |
File was renamed from init.py |
| | |
| | | |
| | | from __future__ import print_function, absolute_import |
| | | |
| | | import time as t |
| | | |
| | | import schedule |
| | | |
| | | import gm.api as gmapi |
| | | |
| | | import big_money_num_manager |
| | | import client_manager |
| | | from code_attribute import big_money_num_manager, global_data_loader, gpcode_manager, gpcode_first_screen_manager |
| | | from ths import client_manager |
| | | import constant |
| | | import global_data_loader |
| | | import global_util |
| | | import gpcode_first_screen_manager |
| | | import gpcode_manager |
| | | from utils import global_util, tool |
| | | import threading |
| | | |
| | | import server |
| | | import tool |
| | | |
| | | from db import redis_manager |
| | | import authority |
| | | from user import authority |
| | | import decimal |
| | | |
| | | from third_data.history_k_data_util import HistoryKDatasUtils |
| | | from trade import trade_gui, l2_trade_util, trade_manager |
| | | from trade import l2_trade_util, trade_manager |
| | | from l2.cancel_buy_strategy import L2LimitUpSellStatisticUtil, LCancelBigNumComputer |
| | | from log import logger_juejin_tick, logger_system |
| | | from logs.log import logger_juejin_tick, logger_system |
| | | from trade.trade_data_manager import CodeActualPriceProcessor |
| | | from trade.trade_queue_manager import JueJinBuy1VolumnManager |
| | | |
| | |
| | | |
| | | if __name__ == '__main__': |
| | | # init_data()+ |
| | | pass |
| | | init(None) |
| | |
| | | import logging |
| | | import time |
| | | |
| | | import big_money_num_manager |
| | | from code_attribute import big_money_num_manager, gpcode_manager |
| | | import constant |
| | | import gpcode_manager |
| | | import l2_data_util |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | from l2.safe_count_manager import BuyL2SafeCountManager |
| | | from l2.transaction_progress import TradeBuyQueue |
| | | from output import kp_client_msg_manager |
| | | from trade import trade_data_manager, trade_queue_manager, l2_trade_factor |
| | | from l2 import l2_log, l2_data_log, l2_data_source_util |
| | | from l2.l2_data_util import L2DataUtil, local_today_num_operate_map, local_today_datas |
| | | from log import logger_buy_1_volumn, logger_l2_h_cancel, logger_l2_s_cancel |
| | | from logs.log import logger_buy_1_volumn, logger_l2_h_cancel, logger_l2_s_cancel |
| | | |
| | | |
| | | class SecondCancelBigNumComputer: |
| | |
| | | cancel_rate_threshold) |
| | | return True, data |
| | | |
| | | rate__ = round(cancel_num / total_nums, 4) |
| | | if rate__ > cancel_rate_threshold: |
| | | indexs__ = list(watch_indexs_dict.keys()) |
| | | indexs__.sort() |
| | | l2_log.trade_record(code, "H撤范围", "'start_index':{},'end_index':{}, 'count':{}", |
| | | indexs__[0], indexs__[-1], |
| | | len(watch_indexs_dict.keys())) |
| | | l2_log.trade_record(code, "H撤", "'index':{} , 'rate':{} ,'target_rate':{}", i, rate__, |
| | | cancel_rate_threshold) |
| | | return True, data |
| | | |
| | | finally: |
| | | l2_log.cancel_debug(code, "H级撤单计算结果 范围:{}-{} 处理进度:{} 取消计算结果:{}/{} 目标撤单比例:{}", start_index, end_index, |
| | | process_index, cancel_num, |
| | |
| | | """ |
| | | import json |
| | | |
| | | import tool |
| | | from utils import tool |
| | | from db import redis_manager |
| | | from log import logger_trade_queue_price_info |
| | | from logs.log import logger_trade_queue_price_info |
| | | |
| | | |
| | | class Buy1PriceManager: |
| | |
| | | # item逐笔委托 |
| | | # (data['SecurityID'], data['Price'], data['Volume'], data['Side'], data['OrderType'], |
| | | # data['OrderTime'],data['MainSeq'], data['SubSeq'], data['OrderNO'], data['OrderStatus']) |
| | | import decimal |
| | | |
| | | import tool |
| | | from l2.l2_data_util import L2DataUtil |
| | | |
| | | |
| | | def __convert_order(item, limit_up_price): |
| | |
| | | # l2数据的日志 |
| | | import time |
| | | |
| | | import log |
| | | from logs import log |
| | | from l2 import l2_log |
| | | |
| | | |
| | |
| | | import json |
| | | |
| | | from db import redis_manager |
| | | import tool |
| | | from log import logger_l2_trade_buy |
| | | from utils import tool |
| | | from logs.log import logger_l2_trade_buy |
| | | |
| | | _redisManager = redis_manager.RedisManager(1) |
| | | |
| | |
| | | import logging |
| | | import random |
| | | import time as t |
| | | |
| | | import big_money_num_manager |
| | | import code_data_util |
| | | import code_volumn_manager |
| | | from code_attribute import big_money_num_manager, code_volumn_manager, code_data_util, industry_codes_sort, \ |
| | | limit_up_time_manager, global_data_loader, gpcode_manager |
| | | import constant |
| | | import global_data_loader |
| | | import global_util |
| | | import gpcode_manager |
| | | import industry_codes_sort |
| | | from utils import global_util, ths_industry_util, tool |
| | | import l2_data_util |
| | | import limit_up_time_manager |
| | | from db import redis_manager |
| | | import ths_industry_util |
| | | import tool |
| | | from l2.huaxin import l2_huaxin_util |
| | | from third_data.code_plate_key_manager import CodePlateKeyBuyManager |
| | | from trade import trade_manager, trade_queue_manager, l2_trade_factor, l2_trade_util, \ |
| | | trade_result_manager, first_code_score_manager |
| | |
| | | from l2.l2_data_manager import L2DataException, TradePointManager |
| | | from l2.l2_data_util import local_today_datas, L2DataUtil, local_today_num_operate_map,local_today_buyno_map, local_latest_datas |
| | | import l2.l2_data_util |
| | | from log import logger_l2_trade_buy, logger_l2_process, \ |
| | | from logs.log import logger_l2_trade_buy, logger_l2_process, \ |
| | | logger_place_order_score |
| | | |
| | | # TODO l2数据管理 |
| | |
| | | if not plate_can_buy: |
| | | return False, True, msg |
| | | |
| | | if volume_rate_info[0] < 0.4: |
| | | return False, True, f"量大于40%才下单,量比:{volume_rate_info[0]}" |
| | | # if volume_rate_info[0] < 0.4: |
| | | # return False, True, f"量大于40%才下单,量比:{volume_rate_info[0]}" |
| | | |
| | | # 是否有K线形态(有K线形态或者天量大阳) |
| | | has_k_format = score_info[1][3][6][0] or score_info[1][3][7][0] |
| | |
| | | """ |
| | | L2数据溯源 |
| | | """ |
| | | import tool |
| | | from utils import tool |
| | | |
| | | |
| | | class L2DataSourceUtils(object): |
| | |
| | | import numpy |
| | | |
| | | import constant |
| | | import gpcode_manager |
| | | import l2_data_util |
| | | from code_attribute import gpcode_manager |
| | | from l2 import l2_data_log, l2_data_source_util |
| | | import log |
| | | from logs import log |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | |
| | | _redisManager = redis_manager.RedisManager(1) |
| | | # l2数据管理 |
| | |
| | | from log import logger_l2_trade_cancel, logger_l2_trade_buy, logger_trade_record, logger_l2_trade |
| | | from logs.log import logger_l2_trade_cancel, logger_l2_trade_buy, logger_trade_record, logger_l2_trade |
| | | |
| | | threadIds = {} |
| | | |
| | |
| | | from l2 import l2_data_source_util |
| | | from trade import l2_trade_factor |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | from l2.l2_data_util import L2DataUtil |
| | | import l2_data_util |
| | | |
| | | |
| | | class BuyL2SafeCountManager(object): |
| | |
| | | |
| | | import constant |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | import l2.l2_data_util |
| | | from log import logger_l2_trade_buy_queue, logger_l2_trade_buy_progress |
| | | from logs.log import logger_l2_trade_buy_queue, logger_l2_trade_buy_progress |
| | | |
| | | |
| | | class TradeBuyQueue: |
| | |
| | | # 比较时间的大小 |
| | | import json |
| | | import time |
| | | from tool import async_call |
| | | from utils.tool import async_call |
| | | |
| | | from l2 import l2_data_manager |
| | | import tool |
| | | from utils import tool |
| | | |
| | | |
| | | def run_time(): |
New file |
| | |
| | | """ |
| | | GUI管理 |
| | | """ |
| | | |
| | | import multiprocessing |
| | | |
| | | |
| | | from trade.huaxin import trade_server |
| | | from ocr import ocr_server |
| | | from third_data import data_server |
| | | |
| | | from server import * |
| | | import l2.l2_data_util |
| | | |
| | | |
| | | |
| | | def __read_server_pipe(pipe): |
| | | if pipe: |
| | | while True: |
| | | value = pipe.recv() |
| | | if value is not None: |
| | | value = json.loads(value) |
| | | if value.get("type") == "clear_l2": |
| | | code = value["data"]["code"] |
| | | print("清除l2数据", code) |
| | | if len(code) != 6: |
| | | continue |
| | | l2_data_manager.clear_l2_data(code) |
| | | # 删除level2的数据 |
| | | if l2.l2_data_util.local_today_datas and code in l2.l2_data_util.local_today_datas: |
| | | l2.l2_data_util.local_today_datas.pop(code) |
| | | if l2.l2_data_util.local_latest_datas and code in l2.l2_data_util.local_latest_datas: |
| | | l2.l2_data_util.local_latest_datas.pop(code) |
| | | |
| | | time.sleep(0.1) |
| | | |
| | | |
| | | # 交易服务 |
| | | def createTradeServer(): |
| | | print("create TradeServer") |
| | | # 初始化参数 |
| | | global_data_loader.init() |
| | | |
| | | t1 = threading.Thread(target=createDataServer) |
| | | # 后台运行 |
| | | t1.setDaemon(True) |
| | | t1.start() |
| | | |
| | | trade_server.run() |
| | | |
| | | |
| | | # 主服务 |
| | | def createServer(pipe_juejin, pipe_gui): |
| | | print("create Server") |
| | | |
| | | t1 = threading.Thread(target=lambda: __read_server_pipe(pipe_gui)) |
| | | # 后台运行 |
| | | t1.setDaemon(True) |
| | | t1.start() |
| | | |
| | | laddr = "", 9001 |
| | | tcpserver = MyThreadingTCPServer(laddr, MyBaseRequestHandle, pipe_juejin=pipe_juejin) # 注意:参数是MyBaseRequestHandle |
| | | # tcpserver.handle_request() # 只接受一个客户端连接 |
| | | tcpserver.serve_forever() # 永久循环执行,可以接受多个客户端连接 |
| | | |
| | | |
| | | # 识别服务 |
| | | def createOCRServer(): |
| | | print("create OCRServer") |
| | | tcpserver = ocr_server.run("", 9002) |
| | | tcpserver.serve_forever() |
| | | |
| | | |
| | | def createDataServer(): |
| | | print("create DataServer") |
| | | tcpserver = data_server.run("", 9004) |
| | | tcpserver.serve_forever() |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | #tradeServerProcess = multiprocessing.Process(target=createTradeServer) |
| | | serverProcess = multiprocessing.Process(target=createServer, args=(None, None,)) |
| | | jueJinTradeProcess = multiprocessing.Process(target=trade_juejin.run) |
| | | ocrServerProcess = multiprocessing.Process(target=createOCRServer) |
| | | |
| | | #tradeServerProcess.start() |
| | | serverProcess.start() |
| | | ocrServerProcess.start() |
| | | jueJinTradeProcess.start() |
| | | # 将tradeServer作为主进程 |
| | | createTradeServer() |
| | |
| | | from http.server import BaseHTTPRequestHandler |
| | | import cv2 |
| | | |
| | | import ths_industry_util |
| | | import constant |
| | | from utils import ths_industry_util |
| | | from ocr import ocr_util |
| | | from ocr.ocr_util import OcrUtil |
| | | from third_data import kpl_util |
| | | from trade import bidding_money_manager |
| | | |
| | |
| | | for r in range(0, rows): |
| | | for c in range(0, cols): |
| | | mat[r][c] = [datas[r * cols + c]] |
| | | # cv2.imwrite("D:/test.png", mat) |
| | | # cv2.imwrite(f"{constant.get_path_prefix()}/test.png", mat) |
| | | ocr_results = ocr_util.OcrUtil.ocr_with_key(mat, key) |
| | | if not ocr_results: |
| | | # 多重识别,防止识别出错 |
| | |
| | | for r in range(0, rows): |
| | | for c in range(0, cols): |
| | | mat[r][c] = [datas[r * cols + c]] |
| | | # cv2.imwrite("D:/test.png", mat) |
| | | # cv2.imwrite(f"{constant.get_path_prefix()}/test.png", mat) |
| | | ocr_results = ocr_util.OcrUtil.ocr_with_key(mat, ".") |
| | | code_name = "" |
| | | for res in ocr_results: |
| | |
| | | kpl_datas = kpl_util.parse_kpl_datas(results) |
| | | if kpl_datas: |
| | | bidding_money_manager.set_bidding_money(kpl_datas) |
| | | with open("D:/kpl.png", mode="wb") as f: |
| | | with open(f"{constant.get_path_prefix()}/kpl.png", mode="wb") as f: |
| | | f.write(imgdata) |
| | | except Exception as e: |
| | | logging.exception(e) |
| | |
| | | # 下单参数信息 |
| | | # 选股宝 |
| | | # 市场热度 |
| | | import os |
| | | import sys |
| | | import time |
| | | |
| | | import code_volumn_manager |
| | | import code_attribute |
| | | from code_attribute import code_volumn_manager, limit_up_time_manager, global_data_loader, gpcode_manager |
| | | import constant |
| | | import global_data_loader |
| | | import global_util |
| | | import gpcode_manager |
| | | import limit_up_time_manager |
| | | import log |
| | | import tool |
| | | from utils import global_util, tool |
| | | from logs import log |
| | | from l2 import l2_data_manager, l2_data_util, transaction_progress, l2_data_manager_new, code_price_manager |
| | | from l2.cancel_buy_strategy import HourCancelBigNumComputer |
| | | import l2.l2_data_manager_new |
| | | from third_data import kpl_data_manager, kpl_util, kpl_api, block_info |
| | | from third_data.code_plate_key_manager import RealTimeKplMarketData |
| | | from third_data.kpl_data_manager import KPLLimitUpDataRecordManager, KPLDataManager |
| | | from third_data import kpl_data_manager, kpl_api |
| | | from third_data.kpl_data_manager import KPLLimitUpDataRecordManager |
| | | from trade import first_code_score_manager, l2_trade_factor, trade_manager, l2_trade_util |
| | | from trade.l2_trade_factor import L2TradeFactorUtil |
| | | import trade.deal_big_money_manager |
| | | from jinja2 import Environment, FileSystemLoader |
| | | |
| | | base_output_content = {} |
| | | kpl_block_info_dict = {} |
| | | |
| | | __kplDataManager = kpl_data_manager.KPLDataManager() |
| | | |
| | |
| | | |
| | | |
| | | def render(params): |
| | | env = Environment(loader=FileSystemLoader('D:/workspace/trade/output')) |
| | | env = Environment(loader=FileSystemLoader('/workspace/trade/output')) |
| | | css = env.get_template('css/index.css') |
| | | params["css"] = css.render() |
| | | template = env.get_template('index.html') |
| | |
| | | |
| | | |
| | | def get_output_params(code, jingxuan_cache_dict, industry_cache_dict): |
| | | __start_time = time.time() |
| | | |
| | | def format_plate_output(_plat): |
| | | if _plat in jingxuan_cache_dict: |
| | | return _plat, money_desc(jingxuan_cache_dict[_plat][3]) |
| | |
| | | if l2_trade_util.WhiteListCodeManager.is_in(code): |
| | | code_extra_infos.append("白名单") |
| | | # 获取白名单,黑名单 |
| | | if trade_manager.gpcode_manager.WantBuyCodesManager.is_in(code): |
| | | if code_attribute.gpcode_manager.WantBuyCodesManager.is_in(code): |
| | | code_extra_infos.append("想买单") |
| | | if trade_manager.gpcode_manager.PauseBuyCodesManager.is_in(code): |
| | | if code_attribute.gpcode_manager.PauseBuyCodesManager.is_in(code): |
| | | code_extra_infos.append("暂不买") |
| | | params["code"] = code |
| | | params["code_name"] = f"{gpcode_manager.get_code_name(code)} {code} ({','.join(code_extra_infos)})" |
| | |
| | | |
| | | params["score_data"]["k_form"] = {"score": k_score, "datas": k_source} |
| | | |
| | | log.logger_debug.info(f"K线形态耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | # 历史股性 |
| | | nature_score = 0 |
| | | nature_source = [] |
| | |
| | | code_nature_datas["first_open_limit_up_yijia"] = "无首板炸板" |
| | | |
| | | params["score_data"]["code_nature"] = code_nature_datas |
| | | |
| | | log.logger_debug.info(f"历史股性耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | # 板块热度 |
| | | hot_block_score = 0 |
| | |
| | | |
| | | # zyltgb, limit_price, bidding, k_form, code_nature, hot_block, volume_rate, limit_up_time, |
| | | # deal_big_money |
| | | log.logger_debug.info(f"板块热度耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | ###############################下单信息############################### |
| | | params["trade_data"] = {} |
| | |
| | | (score, score_list), |
| | | score_source_list)) |
| | | # 是否可以买入的信息 |
| | | can_buy_info = l2.l2_data_manager_new.L2TradeDataProcessor.can_buy_first(code, limit_up_price, __L2PlaceOrderParamsManager.score_index, |
| | | __L2PlaceOrderParamsManager.score, |
| | | __L2PlaceOrderParamsManager.score_info, |
| | | (volume_rate, |
| | | code_volumn_manager.get_volume_rate_index(volume_rate))) |
| | | can_buy_info = l2.l2_data_manager_new.L2TradeDataProcessor.can_buy_first(code, limit_up_price, |
| | | __L2PlaceOrderParamsManager.score_index, |
| | | __L2PlaceOrderParamsManager.score, |
| | | __L2PlaceOrderParamsManager.score_info, |
| | | (volume_rate, |
| | | code_volumn_manager.get_volume_rate_index( |
| | | volume_rate))) |
| | | params["trade_data"]["can_buy_info"] = can_buy_info |
| | | |
| | | __base_L2PlaceOrderParamsManager = l2_trade_factor.L2PlaceOrderParamsManager(code, False, volume_rate, |
| | |
| | | elif trade_state == trade_manager.TRADE_STATE_BUY_SUCCESS: |
| | | params["trade_data"]["trade_state"]["desc"] = "已成交" |
| | | |
| | | log.logger_debug.info(f"下单信息耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | # H撤监听范围 |
| | | if trade_state == trade_manager.TRADE_STATE_BUY_PLACE_ORDER or trade_state == trade_manager.TRADE_STATE_BUY_DELEGATED or trade_state == trade_manager.TRADE_STATE_BUY_SUCCESS: |
| | | hcancel_datas_dict, cancel_indexes_set = HourCancelBigNumComputer.get_watch_index_dict(code) |
| | |
| | | params["trade_data"]["h_cancel"]["datas"].append( |
| | | (val["time"], val["num"], money_desc(val["num"] * float(val["price"]) * 100), |
| | | (1 if canceled else 0))) |
| | | log.logger_debug.info(f"H撤监听范围耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | ##############################主动买,被动买################################## |
| | | # 返回主动买,被动买,不买的列表(代码, 名称, 得分, 是否涨停) |
| | |
| | | {"name": d[1], "code": d[0], "score": d[2], "limit_up": d[3], "open_limit_up": d[4]}) |
| | | |
| | | params["passive_buy_codes"] = params["passive_buy_codes"] |
| | | log.logger_debug.info(f"主动买,被动买耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | trade_info = __load_trade_record(code, total_datas) |
| | | params["trade_record"] = {"open_limit_up": trade_info[0], "records": trade_info[2]} |
| | | |
| | | log.logger_debug.info(f"读取交易记录耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | ##############################开盘啦相关信息################################## |
| | | industry = global_util.code_industry_map.get(code) |
| | | params["kpl_code_info"] = { |
| | | "industry": format_plate_output(industry)} |
| | | # 获取开盘啦板块 |
| | | plate_info = kpl_api.getStockIDPlate(code) |
| | | plate_info = None |
| | | if code not in kpl_block_info_dict: |
| | | plate_info = kpl_api.getStockIDPlate(code) |
| | | else: |
| | | plate_info = kpl_block_info_dict.get(code) |
| | | if plate_info: |
| | | kpl_block_info_dict[code] = plate_info |
| | | plate_info.sort(key=lambda x: x[2]) |
| | | plate_info.reverse() |
| | | params["kpl_code_info"]["plate"] = [(k[0], k[1], k[2], format_plate_output(k[1])[1]) for k in plate_info] |
| | | |
| | | log.logger_debug.info(f"开盘啦板块耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | |
| | | # 获取代码的历史涨停数据,(涨停原因,日期,板块) |
| | | code_records = KPLLimitUpDataRecordManager.get_latest_infos(code, 4, False)[:2] |
| | |
| | | params["kpl_code_info"]["today"] = (format_plate_output(d[2]), d[1], plates) |
| | | break |
| | | |
| | | log.logger_debug.info(f"获取代码的历史涨停数据耗时:{time.time() - __start_time}") |
| | | __start_time = time.time() |
| | | return params |
| | | |
| | | |
| | |
| | | import threading |
| | | import time |
| | | |
| | | import gpcode_manager |
| | | import log |
| | | from code_attribute import gpcode_manager |
| | | from logs import log |
| | | from db.redis_manager import RedisManager |
| | | from log import logger_kp_msg |
| | | from logs.log import logger_kp_msg |
| | | |
| | | CLIENT_IDS = ["zjb", "hxh"] |
| | | |
| | |
| | | """ |
| | | |
| | | # 判断是龙几,判断是否涨停,判断是否炸板,加载分数 |
| | | import redis |
| | | |
| | | import code_volumn_manager |
| | | import gpcode_manager |
| | | import limit_up_time_manager |
| | | import tool |
| | | from code_attribute import code_volumn_manager, limit_up_time_manager, gpcode_manager |
| | | from utils import tool |
| | | from db import redis_manager |
| | | from third_data.kpl_data_manager import KPLDataManager |
| | | from third_data.kpl_util import KPLDataType |
| | |
| | | import threading |
| | | import time |
| | | |
| | | import alert_util |
| | | import client_manager |
| | | import code_nature_analyse |
| | | import code_volumn_manager |
| | | from utils import alert_util, data_process, global_util, ths_industry_util, tool, import_util |
| | | from code_attribute import code_volumn_manager, code_nature_analyse, global_data_loader, gpcode_manager, \ |
| | | gpcode_first_screen_manager |
| | | import constant |
| | | import data_process |
| | | import global_data_loader |
| | | import global_util |
| | | import gpcode_first_screen_manager |
| | | import gpcode_manager |
| | | import authority |
| | | import init |
| | | from user import authority |
| | | import inited_data |
| | | from l2 import l2_data_manager_new, l2_data_manager, l2_data_log, l2_log, code_price_manager |
| | | import l2_data_util |
| | | from l2.cancel_buy_strategy import HourCancelBigNumComputer, L2LimitUpMoneyStatisticUtil, LCancelBigNumComputer |
| | | import l2.l2_data_util |
| | | |
| | | import ths_industry_util |
| | | import ths_util |
| | | import tool |
| | | from output import code_info_output |
| | | from third_data import hot_block_data_process, block_info, kpl_api |
| | | from third_data.code_plate_key_manager import CodesHisReasonAndBlocksManager |
| | | from third_data.history_k_data_util import HistoryKDatasUtils |
| | | from third_data.kpl_data_manager import KPLCodeLimitUpReasonManager, KPLLimitUpDataRecordManager |
| | | from ths import l2_listen_pos_health_manager, l2_code_operate |
| | | from trade import trade_gui, trade_data_manager, trade_manager, l2_trade_util, deal_big_money_manager, \ |
| | | from ths import l2_listen_pos_health_manager, l2_code_operate, client_manager |
| | | from trade import trade_data_manager, trade_manager, l2_trade_util, deal_big_money_manager, \ |
| | | current_price_process_manager, trade_juejin |
| | | from code_data_util import ZYLTGBUtil |
| | | from code_attribute.code_data_util import ZYLTGBUtil |
| | | import l2.transaction_progress |
| | | |
| | | from log import logger_l2_error, logger_device, logger_trade_delegate, logger_buy_1_volumn_record, \ |
| | | from logs.log import logger_l2_error, logger_device, logger_trade_delegate, logger_buy_1_volumn_record, \ |
| | | logger_l2_trade_queue, logger_l2_latest_data, logger_l2_trade_buy_queue, logger_first_code_record, logger_debug |
| | | from trade.huaxin import huaxin_trade_record_manager |
| | | from trade.trade_manager import TradeTargetCodeModeManager |
| | | from trade.trade_queue_manager import THSBuy1VolumnManager, thsl2tradequeuemanager |
| | | |
| | | ths_util = import_util.import_lib("ths.ths_util") |
| | | trade_gui = import_util.import_lib("trade.trade_gui") |
| | | |
| | | class MyTCPServer(socketserver.TCPServer): |
| | | def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, pipe_juejin=None, pipe_ui=None): |
| | |
| | | # 获取涨停价 |
| | | _limit_up_price = gpcode_manager.get_limit_up_price(code) |
| | | if not _limit_up_price: |
| | | init.re_set_price_pres([code], True) |
| | | inited_data.re_set_price_pres([code], True) |
| | | # 再次获取涨停价 |
| | | _limit_up_price = gpcode_manager.get_limit_up_price(code) |
| | | if _limit_up_price: |
| | |
| | | for code in codes: |
| | | # 如果涨停价是空值就需要设置昨日收盘价格 |
| | | if gpcode_manager.get_limit_up_price(code) is None: |
| | | init.re_set_price_pres([code], True) |
| | | inited_data.re_set_price_pres([code], True) |
| | | |
| | | # 板块关键字准备 |
| | | for code in codes: |
| | |
| | | code) is None: |
| | | need_get_volumn = True |
| | | if need_get_volumn: |
| | | volumes_data = init.get_volumns_by_code(code, 150) |
| | | volumes = init.parse_max_volume(volumes_data[:90], code_nature_analyse.is_new_top( |
| | | gpcode_manager.get_limit_up_price(code), volumes_data[:90])) |
| | | volumes_data = inited_data.get_volumns_by_code(code, 150) |
| | | volumes = inited_data.parse_max_volume(volumes_data[:90], |
| | | code_nature_analyse.is_new_top( |
| | | gpcode_manager.get_limit_up_price(code), |
| | | volumes_data[:90])) |
| | | logger_first_code_record.info("{} 获取到首板60天最大量:{}", code, volumes) |
| | | code_volumn_manager.set_histry_volumn(code, volumes[0], volumes[1], volumes[2]) |
| | | # 判断K线形态 |
| | |
| | | # 获取涨停价 |
| | | if temp_codes: |
| | | # 获取涨停价 |
| | | init.re_set_price_pres(temp_codes) |
| | | inited_data.re_set_price_pres(temp_codes) |
| | | # 重新获取涨停价 |
| | | for code in temp_codes: |
| | | limit_up_price = gpcode_manager.get_limit_up_price(code) |
| | |
| | | gpcode_manager.FirstCodeManager.add_limited_up_record([code]) |
| | | pricePre = gpcode_manager.get_price_pre(code) |
| | | if pricePre is None: |
| | | init.re_set_price_pres([code]) |
| | | inited_data.re_set_price_pres([code]) |
| | | |
| | | rate = round((float(price) - pricePre) * 100 / pricePre, 1) |
| | | prices.append( |
| | |
| | | logging.exception(e) |
| | | trade_manager.save_trade_delegate_data(dataList) |
| | | # 刷新交易界面 |
| | | trade_gui.THSGuiTrade().refresh_data() |
| | | if trade_gui is not None: |
| | | trade_gui.THSGuiTrade().refresh_data() |
| | | finally: |
| | | pass |
| | | |
| | |
| | | thsDead = data.get("thsDead") |
| | | logger_device.info("({})客户端信息:{}".format(client_id, json.dumps(data))) |
| | | client_manager.saveClientActive(int(client_id), host, thsDead) |
| | | if ths_util.is_ths_dead(client_id): |
| | | # TODO 重启同花顺 |
| | | # 报警 |
| | | l2_clients = authority.get_l2_clients() |
| | | if client_id in l2_clients: |
| | | alert_util.alarm() |
| | | if constant.is_windows(): |
| | | # 动态导入 |
| | | |
| | | if ths_util.is_ths_dead(client_id): |
| | | # TODO 重启同花顺 |
| | | # 报警 |
| | | l2_clients = authority.get_l2_clients() |
| | | if client_id in l2_clients: |
| | | alert_util.alarm() |
| | | elif type == 60: |
| | | # L2自启动成功 |
| | | data = data_process.parse(_str)["data"] |
| | |
| | | return_str = json.dumps({"code": 1, "msg": "未处于可撤单状态"}) |
| | | else: |
| | | return_str = json.dumps({"code": 1, "msg": "请上传代码"}) |
| | | |
| | | elif type == 82: |
| | | # 获取委托列表 |
| | | data = json.loads(_str) |
| | | update_time = data["data"]["update_time"] |
| | | results, update_time = huaxin_trade_record_manager.DelegateRecordManager.list_by_day( |
| | | tool.get_now_date_str("%Y%m%d"), update_time) |
| | | return_str = json.dumps( |
| | | {"code": 0, "data": {"list": results, "updateTime": update_time}, "msg": "请上传代码"}) |
| | | |
| | | elif type == 201: |
| | | # 加入黑名单 |
| | | data = json.loads(_str) |
| | |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | |
| | | |
| | | # 交易成功无法读取时备用 |
| | | while True: |
| | | while False: |
| | | try: |
| | | datas = trade_juejin.get_execution_reports() |
| | | # 上传数据 |
| | |
| | | try: |
| | | global_data_loader.load_zyltgb() |
| | | limit_up_price = float(gpcode_manager.get_limit_up_price(code)) |
| | | volumes_data = init.get_volumns_by_code(code, 150) |
| | | volumes_data = inited_data.get_volumns_by_code(code, 150) |
| | | volumes_data = volumes_data[1:] |
| | | volumes = init.parse_max_volume(volumes_data[:60], |
| | | code_nature_analyse.is_new_top(limit_up_price, |
| | | volumes_data[:60])) |
| | | volumes = inited_data.parse_max_volume(volumes_data[:60], |
| | | code_nature_analyse.is_new_top(limit_up_price, |
| | | volumes_data[:60])) |
| | | logger_first_code_record.info("{} 获取到首板60天最大量:{}", code, volumes) |
| | | code_volumn_manager.set_histry_volumn(code, volumes[0], volumes[1], volumes[2]) |
| | | # 判断K线形态 |
File was renamed from l2_trade_test.py |
| | |
| | | # 交易测试 |
| | | # 清除交易数据 |
| | | import decimal |
| | | import itertools |
| | | import json |
| | | import logging |
| | | import random |
| | | import time |
| | | import unittest |
| | | from copy import deepcopy |
| | | from unittest import mock |
| | | |
| | | import big_money_num_manager |
| | | import gpcode_manager |
| | | import log |
| | | import tool |
| | | from code_attribute import big_money_num_manager, gpcode_manager |
| | | from logs import log |
| | | from utils import tool |
| | | from db import redis_manager |
| | | from l2 import l2_log, l2_data_manager, transaction_progress, safe_count_manager |
| | | from l2 import l2_log, l2_data_manager, transaction_progress |
| | | from l2.safe_count_manager import BuyL2SafeCountManager |
| | | from l2.transaction_progress import TradeBuyQueue |
| | | from third_data import kpl_util |
| | | from third_data.code_plate_key_manager import RealTimeKplMarketData, LimitUpCodesPlateKeyManager |
| | | from third_data.kpl_data_manager import KPLDataManager |
| | | from trade import trade_data_manager, l2_trade_factor |
| | | from trade import trade_data_manager |
| | | from trade.trade_queue_manager import THSBuy1VolumnManager |
| | | import l2.l2_data_manager_new, l2.l2_data_manager, l2.l2_data_util, l2.cancel_buy_strategy |
| | | |
| | |
| | | import datetime |
| | | |
| | | import constant |
| | | import init |
| | | import tool |
| | | from third_data import kpl_util, kpl_data_manager |
| | | from utils import tool |
| | | from third_data import kpl_util |
| | | from third_data.history_k_data_util import HistoryKDatasUtils |
| | | from third_data.kpl_data_manager import KPLLimitUpDataRecordManager, KPLDataManager |
| | | |
| | |
| | | import json |
| | | |
| | | import constant |
| | | import global_util |
| | | import log |
| | | import tool |
| | | from utils import global_util, tool |
| | | from logs import log |
| | | from db import redis_manager |
| | | |
| | | from log import logger_kpl_limit_up, logger_kpl_block_can_buy |
| | | from logs.log import logger_kpl_limit_up, logger_kpl_block_can_buy |
| | | from third_data.kpl_util import KPLPlatManager |
| | | from trade import trade_manager |
| | | |
| | |
| | | import base64 |
| | | import http |
| | | import json |
| | | import logging |
| | | import socketserver |
| | | import time |
| | | from http.server import BaseHTTPRequestHandler |
| | | import cv2 |
| | | import dask |
| | | |
| | | import global_util |
| | | import gpcode_manager |
| | | import init |
| | | import log |
| | | import log_analyse |
| | | import tool |
| | | from utils import global_util, tool |
| | | from code_attribute import gpcode_manager |
| | | from logs import log, log_analyse |
| | | from l2 import code_price_manager, l2_data_util |
| | | from l2.cancel_buy_strategy import HourCancelBigNumComputer |
| | | from output.limit_up_data_filter import IgnoreCodeManager |
| | |
| | | response_data = json.dumps({"code": 0, "data": {"best_feng_kou": best_feng_kou, "feng_kou": feng_kou, |
| | | "industry_rank": industry_rank, "feng_xiang": feng_xiang}}) |
| | | elif url.path == "/get_score_info": |
| | | start_time = time.time() |
| | | ps_dict = dict([(k, v[0]) for k, v in parse_qs(url.query).items()]) |
| | | code = ps_dict['code'] |
| | | name = ps_dict.get('name') |
| | |
| | | self.__blocks_dict[code] = (time.time(), data["kpl_code_info"]["plate"]) |
| | | |
| | | response_data = json.dumps({"code": 0, "data": data}) |
| | | print("get_score_info 耗时:", time.time()-start_time) |
| | | |
| | | # 获取评分信息 |
| | | pass |
| | | elif url.path == "/kpl/get_limit_up_list": |
| | |
| | | """ |
| | | 历史K线服务 |
| | | """ |
| | | import datetime |
| | | import decimal |
| | | import json |
| | | |
| | | import tool |
| | | import requests |
| | | |
| | | import constant |
| | | from utils import tool |
| | | from db import redis_manager |
| | | import gm.api as gmapi |
| | | |
| | | |
| | | class JueJinHttpApi: |
| | | __BASE_URL = "http://193.112.35.168:10009/" |
| | | |
| | | @classmethod |
| | | def __request(cls, path_str, data_json): |
| | | def deformat_date(val): |
| | | if type(val) == str and val.find('T') > -1 and val.find(':') > -1 and val.find( |
| | | '+') > -1: |
| | | return datetime.datetime.fromisoformat(val) |
| | | return val |
| | | |
| | | url = f'{cls.__BASE_URL}{path_str}' |
| | | # 发送POST请求 |
| | | response = requests.post(url, json=data_json) |
| | | result = response.text |
| | | resultJson = json.loads(result) |
| | | if resultJson['code'] == 0: |
| | | data = resultJson['data'] |
| | | if type(data) == list: |
| | | for d in data: |
| | | if type(d) != dict: |
| | | continue |
| | | for k in d: |
| | | d[k] = deformat_date(d[k]) |
| | | elif type(data) == dict: |
| | | for k in data: |
| | | data[k] = deformat_date(data[k]) |
| | | return data |
| | | |
| | | return None |
| | | |
| | | @classmethod |
| | | def get_instruments(cls, symbols, fields): |
| | | return cls.__request("get_instruments", {"symbols": symbols, "fields": fields}) |
| | | |
| | | @classmethod |
| | | def history_n(cls, symbol, frequency, count, adjust, fields): |
| | | return cls.__request("history_n", {"symbol": symbol, "frequency": frequency, "count": count, "adjust": adjust, |
| | | "fields": fields}) |
| | | |
| | | @classmethod |
| | | def current(cls, symbols, fields): |
| | | return cls.__request("current", {"symbols": symbols, "fields": fields}) |
| | | |
| | | @classmethod |
| | | def get_previous_trading_date(cls, exchange, date): |
| | | return cls.__request("get_previous_trading_date", {"exchange": exchange, "date": date}) |
| | | |
| | | @classmethod |
| | | def get_next_trading_date(cls, exchange, date): |
| | | return cls.__request("get_next_trading_date", {"exchange": exchange, "date": date}) |
| | | |
| | | @classmethod |
| | | def get_trading_dates(cls, exchange, start_date, end_date): |
| | | return cls.__request("get_trading_dates", |
| | | {"exchange": exchange, "start_date": start_date, "end_date": end_date}) |
| | | |
| | | |
| | | class JueJinApi: |
| | |
| | | def get_gp_latest_info(cls, codes, fields=None): |
| | | if not codes: |
| | | return [] |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | symbols = cls.get_juejin_code_list_with_prefix(codes) |
| | | gmapi.set_token(token) |
| | | data = gmapi.get_instruments(symbols=",".join(symbols), fields=fields) |
| | | print(data) |
| | | return data |
| | | if constant.JUEJIN_LOCAL_API: |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | data = gmapi.get_instruments(symbols=",".join(symbols), fields=fields) |
| | | return data |
| | | else: |
| | | return JueJinHttpApi.get_instruments(symbols=",".join(symbols), fields=fields) |
| | | |
| | | @classmethod |
| | | def get_history_tick_n(cls, code, count, fields=None): |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | symbols = cls.get_juejin_code_list_with_prefix([code]) |
| | | gmapi.set_token(token) |
| | | # 前除权 |
| | | results = gmapi.history_n(symbol=symbols[0], frequency="1d", count=count, adjust=1, fields=fields) |
| | | return results |
| | | if constant.JUEJIN_LOCAL_API: |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | # 前除权 |
| | | results = gmapi.history_n(symbol=symbols[0], frequency="1d", count=count, adjust=1, fields=fields) |
| | | return results |
| | | else: |
| | | results = JueJinHttpApi.history_n(symbol=symbols[0], frequency="1d", count=count, adjust=1, fields=fields) |
| | | return results |
| | | |
| | | @classmethod |
| | | def get_gp_current_info(cls, codes): |
| | | if not codes: |
| | | return [] |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | symbols = cls.get_juejin_code_list_with_prefix(codes) |
| | | gmapi.set_token(token) |
| | | data = gmapi.current(symbols=",".join(symbols)) |
| | | print(data) |
| | | return data |
| | | |
| | | if constant.JUEJIN_LOCAL_API: |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | data = gmapi.current(symbols=",".join(symbols)) |
| | | return data |
| | | else: |
| | | data = JueJinHttpApi.current(symbols=",".join(symbols), fields='') |
| | | return data |
| | | # 返回指定日期的上个交易日 |
| | | |
| | | @classmethod |
| | | def get_previous_trading_date(cls, date): |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | return gmapi.get_previous_trading_date("SHSE", date) |
| | | if constant.JUEJIN_LOCAL_API: |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | return gmapi.get_previous_trading_date("SHSE", date) |
| | | else: |
| | | return JueJinHttpApi.get_previous_trading_date("SHSE", date) |
| | | |
| | | # 返回指定日期的下个交易日 |
| | | @classmethod |
| | | def get_next_trading_date(cls, date): |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | return gmapi.get_previous_trading_date("SHSE", date) |
| | | if constant.JUEJIN_LOCAL_API: |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | return gmapi.get_next_trading_date("SHSE", date) |
| | | else: |
| | | return JueJinHttpApi.get_next_trading_date("SHSE", date) |
| | | |
| | | @classmethod |
| | | def get_trading_dates(cls, start_date, end_date): |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | return gmapi.get_trading_dates("SHSE", start_date, end_date) |
| | | if constant.JUEJIN_LOCAL_API: |
| | | account_id, s_id, token = cls.getJueJinAccountInfo() |
| | | gmapi.set_token(token) |
| | | return gmapi.get_trading_dates("SHSE", start_date, end_date) |
| | | else: |
| | | return JueJinHttpApi.get_trading_dates("SHSE", start_date, end_date) |
| | | |
| | | |
| | | class HistoryKDatasUtils(object): |
| | |
| | | code_name = data['sec_name'] |
| | | results[code] = code_name |
| | | return results |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | print(JueJinApi.get_gp_current_info(["000333", "600686"])) |
| | |
| | | import datetime |
| | | import json |
| | | |
| | | import init |
| | | import tool |
| | | from utils import tool |
| | | from db import redis_manager |
| | | from db import mysql_data |
| | | import limit_up_time_manager |
| | | import gpcode_manager |
| | | from code_attribute import limit_up_time_manager, gpcode_manager |
| | | from l2 import code_price_manager |
| | | from third_data.history_k_data_util import HistoryKDatasUtils |
| | | |
| | |
| | | import os |
| | | |
| | | import constant |
| | | import tool |
| | | from utils import tool |
| | | |
| | | # 开盘啦历史涨停数据管理 |
| | | from db import mysql_data, redis_manager |
| | | from log import logger_kpl_limit_up_reason_change |
| | | from logs.log import logger_kpl_limit_up_reason_change |
| | | from third_data import kpl_util, kpl_api |
| | | from third_data.code_plate_key_manager import LimitUpCodesPlateKeyManager, CodesHisReasonAndBlocksManager |
| | | |
| | |
| | | |
| | | |
| | | def load_history_limit_up(): |
| | | for file_name in os.listdir("D:/kpl/his"): |
| | | for file_name in os.listdir(f"{constant.get_path_prefix()}/kpl/his"): |
| | | if file_name.find("HisDaBanList_1.log") < 0: |
| | | continue |
| | | day = file_name[:10] |
| | | with open(f"D:/kpl/his/{file_name}", 'r', encoding="utf-16") as f: |
| | | with open(f"{constant.get_path_prefix()}/kpl/his/{file_name}", 'r', encoding="utf-16") as f: |
| | | lines = f.readlines() |
| | | line = lines[0] |
| | | result = json.loads(line) |
| | |
| | | from datetime import datetime |
| | | |
| | | import requests |
| | | import init |
| | | import inited_data |
| | | from third_data import hot_block |
| | | |
| | | |
File was renamed from client_manager.py |
| | |
| | | # 客户端管理器 |
| | | import json |
| | | |
| | | import authority |
| | | from user import authority |
| | | from db import redis_manager |
| | | import ths_util |
| | | from utils import import_util |
| | | |
| | | ths_util = import_util.import_lib("ths.ths_util") |
| | | |
| | | __redisManager = redis_manager.RedisManager(0) |
| | | |
| | |
| | | import logging |
| | | import threading |
| | | |
| | | import client_manager |
| | | import gpcode_manager |
| | | from ths import client_manager |
| | | from code_attribute import gpcode_manager |
| | | from l2 import l2_data_manager |
| | | from trade import l2_trade_util |
| | | |
| | | import server |
| | | import tool |
| | | from utils import tool |
| | | import time |
| | | from db import redis_manager |
| | | from log import logger_code_operate |
| | | from logs.log import logger_code_operate |
| | | |
| | | __reset_code_dict = {} |
| | | __set_operate_code_state_dict = {} |
| | |
| | | |
| | | @staticmethod |
| | | def setGPCode(client_id, position, gpcode): |
| | | print("setGPCode") |
| | | data = {"action": "setGPCode", "data": {"index": int(position), "code": gpcode}} |
| | | logger_code_operate.info("setGPCode:clientid-{} position-{} code-{}".format(client_id, position, gpcode)) |
| | | gpcode_manager.set_operate(gpcode) |
| | |
| | | 同花顺l2监听位置健康度管理 |
| | | """ |
| | | # 不健康 |
| | | import tool |
| | | from utils import tool |
| | | from db import redis_manager |
| | | |
| | | UN_HEALTHY = 0 |
File was renamed from ths_util.py |
| | |
| | | import win32gui |
| | | |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | from trade import trade_gui |
| | | |
| | | __redisManager = redis_manager.RedisManager(2) |
| | |
| | | """ |
| | | import json |
| | | |
| | | import tool |
| | | from utils import tool |
| | | from db import redis_manager |
| | | |
| | | __redisManager = redis_manager.RedisManager(2) |
| | |
| | | import decimal |
| | | import logging |
| | | |
| | | import client_manager |
| | | from ths import client_manager |
| | | import constant |
| | | import gpcode_manager |
| | | import tool |
| | | from code_attribute import gpcode_manager |
| | | from utils import tool, import_util |
| | | from ths.l2_code_operate import L2CodeOperate |
| | | from trade import trade_manager, trade_gui, l2_trade_util |
| | | from trade import trade_manager, l2_trade_util |
| | | from trade.trade_data_manager import CodeActualPriceProcessor |
| | | |
| | | trade_gui = import_util.import_lib("trade.trade_gui") |
| | | |
| | | __actualPriceProcessor = CodeActualPriceProcessor() |
| | | |
| | |
| | | for d in _delete_list: |
| | | _buy_win_codes.append(d[1]) |
| | | try: |
| | | if not constant.API_TRADE_ENABLE: |
| | | if not constant.API_TRADE_ENABLE and trade_gui is not None: |
| | | trade_gui.THSBuyWinManagerNew.fill_codes(_buy_win_codes) |
| | | except Exception as e: |
| | | logging.exception(e) |
| | |
| | | """ |
| | | import json |
| | | |
| | | import tool |
| | | from utils import tool |
| | | from db import redis_manager |
| | | from l2 import l2_data_util, l2_data_source_util |
| | | |
| | |
| | | # limit_price 涨停价是否大于100块 |
| | | # limit_up_time 是否10点之前涨停 |
| | | # k_form(15个交易日是否涨幅24.9%,是否破前高,是否超跌,是否接近前高,是否N,是否V,是否有形态) |
| | | import code_nature_analyse |
| | | import code_volumn_manager |
| | | import global_data_loader |
| | | import global_util |
| | | import gpcode_manager |
| | | import tool |
| | | from code_attribute import code_volumn_manager, code_nature_analyse, global_data_loader, gpcode_manager |
| | | from utils import global_util, tool |
| | | from third_data import block_info |
| | | from trade import l2_trade_factor, deal_big_money_manager, bidding_money_manager |
| | | |
New file |
| | |
| | | from loguru import logger |
| | | |
| | | |
| | | class MyLogger: |
| | | def __init__(self): |
| | | logger.remove() |
| | | # 每一天生成一个日志文件,历史日志文件采用zip压缩,异步写入日志 |
| | | logger.add(self.get_path("l2", "transaction"), |
| | | filter=lambda record: record["extra"].get("name") == "transaction", |
| | | rotation="00:00", compression="zip", enqueue=True) |
| | | logger.add(self.get_path("l2", "orderdetail"), |
| | | filter=lambda record: record["extra"].get("name") == "orderdetail", |
| | | rotation="00:00", compression="zip", enqueue=True) |
| | | logger.add(self.get_path("l2", "upload"), |
| | | filter=lambda record: record["extra"].get("name") == "upload", |
| | | rotation="00:00", compression="zip", enqueue=True) |
| | | logger.add(self.get_path("contact", "debug"), |
| | | filter=lambda record: record["extra"].get("name") == "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" |
| | | |
| | | def get_logger(self, log_name): |
| | | return logger.bind(name=log_name) |
| | | |
| | | |
| | | __mylogger = MyLogger() |
| | | logger_l2_transaction = __mylogger.get_logger("transaction") |
| | | 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") |
New file |
| | |
| | | """ |
| | | 交易API |
| | | """ |
| | | import json |
| | | import logging |
| | | import random |
| | | import threading |
| | | import time |
| | | |
| | | |
| | | from utils import socket_util |
| | | |
| | | |
| | | class ClientSocketManager: |
| | | # 客户端类型 |
| | | CLIENT_TYPE_TRADE = "trade" |
| | | CLIENT_TYPE_DELEGATE_LIST = "delegate_list" |
| | | CLIENT_TYPE_DEAL_LIST = "deal_list" |
| | | CLIENT_TYPE_POSITION_LIST = "position_list" |
| | | CLIENT_TYPE_MONEY = "money" |
| | | CLIENT_TYPE_DEAL = "deal" |
| | | CLIENT_TYPE_CMD_L2 = "l2_cmd" |
| | | socket_client_dict = {} |
| | | socket_client_lock_dict = {} |
| | | active_client_dict = {} |
| | | |
| | | @classmethod |
| | | def add_client(cls, _type, rid, sk): |
| | | if _type == cls.CLIENT_TYPE_TRADE: |
| | | # 交易列表 |
| | | if _type not in cls.socket_client_dict: |
| | | cls.socket_client_dict[_type] = [] |
| | | cls.socket_client_dict[_type].append((rid, sk)) |
| | | cls.socket_client_lock_dict[rid] = threading.Lock() |
| | | else: |
| | | cls.socket_client_dict[_type] = (rid, sk) |
| | | cls.socket_client_lock_dict[rid] = threading.Lock() |
| | | |
| | | @classmethod |
| | | def acquire_client(cls, _type): |
| | | if _type == cls.CLIENT_TYPE_TRADE: |
| | | if _type in cls.socket_client_dict: |
| | | # 根据排序活跃时间排序 |
| | | client_list = sorted(cls.socket_client_dict[_type], key=lambda x: cls.active_client_dict.get(x[0]) if x[ |
| | | 0] in cls.active_client_dict else 0, |
| | | reverse=True) |
| | | for d in client_list: |
| | | if d[0] in cls.socket_client_lock_dict: |
| | | try: |
| | | if cls.socket_client_lock_dict[d[0]].acquire(blocking=False): |
| | | return d |
| | | except threading.TimeoutError: |
| | | pass |
| | | else: |
| | | if _type in cls.socket_client_dict: |
| | | try: |
| | | d = cls.socket_client_dict[_type] |
| | | if d[0] in cls.socket_client_lock_dict: |
| | | if cls.socket_client_lock_dict[d[0]].acquire(blocking=False): |
| | | return d |
| | | except threading.TimeoutError: |
| | | pass |
| | | return None |
| | | |
| | | @classmethod |
| | | def release_client(cls, rid): |
| | | if rid in cls.socket_client_lock_dict: |
| | | # 释放锁 |
| | | cls.socket_client_lock_dict[rid].release() |
| | | |
| | | @classmethod |
| | | def del_client(cls, rid): |
| | | # 删除线程锁 |
| | | if rid in cls.socket_client_lock_dict: |
| | | cls.socket_client_lock_dict.pop(rid) |
| | | # 删除sk |
| | | for t in cls.socket_client_dict: |
| | | if type(cls.socket_client_dict[t]) == list: |
| | | for d in cls.socket_client_dict[t]: |
| | | if d[0] == rid: |
| | | cls.socket_client_dict[t].remove(d) |
| | | break |
| | | |
| | | elif type(cls.socket_client_dict[t]) == tuple: |
| | | if cls.socket_client_dict[t][0] == rid: |
| | | cls.socket_client_dict.pop(t) |
| | | break |
| | | |
| | | # 心跳信息 |
| | | @classmethod |
| | | def heart(cls, rid): |
| | | cls.active_client_dict[rid] = time.time() |
| | | |
| | | |
| | | TRADE_DIRECTION_BUY = 1 |
| | | TRADE_DIRECTION_SELL = 2 |
| | | |
| | | # 超时时间2s |
| | | TIMEOUT = 2.0 |
| | | |
| | | # 等待响应的request_id |
| | | __request_response_dict = {} |
| | | |
| | | |
| | | def __get_request_id(type): |
| | | return f"{type}_{round(time.time() * 10000)}_{random.randint(0, 100000)}" |
| | | |
| | | |
| | | # 网络请求 |
| | | def __request(_type, data): |
| | | client = ClientSocketManager.acquire_client(_type) |
| | | if not client: |
| | | raise Exception("无可用的交易client") |
| | | try: |
| | | request_id = __get_request_id(_type) |
| | | root_data = {"type": "cmd", |
| | | "data": data, |
| | | "request_id": request_id} |
| | | root_data = socket_util.encryp_client_params_sign(root_data) |
| | | print("请求前对象", root_data) |
| | | # 添加请求头 |
| | | client[1].sendall(socket_util.load_header(json.dumps(root_data).encode(encoding='utf-8'))) |
| | | result = client[1].recv(1024) |
| | | print("请求发送成功", result.decode(encoding='utf-8')) |
| | | except BrokenPipeError as e: |
| | | ClientSocketManager.del_client(client[0]) |
| | | raise e |
| | | except Exception as e: |
| | | logging.exception(e) |
| | | raise e |
| | | return request_id, client |
| | | |
| | | |
| | | def __read_response(client, request_id, blocking, timeout=TIMEOUT): |
| | | if blocking: |
| | | start_time = time.time() |
| | | while True: |
| | | time.sleep(0.01) |
| | | if request_id in __request_response_dict: |
| | | # 获取到了响应内容 |
| | | result = __request_response_dict.pop(request_id) |
| | | return result |
| | | if time.time() - start_time > timeout: |
| | | ClientSocketManager.release_client(client[0]) |
| | | raise Exception(f"读取内容超时: request_id={request_id}") |
| | | return None |
| | | |
| | | |
| | | def set_response(client_id, request_id, response): |
| | | if client_id and request_id: |
| | | # 主动触发 |
| | | ClientSocketManager.release_client(client_id) |
| | | __request_response_dict[request_id] = response |
| | | else: |
| | | # 被动触发 |
| | | pass |
| | | |
| | | |
| | | # 下单委托 |
| | | # direction 1-买 2-卖 |
| | | # code:代码 |
| | | # volume:交易量 |
| | | # price:价格(如果是卖时不传价格就按照5挡价卖) |
| | | # blocking是否阻塞进程 |
| | | def order(direction, code, volume, price, price_type=2, blocking=True): |
| | | print("客户端", ClientSocketManager.socket_client_dict) |
| | | request_id, client = __request(ClientSocketManager.CLIENT_TYPE_TRADE, |
| | | {"type": ClientSocketManager.CLIENT_TYPE_TRADE, "trade_type": 1, |
| | | "direction": direction, |
| | | "code": code, |
| | | "volume": volume, |
| | | "price_type": price_type, |
| | | "price": price, "sinfo": f"b_{code}_{round(time.time() * 1000)}"}) |
| | | |
| | | return __read_response(client, request_id, blocking) |
| | | |
| | | |
| | | def cancel_order(direction, code, orderSysID, blocking=False): |
| | | request_id, client = __request(ClientSocketManager.CLIENT_TYPE_TRADE, |
| | | {"type": ClientSocketManager.CLIENT_TYPE_TRADE, "trade_type": 2, |
| | | "direction": direction, |
| | | "code": code, |
| | | "orderSysID": orderSysID, "sinfo": f"cb_{code}_{round(time.time() * 1000)}"}) |
| | | |
| | | return __read_response(client, request_id, blocking) |
| | | |
| | | |
| | | # CLIENT_TYPE_DELEGATE_LIST = "delegate_list" |
| | | # CLIENT_TYPE_DEAL_LIST = "deal_list" |
| | | # CLIENT_TYPE_POSITION_LIST = "position_list" |
| | | # CLIENT_TYPE_MONEY = "money" |
| | | # CLIENT_TYPE_DEAL = "deal" |
| | | |
| | | # 获取委托列表 |
| | | # can_cancel:是否可以撤 |
| | | def get_delegate_list(can_cancel=True, blocking=True): |
| | | request_id, client = __request(ClientSocketManager.CLIENT_TYPE_DELEGATE_LIST, |
| | | {"type": ClientSocketManager.CLIENT_TYPE_DELEGATE_LIST, |
| | | "can_cancel": 1 if can_cancel else 0}) |
| | | |
| | | return __read_response(client, request_id, blocking) |
| | | |
| | | |
| | | # 获取成交列表 |
| | | def get_deal_list(blocking=True): |
| | | request_id, client = __request(ClientSocketManager.CLIENT_TYPE_DEAL_LIST, |
| | | {"type": ClientSocketManager.CLIENT_TYPE_DEAL_LIST}) |
| | | return __read_response(client, request_id, blocking) |
| | | |
| | | |
| | | # 获取持仓列表 |
| | | def get_position_list(blocking=True): |
| | | request_id, client = __request(ClientSocketManager.CLIENT_TYPE_POSITION_LIST, |
| | | {"type": ClientSocketManager.CLIENT_TYPE_POSITION_LIST}) |
| | | return __read_response(client, request_id, blocking) |
| | | |
| | | |
| | | # 获取账户资金状况 |
| | | def get_money(blocking=True): |
| | | request_id, client = __request(ClientSocketManager.CLIENT_TYPE_MONEY, |
| | | {"type": ClientSocketManager.CLIENT_TYPE_MONEY}) |
| | | return __read_response(client, request_id, blocking) |
| | | |
| | | |
| | | # 设置L2订阅数据 |
| | | def set_l2_codes_data(codes_data, blocking=True): |
| | | request_id, client = __request(ClientSocketManager.CLIENT_TYPE_CMD_L2, |
| | | {"type": ClientSocketManager.CLIENT_TYPE_CMD_L2, "data": codes_data}) |
| | | return __read_response(client, request_id, blocking) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | d = {"id": "123123"} |
| | | print(d.pop("id")) |
New file |
| | |
| | | """ |
| | | 华兴交易记录 |
| | | """ |
| | | |
| | | # 委托记录 |
| | | import datetime |
| | | |
| | | from utils import tool |
| | | from db import mysql_data |
| | | from third_data.history_k_data_util import HistoryKDatasUtils |
| | | |
| | | |
| | | class DelegateRecordManager: |
| | | @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_delegate_record where orderLocalID='{d['orderLocalID']}'") |
| | | if not result: |
| | | # 新增数据 |
| | | nameDict = HistoryKDatasUtils.get_gp_codes_names([d['securityID']]) |
| | | name = nameDict.get(d['securityID']) |
| | | mysqldb.execute( |
| | | "insert into hx_trade_delegate_record values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % ( |
| | | d["orderLocalID"], d["securityID"], name, d["direction"], |
| | | d["orderSysID"], d["insertTime"], d["insertDate"], d["acceptTime"], d["cancelTime"], |
| | | d["limitPrice"], d["turnover"], d["volume"], d["volumeTraded"], d["orderStatus"], |
| | | d["orderSubmitStatus"], d["statusMsg"], tool.get_now_datetime_str(), |
| | | tool.get_now_datetime_str())) |
| | | else: |
| | | # 修改数据 |
| | | updateDict = {} |
| | | if result[4] != d['orderSysID']: |
| | | updateDict['orderSysID'] = d['orderSysID'] |
| | | if result[7] != d['acceptTime']: |
| | | updateDict['acceptTime'] = d['acceptTime'] |
| | | if result[8] != d['cancelTime']: |
| | | updateDict['cancelTime'] = d['cancelTime'] |
| | | if result[10] != str(d['turnover']): |
| | | updateDict['turnover'] = d['turnover'] |
| | | if result[12] != d['volumeTraded']: |
| | | updateDict['volumeTraded'] = d['volumeTraded'] |
| | | if result[13] != int(d['orderStatus']): |
| | | updateDict['orderStatus'] = d['orderStatus'] |
| | | if result[14] != int(d['orderSubmitStatus']): |
| | | updateDict['orderSubmitStatus'] = d['orderSubmitStatus'] |
| | | if result[15] != d['statusMsg']: |
| | | updateDict['statusMsg'] = d['statusMsg'] |
| | | 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_delegate_record set {','.join(where_list)} where orderLocalID='{result[0]}'") |
| | | finally: |
| | | pass |
| | | |
| | | @classmethod |
| | | def list_by_day(cls, day, min_update_time): |
| | | mysqldb = mysql_data.Mysqldb() |
| | | try: |
| | | results = mysqldb.select_all( |
| | | f"select * from hx_trade_delegate_record r where r.insertDate='{day}' and updateTime > '{min_update_time}' order by createTime") |
| | | # 转dict |
| | | key_list = ["orderLocalID", "securityID", "securityName", "direction", "orderSysID", "insertTime", |
| | | "insertDate", "acceptTime", "cancelTime", "limitPrice", "turnover", "volume", "volumeTraded", |
| | | "orderStatus", "orderSubmitStatus", "statusMsg", "createTime", "updateTime"] |
| | | fresults = [] |
| | | max_update_time = None |
| | | if results: |
| | | for r in results: |
| | | if not max_update_time: |
| | | max_update_time = r[-1] |
| | | if r[-1] > max_update_time: |
| | | max_update_time = r[-1] |
| | | |
| | | 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, max_update_time.strftime("%Y-%m-%d %H:%M:%S") if max_update_time else None |
| | | finally: |
| | | pass |
| | | |
| | | |
| | | # 成交记录 |
| | | class DealRecordManager: |
| | | pass |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | results = DelegateRecordManager.list_by_day('20230704', '1970-01-01') |
| | | print(results) |
New file |
| | |
| | | import hashlib |
| | | import json |
| | | import logging |
| | | import random |
| | | import socket |
| | | import socketserver |
| | | 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 import huaxin_trade_api as trade_api |
| | | from utils import socket_util |
| | | |
| | | |
| | | class MyTCPServer(socketserver.TCPServer): |
| | | def __init__(self, server_address, RequestHandlerClass): |
| | | socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=True) |
| | | |
| | | |
| | | # 如果使用异步的形式则需要再重写ThreadingTCPServer |
| | | class MyThreadingTCPServer(socketserver.ThreadingMixIn, MyTCPServer): pass |
| | | |
| | | |
| | | class MyBaseRequestHandle(socketserver.BaseRequestHandler): |
| | | __inited = False |
| | | |
| | | def setup(self): |
| | | self.__init() |
| | | |
| | | @classmethod |
| | | def __init(cls): |
| | | if cls.__inited: |
| | | return True |
| | | cls.__inited = True |
| | | cls.__req_socket_dict = {} |
| | | |
| | | def __is_sign_right(self, data_json): |
| | | list_str = [] |
| | | sign = data_json["sign"] |
| | | data_json.pop("sign") |
| | | for k in data_json: |
| | | list_str.append(f"{k}={data_json[k]}") |
| | | list_str.sort() |
| | | __str = "&".join(list_str) + "JiaBei@!*." |
| | | md5 = hashlib.md5(__str.encode(encoding='utf-8')).hexdigest() |
| | | if md5 != sign: |
| | | raise Exception("签名出错") |
| | | |
| | | @classmethod |
| | | def getRecvData(cls, skk): |
| | | data = "" |
| | | header_size = 10 |
| | | buf = skk.recv(header_size) |
| | | header_str = buf |
| | | if buf: |
| | | start_time = time.time() |
| | | buf = buf.decode('utf-8') |
| | | if buf.startswith("##"): |
| | | content_length = int(buf[2:10]) |
| | | received_size = 0 |
| | | while not received_size == content_length: |
| | | r_data = skk.recv(10240) |
| | | received_size += len(r_data) |
| | | data += r_data.decode('utf-8') |
| | | else: |
| | | data = skk.recv(1024 * 1024) |
| | | data = buf + data.decode('utf-8') |
| | | logger_l2_upload.info(f"读取数据耗时:{round((time.time() - start_time) * 1000, 1)}") |
| | | return data, header_str |
| | | |
| | | def handle(self): |
| | | host = self.client_address[0] |
| | | super().handle() |
| | | sk: socket.socket = self.request |
| | | while True: |
| | | try: |
| | | # data = sk.recv(1024*1024, socket.MSG_WAITALL) |
| | | data, header = self.getRecvData(sk) |
| | | if data: |
| | | data_str = data |
| | | # print("收到数据------", f"{data_str[:20]}......{data_str[-20:]}") |
| | | data_json = None |
| | | try: |
| | | data_json = json.loads(data_str) |
| | | except json.decoder.JSONDecodeError as e: |
| | | # JSON解析失败 |
| | | sk.sendall(json.dumps( |
| | | {"code": 100, "msg": f"JSON解析失败:字符串内容:{data_str[:30]}......{data_str[-20:]}"}).encode( |
| | | encoding='utf-8')) |
| | | logging.exception( |
| | | f"json解析失败,字符串长度:{len(data_str)},字符串内容:\"{data_str[:30]}......{data_str[-20:]}\"") |
| | | continue |
| | | if data_json["type"] == 'register': |
| | | client_type = data_json["data"]["client_type"] |
| | | rid = data_json["rid"] |
| | | trade_api.ClientSocketManager.add_client(client_type, rid, sk) |
| | | sk.sendall(json.dumps({"type": "register"}).encode(encoding='utf-8')) |
| | | try: |
| | | |
| | | # print("客户端", ClientSocketManager.socket_client_dict) |
| | | while True: |
| | | result, header = self.getRecvData(sk) |
| | | try: |
| | | resultJSON = json.loads(result) |
| | | if resultJSON["type"] == 'heart': |
| | | # 记录活跃客户端 |
| | | trade_api.ClientSocketManager.heart(resultJSON['client_id']) |
| | | else: |
| | | logger_contact_debug.warning(f"接收到非心跳信息:{result}") |
| | | except json.decoder.JSONDecodeError as e: |
| | | if not result: |
| | | sk.close() |
| | | print("JSON解析出错", result, header) |
| | | time.sleep(1) |
| | | except ConnectionResetError as ee: |
| | | trade_api.ClientSocketManager.del_client(rid) |
| | | except Exception as e: |
| | | logging.exception(e) |
| | | |
| | | 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')) |
| | | # print("响应结果:", data_json['data']) |
| | | elif data_json["type"] == "l2_order": |
| | | # L2逐笔委托 |
| | | data = data_json["data"] |
| | | code = data["code"] |
| | | datas = data["data"] |
| | | logger_l2_orderdetail.info(f"{code}#{datas}") |
| | | sk.sendall(json.dumps({"code": 0}).encode(encoding='utf-8')) |
| | | |
| | | elif data_json["type"] == "l2_trans": |
| | | data = data_json["data"] |
| | | code = data["code"] |
| | | datas = data["data"] |
| | | logger_l2_transaction.info(f"{code}#{datas}") |
| | | sk.sendall(json.dumps({"code": 0}).encode(encoding='utf-8')) |
| | | # ------客户端请求接口------- |
| | | elif data_json["type"] == 'buy': |
| | | # 验证签名 |
| | | 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"))) |
| | | continue |
| | | codes_data = data_json["data"] |
| | | code = codes_data["code"] |
| | | volume = codes_data["volume"] |
| | | price = codes_data["price"] |
| | | try: |
| | | # 验证签名是否正确 |
| | | result = trade_api.order(trade_api.TRADE_DIRECTION_BUY, code, volume, |
| | | round(float(price), 2)) |
| | | if result: |
| | | resultJSON = json.loads(result) |
| | | if resultJSON['code'] == 0: |
| | | # TODO 下单成功保存下单结果数据 |
| | | pass |
| | | else: |
| | | # 返回下单失败 |
| | | raise Exception("下单失败") |
| | | except Exception as e: |
| | | pass |
| | | print("---下单结果----") |
| | | sk.sendall(result.encode("utf-8")) |
| | | |
| | | elif data_json["type"] == 'cancel_order': |
| | | # 验证签名 |
| | | 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"))) |
| | | continue |
| | | |
| | | codes_data = data_json["data"] |
| | | code = codes_data["code"] |
| | | orderSysID = codes_data["orderSysID"] |
| | | try: |
| | | result = trade_api.cancel_order(trade_api.TRADE_DIRECTION_BUY, code, orderSysID, True) |
| | | print("---撤单结果----") |
| | | print(result) |
| | | sk.sendall(result.encode("utf-8")) |
| | | except Exception as e: |
| | | sk.sendall( |
| | | socket_util.load_header( |
| | | json.dumps({"code": 1, "msg": str(e)}).encode( |
| | | "utf-8"))) |
| | | |
| | | |
| | | elif data_json["type"] == 'sell': |
| | | # 验证签名 |
| | | 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"))) |
| | | continue |
| | | codes_data = data_json["data"] |
| | | code = codes_data["code"] |
| | | volume = codes_data["volume"] |
| | | price = codes_data["price"] |
| | | price_type = codes_data["price_type"] |
| | | result = trade_api.order(trade_api.TRADE_DIRECTION_SELL, code, volume, price, |
| | | price_type=price_type) |
| | | print("---卖出结果----") |
| | | print(result) |
| | | |
| | | elif data_json["type"] == 'test': |
| | | # 卖出 |
| | | # trade_api.order(trade_api.TRADE_DIRECTION_SELL, "600854", 100, 5.45) |
| | | result = trade_api.get_deal_list() |
| | | print("\n\n---成交列表----") |
| | | for d in result["data"]: |
| | | print(d) |
| | | |
| | | result = trade_api.get_delegate_list(True) |
| | | print("\n\n---可撤委托----") |
| | | for d in result["data"]: |
| | | print(d) |
| | | result = trade_api.get_delegate_list(False) |
| | | print("\n\n---全部委托----") |
| | | for d in result["data"]: |
| | | print(d) |
| | | |
| | | result = trade_api.get_position_list() |
| | | print("\n\n---持仓列表----") |
| | | for d in result["data"]: |
| | | print(d) |
| | | |
| | | result = trade_api.get_money() |
| | | print("\n\n---账户列表----") |
| | | for d in result["data"]: |
| | | print(d) |
| | | elif data_json["type"] == 'test_l2': |
| | | codes_data = data_json["data"] |
| | | result = trade_api.set_l2_codes_data(codes_data) |
| | | print("\n\n---L2设置结果----") |
| | | print(result) |
| | | else: |
| | | while True: |
| | | r = sk.recv(1024 * 100) |
| | | if r: |
| | | print(r.decode('utf-8')) |
| | | sk.sendall("123".encode('utf-8')) |
| | | |
| | | # result = trade_server_processor.process(data_json["data"]) |
| | | # sk.sendall(json.dumps({"code": 0}).encode(encoding='utf-8')) |
| | | else: |
| | | # 断开连接 |
| | | break |
| | | # sk.close() |
| | | except Exception as e: |
| | | logging.exception(e) |
| | | break |
| | | |
| | | def finish(self): |
| | | super().finish() |
| | | |
| | | |
| | | def run(): |
| | | laddr = "0.0.0.0", 10008 |
| | | tcpserver = MyThreadingTCPServer(laddr, MyBaseRequestHandle) # 注意:参数是MyBaseRequestHandle |
| | | # tcpserver.handle_request() # 只接受一个客户端连接 |
| | | tcpserver.serve_forever() |
| | | |
| | | |
| | | def test1(): |
| | | r = (trade_api.ClientSocketManager.acquire_client(trade_api.ClientSocketManager.CLIENT_TYPE_TRADE)) |
| | | print("test1", r) |
| | | time.sleep(random.randint(0, 3)) |
| | | if r: |
| | | trade_api.ClientSocketManager.release_client(r[0]) |
| | | |
| | | |
| | | def test2(): |
| | | time.sleep(random.randint(0, 3)) |
| | | print("test2", trade_api.ClientSocketManager.acquire_client(trade_api.ClientSocketManager.CLIENT_TYPE_TRADE)) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | run() |
| | | # ClientSocketManager.add_client(ClientSocketManager.CLIENT_TYPE_TRADE, "1", None) |
| | | # ClientSocketManager.add_client(ClientSocketManager.CLIENT_TYPE_TRADE, "2", None) |
| | | # ClientSocketManager.add_client(ClientSocketManager.CLIENT_TYPE_TRADE, "3", None) |
| | | # |
| | | # for i in range(0, 3): |
| | | # t1 = threading.Thread(target=lambda: test1()) |
| | | # t1.setDaemon(True) |
| | | # t1.start() |
| | | # |
| | | # for i in range(0, 3): |
| | | # t1 = threading.Thread(target=lambda: test2()) |
| | | # t1.setDaemon(True) |
| | | # t1.start() |
| | | # |
| | | while True: |
| | | time.sleep(10) |
| | |
| | | |
| | | # 交易订单号管理 |
| | | import constant |
| | | import tool |
| | | from utils import tool |
| | | from db.redis_manager import RedisManager |
| | | from log import logger_huaxin_trade |
| | | from logs.log import logger_huaxin_trade |
| | | |
| | | |
| | | class TradeOrderIdManager: |
| | |
| | | |
| | | # l2交易因子 |
| | | |
| | | import big_money_num_manager |
| | | from code_attribute import big_money_num_manager, limit_up_time_manager, global_data_loader, gpcode_manager |
| | | import constant |
| | | import global_data_loader |
| | | import global_util |
| | | import gpcode_manager |
| | | import limit_up_time_manager |
| | | from utils import global_util, tool |
| | | |
| | | |
| | | # 下单参数 |
| | | import tool |
| | | from l2 import code_price_manager |
| | | |
| | | |
| | | class L2PlaceOrderParamsManager: |
| | |
| | | # 是否在禁止交易代码中 |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | |
| | | __redis_manager = redis_manager.RedisManager(2) |
| | | |
| | |
| | | |
| | | # 交易撤销数据管理器 |
| | | import constant |
| | | import global_util |
| | | from utils import global_util, tool |
| | | import l2_data_util |
| | | from db import redis_manager |
| | | import tool |
| | | from log import logger_trade |
| | | from logs.log import logger_trade |
| | | |
| | | |
| | | class TradeCancelDataManager: |
| | |
| | | |
| | | import array |
| | | import logging |
| | | import re |
| | | import threading |
| | | import time |
| | | import random |
| | | |
| | | import numpy |
| | | import win32gui |
| | | import win32con |
| | | |
| | | import constant |
| | | from ocr import ocr_util |
| | | from trade import l2_trade_util |
| | | from db import redis_manager |
| | | from log import * |
| | | from tool import async_call |
| | | from logs.log import * |
| | | from utils.tool import async_call |
| | | from utils import win32_util, capture_util |
| | | |
| | | |
| | |
| | | import gm.api as gmapi |
| | | |
| | | import constant |
| | | import gpcode_manager |
| | | import tool |
| | | from code_attribute import gpcode_manager |
| | | from db.redis_manager import RedisManager |
| | | from log import logger_juejin_trade |
| | | from utils import network_util |
| | | from logs.log import logger_juejin_trade |
| | | from utils import network_util, tool |
| | | |
| | | __context_dict = {} |
| | | |
| | |
| | | 对一系列的代码交易变量,下单,撤单进行管理 |
| | | """ |
| | | # 交易管理器 |
| | | import json |
| | | import time |
| | | |
| | | import dask |
| | | |
| | | import constant |
| | | from db import mysql_data, redis_manager |
| | | from output import kp_client_msg_manager |
| | | from trade import trade_data_manager, l2_trade_util, trade_juejin |
| | | import trade.trade_gui |
| | | |
| | | import time as t |
| | | from l2 import l2_data_manager, l2_data_log |
| | | |
| | | from log import * |
| | | from logs.log import * |
| | | from utils import import_util |
| | | |
| | | trade_gui = import_util.import_lib("trade.trade_gui") |
| | | |
| | | __redis_manager = redis_manager.RedisManager(2) |
| | | |
| | |
| | | # 买成功 |
| | | TRADE_STATE_BUY_SUCCESS = 12 |
| | | |
| | | guiTrade = trade.trade_gui.THSGuiTrade() |
| | | guiTrade = trade_gui.THSGuiTrade() if trade_gui is not None else None |
| | | |
| | | latest_trade_delegate_data = [] |
| | | |
| | |
| | | l2_data_manager.TradePointManager.delete_buy_cancel_point(code) |
| | | l2_data_manager.TradePointManager.delete_buy_point(code) |
| | | # 移除交易窗口分配 |
| | | trade.trade_gui.THSBuyWinManagerNew.cancel_distribute_win_for_code(code) |
| | | if trade_gui is not None: |
| | | trade_gui.THSBuyWinManagerNew.cancel_distribute_win_for_code(code) |
| | | # 交易成功时间过去3s之后,且当前委托列表里面还有该代码数据就再次执行撤单 |
| | | if tool.trade_time_sub(tool.get_now_time_str(), _time) > 3: |
| | | # 获取到当前是否委托 |
| | |
| | | import decimal |
| | | import json |
| | | |
| | | import gpcode_manager |
| | | from code_attribute import gpcode_manager |
| | | from db import redis_manager |
| | | import tool |
| | | from utils import tool |
| | | from trade import trade_manager |
| | | |
| | | |
| | |
| | | LCancelBigNumComputer |
| | | from l2.l2_data_util import local_today_datas, local_today_num_operate_map |
| | | from l2.safe_count_manager import BuyL2SafeCountManager |
| | | from log import logger_l2_error |
| | | from logs.log import logger_l2_error |
| | | from trade import trade_data_manager |
| | | from trade.trade_queue_manager import THSBuy1VolumnManager |
| | | |
File was renamed from alert_util.py |
| | |
| | | |
| | | # 报警 |
| | | import constant |
| | | import tool |
| | | from utils import tool |
| | | |
| | | |
| | | def alarm(): |
| | |
| | | cls.__instance = super(AlertUtil, cls).__new__(cls, *args, **kwargs) |
| | | # 初始化设置 |
| | | pygame.mixer.init() |
| | | pygame.mixer.music.load('alert.mp3') |
| | | pygame.mixer.music.load('../alert.mp3') |
| | | pygame.mixer.music.set_volume(1) |
| | | return cls.__instance |
| | | |
New file |
| | |
| | | import hashlib |
| | | |
| | | |
| | | def md5_encrypt(value): |
| | | md5 = hashlib.md5() |
| | | md5.update(value.encode('utf-8')) |
| | | return md5.hexdigest() |
File was renamed from data_export_util.py |
| | |
| | | |
| | | import xlwt |
| | | |
| | | import gpcode_manager |
| | | import l2_data_util |
| | | import constant |
| | | from code_attribute import gpcode_manager |
| | | import l2.l2_data_util |
| | | import log |
| | | from logs import log |
| | | from l2 import l2_data_source_util |
| | | from trade import deal_big_money_manager |
| | | |
| | |
| | | export_l2_data(code, datas, process_indexs, trade_indexs) |
| | | |
| | | |
| | | def export_l2_data(code, datas, process_indexs, trade_indexs, dest_dir="D:/export/l2"): |
| | | def export_l2_data(code, datas, process_indexs, trade_indexs, dest_dir=f"{constant.get_path_prefix()}/export/l2"): |
| | | def find_process_index(index): |
| | | for i in range(0, len(process_indexs)): |
| | | if process_indexs[i][0] <= index <= process_indexs[i][1]: |
| | |
| | | return file_name |
| | | |
| | | |
| | | def export_l2_data_origin(code, datas, key, dest_dir="D:/export/l2_origin"): |
| | | def export_l2_data_origin(code, datas, key, dest_dir=f"{constant.get_path_prefix()}/export/l2_origin"): |
| | | file_dir = "{}/{}".format(dest_dir, code) |
| | | if not os.path.exists(file_dir): |
| | | os.makedirs(file_dir) |
| | |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | export_l2_excel("002343") |
| | | export_l2_excel("002765") |
File was renamed from data_process.py |
| | |
| | | # 数据处理 |
| | | import json |
| | | import logging |
| | | from db import redis_manager |
| | | from log import logger_l2_error |
| | | from logs.log import logger_l2_error |
| | | |
| | | __redisManager = redis_manager.RedisManager(0) |
| | | |
New file |
| | |
| | | import importlib |
| | | import importlib.util |
| | | |
| | | # 导入lib |
| | | import constant |
| | | |
| | | |
| | | def import_lib(name, only_enable_windows=True): |
| | | if only_enable_windows: |
| | | if not constant.is_windows(): |
| | | return None |
| | | if importlib.util.find_spec(name): |
| | | return importlib.import_module(name) |
| | | return None |
New file |
| | |
| | | """ |
| | | socket工具类 |
| | | """ |
| | | |
| | | # 添加数据头 |
| | | import json |
| | | |
| | | from utils import crypt_util |
| | | |
| | | |
| | | def load_header(data_bytes): |
| | | slen = '##%08d' % len(data_bytes) |
| | | return slen.encode("utf-8") + data_bytes |
| | | |
| | | |
| | | # 接收数据,去除头 |
| | | def recv_data(sk): |
| | | data = "" |
| | | header_size = 10 |
| | | buf = sk.recv(1024) |
| | | header_str = buf[:header_size] |
| | | if buf: |
| | | buf = buf.decode('utf-8') |
| | | if buf.startswith("##"): |
| | | content_length = int(buf[2:10]) |
| | | received_size = 0 |
| | | # 加上读取头的数据 |
| | | received_size += len(buf[header_size:]) |
| | | data += buf[header_size:].decode('utf-8') |
| | | while not received_size == content_length: |
| | | r_data = sk.recv(10240) |
| | | received_size += len(r_data) |
| | | data += r_data.decode('utf-8') |
| | | else: |
| | | data = sk.recv(1024 * 1024) |
| | | data = buf + data.decode('utf-8') |
| | | return data, header_str |
| | | |
| | | |
| | | # 客户端参数加密 |
| | | def encryp_client_params_sign(dataJson): |
| | | if type(dataJson) != dict: |
| | | return dataJson |
| | | str_list = [] |
| | | for k in dataJson: |
| | | if type(dataJson[k]) == dict: |
| | | str_list.append(f"{k}={json.dumps(dataJson[k])}") |
| | | else: |
| | | str_list.append(f"{k}={dataJson[k]}") |
| | | str_list.sort() |
| | | str_list.append("%Yeshi2014@#.") |
| | | dataJson["sign"] = crypt_util.md5_encrypt("&".join(str_list)) |
| | | return dataJson |
| | | |
| | | |
| | | # 客户端密码加密验证 |
| | | def is_client_params_sign_right(dataJson): |
| | | if type(dataJson) != dict: |
| | | return False |
| | | sign = dataJson["sign"] |
| | | dataJson.pop("sign") |
| | | str_list = [] |
| | | for k in dataJson: |
| | | if type(dataJson[k]) == dict: |
| | | str_list.append(f"{k}={json.dumps(dataJson[k],separators=(',',':'))}") |
| | | else: |
| | | str_list.append(f"{k}={dataJson[k]}") |
| | | str_list.sort() |
| | | str_list.append("%Yeshi2014@#.") |
| | | new_sign = crypt_util.md5_encrypt("&".join(str_list)) |
| | | #print("加密前字符串","&".join(str_list)) |
| | | if sign == new_sign: |
| | | return True |
| | | else: |
| | | return False |
File was renamed from ths_industry_util.py |
| | |
| | | # 同花顺行业 |
| | | import time |
| | | |
| | | import global_data_loader |
| | | import global_util |
| | | from code_attribute import global_data_loader |
| | | from utils import global_util, tool |
| | | from db import mysql_data |
| | | |
| | | # 获取行业映射 |
| | | import tool |
| | | |
| | | |
| | | def get_code_industry_maps(): |
File was renamed from tool.py |
| | |
| | | time_str = datetime.datetime.now().strftime("%H:%M:%S") |
| | | return time_str |
| | | |
| | | def get_now_datetime_str(): |
| | | time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| | | return time_str |
| | | |
| | | def get_now_timestamp(): |
| | | return round(time.time() * 1000) |