1use std::sync::Arc;
2
3use longport_httpcli::{HttpClient, Json, Method};
4use serde::{Deserialize, Serialize};
5use tracing::{Subscriber, dispatcher, instrument::WithSubscriber};
6
7use crate::{
8 Config, Result,
9 grid::{
10 GetGridOrderDetailOptions, GetGridOrdersByIdsOptions, GetGridOrdersOptions,
11 GetGridTriggerHistoryOptions, GridOrder, GridOrderDetail, GridSymbolInfo,
12 ReplaceGridOrderOptions, SubmitGridOrderOptions, TriggerOrder,
13 },
14 types::normalize_symbol_owned,
15};
16
17#[derive(Debug, Deserialize)]
18struct EmptyResponse {}
19
20#[derive(Debug, Serialize, Deserialize)]
22pub struct SubmitGridOrderResponse {
23 pub order_id: String,
25}
26
27#[derive(Debug, Deserialize)]
29pub struct GridOrdersResponse {
30 #[serde(default)]
32 pub grid_order: Vec<GridOrder>,
33 #[serde(default)]
35 pub has_more: bool,
36}
37
38#[derive(Debug, Deserialize)]
40pub struct GridTriggerHistoryResponse {
41 #[serde(default)]
43 pub trigger_orders: Vec<TriggerOrder>,
44 #[serde(default)]
46 pub has_more: bool,
47}
48
49struct InnerGridContext {
50 http_cli: HttpClient,
51 log_subscriber: Arc<dyn Subscriber + Send + Sync>,
52}
53
54impl Drop for InnerGridContext {
55 fn drop(&mut self) {
56 dispatcher::with_default(&self.log_subscriber.clone().into(), || {
57 tracing::info!("grid context dropped");
58 });
59 }
60}
61
62#[derive(Clone)]
64pub struct GridContext(Arc<InnerGridContext>);
65
66impl GridContext {
67 pub fn new(config: Arc<Config>) -> Self {
69 let log_subscriber = config.create_log_subscriber("grid");
70 dispatcher::with_default(&log_subscriber.clone().into(), || {
71 tracing::info!(language = ?config.language, "creating grid context");
72 });
73 let ctx = Self(Arc::new(InnerGridContext {
74 http_cli: config.create_http_client(),
75 log_subscriber,
76 }));
77 dispatcher::with_default(&ctx.0.log_subscriber.clone().into(), || {
78 tracing::info!("grid context created");
79 });
80 ctx
81 }
82
83 #[inline]
85 pub fn log_subscriber(&self) -> Arc<dyn Subscriber + Send + Sync> {
86 self.0.log_subscriber.clone()
87 }
88
89 pub async fn submit(&self, options: SubmitGridOrderOptions) -> Result<SubmitGridOrderResponse> {
91 Ok(self
92 .0
93 .http_cli
94 .request(Method::POST, "/v1/gridtrading/submit")
95 .body(Json(options))
96 .response::<Json<SubmitGridOrderResponse>>()
97 .send()
98 .with_subscriber(self.0.log_subscriber.clone())
99 .await?
100 .0)
101 }
102
103 pub async fn replace(&self, options: ReplaceGridOrderOptions) -> Result<()> {
105 self.0
106 .http_cli
107 .request(Method::POST, "/v1/gridtrading/replace")
108 .body(Json(options))
109 .response::<Json<EmptyResponse>>()
110 .send()
111 .with_subscriber(self.0.log_subscriber.clone())
112 .await?;
113 Ok(())
114 }
115
116 pub async fn list(
118 &self,
119 options: impl Into<Option<GetGridOrdersOptions>>,
120 ) -> Result<GridOrdersResponse> {
121 Ok(self
122 .0
123 .http_cli
124 .request(Method::GET, "/v1/gridtrading/list")
125 .query_params(options.into().unwrap_or_default())
126 .response::<Json<GridOrdersResponse>>()
127 .send()
128 .with_subscriber(self.0.log_subscriber.clone())
129 .await?
130 .0)
131 }
132
133 pub async fn list_by_ids(&self, options: GetGridOrdersByIdsOptions) -> Result<Vec<GridOrder>> {
135 #[derive(Deserialize)]
136 struct Response {
137 #[serde(default)]
138 grid_order: Vec<GridOrder>,
139 }
140
141 Ok(self
142 .0
143 .http_cli
144 .request(Method::POST, "/v1/gridtrading/list")
145 .body(Json(options))
146 .response::<Json<Response>>()
147 .send()
148 .with_subscriber(self.0.log_subscriber.clone())
149 .await?
150 .0
151 .grid_order)
152 }
153
154 pub async fn detail(&self, options: GetGridOrderDetailOptions) -> Result<GridOrderDetail> {
156 Ok(self
157 .0
158 .http_cli
159 .request(Method::GET, "/v1/gridtrading/detail")
160 .query_params(options)
161 .response::<Json<GridOrderDetail>>()
162 .send()
163 .with_subscriber(self.0.log_subscriber.clone())
164 .await?
165 .0)
166 }
167
168 pub async fn trigger_history(
170 &self,
171 options: GetGridTriggerHistoryOptions,
172 ) -> Result<GridTriggerHistoryResponse> {
173 Ok(self
174 .0
175 .http_cli
176 .request(Method::GET, "/v1/gridtrading/trigger_history_list")
177 .query_params(options)
178 .response::<Json<GridTriggerHistoryResponse>>()
179 .send()
180 .with_subscriber(self.0.log_subscriber.clone())
181 .await?
182 .0)
183 }
184
185 pub async fn cancel(&self, order_id: impl Into<String>) -> Result<()> {
187 self.grid_action("/v1/gridtrading/cancel", order_id).await
188 }
189
190 pub async fn suspend(&self, order_id: impl Into<String>) -> Result<()> {
192 self.grid_action("/v1/gridtrading/suspend", order_id).await
193 }
194
195 pub async fn restart(&self, order_id: impl Into<String>) -> Result<()> {
197 self.grid_action("/v1/gridtrading/restart", order_id).await
198 }
199
200 async fn grid_action(&self, path: &'static str, order_id: impl Into<String>) -> Result<()> {
202 #[derive(Debug, Serialize)]
203 struct Body {
204 order_id: String,
205 }
206
207 self.0
208 .http_cli
209 .request(Method::POST, path)
210 .body(Json(Body {
211 order_id: order_id.into(),
212 }))
213 .response::<Json<EmptyResponse>>()
214 .send()
215 .with_subscriber(self.0.log_subscriber.clone())
216 .await?;
217 Ok(())
218 }
219
220 pub async fn symbol_info(&self, symbol: impl Into<String>) -> Result<GridSymbolInfo> {
223 #[derive(Debug, Serialize)]
224 struct Query {
225 symbol: String,
226 }
227
228 Ok(self
229 .0
230 .http_cli
231 .request(Method::GET, "/v1/orders/info")
232 .query_params(Query {
233 symbol: normalize_symbol_owned(symbol),
234 })
235 .response::<Json<GridSymbolInfo>>()
236 .send()
237 .with_subscriber(self.0.log_subscriber.clone())
238 .await?
239 .0)
240 }
241}
242
243#[cfg(test)]
244mod symbol_normalization_tests {
245 use crate::grid::{GetGridOrdersOptions, GridTradeRule, SubmitGridOrderOptions};
246
247 #[test]
250 fn grid_builders_strip_hk_padding() {
251 let submit = SubmitGridOrderOptions::new("00700.HK", "HKD", GridTradeRule::default());
252 assert_eq!(serde_json::to_value(&submit).unwrap()["symbol"], "700.HK");
253
254 let list = GetGridOrdersOptions::new().symbol("00700.HK");
255 assert_eq!(serde_json::to_value(&list).unwrap()["symbol"], "700.HK");
256
257 let list = GetGridOrdersOptions::new().symbol("AAPL.US");
259 assert_eq!(serde_json::to_value(&list).unwrap()["symbol"], "AAPL.US");
260 }
261}