kucoin_api/lib.rs
1//! # kucoin_api
2//! kucoin_api is an open source library API wrapper for the
3//! [Kucoin Cryptocurrency Exchange](https://www.kucoin.com/). It is derived from Eric Abraham's kucoin_rs.
4//!
5//! Trading cryptocurrencies is high risk and there are no guarentees towards the stability or effectiveness
6//! of this project. Comments, contributions, stars and donations are, however, all welcome.
7//!
8//! ## Description
9//!
10//! kucoin_api supports all currently available Kucoin REST and Websocket endpoints. It is designed to be
11//! async and relies primarily on the tokio async runtime, reqwest for the HTTP layer and tokio_tungstenite
12//! for the Websocket layer.
13//!
14//! For the official API documentation visit [Kucoin Docs](https://docs.kucoin.com/).
15//!
16//! Please be aware that due to the nature of a number of endpoints, the response structs and input parameters of
17//! several requests may contain Option\<T\> and will require appropriate pattern matching. These generally coincide
18//! with optional input params which can be seen by visiting the official Kucoin API documentation noted above.
19//!
20//! These project docs also provide details regarding necessary input parameters and response structs,
21//! helping to identify cases where Option\<T\> matching is and is not necessary.
22//!
23//! ## Getting Started
24//!
25//! The library can be used either directly through the git repository or by utilizing cargo and installing the desired version. Once
26//! the library is accessible, simply bring the extern crate into your project.
27//!
28//! If you want information on particular endpoints, please review the library documentation.
29//!
30//! ### Authorization
31//!
32//! Authorization is required for many of the endpoints. The [`Kucoin Client`](./kucoin/client/struct.Kucoin.html) handles all
33//! header construction but does require that the client is initialized with credentials to do so. To include credentials do the following:
34//!
35//! ```
36//! use kucoin_api::client::{Kucoin, Credentials, KucoinEnv};
37//!
38//! let credentials = Credentials::new(
39//! "xxxxxxxxxxxxxXXXXXXxxx", // API KEY
40//! "XXxxxxx-xxxxxx-xXxxxx-xxxx", // SECRET KEY
41//! "xxxxxx" // PASSPHRASE
42//! );
43//!
44//! let api = Kucoin::new(KucoinEnv::Live, Some(credentials));
45//! ```
46//! A non-authorized client can be used for accessing Public Endpoints by inputting a None: `Kucoin::new(KucoinEnv::Live, None);`
47//!
48//! ## Examples
49//!
50//! Below are some basic examples.
51//!
52//! Private endpoints require an authorized client. Check above for further details on initializing kucoin_api
53//! with appropriate credentials to access private endpoints
54//!
55//! ### REST Usage
56//!
57//! REST calls, like Websocket connections, require first setting up the client. Once the client is setup, calls can be made in whatever
58//! ways suit end-users' needs.
59//!
60//! Please note that endpoints have varying amounts of input parameter requirements and options. Required parameters are always direct inputs
61//! but types may vary. Optional requirements are wrapped in Option\<T\>, so be aware that a large number of calls require None or Some(T).
62//! inputs. The endpoints with signficant number of options take advantage of builder methods on optional structs.
63//! This documention provides details of where this is necessary. To check for specific endpoints, see:
64//! [`Kucoin Client`](./kucoin/client/struct.Kucoin.html). Optional structs with builders will be identified in the fn signatures.
65//!
66//! A simple example is:
67//!
68//! ```ignore
69//! extern crate kucoin_api;
70//!
71//! use kucoin_api::tokio;
72//! use kucoin_api::failure;
73//! use kucoin_api::client::{Kucoin, Credentials, KucoinEnv};
74//!
75//! #[tokio::main]
76//! async fn main() -> Result<(), failure::Error> {
77//! let api = Kucoin::new(KucoinEnv::Sandbox, None)?;
78//! let result = api.get_ticker("BTC-USDT").await?;
79//! match result.data {
80//! Some(d) => println!("{:#?}", d),
81//! None => println!("Code: {}, msg: {:#?}", result.code, result.msg),
82//! }
83//! Ok(())
84//! }
85//! ```
86//!
87//! An example with custom error handling is:
88//!
89//! ```ignore
90//! extern crate kucoin_api;
91//!
92//! use kucoin_api::tokio;
93//! use kucoin_api::failure;
94//! use kucoin_api::client::{Kucoin, Credentials, KucoinEnv};
95//! use kucoin_api::error::APIError;
96//!
97//! #[tokio::main]
98//! async fn main() -> Result<(), failure::Error> {
99//! let result = api.get_server_time().await;
100//! match result {
101//! Err(e) => {
102//! match e {
103//! APIError::HTTP(e) => eprintln!("Reqwest Error: {}", e),
104//! _ => eprintln!("Non HTTP Error: {}", e),
105//! }
106//! },
107//! Ok(s) => {
108//! match s.data {
109//! Some(d) => println!("{:#?}", d),
110//! None => println!("Code: {}, msg: {:#?}", s.code, s.msg),
111//! }
112//! }
113//! }
114//! Ok(())
115//! }
116//! ```
117//!
118//!
119//! ### Websocket Usage
120//!
121//! Websockets require several steps to initalize. A single websocket can accept up to 10 subscriptions,
122//! as per Kucoin limitations. Due to this, the instantiation of the socket takes a Vec\<[WSTopic](./kucoin/model/websocket/enum.WSTopic.html)\>.
123//! The reason is because multiple subscriptions can be initialized from one call. Below is a simplified single subscription with a line-by-line
124//! short explanation including some basic options for specified error handling.
125//!
126//! ```ignore
127//! extern crate kucoin_api;
128//!
129//! use kucoin_api::tokio;
130//! use kucoin_api::failure;
131//! use kucoin_api::tokio::stream::StreamExt;
132//!
133//! use kucoin_api::client::{Kucoin, Credentials, KucoinEnv};
134//! use kucoin_api::model::websocket::{Subscribe, KucoinWebsocketMsg, WSType, WSTopic, WSResp};
135//!
136//! #[tokio::main]
137//! async fn main() -> Result<(), failure::Error> {
138//! // If credentials are needed, generate a new Credentials struct w/ the necessary keys
139//! let credentials = Credentials::new(
140//! "xxxxxxxxxxxxxXXXXXXxxx",
141//! "XXxxxxx-xxxxxx-xXxxxx-xxxx",
142//! "xxxxxx"
143//! );
144//!
145//! // Initialize the Kucoin API struct
146//! let api = Kucoin::new(KucoinEnv::Live, Some(credentials))?;
147//!
148//! // Generate the dynamic Public or Private websocket url and endpoint from Kucoin
149//! // which includes a token required for connecting
150//! let url = api.get_socket_endpoint(WSType::Public).await?;
151//!
152//! // Initialize the websocket
153//! let mut ws = api.websocket();
154//!
155//! // Generate a Vec<WSTopic> of desired subs. Note they need to be public or private
156//! // depending on the url
157//! let subs = vec![WSTopic::Ticker(vec!["BTC-USDT".to_string()])];
158//!
159//! // Initalize your subscription and use await to unwrap the future
160//! ws.subscribe(url, subs).await?;
161//!
162//! // Handle incoming responses matching messages. Note, the message matching is
163//! // not required for a single subscription but may be desired
164//! // for more complex event handling for multi-subscribed sockets add the additional
165//! // KucoinWebSocketMsg matches.
166//! while let Some(msg) = ws.try_next().await? {
167//! match msg {
168//! KucoinWebsocketMsg::TickerMsg(msg) => println!("{:#?}", msg),
169//! KucoinWebsocketMsg::PongMsg(msg) => println!("{:#?}", msg), // Optional
170//! KucoinWebsocketMsg::WelcomeMsg(msg) => println!("{:#?}", msg), // Optional
171//! _ => (),
172//! }
173//! }
174//! Ok(())
175//! }
176//! ```
177//! [`KucoinWebsocketMsg`](./kucoin/model/websocket/enum.KucoinWebsocketMsg.html) has all the message response types
178//! available and can be referenced to identify desired endpoints.
179//!
180//! [`WSTopic`](./kucoin/model/websocket/enum.WSTopic.html) has all the available websocket topics/endpoints that are
181//! available for subscription.
182//!
183//! Note that Level3 data has been separated by message type despite it requiring only a single subscription.
184//! All other subscriptions coincide 1:1 with their response type and KucoinWebsocketMsg,
185//! excluding their Ping, Pong and Welcome messages. Ping, Pong and Welcome can be tracked through their own match arm.
186//! The reasoning for this exception is that for the majority of use cases, each Level3 message has to be handled
187//! in its own way to properly construct an orderbook. By separating the messages by type from the incoming
188//! stream at the library level, it helps to reduce duplication for the end user.
189//!
190//! ## Error Handling
191//!
192//! kucoin_api uses the [`failure crate`](https://crates.io/crates/failure) to propagate errors. Kucoin REST errors are
193//! passed as part of the response structs, however by default, reqwest errors panic. For websocket endpoints, similarly,
194//! by default most protocol and connection errors will panic. Use of `?` will result in panics as well. End users can however
195//! use the custom [`APIError`](./kucoin/error/enum.APIError.html) enum to match error responses which provide non panic
196//! alternatives allowing for specified error handling. Users can also implement their own more comprehensive solutions.
197//!
198//! ## Contribution
199//!
200//! Contributions are more than welcome for fixing bugs, writing further documentation, writing further tests,
201//! adding features or helping to improve performance. I'll do my best to review and implement pull requests.
202//!
203//! ## Donations
204//!
205//! Donations are always appreciated and help support development of more open source trading tools.
206//!
207//! BTC: 3KvTuAnv7o2VAf4LGgg1MiDURd2DgjFGaa
208//!
209//! ETH: 0x7713a223e0e86355ac02b1e0de77695e822071cf
210//!
211//! NEO: AWngpjmoXPHiJH6rtf81brPiyPomYAqe8j
212//!
213//! Contact me for any other specific cryptocurrencies you'd prefer to use.
214//!
215//! ## License
216//!
217//! This project is open source and uses the MIT license. Feel free to utilize it in whatever way you see fit.
218
219pub extern crate futures;
220pub extern crate pin_project;
221pub extern crate reqwest;
222pub extern crate tokio;
223pub extern crate tokio_native_tls;
224pub extern crate tokio_tungstenite;
225pub extern crate tungstenite;
226pub extern crate url;
227
228pub extern crate serde;
229pub extern crate serde_json;
230
231#[macro_use]
232pub extern crate serde_derive;
233#[macro_use]
234pub extern crate failure;
235
236/// Main Kucoin API Client w/ All Endpoints
237pub mod client;
238pub mod error;
239pub mod margin;
240pub mod market;
241/// API Response Strucs
242pub mod model;
243pub mod trade;
244pub mod user;
245/// Utility Functions
246pub mod utils;
247pub mod websocket;