-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Open
Labels
enhancementNew feature or requestNew feature or request
Description
Discussed in #1298
Originally posted by silverwolf-x August 4, 2025
I want to add reasons for the end of certain trades, for example, how do I tag the ending order of the buy trade from 2013-02-26, indicating that I ended the trade due to reason R, and write R into this order and trade.
from datetime import date
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA, GOOG
class SmaCross(Strategy):
n1 = 10
n2 = 20
def init(self):
close = self.data.Close
self.sma1 = self.I(SMA, close, self.n1)
self.sma2 = self.I(SMA, close, self.n2)
def next(self):
if not self.data.index[-1].date() >= date(2013, 2, 1):
if crossover(self.sma1, self.sma2):
self.position.close()
self.buy()
elif crossover(self.sma2, self.sma1):
self.position.close()
self.sell()
else:
if self.data.index[-1].date() == date(2013, 2, 26):
self.buy(size=1, tag="2013-02-26buy")
if self.data.index[-1].date() == date(2013, 2, 27):
self.position.close()
bt = Backtest(GOOG, SmaCross, cash=10000, commission=0.002)
stats = bt.run()
My Hope:
when calling either self.position.close(reason="R") or self.trade.close(reason="R"), I want to update the tag of any canceled order to "R". This makes sense because, at that point, the order looks like this:
{
'is_contingent': False,
'is_long': False,
'is_short': True,
'limit': None,
'parent_trade': <Trade size=34 time=2146- price=801.1- pl=173 tag=2013-02-26buy>,
'size': -34.0,
'sl': None,
'stop': None,
'tag': '2013-02-26buy',
'tp': None
}
Since the order already contains a parent_trade
, updating the tag to "R" clearly indicates that the reason for closing the trade was "R".
Additionally, it would be useful if trades included a new property: close_reason
(e.g.), which would display "R" in such cases.
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request