Continue implementing live risk checks
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
from decimal import Decimal as D
|
||||
|
||||
from core.exchanges import GenericAPIError
|
||||
from core.lib.elastic import store_msg
|
||||
from core.util import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
|
||||
def get_balance_hook(user_id, user_name, account_id, account_name, balance):
|
||||
@@ -20,144 +24,73 @@ def get_balance_hook(user_id, user_name, account_id, account_name, balance):
|
||||
)
|
||||
|
||||
|
||||
def tp_price_to_percent(tp_price, side, current_price, current_units, unrealised_pl):
|
||||
def get_pair(account, base, quote, invert=False):
|
||||
"""
|
||||
Determine the percent change of the TP price from the initial price.
|
||||
Positive values indicate a profit, negative values indicate a loss.
|
||||
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.
|
||||
"""
|
||||
pl_per_unit = D(unrealised_pl) / D(current_units)
|
||||
if side == "long":
|
||||
initial_price = D(current_price) - pl_per_unit
|
||||
# Currently we only have two exchanges with different pair separators
|
||||
if account.exchange == "alpaca":
|
||||
separator = "/"
|
||||
elif account.exchange == "oanda":
|
||||
separator = "_"
|
||||
|
||||
# Flip the pair if needed
|
||||
if invert:
|
||||
symbol = f"{quote.upper()}{separator}{base.upper()}"
|
||||
else:
|
||||
initial_price = D(current_price) + pl_per_unit
|
||||
|
||||
# Get the percent change of the TP price from the initial price.
|
||||
change_percent = ((initial_price - D(tp_price)) / initial_price) * 100
|
||||
|
||||
if side == "long":
|
||||
if D(tp_price) < initial_price:
|
||||
loss = True
|
||||
else:
|
||||
loss = False
|
||||
else:
|
||||
if D(tp_price) > initial_price:
|
||||
loss = True
|
||||
else:
|
||||
loss = False
|
||||
|
||||
# if we are in loss on the short side, we want to show a negative
|
||||
if loss:
|
||||
change_percent = 0 - abs(change_percent)
|
||||
else:
|
||||
change_percent = abs(change_percent)
|
||||
|
||||
return round(change_percent, 5)
|
||||
symbol = f"{base.upper()}{separator}{quote.upper()}"
|
||||
# Check it exists
|
||||
if symbol not in account.supported_symbols:
|
||||
return False
|
||||
return symbol
|
||||
|
||||
|
||||
def sl_price_to_percent(sl_price, side, current_price, current_units, unrealised_pl):
|
||||
def to_currency(direction, account, amount, from_currency, to_currency):
|
||||
"""
|
||||
Determine the percent change of the SL price from the initial price.
|
||||
Positive values indicate a loss, negative values indicate a profit.
|
||||
This may seem backwards, but it is important to note that by default,
|
||||
SL indicates a loss, and positive values should be expected.
|
||||
Negative values indicate a negative loss, so a profit.
|
||||
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
|
||||
"""
|
||||
pl_per_unit = D(unrealised_pl) / D(current_units)
|
||||
if side == "long":
|
||||
initial_price = D(current_price) - pl_per_unit
|
||||
else:
|
||||
initial_price = D(current_price) + pl_per_unit
|
||||
# If we're converting to the same currency, just return the amount
|
||||
if from_currency == to_currency:
|
||||
return amount
|
||||
inverted = False
|
||||
|
||||
# initial_price = D(current_price) - pl_per_unit
|
||||
# This is needed because OANDA has different values for bid and ask
|
||||
if direction == "buy":
|
||||
price_index = "bids"
|
||||
elif direction == "sell":
|
||||
price_index = "asks"
|
||||
symbol = get_pair(account, from_currency, to_currency)
|
||||
if not symbol:
|
||||
symbol = get_pair(account, from_currency, to_currency, invert=True)
|
||||
inverted = True
|
||||
|
||||
# Get the percent change of the SL price from the initial price.
|
||||
change_percent = ((initial_price - D(sl_price)) / initial_price) * 100
|
||||
# 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")
|
||||
try:
|
||||
prices = account.client.get_currencies([symbol])
|
||||
except GenericAPIError as e:
|
||||
log.error(f"Error getting currencies and inverted currencies: {e}")
|
||||
return None
|
||||
price = D(prices["prices"][0][price_index][0]["price"])
|
||||
|
||||
# If the trade is long, the SL price will be higher than the initial price.
|
||||
# if side == "long":
|
||||
# change_percent *= -1
|
||||
# If we had to flip base and quote, we need to use the reciprocal of the price
|
||||
if inverted:
|
||||
price = D(1.0) / price
|
||||
|
||||
if side == "long":
|
||||
if D(sl_price) > initial_price:
|
||||
profit = True
|
||||
else:
|
||||
profit = False
|
||||
else:
|
||||
if D(sl_price) < initial_price:
|
||||
profit = True
|
||||
else:
|
||||
profit = False
|
||||
# Convert the amount to the destination currency
|
||||
converted = D(amount) * price
|
||||
|
||||
if profit:
|
||||
change_percent = 0 - abs(change_percent)
|
||||
else:
|
||||
change_percent = abs(change_percent)
|
||||
|
||||
return round(change_percent, 5)
|
||||
|
||||
|
||||
def convert_open_trades(open_trades):
|
||||
"""
|
||||
Convert a list of open trades into a list of Trade-like objects.
|
||||
"""
|
||||
trades = []
|
||||
for trade in open_trades:
|
||||
current_price = trade["price"]
|
||||
current_units = trade["currentUnits"]
|
||||
unrealised_pl = trade["unrealizedPL"]
|
||||
side = trade["side"]
|
||||
cast = {
|
||||
"id": trade["id"],
|
||||
"symbol": trade["symbol"],
|
||||
"amount": current_units,
|
||||
"side": side,
|
||||
"state": trade["state"],
|
||||
"price": current_price,
|
||||
"pl": unrealised_pl,
|
||||
}
|
||||
|
||||
# Add some extra fields, sometimes we have already looked up the
|
||||
# prices and don't need to call convert_trades_to_usd
|
||||
if "take_profit_usd" in trade:
|
||||
cast["take_profit_usd"] = trade["take_profit_usd"]
|
||||
if "stop_loss_usd" in trade:
|
||||
cast["stop_loss_usd"] = trade["stop_loss_usd"]
|
||||
if "trailing_stop_loss_usd" in trade:
|
||||
cast["trailing_stop_loss_usd"] = trade["trailing_stop_loss_usd"]
|
||||
|
||||
if "takeProfitOrder" in trade:
|
||||
if trade["takeProfitOrder"]:
|
||||
take_profit = trade["takeProfitOrder"]["price"]
|
||||
take_profit_percent = tp_price_to_percent(
|
||||
take_profit, side, current_price, current_units, unrealised_pl
|
||||
)
|
||||
|
||||
cast["take_profit"] = take_profit
|
||||
cast["take_profit_percent"] = take_profit_percent
|
||||
|
||||
if "stopLossOrder" in trade:
|
||||
if trade["stopLossOrder"]:
|
||||
stop_loss = trade["stopLossOrder"]["price"]
|
||||
stop_loss_percent = sl_price_to_percent(
|
||||
stop_loss, side, current_price, current_units, unrealised_pl
|
||||
)
|
||||
|
||||
cast["stop_loss"] = stop_loss
|
||||
cast["stop_loss_percent"] = stop_loss_percent
|
||||
|
||||
if "trailingStopLossOrder" in trade:
|
||||
if trade["trailingStopLossOrder"]:
|
||||
trailing_stop_loss = trade["trailingStopLossOrder"]["price"]
|
||||
trailing_stop_loss_percent = sl_price_to_percent(
|
||||
trailing_stop_loss,
|
||||
side,
|
||||
current_price,
|
||||
current_units,
|
||||
unrealised_pl,
|
||||
)
|
||||
|
||||
cast["trailing_stop_loss"] = trailing_stop_loss
|
||||
cast["trailing_stop_loss_percent"] = trailing_stop_loss_percent
|
||||
|
||||
trades.append(cast)
|
||||
return trades
|
||||
return converted
|
||||
|
||||
Reference in New Issue
Block a user