Skip to main content

PerpetualPosition

Struct PerpetualPosition 

Source
pub struct PerpetualPosition {
    pub symbol: String,
    pub quantity: Positive,
    pub entry_price: Positive,
    pub side: Side,
    pub leverage: Positive,
    pub margin: Positive,
    pub margin_type: MarginType,
    pub funding_rate: Decimal,
    pub date: DateTime<Utc>,
    pub fees: Positive,
}
Expand description

Represents a perpetual swap contract position.

Perpetual swaps are derivative contracts common in cryptocurrency markets that allow traders to speculate on price movements with leverage, without an expiration date. They use a funding rate mechanism to keep the contract price anchored to the spot price.

§Fields

  • symbol - Trading pair (e.g., “BTC-USDT-PERP”)
  • quantity - Position size in base currency
  • entry_price - Average entry price
  • side - Long or Short position
  • leverage - Applied leverage (1x to 125x typical)
  • margin - Collateral posted for this position
  • margin_type - Cross or Isolated margin mode
  • funding_rate - Current funding rate (updated periodically)
  • date - Position open timestamp
  • fees - Trading fees (maker/taker)

Fields§

§symbol: String

Trading pair symbol (e.g., “BTC-USDT-PERP”).

§quantity: Positive

Position size in base currency units.

§entry_price: Positive

Average entry price for the position.

§side: Side

Position direction (Long or Short).

§leverage: Positive

Leverage multiplier applied to the position.

§margin: Positive

Margin/collateral posted for this position.

§margin_type: MarginType

Margin mode (Cross or Isolated).

§funding_rate: Decimal

Current funding rate as a decimal (e.g., 0.0001 = 0.01%).

§date: DateTime<Utc>

Timestamp when the position was opened.

§fees: Positive

Total trading fees paid.

Implementations§

Source§

impl PerpetualPosition

Source

pub const DEFAULT_FUNDING_INTERVAL_HOURS: u32 = 8

Default funding interval in hours (8 hours for most exchanges).

Source

pub const DEFAULT_MAINTENANCE_MARGIN_RATIO: Decimal = Decimal::ONE_HUNDRED

Default maintenance margin ratio (typically 0.5% to 1%).

Source

pub fn new( symbol: String, quantity: Positive, entry_price: Positive, side: Side, leverage: Positive, margin: Positive, margin_type: MarginType, funding_rate: Decimal, date: DateTime<Utc>, fees: Positive, ) -> Self

Creates a new perpetual position.

§Arguments
  • symbol - Trading pair symbol
  • quantity - Position size in base currency
  • entry_price - Average entry price
  • side - Long or Short
  • leverage - Leverage multiplier
  • margin - Collateral posted
  • margin_type - Cross or Isolated
  • funding_rate - Current funding rate
  • date - Position open timestamp
  • fees - Trading fees
Source

pub fn long( symbol: String, quantity: Positive, entry_price: Positive, leverage: Positive, margin: Positive, ) -> Self

Creates a long perpetual position with default settings.

§Arguments
  • symbol - Trading pair symbol
  • quantity - Position size
  • entry_price - Entry price
  • leverage - Leverage multiplier
  • margin - Collateral posted
Source

pub fn short( symbol: String, quantity: Positive, entry_price: Positive, leverage: Positive, margin: Positive, ) -> Self

Creates a short perpetual position with default settings.

§Arguments
  • symbol - Trading pair symbol
  • quantity - Position size
  • entry_price - Entry price
  • leverage - Leverage multiplier
  • margin - Collateral posted
Source

pub fn notional_value_at_entry(&self) -> Positive

Returns the notional value of the position.

Notional = quantity × entry_price

Source

pub fn notional_value_at_price(&self, current_price: Positive) -> Positive

Returns the current notional value at a given price.

§Arguments
  • current_price - Current market price
Source

pub fn unrealized_pnl( &self, current_price: Positive, ) -> Result<Decimal, PricingError>

Calculates the unrealized P&L at a given price.

§Arguments
  • current_price - Current market price
