To create a custom trading strategy, create a new class that inherits from BaseStrategy.
Key steps in the implementation:
- Define
params: A tuple of parameters used to configure the strategy (e.g., indicator periods or column names). - Initialize indicators in
__init__: Use built-in indicators (like MACD or CrossOver) or CustomIndicator to wrap columns in your dataframe. - Define
buy_signal(self): Return True when all buy conditions are met. - Define
sell_signal(self): Return True when the sell condition is met.
Note: Inside the signal methods, self.dataclose[0] refers to the current closing price.
from fastquant import CustomStrategy, BaseStrategy
from fastquant.indicators import MACD, CrossOver
from fastquant.indicators.custom import CustomIndicator
class MAMAStrategy(BaseStrategy):
params = (
("alma_column", "alma"),
("macd_fast_period", 12),
("macd_slow_period", 16),
("macd_signal_period", 9)
)
def __init__(self):
super().__init__()
# Setup indicators
self.macd_ind = MACD(
period_me1=self.params.macd_fast_period,
period_me2=self.params.macd_slow_period,
period_signal=self.params.macd_signal_period
)
self.macd_signal_crossover = CrossOver(self.macd_ind, self.macd_ind.signal)
# Wrap a custom column from the dataframe
self.alma = CustomIndicator(self.data, custom_column=self.params.alma_column)
self.alma.plotinfo.subplot = False
self.alma.plotinfo.plotname = "ALMA"
def buy_signal(self):
# Example: Close is above ALMA AND MACD crosses signal line upward
alma_buy = self.dataclose[0] > self.alma[0]
macd_buy = self.macd_signal_crossover[0] > 0
return alma_buy and macd_buy
def sell_signal(self):
# Example: Close falls below ALMA
return self.alma[0] > self.dataclose[0]