Administrator
2023-04-21 0ed2c53acd278d57a39390fd4db78c5aaf088e0a
juejin.py
@@ -31,9 +31,8 @@
import authority
import decimal
from trade import trade_gui, l2_trade_util
from trade import trade_gui, l2_trade_util, trade_manager
from l2.cancel_buy_strategy import L2LimitUpSellStatisticUtil
from l2_code_operate import L2CodeOperate
from log import logger_juejin_tick, logger_system
from trade.trade_data_manager import CodeActualPriceProcessor
from trade.trade_queue_manager import JueJinBuy1VolumnManager
@@ -74,7 +73,7 @@
    global_data_loader.load_volumn()
    # 9点25之前删除所有代码
    if tool.trade_time_sub(tool.get_now_time_str(), "09:25:00") <= 0:
    if tool.trade_time_sub(tool.get_now_time_str(), "09:25:00") <= 0 or True:
        # 删除L2监听代码
        gpcode_manager.clear_listen_codes()
        # 删除首板代码
@@ -87,6 +86,8 @@
        l2_trade_util.WhiteListCodeManager.clear()
        # 清空想要买
        gpcode_manager.WantBuyCodesManager.clear()
        # 清空分数禁止代码
        trade_manager.ForbiddenBuyCodeByScoreManager.clear()
# 每日初始化
@@ -101,7 +102,7 @@
    # 今日实时涨停
    global_data_loader.add_limit_up_codes([], True)
    # 主要获取收盘价
    get_latest_info(None)
    __get_latest_info(None)
    # 获取60天最大量与昨日量
    global_util.today_volumn.clear()
    global_util.max60_volumn.clear()
@@ -147,11 +148,11 @@
    t1.start()
    # 多个时间点获取收盘价
    gmapi.schedule(schedule_func=get_latest_info, date_rule='1d', time_rule='08:30:00')
    gmapi.schedule(schedule_func=get_latest_info, date_rule='1d', time_rule='08:50:00')
    gmapi.schedule(schedule_func=get_latest_info, date_rule='1d', time_rule='09:28:00')
    gmapi.schedule(schedule_func=get_current_info, date_rule='1d', time_rule='09:25:00')
    gmapi.schedule(schedule_func=get_current_info, date_rule='1d', time_rule='09:29:00')
    gmapi.schedule(schedule_func=__get_latest_info, date_rule='1d', time_rule='08:30:00')
    gmapi.schedule(schedule_func=__get_latest_info, date_rule='1d', time_rule='08:50:00')
    gmapi.schedule(schedule_func=__get_latest_info, date_rule='1d', time_rule='09:28:00')
    gmapi.schedule(schedule_func=__get_current_info, date_rule='1d', time_rule='09:25:00')
    gmapi.schedule(schedule_func=__get_current_info, date_rule='1d', time_rule='09:29:00')
    re_subscribe_tick()
    # re_subscribe_bar()
@@ -162,7 +163,7 @@
            gpcode_manager.init_listen_code_by_pos(client, i)
def get_latest_info(context):
def __get_latest_info(context):
    # 初始化内容
    clients = authority.get_l2_clients()
    for c in clients:
@@ -183,7 +184,7 @@
# 获取最新的信息
def get_current_info():
def __get_current_info():
    data = gpcode_manager.get_gp_list()
    results = JueJinManager.get_gp_current_info(data)
    logger_juejin_tick.debug("定时获取:{}", results)
@@ -192,7 +193,6 @@
        symbol = result['symbol']
        # 保存最新价
        symbol = symbol.split(".")[1]
        accpt_price(symbol, price)
# 设置收盘价
@@ -244,150 +244,7 @@
        #     L2LimitUpMoneyStatisticUtil.verify_num(data_[0], data_[2], data_[1])
        # print(tick["created_at"],tick["quotes"][0]["bid_v"])
        accpt_price(symbol, price)
        __prices_now[symbol] = price