§Decision (issue #471): fallible because pnl_at_price is

This is the whole body of LegAble::pnl_at_price for a perpetual, so leaving it infallible would have moved that method’s abort one frame down rather than removing it. entry_price and quantity are pub, so no constructor guard bounds the product.

§Errors

Returns PricingError::Decimal when the price difference or the quantity scaling leaves the representable Decimal range.

Source

pub fn roe_percentage( &self, current_price: Positive, ) -> Result<Decimal, PricingError>

Calculates the ROE (Return on Equity) percentage.

ROE = (Unrealized P&L / Margin) × 100

A zero margin has no return on equity to report, and the function keeps its existing answer of Decimal::ZERO for that case rather than turning it into an error.

§Arguments
  • current_price - Current market price
§Errors

Propagates PerpetualPosition::unrealized_pnl, and returns PricingError::Decimal when the ratio or its percentage scaling leaves the representable Decimal range.

Source

pub fn margin_ratio( &self, current_price: Positive, ) -> Result<Decimal, PricingError>

Calculates the margin ratio at a given price.

Margin Ratio = (Margin + Unrealized P&L) / Notional Value

A zero notional has no margin ratio to report, and the function keeps its existing answer of Decimal::ZERO for that case rather than turning it into an error.

§Arguments
  • current_price - Current market price
§Errors

Propagates PerpetualPosition::unrealized_pnl, and returns PricingError::Decimal when the equity sum or the ratio leaves the representable Decimal range.

Source

pub fn update_funding_rate(&mut self, new_rate: Decimal)

Updates the funding rate.

§Arguments
  • new_rate - New funding rate
Source

pub fn effective_leverage( &self, current_price: Positive, ) -> Result<Decimal, PricingError>

Calculates the effective leverage at a given price.

Effective Leverage = Notional Value / (Margin + Unrealized P&L)

A position whose equity has been wiped out is infinitely levered, and the function keeps its existing answer of Decimal::MAX for that case rather than turning it into an error.

§Arguments
  • current_price - Current market price
§Errors

Propagates PerpetualPosition::unrealized_pnl, and returns PricingError::Decimal when the equity sum or the quotient leaves the representable Decimal range.

Trait Implementations§

Source§

impl Clone for PerpetualPosition

Source§

fn clone(&self) -> PerpetualPosition

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl ComposeSchema for PerpetualPosition

Source§

impl Debug for PerpetualPosition

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for PerpetualPosition

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for PerpetualPosition

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for PerpetualPosition

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<PerpetualPosition> for Leg

Source§

fn from(position: PerpetualPosition) -> Self

Converts to this type from the input type.
Source§

impl Fundable for PerpetualPosition

Source§

fn funding_rate(&self) -> Decimal

Returns the current funding rate (as a decimal, e.g., 0.0001 = 0.01%).
Source§

fn funding_interval_hours(&self) -> u32

Returns the funding interval in hours (typically 8 for most exchanges).
Source§

fn funding_payment(&self, mark_price: Positive) -> Decimal

Calculates the funding payment for the current period. Read more
Source§

fn annualized_funding(&self, mark_price: Positive) -> Decimal

Calculates the annualized funding cost/income. Read more
Source§

impl LegAble for PerpetualPosition

Source§

fn get_symbol(&self) -> &str

Returns the symbol/ticker of the underlying instrument.
Source§

fn get_quantity(&self) -> Positive

Returns the position quantity (number of units/contracts).
Source§

fn get_side(&self) -> Side

Returns the position side (Long or Short).
Source§

fn pnl_at_price(&self, price: Positive) -> Result<Decimal, PricingError>

Calculates the profit/loss at a given price. Read more
Source§

fn total_cost(&self) -> Result<Positive, PositionError>

Returns the total cost to establish this position. Read more
Source§

fn fees(&self) -> Result<Positive, PositionError>

Returns the total fees associated with this position. Read more
Source§

fn delta(&self) -> Result<Decimal, GreeksError>

Returns the delta of this position. Read more
Source§

fn theta(&self) -> Result<Decimal, GreeksError>

Returns the theta of this position. Read more
Source§

fn gamma(&self) -> Result<Decimal, GreeksError>

Returns the gamma of this position. Read more
Source§

fn vega(&self) -> Result<Decimal, GreeksError>

Returns the vega of this position. Read more
Source§

fn rho(&self) -> Result<Decimal, GreeksError>

Returns the rho of this position. Read more
Source§

fn is_long(&self) -> bool

Checks if this is a long position.
Source§

fn is_short(&self) -> bool

Checks if this is a short position.
Source§

fn notional_value(&self, price: Positive) -> Positive

Returns the notional value of the position at a given price. Read more
Source§

impl Marginable for PerpetualPosition

Source§

fn initial_margin(&self) -> Positive

Returns the initial margin requirement.
Source§

fn maintenance_margin(&self) -> Positive

Returns the maintenance margin requirement.
Source§

fn leverage(&self) -> Positive

Returns the current leverage applied to the position.
Source§

fn liquidation_price(&self, _current_price: Positive) -> Positive

Calculates the liquidation price for this position. Read more
Source§

fn is_liquidation_risk( &self, current_price: Positive, _margin_ratio: Decimal, ) -> bool

Checks if the position is at risk of liquidation. Read more
Source§

impl PartialEq for PerpetualPosition

Source§

fn eq(&self, other: &PerpetualPosition) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for PerpetualPosition

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for PerpetualPosition

Source§

impl ToSchema for PerpetualPosition

Source§

fn name() -> Cow<'static, str>

Return name of the schema. Read more
Source§

fn schemas(schemas: &mut Vec<(String, RefOr<Schema>)>)

Implement reference utoipa::openapi::schema::Schemas for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PartialSchema for T
where T: ComposeSchema + ?Sized,

Source§

fn schema() -> RefOr<Schema>

Return ref or schema of implementing type that can then be used to construct combined schemas.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,

Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more