def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super(BollChannelStrategy, self).__init__(cta_engine, strategy_name,
                                                  vt_symbol, setting)

        self.bg = BarGenerator(self.on_bar, 15, self.on_15min_bar)
        self.am = ArrayManager()
예제 #2
0
class Single_bar:
    """
    用来生成单品种的K线
    
    """
    def __init__(self, strategy: StrategyTemplate, vt_symbol: str):
        """"""
        # 和portfolio的接口
        self.portfolio = strategy
        self.vt_symbol = vt_symbol

        # 需要合成的K线周期设置
        self.bar_interval = self.portfolio.bar_interval
        self.bar_frequency = self.portfolio.bar_frequency

        # K线合成工具和储存容器
        self.bg = BarGenerator(self.on_bar, self.bar_interval,
                               self.on_5min_bar, self.bar_frequency)
        self.am = ArrayManager()

        # K线合成计数
        self.bar_count = 0

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.bg.update_bar(bar)

    def on_5min_bar(self, bar: BarData):
        """"""
        self.bar_count += 1
        self.am.update_bar(bar)
    def __init__(self, strategy_engine, strategy_name: str, spread: SpreadData,
                 setting: dict):
        """"""
        super().__init__(strategy_engine, strategy_name, spread, setting)

        self.bg = BarGenerator(self.on_spread_bar)
        self.am = ArrayManager()
예제 #4
0
class Ma1(CtaTemplate):
    author = "李鹏"
    fast_window = 10
    slow_window = 20
    fixed_size = 1
    fast_ma1 = 0.0
    fast_ma2 = 0.0
    slow_ma1 = 0.0
    slow_ma2 = 0.0

    parameters = ["fast_window", "slow_window", "fixed_size"]
    variables = ["fast_ma1", "fast_ma2", "slow_ma1", "slow_ma2"]

    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        super(Ma1, self).__init__(cta_engine, strategy_name, vt_symbol, setting)
        # K 线生成器,用来生成分钟K线 小时K线 日K线 或者周K线 主要是根据tick线生成K线
        self.bg = BarGenerator(self.on_bar)
        # K线序列管理器
        self.am = ArrayManager()

    def on_init(self):
        self.write_log("策略初始化")
        self.load_bar(20)

    def on_start(self):
        self.write_log("策略启动")

    def on_tick(self, tick: TickData):
        self.bg.update_tick(tick)

    def on_bar(self, bar: BarData):
        # 默认的分钟K线更新,除了tick级别和分钟K线级别是这两个,其他上层级别可自己定义
        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return
        fast_ma = am.sma(self.fast_window, array=True)
        # 获取最新的快速均线值,因为每根K线都是在形成后才调用的这个函数,所以不用刻意的向前跳
        self.fast_ma1 = fast_ma[-1]
        self.fast_ma2 = fast_ma[-2]
        slow_ma = am.sma(self.slow_window, array=True)
        self.slow_ma1 = slow_ma[-1]
        self.slow_ma2 = slow_ma[-2]
        # 上穿和下穿的标志
        cross_over = self.fast_ma1 > self.slow_ma1 and self.fast_ma2 < self.slow_ma2
        cross_below = self.fast_ma1 < self.slow_ma1 and self.fast_ma2 > self.slow_ma2
        if cross_over:
            if self.pos == 0:
                # 当前空仓就多头开仓
                self.buy(bar.close_price, self.fixed_size)  # 多头开仓,买开
            elif self.pos < 0:
                # 当前空头持仓,就平掉空仓,再多头开仓
                self.cover(bar.close_price, self.fixed_size)  # 空头平仓,买平
                self.buy(bar.close_price, self.fixed_size)  # 买开
        if cross_below:
            if self.pos == 0:
                self.short(bar.close_price, self.fixed_size)
            elif self.pos > 0:
                self.sell(bar.close_price, self.fixed_size)
                self.short(bar.close_price, self.fixed_size)
예제 #5
0
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super(TurtleSignalStrategy, self).__init__(cta_engine, strategy_name,
                                                   vt_symbol, setting)

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()
예제 #6
0
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super(DualThrustStrategy, self).__init__(cta_engine, strategy_name,
                                                 vt_symbol, setting)

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()
        self.bars = []
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super(KingKeltnerStrategy, self).__init__(
            cta_engine, strategy_name, vt_symbol, setting
        )

        self.bg = BarGenerator(self.on_bar, 5, self.on_5min_bar)
        self.am = ArrayManager()
