Skip to main content

BulkHttpClient

Struct BulkHttpClient 

Source
pub struct BulkHttpClient { /* private fields */ }
Expand description

HTTP REST API client for Bulk Labs exchange.

Supports both public (unsigned) and private (signed) endpoints. Construct with None for read-only access or provide a private key for trading operations.

Implementations§

Source§

impl BulkHttpClient

Source

pub fn new(config: &HttpConfig) -> Result<Self>

Create bulk HTTP client

§Arguments
  • config: http client config
Examples found in repository?
examples/account_query.rs (lines 39-43)
31async fn main() -> eyre::Result<()> {
32    tracing_subscriber::fmt()
33        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
34        .init();
35
36    let args = Args::parse();
37
38    info!("Connecting to {} for account: {:?}", args.url, args.account);
39    let client = BulkHttpClient::new(&HttpConfig {
40        base_url: args.url,
41        signer: None,
42        ..Default::default()
43    });
44
45    let addr = Pubkey::from_str(args.account.as_str())?;
46    let account = client?.get_account(addr).await;
47
48    eprintln!("account: {:?}", account);
49    process::exit(0);
50}
More examples
Hide additional examples
examples/md_query.rs (lines 37-41)
29async fn main() -> eyre::Result<()> {
30    tracing_subscriber::fmt()
31        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
32        .init();
33
34    let args = Args::parse();
35
36    info!("Connecting to {} for symbol: {:?}", args.url, args.symbol);
37    let client = BulkHttpClient::new(&HttpConfig {
38        base_url: args.url,
39        signer: None,
40        ..Default::default()
41    })
42    .unwrap();
43
44    let book = client.get_orderbook(&args.symbol, None, None).await?;
45    eprintln!("book: {:?}\n", book);
46
47    let ticker = client.get_ticker(&args.symbol).await?;
48    eprintln!("ticker: {:?}\n", ticker);
49
50    let markets = client.get_exchange_info().await?;
51    eprintln!("markets: {:?}\n", markets);
52
53    process::exit(0);
54}
examples/execute_cond.rs (lines 40-44)
30async fn main() -> eyre::Result<()> {
31    tracing_subscriber::fmt()
32        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
33        .init();
34
35    let args = Args::parse();
36
37    info!("Connecting to {} for execution", args.url);
38    let key = env::var("BULK_PRIVATE_KEY")?;
39    let signer = TransactionSigner::from_private_key(key.as_str())?;
40    let client = BulkHttpClient::new(&HttpConfig {
41        base_url: args.url,
42        signer: Some(signer.clone()),
43        ..Default::default()
44    })
45    .unwrap();
46
47    let account = if false {
48        Pubkey::from_str("8oqBACkDvyJjBoiWNbZPXrnjZvFjzUjMThbi9oahAVvH")?
49    } else {
50        signer.public_key()
51    };
52    let nonce = 1776682154418;
53
54    let orders = vec![Action::TakeProfit(StopOrTP {
55        symbol: Arc::from("BTC-USD"),
56        is_above: false,
57        size: 0.480894,
58        threshold: 40000.0,
59        limit: None,
60        meta: ActionMeta {
61            account,
62            nonce,
63            seqno: 0,
64            hash: None,
65        },
66    })];
67
68    let results = client.place_tx(orders, Some(account), Some(nonce)).await?;
69    eprintln!("results: {:?}\n", results);
70
71    process::exit(0);
72}
examples/execute_limit.rs (lines 40-44)
30async fn main() -> eyre::Result<()> {
31    tracing_subscriber::fmt()
32        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
33        .init();
34
35    let args = Args::parse();
36
37    info!("Connecting to {} for execution", args.url);
38    let key = env::var("BULK_PRIVATE_KEY")?;
39    let signer = TransactionSigner::from_private_key(key.as_str())?;
40    let client = BulkHttpClient::new(&HttpConfig {
41        base_url: args.url,
42        signer: Some(signer.clone()),
43        ..Default::default()
44    })
45    .unwrap();
46
47    let account = signer.public_key();
48    let nonce = make_nonce();
49
50    let mut orders = vec![
51        Action::LimitOrder(LimitOrder {
52            symbol: Arc::from("BTC-USD"),
53            is_buy: true,
54            price: 1000.0,
55            size: 0.0001,
56            tif: TimeInForce::IOC,
57            reduce_only: false,
58            iso: false,
59            builder_code: None,
60            meta: ActionMeta {
61                account,
62                nonce,
63                seqno: 0,
64                hash: None,
65            },
66        }),
67        Action::LimitOrder(LimitOrder {
68            symbol: Arc::from("ETH-USD"),
69            is_buy: true,
70            price: 1000.0,
71            size: 0.0001,
72            tif: TimeInForce::IOC,
73            reduce_only: false,
74            iso: false,
75            builder_code: None,
76            meta: ActionMeta {
77                account,
78                nonce,
79                seqno: 1,
80                hash: None,
81            },
82        }),
83    ];
84
85    let oids = orders
86        .iter_mut()
87        .map(|o| o.hash().to_string())
88        .collect::<Vec<_>>();
89
90    eprintln!("order IDs: {:?}", oids);
91
92    let results = client.place_tx(orders, Some(account), Some(nonce)).await?;
93    eprintln!("results: {:?}\n", results);
94
95    process::exit(0);
96}
Source

pub fn with_url(base_url: &str, private_key: Option<&str>) -> Result<Self>

Create bulk HTTP client with url, private key

§Arguments
  • base_url: http client url
  • private_key: optional private key
Source

pub fn with_signer(base_url: &str, signer: TransactionSigner) -> Result<Self>

Create bulk HTTP client with a pre-built signer (software key or Ledger).

§Example
let signer = TransactionSigner::from_ledger("usb://ledger", None)?;
let client = BulkHttpClient::with_signer("https://exchange-api.bulk.trade/api/v1", signer)?;
let resp = client.request_faucet(None, None, None).await?;
Source

pub fn config(&self) -> &HttpConfig

Channel configuration

Source

pub fn public_key(&self) -> Option<Pubkey>

Pubkeyt associated with this channel

Source

pub async fn get_exchange_info(&self) -> Result<Vec<MarketInfo>>

Get exchange information including all available markets.

Examples found in repository?
examples/md_query.rs (line 50)
29async fn main() -> eyre::Result<()> {
30    tracing_subscriber::fmt()
31        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
32        .init();
33
34    let args = Args::parse();
35
36    info!("Connecting to {} for symbol: {:?}", args.url, args.symbol);
37    let client = BulkHttpClient::new(&HttpConfig {
38        base_url: args.url,
39        signer: None,
40        ..Default::default()
41    })
42    .unwrap();
43
44    let book = client.get_orderbook(&args.symbol, None, None).await?;
45    eprintln!("book: {:?}\n", book);
46
47    let ticker = client.get_ticker(&args.symbol).await?;
48    eprintln!("ticker: {:?}\n", ticker);
49
50    let markets = client.get_exchange_info().await?;
51    eprintln!("markets: {:?}\n", markets);
52
53    process::exit(0);
54}
Source

pub async fn get_ticker(&self, symbol: &str) -> Result<Ticker>

Get market ticker/statistics for a symbol.

Examples found in repository?
examples/md_query.rs (line 47)
29async fn main() -> eyre::Result<()> {
30    tracing_subscriber::fmt()
31        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
32        .init();
33
34    let args = Args::parse();
35
36    info!("Connecting to {} for symbol: {:?}", args.url, args.symbol);
37    let client = BulkHttpClient::new(&HttpConfig {
38        base_url: args.url,
39        signer: None,
40        ..Default::default()
41    })
42    .unwrap();
43
44    let book = client.get_orderbook(&args.symbol, None, None).await?;
45    eprintln!("book: {:?}\n", book);
46
47    let ticker = client.get_ticker(&args.symbol).await?;
48    eprintln!("ticker: {:?}\n", ticker);
49
50    let markets = client.get_exchange_info().await?;
51    eprintln!("markets: {:?}\n", markets);
52
53    process::exit(0);
54}
Source

pub async fn get_klines( &self, symbol: &str, interval: &str, start_time: Option<u64>, end_time: Option<u64>, limit: Option<u32>, ) -> Result<Vec<Candle>>

Get historical candlestick/OHLCV data.

§Arguments
  • symbol: Market symbol (e.g. “BTC-USD”)
  • interval: Candle interval (“1m”, “5m”, “15m”, “30m”, “1h”, “4h”, “1d”, “1w”)
  • start_time: Optional start timestamp in milliseconds
  • end_time: Optional end timestamp in milliseconds
  • limit: Maximum candles to return (default 500, max 1000)
Source

pub async fn get_orderbook( &self, symbol: &str, nlevels: Option<u32>, aggregation: Option<f64>, ) -> Result<L2Snapshot>

Get L2 order book snapshot.

§Arguments
  • symbol: Market symbol
  • nlevels: Number of price levels per side (default 20, max 1000)
  • aggregation: Optional price aggregation/grouping
Examples found in repository?
examples/md_query.rs (line 44)
29async fn main() -> eyre::Result<()> {
30    tracing_subscriber::fmt()
31        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
32        .init();
33
34    let args = Args::parse();
35
36    info!("Connecting to {} for symbol: {:?}", args.url, args.symbol);
37    let client = BulkHttpClient::new(&HttpConfig {
38        base_url: args.url,
39        signer: None,
40        ..Default::default()
41    })
42    .unwrap();
43
44    let book = client.get_orderbook(&args.symbol, None, None).await?;
45    eprintln!("book: {:?}\n", book);
46
47    let ticker = client.get_ticker(&args.symbol).await?;
48    eprintln!("ticker: {:?}\n", ticker);
49
50    let markets = client.get_exchange_info().await?;
51    eprintln!("markets: {:?}\n", markets);
52
53    process::exit(0);
54}
Source

pub async fn get_account(&self, user: Pubkey) -> Result<AccountData>

Get complete account state including positions, orders, and margin.

§Arguments
  • user: user pubkey to query
Examples found in repository?
examples/account_query.rs (line 46)
31async fn main() -> eyre::Result<()> {
32    tracing_subscriber::fmt()
33        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
34        .init();
35
36    let args = Args::parse();
37
38    info!("Connecting to {} for account: {:?}", args.url, args.account);
39    let client = BulkHttpClient::new(&HttpConfig {
40        base_url: args.url,
41        signer: None,
42        ..Default::default()
43    });
44
45    let addr = Pubkey::from_str(args.account.as_str())?;
46    let account = client?.get_account(addr).await;
47
48    eprintln!("account: {:?}", account);
49    process::exit(0);
50}
Source

pub async fn get_open_orders(&self, user: &str) -> Result<Vec<OrderState>>

Get resting orders for an account.

§Arguments
  • user: user pubkey to query
Source

pub async fn get_fills(&self, user: &str) -> Result<Vec<Fill>>

Get trade history (up to 5000 recent fills).

§Arguments
  • user: user pubkey to query
Source

pub async fn get_position_history( &self, user: &str, ) -> Result<Vec<PositionInfo>>

Get closed position history (up to 5000 positions).

§Arguments
  • user: user pubkey to query
Source

pub async fn place_tx( &self, actions: Vec<Action>, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Vec<Response>>

Place multiple order actions in a single signed transaction.

Accepts any mix of limit orders, market orders, cancels, and cancel-alls.

§Example
let resp = client.place_tx(vec![
    Action::LimitOrder(LimitOrder { .. }),
    Action::CancelAll(CancelAll { .. }),
], None, None).await?;
Examples found in repository?
examples/execute_cond.rs (line 68)
30async fn main() -> eyre::Result<()> {
31    tracing_subscriber::fmt()
32        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
33        .init();
34
35    let args = Args::parse();
36
37    info!("Connecting to {} for execution", args.url);
38    let key = env::var("BULK_PRIVATE_KEY")?;
39    let signer = TransactionSigner::from_private_key(key.as_str())?;
40    let client = BulkHttpClient::new(&HttpConfig {
41        base_url: args.url,
42        signer: Some(signer.clone()),
43        ..Default::default()
44    })
45    .unwrap();
46
47    let account = if false {
48        Pubkey::from_str("8oqBACkDvyJjBoiWNbZPXrnjZvFjzUjMThbi9oahAVvH")?
49    } else {
50        signer.public_key()
51    };
52    let nonce = 1776682154418;
53
54    let orders = vec![Action::TakeProfit(StopOrTP {
55        symbol: Arc::from("BTC-USD"),
56        is_above: false,
57        size: 0.480894,
58        threshold: 40000.0,
59        limit: None,
60        meta: ActionMeta {
61            account,
62            nonce,
63            seqno: 0,
64            hash: None,
65        },
66    })];
67
68    let results = client.place_tx(orders, Some(account), Some(nonce)).await?;
69    eprintln!("results: {:?}\n", results);
70
71    process::exit(0);
72}
More examples
Hide additional examples
examples/execute_limit.rs (line 92)
30async fn main() -> eyre::Result<()> {
31    tracing_subscriber::fmt()
32        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
33        .init();
34
35    let args = Args::parse();
36
37    info!("Connecting to {} for execution", args.url);
38    let key = env::var("BULK_PRIVATE_KEY")?;
39    let signer = TransactionSigner::from_private_key(key.as_str())?;
40    let client = BulkHttpClient::new(&HttpConfig {
41        base_url: args.url,
42        signer: Some(signer.clone()),
43        ..Default::default()
44    })
45    .unwrap();
46
47    let account = signer.public_key();
48    let nonce = make_nonce();
49
50    let mut orders = vec![
51        Action::LimitOrder(LimitOrder {
52            symbol: Arc::from("BTC-USD"),
53            is_buy: true,
54            price: 1000.0,
55            size: 0.0001,
56            tif: TimeInForce::IOC,
57            reduce_only: false,
58            iso: false,
59            builder_code: None,
60            meta: ActionMeta {
61                account,
62                nonce,
63                seqno: 0,
64                hash: None,
65            },
66        }),
67        Action::LimitOrder(LimitOrder {
68            symbol: Arc::from("ETH-USD"),
69            is_buy: true,
70            price: 1000.0,
71            size: 0.0001,
72            tif: TimeInForce::IOC,
73            reduce_only: false,
74            iso: false,
75            builder_code: None,
76            meta: ActionMeta {
77                account,
78                nonce,
79                seqno: 1,
80                hash: None,
81            },
82        }),
83    ];
84
85    let oids = orders
86        .iter_mut()
87        .map(|o| o.hash().to_string())
88        .collect::<Vec<_>>();
89
90    eprintln!("order IDs: {:?}", oids);
91
92    let results = client.place_tx(orders, Some(account), Some(nonce)).await?;
93    eprintln!("results: {:?}\n", results);
94
95    process::exit(0);
96}
Source

pub async fn place_limit_order( &self, symbol: &str, side: Side, price: f64, size: f64, tif: TimeInForce, reduce_only: bool, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Place a single limit order.

Source

pub async fn place_market_order( &self, symbol: &str, side: Side, size: f64, reduce_only: bool, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Place a single market order.

Source

pub async fn cancel_order( &self, symbol: &str, order_id: &str, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Cancel a single order by ID.

Source

pub async fn cancel_all( &self, symbols: Vec<String>, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Cancel all orders, optionally filtered by symbols.

Source

pub async fn update_leverage( &self, settings: HashMap<String, f64>, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Update maximum leverage settings for markets.

§Arguments
  • settings: Map of (symbol, max_leverage) pairs
Source

pub async fn manage_agent_wallet( &self, agent_pubkey: Pubkey, delete: bool, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Create or delete an agent wallet authorization.

§Arguments
  • agent_pubkey: Agent’s public key (base58)
  • delete: true to remove the agent, false to add
Source

pub async fn approve_builder_code( &self, to: Pubkey, fee: u8, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Approve a builder-code recipient for routed orders.

Builder codes are encoded as builder-code fees on the wire.

Source

pub async fn revoke_builder_code( &self, to: Pubkey, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Revoke a builder-code recipient approval.

Source

pub async fn whitelist_faucet( &self, target_account: Pubkey, whitelist: bool, account: Option<Pubkey>, nonce: Option<u64>, ) -> Result<Response>

Whitelist or unwhitelist an account for testnet faucet access.

Testnet admin only.

§Arguments
  • target_account: account to be whitelisted
  • whitelist: if true is added whitelisted, if false removed
  • nonce: tx nonce
Source

pub async fn request_faucet( &self, user: Option<Pubkey>, amount: Option<f64>, nonce: Option<u64>, ) -> Result<Response>

Request testnet faucet funds.

Testnet only.

§Arguments
  • user: Optional target user public key (defaults to signer’s key)
  • amount: Optional specific amount (only for whitelisted accounts)
  • nonce: Optional nonce

Trait Implementations§

Source§

impl Clone for BulkHttpClient

Source§

fn clone(&self) -> BulkHttpClient

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

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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

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

Source§

fn vzip(self) -> V

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