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: SideImplementations§
Source§impl OrderArgs
impl OrderArgs
Sourcepub fn new(token_id: &str, price: Decimal, size: Decimal, side: Side) -> Self
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
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§
Auto Trait Implementations§
impl Freeze for OrderArgs
impl RefUnwindSafe for OrderArgs
impl Send for OrderArgs
impl Sync for OrderArgs
impl Unpin for OrderArgs
impl UnwindSafe for OrderArgs
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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