You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

192 lines
6.4 KiB
Python

from decimal import Decimal as D
from core.exchanges import GenericAPIError
from core.models import Strategy, Trade
from core.util import logs
log = logs.get_logger(__name__)
# def to_usd(account, amount, from_currency):
# if account.exchange == "alpaca":
# separator = "/"
# elif account.exchange == "oanda":
# separator = "_"
# symbol = f"{from_currency.upper()}{separator}{to_currency.upper()}"
# prices = account.client.get_currencies([symbol])
def to_currency(direction, account, amount, from_currency, to_currency):
if account.exchange == "alpaca":
separator = "/"
elif account.exchange == "oanda":
separator = "_"
if direction == "buy":
price_index = "bids"
elif direction == "sell":
price_index = "asks"
symbol = f"{from_currency.upper()}{separator}{to_currency.upper()}"
if symbol not in account.supported_symbols:
symbol = f"{to_currency.upper()}{separator}{from_currency.upper()}"
inverted = True
try:
prices = account.client.get_currencies([symbol])
except GenericAPIError as e:
log.error(f"Error getting currencies and inverted currencies: {e}")
return None
price = prices["prices"][0][price_index][0]["price"]
if inverted:
price = D(1.0) / D(price)
converted = D(amount) * price
return converted
def get_pair(account, base, quote):
if account.exchange == "alpaca":
separator = "/"
elif account.exchange == "oanda":
separator = "_"
symbol = f"{base.upper()}{separator}{quote.upper()}"
if symbol not in account.supported_symbols:
return False
return symbol
def get_trade_size_in_base(
direction, account, strategy, cash_balance, price, base, precision
):
trade_size_as_ratio = D(strategy.trade_size_percent) / D(100)
log.debug(f"Trade size as ratio: {trade_size_as_ratio}")
amount_fiat = D(trade_size_as_ratio) * D(cash_balance)
log.debug(f"Trade size: {amount_fiat}")
# We can do this because the quote IS in $ or equivalent
# trade_size_in_base = D(amount_fiat) / D(price)
trade_size_in_base = to_currency(
direction, account, amount_fiat, account.currency, base
)
log.debug(f"Trade size in base: {trade_size_in_base}")
return trade_size_in_base
def get_tp_sl(direction, strategy, price):
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_var = D(price) * D(stop_loss_as_ratio)
take_profit_var = D(price) * D(take_profit_as_ratio)
log.debug(f"Stop loss var: {stop_loss_var}")
log.debug(f"Take profit var: {take_profit_var}")
if direction == "buy":
stop_loss = D(price) - D(stop_loss_var)
take_profit = D(price) + D(take_profit_var)
elif direction == "sell":
stop_loss = D(price) + D(stop_loss_var)
take_profit = D(price) - D(take_profit_var)
log.debug(f"Stop loss: {stop_loss}")
log.debug(f"Take profit: {take_profit}")
return (stop_loss, take_profit)
def get_price_bound(direction, strategy, price):
price_slippage_as_ratio = D(strategy.price_slippage_percent) / D(100)
log.debug(f"Price slippage as ratio: {price_slippage_as_ratio}")
price_slippage = D(price) * D(price_slippage_as_ratio)
log.debug(f"Price slippage: {price_slippage}")
if direction == "buy":
price_bound = D(price) - D(price_slippage)
elif direction == "sell":
price_bound = D(price) + D(price_slippage)
price_bound = D(price) + D(price_slippage)
log.debug(f"Price bound: {price_bound}")
return price_bound
def execute_strategy(callback, strategy):
cash_balance = strategy.account.client.get_balance()
instruments = strategy.account.instruments
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 callback.exchange != account.exchange:
log.error("Market exchange differs from account exchange.")
return
symbol = get_pair(account, base, quote)
if not symbol:
log.error(f"Symbol not supported by account: {symbol}")
return False
instrument = strategy.account.client.extract_instrument(instruments, symbol)
if not instrument:
log.error(f"Symbol not found: {symbol}")
return False
try:
trade_precision = instrument["tradeUnitsPrecision"]
display_precision = instrument["displayPrecision"]
except KeyError:
log.error(f"Precision not found for {symbol}")
return False
price = round(D(callback.price), display_precision)
log.debug(f"Extracted price of quote: {price}")
# 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_in_base = get_trade_size_in_base(
direction, account, strategy, cash_balance, price, base, display_precision
)
stop_loss, take_profit = get_tp_sl(direction, strategy, price)
price_bound = round(get_price_bound(direction, strategy, price), display_precision)
new_trade = Trade.objects.create(
user=user,
account=account,
hook=hook,
symbol=symbol,
type=type,
# amount_fiat=amount_fiat,
amount=float(round(trade_size_in_base, trade_precision)),
price=price_bound,
stop_loss=float(round(stop_loss, display_precision)),
take_profit=float(round(take_profit, display_precision)),
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.")
continue
execute_strategy(callback, strategy)