예제 #8
0
    def __init__(self, strategy_engine: StrategyEngine, strategy_name: str,
                 vt_symbols: List[str], setting: dict):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)

        self.vt_symbol = vt_symbols[0]
        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()
예제 #9
0
    def __init__(self, fast_window: int, slow_window: int):
        """"""
        super(MaSignal, self).__init__()

        self.fast_window = fast_window
        self.slow_window = slow_window

        self.bg = BarGenerator(self.on_bar, 5, self.on_5min_bar)
        self.am = ArrayManager()
예제 #10
0
 def to_1m_bar(self):
     '''
     这里用的vnpy的BarGenerator,从tick数据生成1m bar数据
     '''
     bars = []
     def on_bar(bar):
         bars.append(bar)
     bargenerator = BarGenerator(on_bar=on_bar)
     for tick in self.to_vnpy_tick():
         bargenerator.update_tick(tick)
     return bars
예제 #11
0
    def __init__(self, rsi_window: int, rsi_level: float):
        """Constructor"""
        super(RsiSignal, self).__init__()

        self.rsi_window = rsi_window
        self.rsi_level = rsi_level
        self.rsi_long = 50 + self.rsi_level
        self.rsi_short = 50 - self.rsi_level

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()
예제 #12
0
    def __init__(self, cci_window: int, cci_level: float):
        """"""
        super(CciSignal, self).__init__()

        self.cci_window = cci_window
        self.cci_level = cci_level
        self.cci_long = self.cci_level
        self.cci_short = -self.cci_level

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()
예제 #13
0
    def __init__(self, strategy_engine, strategy_name: str, spread: SpreadData,
                 setting: dict):
        """"""
        super().__init__(strategy_engine, strategy_name, spread, setting)

        self.bg = BarGenerator(self.on_open_spread_bar, self.open_window,
                               self.on_open_spread_bar)
        self.am = ArrayManager()

        self.spread_pos = 0.0
        self.boll_up = 0.0
        self.boll_down = 0.0
        self.boll_mid = 0.0
예제 #14
0
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super(MultiTimeframeStrategy, self).__init__(cta_engine, strategy_name,
                                                     vt_symbol, setting)

        self.rsi_long = 50 + self.rsi_signal
        self.rsi_short = 50 - self.rsi_signal

        self.bg5 = BarGenerator(self.on_bar, 5, self.on_5min_bar)
        self.am5 = ArrayManager()

        self.bg15 = BarGenerator(self.on_bar, 15, self.on_15min_bar)
        self.am15 = ArrayManager()
    def __init__(self, strategy_engine: StrategyEngine, strategy_name: str,
                 vt_symbols: List[str], setting: dict):

        super(TurtleStrategy, self).__init__(strategy_engine, strategy_name,
                                             vt_symbols, setting)
        self.vt_symbols = vt_symbols
        # 合约的list
        self.total_long = 0
        # 所有合约的多仓位和
        self.total_short = 0
        # 所有合约的空仓位和
        self.context = {
            symbol: {
                'entry_long': 0,  # 开/加多仓价格阈值
                'entry_short': 0,  # 开/加空仓价格阈值
                'exit_long': 0,  # 平多仓价格阈值
                'exit_short': 0,  # 平空仓价格阈值
                'atr_value': 0,  # ATR
                'stop_loss_long': 0,  # 多仓止损价格
                'stop_loss_short': 0,  # 空仓止损价格
                'multiplier': 0,  # 合约规模
                'unit': 0,  # 仓位
                'am': ArrayManager(),
            }
            for symbol in vt_symbols
        }

        def on_bar(bar: BarData):
            pass

        self.bgs = {symbol: BarGenerator(on_bar)
                    for symbol in vt_symbols}
        self.last_tick_time: datetime = None
    def __init__(
        self,
        strategy_engine: StrategyEngine,
        strategy_name: str,
        vt_symbols: List[str],
        setting: dict
    ):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)

        self.bgs: Dict[str, BarGenerator] = {}
        self.targets: Dict[str, int] = {}
        self.last_tick_time: datetime = None
        self.amplitude_data: Dict[str, np.array] = {}
        self.volitility_data: Dict[str, int] = {}
        self.sorted_volitility_data: list[np.array] = [] 
        self.selected_symbols: list[str] = []
        self.bar_count: int = 0
        
        for vt_symbol in self.vt_symbols:
            self.amplitude_data[vt_symbol] = np.zeros(volitility_window)
            self.volitility_data[vt_symbol] = np.zeros(1)

        # Obtain contract info
        #self.leg1_symbol, self.leg2_symbol = vt_symbols

        def on_bar(bar: BarData):
            """"""
            pass

        for vt_symbol in self.vt_symbols:
            self.targets[vt_symbol] = 0
            self.bgs[vt_symbol] = BarGenerator(on_bar, Interval.Day)
