from decimal import Decimal as D from alpaca.common.exceptions import APIError from core.models import Strategy, Trade from core.util import logs log = logs.get_logger(__name__) def get_balance(account): account_info = account.client.get_account() cash = account_info["equity"] try: return float(cash) except ValueError: return False def get_market_value(account, symbol): try: position = account.client.get_position(symbol) return float(position["market_value"]) except APIError: return False def execute_strategy(callback, strategy): cash_balance = strategy.account.client.get_balance() log.debug(f"Cash balance: {cash_balance}") user = strategy.user account = strategy.account hook = callback.hook base = callback.base quote = callback.quote direction = hook.direction if account.exchange == "alpaca": if quote not in ["usd", "usdt", "usdc", "busd"]: log.error(f"Quote not compatible with Dollar: {quote}") return False quote = "usd" # TODO: MASSIVE HACK symbol = f"{base.upper()}/{quote.upper()}" elif account.exchange == "oanda": symbol = f"{base.upper()}_{quote.upper()}" if symbol not in account.supported_symbols: log.error(f"Symbol not supported by account: {symbol}") return False print(f"Identified pair from callback {symbol}") # market_from_alpaca = get_market_value(account, symbol) # change_percent = abs(((float(market_from_alpaca)-price)/price)*100) # if change_percent > strategy.price_slippage_percent: # log.error(f"Price slippage too high: {change_percent}") # return False # type = "limit" type = "market" trade_size_as_ratio = D(strategy.trade_size_percent) / D(100) log.debug(f"Trade size as ratio: {trade_size_as_ratio}") amount_usd = D(trade_size_as_ratio) * D(cash_balance) log.debug(f"Trade size: {amount_usd}") price = round(D(callback.price), 8) if not price: return log.debug(f"Extracted price of quote: {price}") # We can do this because the quote IS in $ or equivalent trade_size_in_quote = D(amount_usd) / D(price) log.debug(f"Trade size in quote: {trade_size_in_quote}") # calculate sl/tp stop_loss_as_ratio = D(strategy.stop_loss_percent) / D(100) take_profit_as_ratio = D(strategy.take_profit_percent) / D(100) log.debug(f"Stop loss as ratio: {stop_loss_as_ratio}") log.debug(f"Take profit as ratio: {take_profit_as_ratio}") stop_loss_subtract = D(price) * D(stop_loss_as_ratio) take_profit_add = D(price) * D(take_profit_as_ratio) log.debug(f"Stop loss subtract: {stop_loss_subtract}") log.debug(f"Take profit add: {take_profit_add}") stop_loss = D(price) - D(stop_loss_subtract) take_profit = D(price) + D(take_profit_add) log.debug(f"Stop loss: {stop_loss}") log.debug(f"Take profit: {take_profit}") new_trade = Trade.objects.create( user=user, account=account, hook=hook, symbol=symbol, type=type, # amount_usd=amount_usd, amount=float(round(trade_size_in_quote, 2)), # price=price, stop_loss=float(round(stop_loss, 2)), take_profit=float(round(take_profit, 2)), direction=direction, ) new_trade.save() info = new_trade.post() log.debug(f"Posted trade: {info}") def process_callback(callback): log.info(f"Received callback for {callback.hook}") strategies = Strategy.objects.filter(hooks=callback.hook, enabled=True) log.debug(f"Matched strategies: {strategies}") for strategy in strategies: log.debug(f"Executing strategy {strategy}") if callback.hook.user != strategy.user: log.error("Ownership differs between callback and strategy.") return execute_strategy(callback, strategy)