fisk/core/exchanges/common.py

98 lines
3.2 KiB
Python

from decimal import Decimal as D
from core.lib.elastic import store_msg
def get_balance_hook(user_id, user_name, account_id, account_name, balance):
"""
Called every time the balance is fetched on an account.
Store this into Elasticsearch.
"""
store_msg(
"balances",
{
"user_id": user_id,
"user_name": user_name,
"account_id": account_id,
"account_name": account_name,
"balance": balance,
},
)
def tp_price_to_percent(tp_price, current_price, current_units, unrealised_pl):
# Is this right?
pl_per_unit = D(unrealised_pl) / D(current_units)
initial_price = D(current_price) - pl_per_unit
# Get the percent change of the TP price from the initial price.
change_percent = ((D(tp_price) - initial_price) / initial_price) * 100
# Doesn't check direction
return abs(round(change_percent, 5))
def sl_price_to_percent(sl_price, current_price, current_units, unrealised_pl):
# Is this right?
pl_per_unit = D(unrealised_pl) / D(current_units)
initial_price = D(current_price) - pl_per_unit
# Get the percent change of the SL price from the initial price.
change_percent = ((D(sl_price) - initial_price) / initial_price) * 100
# Doesn't check direction
return abs(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"]
cast = {
"id": trade["id"],
"symbol": trade["symbol"],
"amount": current_units,
"side": trade["side"],
"state": trade["state"],
"price": current_price,
"pl": unrealised_pl,
}
if "takeProfitOrder" in trade:
if trade["takeProfitOrder"]:
take_profit = trade["takeProfitOrder"]["price"]
take_profit_percent = tp_price_to_percent(
take_profit, 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, 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, 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