crypto_trading 0.2.2

Easy Binance API Wrapping Crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use core::fmt;
use std::{default, fmt::{write, Display}, time::{SystemTime, UNIX_EPOCH}};

use anyhow::{Context, Ok};
use serde::{Deserialize, Serialize};

use crate::{query, utils};

#[derive(Deserialize, Debug, Clone)]
struct Balance {
    #[serde(rename = "accountAlias")]
    account_alias: String,
    asset: String,  // JSON과 이름이 같으면 rename 필요 없음
    balance: String,
    #[serde(rename = "crossWalletBalance")]
    cross_wallet_balance: String,
    #[serde(rename = "crossUnPnl")]
    cross_un_pnl: String,  // 오타 수정
    #[serde(rename = "availableBalance")]
    available_balance: String,
    #[serde(rename = "maxWithdrawAmount")]
    max_withdraw_amount: String,
    #[serde(rename = "marginAvailable")]
    margin_available: bool,
    #[serde(rename = "updateTime")]
    update_time: u64,
}

// 근데 여기서 필요한 것들은 모두 구현해야한다는거지...
// 그것까지 자동화시켜야하나요?? 

#[derive(Serialize,Deserialize, Default, Clone)]
pub struct Kline {
    pub symbol: String,
    pub interval: String,
    pub open_time: u64,  // 이 필드는 i64로 수정합니다.
    pub open: f64,
    pub high: f64,
    pub low: f64,
    pub close: f64,
    pub volume: f64,
    pub close_time: u64,
    pub idx: u64,
}

impl Kline {
    pub fn open_time(&self) -> anyhow::Result<String> {
        let time = utils::timestamp_to_local(self.open_time as i64)?;
        Ok(time)
    }

    pub fn close_time(&self) -> anyhow::Result<String> {
        let time = utils::timestamp_to_local(self.close_time as i64)?;
        Ok(time)
    }

    // 캔들의 바디의 top을 반환
    pub fn get_candle_body_high(&self) -> f64 {
        // 양봉 -> 종가
        // 음봉 -> 시가
        match self.is_green_candle() {
            true => self.close,
            false => self.open,
        }
    }

    pub fn get_candle_body_low(&self) -> f64 {
        match self.is_green_candle() {
            true => self.open,
            false => self.close,
        }
    }

    // 양봉인지 체크
    pub fn is_green_candle(&self) -> bool {
        // 시가보다 종가가 높으면 양봉
        // 시가보다 종가가 낮으면 음봉

        self.open < self.close
    }
}

impl fmt::Debug for Kline {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // 매크로 내에서 실제로 중괄호를 표현하려면 {{ -> { 이렇게 해야한다고함.
        // std::fmt::Error는 데이터를 담을 수 없구나.
        let open_str = utils::timestamp_to_local(self.open_time as i64).map_err(|_| std::fmt::Error)?;
        let close_str = utils::timestamp_to_local(self.close_time as i64).map_err(|_| std::fmt::Error)?;
        write!(f, 
            "kline {{\n  open_time: {},\n  open: {},\n  high: {},\n  low: {},\n  close: {},\n  volume: {},\n  close_time: {}\n}}",  
            open_str, self.open, self.high, self.low, self.close, self.volume, close_str
        )
    }
}

#[derive(Deserialize, Default, Clone)]
pub struct Klines {
    pub kline_list: Vec<Kline>,
}

impl  Klines {
    pub fn new(kline_list: Vec<Kline>) -> Self {
        Klines { kline_list }
    }

    // show first to cnt kline data
    pub fn print_first_nth_kline(&self, cnt: usize) {
        self.kline_list.iter().take(cnt).for_each(|k| {
            println!("{:?}", k);
        });
    }

    pub fn print_last_nth_kline(&self, cnt: usize) {
        self.kline_list.iter().rev().take(cnt).for_each(|k| {
            println!("{:?}", k);
        });
    }

    pub fn close_as_vec(&self) -> Vec<f64> {
        let close_slice = self.kline_list.iter().map(|k| k.close).collect::<Vec<f64>>();
        close_slice
    }
}

impl fmt::Debug for Klines {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "klines {{")?;
        writeln!(f, "  [")?;
        for kline in &self.kline_list {
            writeln!(f, "    {:?}", kline)?;
        }
        writeln!(f, "  ]")?;
        write!(f, "}}")
    }
}

