当前位置: 首页 > 工具软件 > VN.PY > 使用案例 >

量化交易之vn.py篇 - 同步仓位部分实现逻辑(分钟级别发单,on_bar实现)

蒙华翰
2023-12-01
    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.cancel_all()

        # get current strategy data & current strategy_position(buy & sell) of symbol & current real_position(buy & sell) of symbol
        self.strategy_position_dictionary = PositionJsonOperator.tqz_get_sum_position_jsonfile_data_buy_sell(
            self.cta_strategy_positionjson_file
        )
        self.tqz_update_and_merge_strategyReal_vt_symbols()
        strategy_position_buy, strategy_position_sell, real_position_buy, real_position_sell = self.tqz_get_strategy_position_and_real_position(
            market_vt_symbol=bar.vt_symbol,
            strategy_data=self.strategy_position_dictionary
        )
        current_futures_type = TQZSymbolOperator.tqz_get_futures_type(vt_symbol=bar.vt_symbol)
        min_offset_price = self.strategy_engine.contracts[bar.vt_symbol].pricetick

        # if current symbol is in syncronized condition, return;
        if self.__tqz_strategy_is_real(strategy_position_buy=strategy_position_buy, strategy_position_sell=strategy_position_sell, real_position_buy=real_position_buy, real_position_sell=real_position_sell, futures_type=current_futures_type) is True:
            return
        
        if (bar.vt_symbol not in self.strategy_vt_symbols) or current_futures_type in [TQZFuturesType.COMMODITY_FUTURES, TQZFuturesType.TREASURY_FUTURES]:

            self.tqz_synchronization_position_double_direction_mode(
                market_vt_symbol=bar.vt_symbol,
                now_price=bar.close_price,
                offset_price=(min_offset_price * 5),
                strategy_position_buy=strategy_position_buy,
                strategy_position_sell=strategy_position_sell,
                real_position_buy=real_position_buy,
                real_position_sell=real_position_sell
            )

        elif current_futures_type is TQZFuturesType.STOCK_INDEX_FUTURES:

            self.tqz_synchronization_position_lock_mode(
                market_vt_symbol=bar.vt_symbol,
                now_price=bar.close_price,
                offset_price=(min_offset_price * 5),
                strategy_position_net=(strategy_position_buy - strategy_position_sell),
                real_position_net=(real_position_buy - real_position_sell)
            )

        else:
            pass

        self.put_event()


    def tqz_synchronization_position_lock_mode(self, market_vt_symbol, now_price, offset_price, strategy_position_net, real_position_net,):
        """
        synchronization position with lock mode(cffex mode)
        """

        vt_orderids = []

        if strategy_position_net > 0 and real_position_net > 0:

            if strategy_position_net > real_position_net:

                lot = TQZPositionData.tqz_risk_control(lot=strategy_position_net-real_position_net)
                print(f'开多 {str(lot)} 手', end="  ")
                vt_orderids = self.buy(vt_symbol=market_vt_symbol, price=(now_price + offset_price), volume=lot, lock=True)
                print(f'vt_orderids: {vt_orderids}')

            elif strategy_position_net < real_position_net:

                lot = TQZPositionData.tqz_risk_control(lot=real_position_net - strategy_position_net)
                print(f'平多 {str(lot)} 手', end="  ")
                vt_orderids = self.sell(vt_symbol=market_vt_symbol, price=(now_price - offset_price), volume=lot, lock=True)
                print(f'vt_orderids: {vt_orderids}')

            elif strategy_position_net == real_position_net:
                print(f'净仓相等, 不做处理')

        elif strategy_position_net > 0 and real_position_net < 0:

            lot = TQZPositionData.tqz_risk_control(lot=strategy_position_net-real_position_net)
            print(f'开多 {str(lot)} 手', end="  ")
            vt_orderids = self.buy(vt_symbol=market_vt_symbol, price=(now_price + offset_price), volume=lot, lock=True)
            print(f'vt_orderids: {vt_orderids}')

        elif strategy_position_net < 0 and real_position_net > 0:

            lot = TQZPositionData.tqz_risk_control(lot=real_position_net - strategy_position_net)
            print(f'开空 {str(lot)} 手', end="  ")
            vt_orderids = self.short(vt_symbol=market_vt_symbol, price=(now_price - offset_price), volume=lot, lock=True)
            print(f'vt_orderids: {vt_orderids}')

        elif strategy_position_net < 0 and real_position_net < 0:

            if abs(strategy_position_net) > abs(real_position_net):

                lot = TQZPositionData.tqz_risk_control(lot=abs(strategy_position_net)-abs(real_position_net))
                print(f'开空 {str(lot)} 手', end="  ")
                vt_orderids = self.short(vt_symbol=market_vt_symbol, price=(now_price - offset_price), volume=lot, lock=True)
                print(f'vt_orderids: {vt_orderids}')

            elif abs(strategy_position_net) < abs(real_position_net):

                lot = TQZPositionData.tqz_risk_control(lot=abs(real_position_net) - abs(strategy_position_net))
                print(f'平空 {str(lot)} 手', end="  ")
                vt_orderids = self.cover(vt_symbol=market_vt_symbol, price=(now_price + offset_price), volume=lot, lock=True)
                print(f'vt_orderids: {vt_orderids}')

            elif strategy_position_net == real_position_net:
                print(f'净仓相等, 不做处理')

        return vt_orderids

    def tqz_synchronization_position_double_direction_mode(self, market_vt_symbol, now_price, offset_price, strategy_position_buy, strategy_position_sell, real_position_buy, real_position_sell):
        """
        synchronization position with double direction(buy direction & sell direction) mode
        """

        buy_vt_orderids = []
        sell_vt_orderids = []

        interval = " | "
        print(market_vt_symbol, end="  ")
        if strategy_position_buy > real_position_buy:

            lot = TQZPositionData.tqz_risk_control(lot=strategy_position_buy - real_position_buy)
            print(f'开多 {str(lot)} 手', end="  ")
            buy_vt_orderids = self.buy(vt_symbol=market_vt_symbol, price=(now_price+offset_price), volume=lot)
            print(f'buy_result: {buy_vt_orderids}', end=interval)

        elif strategy_position_buy < real_position_buy:

            lot = TQZPositionData.tqz_risk_control(lot=real_position_buy - strategy_position_buy)
            print(f'平多 {str(lot)} 手', end="  ")
            buy_vt_orderids = self.sell(vt_symbol=market_vt_symbol, price=(now_price-offset_price), volume=lot)
            print(f'sell_result: {buy_vt_orderids}', end=interval)

        elif strategy_position_buy is real_position_buy:
            print("多单匹配 不处理", end=interval)

        if strategy_position_sell > real_position_sell:

            lot = TQZPositionData.tqz_risk_control(lot=strategy_position_sell - real_position_sell)
            print(f'开空 {str(lot)} 手', end="  ")
            sell_vt_orderids = self.short(vt_symbol=market_vt_symbol, price=(now_price-offset_price), volume=lot)
            print(f'short_result: {sell_vt_orderids}')

        elif strategy_position_sell < real_position_sell:

            lot = TQZPositionData.tqz_risk_control(lot=real_position_sell - strategy_position_sell)
            print(f'平空 {str(lot)} 手', end="  ")
            sell_vt_orderids = self.cover(vt_symbol=market_vt_symbol, price=(now_price+offset_price), volume=lot)
            print(f'cover_result: {sell_vt_orderids}')

        elif strategy_position_sell is real_position_sell:
            print("空单匹配 不处理")

        return list(set(buy_vt_orderids + sell_vt_orderids))  # 返回值: [vt_orderids]

    def tqz_get_strategy_position_and_real_position(self, market_vt_symbol, strategy_data):
        """
        get real position(buy, sell) and strategy position(buy, sell)
        """

        # strategy position
        strategy_position_buy = TQZSymbolOperator.tqz_get_strategy_position(
            market_vt_symbol=market_vt_symbol,
            direction=Direction.LONG,
            strategy_data=strategy_data
        )
        strategy_position_sell = TQZSymbolOperator.tqz_get_strategy_position(
            market_vt_symbol=market_vt_symbol,
            direction=Direction.SHORT,
            strategy_data=strategy_data
        )

        # real position
        real_position_buy = self.tqz_get_real_position(
            market_vt_symbol=market_vt_symbol,
            direction=Direction.LONG
        )
        real_position_sell = self.tqz_get_real_position(
            market_vt_symbol=market_vt_symbol,
            direction=Direction.SHORT
        )

        return strategy_position_buy, strategy_position_sell, real_position_buy, real_position_sell

    def tqz_update_and_merge_strategyReal_vt_symbols(self):
        """
        Update and Merge current strategy vt_symbols and real vt_symbols, return a new vt_symbols list(strategy and real)
        """

        self.real_vt_symbols = []
        [self.real_vt_symbols.append(
            TQZSymbolOperator.get_vt_symbol(
                strategy_symbol=position_data_model.vt_symbol_direction
            )
        ) for position_data_model in TQZPositionData.position_data_models()]

        self.strategy_vt_symbols = list(set(TQZSymbolOperator.tqz_get_strategy_vt_symbols(
            self.strategy_position_dictionary.keys()
        )))

        return list(set(self.strategy_vt_symbols + self.real_vt_symbols))


    # ------ private part ------
    def __tqz_strategy_is_real(self, strategy_position_buy, real_position_buy, strategy_position_sell, real_position_sell, futures_type: TQZFuturesType):
        """
        strategy position(buy, sell) is real position(buy, sell) or not
        """

        if futures_type in [TQZFuturesType.COMMODITY_FUTURES, TQZFuturesType.TREASURY_FUTURES]:
            is_same = (strategy_position_buy is real_position_buy) and (strategy_position_sell is real_position_sell)
        elif futures_type is TQZFuturesType.STOCK_INDEX_FUTURES:
            is_same = (strategy_position_buy - strategy_position_sell) is (real_position_buy - real_position_sell)
        else:
            self.write_log("__tqz_strategy_is_real: 理论上这句代码不会执行.")
            is_same = True

        return is_same

 

 类似资料: