Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add trade stream to Gate.IO #739

Merged
merged 1 commit into from
Feb 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 53 additions & 5 deletions src/ExchangeSharp/API/Exchanges/GateIo/ExchangeGateIoAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ protected override async Task<IEnumerable<string>> OnGetMarketSymbolsAsync()
{
foreach (JToken token in obj)
{
symbols.Add(token["id"].ToStringInvariant());
if (token["trade_status"].ToStringLowerInvariant() == "tradable")
symbols.Add(token["id"].ToStringInvariant());
}
}
return symbols;
Expand Down Expand Up @@ -117,7 +118,7 @@ protected internal override async Task<IEnumerable<ExchangeMarket>> OnGetMarketS
var market = new ExchangeMarket
{
MarketSymbol = marketSymbolToken["id"].ToStringUpperInvariant(),
IsActive = marketSymbolToken["trade_status"].ToStringUpperInvariant() == "tradable",
IsActive = marketSymbolToken["trade_status"].ToStringLowerInvariant() == "tradable",
QuoteCurrency = marketSymbolToken["quote"].ToStringUpperInvariant(),
BaseCurrency = marketSymbolToken["base"].ToStringUpperInvariant(),
};
Expand Down Expand Up @@ -433,15 +434,15 @@ protected override async Task OnCancelOrderAsync(string orderId, string symbol =
await MakeJsonRequestAsync<JToken>($"/spot/orders/{orderId}?currency_pair={symbol}", BaseUrl, payload, "DELETE");
}

string unixTimeInSeconds => ((long)CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.Now)).ToStringInvariant();
protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary<string, object>? payload)
{
if (CanMakeAuthenticatedRequest(payload))
{
payload.Remove("nonce");
var timestamp = ((long)CryptoUtility.UnixTimestampFromDateTimeSeconds(DateTime.Now)).ToStringInvariant();

request.AddHeader("KEY", PublicApiKey!.ToUnsecureString());
request.AddHeader("Timestamp", timestamp);
request.AddHeader("Timestamp", unixTimeInSeconds);

var privateApiKey = PrivateApiKey!.ToUnsecureString();

Expand All @@ -453,7 +454,7 @@ protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dicti
var hashBytes = sha512Hash.ComputeHash(sourceBytes);
var bodyHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
var queryString = string.IsNullOrEmpty(request.RequestUri.Query) ? "" : request.RequestUri.Query.Substring(1);
var signatureString = $"{request.Method}\n{request.RequestUri.AbsolutePath}\n{queryString}\n{bodyHash}\n{timestamp}";
var signatureString = $"{request.Method}\n{request.RequestUri.AbsolutePath}\n{queryString}\n{bodyHash}\n{unixTimeInSeconds}";

using (HMACSHA512 hmac = new HMACSHA512(Encoding.UTF8.GetBytes(privateApiKey)))
{
Expand All @@ -469,5 +470,52 @@ protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dicti
await base.ProcessRequestAsync(request, payload);
}
}

protected override async Task<IWebSocket> OnGetTradesWebSocketAsync(Func<KeyValuePair<string, ExchangeTrade>, Task> callback, params string[] marketSymbols)
{
if (marketSymbols == null || marketSymbols.Length == 0)
{
marketSymbols = (await GetMarketSymbolsAsync(true)).ToArray();
}
return await ConnectPublicWebSocketAsync(null, messageCallback: async (_socket, msg) =>
{
JToken parsedMsg = JToken.Parse(msg.ToStringFromUTF8());

if (parsedMsg["channel"].ToStringInvariant().Equals("spot.trades"))
{
if (parsedMsg["error"] != null)
throw new APIException($"Exchange returned error: {parsedMsg["error"].ToStringInvariant()}");
else if (parsedMsg["result"]["status"].ToStringInvariant().Equals("success"))
{
// successfully subscribed to trade stream
}
else
{
var exchangeTrade = parsedMsg["result"].ParseTrade("amount", "price", "side", "create_time_ms", TimestampType.UnixMillisecondsDouble, "id");

await callback(new KeyValuePair<string, ExchangeTrade>(parsedMsg["result"]["currency_pair"].ToStringInvariant(), exchangeTrade));
}
}
}, connectCallback: async (_socket) =>
{/*{ "time": int(time.time()),
"channel": "spot.trades",
"event": "subscribe", # "unsubscribe" for unsubscription
"payload": ["BTC_USDT"]
}*/

// this doesn't work for some reason
//await _socket.SendMessageAsync(new
//{
// time = unixTimeInSeconds,
// channel = "spot.trades",
// @event = "subscribe",
// payload = marketSymbols,
//});
var quotedSymbols = marketSymbols.Select(s => $"\"{s}\"");
var combinedString = string.Join(",", quotedSymbols);
await _socket.SendMessageAsync(
$"{{ \"time\": {unixTimeInSeconds},\"channel\": \"spot.trades\",\"event\": \"subscribe\",\"payload\": [{combinedString}] }}");
});
}
}
}