Current section

Files

Jump to
bingex lib bingex swap model account_event.ex
Raw

lib/bingex/swap/model/account_event.ex

defmodule Bingex.Swap.Model.AccountEvent do
@moduledoc """
Represents an account event in swap.
"""
import Bingex.{Helpers, Convertors}
alias Bingex.Swap.Model.{WalletUpdate, PositionUpdate}
defstruct [
:type,
:symbol,
:timestamp,
wallet_updates: [],
position_updates: []
]
@type t() :: %__MODULE__{
type: nil | event_type(),
symbol: nil | binary(),
wallet_updates: list(WalletUpdate.t()),
position_updates: list(PositionUpdate.t()),
timestamp: nil | integer()
}
@type event_type() :: :order | :funding_fee | :deposit | :withdraw
@spec decode(map()) :: {:ok, t()} | :error
def decode(%{} = data) do
{:ok,
%__MODULE__{
type: get_event_type(data),
symbol: get_and_transform(data, "s", &to_non_empty_binary/1),
wallet_updates: get_wallet_updates(data),
position_updates: get_position_updates(data),
timestamp: get_and_transform(data, "E", &to_pos_integer/1)
}}
end
def decode(_data), do: :error
defp get_event_type(%{"a" => %{"m" => type}}) do
case type do
"ORDER" -> :order
"FUNDING_FEE" -> :funding_fee
"DEPOSIT" -> :deposit
"WITHDRAW" -> :withdraw
_ -> nil
end
end
defp get_event_type(_), do: nil
defp get_position_updates(%{"a" => %{"P" => updates}}) when is_list(updates) do
Enum.map(updates, fn update ->
case PositionUpdate.decode(update) do
{:ok, update} -> update
:error -> nil
end
end)
|> Enum.reject(&is_nil/1)
end
defp get_position_updates(_), do: []
defp get_wallet_updates(%{"a" => %{"B" => updates}}) when is_list(updates) do
Enum.map(updates, fn update ->
case WalletUpdate.decode(update) do
{:ok, update} -> update
:error -> nil
end
end)
|> Enum.reject(&is_nil/1)
end
defp get_wallet_updates(_), do: []
end