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

Importing a "state of trading" from outside to backtrader



  • Hello everyone,
    I'd like to start a backtrader "session" with existing positions, with custom values / size / prices, to keep track of a pre-existing paper trading (from outside).
    Is this possible, or must I start with a "fresh" session each time with no positions ?

    Thanks :)



  • Have a look at the lifecycle of backtrader.

    You could try making your initial purchases in nextstart which runs only once between prenext and next. You would need to set the value of the cash at the first next or else the purchase made in nextstart will come from that cash.

    Let's say you want to buy 50 shares of your instrument, and then set the starting cash to $250,000, you could try something like this.

    def __init__(self):
        self.cash_set = False
    
    def nextstart(self):
        self.buy(size=50)
    
    def next(self):
        if not self.cash_set:
            self.broker.set_cash(250000)
            self.cash_set = True
    

    This will put in a market order which should fill at the first bar, leaving you with 50 shares. Then the cash will be reset to $250,000 for the start of your backtest.

    python test.py --fromdate 2003-01-01 --todate 2003-02-10
    
    BUY @price: 2003-01-31 9.03
    2003-02-03 Cash: 250000.00 Market Value 250000.00 Shares 50.00 Price 8.98
    BUY @price: 2003-02-03 8.88
    2003-02-04 Cash: 250008.88 Market Value 250443.75 Shares 49.00 Price 8.88
    

    Of course any intial acb or history from your positions in your trading account will be lost.



  • Could you please clarify the exact scenario:

    1. Do you want to start the backtesting with the position you had while live trading using paper account ? (In this case you indeed want to somehow tell the Backtrader's simulated broker about the position you had in your paper trading account)

    2. Do you want to restart the somehow terminated live-trading session using paper account ? In this case your paper trading account is probably maintaining the position for your already.

    3. Are you storing some information about your current position in your session and would like to sync it with the position maintained in your paper account upon session restart ? This may be non-trivial, given the open orders leftovers, in case of session crashes.



  • @run-out Ok thanks, that are good first steps I'll use.
    The issue is that I would like to register those "pre-buys" with a price I choose. Or the value that will change overtime will be wrong.
    For example : if I bought on my paper trading session 50 assets A for $100 in the past, I can't simulate this with your way. I'll be able to "pre-buy" 50 assets, but with the market price at the first bar. It would be amazing to "set_position" and "set_prices" of those positions manually, especially in a pre-next, to create a custom "starting state".

    @vladisld I'm not sure about the difference between scenarios. I guess it's 1. Yes, 2. No, 3. Kinda.
    I'd like to be able to create checkpoints to have a better "papertrading" behaviour on backtrader.
    If I change my data, or my signals calculations today, I'll change all my past performance and decisions if I re-run backtrader with those changes.
    I'd like to be able to do backtesting "step by step", keeping the past untouch even if I modify my code.
    Those are two faces of the same coin.

    I hope I'm clear now, and sorry for my English :)



  • I'm not sure I follow. If you buy 50 shares and have your correct starting cash balance, what difference will it make to your back test if your cost is previously $50, $60, or $120? Where will that have an impact on your results?



  • If you want to

    • import your positions from outside of the bt
    • continue your backtests (not live trading)

    than

    • extend you data feed to the past to have price data for that old positions
    • make separate strategy in bt which will issue orders to open/close that positions
    • setup 2nd strategy where you can continue development, but set the time from which this strategy issue orders

    Now when you run bt you will have old positions and new positions in the same backtest.



  • @KevinSL said in Importing a "state of trading" from outside to backtrader:

    It would be amazing to "set_position" and "set_prices" of those positions manually, especially in a pre-next, to create a custom "starting state"

    Not sure about the pre-next (which is just called in data feeds and/or indicators sync scenarios) but probably in nextstart as @run-out stated or even in separate analysis's create_analysis (as weird as it may sound ):

    Here the example (hack actually) of how it was once done in one of my experiments:

    ...
    #get the pos_size, pos_price, last_pos_update_time from somewhere 
    ...
    data_pos = self.strategy.broker.positions[self.data]
    data_pos.set(pos_size, pos_price)
    data_pos.datetime = last_pos_update_time
    


  • @run-out Oh, yeah, I maybe missunderstood how value is calculated. I thought it was a variation between "buy price" and "current price" but indeed I understand it's stupid and that's not how it would work.



  • @vladisld That's close to what I need, indeed ! I think that you all have helped me greatly, I think I'll can work from there.

    @ab_trader My code is quite dense already, I really don't want to duplicate strategies, but indeed it was a way to figure it out

    Thank you all !



  • @run-out Oh, yes, my assets are not _stocklike. So, in comminfo -> cashadjust, it will look for a price and newprice, so I guess I need them, don't I ?


Log in to reply
 

});