Skip to main content

Trade

Struct Trade 

Source
pub struct Trade {
Show 15 fields pub id: Uuid, pub action: Action, pub side: Side, pub option_style: OptionStyle, pub fee: Positive, pub symbol: Option<String>, pub strike: Positive, pub expiry: DateTime<Utc>, pub timestamp: i64, pub quantity: Positive, pub premium: Positive, pub contract_size: Positive, pub underlying_price: Positive, pub notes: Option<String>, pub status: TradeStatus,
}
Expand description

Represents a trade with detailed information such as action, side, option style, associated fees, and various metadata.

§Contract size

A trade carries its own contract_size, so the record stays self-contained once the position it came from is gone. premium is quoted per unit of the underlying and fee per contract: the trade’s premium is premium × contract_size × quantity and its fees fee × quantity. Trade::cost, Trade::income and Trade::net combine them with checked arithmetic and return a TradeError::ArithmeticOverflow when the result leaves the representable range.

Fields§

§id: Uuid
  • id - A universally unique identifier (UUID) for the trade.
§action: Action
  • action - The action associated with the trade (e.g., Buy or Sell).
§side: Side
  • side - Indicates whether the trade is on the Long or Short side.
§option_style: OptionStyle

Specifies the style of an options contract Call or Put.

§fee: Positive
  • fee - The transaction fee associated with the trade, represented as a positive value.
§symbol: Option<String>
  • symbol - An optional ticker symbol for the trade (e.g., “AAPL” for Apple Inc.).
§strike: Positive
  • strike - The strike price of the option, represented as a positive value (e.g., 180.0).
§expiry: DateTime<Utc>
  • expiry - The expiration date of the Option, represented as a DateTime<Utc> (e.g., 2025-06-20T00:00:00Z).
§timestamp: i64
  • timestamp - The trade execution time in nanoseconds since the Unix epoch (1970-01-01 00:00:00 UTC). Serialized using nanoseconds with serde.
§quantity: Positive
  • quantity - The number of contracts traded, represented as a positive value.
§premium: Positive
  • premium - The premium per unit of the underlying, as quoted. One contract pays premium × contract_size.
§contract_size: Positive
  • contract_size - The contract multiplier: units of the underlying covered by one contract (100 for a standard US equity option). Defaults to 1, so a trade recorded before the field existed deserializes unchanged. The trade carries its own multiplier so the record stays self-contained after the position it came from is gone.
§underlying_price: Positive
  • underlying_price - The price of the underlying asset, represented as a positive value.
§notes: Option<String>
  • notes - Optional free-form notes associated with the trade.
§status: TradeStatus

Represents the current status of a trade.

This status field indicates the state of a trade during its lifecycle. It uses the TradeStatus enum to define the possible statuses.

This field is essential for tracking and managing the lifecycle of a trade.

Implementations§

Source§

impl Trade

Source

pub fn new( id: Uuid, action: Action, side: Side, option_style: OptionStyle, fee: Positive, symbol: Option<String>, strike: Positive, expiry: DateTime<Utc>, quantity: Positive, premium: Positive, underlying_price: Positive, notes: Option<String>, status: TradeStatus, ) -> Result<Self, TradeError>

Creates a new instance of the struct with the provided parameters.

§Parameters
  • id (uuid::Uuid): The unique identifier for the entity.
  • action (Action): The action being performed (e.g., buy, sell).
  • side (Side): The side of the transaction (e.g., long, short).
  • option_style (OptionStyle): The style of the option (e.g., American, European).
  • fee (Positive): The fee associated with the transaction. It must be a positive value.
  • symbol (Option<String>): The symbol of the underlying asset, if applicable.
  • strike (Positive): The strike price of the option. This must be a positive value.
  • expiry (DateTime<Utc>): The expiration date and time of the option in UTC.
  • quantity (Positive): The quantity involved in the transaction. This must be a positive value.
  • premium (Positive): The premium per unit of the underlying.
  • underlying_price (Positive): The price of the underlying asset. This must be a positive value.
  • notes (Option<String>): Any additional notes or metadata for the transaction.
§Returns

An instance of the struct initialized with the provided parameters, along with a timestamp (i64) in nanoseconds representing the moment of creation. The contract size is 1; chain Trade::with_contract_size to record a larger multiplier.

§Errors

Returns TradeError::ArithmeticOverflow when the current time in nanoseconds since the Unix epoch leaves the i64 range, after 2262, even when truncated to whole seconds.

§Remarks
  • Ensure all Positive values are validated and created using the appropriate constructors.
  • The symbol and notes parameters are optional and can be set to None if not applicable.
Source

pub fn with_contract_size(self, contract_size: Positive) -> Self

Returns the trade with its contract multiplier set to contract_size.

Trade::new records a contract that covers one unit of the underlying; chain this to record market contracts, for example .with_contract_size(Positive::HUNDRED) for a standard US equity option.

Source

pub fn datetime(&self) -> DateTime<Utc>

Convert back to DateTime<Utc> when you need it for pretty printing.

