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

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=[''], 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 = 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)

    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]
            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
        # 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():
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:  # Sell
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
            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:
        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:
        # 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 =
            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,, doprint=True)

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

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

    Traceback (most recent call last):
    File "", line 166, in <module>
    strategies =
    File "/usr/local/lib/python3.5/dist-packages/backtrader/", line 1127, in run
    runstrat = self.runstrategies(iterstrat)
    File "/usr/local/lib/python3.5/dist-packages/backtrader/", line 1290, in runstrategies
    File "/usr/local/lib/python3.5/dist-packages/backtrader/", line 1691, in _runonce
    File "/usr/local/lib/python3.5/dist-packages/backtrader/", line 287, in _oncepost
    File "", 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/", line 1218, in sell_bracket
    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


Log in to reply