Current section

Files

Jump to
bingex lib bingex swap models position_update.ex
Raw

lib/bingex/swap/models/position_update.ex

defmodule Bingex.Swap.PositionUpdate do
@moduledoc """
Represents position update information for a swap contract in BingX (ws event).
This module provides a structured representation of real-time position updates,
including margin details, profit/loss, and pricing information.
"""
import Bingex.{Helpers, Convertors}
alias Bingex.Order
defstruct [
:side,
:symbol,
:margin,
:position_margin,
:average_price,
:unrealized_pnl,
:realized_pnl,
:margin_mode
]
@typedoc """
Position update information.
Fields:
- `side` (`Order.position_side()`): Position type (e.g., `long`, `short`).
- `symbol` (binary): Trading pair symbol (e.g., "BTC-USDT").
- `margin` (float): Initial margin allocated to the position.
- `position_margin` (float): Current margin assigned to the position.
- `average_price` (float): Average entry price of the position.
- `unrealized_pnl` (float): Unrealized profit or loss.
- `realized_pnl` (float): Realized profit or loss from position adjustments.
- `margin_mode` (`Order.margin_mode()`): Margin mode (e.g., `isolated`, `cross`).
"""
@type t() :: %__MODULE__{
side: Order.position_side(),
symbol: binary(),
margin: float(),
position_margin: float(),
average_price: float(),
unrealized_pnl: float(),
realized_pnl: float(),
margin_mode: Order.margin_mode()
}
@spec decode(map()) :: {:ok, t()} | :error
def decode(%{} = data) do
%__MODULE__{
side: get_and_transform(data, "ps", &decode_position_side/1),
symbol: get_and_transform(data, "s", &to_non_empty_binary/1),
margin: get_and_transform(data, "iw", &to_float/1),
position_margin: get_and_transform(data, "pa", &to_float/1),
average_price: get_and_transform(data, "ep", &to_float/1),
unrealized_pnl: get_and_transform(data, "up", &to_float/1),
realized_pnl: get_and_transform(data, "cr", &decode_position_side/1),
margin_mode: get_and_transform(data, "mt", &decode_margin_mode/1)
}
end
def decode(_data), do: :error
end