binance/spot/
error.rs

1use serde_repr::{Deserialize_repr, Serialize_repr};
2
3/// Error codes for Binance.
4#[derive(Serialize_repr, Deserialize_repr, Debug, PartialEq)]
5#[repr(i16)]
6pub enum ErrorCode {
7    // 10xx - General Server or Network issues
8    /// An unknown error occurred while processing the request.
9    Unknown = -1000,
10    /// Internal error; unable to process your request. Please try again.
11    Disconnected = -1001,
12    /// You are not authorized to execute this request.
13    Unauthorized = -1002,
14    /// Too many requests queued.
15    /// Too much request weight used; current limit is %s request weight per %s. Please use WebSocket Streams for live updates to avoid polling the API.
16    /// Way too much request weight used; IP banned until %s. Please use WebSocket Streams for live updates to avoid bans.
17    TooManyRequests = -1003,
18    /// An unexpected response was received from the message bus. Execution status unknown.
19    UnexpectedResp = -1006,
20    /// Timeout waiting for response from backend server. Send status unknown; execution status unknown.
21    Timeout = -1007,
22    /// Server is currently overloaded with other requests. Please try again in a few minutes.
23    ServerBusy = -1008,
24    /// This code is sent when an error has been returned by the matching engine.
25    ErrorMsgReceived = -1010,
26    /// The request is rejected by the API. (i.e. The request didn't reach the Matching Engine.)
27    /// Potential error messages can be found in Filter Failures or Failures during order placement.
28    InvalidMessage = -1013,
29    /// Unsupported order combination.
30    UnknownOrderComposition = -1014,
31    /// Too many new orders.
32    /// Too many new orders; current limit is %s orders per %s.
33    TooManyOrders = -1015,
34    /// This service is no longer available.
35    ServiceShuttingDown = -1016,
36    /// This operation is not supported.
37    UnsupportedOperation = -1020,
38    /// Timestamp for this request is outside of the recvWindow.
39    /// Timestamp for this request was 1000ms ahead of the server's time.
40    InvalidTimestamp = -1021,
41    /// Signature for this request is not valid.
42    InvalidSignature = -1022,
43    /// SenderCompId(49) is currently in use. Concurrent use of the same SenderCompId within one account is not allowed.
44    CompIdInUse = -1033,
45    /// Too many concurrent connections; current limit is '%s'.
46    /// Too many connection attempts for account; current limit is %s per '%s'.
47    /// Too many connection attempts from IP; current limit is %s per '%s'.
48    TooManyConnections = -1034,
49    /// Please send Logout<5> message to close the session.
50    LoggedOut = -1035,
51
52    // 11xx - Request issues
53    /// Illegal characters found in a parameter.
54    /// Illegal characters found in parameter '%s'; legal range is '%s'.
55    IllegalChars = -1100,
56    /// Too many parameters sent for this endpoint.
57    /// Too many parameters; expected '%s' and received '%s'.
58    /// Duplicate values for a parameter detected.
59    TooManyParameters = -1101,
60    /// A mandatory parameter was not sent, was empty/null, or malformed.
61    /// Mandatory parameter '%s' was not sent, was empty/null, or malformed.
62    /// Param '%s' or '%s' must be sent, but both were empty/null!
63    /// Required tag '%s' missing.
64    /// Field value was empty or malformed.
65    /// '%s' contains unexpected value. Cannot be greater than %s.
66    MandatoryParamEmptyOrMalformed = -1102,
67    /// An unknown parameter was sent.
68    /// Undefined Tag.
69    UnknownParam = -1103,
70    /// Not all sent parameters were read.
71    /// Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'.
72    UnreadParameters = -1104,
73    /// A parameter was empty.
74    /// Parameter '%s' was empty.
75    ParamEmpty = -1105,
76    /// A parameter was sent when not required.
77    /// Parameter '%s' sent when not required.
78    /// A tag '%s' was sent when not required.
79    ParamNotRequired = -1106,
80    /// Parameter '%s' overflowed.
81    ParamOverflow = -1108,
82    /// Parameter '%s' has too much precision.
83    BadPrecision = -1111,
84    /// No orders on book for symbol.
85    NoDepth = -1112,
86    /// TimeInForce parameter sent when not required.
87    TifNotRequired = -1114,
88    /// Invalid timeInForce.
89    InvalidTif = -1115,
90    /// Invalid orderType.
91    InvalidOrderType = -1116,
92    /// Invalid side.
93    InvalidSide = -1117,
94    /// New client order ID was empty.
95    EmptyNewClOrdId = -1118,
96    /// Original client order ID was empty.
97    EmptyOrgClOrdId = -1119,
98    /// Invalid interval.
99    BadInterval = -1120,
100    /// Invalid symbol.
101    BadSymbol = -1121,
102    /// Invalid symbolStatus.
103    InvalidSymbolstatus = -1122,
104    /// This listenKey does not exist.
105    InvalidListenKey = -1125,
106    /// Lookup interval is too big.
107    /// More than %s hours between startTime and endTime.
108    MoreThanXxHours = -1127,
109    /// Combination of optional parameters invalid.
110    /// Combination of optional fields invalid. Recommendation: '%s' and '%s' must both be sent.
111    /// Fields [%s] must be sent together or omitted entirely.
112    /// Invalid MDEntryType (269) combination. BID and OFFER must be requested together.
113    OptionalParamsBadCombo = -1128,
114    /// Invalid data sent for a parameter.
115    /// Data sent for parameter '%s' is not valid.
116    InvalidParameter = -1130,
117    /// strategyType was less than 1000000.
118    /// TargetStrategy (847) was less than 1000000.
119    BadStrategyType = -1134,
120    /// Invalid JSON Request
121    /// JSON sent for parameter '%s' is not valid
122    InvalidJson = -1135,
123    /// Invalid ticker type.
124    InvalidTickerType = -1139,
125    /// cancelRestrictions has to be either ONLY_NEW or ONLY_PARTIALLY_FILLED.
126    InvalidCancelRestrictions = -1145,
127    /// Symbol is present multiple times in the list.
128    DuplicateSymbols = -1151,
129    /// Invalid X-MBX-SBE header; expected <SCHEMA_ID>:<VERSION>.
130    InvalidSbeHeader = -1152,
131    /// Unsupported SBE schema ID or version specified in the X-MBX-SBE header.
132    UnsupportedSchemaId = -1153,
133    /// SBE is not enabled.
134    SbeDisabled = -1155,
135    /// Order type not supported in OCO.
136    /// If the order type provided in the aboveType and/or belowType is not supported.
137    OcoOrderTypeRejected = -1158,
138    /// Parameter '%s' is not supported if aboveTimeInForce/belowTimeInForce is not GTC.
139    /// If the order type for the above or below leg is STOP_LOSS_LIMIT, and icebergQty is provided for that leg, the timeInForce has to be GTC else it will throw an error.
140    /// TimeInForce (59) must be GTC (1) when MaxFloor (111) is used.
141    OcoIcebergqtyTimeinforce = -1160,
142    /// Unable to encode the response in SBE schema 'x'. Please use schema 'y' or higher.
143    DeprecatedSchema = -1161,
144    /// A limit order in a buy OCO must be below.
145    BuyOcoLimitMustBeBelow = -1165,
146    /// A limit order in a sell OCO must be above.
147    SellOcoLimitMustBeAbove = -1166,
148    /// At least one OCO order must be contingent.
149    BothOcoOrdersCannotBeLimit = -1168,
150    /// Invalid tag number.
151    InvalidTagNumber = -1169,
152    /// Tag '%s' not defined for this message type.
153    TagNotDefinedInMessage = -1170,
154    /// Tag '%s' appears more than once.
155    TagAppearsMoreThanOnce = -1171,
156    /// Tag '%s' specified out of required order.
157    TagOutOfOrder = -1172,
158    /// Repeating group '%s' fields out of order.
159    GroupFieldsOutOfOrder = -1173,
160    /// Component '%s' is incorrectly populated on '%s' order. Recommendation: '%s'
161    InvalidComponent = -1174,
162    /// Continuation of sequence numbers to new session is currently unsupported. Sequence numbers must be reset for each new session.
163    ResetSeqNumSupport = -1175,
164    /// Logon<A> should only be sent once.
165    AlreadyLoggedIn = -1176,
166    /// CheckSum(10) contains an incorrect value.
167    /// BeginString (8) is not the first tag in a message.
168    /// MsgType (35) is not the third tag in a message.
169    /// BodyLength (9) does not contain the correct byte count.
170    /// Only printable ASCII characters and SOH (Start of Header) are allowed.
171    GarbledMessage = -1177,
172    /// SenderCompId(49) contains an incorrect value. The SenderCompID value should not change throughout the lifetime of a session.
173    BadSenderCompid = -1178,
174    /// MsgSeqNum(34) contains an unexpected value. Expected: '%d'.
175    BadSeqNum = -1179,
176    /// Logon<A> must be the first message in the session.
177    ExpectedLogon = -1180,
178    /// Too many messages; current limit is '%d' messages per '%s'.
179    TooManyMessages = -1181,
180    /// Conflicting fields: [%s]
181    ParamsBadCombo = -1182,
182    /// Requested operation is not allowed in DropCopy sessions.
183    NotAllowedInDropCopySessions = -1183,
184    /// DropCopy sessions are not supported on this server. Please reconnect to a drop copy server.
185    DropCopySessionNotAllowed = -1184,
186    /// Only DropCopy sessions are supported on this server. Either reconnect to order entry server or send DropCopyFlag (9406) field.
187    DropCopySessionRequired = -1185,
188    /// Requested operation is not allowed in order entry sessions.
189    NotAllowedInOrderEntrySessions = -1186,
190    /// Requested operation is not allowed in market data sessions.
191    NotAllowedInMarketDataSessions = -1187,
192    /// Incorrect NumInGroup count for repeating group '%s'.
193    IncorrectNumInGroupCount = -1188,
194    /// Group '%s' contains duplicate entries.
195    DuplicateEntriesInAGroup = -1189,
196    /// MDReqID (262) contains a subscription request id that is already in use on this connection.
197    /// MDReqID (262) contains an unsubscription request id that does not match any active subscription.
198    InvalidRequestId = -1190,
199    /// Too many subscriptions. Connection may create up to '%s' subscriptions at a time.
200    /// Similar subscription is already active on this connection. Symbol='%s', active subscription id: '%s'.
201    TooManySubscriptions = -1191,
202    /// Invalid value for time unit; expected either MICROSECOND or MILLISECOND.
203    InvalidTimeUnit = -1194,
204    /// A stop loss order in a buy OCO must be above.
205    BuyOcoStopLossMustBeAbove = -1196,
206    /// A stop loss order in a sell OCO must be below.
207    SellOcoStopLossMustBeBelow = -1197,
208    /// A take profit order in a buy OCO must be below.
209    BuyOcoTakeProfitMustBeBelow = -1198,
210    /// A take profit order in a sell OCO must be above.
211    SellOcoTakeProfitMustBeAbove = -1199,
212    /// NEW_ORDER_REJECTED
213    /// This code is sent when an error has been returned by the matching engine.
214    NewOrderRejected = -2010,
215    /// CANCEL_REJECTED
216    /// This code is sent when an error has been returned by the matching engine.
217    CancelRejected = -2011,
218    /// Order does not exist.
219    NoSuchOrder = -2013,
220    /// API-key format invalid.
221    BadApiKeyFmt = -2014,
222    /// Invalid API-key, IP, or permissions for action.
223    RejectedMbxKey = -2015,
224    /// No trading window could be found for the symbol. Try ticker/24hrs instead.
225    NoTradingWindow = -2016,
226    /// This code is sent when either the cancellation of the order failed or the new order placement failed but not both.
227    /// Errors regarding placing orders via cancelReplace
228    OrderCancelReplacePartiallyFailed = -2021,
229    /// This code is sent when both the cancellation of the order failed and the new order placement failed.
230    /// Errors regarding placing orders via cancelReplace
231    OrderCancelReplaceFailed = -2022,
232    /// Order was canceled or expired with no executed qty over 90 days ago and has been archived.
233    OrderArchived = -2026,
234    /// This code is sent when an error has been returned by the matching engine.
235    OrderAmendRejected = -2038,
236    /// Client order ID is not correct for this order ID.
237    ClientOrderIdInvalid = -2039,
238}
239
240#[derive(Debug)]
241pub enum Error {
242    Io(std::io::Error),
243    Msg(String),
244    Reqwest(reqwest::Error),
245    SerdeJson(serde_json::Error),
246    SerdeUrlEncoded(serde_urlencoded::ser::Error),
247    SerdePathToError(serde_path_to_error::Error<serde_json::Error>),
248}
249
250impl std::fmt::Display for Error {
251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252        match self {
253            Error::Io(error) => write!(f, "I/O error: {error}"),
254            Error::Msg(msg) => write!(f, "{msg}"),
255            Error::Reqwest(error) => write!(f, "reqwest error: {error}"),
256            Error::SerdeJson(error) => write!(f, "serde_json error: {error}"),
257            Error::SerdeUrlEncoded(error) => write!(f, "serde_urlencoded error: {error}"),
258            Error::SerdePathToError(error) => write!(
259                f,
260                "serde_path_to_error error: path: {}, msg: {}",
261                error.path(),
262                error.inner()
263            ),
264        }
265    }
266}
267
268impl std::error::Error for Error {}
269
270impl From<std::io::Error> for Error {
271    fn from(err: std::io::Error) -> Self {
272        Error::Io(err)
273    }
274}
275
276impl From<String> for Error {
277    fn from(msg: String) -> Self {
278        Error::Msg(msg)
279    }
280}
281
282impl From<&str> for Error {
283    fn from(msg: &str) -> Self {
284        Error::Msg(msg.to_string())
285    }
286}
287
288impl From<reqwest::Error> for Error {
289    fn from(err: reqwest::Error) -> Self {
290        Error::Reqwest(err)
291    }
292}
293
294impl From<serde_json::Error> for Error {
295    fn from(err: serde_json::Error) -> Self {
296        Error::SerdeJson(err)
297    }
298}
299
300impl From<serde_urlencoded::ser::Error> for Error {
301    fn from(err: serde_urlencoded::ser::Error) -> Self {
302        Error::SerdeUrlEncoded(err)
303    }
304}
305
306impl From<serde_path_to_error::Error<serde_json::Error>> for Error {
307    fn from(err: serde_path_to_error::Error<serde_json::Error>) -> Self {
308        Error::SerdePathToError(err)
309    }
310}