Counter-trend

Counter-trend trading is a strategy that involves taking positions against the prevailing market trend. The idea is to capitalize on potential reversals or corrections in the market. In a market-making bot, counter-trend strategies can help identify overbought or oversold conditions, allowing the bot to enter trades when prices are expected to revert to their mean.

▎How Counter-Trend Works

  1. Identifying Overbought/Oversold Conditions:

    • The bot uses indicators such as the Relative Strength Index (RSI) or Bollinger Bands to determine when an asset may be overbought (indicating a potential sell) or oversold (indicating a potential buy).

  2. Trading Decisions:

    • If the RSI indicates that an asset is overbought (e.g., RSI > 70), the bot may place sell orders.

    • If the RSI indicates that an asset is oversold (e.g., RSI < 30), the bot may place buy orders.

  3. Risk Management:

    • Similar to trend-following strategies, counter-trend strategies require robust risk management, including stop-loss orders and position sizing to protect against adverse price movements.

▎Example Code for Counter-Trend Feature

Here’s a simple implementation of a counter-trend feature within a market-making bot using Python:

import time import random

class CounterTrendBot: def init(self, rsi_period=14, overbought=70, oversold=30): self.rsi_period = rsi_period self.overbought = overbought self.oversold = oversold self.prices = [] # Store historical prices

def get_current_price(self):
    # Simulated price retrieval
    return random.uniform(95, 105)  # Simulating price around $100

def calculate_rsi(self):
    if len(self.prices) < self.rsi_period:
        return None
    
    gains = []
    losses = []

    for i in range(1, self.rsi_period):
        change = self.prices[-i] - self.prices[-(i + 1)]
        if change > 0:
            gains.append(change)
            losses.append(0)
        else:
            losses.append(-change)
            gains.append(0)

    avg_gain = sum(gains) / self.rsi_period
    avg_loss = sum(losses) / self.rsi_period

    if avg_loss == 0:
        return 100  # Avoid division by zero

    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))
    return rsi

def check_counter_trend(self):
    current_price = self.get_current_price()
    self.prices.append(current_price)

    rsi = self.calculate_rsi()

    print(f"Current Price: {current_price:.2f}, RSI: {rsi:.2f}" if rsi else f"Current Price: {current_price:.2f}")

    if rsi is not None:
        if rsi > self.overbought:
            self.execute_trade("SELL", current_price)
        elif rsi < self.oversold:
            self.execute_trade("BUY", current_price)

def execute_trade(self, action, price):
    print(f"Executing {action} at {price:.2f}")

def run(self):
    while True:
        self.check_counter_trend()
        time.sleep(1)  # Wait for a second before checking again

Example usage

if name == "main": bot = CounterTrendBot(rsi_period=14, overbought=70, oversold=30) bot.run()

▎Explanation of the Code

  • CounterTrendBot Class: This class implements a basic counter-trend strategy.

  • get_current_price(): Simulates retrieving the current market price. In a real-world application, this would interface with an API for live data.

  • calculate_rsi(): Calculates the Relative Strength Index (RSI) based on the last rsi_period prices. It returns None if there aren’t enough data points.

  • check_counter_trend(): Retrieves the current price, updates the historical prices list, calculates the RSI, and checks for trading signals based on overbought/oversold conditions.

  • execute_trade(action, price): Executes the trade by printing the action (buy/sell) and the price.

  • run(): Continuously checks for counter-trend signals every second.

Last updated