import requests import numpy as np class MockExchangeAPI: def get_latest_price(self, symbol): # Mock function to get the latest price. Replace with actual API call. return requests.get(f"https://api.exchange.com/latestPrice?symbol={symbol}").json() def execute_trade(self, symbol, trade_type, quantity): # Mock function to execute a trade. Replace with actual API call. print(f"Executing {trade_type} trade for {quantity} of {symbol}") class TradingBot: def __init__(self, symbol, short_window, long_window, api): self.symbol = symbol self.short_window = short_window self.long_window = long_window self.api = api self.prices = [] def calculate_ema(self, prices, window): return np.mean(prices[-window:]) # Simplified EMA for demonstration def fetch_latest_price(self): latest_price = self.api.get_latest_price(self.symbol) self.prices.append(latest_price) return latest_price def evaluate_signals(self): if len(self.prices) >= self.long_window: short_ema = self.calculate_ema(self.prices, self.short_window) long_ema = self.calculate_ema(self.prices, self.long_window) if short_ema > long_ema: return "buy" elif short_ema < long_ema: return "sell" return "hold" def execute_trade(self, signal): if signal == "buy": self.api.execute_trade(self.symbol, "buy", 1) # Example quantity elif signal == "sell": self.api.execute_trade(self.symbol, "sell", 1) def run(self): while True: latest_price = self.fetch_latest_price() signal = self.evaluate_signals() self.execute_trade(signal) if __name__ == "__main__": api = MockExchangeAPI() bot = TradingBot("BTC-USD", short_window=10, long_window=50, api=api) bot.run()