예제 #17
0
    def new_chart(self) -> None:
        """"""
        # Filter invalid vt_symbol
        vt_symbol = self.symbol_line.text()
        if not vt_symbol:
            return

        if vt_symbol in self.charts:
            return

        contract = self.main_engine.get_contract(vt_symbol)
        if not contract:
            return

        # Create new chart
        self.bgs[vt_symbol] = BarGenerator(self.on_bar)

        chart = self.create_chart()
        self.charts[vt_symbol] = chart

        self.tab.addTab(chart, vt_symbol)

        # Query history data
        end = datetime.now(get_localzone())
        start = end - timedelta(days=5)

        self.chart_engine.query_history(vt_symbol, Interval.MINUTE, start, end)
예제 #18
0
    def __init__(
        self,
        strategy_engine: StrategyEngine,
        strategy_name: str,
        vt_symbols: List[str],
        setting: dict
    ):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)

        self.bgs: Dict[str, BarGenerator] = {}
        self.ams: Dict[str, ArrayManager] = {}

        self.rsi_data: Dict[str, float] = {}
        self.atr_data: Dict[str, float] = {}
        self.atr_ma: Dict[str, float] = {}
        self.intra_trade_high: Dict[str, float] = {}
        self.intra_trade_low: Dict[str, float] = {}

        self.targets: Dict[str, int] = {}
        self.last_tick_time: datetime = None

        # Obtain contract info
        for vt_symbol in self.vt_symbols:
            def on_bar(bar: BarData):
                """"""
                pass

            self.bgs[vt_symbol] = BarGenerator(on_bar)
            self.ams[vt_symbol] = ArrayManager()
            self.targets[vt_symbol] = 0
예제 #19
0
    def __init__(self, strategy_engine: StrategyEngine, strategy_name: str,
                 vt_symbols: List[str], setting: dict):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)

        self.bgs: Dict[str, BarGenerator] = {}
        self.last_tick_time: datetime = None

        # Obtain contract info
        for vt_symbol in self.vt_symbols:
            symbol, exchange = extract_vt_symbol(vt_symbol)

            if "C" in symbol:
                self.call_symbol = vt_symbol
                _, strike_str = symbol.split("-C-")  # For CFFEX/DCE options
                self.strike_price = int(strike_str)
            elif "P" in symbol:
                self.put_symbol = vt_symbol
            else:
                self.futures_symbol = vt_symbol

            def on_bar(bar: BarData):
                """"""
                pass

            self.bgs[vt_symbol] = BarGenerator(on_bar)
예제 #20
0
    def __init__(
        self,
        strategy_engine: StrategyEngine,
        strategy_name: str,
        vt_symbols: List[str],
        setting: dict
    ):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)

        self.bgs: Dict[str, BarGenerator] = {}
        self.targets: Dict[str, int] = {}
        self.last_tick_time: datetime = None

        self.spread_count: int = 0
        self.spread_data: np.array = np.zeros(100)

        # Obtain contract info
        self.leg1_symbol, self.leg2_symbol = vt_symbols

        def on_bar(bar: BarData):
            """"""
            pass

        for vt_symbol in self.vt_symbols:
            self.targets[vt_symbol] = 0
            self.bgs[vt_symbol] = BarGenerator(on_bar)
예제 #21
0
    def __init__(self, strategy_engine: StrategyEngine, strategy_name: str,
                 vt_symbols: List[str], setting: dict):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)

        self.bgs: Dict[str, BarGenerator] = {}
        self.last_tick_time: datetime = None

        for vt_symbol in self.vt_symbols:

            def on_bar(bar: BarData):
                """"""
                pass

            self.bgs[vt_symbol] = BarGenerator(on_bar)

        # 单品种K线合成class
        self.bars = {}
        for vt_symbol in self.vt_symbols:
            self.bars[vt_symbol] = Single_bar(self, vt_symbol)

        self.y_symbol = vt_symbols[0]
        self.x_symbol = vt_symbols[1]

        # 单品种K线获取接口
        self.am1 = self.bars[self.y_symbol].am
        self.am2 = self.bars[self.x_symbol].am

        # 用来计算是否合成了一根bar

        self.bar_count = 1

        self.df = []
        self.mean = []
        self.std = []
예제 #22
0
    def __init__(
        self,
        strategy_engine: StrategyEngine,
        strategy_name: str,
        vt_symbols: List[str],
        setting: dict
    ):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)
        
        self.last_tick_time: datetime = None
        self.ams:Dict[str, ArrayManager] = {}
        self.bgs: Dict[str, BarGenerator] = {}

        # 策略内动态调整OLS相关参数,小数参数会被int()


       
        self.short_entry_multiplier = abs(self.entry_multiplier)
        self.short_exit_multiplier = 0
        self.long_entry_multiplier =  -abs(self.entry_multiplier)
        self.long_exit_multiplier = 0

        self.mean_window = int(self.std_window * self.std_mean_window_ratio)

        

        self.y_symbol = self.vt_symbols[0]
        self.x_symbol = self.vt_symbols[1]


        self.x_fixed_size = np.abs(self.fixed_size * 1)
        self.y_fixed_size = np.abs(self.fixed_size * 1)

        self.x_pos_target = 0
        self.y_pos_target = 0




        # 实例化缓存期货品种价格序列容器
        for vt_symbol in self.vt_symbols:

            self.ams[vt_symbol] =  ArrayManager(size=max(self.std_window,self.mean_window)+50)

        #实例化bg容器
        

        for vt_symbol in self.vt_symbols:

            def on_bar(bar: BarData):
                """"""
                pass

            self.bgs[vt_symbol] = BarGenerator(on_bar)


        # 实例化缓存价差价格序列容器
        self.sam = SpreadArrayManager(size=max(self.std_window,self.mean_window)+50)
예제 #23
0
    def __init__(self, strategy: StrategyTemplate, vt_symbol: str):
        """"""
        # 和portfolio的接口
        self.portfolio = strategy
        self.vt_symbol = vt_symbol

        # 需要合成的K线周期设置
        self.bar_interval = self.portfolio.bar_interval
        self.bar_frequency = self.portfolio.bar_frequency

        # K线合成工具和储存容器
        self.bg = BarGenerator(self.on_bar, self.bar_interval,
                               self.on_5min_bar, self.bar_frequency)
        self.am = ArrayManager()

        # K线合成计数
        self.bar_count = 0
예제 #24
0
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super(MarketMakerStrategy, self).__init__(
            cta_engine, strategy_name, vt_symbol, setting
        )

        self.bg = BarGenerator(self.on_bar)

        # 创建Array队列
        self.tickArray = TickArrayManager(self.tickSize)

        self.entrust = 0
        self.min_diff = 0.001

        self.ask_price = 0
        self.bid_price = 0

        self.order_time = 0
예제 #25
0
    def get_bar_generator(self, vt_symbol: str):
        """"""
        bg = self.bar_generators.get(vt_symbol, None)

        if not bg:
            bg = BarGenerator(self.record_bar)
            self.bar_generators[vt_symbol] = bg

        return bg
    def __init__(self, strategy: StrategyTemplate, vt_symbol: str):
        """"""

        self.portfolio = strategy
        self.vt_symbol = vt_symbol

        self.long_ma_window = self.portfolio.long_ma_window
        self.short_ma_window = self.portfolio.short_ma_window
        self.trailing_percent = self.portfolio.trailing_percent
        self.fixed_size = self.portfolio.fixed_size

        self.long_ma_value = 0
        self.short_ma_value = 0
        self.intra_trade_high = 0
        self.intra_trade_low = 0

        self.bg = BarGenerator(self.on_bar, 5, self.on_5min_bar)
        self.am = ArrayManager()
