top of page

How to Automate Strategy of Supertrend and Moving Average using Python

Trading in financial markets has changed with automation. Instead of manually analyzing charts and placing trades, traders can now use Python to automate strategies and execute trades based on clear signals without emotional interference.


One effective approach combines Supertrend and Moving Average to capture strong trends while managing risk. This strategy ensures that trades align with the market direction, reducing unnecessary losses.


In this guide, we will automate this strategy using Python. You will learn how to get live data, apply Supertrend and Moving Average indicators, generate buy and sell signals, and execute trades automatically.


Setting Up the Python Environment


Python environment setup
Python environment setup


To implement this strategy, install the required libraries.

pip install pandas numpy matplotlib ta yfinance alpaca-trade-api






Import Required Libraries

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
from ta.trend import Supertrend, EMAIndicator
import alpaca_trade_api as tradeapi

Fetching Market Data


Fetch market data
Fetch market data

We use yfinance to get real-time silver price data.

symbol = "SI=F"  # Silver Futures symbol on Yahoo Finance

data = yf.download(symbol, start="2022-01-01", end="2024-01-01", interval="1d")


print(data.head())




Applying Supertrend Indicator in Python


Apply supertrend indicator
Apply supertrend indicator



To confirm strong trends, we will apply three Supertrend indicators with different settings.







def calculate_supertrend(data):
    data["Supertrend_1"] = Supertrend(data['High'], data['Low'], data['Close'], period=1, multiplier=2).supertrend
    data["Supertrend_2"] = Supertrend(data['High'], data['Low'], data['Close'], period=21, multiplier=14).supertrend
    data["Supertrend_3"] = Supertrend(data['High'], data['Low'], data['Close'], period=7, multiplier=3).supertrend
    return data
data = calculate_supertrend(data)

Applying Moving Average in Python


Apply moving average
Apply moving average

The Exponential Moving Average will be used as a trailing stop-loss and to confirm trade direction.








def calculate_ema(data, window=20):
    ema = EMAIndicator(close=data["Close"], window=window)
    data[f'EMA_{window}'] = ema.ema_indicator()
    return data
data = calculate_ema(data)

Generating Buy and Sell Signals


Generate buy and sell signal
Generate buy and sell signal

A buy trade is considered when all three Supertrend indicators turn green and the price is above the Exponential Moving Average.


A sell trade is considered when all three Supertrend indicators turn red and the price is below the Exponential Moving Average.





def generate_signals(data):
    data['Buy_Signal'] = (data['Close'] > data['Supertrend_1']) & \
                         (data['Close'] > data['Supertrend_2']) & \
                         (data['Close'] > data['Supertrend_3']) & \
                         (data['Close'] > data['EMA_20'])
    data['Sell_Signal'] = (data['Close'] < data['Supertrend_1']) & \
                          (data['Close'] < data['Supertrend_2']) & \
                          (data['Close'] < data['Supertrend_3']) & \
                          (data['Close'] < data['EMA_20'])
    
    return data
data = generate_signals(data)


Trade Execution Rules


Trade execution rules
Trade execution rules

  • When to Enter a Trade

A buy trade is placed when all Supertrend indicators are green and the price is above the Exponential Moving Average.

A sell trade is placed when all Supertrend indicators are red and the price is below the Exponential Moving Average.


  • When to Exit a Trade

The trade is exited when the price reaches the profit target or stop-loss.

If the price closes below the Exponential Moving Average for a buy trade, or above it for a sell trade, the trade is also exited.


def execute_trade(data):
    for i in range(1, len(data)):  
        if data['Buy_Signal'].iloc[i]:
            entry_price = data['Close'].iloc[i]
            stop_loss = entry_price * (1 - 0.0022)  
            target_price = entry_price * (1 + 0.0035)  
            
            for j in range(i + 1, len(data)):
                if data['Close'].iloc[j] < stop_loss or data['Close'].iloc[j] < data['EMA_20'].iloc[j]:
                    print(f"Buy at {entry_price}, Exit at {data['Close'].iloc[j]}, Profit: {data['Close'].iloc[j] - entry_price}")
                    break
                if data['Close'].iloc[j] >= target_price:
                    print(f"Buy at {entry_price}, Exit at {target_price}, Profit: {target_price - entry_price}")
                    break
        elif data['Sell_Signal'].iloc[i]:
            entry_price = data['Close'].iloc[i]
            stop_loss = entry_price * (1 + 0.0022)  
            target_price = entry_price * (1 - 0.0035)  
            
            for j in range(i + 1, len(data)):
                if data['Close'].iloc[j] > stop_loss or data['Close'].iloc[j] > data['EMA_20'].iloc[j]:
                    print(f"Sell at {entry_price}, Exit at {data['Close'].iloc[j]}, Profit: {entry_price - data['Close'].iloc[j]}")
                    break
                if data['Close'].iloc[j] <= target_price:
                    print(f"Sell at {entry_price}, Exit at {target_price}, Profit: {entry_price - target_price}")
                    break
execute_trade(data)

Automating Trades Using Alpaca API


Alpaca API
Alpaca API

To automate live trading, we use the Alpaca API.

API_KEY = "your_api_key"
API_SECRET = "your_api_secret"

api = tradeapi.REST(API_KEY, API_SECRET, BASE_URL, api_version='v2')



def place_order(symbol, qty, side):
    api.submit_order(
        symbol=symbol,
        qty=qty,
        side=side,
        type='market',
        time_in_force='gtc'
    )
if data['Buy_Signal'].iloc[-1]:
    place_order("SI=F", 1, "buy")
elif data['Sell_Signal'].iloc[-1]:
    place_order("SI=F", 1, "sell")

Final Thoughts

Automating the Supertrend and Moving Average strategy using Python ensures that trades are executed with accuracy.


This strategy:

  • Uses three Supertrend indicators to confirm strong trends

  • Uses the Exponential Moving Average as a trailing stop and trend confirmation

  • Sets profit targets and stop-loss levels for risk control

  • Automates trade execution using the Alpaca API


Before trading with real money, always backtest and paper trade the strategy. Proper risk management is essential for long-term success in algorithmic trading.


FAQs

Can this strategy be used for cryptocurrency trading?

Yes, but settings may need adjustments based on market volatility.


Why do we use three Supertrend indicators?

Using multiple Supertrend settings confirms strong trends and reduces false signals.


How can I reduce trading risk?

By setting a fixed stop-loss and trailing stop-loss, risk is controlled effectively.


Is this strategy beginner-friendly?

Yes, but beginners should practice in a demo account before trading live.


7 Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
abhay887166
Apr 20

Thanks for sharing code with explanation.

Like

This is gold for anyone into algo trading.

Like

Thank you for focusing on trading discipline.

Like

So underrated but so important. Thanks for this!

Like

Thanks for sharing a real strategy for MCX!

Like
bottom of page