# 获取到现价
def accpt_price(code, price, price_from="juejin"):
    return
    gpcode_manager.set_price(code, price)
    # 获取收盘价
    pricePre = gpcode_manager.get_price_pre(code)
    if pricePre is not None:
        rate = round((price - pricePre) * 100 / pricePre, 1)
        if rate >= 7:
            logger_juejin_tick.info("{}-{}-{}", code, price, rate)
            if not gpcode_manager.is_listen_old(code) and not gpcode_manager.is_operate(
                    code) and not gpcode_manager.is_listen_full():
                L2CodeOperate.get_instance().add_operate(1, code, "现价变化,rate-{} from-{}".format(rate, price_from))
            # 进入监控
        elif rate < 5:
            # 移除监控
            if gpcode_manager.is_listen_old(code) and not gpcode_manager.is_operate(code):
                L2CodeOperate.get_instance().add_operate(0, code, "现价变化,rate-{} from-{}".format(rate, price_from))
# 获取到现价
def accept_prices(prices):
    # 获取首板代码
    first_codes = gpcode_manager.get_first_gp_codes()
    print("价格代码数量:", len(prices))
    __actualPriceProcessor.save_current_price_codes_count(len(prices))
    # 采集的代码数量不对
    if len(gpcode_manager.get_gp_list()) - len(prices) > 10:
        return
    now_str = tool.get_now_time_str()
    now_strs = now_str.split(":")
    now_second = int(now_strs[0]) * 60 * 60 + int(now_strs[1]) * 60 + int(now_strs[2])
    start = 60 * 60 * 9 + 31 * 60
    if False:
        for d in prices:
            code, price = d["code"], float(d["price"])
            accpt_price(code, price, "ths")
    else:
        _code_list = []
        _delete_list = []
        for d in prices:
            code, price = d["code"], float(d["price"])
            gpcode_manager.set_price(code, price)
            # 获取收盘价
            pricePre = gpcode_manager.get_price_pre(code)
            if pricePre is not None:
                rate = round((price - pricePre) * 100 / pricePre, 2)
                if first_codes and code in first_codes:
                    rate = rate / 2
                if rate >= 0:
                    # 暂存涨幅为正的代码
                    _code_list.append((rate, code))
                else:
                    # 暂存涨幅为负的代码
                    _delete_list.append((rate, code))
                try:
                    __actualPriceProcessor.process_rate(code, rate, now_str)
                except Exception as e:
                    logging.exception(e)
                try:
                    __actualPriceProcessor.save_current_price(code, price,
                                                              gpcode_manager.get_limit_up_price_by_preprice(
                                                                  pricePre) == tool.to_price(
                                                                  decimal.Decimal(d["price"])))
                except Exception as e:
                    logging.exception(e)
        # -------------------------------处理交易位置分配---------------------------------
        # 排序
        new_code_list = sorted(_code_list, key=lambda e: (e.__getitem__(0), e.__getitem__(1)), reverse=True)
        # 预填充下单代码
        _buy_win_codes = []
        for d in new_code_list:
            _buy_win_codes.append(d[1])
        for d in _delete_list:
            _buy_win_codes.append(d[1])
        try:
            trade_gui.THSBuyWinManagerNew.fill_codes(_buy_win_codes)
        except Exception as e:
            logging.exception(e)
            pass
        # -------------------------------处理L2监听---------------------------------
        client_ids = client_manager.getValidL2Clients()
        # 最多填充的代码数量
        max_count = len(client_ids) * constant.L2_CODE_COUNT_PER_DEVICE
        if max_count == 0:
            max_count = constant.L2_CODE_COUNT_PER_DEVICE
        _delete_list = []
        for item in new_code_list:
            if l2_trade_util.is_in_forbidden_trade_codes(item[1]) or item[0] < 0:
                _delete_list.append(item)
        for item in _delete_list:
            new_code_list.remove(item)
        # 截取前几个代码填充
        add_list = new_code_list[:max_count]
        # 后面的代码全部删除
        _delete_list.extend(new_code_list[max_count:])
        add_code_list = []
        del_code_list = []
        for d in add_list:
            add_code_list.append(d[1])
        for d in _delete_list:
            del_code_list.append(d[1])
        # 后面的代码数量
        # 先删除应该删除的代码
        for code in del_code_list:
            if gpcode_manager.is_listen_old(code):
                # 判断是否在监听里面
                L2CodeOperate.get_instance().add_operate(0, code, "现价变化")
        # 增加应该增加的代码
        for code in add_code_list:
            if not gpcode_manager.is_listen_old(code):
                L2CodeOperate.get_instance().add_operate(1, code, "现价变化")
        # 获取卡位数量
        free_count = gpcode_manager.get_free_listen_pos_count()
        if free_count < 2:
            # 空闲位置不足
            listen_codes = gpcode_manager.get_listen_codes()
            for code in listen_codes:
                if not gpcode_manager.is_in_gp_pool(code):
                    client_id, pos = gpcode_manager.get_listen_code_pos(code)
                    gpcode_manager.set_listen_code_by_pos(client_id, pos, "")
                    free_count += 1
                    if free_count > 2:
                        break
        print(add_code_list, del_code_list)
