|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Newtonsoft.Json.Linq; |
| 6 | + |
| 7 | +namespace ExchangeSharp |
| 8 | +{ |
| 9 | + public sealed class ExchangeMEXCAPI : ExchangeAPI |
| 10 | + { |
| 11 | + public override string BaseUrl { get; set; } = "https://api.mexc.com/api/v3"; |
| 12 | + public override string BaseUrlWebSocket { get; set; } = "wss://wbs.mexc.com/ws"; |
| 13 | + |
| 14 | + public override string PeriodSecondsToString(int seconds) => |
| 15 | + CryptoUtility.SecondsToPeriodInMinutesUpToHourString(seconds); |
| 16 | + |
| 17 | + private ExchangeMEXCAPI() |
| 18 | + { |
| 19 | + NonceStyle = NonceStyle.UnixMilliseconds; |
| 20 | + MarketSymbolSeparator = string.Empty; |
| 21 | + MarketSymbolIsUppercase = true; |
| 22 | + RateLimit = new RateGate(20, TimeSpan.FromSeconds(2)); |
| 23 | + } |
| 24 | + |
| 25 | + public override Task<string> ExchangeMarketSymbolToGlobalMarketSymbolAsync(string marketSymbol) |
| 26 | + { |
| 27 | + var quoteLength = 3; |
| 28 | + if (marketSymbol.EndsWith("USDT") || |
| 29 | + marketSymbol.EndsWith("USDC") || |
| 30 | + marketSymbol.EndsWith("TUSD")) |
| 31 | + { |
| 32 | + quoteLength = 4; |
| 33 | + } |
| 34 | + |
| 35 | + var baseSymbol = marketSymbol.Substring(marketSymbol.Length - quoteLength); |
| 36 | + |
| 37 | + return ExchangeMarketSymbolToGlobalMarketSymbolWithSeparatorAsync( |
| 38 | + marketSymbol.Replace(baseSymbol, "") |
| 39 | + + GlobalMarketSymbolSeparator |
| 40 | + + baseSymbol); |
| 41 | + } |
| 42 | + |
| 43 | + protected override async Task<IEnumerable<string>> OnGetMarketSymbolsAsync() |
| 44 | + { |
| 45 | + return (await OnGetMarketSymbolsMetadataAsync()) |
| 46 | + .Select(x => x.MarketSymbol); |
| 47 | + } |
| 48 | + |
| 49 | + protected internal override async Task<IEnumerable<ExchangeMarket>> OnGetMarketSymbolsMetadataAsync() |
| 50 | + { |
| 51 | + var symbols = await MakeJsonRequestAsync<JToken>("/exchangeInfo", BaseUrl); |
| 52 | + |
| 53 | + return (symbols["symbols"] ?? throw new ArgumentNullException()) |
| 54 | + .Select(symbol => new ExchangeMarket() |
| 55 | + { |
| 56 | + MarketSymbol = symbol["symbol"].ToStringInvariant(), |
| 57 | + IsActive = symbol["isSpotTradingAllowed"].ConvertInvariant<bool>(), |
| 58 | + MarginEnabled = symbol["isMarginTradingAllowed"].ConvertInvariant<bool>(), |
| 59 | + BaseCurrency = symbol["baseAsset"].ToStringInvariant(), |
| 60 | + QuoteCurrency = symbol["quoteAsset"].ToStringInvariant(), |
| 61 | + QuantityStepSize = symbol["baseSizePrecision"].ConvertInvariant<decimal>(), |
| 62 | + // Not 100% sure about this |
| 63 | + PriceStepSize = |
| 64 | + CryptoUtility.PrecisionToStepSize(symbol["quoteCommissionPrecision"].ConvertInvariant<decimal>()), |
| 65 | + MinTradeSizeInQuoteCurrency = symbol["quoteAmountPrecision"].ConvertInvariant<decimal>(), |
| 66 | + MaxTradeSizeInQuoteCurrency = symbol["maxQuoteAmount"].ConvertInvariant<decimal>() |
| 67 | + }); |
| 68 | + } |
| 69 | + |
| 70 | + protected override async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>> OnGetTickersAsync() |
| 71 | + { |
| 72 | + var tickers = new List<KeyValuePair<string, ExchangeTicker>>(); |
| 73 | + var token = await MakeJsonRequestAsync<JToken>("/ticker/24hr", BaseUrl); |
| 74 | + foreach (var t in token) |
| 75 | + { |
| 76 | + var symbol = (t["symbol"] ?? throw new ArgumentNullException()).ToStringInvariant(); |
| 77 | + tickers.Add(new KeyValuePair<string, ExchangeTicker>(symbol, |
| 78 | + await this.ParseTickerAsync( |
| 79 | + t, |
| 80 | + symbol, |
| 81 | + "askPrice", |
| 82 | + "bidPrice", |
| 83 | + "lastPrice", |
| 84 | + "volume", |
| 85 | + timestampType: TimestampType.UnixMilliseconds, |
| 86 | + timestampKey: "closeTime"))); |
| 87 | + } |
| 88 | + |
| 89 | + return tickers; |
| 90 | + } |
| 91 | + |
| 92 | + protected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol) => |
| 93 | + await this.ParseTickerAsync( |
| 94 | + await MakeJsonRequestAsync<JToken>($"/ticker/24hr?symbol={marketSymbol.ToUpperInvariant()}", BaseUrl), |
| 95 | + marketSymbol, |
| 96 | + "askPrice", |
| 97 | + "bidPrice", |
| 98 | + "lastPrice", |
| 99 | + "volume", |
| 100 | + timestampType: TimestampType.UnixMilliseconds, |
| 101 | + timestampKey: "closeTime"); |
| 102 | + |
| 103 | + protected override async Task<ExchangeOrderBook> OnGetOrderBookAsync(string marketSymbol, int maxCount = 100) |
| 104 | + { |
| 105 | + const int maxDepth = 5000; |
| 106 | + const string sequenceKey = "lastUpdateId"; |
| 107 | + marketSymbol = marketSymbol.ToUpperInvariant(); |
| 108 | + if (string.IsNullOrEmpty(marketSymbol)) |
| 109 | + { |
| 110 | + throw new ArgumentOutOfRangeException(nameof(marketSymbol), "Market symbol cannot be empty."); |
| 111 | + } |
| 112 | + |
| 113 | + if (maxCount > maxDepth) |
| 114 | + { |
| 115 | + throw new ArgumentOutOfRangeException(nameof(maxCount), $"Max order book depth is {maxDepth}"); |
| 116 | + } |
| 117 | + |
| 118 | + var token = await MakeJsonRequestAsync<JToken>($"/depth?symbol={marketSymbol}"); |
| 119 | + var orderBook = token.ParseOrderBookFromJTokenArrays(sequence: sequenceKey); |
| 120 | + orderBook.MarketSymbol = marketSymbol; |
| 121 | + orderBook.ExchangeName = Name; |
| 122 | + orderBook.LastUpdatedUtc = DateTime.UtcNow; |
| 123 | + |
| 124 | + return orderBook; |
| 125 | + } |
| 126 | + |
| 127 | + protected override async Task<IEnumerable<ExchangeTrade>> OnGetRecentTradesAsync(string marketSymbol, |
| 128 | + int? limit = null) |
| 129 | + { |
| 130 | + const int maxLimit = 1000; |
| 131 | + const int defaultLimit = 500; |
| 132 | + marketSymbol = marketSymbol.ToUpperInvariant(); |
| 133 | + if (limit == null || limit <= 0) |
| 134 | + { |
| 135 | + limit = defaultLimit; |
| 136 | + } |
| 137 | + |
| 138 | + if (limit > maxLimit) |
| 139 | + { |
| 140 | + throw new ArgumentOutOfRangeException(nameof(limit), $"Max recent trades limit is {maxLimit}"); |
| 141 | + } |
| 142 | + |
| 143 | + var token = await MakeJsonRequestAsync<JToken>($"/trades?symbol={marketSymbol}&limit={limit.Value}"); |
| 144 | + return token |
| 145 | + .Select(t => t.ParseTrade( |
| 146 | + "qty", |
| 147 | + "price", |
| 148 | + "isBuyerMaker", |
| 149 | + "time", |
| 150 | + TimestampType.UnixMilliseconds, |
| 151 | + "id", |
| 152 | + "true")); |
| 153 | + } |
| 154 | + |
| 155 | + protected override async Task<IEnumerable<MarketCandle>> OnGetCandlesAsync( |
| 156 | + string marketSymbol, |
| 157 | + int periodSeconds, |
| 158 | + DateTime? startDate = null, |
| 159 | + DateTime? endDate = null, |
| 160 | + int? limit = null) |
| 161 | + { |
| 162 | + var period = PeriodSecondsToString(periodSeconds); |
| 163 | + const int maxLimit = 1000; |
| 164 | + const int defaultLimit = 500; |
| 165 | + if (limit == null || limit <= 0) |
| 166 | + { |
| 167 | + limit = defaultLimit; |
| 168 | + } |
| 169 | + |
| 170 | + if (limit > maxLimit) |
| 171 | + { |
| 172 | + throw new ArgumentOutOfRangeException(nameof(limit), $"Max recent candlesticks limit is {maxLimit}"); |
| 173 | + } |
| 174 | + |
| 175 | + |
| 176 | + var url = $"/klines?symbol={marketSymbol}&interval={period}&limit={limit.Value}"; |
| 177 | + if (startDate != null) |
| 178 | + { |
| 179 | + url = |
| 180 | + $"{url}&startTime={new DateTimeOffset(startDate.Value).ToUnixTimeMilliseconds()}"; |
| 181 | + } |
| 182 | + |
| 183 | + if (endDate != null) |
| 184 | + { |
| 185 | + url = $"{url}&endTime={new DateTimeOffset(endDate.Value).ToUnixTimeMilliseconds()}"; |
| 186 | + } |
| 187 | + |
| 188 | + var candleResponse = await MakeJsonRequestAsync<JToken>(url); |
| 189 | + return candleResponse.Select( |
| 190 | + cr => |
| 191 | + this.ParseCandle( |
| 192 | + cr, |
| 193 | + marketSymbol, |
| 194 | + periodSeconds, |
| 195 | + 1, |
| 196 | + 2, |
| 197 | + 3, |
| 198 | + 4, |
| 199 | + 0, |
| 200 | + TimestampType.UnixMilliseconds, |
| 201 | + 5, |
| 202 | + 7 |
| 203 | + )); |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + public partial class ExchangeName |
| 208 | + { |
| 209 | + public const string MEXC = "MEXC"; |
| 210 | + } |
| 211 | +} |
0 commit comments