"""Run with: uv run --with backtrader==1.9.78.123 backtrader-fill-example.py"""
from io import StringIO

import backtrader as bt


class RoundTrip(bt.Strategy):
    def next(self):
        if len(self) == 1:
            self.buy(size=10)
        elif len(self) == 2:
            self.sell(size=10)

    def notify_order(self, order):
        if order.status == order.Completed:
            print(order.getordername(), order.executed.size,
                  f"@ {order.executed.price:.2f}, fee {order.executed.comm:.2f}")


if __name__ == "__main__":
    # Synthetic daily bars. The signal sees the first close at 100.
    bars = StringIO(
        "date,open,high,low,close,volume\n"
        "2020-01-06,99,101,98,100,1000\n"
        "2020-01-07,102,105,101,104,1000\n"
        "2020-01-08,103,104,100,101,1000\n"
    )
    engine = bt.Cerebro(stdstats=False)
    engine.adddata(bt.feeds.GenericCSVData(
        dataname=bars, name="synthetic", dtformat="%Y-%m-%d", openinterest=-1,
    ))
    engine.addstrategy(RoundTrip)
    engine.broker.setcash(10000)
    engine.broker.setcommission(commission=0.001)
    engine.run()
    print(f"Final cash: {engine.broker.getcash():.2f}")
