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

How best to track trade PNL

  • I am struggling to work how how to output the PNL of a trade once it is in play, this is so that I can monitor a trade and close it if it's PNL reaches -1% of the account size.

    I've been looking at the self.position variable which on output shows:

    Position:  --- Position Begin
    - Size: -66666
    - Price: 1.54975
    - Price orig: 0.0
    - Closed: 0
    - Opened: -66666
    - Adjbase: 1.61085
    --- Position End

    The only aspect that seems to change on each iteration of next() is Adjbase, is that showing the change in price? If so I can work out the PNL from that perhaps.

    I've dug around the docs but struggling to find the information I need, perhaps there is an easy way to do this? Any help appreciated.


  • bt has trade object, therefore you can track trade pnl. I didn;t try it by myself, but as an idea - strategy has the attributes _tradespending and _trades which contains all trades. So it can be possible to get necessary data from there.

    Useful links - Docs - Strategy and Docs - Broker - Trades.

  • Ah perfect, thanks @ab_trader.

  • How do you access the attribute values out of _trades? I've tried this:

            for k, v in self._trades.items():

    and get this error:

    AttributeError: 'Lines_LineSeries_DataSeries_OHLC_OHLCDateTime_Abst' object has no attribute 'tradeid'

Log in to reply