MACD Trading Bot Development
MACD (Moving Average Convergence Divergence) is one of the most popular trend indicators. Shows the relationship of two exponential moving averages and allows identification of momentum and trend reversals.
How MACD Works
MACD consists of three lines:
- MACD line: EMA(12) - EMA(26) of fast and slow
- Signal line: EMA(9) of MACD line
- Histogram: MACD - Signal (visualizes divergence)
Standard parameters: (12, 26, 9).
Bot Implementation
import pandas_ta as ta
import ccxt
class MACDBot:
def __init__(self, symbol: str, fast=12, slow=26, signal=9):
self.exchange = ccxt.bybit({'apiKey': API_KEY, 'secret': SECRET})
self.symbol = symbol
self.fast = fast
self.slow = slow
self.signal = signal
async def get_signal(self) -> str:
ohlcv = await self.exchange.fetch_ohlcv(self.symbol, '4h', limit=200)
df = pd.DataFrame(ohlcv, columns=['ts','open','high','low','close','vol'])
# Calculate MACD
macd_df = ta.macd(df['close'], fast=self.fast, slow=self.slow, signal=self.signal)
macd = macd_df[f'MACD_{self.fast}_{self.slow}_{self.signal}']
signal = macd_df[f'MACDs_{self.fast}_{self.slow}_{self.signal}']
hist = macd_df[f'MACDh_{self.fast}_{self.slow}_{self.signal}']
# Signal: MACD and Signal line crossover
prev_cross = macd.iloc[-2] - signal.iloc[-2]
curr_cross = macd.iloc[-1] - signal.iloc[-1]
if prev_cross < 0 and curr_cross > 0:
return 'BUY' # bullish crossover
elif prev_cross > 0 and curr_cross < 0:
return 'SELL' # bearish crossover
# Additional filter: histogram changes sign
if hist.iloc[-2] < 0 and hist.iloc[-1] > 0:
return 'BUY'
elif hist.iloc[-2] > 0 and hist.iloc[-1] < 0:
return 'SELL'
return 'HOLD'
Parameter Tuning
MACD (12, 26, 9) — for daily and 4-hour timeframes. For shorter timeframes:
- 1h: MACD (5, 13, 4) — faster reaction, more false signals
- 15m: MACD (3, 10, 16) — very aggressive, only with additional filters
Divergence is a stronger signal than just crossover: price makes new low, MACD doesn't. This is a sign of weakening downtrend.
Bot based on MACD with basic risk management logic is developed in 1–2 weeks.