def on_bar(context, bars):
    print("on_bar", bars)
@@ -421,8 +278,8 @@
        elif action == 'accpt_price':
            try:
                datas = jsonValue["data"]
                for data in datas:
                    accpt_price(data["code"], float(data["price"]))
                # for data in datas:
                #     accpt_price(data["code"], float(data["price"]))
            except Exception as e:
                print(str(e))
@@ -557,15 +414,6 @@
        return gmapi.get_trading_dates("SHSE", start_date, end_date)
def trade(code, volume):
    account_id, s_id, token = getAccountInfo()
    gmapi.set_token(token)
    gmapi.set_account_id(account_id)
    result = gmapi.order_volume(symbol=code, volume=volume, side=gmapi.OrderSide_Sell,
                                order_type=gmapi.OrderType_Market, position_effect=gmapi.PositionEffect_Close)
    print(result)
# 获取近90天的最大量与最近的量
def get_volumns(codes):
    end = datetime.datetime.now()
@@ -639,47 +487,5 @@
    return max_volume, max_volume, max_volume_date.strftime("%Y-%m-%d")
# 是否有涨停
def is_have_limit_up(datas):
    for i in range(len(datas)):
        item = datas[i]
        limit_up_price = float(gpcode_manager.get_limit_up_price_by_preprice(item["pre_close"]))
        if abs(limit_up_price - item["close"]) < 0.01:
            return True
    return False
# 首板涨停溢价率
def get_limit_up_money_percent(datas):
    datas.sort(key=lambda x: x["bob"])
    first_rate_list = []
    for i in range(0, len(datas)):
        item = datas[i]
        limit_up_price = float(gpcode_manager.get_limit_up_price_by_preprice(item["pre_close"]))
        if abs(limit_up_price - item["close"]) < 0.001 and abs(
                limit_up_price - datas[i - 1]["close"]) >= 0.001 and 0 < i < len(datas) - 1:
            # 首板涨停
            rate = (datas[i + 1]["high"] - datas[i + 1]["pre_close"]) / datas[i + 1]["pre_close"]
            first_rate_list.append(rate)
    if not first_rate_list:
        return 1
    count = 0
    for rate in first_rate_list:
        if rate >= 0.01:
            count += 1
    return count / len(first_rate_list)
# 根据涨幅高低分配交易窗口
def distribute_buy_win():
    if tool.trade_time_sub(tool.get_now_time_str(), "09:30:00") > 0:
        raise Exception("只能9:30之前重新分配窗口")
    datas = JueJinManager.get_codes_limit_rate(gpcode_manager.get_gp_list())
    matrix = numpy.array(datas)
    codes = matrix[:, 0].tolist()
    trade_gui.THSBuyWinManagerNew.fill_codes(codes)
if __name__ == '__main__':
    print(JueJinManager.get_trading_dates("2023-03-01", "2023-03-29"))
    init_data()