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

Reach _trades list

  • I have to get orders and trades list after strategy stop.

    According to, they could be reached by _orders and _traders fields of strategy.

    There is no problem with _orders - it's just a list. But _trades is


    Standard Google and SO answers didn't help to transfer it into list. How to do that?

  • I reached _trades list by exploring _trades in PyCharm's variables list. Recipe:

    trades = list(list(strategy._trades.copy().values())[0].values())[0]

    Could someone suggest shorter and more elegant way? This house of cards will be crashed, the question of time.

  • you could write them to csv, or if you are using pycharm you can have the console output to csv
    did you look at the backtrader.analyzers.Transactions?

  • administrators

    Trades are indexed using 2 things:

    • data on which the trade happened
    • tradeid (default is 0 unless the user sets a specific tradeid, which can be done during buy, sell and close)

    All trades on a specific data when no specific tradeid can be fetched as:

    data_trades = self._trades[data][0]

    And this gives you a list of trades on data

    As suggested by @brad-lloyd you may write them down from the method notify_trade in the strategy.

    Or you may have a look at TradeAnalyzer which also uses the notify_trade to keep track of all trades. This would be the best model, since it seems you want to keep them, and that was the whole point of the Analyzer

  • Thank you all for suggestions. It helps!

  • I'm starting to work on some code that is intended to persist information about trades, both open and closed, in order to preserve some state of a system between restarts.

    I've looked both at observers/ as well as analyzers/

    Is either of these a better starting point than the other? In some respects, an "observer" seems to fit what I am trying to do, but instead of plotting observer values, I will be writing them to some type of persistent storage.

    I appreciate any guidance here to get started on the right foot.

  • @RandyT from my experience with drawdowns - analyzer is less memory consuming, but numbers are updated at each step; observer is mainly required for plots, but keep everything as time series. What are you going to output?

  • My requirements are as follows (and sure to grow):

    • Each system will maintain its own record of trades
      -- This is to allow the system to know its own current position and not take position from the broker since multiple systems may hold the same instrument.
    • Information about indicators values when the trades were entered and exited
      -- This is to enable applying exit rules for trades based on for example if the trend was up or down when entered.
    • Track the size of position based on a current trade.
      -- This is to enable me to scale into trades. Entering 1/2 the size given by the sizer in first tranche followed by the second half of the position if indicators are still indicating an entry on next bar.

    Generally, the requirement is to give a place to persist state so that a system can be restarted and know what its general operating rules are from that point in time and to have some information about previous trade history.

  • if you are using IB, you should be able to put each system in a sub account and manage the positions this way.

    you can also access the IB transaction log and I think you can retrieve things by order id, but I know this was somewhat of an issue for us, IB was not all that helpful. on a daily basis you should probably reconcile what your system thinks your position is vs what the broker has, the brokers make mistakes more often than you would think

    we had a similar issue with needing persistent state variables for live trading and ended up having to store them in a database, but I would think you could do the same in a single csv file and just read the last lines in at startup.

  • @Brad-Lloyd If you are referring to the IB FA accounts, I am familiar. I cannot imagine dealing with the funding issues for each subaccount to manage a strategy per subaccount. :-) Maybe that is just me. Also, I don't see any way in the IB API that I can write info about the entry as to what current values of indicators in the system are, etc.

    As I dig more into this requirement, it seems that it might be as easy as just writing out the cerebroinfo Dict or perhaps add another storage option for tradeinfo Dict? If that was updated out of notify_trade() and persisted to filesystem or some other storage, I think this would be the place to allow me to do what I am looking for.

    Any thoughts?

  • Only if you want to use:

    def pretty(d, indent=0):
                for key, value in d.iteritems():
                    if isinstance(value, dict):
                        print '\t' * indent + (("%10s: {\n") % str(key).upper())
                        pretty(value, indent+1)
                        print '\t' * indent + ' ' * 12 + ('} # %s #\n' % str(key).upper())
                    elif isinstance(value, list):
                        for val in value:
                            print '\t' * indent + (("%30s: [\n") % str(key).upper())
                            pretty(val, indent+1)
                            print '\t' * indent + ' ' * 12 + ('] # %s #\n' % str(key).upper())
                        print '\t' * indent + (("%10s: %s") % (str(key).upper(),str(value)))
    tradeAnalyzer = strat.analyzers.getbyname('TradeAnalyzer')             

Log in to reply