116 lines
3.6 KiB
Python
116 lines
3.6 KiB
Python
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):
|
|
success, cash_balance = strategy.account.client.get_balance()
|
|
log.debug(f"Cash balance: {cash_balance}")
|
|
if not success:
|
|
return None
|
|
|
|
user = strategy.user
|
|
account = strategy.account
|
|
hook = callback.hook
|
|
base = callback.base
|
|
quote = callback.quote
|
|
direction = hook.direction
|
|
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()}"
|
|
|
|
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 = strategy.trade_size_percent / 100
|
|
log.debug(f"Trade size as ratio: {trade_size_as_ratio}")
|
|
amount_usd = trade_size_as_ratio * cash_balance
|
|
log.debug(f"Trade size: {amount_usd}")
|
|
price = callback.price
|
|
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 = amount_usd / price
|
|
log.debug(f"Trade size in quote: {trade_size_in_quote}")
|
|
|
|
# calculate sl/tp
|
|
stop_loss_as_ratio = strategy.stop_loss_percent / 100
|
|
take_profit_as_ratio = strategy.take_profit_percent / 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 = price * stop_loss_as_ratio
|
|
take_profit_add = price * take_profit_as_ratio
|
|
log.debug(f"Stop loss subtract: {stop_loss_subtract}")
|
|
log.debug(f"Take profit add: {take_profit_add}")
|
|
|
|
stop_loss = price - stop_loss_subtract
|
|
take_profit = price + 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=trade_size_in_quote,
|
|
# price=price,
|
|
stop_loss=stop_loss,
|
|
take_profit=take_profit,
|
|
direction=direction,
|
|
)
|
|
new_trade.save()
|
|
posted, info = new_trade.post()
|
|
log.debug(f"Posted trade: {posted} - {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)
|