예제 #27
0
    def __init__(self, strategy_engine: StrategyEngine, strategy_name: str,
                 vt_symbols: List[str], setting: dict):
        """"""
        super().__init__(strategy_engine, strategy_name, vt_symbols, setting)
        self.bgs: Dict[str, BarGenerator] = {}
        self.ams: Dict[str, ArrayManager] = {}
        self.intra_trade_lows: Dict[str, float] = {}
        self.intra_trade_highs: Dict[str, float] = {}
        self.atr_values: Dict[str, float] = {}
        self.atr_mas: Dict[str, float] = {}
        self.rsi_values: Dict[str, float] = {}

        def on_bar(bar: BarData):
            """"""
            pass

        self.bgs[self.vt_symbols[0]] = BarGenerator(on_bar, 15,
                                                    self.on_15min_symbol_bar1)
        self.bgs[self.vt_symbols[1]] = BarGenerator(on_bar, 15,
                                                    self.on_15min_symbol_bar2)
        # self.bgs[self.vt_symbols[2]] = BarGenerator(on_bar,15,self.on_15min_symbol_bar3)

        self.ams[self.vt_symbols[0]] = ArrayManager()
        self.ams[self.vt_symbols[1]] = ArrayManager()
        # self.ams[self.vt_symbols[2]] = ArrayManager()

        self.intra_trade_lows[self.vt_symbols[0]] = 0
        self.intra_trade_lows[self.vt_symbols[1]] = 0
        # self.intra_trade_lows[self.vt_symbols[2]] = 0

        self.intra_trade_highs[self.vt_symbols[0]] = 0
        self.intra_trade_highs[self.vt_symbols[1]] = 0
        # self.intra_trade_highs[self.vt_symbols[2]] = 0

        self.atr_values[self.vt_symbols[0]] = 0
        self.atr_values[self.vt_symbols[1]] = 0
        # self.atr_values[self.vt_symbols[2]] = 0

        self.atr_mas[self.vt_symbols[0]] = 0
        self.atr_mas[self.vt_symbols[1]] = 0
        # self.atr_mas[self.vt_symbols[2]] = 0

        self.rsi_values[self.vt_symbols[0]] = 0
        self.rsi_values[self.vt_symbols[1]] = 0
    def __init__(self, strategy: StrategyTemplate, vt_symbol: str):
        """"""

        self.portfolio = strategy
        self.vt_symbol = vt_symbol

        self.fast_period = self.portfolio.fast_period
        self.slow_period = self.portfolio.slow_period
        self.signal_period = self.portfolio.signal_period
        self.trailing_percent = self.portfolio.trailing_percent
        self.fixed_size = self.portfolio.fixed_size
        self.bar_interval = self.portfolio.bar_interval
        self.bar_frequency = self.portfolio.bar_frequency

        self.macd_value = 0
        self.intra_trade_high = 0
        self.intra_trade_low = 0

        self.bg = BarGenerator(self.on_bar, self.bar_interval,
                               self.on_5min_bar, self.bar_frequency)
        self.am = ArrayManager()
예제 #29
0
class MaSignal(CtaSignal):
    """"""
    def __init__(self, fast_window: int, slow_window: int):
        """"""
        super(MaSignal, self).__init__()

        self.fast_window = fast_window
        self.slow_window = slow_window

        self.bg = BarGenerator(self.on_bar, 5, self.on_5min_bar)
        self.am = ArrayManager()

    def on_tick(self, tick: TickData):
        """
        Callback of new tick data update.
        """
        self.bg.update_tick(tick)

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.bg.update_bar(bar)

    def on_5min_bar(self, bar: BarData):
        """"""
        self.am.update_bar(bar)
        if not self.am.inited:
            self.set_signal_pos(0)

        fast_ma = self.am.sma("c", self.fast_window)
        slow_ma = self.am.sma("c", self.slow_window)

        if fast_ma > slow_ma:
            self.set_signal_pos(1)
        elif fast_ma < slow_ma:
            self.set_signal_pos(-1)
        else:
            self.set_signal_pos(0)
예제 #30
0
파일: widget.py 프로젝트: xyh888/KRData
    def show_corr_chart(self, r, c):
        self._selected_row = r
        _end = self.corr_table.item(r, 0).text()

        source_data = self.raw_data['HSI']
        forward = 1
        start = self.data.shift(self.period).asof(_end).datetime
        end = self.data.shift(-forward).asof(_end).datetime
        data = source_data.loc[start:end]
        self.source_chart_widget.clear_all()
        # barList = []
        if self.interval >= 60:
            self.bar_generator = BarGenerator(None, 1, self.source_chart_widget.update_bar, Interval.HOUR)
        else:
            self.bar_generator = BarGenerator(None, self.interval, self.source_chart_widget.update_bar, Interval.MINUTE)

        for _, d in data.iterrows():
            b = BarData('KRData', d.code, Exchange.HKFE, d.datetime, None,
                        d.volume, 0, d.open, d.high, d.low, d.close)
            self.bar_generator.update_bar(b)
            if d.datetime == parser.parse(_end):
                last_bar = self.source_chart_widget._manager.get_bar(self.source_chart_widget.last_ix)
                self.source_chart_widget.add_splitLine(last_bar.datetime)