OrderArgs

Struct OrderArgs 

Source
pub struct OrderArgs {
    pub token_id: String,
    pub price: Decimal,
    pub size: Decimal,
    pub side: Side,
}

Fields§

§token_id: String§price: Decimal§size: Decimal§side: Side

Implementations§

Source§

impl OrderArgs

Source

pub fn new(token_id: &str, price: Decimal, size: Decimal, side: Side) -> Self

Examples found in repository?
examples/order.rs (line 53)
15async fn main() -> Result<()> {
16    let base_url =
17        env::var("POLY_API_URL").unwrap_or_else(|_| "https://clob.polymarket.com".into());
18    let private_key = env_var("POLY_PRIVATE_KEY");
19    let chain_id = env::var("POLY_CHAIN_ID")
20        .ok()
21        .and_then(|value| value.parse::<u64>().ok())
22        .unwrap_or(137);
23
24    // CLOB auth process, more info here https://docs.polymarket.com/developers/CLOB/authentication
25    let l1_client = ClobClient::with_l1_headers(&base_url, &private_key, chain_id);
26    let creds = l1_client.create_or_derive_api_key(None).await?;
27    let mut client = ClobClient::with_l2_headers(&base_url, &private_key, chain_id, creds.clone());
28
29    if let Ok(funder) = env::var("POLY_FUNDER") {
30        client.set_funder(&funder)?;
31    }
32
33    let gamma_params = GammaListParams {
34        limit: Some(5), // how many markets to fetch max
35        ..Default::default()
36    };
37    let markets_response = client.get_markets(None, Some(&gamma_params)).await?;
38    let market = markets_response
39        .data
40        .get(1) // TODO: for some reason market[0] doesnt countain token id, nor condition id. needs fixing
41        .expect("Gamma markets returned no data");
42
43    let token_id = market.clob_token_ids.first().unwrap();
44
45    let book = client.get_order_book(&token_id).await?;
46    let best_bid = book.bids.first().expect("order book has no bids").price;
47    let best_ask = book.asks.first().expect("order book has no asks").price;
48    let book_mid = (best_bid + best_ask) / Decimal::from(2);
49    let min_order_size: Decimal = 2.into();
50    let order_size = min_order_size;
51    let order_price = book_mid;
52
53    let args = OrderArgs::new(&token_id, order_price, order_size, Side::BUY);
54    let signed_order = client.create_order(&args, None, None, None).await?;
55
56    let response = client.post_order(signed_order, OrderType::GTC).await?;
57    println!("order posted: {}", response);
58
59    Ok(())
60}
More examples
Hide additional examples
examples/wss_user.rs (line 96)
17async fn main() -> Result<()> {
18    let base_url =
19        env::var("POLY_API_URL").unwrap_or_else(|_| "https://clob.polymarket.com".into());
20    let private_key = env_var("POLY_PRIVATE_KEY");
21    let chain_id = env::var("POLY_CHAIN_ID")
22        .ok()
23        .and_then(|value| value.parse::<u64>().ok())
24        .unwrap_or(137);
25
26    let l1_client = ClobClient::with_l1_headers(&base_url, &private_key, chain_id);
27    let creds = l1_client.create_or_derive_api_key(None).await?;
28    let mut l2_client =
29        ClobClient::with_l2_headers(&base_url, &private_key, chain_id, creds.clone());
30
31    if let Ok(funder) = env::var("POLY_FUNDER") {
32        l2_client.set_funder(&funder)?;
33    }
34
35    let min_liquidity = env::var("POLY_WSS_MIN_LIQUIDITY")
36        .ok()
37        .and_then(|value| Decimal::from_str(&value).ok())
38        .unwrap_or_else(|| Decimal::from(1_000_000));
39
40    let gamma_params = GammaListParams {
41        limit: Some(5),
42        liquidity_num_min: Some(min_liquidity),
43        ..Default::default()
44    };
45    let markets_response = l2_client.get_markets(None, Some(&gamma_params)).await?;
46
47    let market_ids: Vec<String> = markets_response
48        .data
49        .iter()
50        .filter(|market| market.liquidity_num.unwrap_or(Decimal::ZERO) >= min_liquidity)
51        .map(|market| market.condition_id.clone())
52        .filter(|id| !id.is_empty())
53        .take(2)
54        .collect();
55
56    if market_ids.is_empty() {
57        return Err(PolyError::validation(
58            "Gamma did not return any markets with condition_ids",
59        ));
60    }
61
62    let primary_market = markets_response
63        .data
64        .iter()
65        .find(|market| {
66            !market.clob_token_ids.is_empty()
67                && market.liquidity_num.unwrap_or(Decimal::ZERO) >= min_liquidity
68        })
69        .ok_or_else(|| {
70            PolyError::validation("No Gamma markets returned a CLOB token id for trading")
71        })?;
72    let token_id = primary_market.clob_token_ids.first().unwrap().clone();
73
74    let book = l2_client.get_order_book(&token_id).await?;
75    let _best_ask = book.asks.first().ok_or_else(|| {
76        PolyError::validation("Order book has no asks; cannot derive a safe price")
77    })?;
78    let tick_size = primary_market.minimum_tick_size;
79    let max_bid_level = book
80        .bids
81        .iter()
82        .max_by(|a, b| {
83            a.size
84                .partial_cmp(&b.size)
85                .unwrap_or(std::cmp::Ordering::Equal)
86        })
87        .ok_or_else(|| PolyError::validation("Order book has no depth data"))?;
88    let far_price =
89        max_bid_level.price - tick_size * Decimal::from_u32(10).unwrap_or(Decimal::ZERO);
90    let order_price = if far_price > Decimal::ZERO {
91        far_price
92    } else {
93        max_bid_level.price - tick_size
94    };
95    let order_size = Decimal::new(5, 0); // 0.1 size
96    let order_args = OrderArgs::new(&token_id, order_price, order_size, Side::BUY);
97
98    let mut user_client = WssUserClient::new(creds.clone());
99    user_client.subscribe(market_ids.clone()).await?;
100
101    println!(
102        "Subscribed to user channel for markets {market_ids:?} (waiting for your cancel/update)..."
103    );
104    let signed_order = l2_client
105        .create_order(&order_args, None, None, None)
106        .await?;
107    let response = l2_client.post_order(signed_order, OrderType::GTC).await?;
108    let order_id = response
109        .get("orderID")
110        .and_then(|value| value.as_str())
111        .ok_or_else(|| PolyError::validation("Post order response missing orderID"))?
112        .to_string();
113    println!(
114        "Placed order on {} @ {}: {response:#}",
115        token_id, order_price
116    );
117    println!(
118        "Order id {} - cancel it via the `wss_cancel` example while this stream is running.",
119        order_id
120    );
121
122    loop {
123        match user_client.next_event().await {
124            Ok(WssUserEvent::Order(order)) => {
125                println!(
126                    "order {} {} matched={} price={} side={}",
127                    order.id,
128                    order.message_type,
129                    order.size_matched,
130                    order.price,
131                    order.side.as_str()
132                );
133                if order.message_type.eq_ignore_ascii_case("CANCELLATION") {
134                    println!("Order {} cancelled; exiting.", order.id);
135                    break;
136                }
137            }
138            Ok(WssUserEvent::Trade(trade)) => {
139                println!(
140                    "trade {} {} {}@{} status={}",
141                    trade.id,
142                    trade.side.as_str(),
143                    trade.size,
144                    trade.price,
145                    trade.status
146                );
147            }
148            Err(err) => {
149                eprintln!("user stream error: {}", err);
150                break;
151            }
152        }
153    }
154
155    Ok(())
156}

Trait Implementations§

Source§

impl Clone for OrderArgs

Source§

fn clone(&self) -> OrderArgs

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for OrderArgs

Source§

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

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

impl Default for OrderArgs

Source§

fn default() -> Self

Returns the “default value” for a 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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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: 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> 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