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

fix: Extends the order data from the kraken order placed #813

Merged
merged 1 commit into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
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
53 changes: 38 additions & 15 deletions src/ExchangeSharp/API/Exchanges/Kraken/ExchangeKrakenAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -236,16 +236,19 @@ private async Task<ExchangeOrderResult> ParseHistoryOrder(string orderId, JToken
//}
// }

ExchangeOrderResult orderResult = new ExchangeOrderResult { OrderId = orderId };
orderResult.Result = ExchangeAPIOrderResult.Filled;
orderResult.Message = "";
orderResult.MarketSymbol = order["pair"].ToStringInvariant();
orderResult.IsBuy = (order["type"].ToStringInvariant() == "buy");
orderResult.Amount = order["vol"].ConvertInvariant<decimal>();
orderResult.Fees = order["fee"].ConvertInvariant<decimal>();
orderResult.Price = order["price"].ConvertInvariant<decimal>();
orderResult.AveragePrice = order["price"].ConvertInvariant<decimal>();
orderResult.TradeId = order["postxid"].ToStringInvariant(); //verify which is orderid & tradeid
ExchangeOrderResult orderResult = new ExchangeOrderResult
{
OrderId = orderId,
Result = ExchangeAPIOrderResult.Filled,
Message = "",
MarketSymbol = order["pair"].ToStringInvariant(),
IsBuy = order["type"].ToStringInvariant() == "buy",
Amount = order["vol"].ConvertInvariant<decimal>(),
Fees = order["fee"].ConvertInvariant<decimal>(),
Price = order["price"].ConvertInvariant<decimal>(),
AveragePrice = order["price"].ConvertInvariant<decimal>(),
TradeId = order["postxid"].ToStringInvariant() //verify which is orderid & tradeid
};
orderResult.OrderId = order["ordertxid"].ToStringInvariant(); //verify which is orderid & tradeid
orderResult.AmountFilled = order["vol"].ConvertInvariant<decimal>();
// orderResult.OrderDate - not provided here. ideally would be null but ExchangeOrderResult.OrderDate is not nullable
Expand All @@ -258,6 +261,21 @@ private async Task<ExchangeOrderResult> ParseHistoryOrder(string orderId, JToken
return orderResult;
}

internal ExchangeOrderResult ExtendResultsWithOrderDescr(ExchangeOrderResult result, string orderStr)
{
//"buy 0.00000001 XBTUSD @ limit 1000000"
//"buy 58.00000000 ADAUSDT @ market"
string[] orderStrParts = orderStr.Split(' ');
result.IsBuy = string.Equals(orderStrParts[0], "buy", StringComparison.InvariantCultureIgnoreCase);
result.Amount = orderStrParts[1].ConvertInvariant<decimal>();
result.MarketSymbol = orderStrParts[2];
var isMarket = string.Equals(orderStrParts[4], "market", StringComparison.InvariantCultureIgnoreCase);
if (!isMarket) {
result.Price = orderStrParts[5].ConvertInvariant<decimal>();
}
return result;
}

private async Task<IEnumerable<ExchangeOrderResult>> QueryOrdersAsync(string symbol, string path)
{
await PopulateLookupTables();
Expand Down Expand Up @@ -496,12 +514,12 @@ protected override async Task<IEnumerable<KeyValuePair<string, ExchangeTicker>>>
{
tickers.Add(new KeyValuePair<string, ExchangeTicker>(marketSymbol, await ConvertToExchangeTickerAsync(marketSymbol, ticker)));
}
catch(Exception e)
catch (Exception e)
{
Logger.Error(e);
}
}
if(unfoundSymbols.Count > 0)
if (unfoundSymbols.Count > 0)
{
Logger.Warn($"Of {marketSymbols.Count()} symbols, tickers could not be found for {unfoundSymbols.Count}: [{String.Join(", ", unfoundSymbols)}]");
}
Expand Down Expand Up @@ -700,12 +718,17 @@ protected override async Task<ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrd
JToken token = await MakeJsonRequestAsync<JToken>("/0/private/AddOrder", null, payload);
ExchangeOrderResult result = new ExchangeOrderResult
{
OrderDate = CryptoUtility.UtcNow
OrderDate = CryptoUtility.UtcNow,
Result = ExchangeAPIOrderResult.Open
};
if (token["txid"] is JArray array)
{
result.OrderId = array[0].ToStringInvariant();
}
if (token["descr"] is JObject descrArray)
{
result = ExtendResultsWithOrderDescr(result, descrArray["order"].ToStringInvariant());
}
return result;
}

Expand Down Expand Up @@ -869,7 +892,7 @@ [3]pair string Asset pair
string marketSymbol = token[3].ToStringInvariant();
//Kraken updates the candle open time to the current time, but we want it as open-time i.e. close-time - interval
token[1][0] = token[1][1].ConvertInvariant<long>() - interval * 60;
var candle = this.ParseCandle(token[1], marketSymbol, interval * 60, 2, 3, 4, 5, 0, TimestampType.UnixSeconds, 7, null, 6,8);
var candle = this.ParseCandle(token[1], marketSymbol, interval * 60, 2, 3, 4, 5, 0, TimestampType.UnixSeconds, 7, null, 6, 8);
await callbackAsync(candle);
}
}, connectCallback: async (_socket) =>
Expand All @@ -895,7 +918,7 @@ protected override async Task<IWebSocket> OnGetPositionsWebSocketAsync(Action<Ex
{
if (token.Count == 3 && token[1].ToString() == "openOrders")
{
foreach(JToken element in token[0])
foreach (JToken element in token[0])
{
if (element is JObject position)
{
Expand Down
44 changes: 44 additions & 0 deletions tests/ExchangeSharpTests/ExchangeKrakenAPITests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System.Threading.Tasks;
using ExchangeSharp;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

namespace ExchangeSharpTests
{
[TestClass]
public sealed class ExchangeKrakenTests
{
private ExchangeKrakenAPI api;

[TestInitialize()]
public async Task Startup()
{
api = (await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Kraken)).As<ExchangeKrakenAPI>();
return;
}

[TestMethod]
public void ExtendResultsWithOrderDescrTest()
{
string toParse = "buy 58.00000000 ADAUSDT @ market";
var extendedOrder = api.ExtendResultsWithOrderDescr(new ExchangeOrderResult(), toParse);

extendedOrder.IsBuy.Should().BeTrue();
extendedOrder.Amount.Should().Be(58);
extendedOrder.MarketSymbol.Should().Be("ADAUSDT");
}

[TestMethod]
public void ExtendResultsWithOrderDescrAndPriceTest()
{
string toParse = "buy 0.001254 BTCUSDT @ limit 1000";
var extendedOrder = api.ExtendResultsWithOrderDescr(new ExchangeOrderResult(), toParse);

extendedOrder.IsBuy.Should().BeTrue();
extendedOrder.Amount.Should().Be(0.001254);
extendedOrder.MarketSymbol.Should().Be("BTCUSDT");
extendedOrder.Price.Should().Be(1000);
}
}
}