Created
March 24, 2022 07:27
-
-
Save vedgar/24dba17dbe75a93901c5ae3d2bde8f0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Basic example of a Trading bot with a strategy pattern.""" | |
from statistics import mean | |
from dataclasses import dataclass | |
from functools import partial | |
from exchange import Exchange | |
class Avg: | |
def should_buy(prices: list[int], window_size: int) -> bool: | |
list_window = prices[-window_size:] | |
return prices[-1] < mean(list_window) | |
def should_sell(prices: list[int], window_size: int) -> bool: | |
list_window = prices[-window_size:] | |
return prices[-1] > mean(list_window) | |
class Minmax: | |
def should_buy(prices: list[int], max_price: int) -> bool: | |
return prices[-1] < max_price | |
def should_sell(prices: list[int], min_price: int) -> bool: | |
return prices[-1] > min_price | |
@dataclass | |
class TradingBot: | |
"""Trading bot that connects to a crypto exchange and performs trades.""" | |
exchange: Exchange | |
strategy: type | |
def run(self, symbol: str) -> None: | |
prices = self.exchange.get_market_data(symbol) | |
if self.strategy.to_buy(prices): self.exchange.buy(symbol, 10) | |
elif self.strategy.to_sell(prices): self.exchange.sell(symbol, 10) | |
else: print(f"No action needed for {symbol}.") | |
if __name__ == "__main__": | |
(exchange := Exchange()).connect() | |
class Strategy: | |
to_buy = partial(Minmax.should_buy, max_price=32_000_00) | |
to_sell = partial(Minmax.should_sell, min_price=38_000_00) | |
TradingBot(exchange, Strategy).run("BTC/USD") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment