longport::trade

Struct TradeContext

source
pub struct TradeContext { /* private fields */ }
Expand description

Trade context

Implementations§

source§

impl TradeContext

source

pub async fn try_new( config: Arc<Config>, ) -> Result<(Self, UnboundedReceiver<PushEvent>)>

Create a TradeContext

source

pub async fn subscribe<I>(&self, topics: I) -> Result<()>
where I: IntoIterator<Item = TopicType>,

Subscribe

Reference: https://open.longportapp.com/en/docs/trade/trade-push#subscribe

§Examples
use std::sync::Arc;

use longport::{
    decimal,
    trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext},
    Config,
};

let config = Arc::new(Config::from_env()?);
let (ctx, mut receiver) = TradeContext::try_new(config).await?;

let opts = SubmitOrderOptions::new(
    "700.HK",
    OrderType::LO,
    OrderSide::Buy,
    200,
    TimeInForceType::Day,
)
.submitted_price(decimal!(50i32));
let resp = ctx.submit_order(opts).await?;
println!("{:?}", resp);

while let Some(event) = receiver.recv().await {
    println!("{:?}", event);
}
source

pub async fn unsubscribe<I>(&self, topics: I) -> Result<()>
where I: IntoIterator<Item = TopicType>,

source

pub async fn history_executions( &self, options: impl Into<Option<GetHistoryExecutionsOptions>>, ) -> Result<Vec<Execution>>

Get history executions

Reference: https://open.longportapp.com/en/docs/trade/execution/history_executions

§Examples
use std::sync::Arc;

use longport::{
    trade::{GetHistoryExecutionsOptions, TradeContext},
    Config,
};
use time::macros::datetime;

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let opts = GetHistoryExecutionsOptions::new()
    .symbol("700.HK")
    .start_at(datetime!(2022-05-09 0:00 UTC))
    .end_at(datetime!(2022-05-12 0:00 UTC));
let resp = ctx.history_executions(opts).await?;
println!("{:?}", resp);
source

pub async fn today_executions( &self, options: impl Into<Option<GetTodayExecutionsOptions>>, ) -> Result<Vec<Execution>>

Get today executions

Reference: https://open.longportapp.com/en/docs/trade/execution/today_executions

§Examples
use std::sync::Arc;

use longport::{
    trade::{GetTodayExecutionsOptions, TradeContext},
    Config,
};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let opts = GetTodayExecutionsOptions::new().symbol("700.HK");
let resp = ctx.today_executions(opts).await?;
println!("{:?}", resp);
source

pub async fn history_orders( &self, options: impl Into<Option<GetHistoryOrdersOptions>>, ) -> Result<Vec<Order>>

Get history orders

Reference: https://open.longportapp.com/en/docs/trade/order/history_orders

§Examples
use std::sync::Arc;

use longport::{
    trade::{GetHistoryOrdersOptions, OrderSide, OrderStatus, TradeContext},
    Config, Market,
};
use time::macros::datetime;

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let opts = GetHistoryOrdersOptions::new()
    .symbol("700.HK")
    .status([OrderStatus::Filled, OrderStatus::New])
    .side(OrderSide::Buy)
    .market(Market::HK)
    .start_at(datetime!(2022-05-09 0:00 UTC))
    .end_at(datetime!(2022-05-12 0:00 UTC));
let resp = ctx.history_orders(opts).await?;
println!("{:?}", resp);
source

pub async fn today_orders( &self, options: impl Into<Option<GetTodayOrdersOptions>>, ) -> Result<Vec<Order>>

Get today orders

Reference: https://open.longportapp.com/en/docs/trade/order/today_orders

§Examples
use std::sync::Arc;

use longport::{
    trade::{GetTodayOrdersOptions, OrderSide, OrderStatus, TradeContext},
    Config, Market,
};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let opts = GetTodayOrdersOptions::new()
    .symbol("700.HK")
    .status([OrderStatus::Filled, OrderStatus::New])
    .side(OrderSide::Buy)
    .market(Market::HK);
let resp = ctx.today_orders(opts).await?;
println!("{:?}", resp);
source

pub async fn replace_order(&self, options: ReplaceOrderOptions) -> Result<()>

Replace order

Reference: https://open.longportapp.com/en/docs/trade/order/replace

§Examples
use std::sync::Arc;

use longport::{
    decimal,
    trade::{ReplaceOrderOptions, TradeContext},
    Config,
};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let opts = ReplaceOrderOptions::new("709043056541253632", 100).price(decimal!(300i32));
let resp = ctx.replace_order(opts).await?;
println!("{:?}", resp);
source

pub async fn submit_order( &self, options: SubmitOrderOptions, ) -> Result<SubmitOrderResponse>

Submit order

Reference: https://open.longportapp.com/en/docs/trade/order/submit

§Examples
use std::sync::Arc;

use longport::{
    decimal,
    trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext},
    Config,
};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let opts = SubmitOrderOptions::new(
    "700.HK",
    OrderType::LO,
    OrderSide::Buy,
    200,
    TimeInForceType::Day,
)
.submitted_price(decimal!(50i32));
let resp = ctx.submit_order(opts).await?;
println!("{:?}", resp);
source

pub async fn cancel_order(&self, order_id: impl Into<String>) -> Result<()>

Cancel order

Reference: https://open.longportapp.com/en/docs/trade/order/withdraw

§Examples
use std::sync::Arc;

use longport::{trade::TradeContext, Config};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

ctx.cancel_order("709043056541253632").await?;
source

pub async fn account_balance( &self, currency: Option<&str>, ) -> Result<Vec<AccountBalance>>

Get account balance

Reference: https://open.longportapp.com/en/docs/trade/asset/account

§Examples
use std::sync::Arc;

use longport::{trade::TradeContext, Config};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let resp = ctx.account_balance(None).await?;
println!("{:?}", resp);
source

pub async fn cash_flow( &self, options: GetCashFlowOptions, ) -> Result<Vec<CashFlow>>

Get cash flow

Reference: https://open.longportapp.com/en/docs/trade/asset/cashflow

§Examples
use std::sync::Arc;

use longport::{
    trade::{GetCashFlowOptions, TradeContext},
    Config,
};
use time::macros::datetime;

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let opts = GetCashFlowOptions::new(datetime!(2022-05-09 0:00 UTC), datetime!(2022-05-12 0:00 UTC));
let resp = ctx.cash_flow(opts).await?;
println!("{:?}", resp);
source

pub async fn fund_positions( &self, opts: impl Into<Option<GetFundPositionsOptions>>, ) -> Result<FundPositionsResponse>

Get fund positions

Reference: https://open.longportapp.com/en/docs/trade/asset/fund

§Examples
use std::sync::Arc;

use longport::{trade::TradeContext, Config};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let resp = ctx.fund_positions(None).await?;
println!("{:?}", resp);
source

pub async fn stock_positions( &self, opts: impl Into<Option<GetStockPositionsOptions>>, ) -> Result<StockPositionsResponse>

Get stock positions

Reference: https://open.longportapp.com/en/docs/trade/asset/stock

§Examples
use std::sync::Arc;

use longport::{trade::TradeContext, Config};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let resp = ctx.stock_positions(None).await?;
println!("{:?}", resp);
source

pub async fn margin_ratio( &self, symbol: impl Into<String>, ) -> Result<MarginRatio>

Get margin ratio

Reference: https://open.longportapp.com/en/docs/trade/asset/margin_ratio

§Examples
use std::sync::Arc;

use longport::{trade::TradeContext, Config};

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let resp = ctx.margin_ratio("700.HK").await?;
println!("{:?}", resp);
source

pub async fn order_detail( &self, order_id: impl Into<String>, ) -> Result<OrderDetail>

Get order detail

Reference: https://open.longportapp.com/en/docs/trade/order/order_detail

§Examples
use std::sync::Arc;

use longport::{
    trade::{GetHistoryOrdersOptions, OrderSide, OrderStatus, TradeContext},
    Config, Market,
};
use time::macros::datetime;

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let resp = ctx.order_detail("701276261045858304").await?;
println!("{:?}", resp);
source

pub async fn estimate_max_purchase_quantity( &self, opts: EstimateMaxPurchaseQuantityOptions, ) -> Result<EstimateMaxPurchaseQuantityResponse>

Estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options

Reference: https://open.longportapp.com/en/docs/trade/order/estimate_available_buy_limit

§Examples
use std::sync::Arc;

use longport::{
    trade::{EstimateMaxPurchaseQuantityOptions, OrderSide, OrderType, TradeContext},
    Config,
};
use time::macros::datetime;

let config = Arc::new(Config::from_env()?);
let (ctx, _) = TradeContext::try_new(config).await?;

let resp = ctx
    .estimate_max_purchase_quantity(EstimateMaxPurchaseQuantityOptions::new(
        "700.HK",
        OrderType::LO,
        OrderSide::Buy,
    ))
    .await?;
println!("{:?}", resp);

Trait Implementations§

source§

impl Clone for TradeContext

source§

fn clone(&self) -> TradeContext

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. 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, dst: *mut T)

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

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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> Same for T

source§

type Output = T

Should always be Self
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, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> MaybeSendSync for T