2022-11-10 07:20:14 +00:00
|
|
|
from decimal import Decimal as D
|
|
|
|
|
2022-11-10 07:20:20 +00:00
|
|
|
from core.exchanges import GenericAPIError
|
2022-11-11 07:20:00 +00:00
|
|
|
from core.models import Account, Strategy, Trade
|
2022-10-27 17:08:40 +00:00
|
|
|
from core.util import logs
|
|
|
|
|
|
|
|
log = logs.get_logger(__name__)
|
|
|
|
|
2022-11-10 07:20:20 +00:00
|
|
|
|
|
|
|
# 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])
|
|
|
|
|
2022-11-10 19:27:46 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
def get_pair(account, base, quote, invert=False):
|
|
|
|
"""
|
|
|
|
Get the pair for the given account and currencies.
|
|
|
|
:param account: Account object
|
|
|
|
:param base: Base currency
|
|
|
|
:param quote: Quote currency
|
|
|
|
:param invert: Invert the pair
|
|
|
|
:return: currency symbol, e.g. BTC_USD, BTC/USD, etc.
|
|
|
|
"""
|
|
|
|
# Currently we only have two exchanges with different pair separators
|
2022-11-10 19:27:46 +00:00
|
|
|
if account.exchange == "alpaca":
|
|
|
|
separator = "/"
|
|
|
|
elif account.exchange == "oanda":
|
|
|
|
separator = "_"
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Flip the pair if needed
|
|
|
|
if invert:
|
|
|
|
symbol = f"{quote.upper()}{separator}{base.upper()}"
|
|
|
|
else:
|
|
|
|
symbol = f"{base.upper()}{separator}{quote.upper()}"
|
|
|
|
# Check it exists
|
|
|
|
if symbol not in account.supported_symbols:
|
|
|
|
return False
|
|
|
|
return symbol
|
|
|
|
|
|
|
|
|
|
|
|
def to_currency(direction, account, amount, from_currency, to_currency):
|
|
|
|
"""
|
|
|
|
Convert an amount from one currency to another.
|
|
|
|
:param direction: Direction of the trade
|
|
|
|
:param account: Account object
|
|
|
|
:param amount: Amount to convert
|
|
|
|
:param from_currency: Currency to convert from
|
|
|
|
:param to_currency: Currency to convert to
|
|
|
|
:return: Converted amount
|
|
|
|
"""
|
|
|
|
# This is needed because OANDA has different values for bid and ask
|
2022-11-10 19:27:46 +00:00
|
|
|
if direction == "buy":
|
|
|
|
price_index = "bids"
|
|
|
|
elif direction == "sell":
|
|
|
|
price_index = "asks"
|
2022-11-11 07:20:00 +00:00
|
|
|
symbol = get_pair(account, from_currency, to_currency)
|
|
|
|
if not symbol:
|
|
|
|
symbol = get_pair(account, from_currency, to_currency, invert=True)
|
2022-11-10 19:27:46 +00:00
|
|
|
inverted = True
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Bit of a hack but it works
|
|
|
|
if not symbol:
|
|
|
|
log.error(f"Could not find symbol for {from_currency} -> {to_currency}")
|
|
|
|
raise Exception("Could not find symbol")
|
2022-11-10 19:27:46 +00:00
|
|
|
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"]
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# If we had to flip base and quote, we need to use the reciprocal of the price
|
2022-11-10 19:27:46 +00:00
|
|
|
if inverted:
|
|
|
|
price = D(1.0) / D(price)
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Convert the amount to the destination currency
|
2022-11-10 19:27:46 +00:00
|
|
|
converted = D(amount) * price
|
|
|
|
|
|
|
|
return converted
|
|
|
|
|
2022-11-10 07:20:20 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
def get_trade_size_in_base(direction, account, strategy, cash_balance, base):
|
|
|
|
"""
|
|
|
|
Get the trade size in the base currency.
|
|
|
|
:param direction: Direction of the trade
|
|
|
|
:param account: Account object
|
|
|
|
:param strategy: Strategy object
|
|
|
|
:param cash_balance: Cash balance in the Account's base currency
|
|
|
|
:param base: Base currency
|
|
|
|
:return: Trade size in the base currency
|
|
|
|
"""
|
2022-11-10 19:52:52 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Convert the trade size in percent to a ratio
|
2022-11-10 19:52:52 +00:00
|
|
|
trade_size_as_ratio = D(strategy.trade_size_percent) / D(100)
|
|
|
|
log.debug(f"Trade size as ratio: {trade_size_as_ratio}")
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Multiply with cash balance to get the trade size in the account's
|
|
|
|
# base currency
|
2022-11-10 19:52:52 +00:00
|
|
|
amount_fiat = D(trade_size_as_ratio) * D(cash_balance)
|
|
|
|
log.debug(f"Trade size: {amount_fiat}")
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Convert the trade size to the base currency
|
2022-11-10 07:20:20 +00:00
|
|
|
trade_size_in_base = to_currency(
|
|
|
|
direction, account, amount_fiat, account.currency, base
|
|
|
|
)
|
2022-11-10 19:52:52 +00:00
|
|
|
log.debug(f"Trade size in base: {trade_size_in_base}")
|
2022-11-11 07:20:00 +00:00
|
|
|
|
2022-11-10 19:52:52 +00:00
|
|
|
return trade_size_in_base
|
|
|
|
|
2022-11-10 07:20:20 +00:00
|
|
|
|
2022-11-10 19:52:52 +00:00
|
|
|
def get_tp_sl(direction, strategy, price):
|
2022-11-11 07:20:00 +00:00
|
|
|
"""
|
|
|
|
Get the take profit and stop loss prices.
|
|
|
|
:param direction: Direction of the trade
|
|
|
|
:param strategy: Strategy object
|
|
|
|
:param price: Price of the trade
|
|
|
|
:return: Take profit and stop loss prices
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Convert TP and SL to ratios
|
2022-11-10 19:52:52 +00:00
|
|
|
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}")
|
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Calculate the TP and SL prices by multiplying with the price
|
2022-11-10 19:52:52 +00:00
|
|
|
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}")
|
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Flip addition operators for inverse trade directions
|
|
|
|
# * We need to subtract the SL for buys, since we are losing money if
|
|
|
|
# the price goes down
|
|
|
|
# * We need to add the TP for buys, since we are gaining money if
|
|
|
|
# the price goes up
|
|
|
|
# * We need to add the SL for sells, since we are losing money if
|
|
|
|
# the price goes up
|
|
|
|
# * We need to subtract the TP for sells, since we are gaining money if
|
|
|
|
# the price goes down
|
2022-11-10 19:52:52 +00:00
|
|
|
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}")
|
2022-11-11 07:20:00 +00:00
|
|
|
|
2022-11-10 19:52:52 +00:00
|
|
|
return (stop_loss, take_profit)
|
|
|
|
|
2022-11-10 07:20:20 +00:00
|
|
|
|
2022-11-10 19:52:52 +00:00
|
|
|
def get_price_bound(direction, strategy, price):
|
2022-11-11 07:20:00 +00:00
|
|
|
"""
|
|
|
|
Get the price bound for a given price using the slippage from the strategy.
|
|
|
|
:param direction: Direction of the trade
|
|
|
|
:param strategy: Strategy object
|
|
|
|
:param price: Price of the trade
|
|
|
|
:return: Price bound
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Convert the slippage to a ratio
|
2022-11-10 19:52:52 +00:00
|
|
|
price_slippage_as_ratio = D(strategy.price_slippage_percent) / D(100)
|
|
|
|
log.debug(f"Price slippage as ratio: {price_slippage_as_ratio}")
|
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Calculate the price bound by multiplying with the price
|
|
|
|
# The price bound is the worst price we are willing to pay for the trade
|
|
|
|
price_slippage = D(price) * D(price_slippage_as_ratio)
|
2022-11-10 19:52:52 +00:00
|
|
|
log.debug(f"Price slippage: {price_slippage}")
|
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Subtract slippage for buys, since we lose money if the price goes down
|
2022-11-10 19:52:52 +00:00
|
|
|
if direction == "buy":
|
|
|
|
price_bound = D(price) - D(price_slippage)
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Add slippage for sells, since we lose money if the price goes up
|
2022-11-10 19:52:52 +00:00
|
|
|
elif direction == "sell":
|
|
|
|
price_bound = D(price) + D(price_slippage)
|
|
|
|
log.debug(f"Price bound: {price_bound}")
|
|
|
|
return price_bound
|
|
|
|
|
|
|
|
|
2022-10-27 17:08:40 +00:00
|
|
|
def execute_strategy(callback, strategy):
|
2022-11-11 07:20:00 +00:00
|
|
|
"""
|
|
|
|
Execute a strategy.
|
|
|
|
:param callback: Callback object
|
|
|
|
:param strategy: Strategy object
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Get the account's balance in the native account currency
|
2022-11-04 07:20:42 +00:00
|
|
|
cash_balance = strategy.account.client.get_balance()
|
2022-10-27 17:08:40 +00:00
|
|
|
log.debug(f"Cash balance: {cash_balance}")
|
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Instruments supported by the account
|
|
|
|
if not strategy.account.instruments:
|
|
|
|
strategy.account.update_info()
|
|
|
|
# Refresh account object
|
|
|
|
strategy.account = Account.objects.get(id=strategy.account.id)
|
|
|
|
|
|
|
|
instruments = strategy.account.instruments
|
|
|
|
if not instruments:
|
|
|
|
log.error("No instruments found")
|
|
|
|
return
|
|
|
|
|
|
|
|
# Shorten some hook, strategy and callback vars for convenience
|
2022-10-27 17:08:40 +00:00
|
|
|
user = strategy.user
|
|
|
|
account = strategy.account
|
|
|
|
hook = callback.hook
|
|
|
|
base = callback.base
|
|
|
|
quote = callback.quote
|
|
|
|
direction = hook.direction
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Don't be silly
|
2022-11-10 07:20:28 +00:00
|
|
|
if callback.exchange != account.exchange:
|
|
|
|
log.error("Market exchange differs from account exchange.")
|
|
|
|
return
|
2022-10-27 17:08:40 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Get the pair we are trading
|
2022-11-10 19:52:52 +00:00
|
|
|
symbol = get_pair(account, base, quote)
|
|
|
|
if not symbol:
|
2022-10-27 17:08:40 +00:00
|
|
|
log.error(f"Symbol not supported by account: {symbol}")
|
2022-11-11 07:20:00 +00:00
|
|
|
return
|
2022-10-27 17:08:40 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
print("INSTRUMENTS", instruments)
|
|
|
|
# Extract the information for the symbol
|
2022-11-10 19:27:46 +00:00
|
|
|
instrument = strategy.account.client.extract_instrument(instruments, symbol)
|
|
|
|
if not instrument:
|
|
|
|
log.error(f"Symbol not found: {symbol}")
|
2022-11-11 07:20:00 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
# Get the required precision
|
2022-11-10 19:27:46 +00:00
|
|
|
try:
|
|
|
|
trade_precision = instrument["tradeUnitsPrecision"]
|
|
|
|
display_precision = instrument["displayPrecision"]
|
|
|
|
except KeyError:
|
|
|
|
log.error(f"Precision not found for {symbol}")
|
2022-11-11 07:20:00 +00:00
|
|
|
return
|
2022-11-10 19:52:52 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Round the received price to the display precision
|
2022-11-10 19:52:52 +00:00
|
|
|
price = round(D(callback.price), display_precision)
|
|
|
|
log.debug(f"Extracted price of quote: {price}")
|
|
|
|
|
2022-10-27 17:08:40 +00:00
|
|
|
# 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"
|
2022-11-10 07:20:20 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Only using market orders for now, but with price bounds, so it's a similar
|
|
|
|
# amount of protection from market fluctuations
|
|
|
|
# type = "market"
|
|
|
|
|
|
|
|
# For OANDA we can use the price since it should match exactly
|
|
|
|
# Not yet sure how to use both limit and market orders
|
|
|
|
type = "limit"
|
|
|
|
|
|
|
|
# Convert the trade size, which is currently in the account's base currency,
|
|
|
|
# to the base currency of the pair we are trading
|
2022-11-10 07:20:20 +00:00
|
|
|
trade_size_in_base = get_trade_size_in_base(
|
2022-11-11 07:20:00 +00:00
|
|
|
direction, account, strategy, cash_balance, base
|
2022-11-10 07:20:20 +00:00
|
|
|
)
|
2022-11-11 07:20:00 +00:00
|
|
|
|
|
|
|
# Calculate TP/SL
|
2022-11-10 19:52:52 +00:00
|
|
|
stop_loss, take_profit = get_tp_sl(direction, strategy, price)
|
2022-10-27 17:08:40 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Calculate price bound and round to the display precision
|
2022-11-10 19:52:52 +00:00
|
|
|
price_bound = round(get_price_bound(direction, strategy, price), display_precision)
|
2022-10-27 17:08:40 +00:00
|
|
|
|
2022-11-11 07:20:00 +00:00
|
|
|
# Use the price reported by the callback for limit orders
|
|
|
|
if type == "limit":
|
|
|
|
price_for_trade = price
|
|
|
|
|
|
|
|
# Use the price bound for market orders
|
|
|
|
elif type == "market":
|
|
|
|
price_for_trade = price_bound
|
|
|
|
|
|
|
|
# Create object, note that the amount is rounded to the trade precision
|
2022-10-27 17:08:40 +00:00
|
|
|
new_trade = Trade.objects.create(
|
|
|
|
user=user,
|
|
|
|
account=account,
|
|
|
|
hook=hook,
|
|
|
|
symbol=symbol,
|
|
|
|
type=type,
|
2022-11-10 19:27:46 +00:00
|
|
|
# amount_fiat=amount_fiat,
|
|
|
|
amount=float(round(trade_size_in_base, trade_precision)),
|
2022-11-11 07:20:00 +00:00
|
|
|
# price=price_bound,
|
|
|
|
price=price_for_trade,
|
2022-11-10 19:27:46 +00:00
|
|
|
stop_loss=float(round(stop_loss, display_precision)),
|
|
|
|
take_profit=float(round(take_profit, display_precision)),
|
2022-10-27 17:08:40 +00:00
|
|
|
direction=direction,
|
|
|
|
)
|
|
|
|
new_trade.save()
|
2022-11-06 07:20:32 +00:00
|
|
|
info = new_trade.post()
|
2022-11-10 07:20:14 +00:00
|
|
|
log.debug(f"Posted trade: {info}")
|
2022-10-27 17:08:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
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.")
|
2022-11-10 19:27:46 +00:00
|
|
|
continue
|
2022-10-27 17:08:40 +00:00
|
|
|
execute_strategy(callback, strategy)
|