// 
pub struct BinanceRequest<T> 
where
    T: Endpoint + Into<String>, 
{
    pub base_url: BaseUrl,
    pub endpoint_url: T,
}

impl<T> BinanceRequest<T> 
where 
    T: Endpoint + Into<String>,
{
    pub fn new(base_url: BaseUrl, endpoint_url: T) -> Self {
        BinanceRequest {
            base_url,
            endpoint_url,
        }
    }

    pub fn base_url(&self) -> String {
        self.base_url.into()
    }

    pub fn query(&self) -> String {
        self.endpoint_url.query()
    }

    pub fn query_with_timestamp(&self) -> String {
        self.endpoint_url.query_with_tiemstamp()
    }
}

#[derive(Debug, Clone, Copy)]
pub enum BaseUrl {
    future, 
    spot,
}

impl From<BaseUrl> for String {
    fn from(value: BaseUrl) -> Self {
        match value {
            BaseUrl::future => "https://fapi.binance.com".to_string(),
            BaseUrl::spot => "https://api.binance.com".to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub enum CommonEndpoint {
    Klines {
        symbol: String,
        interval: String,
        limit: Option<i32>, 
    }, 
    OrderBook,
    RecentTradesList,
    HistoricalTrades,
    ExchnageInfo,
    Ticker,
}

impl From<CommonEndpoint> for String {
    fn from(value: CommonEndpoint) -> Self {
        match value {
            CommonEndpoint::Klines { symbol, interval, limit } => {
                                let limit_or_default = limit.unwrap_or(500);
                                // format!("/fapi/v1/klines?symbol={}&interval={}&limit={}", symbol, interval, limit_or_default)
                                format!("/fapi/v1/klines")
                            },
            CommonEndpoint::OrderBook => {
                                "".to_string()
                            },
            CommonEndpoint::RecentTradesList => {
                                "".to_string()
                            },
            CommonEndpoint::HistoricalTrades => {
                                "".to_string()
                            }
            CommonEndpoint::ExchnageInfo => {
                        "/fapi/v1/exchangeInfo".to_string()
                    }
            CommonEndpoint::Ticker => {
                        "/fapi/v1/ticker/24hr".to_string()
            },
        }
    }
}

/// qeury를 손쉽게 만들기 위한 Endpoint trait 구현
/// query!()를 하면 empty string이 반환된다.
impl Endpoint for CommonEndpoint {
    fn query(&self) -> String {
        match self {
            CommonEndpoint::Klines { symbol, interval, limit } => {
                                let limit = limit.unwrap_or(500);
                                query!(symbol, interval, limit)   
                            },
            CommonEndpoint::OrderBook => todo!(),
            CommonEndpoint::RecentTradesList => todo!(),
            CommonEndpoint::HistoricalTrades => todo!(),
            CommonEndpoint::ExchnageInfo => query!(),
            CommonEndpoint::Ticker => query!(),
        }
    }
}

// impl CommonEndpoint {
//     fn query(&self) -> String {
//         self.query()
//     }  
// }

pub enum UserEndpoint {
    Balance, 
    AccountConfig, 
    QueryOrder {
        symbol: String,
    },
    AllOrders {
        symbol: String,
    }
}

impl Endpoint for UserEndpoint {
    fn query(&self) -> String {
        match self {
            UserEndpoint::Balance => {
                query!()
            },
            UserEndpoint::AccountConfig => {
                String::new()
            },
            UserEndpoint::QueryOrder{ symbol } => {
                query!(symbol)
            },
            UserEndpoint::AllOrders{ symbol } => {
                query!(symbol)
            },
        }
    }
}

impl From<UserEndpoint> for String {
    fn from(value: UserEndpoint) -> Self {
        match value {
            UserEndpoint::Balance => {
                "fapi/v3/balance".to_string()
            },
            UserEndpoint::AccountConfig => {
                String::new()
            },
            UserEndpoint::QueryOrder{ symbol: _ } => {
                "fapi/v1/order".to_string()
            },
            UserEndpoint::AllOrders{ symbol: _ } => {
                "fapi/v1/allOrders".to_string()
            },
        }
    }
}

pub enum TradeEndpoint {
    Order,
    Leverage{
        symbol: String,
        leverage: i32,
    },
    CancelOrder {
        symbol: String,
    }, 
    AllOpenOrder {
        symbol: String,
    }, 
    NewOrder {
        symbol: String,
        side: String,   // buy or sell
        r#type: String, // order type ... additional parameter need... 
        time_in_force: String,
        quantity: String,
        price: String,
        stop_price: f64,
        callback_rate: f64,
    }
}

// NewOrder

// trait bound로 가야할 것 같은데?

impl Endpoint for TradeEndpoint {
    fn query(&self) -> String {
        match self {
            TradeEndpoint::Leverage { symbol, leverage } => {
                        query!(symbol, leverage)                
                    },
            TradeEndpoint::Order => {
                        String::new()
                    }
            TradeEndpoint::CancelOrder { symbol } => {
                        query!(symbol)
                    },
            TradeEndpoint::AllOpenOrder { symbol } => {
                        query!(symbol)
                    },
            TradeEndpoint::NewOrder { symbol, side, r#type, time_in_force, quantity, price,  stop_price, callback_rate} => {
                match r#type.as_str() {
                    "LIMIT" => {
                        query!(symbol, side, r#type, time_in_force, quantity, price)
                    },
                    "MARKET" => {
                        query!(symbol, side, r#type, quantity)
                    },
                    "STOP" | "TAKE_PROFIT" => {
                        query!(symbol, side, r#type, quantity, price, stop_price)
                    }, 
                    "STOP_MARKET" | "TAKE_PROFIT_MARKET" => {
                        query!(symbol, side, r#type, stop_price)
                    },
                    "TRAILING_STOP_MARKET" => {
                        query!(symbol, side, r#type, callback_rate)
                    },
                    _ => {
                        "".to_string()
                    }
                }
            },
        }
    }
}

impl From<TradeEndpoint> for String {
    fn from(value: TradeEndpoint) -> Self {
        match value {
            TradeEndpoint::Order => "/fapi/v1/order".to_string(),
            TradeEndpoint::Leverage { symbol: _, leverage: _ } => {
                                format!("fapi/v1/leverage")
                            },
            TradeEndpoint::CancelOrder { symbol: _ } => {
                                format!("fapi/v1/order")
                            },
            TradeEndpoint::AllOpenOrder { symbol: _ } => {
                                format!("fapi/v1/allOpenOrders")
                            }
            TradeEndpoint::NewOrder { symbol, side, r#type, time_in_force, quantity, price, stop_price, callback_rate } => {
                                format!("fapi/v1/order")
                            },
        }
    }
}

// Endpoint trait bound를 활용하기 위함.
// 
pub trait Endpoint {
    fn query(&self) -> String;
    fn query_with_tiemstamp(&self) -> String {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH).unwrap()
            .as_millis()
            .to_string();

        format!("{}&timestamp={}", self.query(), timestamp)
    }
}

struct Order {
    symbol: Option<String>,
    side: Option<String>,   // buy or sell
    r#type: Option<String>, // order type ... additional parameter need... 
    time_in_force: Option<String>,
    quantity: Option<String>,
    price: Option<String>,
    stop_price: Option<f64>,
    callback_rate: Option<f64>,
}

impl Order {
    pub fn new(
        symbol: Option<String>,
        side: Option<String>,
        r#type: Option<String>,
        time_in_force: Option<String>,
        quantity: Option<String>,
        price: Option<String>,
        stop_price: Option<f64>,
        callback_rate: Option<f64>,
    ) -> Self {
        Order {
            symbol,
            side,
            r#type,
            time_in_force,
            quantity,
            price,
            stop_price,
            callback_rate,
        }
    }
}

// #[derive(Debug, Deserialize)]
// pub struct BinanceSymbols {
    
// }

/// exchangeInfo 
#[derive(Debug, Deserialize)]
pub struct BinanceSymbol {
    pub symbol: String,
}

/// Ticker
#[derive(Debug, Deserialize)]
pub struct Tickers {
    tickers: Vec<Ticker>
}

#[derive(Debug, Deserialize, Clone)]
pub struct Ticker {
    pub symbol: String,
    #[serde(rename = "quoteVolume")]
    pub quote_volume: String,
}