简体   繁体   English

Backtrader:订单已创建,我希望订单立即执行(而不是第二天执行),该怎么做?

[英]Backtrader: order created, I would like that the order is execute instantly (and not the day after), how to do that?

I am rather new to backtrader, and I do not really understand how it works.我对 backtrader 很陌生,我不太了解它是如何工作的。 My code is rather simple and looks like this:我的代码相当简单,如下所示:

    class TestStrategy(bt.Strategy):
        params = (
            ('maperiod', 60),
        )

        def log(self, txt, dt=None):
            ''' Logging function for this strategy'''
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(), txt))

        def __init__(self):
            # Keep a reference to the "close" line in the data[0] dataseries
            self.dataclose = self.datas[0].close
            self.data_cpa = self.datas[0].high
            self.data_cpb = self.datas[0].low


            self.order = None
            self.buyprice = None
            self.buycomm = None

            self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.maperiod)

        def next(self):
            # Simply log the closing price of the series from the reference
            self.log('Close, %.8f' % self.dataclose[0])


            if self.dataclose[0] >= self.sma[0]:

                # BUY, BUY, BUY!!! (with all possible default parameters)
                self.log('BUY CREATE, %.8f' % self.dataclose[0])

                # Keep track of the created order to avoid a 2nd order
                self.order = self.buy()
            else:

                if self.dataclose[0] <= self.sma[0]:
                    # SELL, SELL, SELL!!! (with all possible default parameters)
                    self.log('SELL CREATE, %.8f' % self.dataclose[0])

                    # Keep track of the created order to avoid a 2nd order
                    self.order = self.sell()
                    print(self.order)



if __name__ == '__main__':
    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    cerebro.addstrategy(TestStrategy)

    # retrieve the csv file
    modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
    datapath = os.path.join(modpath, './datas/zrxeth_sample.txt')

    # Create a Data Feed
    data = bt.feeds.GenericCSVData(
    dataname = datapath,

    fromdate=datetime.datetime(2018, 9, 28),
    todate=datetime.datetime(2018, 12, 3),

    nullvalue=0.0,

    dtformat=('%Y-%m-%d %H:%M:%S'),

        datetime=0,
        high=1,
        low=2,
        open=3,
        close=4,
        volume=5,
        openinterest=-1
    )

    # Add the Data Feed to Cerebro
    cerebro.adddata(data)

    # Set our desired cash start
    cerebro.broker.setcash(100.0)

    # Print out the starting conditions
    print('Starting Portfolio Value: %.8f' % cerebro.broker.getvalue())

    # Run over everything
    cerebro.run()

    # Print out the final result
    print('Final Portfolio Value: %.8f' % cerebro.broker.getvalue())

When I do print(self.order) it print the order status as 'submitted', 1)how can I know at which price and when it was executed?当我执行 print(self.order) 时,它将订单状态打印为“已提交”,1)我如何知道以哪个价格以及何时执行? 2)how can I ensure that it enters the market (buy side), only after the last order (sell) was executed? 2)我怎样才能确保它进入市场(买方),只有在最后一个订单(卖)被执行之后? Thanks!!谢谢!!

Try adding this after the def init (self): block of code尝试在 def init (self): 代码块之后添加这个

    def notify_order(self, order):
    if order.status in [order.Submitted, order.Accepted]:
        # Buy/Sell order submitted/accepted to/by broker - Nothing to do
        return

    # Check if an order has been completed
    # Attention: broker could reject order if not enough cash
    if order.status in [order.Completed]:
        if order.isbuy():
            self.log(
                'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                (order.executed.price,
                 order.executed.value,
                 order.executed.comm))

            self.buyprice = order.executed.price
            self.buycomm = order.executed.comm
        else:  # Sell
            self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                     (order.executed.price,
                      order.executed.value,
                      order.executed.comm))

        self.bar_executed = len(self)

    elif order.status in [order.Canceled, order.Margin, order.Rejected]:
        self.log('Order Canceled/Margin/Rejected')
    self.order = None

def notify_trade(self, trade):
    if not trade.isclosed:
        return

    self.log('GROSS %.2f, NET %.2f' %
             (trade.pnl, trade.pnlcomm)) 

I found the answer.我找到了答案。

data = MyTVFeed(dataname=datapath,timeframe=bt.TimeFrame.Minutes, compression=30)

in my case I created a custom class for the feed called MyTVFeed.就我而言,我为名为 MyTVFeed 的提要创建了一个自定义类。 When you set the data you have to specify the time frame or it assumes day!当您设置数据时,您必须指定时间范围或假定为天!

You can read about this here ( https://community.backtrader.com/topic/381/faq )你可以在这里阅读( https://community.backtrader.com/topic/381/faq

In my case I set the time to be every 30 minutes since I was using a 30 minute chart.就我而言,我将时间设置为每 30 分钟一次,因为我使用的是 30 分钟图表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何按一天中的时间分组以找出最高顺序? - How do I groupby hours of day to find out the highest order? 在类中定义时如何以特定顺序执行函数? - How do I execute functions in a particular order when defined in a class? 运行 Cerebro 后,我在 backtrader 中的投资组合价值没有发生任何变化,我如何检查它是否正常工作 - After running Cerebro nothing is happening to my portfolio value in backtrader, how do i check if it is working or not 如何使用 ccxt 为 backtrader 创建 pandasData - How to created pandasData for backtrader with ccxt 我如何制作这样的“订购”产品应用程序 - how do I make an “order” products app like this 高级查询集排序顺序-无法按照我的意愿进行排序 - Advanced queryset sort ordering - won't order as I would like 我想按顺序返回一个没有重复的值 - I would like to return a value without duplicates in order 我想让我的程序显示订单总额/发票 - I would like to make my program display the order total/invoice Backtrader - 卖单上的 order.executed.value 错误? - Backtrader - order.executed.value on sell order erroneous? 如何在SQLAlchemy中的GROUP BY之后对算术表达式进行ORDER? - How do I ORDER BY an arithmetic expression after a GROUP BY in SQLAlchemy?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM