Beispiel #1
0
    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super().__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, cta_engine: CtaEngine, strategy_name, vt_symbol, setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)

        self.last_filled_order: Optional[OrderData, None] = None
        self.tick: Optional[TickData, None] = None
        self.contract: Optional[ContractData, None] = None
        self.account: Optional[AccountData, None] = None

        self.bg_1hour = BarGenerator(self.on_bar, 1, on_window_bar=self.on_1hour_bar, interval=Interval.HOUR)  # 1hour
        self.bg_4hour = BarGenerator(self.on_bar, 4, on_window_bar=self.on_4hour_bar, interval=Interval.HOUR)  # 4hour

        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + 'BINANCE.币名称', self.process_acccount_event)
        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + "BINANCE.USDT", self.process_account_event)

        self.buy_orders = []  # 买单id列表。
        self.sell_orders = []  # 卖单id列表。
        self.min_notional = 11  # 最小的交易金额.
    def __init__(self, cta_engine: CtaEngine, strategy_name, vt_symbol,
                 setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)

        self.last_filled_order: Optional[OrderData, None] = None
        self.tick: Optional[TickData, None] = None
        self.contract: Optional[ContractData, None] = None
        self.account: Optional[AccountData, None] = None

        self.bg = BarGenerator(self.on_bar, 15, self.on_15min_bar,
                               Interval.MINUTE)  # 15分钟的数据.
        self.am = MyArrayManager(60)  # 默认是100,设置60
        # ArrayManager

        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + 'BINANCE.币名称', self.process_acccount_event)
        # 现货的资产订阅
        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + "BINANCE.USDT", self.process_account_event)
        # # 合约的资产订阅
        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + "BINANCES.USDT", self.process_account_event)

        self.buy_orders = []  # 买单id列表。
        self.sell_orders = []  # 卖单id列表。
        self.min_notional = 11  # 最小的交易金额.
Beispiel #4
0
    def __init__(self, cta_engine: CtaEngine, strategy_name, vt_symbol,
                 setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        self.bg2 = BarGenerator(self.on_bar, 2, self.on_2min_bar,
                                Interval.MINUTE)
        self.bg5 = BarGenerator(self.on_bar, 5, self.on_5min_bar,
                                Interval.MINUTE)
        self.bg_1hour = BarGenerator(self.on_bar, 1, self.on_1hour_bar,
                                     Interval.HOUR)
        self.bg_4hour = BarGenerator(self.on_bar, 4, self.on_4hour_bar,
                                     Interval.HOUR)

        self.place_order = False
        self.orders = []
Beispiel #5
0
class AtrRsiStrategy(CtaTemplate):
    """"""

    author = "用Python的交易员"

    atr_length = 22
    atr_ma_length = 10
    rsi_length = 5
    rsi_entry = 16
    trailing_percent = 0.8
    fixed_size = 1

    atr_value = 0
    atr_ma = 0
    rsi_value = 0
    rsi_buy = 0
    rsi_sell = 0
    intra_trade_high = 0
    intra_trade_low = 0

    parameters = [
        "atr_length", "atr_ma_length", "rsi_length", "rsi_entry",
        "trailing_percent", "fixed_size"
    ]
    variables = [
        "atr_value", "atr_ma", "rsi_value", "rsi_buy", "rsi_sell",
        "intra_trade_high", "intra_trade_low"
    ]

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

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")

        self.rsi_buy = 50 + self.rsi_entry
        self.rsi_sell = 50 - self.rsi_entry

        self.load_bar(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    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.cancel_all()

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        high = pd.Series(am.high_array)
        low = pd.Series(am.low_array)
        close = pd.Series(am.close_array)

        atr_array = ta.atr(
            high, low, close,
            self.atr_length)  #am.atr(self.atr_length, array=True)
        self.atr_value = atr_array.iloc[-1]
        self.atr_ma = atr_array.iloc[-self.atr_ma_length:].mean()
        self.rsi_value = ta.rsi(close, self.rsi_length).iloc[-1]

        if self.pos == 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = bar.low_price

            if self.atr_value > self.atr_ma:
                if self.rsi_value > self.rsi_buy:
                    self.buy(bar.close_price + 5, self.fixed_size)
                elif self.rsi_value < self.rsi_sell:
                    self.short(bar.close_price - 5, self.fixed_size)

        elif self.pos > 0:
            self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
            self.intra_trade_low = bar.low_price

            long_stop = self.intra_trade_high * \
                (1 - self.trailing_percent / 100)
            self.sell(long_stop, abs(self.pos), stop=True)

        elif self.pos < 0:
            self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
            self.intra_trade_high = bar.high_price

            short_stop = self.intra_trade_low * \
                (1 + self.trailing_percent / 100)
            self.cover(short_stop, abs(self.pos), stop=True)

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
Beispiel #6
0
 def __init__(self, cta_engine: CtaEngine, strategy_name, vt_symbol, setting):
     """"""
     super().__init__(cta_engine, strategy_name, vt_symbol, setting)
     self.bg_1hour = BarGenerator(self.on_bar, 1, self.on_1hour_bar, Interval.HOUR)
     self.am = ArrayManager(size=100)  # 时间序列,类似我们用的pandas, 值保留最近的N个K线的数据.
Beispiel #7
0
class FixedTradeTimeStrategy(CtaTemplate):
    """
    基于价格的定投
    """

    author = "51bitquant"

    fixed_trade_money = 1000

    parameters = ["fixed_trade_money"]


    def __init__(self, cta_engine: CtaEngine, strategy_name, vt_symbol, setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        self.bg_1hour = BarGenerator(self.on_bar, 1, self.on_1hour_bar, Interval.HOUR)
        self.am = ArrayManager(size=100)  # 时间序列,类似我们用的pandas, 值保留最近的N个K线的数据.

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(1)  # 具体加载多少天的数据, 1表示1天的数据,如果是2表示过去2天的数据

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log(f"我的策略启动")
        self.put_event()

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")
        self.put_event()

    def on_tick(self, tick: TickData):
        pass

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.bg_1hour.update_bar(bar)  # 合成1小时的数据.
        self.put_event()

    def on_1hour_bar(self, bar: BarData):
        """
        1小时的K线数据.
        """
        self.cancel_all()  # 取消订单.
        self.am.update_bar(bar)  # 把最新的K线放进时间序列里面.
        if not self.am.inited:  # True
            return

        """
        定投逻辑: 周四下午三点定投, 周五下午四点定投
        """
        # 2000 * 54  # 10万美金,
        if bar.datetime.isoweekday() == 5 and bar.datetime.hour == 16:
            price = bar.close_price * 1.001
            self.buy(price, self.fixed_trade_money/price)

        if bar.datetime.isoweekday() == 4 and bar.datetime.hour == 15:
            price = bar.close_price * 1.001
            self.buy(price, self.fixed_trade_money / price)


        # 下面可以计算基数指标等等....
        # 以及下单的事情.

        self.put_event()

    def on_order(self, order: OrderData):
        """
        订单的回调方法: 订单状态更新的时候,会调用这个方法。
        """
        self.put_event()

    def on_trade(self, trade: TradeData):
        """
        """
        self.put_event()  # 更新UI界面方法。

    def on_stop_order(self, stop_order: StopOrder):
        """
        这个是一个停止单的方法,用来监听你止损单的方法。
        """
        pass
Beispiel #8
0
class Class10SimpleStrategy(CtaTemplate):
    author = "51bitquant"

    def __init__(self, cta_engine: CtaEngine, strategy_name, vt_symbol,
                 setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        self.bg2 = BarGenerator(self.on_bar, 2, self.on_2min_bar,
                                Interval.MINUTE)
        self.bg5 = BarGenerator(self.on_bar, 5, self.on_5min_bar,
                                Interval.MINUTE)
        self.bg_1hour = BarGenerator(self.on_bar, 1, self.on_1hour_bar,
                                     Interval.HOUR)

        self.place_order = False
        self.orders = []
        # self.pos #

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")
        self.put_event()

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

        self.put_event()

    def on_tick(self, tick: TickData):
        print(
            f"tick, ask1:{tick.ask_price_1}, {tick.ask_volume_1}, bid:{tick.bid_price_1}, {tick.bid_volume_1}"
        )
        print(
            f"my current pos is: {self.pos}, ask:{tick.ask_price_1}, bid: {tick.bid_price_1}"
        )

        if self.place_order is False and self.trading:
            buy_order = self.buy(tick.bid_price_1 * 0.9999, 0.5)
            # sell_order = self.short(tick.ask_price_1 * 1.0001, 0.01)
            sell_order = self.sell(tick.ask_price_1 * 1.0002, 0.5)

            # self.short()
            # self.cover()  #

            # self.buy()
            # self.short()
            self.place_order = True
            print(f"buy_order: {buy_order}, sell_order: {sell_order}")
            self.orders += buy_order
            self.orders += sell_order

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        print("1分钟的K线数据", bar)
        self.bg2.update_bar(bar)
        self.bg5.update_bar(bar)  # 合成2分钟的K线
        self.bg_1hour.update_bar(bar)  # 合成一小时的数据。
        self.put_event()

    def on_2min_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        print("2分钟的K线数据", bar)
        self.put_event()

    def on_5min_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        print("5分钟的K线数据", bar)
        self.put_event()

    def on_1hour_bar(self, bar: BarData):

        print("1小时的K线数据", bar)
        self.put_event()

    def on_order(self, order: OrderData):
        """
        订单的回调方法: 订单状态更新的时候,会调用这个方法。
        """

        print("策略推送过来的order: ", order)

        self.put_event()

    def on_trade(self, trade: TradeData):
        """
        订单成交的推送,比如你下10个BTC,那么可能不会一下子成交,会不断慢慢的成交,
        这时有成交它就会推送给你,告诉你成交了多少,还有多少没有成交
        系统通过里面处理这个方法,知道你当前的仓位数量

        """
        print("最新的成交: ", trade)
        self.put_event()  # 更新UI界面方法。

    def on_stop_order(self, stop_order: StopOrder):
        """
        这个是一个停止单的方法,用来监听你止损单的方法。
        """
        pass
class MartingleFutureStrategy(CtaTemplate):
    """
        1. 马丁策略.
        币安邀请链接: https://www.binancezh.pro/cn/futures/ref/51bitquant
        币安合约邀请码:51bitquant
        https://github.com/51bitquant/course_codes
    """
    author = "51bitquant"

    # 策略的核心参数.
    boll_window = 30
    boll_dev = 2.2

    increase_pos_when_dump_pct = 0.04  # 回撤多少加仓
    exit_profit_pct = 0.02  # 出场平仓百分比 2%
    initial_trading_value = 1000  # 首次开仓价值 1000USDT.
    trading_value_multiplier = 1.3  # 加仓的比例. 1000 1300 1300 * 1.3
    max_increase_pos_times = 10.0  # 最大的加仓次数
    trading_fee = 0.00075

    # 变量
    avg_price = 0.0  # 当前持仓的平均价格.
    last_entry_price = 0.0  # 上一次入场的价格.
    current_pos = 0.0  # 当前的持仓的数量.
    current_increase_pos_times = 0  # 当前的加仓的次数.

    # 统计总的利润.
    total_profit = 0

    parameters = [
        "boll_window", "boll_dev", "increase_pos_when_dump_pct",
        "exit_profit_pct", "initial_trading_value", "trading_value_multiplier",
        "max_increase_pos_times", "trading_fee"
    ]

    variables = [
        "avg_price", "last_entry_price", "current_pos",
        "current_increase_pos_times", "total_profit"
    ]

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

        self.last_filled_order: Optional[OrderData, None] = None
        self.tick: Optional[TickData, None] = None
        self.contract: Optional[ContractData, None] = None
        self.account: Optional[AccountData, None] = None

        self.bg = BarGenerator(self.on_bar, 15, self.on_15min_bar,
                               Interval.MINUTE)  # 15分钟的数据.
        self.am = MyArrayManager(60)  # 默认是100,设置60
        # ArrayManager

        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + 'BINANCE.币名称', self.process_acccount_event)
        # 现货的资产订阅
        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + "BINANCE.USDT", self.process_account_event)
        # # 合约的资产订阅
        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + "BINANCES.USDT", self.process_account_event)

        self.buy_orders = []  # 买单id列表。
        self.sell_orders = []  # 卖单id列表。
        self.min_notional = 11  # 最小的交易金额.

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(2)  # 加载两天的数据.

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    def process_account_event(self, event: Event):
        self.account: AccountData = event.data
        # if self.account:
        #     print(
        #         f"self.account available: {self.account.available}, balance:{self.account.balance}, frozen: {self.account.frozen}")

    def on_tick(self, tick: TickData):
        """
        Callback of new tick data update.
        """
        if tick and tick.bid_price_1 > 0 and tick.ask_price_1 > 0:
            self.tick = tick
            self.bg.update_tick(tick)

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

        if self.current_pos * bar.close_price >= self.min_notional:

            if len(self.sell_orders) <= 0 and self.avg_price > 0:
                # 有利润平仓的时候
                profit_percent = bar.close_price / self.avg_price - 1
                if profit_percent >= self.exit_profit_pct:
                    self.cancel_all()
                    orderids = self.short(bar.close_price,
                                          abs(self.current_pos))
                    self.sell_orders.extend(orderids)

            # 考虑加仓的条件: 1) 当前有仓位,且仓位值要大于11USDTyi以上,2)加仓的次数小于最大的加仓次数,3)当前的价格比上次入场的价格跌了一定的百分比。
            dump_percent = self.last_entry_price / bar.close_price - 1
            if len(
                    self.buy_orders
            ) <= 0 and self.current_increase_pos_times <= self.max_increase_pos_times and dump_percent >= self.increase_pos_when_dump_pct:
                # ** 表示的是乘方.
                self.cancel_all()
                increase_pos_value = self.initial_trading_value * self.trading_value_multiplier**self.current_increase_pos_times
                price = bar.close_price
                vol = increase_pos_value / price
                orderids = self.buy(price, vol)
                self.buy_orders.extend(orderids)

        self.bg.update_bar(bar)

    def on_15min_bar(self, bar: BarData):

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        current_close = am.close_array[-1]
        last_close = am.close_array[-2]
        boll_up, boll_down = am.boll(self.boll_window,
                                     self.boll_dev,
                                     array=False)  # 返回最新的布林带值.

        # 突破上轨
        if last_close <= boll_up < current_close:
            if len(
                    self.buy_orders
            ) == 0 and self.current_pos * bar.close_price < self.min_notional:  # 每次下单要大于等于10USDT, 为了简单设置11USDT.
                # 这里没有仓位.
                self.cancel_all()
                # 重置当前的数据.
                self.current_increase_pos_times = 0
                self.avg_price = 0

                price = bar.close_price
                vol = self.initial_trading_value / price
                orderids = self.buy(price, vol)
                self.buy_orders.extend(orderids)  # 以及已经下单的orderids.

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        if order.status == Status.ALLTRADED:
            if order.direction == Direction.LONG:
                # 买单成交.
                self.current_increase_pos_times += 1
                self.last_entry_price = order.price  # 记录上一次成绩的价格.

        if not order.is_active():
            if order.vt_orderid in self.sell_orders:
                self.sell_orders.remove(order.vt_orderid)

            elif order.vt_orderid in self.buy_orders:
                self.buy_orders.remove(order.vt_orderid)

        self.put_event()  # 更新UI使用.

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        if trade.direction == Direction.LONG:
            total = self.avg_price * self.current_pos + trade.price * trade.volume
            self.current_pos += trade.volume
            self.avg_price = total / self.current_pos
        elif trade.direction == Direction.SHORT:
            self.current_pos -= trade.volume

            # 计算统计下总体的利润.
            self.total_profit += (
                trade.price - self.avg_price
            ) * trade.volume - trade.volume * trade.price * 2 * self.trading_fee

        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
class FixedTradPriceStrategy(CtaTemplate):
    """
    基于价格的定投
    """
    author = "51bitquant"
    fixed_trade_money = 1000  # 每次定投的资金比例.
    price_change_pct = 0.05  # 价格变动多少的时候定投

    parameters = ['fixed_trade_money', 'price_change_pct']

    def __init__(self, cta_engine: CtaEngine, strategy_name, vt_symbol, setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        self.bg_4hour = BarGenerator(self.on_bar, 4, self.on_4hour_bar, Interval.HOUR)
        self.am = ArrayManager(size=100)  # 时间序列,类似我们用的pandas, 值保留最近的N个K线的数据.

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(1)  # 具体加载多少天的数据, 1表示1天的数据,如果是2表示过去2天的数据

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log(f"我的策略启动")
        self.put_event()


    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")
        self.put_event()


    def on_tick(self, tick: TickData):
        pass

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.bg_4hour.update_bar(bar)  # 合成四小时的数据.
        self.put_event()

    def on_4hour_bar(self, bar: BarData):
        """
        四小时的K线数据.
        """
        self.cancel_all()  # 撤销所有订单.
        self.am.update_bar(bar)  # 把最新的K线放进时间序列里面.
        # 下面可以计算基数指标等等....
        # 以及下单的事情.

        if not self.am.inited:
            return

        # [0,1,2,3,4,5,6]
        last_close_price = self.am.close_array[-2]  # 上一根K线
        current_close_price = bar.close_price # self.am.close_array[-1] #  当前的收盘价

        # 如果四小时价格下跌5%就买入.
        if (last_close_price - current_close_price)/last_close_price >= self.price_change_pct:
            price = bar.close_price * 1.001
            self.buy(price, self.fixed_trade_money/price)

        self.put_event()

    def on_order(self, order: OrderData):
        """
        订单的回调方法: 订单状态更新的时候,会调用这个方法。
        """
        self.put_event()

    def on_trade(self, trade: TradeData):
        """
        """
        self.put_event()  # 更新UI界面方法。


    def on_stop_order(self, stop_order: StopOrder):
        """
        这个是一个停止单的方法,用来监听你止损单的方法。
        """
        pass
Beispiel #11
0
class MultiTimeframeStrategy(CtaTemplate):
    """"""
    author = "用Python的交易员"

    rsi_signal = 20
    rsi_window = 14
    fast_window = 5
    slow_window = 20
    fixed_size = 1

    rsi_value = 0
    rsi_long = 0
    rsi_short = 0
    fast_ma = 0
    slow_ma = 0
    ma_trend = 0

    parameters = [
        "rsi_signal", "rsi_window", "fast_window", "slow_window", "fixed_size"
    ]

    variables = [
        "rsi_value", "rsi_long", "rsi_short", "fast_ma", "slow_ma", "ma_trend"
    ]

    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super().__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 on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

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

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

    def on_5min_bar(self, bar: BarData):
        """"""
        self.cancel_all()

        self.am5.update_bar(bar)
        if not self.am5.inited:
            return

        if not self.ma_trend:
            return

        close_5 = pd.Series(self.am5.close_array)
        self.rsi_value = ta.rsi(close_5, self.rsi_window).iloc[-1]

        if self.pos == 0:
            if self.ma_trend > 0 and self.rsi_value >= self.rsi_long:
                self.buy(bar.close_price + 5, self.fixed_size)
            elif self.ma_trend < 0 and self.rsi_value <= self.rsi_short:
                self.short(bar.close_price - 5, self.fixed_size)

        elif self.pos > 0:
            if self.ma_trend < 0 or self.rsi_value < 50:
                self.sell(bar.close_price - 5, abs(self.pos))

        elif self.pos < 0:
            if self.ma_trend > 0 or self.rsi_value > 50:
                self.cover(bar.close_price + 5, abs(self.pos))

        self.put_event()

    def on_15min_bar(self, bar: BarData):
        """"""
        self.am15.update_bar(bar)
        if not self.am15.inited:
            return

        close_15 = pd.Series(self.am15.close_array)

        self.fast_ma = ta.sma(close_15, self.fast_window).iloc[-1]
        self.slow_ma = ta.sma(close_15, self.slow_window).iloc[-1]

        if self.fast_ma > self.slow_ma:
            self.ma_trend = 1
        else:
            self.ma_trend = -1

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
Beispiel #12
0
class KingKeltnerStrategy(CtaTemplate):
    """"""

    author = "用Python的交易员"

    kk_length = 11
    kk_dev = 1.6
    trailing_percent = 0.8
    fixed_size = 1

    kk_up = 0
    kk_down = 0
    intra_trade_high = 0
    intra_trade_low = 0

    long_vt_orderids = []
    short_vt_orderids = []
    vt_orderids = []

    parameters = ["kk_length", "kk_dev", "trailing_percent", "fixed_size"]
    variables = ["kk_up", "kk_down"]

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

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

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    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):
        """"""
        for orderid in self.vt_orderids:
            self.cancel_order(orderid)
        self.vt_orderids.clear()

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        high = pd.Series(am.high_array)
        low = pd.Series(am.low_array)
        close = pd.Series(am.close_array)

        range_ = ta.true_range(high, low, close)

        basis = ta.sma(close, self.kk_length)
        band = ta.sma(range_, self.kk_length)
        up = basis + self.kk_dev * band
        down = basis - self.kk_dev * band

        self.kk_up, self.kk_down = up.iloc[-1], down.iloc[-1]

        if self.pos == 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = bar.low_price
            self.send_oco_order(self.kk_up, self.kk_down, self.fixed_size)

        elif self.pos > 0:
            self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
            self.intra_trade_low = bar.low_price

            vt_orderids = self.sell(self.intra_trade_high * (1 - self.trailing_percent / 100),
                                    abs(self.pos), True)
            self.vt_orderids.extend(vt_orderids)

        elif self.pos < 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = min(self.intra_trade_low, bar.low_price)

            vt_orderids = self.cover(self.intra_trade_low * (1 + self.trailing_percent / 100),
                                     abs(self.pos), True)
            self.vt_orderids.extend(vt_orderids)

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        if self.pos != 0:
            if self.pos > 0:
                for short_orderid in self.short_vt_orderids:
                    self.cancel_order(short_orderid)

            elif self.pos < 0:
                for buy_orderid in self.long_vt_orderids:
                    self.cancel_order(buy_orderid)

            for orderid in (self.long_vt_orderids + self.short_vt_orderids):
                if orderid in self.vt_orderids:
                    self.vt_orderids.remove(orderid)

        self.put_event()

    def send_oco_order(self, buy_price, short_price, volume):
        """"""
        self.long_vt_orderids = self.buy(buy_price, volume, True)
        self.short_vt_orderids = self.short(short_price, volume, True)

        self.vt_orderids.extend(self.long_vt_orderids)
        self.vt_orderids.extend(self.short_vt_orderids)

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
Beispiel #13
0
class TurtleSignalStrategy(CtaTemplate):
    """"""
    author = "用Python的交易员"

    entry_window = 20
    exit_window = 10
    atr_window = 20
    fixed_size = 1

    entry_up = 0
    entry_down = 0
    exit_up = 0
    exit_down = 0
    atr_value = 0

    long_entry = 0
    short_entry = 0
    long_stop = 0
    short_stop = 0

    parameters = ["entry_window", "exit_window", "atr_window", "fixed_size"]
    variables = ["entry_up", "entry_down", "exit_up", "exit_down", "atr_value"]

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

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(20)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    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.cancel_all()

        self.am.update_bar(bar)
        if not self.am.inited:
            return

        high = pd.Series(self.am.high_array)
        low = pd.Series(self.am.low_array)
        close = pd.Series(self.am.close_array)

        if not self.pos:
            self.entry_up, self.entry_down = high.rolling(self.entry_window).max().iloc[-1], low.rolling(
                self.entry_window).min().iloc[-1]

        self.exit_up, self.exit_down = high.rolling(self.exit_window).max().iloc[-1], \
                                       low.rolling(self.entry_window).min().iloc[-1]

        if not self.pos:

            self.atr_value = ta.atr(high, low, close, self.atr_window).iloc[-1]  # self.am.atr(self.atr_window)

            self.long_entry = 0
            self.short_entry = 0
            self.long_stop = 0
            self.short_stop = 0

            self.send_buy_orders(self.entry_up)
            self.send_short_orders(self.entry_down)
        elif self.pos > 0:
            self.send_buy_orders(self.entry_up)

            sell_price = max(self.long_stop, self.exit_down)
            self.sell(sell_price, abs(self.pos), True)

        elif self.pos < 0:
            self.send_short_orders(self.entry_down)

            cover_price = min(self.short_stop, self.exit_up)
            self.cover(cover_price, abs(self.pos), True)

        self.put_event()

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        if trade.direction == Direction.LONG:
            self.long_entry = trade.price
            self.long_stop = self.long_entry - 2 * self.atr_value
        else:
            self.short_entry = trade.price
            self.short_stop = self.short_entry + 2 * self.atr_value

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass

    def send_buy_orders(self, price):
        """"""
        t = self.pos / self.fixed_size

        if t < 1:
            self.buy(price, self.fixed_size, True)

        if t < 2:
            self.buy(price + self.atr_value * 0.5, self.fixed_size, True)

        if t < 3:
            self.buy(price + self.atr_value, self.fixed_size, True)

        if t < 4:
            self.buy(price + self.atr_value * 1.5, self.fixed_size, True)

    def send_short_orders(self, price):
        """"""
        t = self.pos / self.fixed_size

        if t > -1:
            self.short(price, self.fixed_size, True)

        if t > -2:
            self.short(price - self.atr_value * 0.5, self.fixed_size, True)

        if t > -3:
            self.short(price - self.atr_value, self.fixed_size, True)

        if t > -4:
            self.short(price - self.atr_value * 1.5, self.fixed_size, True)
class BollChannelStrategy(CtaTemplate):
    """"""

    author = "用Python的交易员"

    boll_window = 18
    boll_dev = 3.4
    cci_window = 10
    atr_window = 30
    sl_multiplier = 5.2
    fixed_size = 1

    boll_up = 0
    boll_down = 0
    cci_value = 0
    atr_value = 0

    intra_trade_high = 0
    intra_trade_low = 0
    long_stop = 0
    short_stop = 0

    parameters = [
        "boll_window",
        "boll_dev",
        "cci_window",
        "atr_window",
        "sl_multiplier",
        "fixed_size"
    ]
    variables = [
        "boll_up",
        "boll_down",
        "cci_value",
        "atr_value",
        "intra_trade_high",
        "intra_trade_low",
        "long_stop",
        "short_stop"
    ]

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

        self.bg = BarGenerator(self.on_bar, 15, self.on_15min_bar)
        self.am = ArrayManager()

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    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_15min_bar(self, bar: BarData):
        """"""
        self.cancel_all()

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        close = pd.Series(am.close_array)
        high = pd.Series(am.high_array)
        low = pd.Series(am.low_array)

        standard_deviation = ta.stdev(close=close, length=self.boll_window)
        deviations = self.boll_dev * standard_deviation

        mid = ta.sma(close=close, length=self.boll_window)

        self.boll_up, self.boll_down = (mid + deviations).iloc[-1],  (mid - deviations).iloc[-1]
        self.cci_value = ta.cci(high, low, close, self.cci_window).iloc[-1]
        self.atr_value = ta.atr(high, low, close, self.atr_window).iloc[-1]

        if self.pos == 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = bar.low_price

            if self.cci_value > 0:
                self.buy(self.boll_up, self.fixed_size, True)
            elif self.cci_value < 0:
                self.short(self.boll_down, self.fixed_size, True)

        elif self.pos > 0:
            self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
            self.intra_trade_low = bar.low_price

            self.long_stop = self.intra_trade_high - self.atr_value * self.sl_multiplier
            self.sell(self.long_stop, abs(self.pos), True)

        elif self.pos < 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = min(self.intra_trade_low, bar.low_price)

            self.short_stop = self.intra_trade_low + self.atr_value * self.sl_multiplier
            self.cover(self.short_stop, abs(self.pos), True)

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
Beispiel #15
0
 def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
     """"""
     super().__init__(cta_engine, strategy_name, vt_symbol, setting)
     self.bg = BarGenerator(self.on_bar)
     self.am = ArrayManager()
class DualThrustStrategy(CtaTemplate):
    """"""

    author = "用Python的交易员"

    fixed_size = 1
    k1 = 0.4
    k2 = 0.6

    bars = []

    day_open = 0
    day_high = 0
    day_low = 0

    day_range = 0
    long_entry = 0
    short_entry = 0
    exit_time = time(hour=14, minute=55)

    long_entered = False
    short_entered = False

    parameters = ["k1", "k2", "fixed_size"]
    variables = ["day_range", "long_entry", "short_entry"]

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

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()
        self.bars = []

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    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.cancel_all()

        self.bars.append(bar)
        if len(self.bars) <= 2:
            return
        else:
            self.bars.pop(0)
        last_bar = self.bars[-2]

        if last_bar.datetime.date() != bar.datetime.date():
            if self.day_high:
                self.day_range = self.day_high - self.day_low
                self.long_entry = bar.open_price + self.k1 * self.day_range
                self.short_entry = bar.open_price - self.k2 * self.day_range

            self.day_open = bar.open_price
            self.day_high = bar.high_price
            self.day_low = bar.low_price

            self.long_entered = False
            self.short_entered = False
        else:
            self.day_high = max(self.day_high, bar.high_price)
            self.day_low = min(self.day_low, bar.low_price)

        if not self.day_range:
            return

        if bar.datetime.time() < self.exit_time:
            if self.pos == 0:
                if bar.close_price > self.day_open:
                    if not self.long_entered:
                        self.buy(self.long_entry, self.fixed_size, stop=True)
                else:
                    if not self.short_entered:
                        self.short(self.short_entry,
                                   self.fixed_size,
                                   stop=True)

            elif self.pos > 0:
                self.long_entered = True

                self.sell(self.short_entry, self.fixed_size, stop=True)

                if not self.short_entered:
                    self.short(self.short_entry, self.fixed_size, stop=True)

            elif self.pos < 0:
                self.short_entered = True

                self.cover(self.long_entry, self.fixed_size, stop=True)

                if not self.long_entered:
                    self.buy(self.long_entry, self.fixed_size, stop=True)

        else:
            if self.pos > 0:
                self.sell(bar.close_price * 0.99, abs(self.pos))
            elif self.pos < 0:
                self.cover(bar.close_price * 1.01, abs(self.pos))

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
class MartingleSpotStrategyV3(CtaTemplate):
    """
    1. 马丁策略.
    币安邀请链接: https://www.binancezh.pro/cn/futures/ref/51bitquant
    币安合约邀请码:51bitquant

    ## 策略思路

    1. 挑选1小时涨幅超过2.6%的币,或者4小涨幅超过4.6%的币, 且上引线不能过长(防止入场),然后入场
    2. 利润超过1%,且最高价回调1%后平仓,当然你可以选择自己的参数
    3. 如果入场后,没有利润,价格继续下跌。那么入场价格下跌5%后,采用马丁策略加仓。

    """
    author = "51bitquant"

    # 策略的核心参数.
    initial_trading_value = 200  # 首次开仓价值 100USDT.
    trading_value_multiplier = 2  # 加仓的比例.
    max_increase_pos_count = 5  # 最大的加仓次数

    hour_pump_pct = 0.026  # 小时的上涨百分比
    four_hour_pump_pct = 0.046  # 四小时的上涨百分比.
    high_close_change_pct = 0.03  # 最高价/收盘价 -1, 防止上引线过长.
    increase_pos_when_dump_pct = 0.05  # 价格下跌 5%就继续加仓.
    exit_profit_pct = 0.01  # 出场平仓百分比 1%
    exit_pull_back_pct = 0.01  # 最高价回调超过1%,且利润超过1% 就出场.
    trading_fee = 0.00075  # 交易手续费

    # 变量
    avg_price = 0.0  # 当前持仓的平均价格.
    last_entry_price = 0.0  # 上一次入场的价格.
    entry_highest_price = 0.0
    current_pos = 0.0  # 当前的持仓的数量.
    current_increase_pos_count = 0  # 当前的加仓的次数.
    total_profit = 0  # 统计总的利润.

    parameters = [
        "initial_trading_value", "trading_value_multiplier",
        "max_increase_pos_count", "hour_pump_pct", "four_hour_pump_pct",
        "high_close_change_pct", "increase_pos_when_dump_pct",
        "exit_profit_pct", "exit_pull_back_pct", "trading_fee"
    ]

    variables = [
        "avg_price", "last_entry_price", "entry_highest_price", "current_pos",
        "current_increase_pos_count", "total_profit"
    ]

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

        self.last_filled_order: Optional[OrderData, None] = None
        self.tick: Optional[TickData, None] = None
        self.contract: Optional[ContractData, None] = None
        self.account: Optional[AccountData, None] = None

        self.bg_1hour = BarGenerator(self.on_bar,
                                     1,
                                     on_window_bar=self.on_1hour_bar,
                                     interval=Interval.HOUR)  # 1hour
        self.bg_4hour = BarGenerator(self.on_bar,
                                     4,
                                     on_window_bar=self.on_4hour_bar,
                                     interval=Interval.HOUR)  # 4hour

        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + 'BINANCE.币名称', self.process_acccount_event)
        # self.cta_engine.event_engine.register(EVENT_ACCOUNT + "BINANCE.USDT", self.process_account_event)

        self.buy_orders = []  # 买单id列表。
        self.sell_orders = []  # 卖单id列表。
        self.min_notional = 11  # 最小的交易金额.

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(3)  # 加载3天的数据.

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    # def process_account_event(self, event: Event):
    #     self.account: AccountData = event.data
    #     if self.account:
    #         print(
    #             f"self.account: available{self.account.available}, balance:{self.account.balance}, frozen: {self.account.frozen}")

    def on_tick(self, tick: TickData):
        """
        Callback of new tick data update.
        """
        if tick.bid_price_1 > 0 and tick.ask_price_1 > 0:
            self.bg_1hour.update_tick(tick)
            self.bg_4hour.update_tick(tick)

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        if self.entry_highest_price > 0:
            self.entry_highest_price = max(bar.high_price,
                                           self.entry_highest_price)

        if self.current_pos * bar.close_price >= self.min_notional:
            # 有仓位
            if len(self.sell_orders) <= 0 < self.avg_price:
                # 有利润平仓的时候
                # 清理掉其他买单.

                profit_percent = bar.close_price / self.avg_price - 1
                profit_pull_back_pct = self.entry_highest_price / bar.close_price - 1
                if profit_percent >= self.exit_profit_pct and profit_pull_back_pct >= self.exit_pull_back_pct:
                    self.cancel_all()
                    orderids = self.sell(bar.close_price,
                                         abs(self.current_pos))
                    self.sell_orders.extend(orderids)

            if len(self.buy_orders) <= 0:
                # 考虑加仓的条件: 1) 当前有仓位,且仓位值要大于11USDTyi以上,2)加仓的次数小于最大的加仓次数,3)当前的价格比上次入场的价格跌了一定的百分比。

                dump_down_pct = self.last_entry_price / bar.close_price - 1

                if self.current_increase_pos_count <= self.max_increase_pos_count and dump_down_pct >= self.increase_pos_when_dump_pct:
                    # ** 表示的是乘方.
                    self.cancel_all()  # 清理其他卖单.

                    increase_pos_value = self.initial_trading_value * self.trading_value_multiplier**self.current_increase_pos_count
                    price = bar.close_price
                    vol = increase_pos_value / price
                    orderids = self.buy(price, vol)
                    self.buy_orders.extend(orderids)

        self.bg_1hour.update_bar(bar)
        self.bg_4hour.update_bar(bar)

        self.put_event()

    def on_1hour_bar(self, bar: BarData):

        close_change_pct = bar.close_price / bar.open_price - 1  # 收盘价涨了多少.
        high_change_pct = bar.high_price / bar.close_price - 1  # 计算上引线

        # 回调一定比例的时候.
        if self.current_pos * bar.close_price < self.min_notional:  # 10 USDT
            # 每次下单要大于等于10USDT, 为了简单设置11USDT.
            if close_change_pct >= self.hour_pump_pct and high_change_pct < self.high_close_change_pct and len(
                    self.buy_orders) == 0:
                # 这里没有仓位.
                # 重置当前的数据.
                self.cancel_all()
                self.current_increase_pos_count = 0
                self.avg_price = 0
                self.entry_highest_price = 0.0

                price = bar.close_price
                vol = self.initial_trading_value / price
                orderids = self.buy(price, vol)
                self.buy_orders.extend(orderids)  # 以及已经下单的orderids.

    def on_4hour_bar(self, bar: BarData):
        close_change_pct = bar.close_price / bar.open_price - 1  # 收盘价涨了多少.
        high_change_pct = bar.high_price / bar.close_price - 1  # 计算上引线

        # 回调一定比例的时候.
        if self.current_pos * bar.close_price < self.min_notional:
            # 每次下单要大于等于10USDT, 为了简单设置11USDT.
            if close_change_pct >= self.four_hour_pump_pct and high_change_pct < self.high_close_change_pct and len(
                    self.buy_orders) == 0:
                # 这里没有仓位.
                # 重置当前的数据.
                self.cancel_all()
                self.current_increase_pos_count = 0
                self.avg_price = 0
                self.entry_highest_price = 0.0

                price = bar.close_price
                vol = self.initial_trading_value / price
                orderids = self.buy(price, vol)
                self.buy_orders.extend(orderids)  # 以及已经下单的orderids.

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        if order.status == Status.ALLTRADED:
            if order.direction == Direction.LONG:
                # 买单成交.
                self.current_increase_pos_count += 1
                self.last_entry_price = order.price  # 记录上一次成绩的价格.
                self.entry_highest_price = order.price

        if not order.is_active():
            if order.vt_orderid in self.sell_orders:
                self.sell_orders.remove(order.vt_orderid)

            elif order.vt_orderid in self.buy_orders:
                self.buy_orders.remove(order.vt_orderid)

        self.put_event()  # 更新UI使用.

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        if trade.direction == Direction.LONG:
            total = self.avg_price * self.current_pos + trade.price * trade.volume
            self.current_pos += trade.volume

            self.avg_price = total / self.current_pos
        elif trade.direction == Direction.SHORT:
            self.current_pos -= trade.volume

            # 计算统计下总体的利润.
            profit = (trade.price - self.avg_price) * trade.volume
            total_fee = trade.volume * trade.price * 2 * self.trading_fee
            self.total_profit += profit - total_fee

        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