Source

pub fn set_timestamp( &mut self, datetime: DateTime<Utc>, ) -> Result<(), TradeError>

Sets the timestamp for the current instance using the provided DateTime<Utc> value.

§Parameters
  • datetime: A DateTime<Utc> object representing the new timestamp to be set.
§Note

If the nanosecond representation overflows, falls back to the whole seconds in nanoseconds.

§Errors

Returns TradeError::ArithmeticOverflow when datetime in nanoseconds since the Unix epoch leaves the i64 range even when truncated to whole seconds (before 1677 or after 2262); the timestamp is left unchanged then.

Source

pub fn cost(&self) -> Result<Positive, TradeError>

Calculates the total cost associated with a transaction based on the action, side, fee, and premium.

§Returns

A Positive type, which represents the total cost of the transaction.

§Logic
  • The total cost is determined by the transaction’s action (Buy/Sell), side (Long/Short), fee, and premium, all adjusted by the quantity.
  • The fee is per contract and is multiplied by the quantity. The premium is per unit of the underlying and is multiplied by contract_size × quantity.
  • Depending on the combination of action and side, the following rules are applied:
    • (Action::Buy, Side::Long) or (Action::Sell, Side::Short): The cost includes both fees and premium.
    • (Action::Buy, Side::Short) or (Action::Sell, Side::Long): The cost includes only fees.
§Errors

Returns TradeError::ArithmeticOverflow when the fees, the premium or their sum leaves the Positive range. Every field is a public Positive, so the products can overflow even though each value is valid on its own.

Source

pub fn income(&self) -> Result<Positive, TradeError>

Computes the income generated based on the action and side of a trade.

§Description

This function calculates the income by determining the premium associated with the current object’s quantity, contract_size and premium values. The resulting income depends on the combination of the action and side values:

  • If the action is Buy and the side is Long, or if the action is Sell and the side is Short, the income is 0.
  • If the action is Buy and the side is Short, or if the action is Sell and the side is Long, the function returns the computed premium.
§Returns
  • Positive::ZERO: If the action and side combination does not result in an income.
  • A Positive value (equal to the computed premium): For combinations where income is generated.
§Errors

Returns TradeError::ArithmeticOverflow when premium × contract_size × quantity leaves the Positive range.

§Dependencies

This method relies on:

  • Action enum (expected values: Buy, Sell)
  • Side enum (expected values: Long, Short)
  • Positive type for representing non-negative values.
Source

pub fn net(&self) -> Result<Decimal, TradeError>

Calculates the net value by subtracting the cost from the income.

§Returns

A Decimal value representing the net result of income minus cost.

§Behavior
  • The income() method is called to obtain the income value, which is then converted to a Decimal using to_dec().
  • The cost() method is called to obtain the cost value, which is also converted to a Decimal using to_dec().
  • The net value is computed as: income.to_dec() - cost.to_dec().
§Errors

Propagates Trade::cost and Trade::income, and returns TradeError::ArithmeticOverflow when the difference leaves the Decimal range.

Source

pub fn is_open(&self) -> bool

Checks if the current trade status is Open.

§Returns
  • true - If the trade’s status is Open.
  • false - If the trade’s status is not Open.

This method is commonly used to determine whether a trade is still active and can be interacted with.

Source

pub fn is_closed(&self) -> bool

Determines whether the trade is closed.

This method checks the status of a trade and returns true if the trade’s status is TradeStatus::Closed, otherwise returns false.

§Returns
  • bool - true if the trade’s status is TradeStatus::Closed, false otherwise.
Source

pub fn is_expired(&self) -> bool

Checks if the trade has expired.

This method compares the current status of the trade with TradeStatus::Expired and returns true if the trade is expired, otherwise false.

§Returns
  • true - If the trade’s status is TradeStatus::Expired.
  • false - If the trade’s status is not TradeStatus::Expired.

Trait Implementations§

Source§

impl Clone for Trade

Source§

fn clone(&self) -> Self

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 Debug for Trade

Source§

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

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

impl<'de> Deserialize<'de> for Trade

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 Trade

Source§

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

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

impl Eq for Trade

Source§

impl Hash for Trade

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Trade

Source§

fn eq(&self, other: &Self) -> 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 Trade

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 Trade

Source§

impl TradeAble for Trade

Source§

fn trade(&self) -> Result<Trade, TradeError>

Retrieves a reference to a Trade instance associated with the current object. Read more
Source§

fn trade_ref(&self) -> Result<&Trade, TradeError>

Returns a reference to the Trade associated with the current instance. Read more
Source§

fn trade_mut(&mut self) -> Result<&mut Trade, TradeError>

Provides a mutable reference to the Trade instance contained within the current structure. Read more

Auto Trait Implementations§

§

impl Freeze for Trade

§

impl RefUnwindSafe for Trade

§

impl Send for Trade

§

impl Sync for Trade

§

impl Unpin for Trade

§

impl UnsafeUnpin for Trade

§

impl UnwindSafe for Trade

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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> 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