For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Error on sell bracket order



  • import datetime
    import pandas as pd
    import time
    import pandas
    import threading
    from io import BytesIO
    import csv
    from cassandra.cluster import Cluster
    from cassandra.auth import PlainTextAuthProvider
    from cassandra.query import dict_factory
    import backtrader as bt

    cluster = Cluster(contact_points=['34.234.1.252'], port=9042)
    session = cluster.connect('security_master')
    session.default_timeout = 60
    session.row_factory = dict_factory
    df = pd.DataFrame(index=[0],columns=['symbol', 'dtsession', 'preco', 'qty', 'time'])
    query = "SELECT symbol, dtsession, preco, qty, time FROM security_master.tickequities where dtsession = '2017-08-31' and symbol='PETR4'"
    future2 = session.execute_async(query)
    rows = future2.result()
    start = time.time()
    files = 'teste.csv'
    with open(files, 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',',quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['dtsession','preco', 'qty'])
    for row in future2.result():
    spamwriter.writerow([str(row['dtsession'])+ ' ' + str(row['time']), row['preco'] , row['qty']])
    df=pd.read_csv(files,index_col=['dtsession'], parse_dates=True)
    end = time.time()
    df.sort_index(inplace=True)
    df = df.resample('5S').agg({'preco': 'ohlc', 'qty': 'sum'})
    d = {'open': df['preco']['open'], 'high': df['preco']['high'],'low':df['preco']['low'],'close':df['preco']['close'], 'volume':df['qty']['qty']}
    df2 = pd.DataFrame(data=d)
    print(end-start)

    Create a Stratey

    class TestStrategy(bt.Strategy):
    params = (
    ('maperiod', 15),
    ('printlog', False),
    )

    def log(self, txt, dt=None, doprint=False):
        ''' Logging function fot this strategy'''
        if self.params.printlog or doprint:
            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
    
        # To keep track of pending orders and buy price/commission
        self.order = None
        self.buyprice = None
        self.buycomm = None
    
        # Add a MovingAverageSimple indicator
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.maperiod)
    
    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')
    
        # Write down: no pending order
        self.order = None
    
    def notify_trade(self, trade):
        if not trade.isclosed:
            return
    
        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))
    
    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f' % self.dataclose[0])
    
        # Check if an order is pending ... if yes, we cannot send a 2nd one
        if self.order:
            return
    
        # Check if we are in the market
        if not self.position:
    
            # Not yet ... we MIGHT BUY if ...
            if self.dataclose[0] > self.sma[0]:
    
                # BUY, BUY, BUY!!! (with all possible default parameters)
                self.log('BUY CREATE, %.2f' % 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, %.2f' % self.dataclose[0])
    
                # Keep track of the created order to avoid a 2nd order
                self.order = self.sell()
    
    def stop(self):
        self.log('(MA Period %2d) Ending Value %.2f' %
                 (self.params.maperiod, self.broker.getvalue()), doprint=True)
    

    if name == 'main':
    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    strats = cerebro.optstrategy(
        TestStrategy,
        maperiod=range(10, 31))
    
    # Create a Data Feed
    data = bt.feeds.PandasData(
        dataname=df2)
    
    # Add the Data Feed to Cerebro
    cerebro.adddata(data)
    
    # Set our desired cash start
    cerebro.broker.setcash(50000.0)
    
    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.FixedSize, stake=10)
    
    # Set the commission
    cerebro.broker.setcommission(commission=0.0)
    
    # Run over everything
    cerebro.run()
    

    Traceback (most recent call last):
    File "algoAndre.py", line 166, in <module>
    strategies = cerebro.run()
    File "/usr/local/lib/python3.5/dist-packages/backtrader/cerebro.py", line 1127, in run
    runstrat = self.runstrategies(iterstrat)
    File "/usr/local/lib/python3.5/dist-packages/backtrader/cerebro.py", line 1290, in runstrategies
    self._runonce(runstrats)
    File "/usr/local/lib/python3.5/dist-packages/backtrader/cerebro.py", line 1691, in _runonce
    strat._oncepost(dt0)
    File "/usr/local/lib/python3.5/dist-packages/backtrader/strategy.py", line 287, in _oncepost
    self.next()
    File "algoAndre.py", line 157, in next
    self.sell_bracket(limitprice=self.dataclose-0.02,price=self.dataclose, stopprice=self.dataclose+0.50)
    File "/usr/local/lib/python3.5/dist-packages/backtrader/strategy.py", line 1218, in sell_bracket
    oret.append(olimit)
    NameError: name 'oret' is not defined
    shell returned 1

    Whats wrong with my code? If I comment my sell_bracket it works perfectly so for now I am only able to send buy_brack



  • I didn't notice any sell_bracket statement in the code you published, only simple buy and sell. So answering your question - anything can be wrong. :)


  • administrators

    Release 1.9.63.122


Log in to reply
 

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.