-
-
Notifications
You must be signed in to change notification settings - Fork 374
Feature/coinmate #718
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
Merged
Merged
Feature/coinmate #718
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
19c2726
Coinmate public methods
bezysoftware 9994f99
Coinmate auth + OnGetAmountsAsync
bezysoftware 766beea
Coinmate buy, sell, order
bezysoftware 981d78b
Coinmate OnGetOpenOrderDetailsAsync
bezysoftware 0d6c44b
Coinmate OnGetDepositAddressAsync, OnWithdrawAsync
bezysoftware cf227b4
Coinmate readme + ExchangeName
bezysoftware File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
303 changes: 303 additions & 0 deletions
303
src/ExchangeSharp/API/Exchanges/Coinmate/ExchangeCoinmateAPI.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,303 @@ | ||
using ExchangeSharp.API.Exchanges.Coinmate.Models; | ||
using Newtonsoft.Json.Linq; | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
|
||
namespace ExchangeSharp | ||
{ | ||
public class ExchangeCoinmateAPI : ExchangeAPI | ||
{ | ||
public override string BaseUrl { get; set; } = "https://coinmate.io/api"; | ||
|
||
public ExchangeCoinmateAPI() | ||
{ | ||
RequestContentType = "application/x-www-form-urlencoded"; | ||
MarketSymbolSeparator = "_"; | ||
NonceStyle = NonceStyle.UnixMilliseconds; | ||
} | ||
|
||
public override string Name => "Coinmate"; | ||
|
||
/// <summary> | ||
/// Coinmate private API requires a client id. Internally this is secured in the PassPhrase property. | ||
/// </summary> | ||
public string ClientId | ||
{ | ||
get { return Passphrase.ToUnsecureString(); } | ||
set { Passphrase = value.ToSecureString(); } | ||
} | ||
|
||
protected override async Task<ExchangeTicker> OnGetTickerAsync(string marketSymbol) | ||
{ | ||
var response = await MakeCoinmateRequest<JToken>($"/ticker?currencyPair={marketSymbol}"); | ||
return await this.ParseTickerAsync(response, marketSymbol, "ask", "bid", "last", "amount", null, "timestamp", TimestampType.UnixSeconds); | ||
} | ||
|
||
protected override async Task<IEnumerable<string>> OnGetMarketSymbolsAsync() | ||
{ | ||
var response = await MakeCoinmateRequest<CoinmateSymbol[]>("/products"); | ||
return response.Select(x => $"{x.FromSymbol}{MarketSymbolSeparator}{x.ToSymbol}").ToArray(); | ||
} | ||
|
||
protected internal override async Task<IEnumerable<ExchangeMarket>> OnGetMarketSymbolsMetadataAsync() | ||
{ | ||
var response = await MakeCoinmateRequest<CoinmateTradingPair[]>("/tradingPairs"); | ||
return response.Select(x => new ExchangeMarket | ||
{ | ||
IsActive = true, | ||
BaseCurrency = x.FirstCurrency, | ||
QuoteCurrency = x.SecondCurrency, | ||
MarketSymbol = x.Name, | ||
MinTradeSize = x.MinAmount, | ||
PriceStepSize = 1 / (decimal)(Math.Pow(10, x.PriceDecimals)), | ||
QuantityStepSize = 1 / (decimal)(Math.Pow(10, x.LotDecimals)) | ||
}).ToArray(); | ||
} | ||
|
||
protected override async Task<ExchangeOrderBook> OnGetOrderBookAsync(string marketSymbol, int maxCount = 100) | ||
{ | ||
var book = await MakeCoinmateRequest<CoinmateOrderBook>("/orderBook?&groupByPriceLimit=False¤cyPair=" + marketSymbol); | ||
var result = new ExchangeOrderBook | ||
{ | ||
MarketSymbol = marketSymbol, | ||
}; | ||
|
||
book.Asks | ||
.GroupBy(x => x.Price) | ||
.ToList() | ||
.ForEach(x => result.Asks.Add(x.Key, new ExchangeOrderPrice { Amount = x.Sum(x => x.Amount), Price = x.Key })); | ||
|
||
book.Bids | ||
.GroupBy(x => x.Price) | ||
.ToList() | ||
.ForEach(x => result.Bids.Add(x.Key, new ExchangeOrderPrice { Amount = x.Sum(x => x.Amount), Price = x.Key })); | ||
|
||
return result; | ||
} | ||
|
||
protected override async Task<IEnumerable<ExchangeTrade>> OnGetRecentTradesAsync(string marketSymbol, int? limit = null) | ||
{ | ||
var txs = await MakeCoinmateRequest<CoinmateTransaction[]>("/transactions?minutesIntoHistory=1440¤cyPair=" + marketSymbol); | ||
return txs.Select(x => new ExchangeTrade | ||
{ | ||
Amount = x.Amount, | ||
Id = x.TransactionId, | ||
IsBuy = x.TradeType == "BUY", | ||
Price = x.Price, | ||
Timestamp = CryptoUtility.ParseTimestamp(x.Timestamp, TimestampType.UnixMilliseconds) | ||
}) | ||
.Take(limit ?? int.MaxValue) | ||
.ToArray(); | ||
} | ||
|
||
protected override async Task<Dictionary<string, decimal>> OnGetAmountsAsync() | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
var balances = await MakeCoinmateRequest<Dictionary<string, CoinmateBalance>>("/balances", payload, "POST"); | ||
|
||
return balances.ToDictionary(x => x.Key, x => x.Value.Balance); | ||
} | ||
|
||
protected override async Task<Dictionary<string, decimal>> OnGetAmountsAvailableToTradeAsync() | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
var balances = await MakeCoinmateRequest<Dictionary<string, CoinmateBalance>>("/balances", payload, "POST"); | ||
|
||
return balances.ToDictionary(x => x.Key, x => x.Value.Available); | ||
} | ||
|
||
protected override async Task<ExchangeOrderResult> OnGetOrderDetailsAsync(string orderId, string marketSymbol = null, bool isClientOrderId = false) | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
|
||
CoinmateOrder o; | ||
|
||
if (isClientOrderId) | ||
{ | ||
payload["clientOrderId"] = orderId; | ||
var orders = await MakeCoinmateRequest<CoinmateOrder[]>("/order", payload, "POST"); | ||
o = orders.OrderByDescending(x => x.Timestamp).FirstOrDefault(); | ||
} | ||
else | ||
{ | ||
payload["orderId"] = orderId; | ||
o = await MakeCoinmateRequest<CoinmateOrder>("/orderById", payload, "POST"); | ||
} | ||
|
||
if (o == null) return null; | ||
|
||
return new ExchangeOrderResult | ||
{ | ||
Amount = o.OriginalAmount, | ||
AmountFilled = o.OriginalAmount - o.RemainingAmount, | ||
AveragePrice = o.AvgPrice, | ||
ClientOrderId = isClientOrderId ? orderId : null, | ||
OrderId = o.Id.ToString(), | ||
Price = o.Price, | ||
IsBuy = o.Type == "BUY", | ||
OrderDate = CryptoUtility.ParseTimestamp(o.Timestamp, TimestampType.UnixMilliseconds), | ||
ResultCode = o.Status, | ||
Result = o.Status switch | ||
{ | ||
"CANCELLED" => ExchangeAPIOrderResult.Canceled, | ||
"FILLED" => ExchangeAPIOrderResult.Filled, | ||
"PARTIALLY_FILLED" => ExchangeAPIOrderResult.FilledPartially, | ||
"OPEN" => ExchangeAPIOrderResult.Open, | ||
_ => ExchangeAPIOrderResult.Unknown | ||
}, | ||
MarketSymbol = marketSymbol | ||
}; | ||
} | ||
|
||
protected override async Task OnCancelOrderAsync(string orderId, string marketSymbol = null) | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
payload["orderId"] = orderId; | ||
|
||
await MakeCoinmateRequest<bool>("/cancelOrder", payload, "POST"); | ||
} | ||
|
||
protected override async Task<ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrderRequest order) | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
|
||
if (order.OrderType != OrderType.Limit && order.OrderType != OrderType.Stop) | ||
{ | ||
throw new NotImplementedException("This type of order is currently not supported."); | ||
} | ||
|
||
payload["amount"] = order.Amount; | ||
payload["price"] = order.Price; | ||
payload["currencyPair"] = order.MarketSymbol; | ||
payload["postOnly"] = order.IsPostOnly.GetValueOrDefault() ? 1 : 0; | ||
|
||
if (order.OrderType == OrderType.Stop) | ||
{ | ||
payload["stopPrice"] = order.StopPrice; | ||
} | ||
|
||
if (order.ClientOrderId != null) | ||
{ | ||
if (!long.TryParse(order.ClientOrderId, out var clientOrderId)) | ||
{ | ||
throw new InvalidOperationException("ClientId must be numerical for Coinmate"); | ||
} | ||
|
||
payload["clientOrderId"] = clientOrderId; | ||
} | ||
|
||
var url = order.IsBuy ? "/buyLimit" : "/sellLimit"; | ||
var id = await MakeCoinmateRequest<long?>(url, payload, "POST"); | ||
|
||
try | ||
{ | ||
return await GetOrderDetailsAsync(id?.ToString(), marketSymbol: order.MarketSymbol); | ||
} | ||
catch | ||
{ | ||
return new ExchangeOrderResult { OrderId = id?.ToString() }; | ||
} | ||
} | ||
|
||
protected override async Task<IEnumerable<ExchangeOrderResult>> OnGetOpenOrderDetailsAsync(string marketSymbol = null) | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
payload["currencyPair"] = marketSymbol; | ||
|
||
var orders = await MakeCoinmateRequest<CoinmateOpenOrder[]>("/openOrders", payload, "POST"); | ||
|
||
return orders.Select(x => new ExchangeOrderResult | ||
{ | ||
Amount = x.Amount, | ||
ClientOrderId = x.ClientOrderId?.ToString(), | ||
IsBuy = x.Type == "BUY", | ||
MarketSymbol = x.CurrencyPair, | ||
OrderDate = CryptoUtility.ParseTimestamp(x.Timestamp, TimestampType.UnixMilliseconds), | ||
OrderId = x.Id.ToString(), | ||
Price = x.Price, | ||
|
||
}).ToArray(); | ||
} | ||
|
||
protected override async Task<ExchangeDepositDetails> OnGetDepositAddressAsync(string currency, bool forceRegenerate = false) | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
var currencyName = GetCurrencyName(currency); | ||
var addresses = await MakeCoinmateRequest<string[]>($"/{currencyName}DepositAddresses", payload, "POST"); | ||
|
||
return new ExchangeDepositDetails | ||
{ | ||
Address = addresses.FirstOrDefault(), | ||
Currency = currency, | ||
}; | ||
} | ||
|
||
protected override async Task<ExchangeWithdrawalResponse> OnWithdrawAsync(ExchangeWithdrawalRequest withdrawalRequest) | ||
{ | ||
var payload = await GetNoncePayloadAsync(); | ||
var currencyName = GetCurrencyName(withdrawalRequest.Currency); | ||
|
||
payload["amount"] = withdrawalRequest.Amount; | ||
payload["address"] = withdrawalRequest.Address; | ||
payload["amountType"] = withdrawalRequest.TakeFeeFromAmount ? "NET" : "GROSS"; | ||
|
||
var id = await MakeCoinmateRequest<long?>($"/{currencyName}Withdrawal", payload, "POST"); | ||
|
||
return new ExchangeWithdrawalResponse | ||
{ | ||
Id = id?.ToString(), | ||
Success = id != null | ||
}; | ||
} | ||
|
||
protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary<string, object> payload) | ||
{ | ||
if (CanMakeAuthenticatedRequest(payload)) | ||
{ | ||
if (string.IsNullOrWhiteSpace(ClientId)) | ||
{ | ||
throw new APIException("Client ID is not set for Coinmate"); | ||
} | ||
|
||
var apiKey = PublicApiKey.ToUnsecureString(); | ||
var messageToSign = payload["nonce"].ToStringInvariant() + ClientId + apiKey; | ||
var signature = CryptoUtility.SHA256Sign(messageToSign, PrivateApiKey.ToUnsecureString()).ToUpperInvariant(); | ||
payload["signature"] = signature; | ||
payload["clientId"] = ClientId; | ||
payload["publicKey"] = apiKey; | ||
await CryptoUtility.WritePayloadFormToRequestAsync(request, payload); | ||
} | ||
} | ||
|
||
private async Task<T> MakeCoinmateRequest<T>(string url, Dictionary<string, object> payload = null, string method = null) | ||
{ | ||
var response = await MakeJsonRequestAsync<CoinmateResponse<T>>(url, null, payload, method); | ||
|
||
if (response.Error) | ||
{ | ||
throw new APIException(response.ErrorMessage); | ||
} | ||
|
||
return response.Data; | ||
} | ||
|
||
private string GetCurrencyName(string currency) | ||
{ | ||
return currency.ToUpper() switch | ||
{ | ||
"BTC" => "bitcoin", | ||
"LTC" => "litecoin", | ||
"BCH" => "bitcoinCash", | ||
"ETH" => "ethereum", | ||
"XRP" => "ripple", | ||
"DASH" => "dash", | ||
"DAI" => "dai", | ||
_ => throw new NotImplementedException("Unsupported currency") | ||
}; | ||
} | ||
|
||
public partial class ExchangeName { public const string Coinmate = "Coinmate"; } | ||
} | ||
} |
10 changes: 10 additions & 0 deletions
10
src/ExchangeSharp/API/Exchanges/Coinmate/Models/CoinmateBalance.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
namespace ExchangeSharp.API.Exchanges.Coinmate.Models | ||
{ | ||
public class CoinmateBalance | ||
{ | ||
public string Currency { get; set; } | ||
public decimal Balance { get; set; } | ||
public decimal Reserved { get; set; } | ||
public decimal Available { get; set; } | ||
} | ||
} |
18 changes: 18 additions & 0 deletions
18
src/ExchangeSharp/API/Exchanges/Coinmate/Models/CoinmateOpenOrder.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
namespace ExchangeSharp.API.Exchanges.Coinmate.Models | ||
{ | ||
public class CoinmateOpenOrder | ||
{ | ||
public int Id { get; set; } | ||
public long Timestamp { get; set; } | ||
public string Type { get; set; } | ||
public string CurrencyPair { get; set; } | ||
public decimal Price { get; set; } | ||
public decimal Amount { get; set; } | ||
public decimal? StopPrice { get; set; } | ||
public string OrderTradeType { get; set; } | ||
public bool Hidden { get; set; } | ||
public bool Trailing { get; set; } | ||
public long? StopLossOrderId { get; set; } | ||
public long? ClientOrderId { get; set; } | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
src/ExchangeSharp/API/Exchanges/Coinmate/Models/CoinmateOrder.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
namespace ExchangeSharp.API.Exchanges.Coinmate.Models | ||
{ | ||
public class CoinmateOrder | ||
{ | ||
public int Id { get; set; } | ||
public long Timestamp { get; set; } | ||
public string Type { get; set; } | ||
public decimal? Price { get; set; } | ||
public decimal? RemainingAmount { get; set; } | ||
public decimal OriginalAmount { get; set; } | ||
public decimal? StopPrice { get; set; } | ||
public string Status { get; set; } | ||
public string OrderTradeType { get; set; } | ||
public decimal? AvgPrice { get; set; } | ||
public bool Trailing { get; set; } | ||
public string StopLossOrderId { get; set; } | ||
public string OriginalOrderId { get; set; } | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
src/ExchangeSharp/API/Exchanges/Coinmate/Models/CoinmateOrderBook.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
namespace ExchangeSharp.API.Exchanges.Coinmate.Models | ||
{ | ||
public class CoinmateOrderBook | ||
{ | ||
public AskBid[] Asks { get; set; } | ||
public AskBid[] Bids { get; set; } | ||
|
||
public class AskBid | ||
{ | ||
public decimal Price { get; set; } | ||
public decimal Amount { get; set; } | ||
} | ||
} | ||
} |
9 changes: 9 additions & 0 deletions
9
src/ExchangeSharp/API/Exchanges/Coinmate/Models/CoinmateResponse.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
namespace ExchangeSharp.API.Exchanges.Coinmate.Models | ||
{ | ||
public class CoinmateResponse<T> | ||
{ | ||
public bool Error { get; set; } | ||
public string ErrorMessage { get; set; } | ||
public T Data { get; set; } | ||
} | ||
} |
9 changes: 9 additions & 0 deletions
9
src/ExchangeSharp/API/Exchanges/Coinmate/Models/CoinmateSymbol.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
namespace ExchangeSharp.API.Exchanges.Coinmate.Models | ||
{ | ||
public class CoinmateSymbol | ||
{ | ||
public string Id { get; set; } | ||
public string FromSymbol { get; set; } | ||
public string ToSymbol { get; set; } | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.