Beispiel #18
0
class DoubleMaStrategy(CtaTemplate):
    author = "用Python的交易员"

    fast_window = 10
    slow_window = 20

    fast_ma0 = 0.0
    fast_ma1 = 0.0

    slow_ma0 = 0.0
    slow_ma1 = 0.0

    parameters = ["fast_window", "slow_window"]
    variables = ["fast_ma0", "fast_ma1", "slow_ma0", "slow_ma1"]

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

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")
        self.put_event()

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

        self.put_event()

    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.
        """

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        close = pd.Series(am.close_array)

        fast_ma = ta.sma(close, self.fast_window)
        self.fast_ma0 = fast_ma.iloc[-1]
        self.fast_ma1 = fast_ma.iloc[-2]

        slow_ma = ta.sma(close, self.slow_window)
        self.slow_ma0 = slow_ma.iloc[-1]
        self.slow_ma1 = slow_ma.iloc[-2]

        cross_over = self.fast_ma0 > self.slow_ma0 and self.fast_ma1 < self.slow_ma1
        cross_below = self.fast_ma0 < self.slow_ma0 and self.fast_ma1 > self.slow_ma1

        if cross_over:
            if self.pos == 0:
                self.buy(bar.close_price, 1)
            elif self.pos < 0:
                self.cover(bar.close_price, 1)
                self.buy(bar.close_price, 1)

        elif cross_below:
            if self.pos == 0:
                self.short(bar.close_price, 1)
            elif self.pos > 0:
                self.sell(bar.close_price, 1)
                self.short(bar.close_price, 1)

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass